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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
fcf863f30fe195fb4594c06a28640a4c0b85e131 | b3632665c205bd5dd4f4b90823a39eb22c3a2e7a | /mebel.h | c4e9e039393df3c753ab9b2468ace4c469c61ea9 | [] | no_license | vadimibs/rabota3 | f361387390b959ceb0fe2578baa10d249c86ab04 | 88226232982d0fcc89e6c0d8edc85acb704bb064 | refs/heads/master | 2022-07-16T16:43:12.081323 | 2020-05-19T14:11:38 | 2020-05-19T14:11:38 | 265,254,200 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 383 | h | #ifndef MEBEL_H_INCLUDED
#define MEBEL_H_INCLUDED
#include "izdelie.h"
class mebel: public izdelie{
protected:
string material;
public:
mebel();
mebel(string name_, int size_, string color_, string material_);
void SetMaterial(string material_);
string GetMaterial() const;
virtual void print()const = 0;
};
#endif // MEBEL_H_INCLUDED
| [
"w1ntoff@mail.ru"
] | w1ntoff@mail.ru |
5ed459d3dbacb0ad2f69e7f496bfc812180cdbf5 | debe35fd227dcb9fc3535c6957ac017b914a7915 | /src/Managers/GlobalManager.h | 7684f3e6af8f9b34a1e075b9e785e03bc4fe49dd | [] | no_license | menegais1/EngineRenderer | d83b79388533c30f2dbd8ea892a1e4bf46253483 | 0aeddc6bbd343658e3c20351d0bcd2141761f53f | refs/heads/master | 2022-12-03T02:58:06.701352 | 2020-08-13T22:59:16 | 2020-08-13T22:59:16 | 284,381,006 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,689 | h | ///Manager responsible for forwarding the GLFW callbacks
///To every CanvasObject instantiated, every object has a uniqueId given
///in the beggining of its lifetime
#ifndef GLOBAL_MANAGER_H
#define GLOBAL_MANAGER_H
#include <vector>
#include <chrono>
#include "../Base/CanvasObject.h"
class GlobalManager {
public:
void keyboard(int key, int scancode, int action, int mods);
void mouseButton(int button, int action, int modifier);
void mouseMovement(double xpos, double ypos);
void render();
int registerObject(CanvasObject *object);
CanvasObject *unregisterObject(CanvasObject *object);
static GlobalManager *getInstance();
CanvasObject *deleteObject(CanvasObject *object);
void changeObjectOrder(CanvasObject *object);
void reshape(int width, int height);
int screenWidth;
int screenHeight;
fvec2 mousePosition;
float deltaTime;
float time = 0;
float fpsUpdateCycle = 0.25;
float lastFpsUpdate = 0;
int fps;
private:
float lastReshapeTime = 0;
std::chrono::time_point<std::chrono::_V2::system_clock, std::chrono::duration<long, std::ratio<1, 1000000000>>> lastTime = std::chrono::high_resolution_clock::now();
std::chrono::time_point<std::chrono::_V2::system_clock, std::chrono::duration<long, std::ratio<1, 1000000000>>> currentTime = std::chrono::high_resolution_clock::now();
int objectIdCounter;
static GlobalManager *instance;
//The order of the objects is descending, so what will be rendered first is last
std::vector<CanvasObject *> objects;
GlobalManager();
void addObjectToList(CanvasObject *object);
CanvasObject *cleanUpObjects();
};
#endif
| [
"menegais1@gmail.com"
] | menegais1@gmail.com |
53b424e3501b355260b3c587cf3dcabc6057ce74 | 63b39b6cb42b762fd9d1114cd6ade08644796e64 | /checkers-server/eventService/RequestService.h | 6d3fa85294b43174fbff0c5d6b9fe4c55e4c2a38 | [] | no_license | Yamadads/checkers | f265e5543bc4908f4e775483171a0ff694d82a51 | 1c837b91dfb73f64084429c05b82a1423928feb3 | refs/heads/master | 2021-01-16T19:14:54.555761 | 2016-02-15T11:46:02 | 2016-02-15T11:46:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 625 | h | /*
* requestService.h
*
* Created on: 09-11-2015
* Author: debian
*/
#ifndef EVENTSERVICE_REQUESTSERVICE_H_
#define EVENTSERVICE_REQUESTSERVICE_H_
#include "../jsonParser/json/json.h"
#include "../game/Server.h"
#include "../game/Client.h"
class RequestService {
protected:
Json::Reader reader;
Json::StyledWriter writer;
public:
RequestService();
virtual ~RequestService();
virtual bool action(Json::Value root, Server *server, Client *client) = 0;
Json::Value shortJson(string key, string value);
bool sendResponse(Json::Value root, Client *client);
};
#endif /* EVENTSERVICE_REQUESTSERVICE_H_ */
| [
"s_pawlak@yahoo.com"
] | s_pawlak@yahoo.com |
960da726aaca071019a120a69226c33828edb107 | 6ea0e138431c129d5c520ea739cabf4a15fb3b10 | /src/Game.cpp | 66903cc27089fef956893a473e37d8fc62b41e54 | [] | no_license | ceh-2000/pong | 10b61dfb36cc8e862cd1aed63e701e7d5eaeef65 | 1d679c8d748b3be362c06dc8b1f87fcfe7ea09e1 | refs/heads/main | 2023-03-07T07:28:36.697065 | 2021-02-17T16:27:21 | 2021-02-17T16:27:21 | 338,654,622 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,642 | cpp | #include <SFML/Graphics.hpp>
#include <iostream>
#include "Game.h"
Game::Game(Paddle& paddle1, Paddle& paddle2, Ball& ball, PaddleView& paddle1View, PaddleView& paddle2View, BallView& ballView):
paddle1(paddle1),
paddle2(paddle2),
ball(ball),
paddle1View(paddle1View),
paddle2View(paddle2View),
ballView(ballView)
{
// Set the initial scores
this->score1 = 0;
this->score2 = 0;
// Set the font of our text
if (!font.loadFromFile("../data/Newsreader_18pt-Regular.ttf"))
{
std::cout << "Could not load font." << std::endl;
}
if (!backgroundTexture.loadFromFile("../data/faces.png"))
{
std::cout << "Could not load image from file." << std::endl;
}
displayScore.setFont(font);
this->gameHappening = false;
this->level = 4;
}
Game::~Game(){}
void Game::resetGame(sf::RenderWindow& app, int winner){
gameHappening = false;
// Set the text on this screen
displayScore.setCharacterSize(40);
displayScore.setPosition(0, 0);
sf::String myText = "Press Space Bar to start\n"
"or exit to quit.\n\n"
"Press up to set player 1 as AI.\n"
"Press down to set player 1 as human.\n"
"Press left to set player 2 as AI.\n"
"Press right to set player 2 as human.\n\n"
"Press a number between 1 and 9\n"
"to set difficulty\n";
if(winner == 2){
myText = "Player 2 Wins!\n"+myText;
}
else if(winner == 1){
myText = "Player 1 Wins!\n"+myText;
}
else{
myText = "Stop coronavirus\nby moving the mask up and down.\n\n"+myText;
}
displayScore.setString(myText);
app.clear(sf::Color::Blue);
displayScore.setFillColor(sf::Color::White);
app.draw(displayScore);
app.display();
// Keyboard inputs for user to select players, difficulty, and game start
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up)){
paddle1View.setAI(true);
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Down)){
paddle1View.setAI(false);
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left)){
paddle2View.setAI(true);
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right)){
paddle2View.setAI(false);
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Num1)){
level = 1;
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Num2)){
level = 2;
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Num3)){
level = 3;
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Num4)){
level = 4;
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Num5)){
level = 5;
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Num6)){
level = 6;
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Num7)){
level = 7;
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Num8)){
level = 8;
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Num9)){
level = 9;
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Space)){
this->score1 = 0;
this->score2 = 0;
gameHappening = true;
resetRound(app, app.getSize().x, app.getSize().y);
}
}
void Game::resetRound(sf::RenderWindow& app, float windowWidth, float windowHeight){
// Check for a game win
if(score1 == 11){
// Set to default players
paddle1View.setAI(true);
paddle2View.setAI(false);
this->level = 4;
resetGame(app, 1);
}
else if(score2 == 11){
// Set to default players
paddle1View.setAI(true);
paddle2View.setAI(false);
this->level = 4;
resetGame(app, 2);
}
// Update the text that shows the score
displayScore.setString("Player 1: "+std::to_string(score1)+" | Player 2: "+std::to_string(score2));
displayScore.setPosition(windowWidth / 2.0f - 130.0f, 0);
displayScore.setCharacterSize(30);
// Reposition the paddles and ball
float paddleDistanceFromEdge = 100.0f;
paddle1.setPosition(paddleDistanceFromEdge - paddle1.getWidth(), windowHeight / 2.0f - paddle1.getHeight() / 2.0f);
paddle2.setPosition(windowWidth - paddleDistanceFromEdge, windowHeight / 2.0f - paddle2.getHeight() / 2.0f);
ball.setPosition(windowWidth / 2.0f - ball.getRadius(), windowHeight / 2.0f - ball.getRadius());
// Scale the ball's velocity based on how far the player has come
float ballVelocity = level * 100 + score1 * 20 + score2 * 20;
ball.setRandomVelocity(ballVelocity);
}
void Game::updateGame(sf::RenderWindow& app, float deltaTime){
if(gameHappening == true){
float windowWidth = app.getSize().x;
float windowHeight = app.getSize().y;
// Check to see if we resize and move the paddle and text
if(abs(windowWidth - 100.0f - paddle2.getPosition().x) > 0.01f ){
paddle2.setPosition(windowWidth - 100.0f, paddle2.getPosition().y);
displayScore.setPosition(windowWidth / 2.0f - 130.0f, 0);
}
// Update the paddles
paddle1View.move(paddle1, windowHeight, windowWidth, ball, deltaTime);
paddle2View.move(paddle2, windowHeight, windowWidth, ball, deltaTime);
ballView.move(ball, deltaTime);
//Check if either player has won the round
int win = ball.checkWin(windowWidth);
if(win == 2){
score2 += 1;
resetRound(app, windowWidth, windowHeight);
}
else if(win == 1){
score1 += 1;
resetRound(app, windowWidth, windowHeight);
}
// Update the ball according to collisions
ball.checkCollisionWall(windowHeight, true);
ball.checkCollisionPaddle1(paddle1, true);
ball.checkCollisionPaddle2(paddle2, true);
// Resolve any lingering intersections using the new trajectory (velocity) of the ball
while(ball.checkCollisionWall(windowHeight, false) | ball.checkCollisionPaddle1(paddle1, false) | ball.checkCollisionPaddle2(paddle2, false))
{
ball.move(deltaTime); // another option is to move ball immediately outside and then continue game
}
// Clear screen and fill with white
app.clear(sf::Color::White);
sf::RectangleShape background(sf::Vector2f(windowWidth, windowHeight));
const sf::Texture *pBackgroundTexture = &backgroundTexture;
background.setTexture(pBackgroundTexture);
app.draw(background);
displayScore.setFillColor(sf::Color::Black);
app.draw(displayScore);
paddle1View.draw(paddle1, app);
paddle2View.draw(paddle2, app);
ballView.draw(ball, app);
// Display
app.display();
}
else{
if(score1 == 11){
resetGame(app, 1);
}
else if(score2 == 11){
resetGame(app, 2);
}
else{
resetGame(app, 0);
}
}
} | [
"clare.heinbaugh@gmail.com"
] | clare.heinbaugh@gmail.com |
6705959800b3220449cdea8c9c827ce196b9550f | 9b6eced5d80668bd4328a8f3d1f75c97f04f5e08 | /bluetoothapitest/bluetoothsvs/T_BTSdpAPI/inc/T_DataSdpAttrValueList.h | 70fe0d33cca84cb5f609d71f90222406faf32f06 | [] | no_license | SymbianSource/oss.FCL.sf.os.bt | 3ca94a01740ac84a6a35718ad3063884ea885738 | ba9e7d24a7fa29d6dd93808867c28bffa2206bae | refs/heads/master | 2021-01-18T23:42:06.315016 | 2010-10-14T10:30:12 | 2010-10-14T10:30:12 | 72,765,157 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,474 | h | /*
* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "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:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description:
*
*/
#if (!defined __T_DATA_SDP_ATTR_VALUE_LIST_H__ )
#define __T_DATA_SDP_ATTR_VALUE_LIST_H__
// User Includes
#include "T_DataSdpAttrValue.h"
#include "T_DataSdpElementBuilder.h"
#include "T_DataSdpAgent.h"
/**
* Test Active Notification class
*
*/
class CT_DataSdpAttrValueList : public CT_DataSdpAttrValue
{
public:
/**
* Public destructor
*/
~CT_DataSdpAttrValueList();
/**
* Process a command read from the ini file
*
* @param aCommand The command to process
* @param aSection The section in the ini containing data for the command
* @param aAsyncErrorIndex Command index for async calls to return errors to
*
* @return ETrue if the command is processed
*
* @leave System wide error
*/
virtual TBool DoCommandL(const TTEFFunction& aCommand, const TTEFSectionName& aSection, const TInt aAsyncErrorIndex);
/**
* Return a pointer to the object that the data wraps
*
* @return pointer to the object that the data wraps
*/
virtual TAny* GetObject() { return iAttrValueList; }
/**
* Set the object that the data wraps
*
* @param aObject object that the wrapper is testing
*
*/
virtual void SetObjectL(TAny* aAny);
/**
* The object will no longer be owned by this
*
* @leave KErrNotSupported if the the function is not supported
*/
virtual void DisownObjectL();
inline virtual TCleanupOperation CleanupOperation();
protected:
/**
* Protected constructor. First phase construction
*/
CT_DataSdpAttrValueList();
/**
* Second phase construction
*/
void ConstructL();
virtual CSdpAttrValueList* GetSdpAttrValueList() const;
virtual CSdpAttrValue* GetSdpAttrValue() const;
private:
static void CleanupOperation(TAny* aAny);
/**
* Helper methods
*/
void DestroyData();
inline void DoCmdDestructor();
inline void DoCmdAppendValueL(const TDesC& aSection);
inline void DoCmdBuildEncodedL(const TDesC& aSection);
private:
CSdpAttrValueList* iAttrValueList;
CT_DataSdpElementBuilder* iElementBuilder;
};
#endif /* __T_DATA_SDP_ATTR_VALUE_LIST_H__ */
| [
"kirill.dremov@nokia.com"
] | kirill.dremov@nokia.com |
6d2b16a70c505dede2b82912e05ab5cb683a269d | 7027b334e40207f80eab358fd12006ba2e63a490 | /lab4/lab4/Point.cpp | 9c0690de8f50a47e010bcd6e087dbb882c6bae8d | [] | no_license | Dushess0/lessonsCPP | 5eb48467b5540c992f2b8b86d6569366b9e8914d | 72790d97f1246c85000e550e7ef80ab816d1645d | refs/heads/master | 2020-04-28T09:06:12.365111 | 2019-05-11T15:19:51 | 2019-05-11T15:19:51 | 175,153,988 | 0 | 0 | null | null | null | null | WINDOWS-1250 | C++ | false | false | 1,109 | cpp | //Definicja znajduje się w pliku Point.cpp
#include <cmath>
#include <ostream>
#include <iostream>
#include "Point.h"
using ::std::ostream;
using ::std::endl;
using ::std::pow;
using ::std::sqrt;
using std::cout;
/* Aby wskazać, ze definicja funkcji dotyczy metody danej klasy
stosujemy tzw. operator zasięgu - "::"
*/
//Specjalna inicjalizacja zmiennych. Zmienne są inicjowane
//nim zostanie wywołane ciało konstruktora
Point::Point() :x_(0), y_(0) {
}
Point::Point(double x, double y) {
x_ = x;
y_ = y;
}
Point::~Point() {
cout << endl;
}
double Point::GetX() const
{
return this->x_;
}
double Point::GetY() const
{
return this->y_;
}
void Point::SetX(double x)
{
this->x_ = x;
}
void Point::SetY(double y)
{
this->y_ = y;
}
double Point::Distance(const Point &other) const {
return sqrt(pow(GetX() - other.GetX(), 2) + pow(GetY() - other.GetY(), 2));
}
void Point::ToString(ostream *out) const {
(*out) << "(" << GetX() << ";" << GetY() << ")";
}
void Point::SET(double x, double y)
{
this->SetX(x);
this->SetY(y);
} | [
"noreply@github.com"
] | Dushess0.noreply@github.com |
f3e4040bd2aa091af393812201eddc440aa7eb44 | 5eb2628304a47e1aafd7496b9c1479b1dd6e07ca | /Health.h | f9a8683133628e903ddcfe4e6a94267a974d990a | [] | no_license | johnn134/TheTankHeardAroundTheWorld | 577044a73621a01db7c68d51fddae95433ff8699 | c88c10caa5e1065a65ab00164f9a18d814e3384d | refs/heads/master | 2021-01-10T09:56:39.154855 | 2015-10-14T21:21:52 | 2015-10-14T21:21:52 | 43,763,952 | 1 | 0 | null | 2015-10-06T17:27:40 | 2015-10-06T16:43:26 | C++ | UTF-8 | C++ | false | false | 281 | h | //view object to show the player's health
#ifndef __HEALTH_H__
#define __HEALTH_H__
#include "ViewObject.h"
#include "Event.h"
#define HEALTH_STRING "Health: "
class Health : public df::ViewObject{
private:
public:
Health();
int eventHandler(const df::Event *p_e);
};
#endif | [
"silverx@verizon.net"
] | silverx@verizon.net |
0fd43608809485b1c41b329438d3d9d7189711d9 | 9c47aff8f135146e599fb19c19fea2c4898129ae | /Render/RenderList.h | c6ebdb4276a8cbd29bc3b6f77626cbe19fb640d1 | [] | no_license | ELTraxo/DX9-Render | 4b1b7d531612784d0289e3bfcf1e16995c90270e | 97150d13bb0e20b73996f4933a01cc5b75c8fe92 | refs/heads/master | 2021-06-20T01:26:31.699033 | 2021-01-12T03:28:15 | 2021-01-12T03:28:15 | 157,016,157 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 413 | h | #pragma once
#include "Primitive.h"
#include "Sprite.h"
#include "Text.h"
using Renderables = std::vector<RenderablePtr>;
class CRenderList
{
Renderables renderables;
public:
CRenderList();
~CRenderList();
Renderables& GetList();
void Clear();
void AddRenderable( PrimitivePtr pPrim );
void AddRenderable( TexturePtr pTexture );
void AddRenderable( TextPtr pFont );
};
using RenderList = CRenderList; | [
"traxin@noreply.github.com"
] | traxin@noreply.github.com |
08efbd0db7b9245205c7795b57e3a8d080b5ae1d | e95ba818ef79f11c2b96e5c38ce9270d971ade56 | /src/engine/octaedit.cpp | ffa64136706d7009b7ab875f3136ad14dfbb841a | [
"Zlib",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | Manmellon/zeromod-sauerbraten | 92095da2f36daafb4742512a5e108e107ee799e7 | ae025cc5ee998b03869ce06ef991322d3eead46b | refs/heads/master | 2020-04-08T05:50:35.967620 | 2018-11-25T21:27:42 | 2018-11-25T21:27:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 81,080 | cpp | #include "engine.h"
extern int outline;
bool boxoutline = false;
void boxs(int orient, vec o, const vec &s, float size)
{
int d = dimension(orient), dc = dimcoord(orient);
float f = boxoutline ? (dc>0 ? 0.2f : -0.2f) : 0;
o[D[d]] += dc * s[D[d]] + f;
vec r(0, 0, 0), c(0, 0, 0);
r[R[d]] = s[R[d]];
c[C[d]] = s[C[d]];
vec v1 = o, v2 = vec(o).add(r), v3 = vec(o).add(r).add(c), v4 = vec(o).add(c);
r[R[d]] = 0.5f*size;
c[C[d]] = 0.5f*size;
gle::defvertex();
gle::begin(GL_TRIANGLE_STRIP);
gle::attrib(vec(v1).sub(r).sub(c));
gle::attrib(vec(v1).add(r).add(c));
gle::attrib(vec(v2).add(r).sub(c));
gle::attrib(vec(v2).sub(r).add(c));
gle::attrib(vec(v3).add(r).add(c));
gle::attrib(vec(v3).sub(r).sub(c));
gle::attrib(vec(v4).sub(r).add(c));
gle::attrib(vec(v4).add(r).sub(c));
gle::attrib(vec(v1).sub(r).sub(c));
gle::attrib(vec(v1).add(r).add(c));
xtraverts += gle::end();
}
void boxs(int orient, vec o, const vec &s)
{
int d = dimension(orient), dc = dimcoord(orient);
float f = boxoutline ? (dc>0 ? 0.2f : -0.2f) : 0;
o[D[d]] += dc * s[D[d]] + f;
gle::defvertex();
gle::begin(GL_LINE_LOOP);
gle::attrib(o); o[R[d]] += s[R[d]];
gle::attrib(o); o[C[d]] += s[C[d]];
gle::attrib(o); o[R[d]] -= s[R[d]];
gle::attrib(o);
xtraverts += gle::end();
}
void boxs3D(const vec &o, vec s, int g)
{
s.mul(g);
loopi(6)
boxs(i, o, s);
}
void boxsgrid(int orient, vec o, vec s, int g)
{
int d = dimension(orient), dc = dimcoord(orient);
float ox = o[R[d]],
oy = o[C[d]],
xs = s[R[d]],
ys = s[C[d]],
f = boxoutline ? (dc>0 ? 0.2f : -0.2f) : 0;
o[D[d]] += dc * s[D[d]]*g + f;
gle::defvertex();
gle::begin(GL_LINES);
loop(x, xs)
{
o[R[d]] += g;
gle::attrib(o);
o[C[d]] += ys*g;
gle::attrib(o);
o[C[d]] = oy;
}
loop(y, ys)
{
o[C[d]] += g;
o[R[d]] = ox;
gle::attrib(o);
o[R[d]] += xs*g;
gle::attrib(o);
}
xtraverts += gle::end();
}
selinfo sel, lastsel, savedsel;
int orient = 0;
int gridsize = 8;
ivec cor, lastcor;
ivec cur, lastcur;
extern int entediting;
bool editmode = false;
bool havesel = false;
bool hmapsel = false;
int horient = 0;
extern int entmoving;
VARF(dragging, 0, 0, 1,
if(!dragging || cor[0]<0) return;
lastcur = cur;
lastcor = cor;
sel.grid = gridsize;
sel.orient = orient;
);
int moving = 0;
ICOMMAND(moving, "b", (int *n),
{
if(*n >= 0)
{
if(!*n || (moving<=1 && !pointinsel(sel, vec(cur).add(1)))) moving = 0;
else if(!moving) moving = 1;
}
intret(moving);
});
VARF(gridpower, 0, 3, 12,
{
if(dragging) return;
gridsize = 1<<gridpower;
if(gridsize>=worldsize) gridsize = worldsize/2;
cancelsel();
});
VAR(passthroughsel, 0, 0, 1);
VAR(editing, 1, 0, 0);
VAR(selectcorners, 0, 0, 1);
VARF(hmapedit, 0, 0, 1, horient = sel.orient);
void forcenextundo() { lastsel.orient = -1; }
extern void hmapcancel();
void cubecancel()
{
havesel = false;
moving = dragging = hmapedit = passthroughsel = 0;
forcenextundo();
hmapcancel();
}
void cancelsel()
{
cubecancel();
entcancel();
}
void toggleedit(bool force)
{
if(!force)
{
if(!isconnected()) return;
if(player->state!=CS_ALIVE && player->state!=CS_DEAD && player->state!=CS_EDITING) return; // do not allow dead players to edit to avoid state confusion
if(!game::allowedittoggle()) return; // not in most multiplayer modes
}
if(!(editmode = !editmode))
{
player->state = player->editstate;
player->o.z -= player->eyeheight; // entinmap wants feet pos
entinmap(player); // find spawn closest to current floating pos
}
else
{
game::resetgamestate();
player->editstate = player->state;
player->state = CS_EDITING;
}
cancelsel();
stoppaintblendmap();
keyrepeat(editmode);
editing = entediting = editmode;
extern int fullbright;
if(fullbright) { initlights(); lightents(); }
if(!force) game::edittoggled(editmode);
}
bool noedit(bool view, bool msg)
{
if(!editmode) { if(msg) conoutf(CON_ERROR, "operation only allowed in edit mode"); return true; }
if(view || haveselent()) return false;
float r = 1.0f;
vec o(sel.o), s(sel.s);
s.mul(float(sel.grid) / 2.0f);
o.add(s);
r = float(max(s.x, max(s.y, s.z)));
bool viewable = (isvisiblesphere(r, o) != VFC_NOT_VISIBLE);
if(!viewable && msg) conoutf(CON_ERROR, "selection not in view");
return !viewable;
}
void reorient()
{
sel.cx = 0;
sel.cy = 0;
sel.cxs = sel.s[R[dimension(orient)]]*2;
sel.cys = sel.s[C[dimension(orient)]]*2;
sel.orient = orient;
}
void selextend()
{
if(noedit(true)) return;
loopi(3)
{
if(cur[i]<sel.o[i])
{
sel.s[i] += (sel.o[i]-cur[i])/sel.grid;
sel.o[i] = cur[i];
}
else if(cur[i]>=sel.o[i]+sel.s[i]*sel.grid)
{
sel.s[i] = (cur[i]-sel.o[i])/sel.grid+1;
}
}
}
ICOMMAND(edittoggle, "", (), toggleedit(false));
COMMAND(entcancel, "");
COMMAND(cubecancel, "");
COMMAND(cancelsel, "");
COMMAND(reorient, "");
COMMAND(selextend, "");
ICOMMAND(selmoved, "", (), { if(noedit(true)) return; intret(sel.o != savedsel.o ? 1 : 0); });
ICOMMAND(selsave, "", (), { if(noedit(true)) return; savedsel = sel; });
ICOMMAND(selrestore, "", (), { if(noedit(true)) return; sel = savedsel; });
ICOMMAND(selswap, "", (), { if(noedit(true)) return; swap(sel, savedsel); });
///////// selection support /////////////
cube &blockcube(int x, int y, int z, const block3 &b, int rgrid) // looks up a world cube, based on coordinates mapped by the block
{
int dim = dimension(b.orient), dc = dimcoord(b.orient);
ivec s(dim, x*b.grid, y*b.grid, dc*(b.s[dim]-1)*b.grid);
s.add(b.o);
if(dc) s[dim] -= z*b.grid; else s[dim] += z*b.grid;
return lookupcube(s, rgrid);
}
#define loopxy(b) loop(y,(b).s[C[dimension((b).orient)]]) loop(x,(b).s[R[dimension((b).orient)]])
#define loopxyz(b, r, f) { loop(z,(b).s[D[dimension((b).orient)]]) loopxy((b)) { cube &c = blockcube(x,y,z,b,r); f; } }
#define loopselxyz(f) { if(local) makeundo(); loopxyz(sel, sel.grid, f); changed(sel); }
#define selcube(x, y, z) blockcube(x, y, z, sel, sel.grid)
////////////// cursor ///////////////
int selchildcount = 0, selchildmat = -1;
ICOMMAND(havesel, "", (), intret(havesel ? selchildcount : 0));
void countselchild(cube *c, const ivec &cor, int size)
{
ivec ss = ivec(sel.s).mul(sel.grid);
loopoctaboxsize(cor, size, sel.o, ss)
{
ivec o(i, cor, size);
if(c[i].children) countselchild(c[i].children, o, size/2);
else
{
selchildcount++;
if(c[i].material != MAT_AIR && selchildmat != MAT_AIR)
{
if(selchildmat < 0) selchildmat = c[i].material;
else if(selchildmat != c[i].material) selchildmat = MAT_AIR;
}
}
}
}
void normalizelookupcube(const ivec &o)
{
if(lusize>gridsize)
{
lu.x += (o.x-lu.x)/gridsize*gridsize;
lu.y += (o.y-lu.y)/gridsize*gridsize;
lu.z += (o.z-lu.z)/gridsize*gridsize;
}
else if(gridsize>lusize)
{
lu.x &= ~(gridsize-1);
lu.y &= ~(gridsize-1);
lu.z &= ~(gridsize-1);
}
lusize = gridsize;
}
void updateselection()
{
sel.o.x = min(lastcur.x, cur.x);
sel.o.y = min(lastcur.y, cur.y);
sel.o.z = min(lastcur.z, cur.z);
sel.s.x = abs(lastcur.x-cur.x)/sel.grid+1;
sel.s.y = abs(lastcur.y-cur.y)/sel.grid+1;
sel.s.z = abs(lastcur.z-cur.z)/sel.grid+1;
}
bool editmoveplane(const vec &o, const vec &ray, int d, float off, vec &handle, vec &dest, bool first)
{
plane pl(d, off);
float dist = 0.0f;
if(!pl.rayintersect(player->o, ray, dist))
return false;
dest = vec(ray).mul(dist).add(player->o);
if(first) handle = vec(dest).sub(o);
dest.sub(handle);
return true;
}
inline bool isheightmap(int orient, int d, bool empty, cube *c);
extern void entdrag(const vec &ray);
extern bool hoveringonent(int ent, int orient);
extern void renderentselection(const vec &o, const vec &ray, bool entmoving);
extern float rayent(const vec &o, const vec &ray, float radius, int mode, int size, int &orient, int &ent);
VAR(gridlookup, 0, 0, 1);
VAR(passthroughcube, 0, 1, 1);
void rendereditcursor()
{
int d = dimension(sel.orient),
od = dimension(orient),
odc = dimcoord(orient);
bool hidecursor = g3d_windowhit(true, false) || blendpaintmode, hovering = false;
hmapsel = false;
if(moving)
{
static vec dest, handle;
if(editmoveplane(vec(sel.o), camdir, od, sel.o[D[od]]+odc*sel.grid*sel.s[D[od]], handle, dest, moving==1))
{
if(moving==1)
{
dest.add(handle);
handle = vec(ivec(handle).mask(~(sel.grid-1)));
dest.sub(handle);
moving = 2;
}
ivec o = ivec(dest).mask(~(sel.grid-1));
sel.o[R[od]] = o[R[od]];
sel.o[C[od]] = o[C[od]];
}
}
else
if(entmoving)
{
entdrag(camdir);
}
else
{
ivec w;
float sdist = 0, wdist = 0, t;
int entorient = 0, ent = -1;
wdist = rayent(player->o, camdir, 1e16f,
(editmode && showmat ? RAY_EDITMAT : 0) // select cubes first
| (!dragging && entediting ? RAY_ENTS : 0)
| RAY_SKIPFIRST
| (passthroughcube==1 ? RAY_PASS : 0), gridsize, entorient, ent);
if((havesel || dragging) && !passthroughsel && !hmapedit) // now try selecting the selection
if(rayboxintersect(vec(sel.o), vec(sel.s).mul(sel.grid), player->o, camdir, sdist, orient))
{ // and choose the nearest of the two
if(sdist < wdist)
{
wdist = sdist;
ent = -1;
}
}
if((hovering = hoveringonent(hidecursor ? -1 : ent, entorient)))
{
if(!havesel)
{
selchildcount = 0;
selchildmat = -1;
sel.s = ivec(0, 0, 0);
}
}
else
{
vec w = vec(camdir).mul(wdist+0.05f).add(player->o);
if(!insideworld(w))
{
loopi(3) wdist = min(wdist, ((camdir[i] > 0 ? worldsize : 0) - player->o[i]) / camdir[i]);
w = vec(camdir).mul(wdist-0.05f).add(player->o);
if(!insideworld(w))
{
wdist = 0;
loopi(3) w[i] = clamp(player->o[i], 0.0f, float(worldsize));
}
}
cube *c = &lookupcube(ivec(w));
if(gridlookup && !dragging && !moving && !havesel && hmapedit!=1) gridsize = lusize;
int mag = lusize / gridsize;
normalizelookupcube(ivec(w));
if(sdist == 0 || sdist > wdist) rayboxintersect(vec(lu), vec(gridsize), player->o, camdir, t=0, orient); // just getting orient
cur = lu;
cor = ivec(vec(w).mul(2).div(gridsize));
od = dimension(orient);
d = dimension(sel.orient);
if(hmapedit==1 && dimcoord(horient) == (camdir[dimension(horient)]<0))
{
hmapsel = isheightmap(horient, dimension(horient), false, c);
if(hmapsel)
od = dimension(orient = horient);
}
if(dragging)
{
updateselection();
sel.cx = min(cor[R[d]], lastcor[R[d]]);
sel.cy = min(cor[C[d]], lastcor[C[d]]);
sel.cxs = max(cor[R[d]], lastcor[R[d]]);
sel.cys = max(cor[C[d]], lastcor[C[d]]);
if(!selectcorners)
{
sel.cx &= ~1;
sel.cy &= ~1;
sel.cxs &= ~1;
sel.cys &= ~1;
sel.cxs -= sel.cx-2;
sel.cys -= sel.cy-2;
}
else
{
sel.cxs -= sel.cx-1;
sel.cys -= sel.cy-1;
}
sel.cx &= 1;
sel.cy &= 1;
havesel = true;
}
else if(!havesel)
{
sel.o = lu;
sel.s.x = sel.s.y = sel.s.z = 1;
sel.cx = sel.cy = 0;
sel.cxs = sel.cys = 2;
sel.grid = gridsize;
sel.orient = orient;
d = od;
}
sel.corner = (cor[R[d]]-(lu[R[d]]*2)/gridsize)+(cor[C[d]]-(lu[C[d]]*2)/gridsize)*2;
selchildcount = 0;
selchildmat = -1;
countselchild(worldroot, ivec(0, 0, 0), worldsize/2);
if(mag>=1 && selchildcount==1)
{
selchildmat = c->material;
if(mag>1) selchildcount = -mag;
}
}
}
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE);
// cursors
notextureshader->set();
renderentselection(player->o, camdir, entmoving!=0);
boxoutline = outline!=0;
enablepolygonoffset(GL_POLYGON_OFFSET_LINE);
if(!moving && !hovering && !hidecursor)
{
if(hmapedit==1)
gle::colorub(0, hmapsel ? 255 : 40, 0);
else
gle::colorub(120,120,120);
boxs(orient, vec(lu), vec(lusize));
}
// selections
if(havesel || moving)
{
d = dimension(sel.orient);
gle::colorub(50,50,50); // grid
boxsgrid(sel.orient, vec(sel.o), vec(sel.s), sel.grid);
gle::colorub(200,0,0); // 0 reference
boxs3D(vec(sel.o).sub(0.5f*min(gridsize*0.25f, 2.0f)), vec(min(gridsize*0.25f, 2.0f)), 1);
gle::colorub(200,200,200);// 2D selection box
vec co(sel.o.v), cs(sel.s.v);
co[R[d]] += 0.5f*(sel.cx*gridsize);
co[C[d]] += 0.5f*(sel.cy*gridsize);
cs[R[d]] = 0.5f*(sel.cxs*gridsize);
cs[C[d]] = 0.5f*(sel.cys*gridsize);
cs[D[d]] *= gridsize;
boxs(sel.orient, co, cs);
if(hmapedit==1) // 3D selection box
gle::colorub(0,120,0);
else
gle::colorub(0,0,120);
boxs3D(vec(sel.o), vec(sel.s), sel.grid);
}
disablepolygonoffset(GL_POLYGON_OFFSET_LINE);
boxoutline = false;
glDisable(GL_BLEND);
}
void tryedit()
{
extern int hidehud;
if(!editmode || hidehud || mainmenu) return;
if(blendpaintmode) trypaintblendmap();
}
//////////// ready changes to vertex arrays ////////////
static bool haschanged = false;
void readychanges(const ivec &bbmin, const ivec &bbmax, cube *c, const ivec &cor, int size)
{
loopoctabox(cor, size, bbmin, bbmax)
{
ivec o(i, cor, size);
if(c[i].ext)
{
if(c[i].ext->va) // removes va s so that octarender will recreate
{
int hasmerges = c[i].ext->va->hasmerges;
destroyva(c[i].ext->va);
c[i].ext->va = NULL;
if(hasmerges) invalidatemerges(c[i], o, size, true);
}
freeoctaentities(c[i]);
c[i].ext->tjoints = -1;
}
if(c[i].children)
{
if(size<=1)
{
solidfaces(c[i]);
discardchildren(c[i], true);
brightencube(c[i]);
}
else readychanges(bbmin, bbmax, c[i].children, o, size/2);
}
else brightencube(c[i]);
}
}
void commitchanges(bool force)
{
if(!force && !haschanged) return;
haschanged = false;
int oldlen = valist.length();
resetclipplanes();
entitiesinoctanodes();
inbetweenframes = false;
octarender();
inbetweenframes = true;
setupmaterials(oldlen);
invalidatepostfx();
updatevabbs();
resetblobs();
}
void changed(const block3 &sel, bool commit = true)
{
if(sel.s.iszero()) return;
readychanges(ivec(sel.o).sub(1), ivec(sel.s).mul(sel.grid).add(sel.o).add(1), worldroot, ivec(0, 0, 0), worldsize/2);
haschanged = true;
if(commit) commitchanges();
}
//////////// copy and undo /////////////
static inline void copycube(const cube &src, cube &dst)
{
dst = src;
dst.visible = 0;
dst.merged = 0;
dst.ext = NULL; // src cube is responsible for va destruction
if(src.children)
{
dst.children = newcubes(F_EMPTY);
loopi(8) copycube(src.children[i], dst.children[i]);
}
}
static inline void pastecube(const cube &src, cube &dst)
{
discardchildren(dst);
copycube(src, dst);
}
void blockcopy(const block3 &s, int rgrid, block3 *b)
{
*b = s;
cube *q = b->c();
loopxyz(s, rgrid, copycube(c, *q++));
}
block3 *blockcopy(const block3 &s, int rgrid)
{
int bsize = sizeof(block3)+sizeof(cube)*s.size();
if(bsize <= 0 || bsize > (100<<20)) return NULL;
block3 *b = (block3 *)new (false) uchar[bsize];
if(b) blockcopy(s, rgrid, b);
return b;
}
void freeblock(block3 *b, bool alloced = true)
{
cube *q = b->c();
loopi(b->size()) discardchildren(*q++);
if(alloced) delete[] b;
}
void selgridmap(selinfo &sel, uchar *g) // generates a map of the cube sizes at each grid point
{
loopxyz(sel, -sel.grid, (*g++ = bitscan(lusize), (void)c));
}
void freeundo(undoblock *u)
{
if(!u->numents) freeblock(u->block(), false);
delete[] (uchar *)u;
}
void pasteundoblock(block3 *b, uchar *g)
{
cube *s = b->c();
loopxyz(*b, 1<<min(int(*g++), worldscale-1), pastecube(*s++, c));
}
void pasteundo(undoblock *u)
{
if(u->numents) pasteundoents(u);
else pasteundoblock(u->block(), u->gridmap());
}
static inline int undosize(undoblock *u)
{
if(u->numents) return u->numents*sizeof(undoent);
else
{
block3 *b = u->block();
cube *q = b->c();
int size = b->size(), total = size;
loopj(size) total += familysize(*q++)*sizeof(cube);
return total;
}
}
struct undolist
{
undoblock *first, *last;
undolist() : first(NULL), last(NULL) {}
bool empty() { return !first; }
void add(undoblock *u)
{
u->next = NULL;
u->prev = last;
if(!first) first = last = u;
else
{
last->next = u;
last = u;
}
}
undoblock *popfirst()
{
undoblock *u = first;
first = first->next;
if(first) first->prev = NULL;
else last = NULL;
return u;
}
undoblock *poplast()
{
undoblock *u = last;
last = last->prev;
if(last) last->next = NULL;
else first = NULL;
return u;
}
};
undolist undos, redos;
VARP(undomegs, 0, 5, 100); // bounded by n megs
int totalundos = 0;
void pruneundos(int maxremain) // bound memory
{
while(totalundos > maxremain && !undos.empty())
{
undoblock *u = undos.popfirst();
totalundos -= u->size;
freeundo(u);
}
//conoutf(CON_DEBUG, "undo: %d of %d(%%%d)", totalundos, undomegs<<20, totalundos*100/(undomegs<<20));
while(!redos.empty())
{
undoblock *u = redos.popfirst();
totalundos -= u->size;
freeundo(u);
}
}
void clearundos() { pruneundos(0); }
COMMAND(clearundos, "");
undoblock *newundocube(selinfo &s)
{
int ssize = s.size(),
selgridsize = ssize,
blocksize = sizeof(block3)+ssize*sizeof(cube);
if(blocksize <= 0 || blocksize > (undomegs<<20)) return NULL;
undoblock *u = (undoblock *)new (false) uchar[sizeof(undoblock) + blocksize + selgridsize];
if(!u) return NULL;
u->numents = 0;
block3 *b = u->block();
blockcopy(s, -s.grid, b);
uchar *g = u->gridmap();
selgridmap(s, g);
return u;
}
void addundo(undoblock *u)
{
u->size = undosize(u);
u->timestamp = totalmillis;
undos.add(u);
totalundos += u->size;
pruneundos(undomegs<<20);
}
VARP(nompedit, 0, 1, 1);
void makeundo(selinfo &s)
{
#ifdef OLDPROTO
if(nompedit && multiplayer(false)) return;
#endif
undoblock *u = newundocube(s);
if(u) addundo(u);
}
void makeundo() // stores state of selected cubes before editing
{
if(lastsel==sel || sel.s.iszero()) return;
lastsel=sel;
makeundo(sel);
}
static inline int countblock(cube *c, int n = 8)
{
int r = n;
loopi(n) if(c[i].children) r += countblock(c[i].children);
return r;
}
static int countblock(block3 *b) { return countblock(b->c(), b->size()); }
void swapundo(undolist &a, undolist &b, int op)
{
#ifndef OLDPROTO
if(noedit()) return;
#else
if(noedit() || (nompedit && multiplayer())) return;
#endif
if(a.empty()) { conoutf(CON_WARN, "nothing more to %s", op == EDIT_REDO ? "redo" : "undo"); return; }
int ts = a.last->timestamp;
if(multiplayer(false))
{
int n = 0, ops = 0;
for(undoblock *u = a.last; u && ts==u->timestamp; u = u->prev)
{
++ops;
n += u->numents ? u->numents : countblock(u->block());
if(ops > 10 || n > 500)
{
if(nompedit) { multiplayer(); return; }
op = -1;
break;
}
}
}
selinfo l = sel;
while(!a.empty() && ts==a.last->timestamp)
{
if(op >= 0) game::edittrigger(sel, op);
undoblock *u = a.poplast(), *r;
if(u->numents) r = copyundoents(u);
else
{
block3 *ub = u->block();
l.o = ub->o;
l.s = ub->s;
l.grid = ub->grid;
l.orient = ub->orient;
r = newundocube(l);
}
if(r)
{
r->size = u->size;
r->timestamp = totalmillis;
b.add(r);
}
pasteundo(u);
if(!u->numents) changed(*u->block(), false);
freeundo(u);
}
commitchanges();
if(!hmapsel)
{
sel = l;
reorient();
}
forcenextundo();
}
void editundo() { swapundo(undos, redos, EDIT_UNDO); }
void editredo() { swapundo(redos, undos, EDIT_REDO); }
// guard against subdivision
#define protectsel(f) { undoblock *_u = newundocube(sel); f; if(_u) { pasteundo(_u); freeundo(_u); } }
vector<editinfo *> editinfos;
editinfo *localedit = NULL;
template<class B>
static void packcube(cube &c, B &buf)
{
if(c.children)
{
buf.put(0xFF);
loopi(8) packcube(c.children[i], buf);
}
else
{
cube data = c;
lilswap(data.texture, 6);
buf.put(c.material&0xFF);
buf.put(c.material>>8);
buf.put(data.edges, sizeof(data.edges));
buf.put((uchar *)data.texture, sizeof(data.texture));
}
}
template<class B>
static bool packblock(block3 &b, B &buf)
{
if(b.size() <= 0 || b.size() > (1<<20)) return false;
block3 hdr = b;
lilswap(hdr.o.v, 3);
lilswap(hdr.s.v, 3);
lilswap(&hdr.grid, 1);
lilswap(&hdr.orient, 1);
buf.put((const uchar *)&hdr, sizeof(hdr));
cube *c = b.c();
loopi(b.size()) packcube(c[i], buf);
return true;
}
struct vslothdr
{
ushort index;
ushort slot;
};
static void packvslots(cube &c, vector<uchar> &buf, vector<ushort> &used)
{
if(c.children)
{
loopi(8) packvslots(c.children[i], buf, used);
}
else loopi(6)
{
ushort index = c.texture[i];
if(vslots.inrange(index) && vslots[index]->changed && used.find(index) < 0)
{
used.add(index);
VSlot &vs = *vslots[index];
vslothdr &hdr = *(vslothdr *)buf.pad(sizeof(vslothdr));
hdr.index = index;
hdr.slot = vs.slot->index;
lilswap(&hdr.index, 2);
packvslot(buf, vs);
}
}
}
static void packvslots(block3 &b, vector<uchar> &buf)
{
vector<ushort> used;
cube *c = b.c();
loopi(b.size()) packvslots(c[i], buf, used);
memset(buf.pad(sizeof(vslothdr)), 0, sizeof(vslothdr));
}
template<class B>
static void unpackcube(cube &c, B &buf)
{
int mat = buf.get();
if(mat == 0xFF)
{
c.children = newcubes(F_EMPTY);
loopi(8) unpackcube(c.children[i], buf);
}
else
{
c.material = mat | (buf.get()<<8);
buf.get(c.edges, sizeof(c.edges));
buf.get((uchar *)c.texture, sizeof(c.texture));
lilswap(c.texture, 6);
}
}
template<class B>
static bool unpackblock(block3 *&b, B &buf)
{
if(b) { freeblock(b); b = NULL; }
block3 hdr;
if(buf.get((uchar *)&hdr, sizeof(hdr)) < int(sizeof(hdr))) return false;
lilswap(hdr.o.v, 3);
lilswap(hdr.s.v, 3);
lilswap(&hdr.grid, 1);
lilswap(&hdr.orient, 1);
if(hdr.size() > (1<<20) || hdr.grid <= 0 || hdr.grid > (1<<12)) return false;
b = (block3 *)new (false) uchar[sizeof(block3)+hdr.size()*sizeof(cube)];
if(!b) return false;
*b = hdr;
cube *c = b->c();
memset(c, 0, b->size()*sizeof(cube));
loopi(b->size()) unpackcube(c[i], buf);
return true;
}
struct vslotmap
{
int index;
VSlot *vslot;
vslotmap() {}
vslotmap(int index, VSlot *vslot) : index(index), vslot(vslot) {}
};
static vector<vslotmap> unpackingvslots;
static void unpackvslots(cube &c, ucharbuf &buf)
{
if(c.children)
{
loopi(8) unpackvslots(c.children[i], buf);
}
else loopi(6)
{
ushort tex = c.texture[i];
loopvj(unpackingvslots) if(unpackingvslots[j].index == tex) { c.texture[i] = unpackingvslots[j].vslot->index; break; }
}
}
static void unpackvslots(block3 &b, ucharbuf &buf)
{
while(buf.remaining() >= int(sizeof(vslothdr)))
{
vslothdr &hdr = *(vslothdr *)buf.pad(sizeof(vslothdr));
lilswap(&hdr.index, 2);
if(!hdr.index) break;
VSlot &vs = *lookupslot(hdr.slot, false).variants;
VSlot ds;
if(!unpackvslot(buf, ds, false)) break;
if(vs.index < 0 || vs.index == DEFAULT_SKY) continue;
VSlot *edit = editvslot(vs, ds);
unpackingvslots.add(vslotmap(hdr.index, edit ? edit : &vs));
}
cube *c = b.c();
loopi(b.size()) unpackvslots(c[i], buf);
unpackingvslots.setsize(0);
}
static bool compresseditinfo(const uchar *inbuf, int inlen, uchar *&outbuf, int &outlen)
{
uLongf len = compressBound(inlen);
if(len > (1<<20)) return false;
outbuf = new (false) uchar[len];
if(!outbuf || compress2((Bytef *)outbuf, &len, (const Bytef *)inbuf, inlen, Z_BEST_COMPRESSION) != Z_OK || len > (1<<16))
{
delete[] outbuf;
outbuf = NULL;
return false;
}
outlen = len;
return true;
}
static bool uncompresseditinfo(const uchar *inbuf, int inlen, uchar *&outbuf, int &outlen)
{
if(compressBound(outlen) > (1<<20)) return false;
uLongf len = outlen;
outbuf = new (false) uchar[len];
if(!outbuf || uncompress((Bytef *)outbuf, &len, (const Bytef *)inbuf, inlen) != Z_OK)
{
delete[] outbuf;
outbuf = NULL;
return false;
}
outlen = len;
return true;
}
bool packeditinfo(editinfo *e, int &inlen, uchar *&outbuf, int &outlen)
{
vector<uchar> buf;
if(!e || !e->copy || !packblock(*e->copy, buf)) return false;
packvslots(*e->copy, buf);
inlen = buf.length();
return compresseditinfo(buf.getbuf(), buf.length(), outbuf, outlen);
}
bool unpackeditinfo(editinfo *&e, const uchar *inbuf, int inlen, int outlen)
{
if(e && e->copy) { freeblock(e->copy); e->copy = NULL; }
uchar *outbuf = NULL;
if(!uncompresseditinfo(inbuf, inlen, outbuf, outlen)) return false;
ucharbuf buf(outbuf, outlen);
if(!e) e = editinfos.add(new editinfo);
if(!unpackblock(e->copy, buf))
{
delete[] outbuf;
return false;
}
unpackvslots(*e->copy, buf);
delete[] outbuf;
return true;
}
void freeeditinfo(editinfo *&e)
{
if(!e) return;
editinfos.removeobj(e);
if(e->copy) freeblock(e->copy);
delete e;
e = NULL;
}
bool packundo(undoblock *u, int &inlen, uchar *&outbuf, int &outlen)
{
vector<uchar> buf;
buf.reserve(512);
*(ushort *)buf.pad(2) = lilswap(ushort(u->numents));
if(u->numents)
{
undoent *ue = u->ents();
loopi(u->numents)
{
*(ushort *)buf.pad(2) = lilswap(ushort(ue[i].i));
entity &e = *(entity *)buf.pad(sizeof(entity));
e = ue[i].e;
lilswap(&e.o.x, 3);
lilswap(&e.attr1, 5);
}
}
else
{
block3 &b = *u->block();
if(!packblock(b, buf)) return false;
buf.put(u->gridmap(), b.size());
packvslots(b, buf);
}
inlen = buf.length();
return compresseditinfo(buf.getbuf(), buf.length(), outbuf, outlen);
}
bool unpackundo(const uchar *inbuf, int inlen, int outlen)
{
uchar *outbuf = NULL;
if(!uncompresseditinfo(inbuf, inlen, outbuf, outlen)) return false;
ucharbuf buf(outbuf, outlen);
if(buf.remaining() < 2)
{
delete[] outbuf;
return false;
}
int numents = lilswap(*(const ushort *)buf.pad(2));
if(numents)
{
if(buf.remaining() < numents*int(2 + sizeof(entity)))
{
delete[] outbuf;
return false;
}
loopi(numents)
{
int idx = lilswap(*(const ushort *)buf.pad(2));
entity &e = *(entity *)buf.pad(sizeof(entity));
lilswap(&e.o.x, 3);
lilswap(&e.attr1, 5);
pasteundoent(idx, e);
}
}
else
{
block3 *b = NULL;
if(!unpackblock(b, buf) || b->grid >= worldsize || buf.remaining() < b->size())
{
freeblock(b);
delete[] outbuf;
return false;
}
uchar *g = buf.pad(b->size());
unpackvslots(*b, buf);
pasteundoblock(b, g);
changed(*b, false);
freeblock(b);
}
delete[] outbuf;
commitchanges();
return true;
}
bool packundo(int op, int &inlen, uchar *&outbuf, int &outlen)
{
switch(op)
{
case EDIT_UNDO: return !undos.empty() && packundo(undos.last, inlen, outbuf, outlen);
case EDIT_REDO: return !redos.empty() && packundo(redos.last, inlen, outbuf, outlen);
default: return false;
}
}
struct prefabheader
{
char magic[4];
int version;
};
struct prefab : editinfo
{
char *name;
GLuint ebo, vbo;
int numtris, numverts;
prefab() : name(NULL), ebo(0), vbo(0), numtris(0), numverts(0) {}
~prefab() { DELETEA(name); if(copy) freeblock(copy); }
void cleanup()
{
if(ebo) { glDeleteBuffers_(1, &ebo); ebo = 0; }
if(vbo) { glDeleteBuffers_(1, &vbo); vbo = 0; }
numtris = numverts = 0;
}
};
static hashnameset<prefab> prefabs;
void cleanupprefabs()
{
enumerate(prefabs, prefab, p, p.cleanup());
}
void delprefab(char *name)
{
prefab *p = prefabs.access(name);
if(p)
{
p->cleanup();
prefabs.remove(name);
conoutf("deleted prefab %s", name);
}
}
COMMAND(delprefab, "s");
void saveprefab(char *name)
{
if(!name[0] || noedit(true) || (nompedit && multiplayer())) return;
prefab *b = prefabs.access(name);
if(!b)
{
b = &prefabs[name];
b->name = newstring(name);
}
if(b->copy) freeblock(b->copy);
protectsel(b->copy = blockcopy(block3(sel), sel.grid));
changed(sel);
defformatstring(filename, strpbrk(name, "/\\") ? "packages/%s.obr" : "packages/prefab/%s.obr", name);
path(filename);
stream *f = opengzfile(filename, "wb");
if(!f) { conoutf(CON_ERROR, "could not write prefab to %s", filename); return; }
prefabheader hdr;
memcpy(hdr.magic, "OEBR", 4);
hdr.version = 0;
lilswap(&hdr.version, 1);
f->write(&hdr, sizeof(hdr));
streambuf<uchar> s(f);
if(!packblock(*b->copy, s)) { delete f; conoutf(CON_ERROR, "could not pack prefab %s", filename); return; }
delete f;
conoutf("wrote prefab file %s", filename);
}
COMMAND(saveprefab, "s");
void pasteblock(block3 &b, selinfo &sel, bool local)
{
sel.s = b.s;
int o = sel.orient;
sel.orient = b.orient;
cube *s = b.c();
loopselxyz(if(!isempty(*s) || s->children || s->material != MAT_AIR) pastecube(*s, c); s++); // 'transparent'. old opaque by 'delcube; paste'
sel.orient = o;
}
prefab *loadprefab(const char *name, bool msg = true)
{
prefab *b = prefabs.access(name);
if(b) return b;
defformatstring(filename, strpbrk(name, "/\\") ? "packages/%s.obr" : "packages/prefab/%s.obr", name);
path(filename);
stream *f = opengzfile(filename, "rb");
if(!f) { if(msg) conoutf(CON_ERROR, "could not read prefab %s", filename); return NULL; }
prefabheader hdr;
if(f->read(&hdr, sizeof(hdr)) != sizeof(prefabheader) || memcmp(hdr.magic, "OEBR", 4)) { delete f; if(msg) conoutf(CON_ERROR, "prefab %s has malformatted header", filename); return NULL; }
lilswap(&hdr.version, 1);
if(hdr.version != 0) { delete f; if(msg) conoutf(CON_ERROR, "prefab %s uses unsupported version", filename); return NULL; }
streambuf<uchar> s(f);
block3 *copy = NULL;
if(!unpackblock(copy, s)) { delete f; if(msg) conoutf(CON_ERROR, "could not unpack prefab %s", filename); return NULL; }
delete f;
b = &prefabs[name];
b->name = newstring(name);
b->copy = copy;
return b;
}
void pasteprefab(char *name)
{
if(!name[0] || noedit() || (nompedit && multiplayer())) return;
prefab *b = loadprefab(name, true);
if(b) pasteblock(*b->copy, sel, true);
}
COMMAND(pasteprefab, "s");
struct prefabmesh
{
struct vertex { vec pos; bvec4 norm; };
static const int SIZE = 1<<9;
int table[SIZE];
vector<vertex> verts;
vector<int> chain;
vector<ushort> tris;
prefabmesh() { memset(table, -1, sizeof(table)); }
int addvert(const vertex &v)
{
uint h = hthash(v.pos)&(SIZE-1);
for(int i = table[h]; i>=0; i = chain[i])
{
const vertex &c = verts[i];
if(c.pos==v.pos && c.norm==v.norm) return i;
}
if(verts.length() >= USHRT_MAX) return -1;
verts.add(v);
chain.add(table[h]);
return table[h] = verts.length()-1;
}
int addvert(const vec &pos, const bvec &norm)
{
vertex vtx;
vtx.pos = pos;
vtx.norm = norm;
return addvert(vtx);
}
void setup(prefab &p)
{
if(tris.empty()) return;
p.cleanup();
loopv(verts) verts[i].norm.flip();
if(!p.vbo) glGenBuffers_(1, &p.vbo);
gle::bindvbo(p.vbo);
glBufferData_(GL_ARRAY_BUFFER, verts.length()*sizeof(vertex), verts.getbuf(), GL_STATIC_DRAW);
gle::clearvbo();
p.numverts = verts.length();
if(!p.ebo) glGenBuffers_(1, &p.ebo);
gle::bindebo(p.ebo);
glBufferData_(GL_ELEMENT_ARRAY_BUFFER, tris.length()*sizeof(ushort), tris.getbuf(), GL_STATIC_DRAW);
gle::clearebo();
p.numtris = tris.length()/3;
}
};
static void genprefabmesh(prefabmesh &r, cube &c, const ivec &co, int size)
{
if(c.children)
{
neighbourstack[++neighbourdepth] = c.children;
loopi(8)
{
ivec o(i, co, size/2);
genprefabmesh(r, c.children[i], o, size/2);
}
--neighbourdepth;
}
else if(!isempty(c))
{
int vis;
loopi(6) if((vis = visibletris(c, i, co, size)))
{
ivec v[4];
genfaceverts(c, i, v);
int convex = 0;
if(!flataxisface(c, i)) convex = faceconvexity(v);
int order = vis&4 || convex < 0 ? 1 : 0, numverts = 0;
vec vo(co), pos[4], norm[4];
pos[numverts++] = vec(v[order]).mul(size/8.0f).add(vo);
if(vis&1) pos[numverts++] = vec(v[order+1]).mul(size/8.0f).add(vo);
pos[numverts++] = vec(v[order+2]).mul(size/8.0f).add(vo);
if(vis&2) pos[numverts++] = vec(v[(order+3)&3]).mul(size/8.0f).add(vo);
guessnormals(pos, numverts, norm);
int index[4];
loopj(numverts) index[j] = r.addvert(pos[j], bvec(norm[j]));
loopj(numverts-2) if(index[0]!=index[j+1] && index[j+1]!=index[j+2] && index[j+2]!=index[0])
{
r.tris.add(index[0]);
r.tris.add(index[j+1]);
r.tris.add(index[j+2]);
}
}
}
}
void genprefabmesh(prefab &p)
{
block3 b = *p.copy;
b.o = ivec(0, 0, 0);
cube *oldworldroot = worldroot;
int oldworldscale = worldscale, oldworldsize = worldsize;
worldroot = newcubes();
worldscale = 1;
worldsize = 2;
while(worldsize < max(max(b.s.x, b.s.y), b.s.z)*b.grid)
{
worldscale++;
worldsize *= 2;
}
cube *s = p.copy->c();
loopxyz(b, b.grid, if(!isempty(*s) || s->children) pastecube(*s, c); s++);
prefabmesh r;
neighbourstack[++neighbourdepth] = worldroot;
loopi(8) genprefabmesh(r, worldroot[i], ivec(i, ivec(0, 0, 0), worldsize/2), worldsize/2);
--neighbourdepth;
r.setup(p);
freeocta(worldroot);
worldroot = oldworldroot;
worldscale = oldworldscale;
worldsize = oldworldsize;
useshaderbyname("prefab");
}
extern int outlinecolour;
static void renderprefab(prefab &p, const vec &o, float yaw, float pitch, float roll, float size, const vec &color)
{
if(!p.numtris)
{
genprefabmesh(p);
if(!p.numtris) return;
}
block3 &b = *p.copy;
matrix4 m;
m.identity();
m.settranslation(o);
if(yaw) m.rotate_around_z(yaw*RAD);
if(pitch) m.rotate_around_x(pitch*RAD);
if(roll) m.rotate_around_y(-roll*RAD);
matrix3 w(m);
if(size > 0 && size != 1) m.scale(size);
m.translate(vec(b.s).mul(-b.grid*0.5f));
gle::bindvbo(p.vbo);
gle::bindebo(p.ebo);
gle::enablevertex();
gle::enablenormal();
prefabmesh::vertex *v = (prefabmesh::vertex *)0;
gle::vertexpointer(sizeof(prefabmesh::vertex), v->pos.v);
gle::normalpointer(sizeof(prefabmesh::vertex), v->norm.v, GL_BYTE);
matrix4 pm;
pm.mul(camprojmatrix, m);
GLOBALPARAM(prefabmatrix, pm);
GLOBALPARAM(prefabworld, w);
SETSHADER(prefab);
gle::color(color);
glDrawRangeElements_(GL_TRIANGLES, 0, p.numverts-1, p.numtris*3, GL_UNSIGNED_SHORT, (ushort *)0);
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
enablepolygonoffset(GL_POLYGON_OFFSET_LINE);
pm.mul(camprojmatrix, m);
GLOBALPARAM(prefabmatrix, pm);
SETSHADER(prefab);
gle::color(vec::hexcolor(outlinecolour));
glDrawRangeElements_(GL_TRIANGLES, 0, p.numverts-1, p.numtris*3, GL_UNSIGNED_SHORT, (ushort *)0);
disablepolygonoffset(GL_POLYGON_OFFSET_LINE);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
gle::disablevertex();
gle::disablenormal();
gle::clearebo();
gle::clearvbo();
}
void renderprefab(const char *name, const vec &o, float yaw, float pitch, float roll, float size, const vec &color)
{
prefab *p = loadprefab(name, false);
if(p) renderprefab(*p, o, yaw, pitch, roll, size, color);
}
void previewprefab(const char *name, const vec &color)
{
prefab *p = loadprefab(name, false);
if(p)
{
block3 &b = *p->copy;
float yaw;
vec o = calcmodelpreviewpos(vec(b.s).mul(b.grid*0.5f), yaw);
renderprefab(*p, o, yaw, 0, 0, 1, color);
}
}
void mpcopy(editinfo *&e, selinfo &sel, bool local)
{
if(local) game::edittrigger(sel, EDIT_COPY);
if(e==NULL) e = editinfos.add(new editinfo);
if(e->copy) freeblock(e->copy);
e->copy = NULL;
protectsel(e->copy = blockcopy(block3(sel), sel.grid));
changed(sel);
}
void mppaste(editinfo *&e, selinfo &sel, bool local)
{
if(e==NULL) return;
if(local) game::edittrigger(sel, EDIT_PASTE);
if(e->copy) pasteblock(*e->copy, sel, local);
}
void copy()
{
if(noedit(true)) return;
mpcopy(localedit, sel, true);
}
void pastehilite()
{
if(!localedit) return;
sel.s = localedit->copy->s;
reorient();
havesel = true;
}
void paste()
{
if(noedit()) return;
mppaste(localedit, sel, true);
}
COMMAND(copy, "");
COMMAND(pastehilite, "");
COMMAND(paste, "");
COMMANDN(undo, editundo, "");
COMMANDN(redo, editredo, "");
static vector<int *> editingvslots;
struct vslotref
{
vslotref(int &index) { editingvslots.add(&index); }
~vslotref() { editingvslots.pop(); }
};
#define editingvslot(...) vslotref vslotrefs[] = { __VA_ARGS__ }; (void)vslotrefs;
void compacteditvslots()
{
loopv(editingvslots) if(*editingvslots[i]) compactvslot(*editingvslots[i]);
loopv(unpackingvslots) compactvslot(*unpackingvslots[i].vslot);
loopv(editinfos)
{
editinfo *e = editinfos[i];
compactvslots(e->copy->c(), e->copy->size());
}
for(undoblock *u = undos.first; u; u = u->next)
if(!u->numents)
compactvslots(u->block()->c(), u->block()->size());
for(undoblock *u = redos.first; u; u = u->next)
if(!u->numents)
compactvslots(u->block()->c(), u->block()->size());
}
///////////// height maps ////////////////
#define MAXBRUSH 64
#define MAXBRUSHC 63
#define MAXBRUSH2 32
int brush[MAXBRUSH][MAXBRUSH];
VAR(brushx, 0, MAXBRUSH2, MAXBRUSH);
VAR(brushy, 0, MAXBRUSH2, MAXBRUSH);
bool paintbrush = 0;
int brushmaxx = 0, brushminx = MAXBRUSH;
int brushmaxy = 0, brushminy = MAXBRUSH;
void clearbrush()
{
memset(brush, 0, sizeof brush);
brushmaxx = brushmaxy = 0;
brushminx = brushminy = MAXBRUSH;
paintbrush = false;
}
void brushvert(int *x, int *y, int *v)
{
*x += MAXBRUSH2 - brushx + 1; // +1 for automatic padding
*y += MAXBRUSH2 - brushy + 1;
if(*x<0 || *y<0 || *x>=MAXBRUSH || *y>=MAXBRUSH) return;
brush[*x][*y] = clamp(*v, 0, 8);
paintbrush = paintbrush || (brush[*x][*y] > 0);
brushmaxx = min(MAXBRUSH-1, max(brushmaxx, *x+1));
brushmaxy = min(MAXBRUSH-1, max(brushmaxy, *y+1));
brushminx = max(0, min(brushminx, *x-1));
brushminy = max(0, min(brushminy, *y-1));
}
vector<int> htextures;
COMMAND(clearbrush, "");
COMMAND(brushvert, "iii");
void hmapcancel() { htextures.setsize(0); }
COMMAND(hmapcancel, "");
ICOMMAND(hmapselect, "", (),
int t = lookupcube(cur).texture[orient];
int i = htextures.find(t);
if(i<0)
htextures.add(t);
else
htextures.remove(i);
);
inline bool isheightmap(int o, int d, bool empty, cube *c)
{
return havesel ||
(empty && isempty(*c)) ||
htextures.empty() ||
htextures.find(c->texture[o]) >= 0;
}
namespace hmap
{
# define PAINTED 1
# define NOTHMAP 2
# define MAPPED 16
uchar flags[MAXBRUSH][MAXBRUSH];
cube *cmap[MAXBRUSHC][MAXBRUSHC][4];
int mapz[MAXBRUSHC][MAXBRUSHC];
int map [MAXBRUSH][MAXBRUSH];
selinfo changes;
bool selecting;
int d, dc, dr, dcr, biasup, br, hws, fg;
int gx, gy, gz, mx, my, mz, nx, ny, nz, bmx, bmy, bnx, bny;
uint fs;
selinfo hundo;
cube *getcube(ivec t, int f)
{
t[d] += dcr*f*gridsize;
if(t[d] > nz || t[d] < mz) return NULL;
cube *c = &lookupcube(t, gridsize);
if(c->children) forcemip(*c, false);
discardchildren(*c, true);
if(!isheightmap(sel.orient, d, true, c)) return NULL;
if (t.x < changes.o.x) changes.o.x = t.x;
else if(t.x > changes.s.x) changes.s.x = t.x;
if (t.y < changes.o.y) changes.o.y = t.y;
else if(t.y > changes.s.y) changes.s.y = t.y;
if (t.z < changes.o.z) changes.o.z = t.z;
else if(t.z > changes.s.z) changes.s.z = t.z;
return c;
}
uint getface(cube *c, int d)
{
return 0x0f0f0f0f & ((dc ? c->faces[d] : 0x88888888 - c->faces[d]) >> fs);
}
void pushside(cube &c, int d, int x, int y, int z)
{
ivec a;
getcubevector(c, d, x, y, z, a);
a[R[d]] = 8 - a[R[d]];
setcubevector(c, d, x, y, z, a);
}
void addpoint(int x, int y, int z, int v)
{
if(!(flags[x][y] & MAPPED))
map[x][y] = v + (z*8);
flags[x][y] |= MAPPED;
}
void select(int x, int y, int z)
{
if((NOTHMAP & flags[x][y]) || (PAINTED & flags[x][y])) return;
ivec t(d, x+gx, y+gy, dc ? z : hws-z);
t.shl(gridpower);
// selections may damage; must makeundo before
hundo.o = t;
hundo.o[D[d]] -= dcr*gridsize*2;
makeundo(hundo);
cube **c = cmap[x][y];
loopk(4) c[k] = NULL;
c[1] = getcube(t, 0);
if(!c[1] || !isempty(*c[1]))
{ // try up
c[2] = c[1];
c[1] = getcube(t, 1);
if(!c[1] || isempty(*c[1])) { c[0] = c[1]; c[1] = c[2]; c[2] = NULL; }
else { z++; t[d]+=fg; }
}
else // drop down
{
z--;
t[d]-= fg;
c[0] = c[1];
c[1] = getcube(t, 0);
}
if(!c[1] || isempty(*c[1])) { flags[x][y] |= NOTHMAP; return; }
flags[x][y] |= PAINTED;
mapz [x][y] = z;
if(!c[0]) c[0] = getcube(t, 1);
if(!c[2]) c[2] = getcube(t, -1);
c[3] = getcube(t, -2);
c[2] = !c[2] || isempty(*c[2]) ? NULL : c[2];
c[3] = !c[3] || isempty(*c[3]) ? NULL : c[3];
uint face = getface(c[1], d);
if(face == 0x08080808 && (!c[0] || !isempty(*c[0]))) { flags[x][y] |= NOTHMAP; return; }
if(c[1]->faces[R[d]] == F_SOLID) // was single
face += 0x08080808;
else // was pair
face += c[2] ? getface(c[2], d) : 0x08080808;
face += 0x08080808; // c[3]
uchar *f = (uchar*)&face;
addpoint(x, y, z, f[0]);
addpoint(x+1, y, z, f[1]);
addpoint(x, y+1, z, f[2]);
addpoint(x+1, y+1, z, f[3]);
if(selecting) // continue to adjacent cubes
{
if(x>bmx) select(x-1, y, z);
if(x<bnx) select(x+1, y, z);
if(y>bmy) select(x, y-1, z);
if(y<bny) select(x, y+1, z);
}
}
void ripple(int x, int y, int z, bool force)
{
if(force) select(x, y, z);
if((NOTHMAP & flags[x][y]) || !(PAINTED & flags[x][y])) return;
bool changed = false;
int *o[4], best, par, q = 0;
loopi(2) loopj(2) o[i+j*2] = &map[x+i][y+j];
#define pullhmap(I, LT, GT, M, N, A) do { \
best = I; \
loopi(4) if(*o[i] LT best) best = *o[q = i] - M; \
par = (best&(~7)) + N; \
/* dual layer for extra smoothness */ \
if(*o[q^3] GT par && !(*o[q^1] LT par || *o[q^2] LT par)) { \
if(*o[q^3] GT par A 8 || *o[q^1] != par || *o[q^2] != par) { \
*o[q^3] = (*o[q^3] GT par A 8 ? par A 8 : *o[q^3]); \
*o[q^1] = *o[q^2] = par; \
changed = true; \
} \
/* single layer */ \
} else { \
loopj(4) if(*o[j] GT par) { \
*o[j] = par; \
changed = true; \
} \
} \
} while(0)
if(biasup)
pullhmap(0, >, <, 1, 0, -);
else
pullhmap(worldsize*8, <, >, 0, 8, +);
cube **c = cmap[x][y];
int e[2][2];
int notempty = 0;
loopk(4) if(c[k]) {
loopi(2) loopj(2) {
e[i][j] = min(8, map[x+i][y+j] - (mapz[x][y]+3-k)*8);
notempty |= e[i][j] > 0;
}
if(notempty)
{
c[k]->texture[sel.orient] = c[1]->texture[sel.orient];
solidfaces(*c[k]);
loopi(2) loopj(2)
{
int f = e[i][j];
if(f<0 || (f==0 && e[1-i][j]==0 && e[i][1-j]==0))
{
f=0;
pushside(*c[k], d, i, j, 0);
pushside(*c[k], d, i, j, 1);
}
edgeset(cubeedge(*c[k], d, i, j), dc, dc ? f : 8-f);
}
}
else
emptyfaces(*c[k]);
}
if(!changed) return;
if(x>mx) ripple(x-1, y, mapz[x][y], true);
if(x<nx) ripple(x+1, y, mapz[x][y], true);
if(y>my) ripple(x, y-1, mapz[x][y], true);
if(y<ny) ripple(x, y+1, mapz[x][y], true);
#define DIAGONAL_RIPPLE(a,b,exp) if(exp) { \
if(flags[x a][ y] & PAINTED) \
ripple(x a, y b, mapz[x a][y], true); \
else if(flags[x][y b] & PAINTED) \
ripple(x a, y b, mapz[x][y b], true); \
}
DIAGONAL_RIPPLE(-1, -1, (x>mx && y>my)); // do diagonals because adjacents
DIAGONAL_RIPPLE(-1, +1, (x>mx && y<ny)); // won't unless changed
DIAGONAL_RIPPLE(+1, +1, (x<nx && y<ny));
DIAGONAL_RIPPLE(+1, -1, (x<nx && y>my));
}
#define loopbrush(i) for(int x=bmx; x<=bnx+i; x++) for(int y=bmy; y<=bny+i; y++)
void paint()
{
loopbrush(1)
map[x][y] -= dr * brush[x][y];
}
void smooth()
{
int sum, div;
loopbrush(-2)
{
sum = 0;
div = 9;
loopi(3) loopj(3)
if(flags[x+i][y+j] & MAPPED)
sum += map[x+i][y+j];
else div--;
if(div)
map[x+1][y+1] = sum / div;
}
}
void rippleandset()
{
loopbrush(0)
ripple(x, y, gz, false);
}
void run(int dir, int mode)
{
d = dimension(sel.orient);
dc = dimcoord(sel.orient);
dcr= dc ? 1 : -1;
dr = dir>0 ? 1 : -1;
br = dir>0 ? 0x08080808 : 0;
// biasup = mode == dir<0;
biasup = dir<0;
bool paintme = paintbrush;
int cx = (sel.corner&1 ? 0 : -1);
int cy = (sel.corner&2 ? 0 : -1);
hws= (worldsize>>gridpower);
gx = (cur[R[d]] >> gridpower) + cx - MAXBRUSH2;
gy = (cur[C[d]] >> gridpower) + cy - MAXBRUSH2;
gz = (cur[D[d]] >> gridpower);
fs = dc ? 4 : 0;
fg = dc ? gridsize : -gridsize;
mx = max(0, -gx); // ripple range
my = max(0, -gy);
nx = min(MAXBRUSH-1, hws-gx) - 1;
ny = min(MAXBRUSH-1, hws-gy) - 1;
if(havesel)
{ // selection range
bmx = mx = max(mx, (sel.o[R[d]]>>gridpower)-gx);
bmy = my = max(my, (sel.o[C[d]]>>gridpower)-gy);
bnx = nx = min(nx, (sel.s[R[d]]+(sel.o[R[d]]>>gridpower))-gx-1);
bny = ny = min(ny, (sel.s[C[d]]+(sel.o[C[d]]>>gridpower))-gy-1);
}
if(havesel && mode<0) // -ve means smooth selection
paintme = false;
else
{ // brush range
bmx = max(mx, brushminx);
bmy = max(my, brushminy);
bnx = min(nx, brushmaxx-1);
bny = min(ny, brushmaxy-1);
}
nz = worldsize-gridsize;
mz = 0;
hundo.s = ivec(d,1,1,5);
hundo.orient = sel.orient;
hundo.grid = gridsize;
forcenextundo();
changes.grid = gridsize;
changes.s = changes.o = cur;
memset(map, 0, sizeof map);
memset(flags, 0, sizeof flags);
selecting = true;
select(clamp(MAXBRUSH2-cx, bmx, bnx),
clamp(MAXBRUSH2-cy, bmy, bny),
dc ? gz : hws - gz);
selecting = false;
if(paintme)
paint();
else
smooth();
rippleandset(); // pull up points to cubify, and set
changes.s.sub(changes.o).shr(gridpower).add(1);
changed(changes);
}
}
void edithmap(int dir, int mode) {
if((nompedit && multiplayer()) || !hmapsel) return;
hmap::run(dir, mode);
}
///////////// main cube edit ////////////////
int bounded(int n) { return n<0 ? 0 : (n>8 ? 8 : n); }
void pushedge(uchar &edge, int dir, int dc)
{
int ne = bounded(edgeget(edge, dc)+dir);
edgeset(edge, dc, ne);
int oe = edgeget(edge, 1-dc);
if((dir<0 && dc && oe>ne) || (dir>0 && dc==0 && oe<ne)) edgeset(edge, 1-dc, ne);
}
void linkedpush(cube &c, int d, int x, int y, int dc, int dir)
{
ivec v, p;
getcubevector(c, d, x, y, dc, v);
loopi(2) loopj(2)
{
getcubevector(c, d, i, j, dc, p);
if(v==p)
pushedge(cubeedge(c, d, i, j), dir, dc);
}
}
static ushort getmaterial(cube &c)
{
if(c.children)
{
ushort mat = getmaterial(c.children[7]);
loopi(7) if(mat != getmaterial(c.children[i])) return MAT_AIR;
return mat;
}
return c.material;
}
VAR(invalidcubeguard, 0, 1, 1);
void mpeditface(int dir, int mode, selinfo &sel, bool local)
{
if(mode==1 && (sel.cx || sel.cy || sel.cxs&1 || sel.cys&1)) mode = 0;
int d = dimension(sel.orient);
int dc = dimcoord(sel.orient);
int seldir = dc ? -dir : dir;
if(local)
game::edittrigger(sel, EDIT_FACE, dir, mode);
if(mode==1)
{
int h = sel.o[d]+dc*sel.grid;
if(((dir>0) == dc && h<=0) || ((dir<0) == dc && h>=worldsize)) return;
if(dir<0) sel.o[d] += sel.grid * seldir;
}
if(dc) sel.o[d] += sel.us(d)-sel.grid;
sel.s[d] = 1;
loopselxyz(
if(c.children) solidfaces(c);
ushort mat = getmaterial(c);
discardchildren(c, true);
c.material = mat;
if(mode==1) // fill command
{
if(dir<0)
{
solidfaces(c);
cube &o = blockcube(x, y, 1, sel, -sel.grid);
loopi(6)
c.texture[i] = o.children ? DEFAULT_GEOM : o.texture[i];
}
else
emptyfaces(c);
}
else
{
uint bak = c.faces[d];
uchar *p = (uchar *)&c.faces[d];
if(mode==2)
linkedpush(c, d, sel.corner&1, sel.corner>>1, dc, seldir); // corner command
else
{
loop(mx,2) loop(my,2) // pull/push edges command
{
if(x==0 && mx==0 && sel.cx) continue;
if(y==0 && my==0 && sel.cy) continue;
if(x==sel.s[R[d]]-1 && mx==1 && (sel.cx+sel.cxs)&1) continue;
if(y==sel.s[C[d]]-1 && my==1 && (sel.cy+sel.cys)&1) continue;
if(p[mx+my*2] != ((uchar *)&bak)[mx+my*2]) continue;
linkedpush(c, d, mx, my, dc, seldir);
}
}
optiface(p, c);
if(invalidcubeguard==1 && !isvalidcube(c))
{
uint newbak = c.faces[d];
uchar *m = (uchar *)&bak;
uchar *n = (uchar *)&newbak;
loopk(4) if(n[k] != m[k]) // tries to find partial edit that is valid
{
c.faces[d] = bak;
c.edges[d*4+k] = n[k];
if(isvalidcube(c))
m[k] = n[k];
}
c.faces[d] = bak;
}
}
);
if (mode==1 && dir>0)
sel.o[d] += sel.grid * seldir;
}
void editface(int *dir, int *mode)
{
if(noedit(moving!=0)) return;
if(hmapedit!=1)
mpeditface(*dir, *mode, sel, true);
else
edithmap(*dir, *mode);
}
VAR(selectionsurf, 0, 0, 1);
void pushsel(int *dir)
{
if(noedit(moving!=0)) return;
int d = dimension(orient);
int s = dimcoord(orient) ? -*dir : *dir;
sel.o[d] += s*sel.grid;
if(selectionsurf==1)
{
player->o[d] += s*sel.grid;
player->resetinterp();
}
}
void mpdelcube(selinfo &sel, bool local)
{
if(local) game::edittrigger(sel, EDIT_DELCUBE);
loopselxyz(discardchildren(c, true); emptyfaces(c));
}
void delcube()
{
if(noedit()) return;
mpdelcube(sel, true);
}
COMMAND(pushsel, "i");
COMMAND(editface, "ii");
COMMAND(delcube, "");
/////////// texture editing //////////////////
int curtexindex = -1, lasttex = 0, lasttexmillis = -1;
int texpaneltimer = 0;
vector<ushort> texmru;
void tofronttex() // maintain most recently used of the texture lists when applying texture
{
int c = curtexindex;
if(texmru.inrange(c))
{
texmru.insert(0, texmru.remove(c));
curtexindex = -1;
}
}
selinfo repsel;
int reptex = -1;
static vector<vslotmap> remappedvslots;
VAR(usevdelta, 1, 0, 0);
static VSlot *remapvslot(int index, bool delta, const VSlot &ds)
{
loopv(remappedvslots) if(remappedvslots[i].index == index) return remappedvslots[i].vslot;
VSlot &vs = lookupvslot(index, false);
if(vs.index < 0 || vs.index == DEFAULT_SKY) return NULL;
VSlot *edit = NULL;
if(delta)
{
VSlot ms;
mergevslot(ms, vs, ds);
edit = ms.changed ? editvslot(vs, ms) : vs.slot->variants;
}
else edit = ds.changed ? editvslot(vs, ds) : vs.slot->variants;
if(!edit) edit = &vs;
remappedvslots.add(vslotmap(vs.index, edit));
return edit;
}
static void remapvslots(cube &c, bool delta, const VSlot &ds, int orient, bool &findrep, VSlot *&findedit)
{
if(c.children)
{
loopi(8) remapvslots(c.children[i], delta, ds, orient, findrep, findedit);
return;
}
static VSlot ms;
if(orient<0) loopi(6)
{
VSlot *edit = remapvslot(c.texture[i], delta, ds);
if(edit)
{
c.texture[i] = edit->index;
if(!findedit) findedit = edit;
}
}
else
{
int i = visibleorient(c, orient);
VSlot *edit = remapvslot(c.texture[i], delta, ds);
if(edit)
{
if(findrep)
{
if(reptex < 0) reptex = c.texture[i];
else if(reptex != c.texture[i]) findrep = false;
}
c.texture[i] = edit->index;
if(!findedit) findedit = edit;
}
}
}
void edittexcube(cube &c, int tex, int orient, bool &findrep)
{
if(orient<0) loopi(6) c.texture[i] = tex;
else
{
int i = visibleorient(c, orient);
if(findrep)
{
if(reptex < 0) reptex = c.texture[i];
else if(reptex != c.texture[i]) findrep = false;
}
c.texture[i] = tex;
}
if(c.children) loopi(8) edittexcube(c.children[i], tex, orient, findrep);
}
VAR(allfaces, 0, 0, 1);
void mpeditvslot(int delta, VSlot &ds, int allfaces, selinfo &sel, bool local)
{
if(local)
{
game::edittrigger(sel, EDIT_VSLOT, delta, allfaces, 0, &ds);
if(!(lastsel==sel)) tofronttex();
if(allfaces || !(repsel == sel)) reptex = -1;
repsel = sel;
}
bool findrep = local && !allfaces && reptex < 0;
VSlot *findedit = NULL;
loopselxyz(remapvslots(c, delta != 0, ds, allfaces ? -1 : sel.orient, findrep, findedit));
remappedvslots.setsize(0);
if(local && findedit)
{
lasttex = findedit->index;
lasttexmillis = totalmillis;
curtexindex = texmru.find(lasttex);
if(curtexindex < 0)
{
curtexindex = texmru.length();
texmru.add(lasttex);
}
}
}
bool mpeditvslot(int delta, int allfaces, selinfo &sel, ucharbuf &buf)
{
VSlot ds;
if(!unpackvslot(buf, ds, delta != 0)) return false;
editingvslot(ds.layer);
mpeditvslot(delta, ds, allfaces, sel, false);
return true;
}
void vdelta(char *body)
{
#ifndef OLDPROTO
if(noedit()) return;
#else
if(noedit() || (nompedit && multiplayer())) return;
#endif
usevdelta++;
execute(body);
usevdelta--;
}
COMMAND(vdelta, "s");
void vrotate(int *n)
{
#ifndef OLDPROTO
if(noedit()) return;
#else
if(noedit() || (nompedit && multiplayer())) return;
#endif
VSlot ds;
ds.changed = 1<<VSLOT_ROTATION;
ds.rotation = usevdelta ? *n : clamp(*n, 0, 5);
mpeditvslot(usevdelta, ds, allfaces, sel, true);
}
COMMAND(vrotate, "i");
void voffset(int *x, int *y)
{
#ifndef OLDPROTO
if(noedit()) return;
#else
if(noedit() || (nompedit && multiplayer())) return;
#endif
VSlot ds;
ds.changed = 1<<VSLOT_OFFSET;
ds.offset = usevdelta ? ivec2(*x, *y) : ivec2(*x, *y).max(0);
mpeditvslot(usevdelta, ds, allfaces, sel, true);
}
COMMAND(voffset, "ii");
void vscroll(float *s, float *t)
{
#ifndef OLDPROTO
if(noedit()) return;
#else
if(noedit() || (nompedit && multiplayer())) return;
#endif
VSlot ds;
ds.changed = 1<<VSLOT_SCROLL;
ds.scroll = vec2(*s, *t).div(1000);
mpeditvslot(usevdelta, ds, allfaces, sel, true);
}
COMMAND(vscroll, "ff");
void vscale(float *scale)
{
#ifndef OLDPROTO
if(noedit()) return;
#else
if(noedit() || (nompedit && multiplayer())) return;
#endif
VSlot ds;
ds.changed = 1<<VSLOT_SCALE;
ds.scale = *scale <= 0 ? 1 : (usevdelta ? *scale : clamp(*scale, 1/8.0f, 8.0f));
mpeditvslot(usevdelta, ds, allfaces, sel, true);
}
COMMAND(vscale, "f");
void vlayer(int *n)
{
#ifndef OLDPROTO
if(noedit()) return;
#else
if(noedit() || (nompedit && multiplayer())) return;
#endif
VSlot ds;
ds.changed = 1<<VSLOT_LAYER;
if(vslots.inrange(*n))
{
ds.layer = *n;
if(vslots[ds.layer]->changed && nompedit && multiplayer()) return;
}
editingvslot(ds.layer);
mpeditvslot(usevdelta, ds, allfaces, sel, true);
}
COMMAND(vlayer, "i");
void valpha(float *front, float *back)
{
#ifndef OLDPROTO
if(noedit()) return;
#else
if(noedit() || (nompedit && multiplayer())) return;
#endif
VSlot ds;
ds.changed = 1<<VSLOT_ALPHA;
ds.alphafront = clamp(*front, 0.0f, 1.0f);
ds.alphaback = clamp(*back, 0.0f, 1.0f);
mpeditvslot(usevdelta, ds, allfaces, sel, true);
}
COMMAND(valpha, "ff");
void vcolor(float *r, float *g, float *b)
{
#ifndef OLDPROTO
if(noedit()) return;
#else
if(noedit() || (nompedit && multiplayer())) return;
#endif
VSlot ds;
ds.changed = 1<<VSLOT_COLOR;
ds.colorscale = vec(clamp(*r, 0.0f, 1.0f), clamp(*g, 0.0f, 1.0f), clamp(*b, 0.0f, 1.0f));
mpeditvslot(usevdelta, ds, allfaces, sel, true);
}
COMMAND(vcolor, "fff");
void vreset()
{
#ifndef OLDPROTO
if(noedit()) return;
#else
if(noedit() || (nompedit && multiplayer())) return;
#endif
VSlot ds;
mpeditvslot(usevdelta, ds, allfaces, sel, true);
}
COMMAND(vreset, "");
void vshaderparam(const char *name, float *x, float *y, float *z, float *w)
{
#ifndef OLDPROTO
if(noedit()) return;
#else
if(noedit() || (nompedit && multiplayer())) return;
#endif
VSlot ds;
ds.changed = 1<<VSLOT_SHPARAM;
if(name[0])
{
SlotShaderParam p = { getshaderparamname(name), -1, {*x, *y, *z, *w} };
ds.params.add(p);
}
mpeditvslot(usevdelta, ds, allfaces, sel, true);
}
COMMAND(vshaderparam, "sffff");
void mpedittex(int tex, int allfaces, selinfo &sel, bool local)
{
if(local)
{
game::edittrigger(sel, EDIT_TEX, tex, allfaces);
if(allfaces || !(repsel == sel)) reptex = -1;
repsel = sel;
}
bool findrep = local && !allfaces && reptex < 0;
loopselxyz(edittexcube(c, tex, allfaces ? -1 : sel.orient, findrep));
}
static int unpacktex(int &tex, ucharbuf &buf, bool insert = true)
{
if(tex < 0x10000) return true;
VSlot ds;
if(!unpackvslot(buf, ds, false)) return false;
VSlot &vs = *lookupslot(tex & 0xFFFF, false).variants;
if(vs.index < 0 || vs.index == DEFAULT_SKY) return false;
VSlot *edit = insert ? editvslot(vs, ds) : findvslot(*vs.slot, vs, ds);
if(!edit) return false;
tex = edit->index;
return true;
}
int shouldpacktex(int index)
{
if(vslots.inrange(index))
{
VSlot &vs = *vslots[index];
if(vs.changed) return 0x10000 + vs.slot->index;
}
return 0;
}
bool mpedittex(int tex, int allfaces, selinfo &sel, ucharbuf &buf)
{
if(!unpacktex(tex, buf)) return false;
mpedittex(tex, allfaces, sel, false);
return true;
}
void filltexlist()
{
if(texmru.length()!=vslots.length())
{
loopvrev(texmru) if(texmru[i]>=vslots.length())
{
if(curtexindex > i) curtexindex--;
else if(curtexindex == i) curtexindex = -1;
texmru.remove(i);
}
loopv(vslots) if(texmru.find(i)<0) texmru.add(i);
}
}
void compactmruvslots()
{
remappedvslots.setsize(0);
loopvrev(texmru)
{
if(vslots.inrange(texmru[i]))
{
VSlot &vs = *vslots[texmru[i]];
if(vs.index >= 0)
{
texmru[i] = vs.index;
continue;
}
}
if(curtexindex > i) curtexindex--;
else if(curtexindex == i) curtexindex = -1;
texmru.remove(i);
}
if(vslots.inrange(lasttex))
{
VSlot &vs = *vslots[lasttex];
lasttex = vs.index >= 0 ? vs.index : 0;
}
else lasttex = 0;
reptex = vslots.inrange(reptex) ? vslots[reptex]->index : -1;
}
void edittex(int i, bool save = true)
{
lasttex = i;
lasttexmillis = totalmillis;
if(save)
{
loopvj(texmru) if(texmru[j]==lasttex) { curtexindex = j; break; }
}
mpedittex(i, allfaces, sel, true);
}
void edittex_(int *dir)
{
if(noedit()) return;
filltexlist();
if(texmru.empty()) return;
texpaneltimer = 5000;
if(!(lastsel==sel)) tofronttex();
curtexindex = clamp(curtexindex<0 ? 0 : curtexindex+*dir, 0, texmru.length()-1);
edittex(texmru[curtexindex], false);
}
void gettex()
{
if(noedit(true)) return;
filltexlist();
int tex = -1;
loopxyz(sel, sel.grid, tex = c.texture[sel.orient]);
loopv(texmru) if(texmru[i]==tex)
{
curtexindex = i;
tofronttex();
return;
}
}
void getcurtex()
{
if(noedit(true)) return;
filltexlist();
int index = curtexindex < 0 ? 0 : curtexindex;
if(!texmru.inrange(index)) return;
intret(texmru[index]);
}
void getseltex()
{
if(noedit(true)) return;
cube &c = lookupcube(sel.o, -sel.grid);
if(c.children || isempty(c)) return;
intret(c.texture[sel.orient]);
}
void gettexname(int *tex, int *subslot)
{
if(noedit(true) || *tex<0) return;
VSlot &vslot = lookupvslot(*tex, false);
Slot &slot = *vslot.slot;
if(!slot.sts.inrange(*subslot)) return;
result(slot.sts[*subslot].name);
}
COMMANDN(edittex, edittex_, "i");
COMMAND(gettex, "");
COMMAND(getcurtex, "");
COMMAND(getseltex, "");
ICOMMAND(getreptex, "", (), { if(!noedit()) intret(vslots.inrange(reptex) ? reptex : -1); });
COMMAND(gettexname, "ii");
void replacetexcube(cube &c, int oldtex, int newtex)
{
loopi(6) if(c.texture[i] == oldtex) c.texture[i] = newtex;
if(c.children) loopi(8) replacetexcube(c.children[i], oldtex, newtex);
}
void mpreplacetex(int oldtex, int newtex, bool insel, selinfo &sel, bool local)
{
if(local) game::edittrigger(sel, EDIT_REPLACE, oldtex, newtex, insel ? 1 : 0);
if(insel)
{
loopselxyz(replacetexcube(c, oldtex, newtex));
}
else
{
loopi(8) replacetexcube(worldroot[i], oldtex, newtex);
}
allchanged();
}
bool mpreplacetex(int oldtex, int newtex, bool insel, selinfo &sel, ucharbuf &buf)
{
if(!unpacktex(oldtex, buf, false)) return false;
editingvslot(oldtex);
if(!unpacktex(newtex, buf)) return false;
mpreplacetex(oldtex, newtex, insel, sel, false);
return true;
}
void replace(bool insel)
{
if(noedit()) return;
if(reptex < 0) { conoutf(CON_ERROR, "can only replace after a texture edit"); return; }
mpreplacetex(reptex, lasttex, insel, sel, true);
}
ICOMMAND(replace, "", (), replace(false));
ICOMMAND(replacesel, "", (), replace(true));
////////// flip and rotate ///////////////
uint dflip(uint face) { return face==F_EMPTY ? face : 0x88888888 - (((face&0xF0F0F0F0)>>4) | ((face&0x0F0F0F0F)<<4)); }
uint cflip(uint face) { return ((face&0xFF00FF00)>>8) | ((face&0x00FF00FF)<<8); }
uint rflip(uint face) { return ((face&0xFFFF0000)>>16)| ((face&0x0000FFFF)<<16); }
uint mflip(uint face) { return (face&0xFF0000FF) | ((face&0x00FF0000)>>8) | ((face&0x0000FF00)<<8); }
void flipcube(cube &c, int d)
{
swap(c.texture[d*2], c.texture[d*2+1]);
c.faces[D[d]] = dflip(c.faces[D[d]]);
c.faces[C[d]] = cflip(c.faces[C[d]]);
c.faces[R[d]] = rflip(c.faces[R[d]]);
if(c.children)
{
loopi(8) if(i&octadim(d)) swap(c.children[i], c.children[i-octadim(d)]);
loopi(8) flipcube(c.children[i], d);
}
}
void rotatequad(cube &a, cube &b, cube &c, cube &d)
{
cube t = a; a = b; b = c; c = d; d = t;
}
void rotatecube(cube &c, int d) // rotates cube clockwise. see pics in cvs for help.
{
c.faces[D[d]] = cflip (mflip(c.faces[D[d]]));
c.faces[C[d]] = dflip (mflip(c.faces[C[d]]));
c.faces[R[d]] = rflip (mflip(c.faces[R[d]]));
swap(c.faces[R[d]], c.faces[C[d]]);
swap(c.texture[2*R[d]], c.texture[2*C[d]+1]);
swap(c.texture[2*C[d]], c.texture[2*R[d]+1]);
swap(c.texture[2*C[d]], c.texture[2*C[d]+1]);
if(c.children)
{
int row = octadim(R[d]);
int col = octadim(C[d]);
for(int i=0; i<=octadim(d); i+=octadim(d)) rotatequad
(
c.children[i+row],
c.children[i],
c.children[i+col],
c.children[i+col+row]
);
loopi(8) rotatecube(c.children[i], d);
}
}
void mpflip(selinfo &sel, bool local)
{
if(local)
{
game::edittrigger(sel, EDIT_FLIP);
makeundo();
}
int zs = sel.s[dimension(sel.orient)];
loopxy(sel)
{
loop(z,zs) flipcube(selcube(x, y, z), dimension(sel.orient));
loop(z,zs/2)
{
cube &a = selcube(x, y, z);
cube &b = selcube(x, y, zs-z-1);
swap(a, b);
}
}
changed(sel);
}
void flip()
{
if(noedit()) return;
mpflip(sel, true);
}
void mprotate(int cw, selinfo &sel, bool local)
{
if(local) game::edittrigger(sel, EDIT_ROTATE, cw);
int d = dimension(sel.orient);
if(!dimcoord(sel.orient)) cw = -cw;
int m = sel.s[C[d]] < sel.s[R[d]] ? C[d] : R[d];
int ss = sel.s[m] = max(sel.s[R[d]], sel.s[C[d]]);
if(local) makeundo();
loop(z,sel.s[D[d]]) loopi(cw>0 ? 1 : 3)
{
loopxy(sel) rotatecube(selcube(x,y,z), d);
loop(y,ss/2) loop(x,ss-1-y*2) rotatequad
(
selcube(ss-1-y, x+y, z),
selcube(x+y, y, z),
selcube(y, ss-1-x-y, z),
selcube(ss-1-x-y, ss-1-y, z)
);
}
changed(sel);
}
void rotate(int *cw)
{
if(noedit()) return;
mprotate(*cw, sel, true);
}
COMMAND(flip, "");
COMMAND(rotate, "i");
enum { EDITMATF_EMPTY = 0x10000, EDITMATF_NOTEMPTY = 0x20000, EDITMATF_SOLID = 0x30000, EDITMATF_NOTSOLID = 0x40000 };
static const struct { const char *name; int filter; } editmatfilters[] =
{
{ "empty", EDITMATF_EMPTY },
{ "notempty", EDITMATF_NOTEMPTY },
{ "solid", EDITMATF_SOLID },
{ "notsolid", EDITMATF_NOTSOLID }
};
void setmat(cube &c, ushort mat, ushort matmask, ushort filtermat, ushort filtermask, int filtergeom)
{
if(c.children)
loopi(8) setmat(c.children[i], mat, matmask, filtermat, filtermask, filtergeom);
else if((c.material&filtermask) == filtermat)
{
switch(filtergeom)
{
case EDITMATF_EMPTY: if(isempty(c)) break; return;
case EDITMATF_NOTEMPTY: if(!isempty(c)) break; return;
case EDITMATF_SOLID: if(isentirelysolid(c)) break; return;
case EDITMATF_NOTSOLID: if(!isentirelysolid(c)) break; return;
}
if(mat!=MAT_AIR)
{
c.material &= matmask;
c.material |= mat;
}
else c.material = MAT_AIR;
}
}
void mpeditmat(int matid, int filter, selinfo &sel, bool local)
{
if(local) game::edittrigger(sel, EDIT_MAT, matid, filter);
ushort filtermat = 0, filtermask = 0, matmask;
int filtergeom = 0;
if(filter >= 0)
{
filtermat = filter&0xFFFF;
filtermask = filtermat&(MATF_VOLUME|MATF_INDEX) ? MATF_VOLUME|MATF_INDEX : (filtermat&MATF_CLIP ? MATF_CLIP : filtermat);
filtergeom = filter&~0xFFFF;
}
if(matid < 0)
{
matid = 0;
matmask = filtermask;
if(isclipped(filtermat&MATF_VOLUME)) matmask &= ~MATF_CLIP;
if(isdeadly(filtermat&MATF_VOLUME)) matmask &= ~MAT_DEATH;
}
else
{
matmask = matid&(MATF_VOLUME|MATF_INDEX) ? 0 : (matid&MATF_CLIP ? ~MATF_CLIP : ~matid);
if(isclipped(matid&MATF_VOLUME)) matid |= MAT_CLIP;
if(isdeadly(matid&MATF_VOLUME)) matid |= MAT_DEATH;
}
loopselxyz(setmat(c, matid, matmask, filtermat, filtermask, filtergeom));
}
void editmat(char *name, char *filtername)
{
if(noedit()) return;
int filter = -1;
if(filtername[0])
{
loopi(sizeof(editmatfilters)/sizeof(editmatfilters[0])) if(!strcmp(editmatfilters[i].name, filtername)) { filter = editmatfilters[i].filter; break; }
if(filter < 0) filter = findmaterial(filtername);
if(filter < 0)
{
conoutf(CON_ERROR, "unknown material \"%s\"", filtername);
return;
}
}
int id = -1;
if(name[0] || filter < 0)
{
id = findmaterial(name);
if(id<0) { conoutf(CON_ERROR, "unknown material \"%s\"", name); return; }
}
mpeditmat(id, filter, sel, true);
}
COMMAND(editmat, "ss");
extern int menudistance, menuautoclose;
VARP(texguiwidth, 1, 12, 1000);
VARP(texguiheight, 1, 8, 1000);
VARP(texguitime, 0, 25, 1000);
static int lastthumbnail = 0;
VARP(texgui2d, 0, 1, 1);
struct texturegui : g3d_callback
{
bool menuon;
vec menupos;
int menustart, menutab;
texturegui() : menustart(-1) {}
void gui(g3d_gui &g, bool firstpass)
{
int origtab = menutab, numtabs = max((slots.length() + texguiwidth*texguiheight - 1)/(texguiwidth*texguiheight), 1);
g.start(menustart, 0.04f, &menutab);
loopi(numtabs)
{
g.tab(!i ? "Textures" : NULL, 0xAAFFAA);
if(i+1 != origtab) continue; //don't load textures on non-visible tabs!
loop(h, texguiheight)
{
g.pushlist();
loop(w, texguiwidth)
{
extern VSlot dummyvslot;
int ti = (i*texguiheight+h)*texguiwidth+w;
if(ti<slots.length())
{
Slot &slot = lookupslot(ti, false);
VSlot &vslot = *slot.variants;
if(slot.sts.empty()) continue;
else if(!slot.loaded && !slot.thumbnail)
{
if(totalmillis-lastthumbnail<texguitime)
{
g.texture(dummyvslot, 1.0, false); //create an empty space
continue;
}
loadthumbnail(slot);
lastthumbnail = totalmillis;
}
if(g.texture(vslot, 1.0f, true)&G3D_UP && (slot.loaded || slot.thumbnail!=notexture))
{
edittex(vslot.index);
hudshader->set();
}
}
else
{
g.texture(dummyvslot, 1.0, false); //create an empty space
}
}
g.poplist();
}
}
g.end();
}
void showtextures(bool on)
{
if(on != menuon && (menuon = on))
{
if(menustart <= lasttexmillis)
menutab = 1+clamp(lookupvslot(lasttex, false).slot->index, 0, slots.length()-1)/(texguiwidth*texguiheight);
menupos = menuinfrontofplayer();
menustart = starttime();
}
}
void show()
{
if(!menuon) return;
filltexlist();
extern int usegui2d;
if(!editmode || ((!texgui2d || !usegui2d) && camera1->o.dist(menupos) > menuautoclose)) menuon = false;
else g3d_addgui(this, menupos, texgui2d ? GUI_2D : 0);
}
} gui;
void g3d_texturemenu()
{
gui.show();
}
void showtexgui(int *n)
{
if(!editmode) { conoutf(CON_ERROR, "operation only allowed in edit mode"); return; }
gui.showtextures(*n==0 ? !gui.menuon : *n==1);
}
// 0/noargs = toggle, 1 = on, other = off - will autoclose if too far away or exit editmode
COMMAND(showtexgui, "i");
void rendertexturepanel(int w, int h)
{
if((texpaneltimer -= curtime)>0 && editmode)
{
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
pushhudmatrix();
hudmatrix.scale(h/1800.0f, h/1800.0f, 1);
flushhudmatrix(false);
SETSHADER(hudrgb);
int y = 50, gap = 10;
gle::defvertex(2);
gle::deftexcoord0();
loopi(7)
{
int s = (i == 3 ? 285 : 220), ti = curtexindex+i-3;
if(texmru.inrange(ti))
{
VSlot &vslot = lookupvslot(texmru[ti]), *layer = NULL;
Slot &slot = *vslot.slot;
Texture *tex = slot.sts.empty() ? notexture : slot.sts[0].t, *glowtex = NULL, *layertex = NULL;
if(slot.texmask&(1<<TEX_GLOW))
{
loopvj(slot.sts) if(slot.sts[j].type==TEX_GLOW) { glowtex = slot.sts[j].t; break; }
}
if(vslot.layer)
{
layer = &lookupvslot(vslot.layer);
layertex = layer->slot->sts.empty() ? notexture : layer->slot->sts[0].t;
}
float sx = min(1.0f, tex->xs/(float)tex->ys), sy = min(1.0f, tex->ys/(float)tex->xs);
int x = w*1800/h-s-50, r = s;
vec2 tc[4] = { vec2(0, 0), vec2(1, 0), vec2(1, 1), vec2(0, 1) };
float xoff = vslot.offset.x, yoff = vslot.offset.y;
if(vslot.rotation)
{
if((vslot.rotation&5) == 1) { swap(xoff, yoff); loopk(4) swap(tc[k].x, tc[k].y); }
if(vslot.rotation >= 2 && vslot.rotation <= 4) { xoff *= -1; loopk(4) tc[k].x *= -1; }
if(vslot.rotation <= 2 || vslot.rotation == 5) { yoff *= -1; loopk(4) tc[k].y *= -1; }
}
loopk(4) { tc[k].x = tc[k].x/sx - xoff/tex->xs; tc[k].y = tc[k].y/sy - yoff/tex->ys; }
glBindTexture(GL_TEXTURE_2D, tex->id);
loopj(glowtex ? 3 : 2)
{
if(j < 2) gle::color(vec(vslot.colorscale).mul(j), texpaneltimer/1000.0f);
else
{
glBindTexture(GL_TEXTURE_2D, glowtex->id);
glBlendFunc(GL_SRC_ALPHA, GL_ONE);
gle::color(vslot.glowcolor, texpaneltimer/1000.0f);
}
gle::begin(GL_TRIANGLE_STRIP);
gle::attribf(x, y); gle::attrib(tc[0]);
gle::attribf(x+r, y); gle::attrib(tc[1]);
gle::attribf(x, y+r); gle::attrib(tc[3]);
gle::attribf(x+r, y+r); gle::attrib(tc[2]);
xtraverts += gle::end();
if(j==1 && layertex)
{
gle::color(layer->colorscale, texpaneltimer/1000.0f);
glBindTexture(GL_TEXTURE_2D, layertex->id);
gle::begin(GL_TRIANGLE_STRIP);
gle::attribf(x+r/2, y+r/2); gle::attrib(tc[0]);
gle::attribf(x+r, y+r/2); gle::attrib(tc[1]);
gle::attribf(x+r/2, y+r); gle::attrib(tc[3]);
gle::attribf(x+r, y+r); gle::attrib(tc[2]);
xtraverts += gle::end();
}
if(!j)
{
r -= 10;
x += 5;
y += 5;
}
else if(j == 2) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
}
y += s+gap;
}
pophudmatrix(true, false);
hudshader->set();
}
}
| [
"andrius4669@gmail.com"
] | andrius4669@gmail.com |
db76149f373b6306d6d36ee5b77a464094be676b | 9de5bc4636f13f78651238c2c7c047387e885a3b | /component/RestServer/export/WorkerThread.h | 3c7f9429cb0376832359465d249b1d91a5aa3673 | [] | no_license | nerfe/CPPRestSDK-server | 1ba7bcaf25344644e38fa5480ff8cc54968aa734 | 8b76ea5ed2071be0456df702847fac37f4f6f08a | refs/heads/main | 2023-07-13T01:06:18.610123 | 2021-07-30T14:56:00 | 2021-07-30T14:56:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 496 | h | #ifndef _WORKERTHREAD_H
#define _WORKERTHREAD_H
#include "thread.h"
#include "workqueue.h"
class WorkerThread
{
private:
std::thread *tid;
static WorkerThread* workerInstance;
public:
CWorkQueue* wmsgQueue;
WorkerThread();
virtual ~WorkerThread();
virtual void Run();
virtual void start();
static WorkerThread* getThreadInstance()
{
if(workerInstance==NULL)
workerInstance=new WorkerThread();
return workerInstance;
}
};
#endif
| [
"chandanshoun@gmail.com"
] | chandanshoun@gmail.com |
5e0e47e322ce264ce384ebef15005272e2c874d6 | 140d78334109e02590f04769ec154180b2eaf78d | /aws-cpp-sdk-sms/include/aws/sms/model/GetServersResult.h | 403b60bdc237b3a097fd4729d71c858848acdd0f | [
"Apache-2.0",
"MIT",
"JSON"
] | permissive | coderTong/aws-sdk-cpp | da140feb7e5495366a8d2a6a02cf8b28ba820ff6 | 5cd0c0a03b667c5a0bd17394924abe73d4b3754a | refs/heads/master | 2021-07-08T07:04:40.181622 | 2017-08-22T21:50:00 | 2017-08-22T21:50:00 | 101,145,374 | 0 | 1 | Apache-2.0 | 2021-05-04T21:06:36 | 2017-08-23T06:24:37 | C++ | UTF-8 | C++ | false | false | 4,243 | h | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#pragma once
#include <aws/sms/SMS_EXPORTS.h>
#include <aws/core/utils/DateTime.h>
#include <aws/sms/model/ServerCatalogStatus.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/sms/model/Server.h>
#include <utility>
namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;
namespace Utils
{
namespace Json
{
class JsonValue;
} // namespace Json
} // namespace Utils
namespace SMS
{
namespace Model
{
class AWS_SMS_API GetServersResult
{
public:
GetServersResult();
GetServersResult(const AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
GetServersResult& operator=(const AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
inline const Aws::Utils::DateTime& GetLastModifiedOn() const{ return m_lastModifiedOn; }
inline void SetLastModifiedOn(const Aws::Utils::DateTime& value) { m_lastModifiedOn = value; }
inline void SetLastModifiedOn(Aws::Utils::DateTime&& value) { m_lastModifiedOn = std::move(value); }
inline GetServersResult& WithLastModifiedOn(const Aws::Utils::DateTime& value) { SetLastModifiedOn(value); return *this;}
inline GetServersResult& WithLastModifiedOn(Aws::Utils::DateTime&& value) { SetLastModifiedOn(std::move(value)); return *this;}
inline const ServerCatalogStatus& GetServerCatalogStatus() const{ return m_serverCatalogStatus; }
inline void SetServerCatalogStatus(const ServerCatalogStatus& value) { m_serverCatalogStatus = value; }
inline void SetServerCatalogStatus(ServerCatalogStatus&& value) { m_serverCatalogStatus = std::move(value); }
inline GetServersResult& WithServerCatalogStatus(const ServerCatalogStatus& value) { SetServerCatalogStatus(value); return *this;}
inline GetServersResult& WithServerCatalogStatus(ServerCatalogStatus&& value) { SetServerCatalogStatus(std::move(value)); return *this;}
inline const Aws::Vector<Server>& GetServerList() const{ return m_serverList; }
inline void SetServerList(const Aws::Vector<Server>& value) { m_serverList = value; }
inline void SetServerList(Aws::Vector<Server>&& value) { m_serverList = std::move(value); }
inline GetServersResult& WithServerList(const Aws::Vector<Server>& value) { SetServerList(value); return *this;}
inline GetServersResult& WithServerList(Aws::Vector<Server>&& value) { SetServerList(std::move(value)); return *this;}
inline GetServersResult& AddServerList(const Server& value) { m_serverList.push_back(value); return *this; }
inline GetServersResult& AddServerList(Server&& value) { m_serverList.push_back(std::move(value)); return *this; }
inline const Aws::String& GetNextToken() const{ return m_nextToken; }
inline void SetNextToken(const Aws::String& value) { m_nextToken = value; }
inline void SetNextToken(Aws::String&& value) { m_nextToken = std::move(value); }
inline void SetNextToken(const char* value) { m_nextToken.assign(value); }
inline GetServersResult& WithNextToken(const Aws::String& value) { SetNextToken(value); return *this;}
inline GetServersResult& WithNextToken(Aws::String&& value) { SetNextToken(std::move(value)); return *this;}
inline GetServersResult& WithNextToken(const char* value) { SetNextToken(value); return *this;}
private:
Aws::Utils::DateTime m_lastModifiedOn;
ServerCatalogStatus m_serverCatalogStatus;
Aws::Vector<Server> m_serverList;
Aws::String m_nextToken;
};
} // namespace Model
} // namespace SMS
} // namespace Aws
| [
"henso@amazon.com"
] | henso@amazon.com |
ff41145cba05ec35d2ff7a85ca27949a407ef29e | 09112640ccaf06b9cc28317a67f803f9131ed65d | /BolosLocos/BolosLocos/skeleton/main.cpp | 409742725ccf15c1ddfc05b850ee22736ce388e1 | [] | no_license | Posna/SimulacionFisicaPracticas | 42552434f44d2bebeec991e4b001f826d74819e7 | 974899fc0c87a4663f663bf814170f3d03e872a3 | refs/heads/master | 2022-03-18T11:31:15.571758 | 2019-12-12T22:12:21 | 2019-12-12T22:12:21 | 209,085,757 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,790 | cpp | #include <ctype.h>
#include <PxPhysicsAPI.h>
#include <iostream>
#include <vector>
#include "core.hpp"
#include "RenderUtils.hpp"
#include "callbacks.hpp"
#include "Particle.h"
#include "ParticleSystem.h"
#include "ParticleForceRegistry.h"
#include "ParticleForceGenerator.h"
#include "ParticleGravity.h"
#include "ParticleExplosion.h"
#include "ParticleWind.h"
#include "ParticleAnchoredSpring.h"
#include "ParticleSpring.h"
#include "ParticleBuoyancy.h"
#include "ParticleCable.h"
#include "ParticleCollisionRegistry.h"
#include "ParticleRod.h"
#include "ParticleSystemRigid.h"
#include "Bolos.h"
#include "Barra.h"
using namespace physx;
PxDefaultAllocator gAllocator;
PxDefaultErrorCallback gErrorCallback;
PxFoundation* gFoundation = NULL;
PxPhysics* gPhysics = NULL;
PxMaterial* gMaterial = NULL;
PxPvd* gPvd = NULL;
PxDefaultCpuDispatcher* gDispatcher = NULL;
PxScene* gScene = NULL;
ContactReportCallback gContactReportCallback;
//Scene 2
ParticleSystemRigid* fuenteI;
ParticleSystemRigid* fuenteD;
ParticleSystemRigid* fuenteC;
//Scene 3
enum Fuerzas { Wind1, Wind2, Wind3 };
std::vector<ParticleForceGenerator*> fuerzas;
//Scene 4
ParticleForceRegistry registry;
ParticleRigid* muelle4;
//Scene 5
ParticleCable* cable;
ParticleCable* cable1;
ParticleCable* cable2;
ParticleContact* contacto1;
ParticleContact* contacto2;
ParticleContact* contacto3;
ParticleRigid* baseCuerdas;
ParticleRigid* rompeBolas;
ParticleRigid* rompeBolas1;
ParticleRigid* rompeBolas2;
//Global
Bolos* b;
Barra* barra1;
PxTransform* t;
PxShape* pShape;
std::vector<PxRigidStatic*> particleRigid;
ParticleRigid* bola = nullptr;
bool complete = true;
float time = 0;
int level_ = 0;
void deleteScene5() {
for each (PxRigidStatic * var in particleRigid)
{
var->release();
}
particleRigid.clear();
delete b;
delete barra1;
delete contacto3;
delete contacto2;
delete contacto1;
delete baseCuerdas;
delete rompeBolas;
delete rompeBolas1;
delete rompeBolas2;
}
void Scene5Update(float t) {
cable->addContact(contacto1, 0);
contacto1->resolve(t);
cable1->addContact(contacto2, 0);
contacto2->resolve(t);
cable2->addContact(contacto3, 0);
contacto3->resolve(t);
}
void Scene5() {
t = new PxTransform(Vector3(0.0, 0.0, 150.0));
pShape = CreateShape(PxBoxGeometry(25, 1, 200));
PxRigidStatic* particleRigidAux = gPhysics->createRigidStatic(*t);
particleRigidAux->attachShape(*pShape);
gScene->addActor(*particleRigidAux);
particleRigid.push_back(particleRigidAux);
t = new PxTransform(Vector3(0.0, 95.0f, 40.0));
pShape = CreateShape(PxBoxGeometry(25, 1, 25));
particleRigidAux = gPhysics->createRigidStatic(*t);
particleRigidAux->attachShape(*pShape);
gScene->addActor(*particleRigidAux);
particleRigid.push_back(particleRigidAux);
barra1 = new Barra();
b = new Bolos(Vector3(0.0, 5.0, 0.0), 5, gPhysics, gScene);
baseCuerdas = new ParticleRigid(gPhysics, gScene, 10.0f, 1.0f, 10.0f, Vector3(0.0f, 100.0f, 40.0f), 86400.0f);
rompeBolas = new ParticleRigid(gPhysics, gScene, 5.0f, Vector3(-5.0f, 10.0f, 35.0f), 86400.0f);
rompeBolas1 = new ParticleRigid(gPhysics, gScene, 5.0f, Vector3(0.0f, 10.0f, 40.0f), 86400.0f);
rompeBolas2 = new ParticleRigid(gPhysics, gScene, 5.0f, Vector3(5.0f, 10.0f, 35.0f), 86400.0f);
contacto1 = new ParticleContact(rompeBolas, baseCuerdas);
contacto2 = new ParticleContact(rompeBolas1, baseCuerdas);
contacto3 = new ParticleContact(rompeBolas2, baseCuerdas);
cable = new ParticleCable(rompeBolas, baseCuerdas, 80);
cable1 = new ParticleCable(rompeBolas1, baseCuerdas, 80);
cable2 = new ParticleCable(rompeBolas2, baseCuerdas, 80);
//bola = new ParticleRigid(gPhysics, gScene, 5, Vector3(0.0, 0.0, 120.0));
}
void deleteScene4() {
for each (PxRigidStatic * var in particleRigid)
{
var->release();
}
particleRigid.clear();
registry.clear();
delete fuerzas[0];
delete muelle4;
fuerzas.clear();
delete barra1;
delete b;
}
void Scene4Update(float t) {
muelle4->update(t);
registry.updateForces(t);
}
void Scene4() {
t = new PxTransform(Vector3(0.0, -14.9, -25.0));
pShape = CreateShape(PxBoxGeometry(25, 15, 75));
PxRigidStatic* particleRigidAux = gPhysics->createRigidStatic(*t);
particleRigidAux->attachShape(*pShape);
gScene->addActor(*particleRigidAux);
particleRigid.push_back(particleRigidAux);
t = new PxTransform(Vector3(0.0, -14.9, 225.0));
pShape = CreateShape(PxBoxGeometry(25, 15, 75));
particleRigidAux = gPhysics->createRigidStatic(*t);
particleRigidAux->attachShape(*pShape);
gScene->addActor(*particleRigidAux);
particleRigid.push_back(particleRigidAux);
t = new PxTransform(Vector3(26.0, 0.0, 100.0));
pShape = CreateShape(PxBoxGeometry(1, 200, 75));
particleRigidAux = gPhysics->createRigidStatic(*t);
particleRigidAux->attachShape(*pShape);
gScene->addActor(*particleRigidAux);
particleRigid.push_back(particleRigidAux);
t = new PxTransform(Vector3(-26.0, 0.0, 100.0));
pShape = CreateShape(PxBoxGeometry(1, 200, 75));
particleRigidAux = gPhysics->createRigidStatic(*t);
particleRigidAux->attachShape(*pShape);
gScene->addActor(*particleRigidAux);
particleRigid.push_back(particleRigidAux);
PxQuat g = PxQuat(3.14 / 9.0, Vector3(1.0, 0.0, 0.0));
t = new PxTransform(Vector3(0.0, -5.0, 165.0), g);
pShape = CreateShape(PxBoxGeometry(25, 1, 20));
particleRigidAux = gPhysics->createRigidStatic(*t);
particleRigidAux->attachShape(*pShape);
gScene->addActor(*particleRigidAux);
particleRigid.push_back(particleRigidAux);
barra1 = new Barra();
b = new Bolos(Vector3(0.0, 5.0, 0.0), 5, gPhysics, gScene);
muelle4 = new ParticleRigid(gPhysics, gScene, 24.9f, 9.9f, 25.0f, Vector3(0.0, 0.0, 100.0), 86400.0f);
fuerzas.push_back(new ParticleBuoyancy(-10.0f, 90990.1f, 20.0f));
registry.add(muelle4, fuerzas[0]);
}
void deleteScene3() {
for each (PxRigidStatic * var in particleRigid)
{
var->release();
}
particleRigid.clear();
delete b;
delete barra1;
for each (ParticleWind * var in fuerzas)
{
delete var;
}
fuerzas.clear();
registry.clear();
}
void Scene3Update(float t) {
registry.updateForces(t);
}
void Scene3() {
fuerzas.push_back(new ParticleWind(Vector3(-25, 0, 80), 15));
fuerzas.push_back(new ParticleWind(Vector3(25, 0, 80), 15));
fuerzas.push_back(new ParticleWind(Vector3(0, -7, 140), 20));
//fuerzas[Explosion]->setInstantForce(true);
t = new PxTransform(Vector3(0.0, 0.0, -25.0));
pShape = CreateShape(PxBoxGeometry(25, 1, 75));
PxRigidStatic* particleRigidAux = gPhysics->createRigidStatic(*t);
particleRigidAux->attachShape(*pShape);
gScene->addActor(*particleRigidAux);
particleRigid.push_back(particleRigidAux);
t = new PxTransform(Vector3(0.0, 0.0, 225.0));
pShape = CreateShape(PxBoxGeometry(25, 1, 75));
particleRigidAux = gPhysics->createRigidStatic(*t);
particleRigidAux->attachShape(*pShape);
gScene->addActor(*particleRigidAux);
particleRigid.push_back(particleRigidAux);
t = new PxTransform(Vector3(20.0, 0.0, 100.0));
pShape = CreateShape(PxBoxGeometry(5, 1, 70));
particleRigidAux = gPhysics->createRigidStatic(*t);
particleRigidAux->attachShape(*pShape);
gScene->addActor(*particleRigidAux);
particleRigid.push_back(particleRigidAux);
t = new PxTransform(Vector3(-20.0, 0.0, 100.0));
pShape = CreateShape(PxBoxGeometry(5, 1, 70));
particleRigidAux = gPhysics->createRigidStatic(*t);
particleRigidAux->attachShape(*pShape);
gScene->addActor(*particleRigidAux);
particleRigid.push_back(particleRigidAux);
barra1 = new Barra();
b = new Bolos(Vector3(0.0, 5.0, 0.0), 5, gPhysics, gScene);
registry.add(bola, fuerzas[0]);
registry.add(bola, fuerzas[1]);
registry.add(bola, fuerzas[2]);
}
void deleteScene2() {
for each (PxRigidStatic * var in particleRigid)
{
var->release();
}
particleRigid.clear();
delete b;
delete barra1;
delete fuenteC;
delete fuenteD;
delete fuenteI;
}
void Scene2Update(float t) {
fuenteI->update(t);
fuenteD->update(t);
fuenteC->update(t);
}
void Scene2() {
t = new PxTransform(Vector3(0.0, 0.0, -25.0));
pShape = CreateShape(PxBoxGeometry(25, 1, 75));
PxRigidStatic* particleRigidAux = gPhysics->createRigidStatic(*t);
particleRigidAux->attachShape(*pShape);
gScene->addActor(*particleRigidAux);
particleRigid.push_back(particleRigidAux);
t = new PxTransform(Vector3(0.0, 0.0, 225.0));
pShape = CreateShape(PxBoxGeometry(25, 1, 75));
particleRigidAux = gPhysics->createRigidStatic(*t);
particleRigidAux->attachShape(*pShape);
gScene->addActor(*particleRigidAux);
particleRigid.push_back(particleRigidAux);
PxQuat g = PxQuat(3.14 / 9.0, Vector3(1.0, 0.0, 0.0));
t = new PxTransform(Vector3(0.0, -5.0, 160.0), g);
pShape = CreateShape(PxBoxGeometry(25, 1, 20));
particleRigidAux = gPhysics->createRigidStatic(*t);
particleRigidAux->attachShape(*pShape);
gScene->addActor(*particleRigidAux);
particleRigid.push_back(particleRigidAux);
barra1 = new Barra();
fuenteI = new ParticleSystemRigid(gPhysics, gScene, Vector3(7.0, 30.0, 100.0), 1.0f);
fuenteC = new ParticleSystemRigid(gPhysics, gScene, Vector3(0.0, 30.0, 100.0), 1.0f);
fuenteD = new ParticleSystemRigid(gPhysics, gScene, Vector3(-7.0, 30.0, 100.0), 1.0f);
b = new Bolos(Vector3(0.0, 5.0, 0.0), 5, gPhysics, gScene);
}
void deleteScene1() {
for each (PxRigidStatic * var in particleRigid)
{
var->release();
}
particleRigid.clear();
delete b;
delete barra1;
}
void Scene1() {
t = new PxTransform(Vector3(0.0, 0.0, 150.0));
pShape = CreateShape(PxBoxGeometry(25, 1, 200));
PxRigidStatic* particleRigidAux = gPhysics->createRigidStatic(*t);
particleRigidAux->attachShape(*pShape);
gScene->addActor(*particleRigidAux);
particleRigid.push_back(particleRigidAux);
barra1 = new Barra();
b = new Bolos(Vector3(0.0, 5.0, 0.0), 5, gPhysics, gScene);
if (bola == nullptr)
bola = new ParticleRigid(gPhysics, gScene, 5, Vector3(0.0, 0.0, 120.0));
}
// Initialize physics engine
void initPhysics(bool interactive)
{
PX_UNUSED(interactive);
gFoundation = PxCreateFoundation(PX_FOUNDATION_VERSION, gAllocator, gErrorCallback);
gPvd = PxCreatePvd(*gFoundation);
PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10);
gPvd->connect(*transport, PxPvdInstrumentationFlag::eALL);
gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(), true, gPvd);
gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f);
// For Solid Rigids +++++++++++++++++++++++++++++++++++++
PxSceneDesc sceneDesc(gPhysics->getTolerancesScale());
sceneDesc.gravity = PxVec3(0.0f, -98.0f, 0.0f);
gDispatcher = PxDefaultCpuDispatcherCreate(2);
sceneDesc.cpuDispatcher = gDispatcher;
sceneDesc.filterShader = contactReportFilterShader;
sceneDesc.simulationEventCallback = &gContactReportCallback;
gScene = gPhysics->createScene(sceneDesc);
// ------------------------------------------------------
}
// Function to configure what happens in each step of physics
// interactive: true if the game is rendering, false if it offline
// t: time passed since last call in milliseconds
void stepPhysics(bool interactive, double t)
{
PX_UNUSED(interactive);
//Crear y borrar cada escena segun toque
if (complete) {
switch (level_)
{
case 0:
Scene1();
break;
case 1:
deleteScene1();
Scene2();
break;
case 2:
deleteScene2();
Scene3();
break;
case 3:
deleteScene3();
Scene4();
break;
case 4:
deleteScene4();
Scene5();
break;
default:
break;
}
complete = false;
}
//Update de cada scene
switch (level_)
{
case 1:
Scene2Update(t);
break;
case 2:
Scene3Update(t);
break;
case 3:
Scene4Update(t);
break;
case 4:
Scene5Update(t);
break;
default:
break;
}
//Updates principales
bola->update(t);
barra1->update(t);
b->update(t);
//Siguiente nivel
if (b->caidos() == b->numBolos()) {
time += t;
if (time > 3.0f) {
complete = true;
level_++;
if (level_ == 5) {
deleteScene5();
}
level_ = level_ % 5;
time = 0;
}
}
gScene->simulate(t);
gScene->fetchResults(true);
}
// Function to clean data
// Add custom code to the begining of the function
void cleanupPhysics(bool interactive)
{
PX_UNUSED(interactive);
// Rigid Body ++++++++++++++++++++++++++++++++++++++++++
gScene->release();
gDispatcher->release();
delete bola;
switch (level_)
{
case 0:
deleteScene1();
break;
case 1:
deleteScene2();
break;
case 2:
deleteScene3();
break;
case 3:
deleteScene4();
break;
case 4:
deleteScene5();
break;
default:
break;
}
// -----------------------------------------------------
gPhysics->release();
PxPvdTransport* transport = gPvd->getTransport();
gPvd->release();
transport->release();
gFoundation->release();
}
// Function called when a key is pressed
void keyPress(unsigned char key, const PxTransform& camera)
{
PX_UNUSED(camera);
switch (toupper(key))
{
case 'Q':
{
level_++;
if (level_ == 5) {
deleteScene5();
}
level_ = level_ % 5;
complete = true;
break;
}
case ' ': {
if (level_ == 2) {
registry.clear();
delete bola;
bola = new ParticleRigid(gPhysics, gScene, 5, barra1->getPos());
registry.add(bola, fuerzas[0]);
registry.add(bola, fuerzas[1]);
registry.add(bola, fuerzas[2]);
}
else {
delete bola;
bola = new ParticleRigid(gPhysics, gScene, 5, barra1->getPos());
}
bola->addForce(Vector3(0.0, 0.0, -1.0), 99999, PxForceMode::eIMPULSE);
break;
}
default:
break;
}
}
void onCollision(physx::PxActor* actor1, physx::PxActor* actor2)
{
PX_UNUSED(actor1);
PX_UNUSED(actor2);
}
int main(int, const char* const*)
{
#ifndef OFFLINE_EXECUTION
extern void renderLoop();
renderLoop();
#else
static const PxU32 frameCount = 100;
initPhysics(false);
for (PxU32 i = 0; i < frameCount; i++)
stepPhysics(false);
cleanupPhysics(false);
#endif
return 0;
} | [
"jomart17@ucm.es"
] | jomart17@ucm.es |
014110b2478e330113d121bf7acb954a22429273 | 84d078cfe9a7676abc9f1f41d7835e9bc2f7722b | /piscine_cpp/d00/ex02/Account.class.cpp | 12b93f21422186ed027f2e0e521ff3e4a802110c | [] | no_license | aradiuk/CPP | 0b58a823317c05ca8941998481da61700752d52d | 1414413ae524c185908b30c4a9ddd77cf791383b | refs/heads/master | 2021-07-19T21:08:34.762887 | 2021-02-16T10:18:15 | 2021-02-16T10:18:15 | 99,698,590 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,975 | cpp | #include "Account.class.hpp"
#include <iostream>
// CHECK THE ORDER
// OF DESTRUCTORS
// LAST 8 ROWS OF
// THE OUTPUT
int Account::_nbAccounts = 0;
int Account::_totalAmount = 0;
int Account::_totalNbDeposits = 0;
int Account::_totalNbWithdrawals = 0;
int Account::getNbAccounts()
{
return _nbAccounts;
}
int Account::getTotalAmount()
{
return _totalAmount;
}
int Account::getNbDeposits()
{
return _totalNbDeposits;
}
int Account::getNbWithdrawals()
{
return _totalNbWithdrawals;
}
Account::Account(int initial_deposit)
{
this->_amount = initial_deposit;
this->_totalAmount += _amount;
this->_nbDeposits = 0;
this->_nbWithdrawals = 0;
this->_accountIndex = this->_nbAccounts;
this->_nbAccounts++;
_displayTimestamp();
std::cout << "index:" << _accountIndex << ";";
std::cout << "amount:" << _amount << ";created\n";
}
Account::~Account()
{
Account::_displayTimestamp();
std::cout << "index:" << this->_accountIndex << ";";
std::cout << "amount:" << this->_amount << ";closed\n";
}
void Account::_displayTimestamp()
{
char str[19];
time_t time = time_t(NULL);
if (strftime(str, sizeof(str), "[%Y%d%m_%H%M%S] ", localtime(&time)))
std::cout << str;
}
void Account::displayAccountsInfos()
{
_displayTimestamp();
std::cout << "accounts:" << getNbAccounts() << ";";
std::cout << "total:" << getTotalAmount() << ";";
std::cout << "deposits:" << getNbDeposits() << ";";
std::cout << "withdrawals:" << getNbWithdrawals() << "\n";
}
void Account::displayStatus() const
{
_displayTimestamp();
std::cout << "index:" << this->_accountIndex << ";";
std::cout << "amount:" << this->_amount << ";";
std::cout << "deposits:" << this->_nbDeposits << ";";
std::cout << "withdrawals:" << this->_nbWithdrawals;
std::cout << std::endl;
}
void Account::makeDeposit(int deposit)
{
int p_amount = this->_amount;
this->_amount += deposit;
this->_nbDeposits++;
Account::_totalAmount += deposit;
Account::_totalNbDeposits++;
_displayTimestamp();
std::cout << "index:" << this->_accountIndex << ";";
std::cout << "p_amount:" << p_amount << ";";
std::cout << "deposit:" << deposit << ";";
std::cout << "amount:" << this->_amount << ";";
std::cout << "nb_deposits:" << this->_nbDeposits;
std::cout << std::endl;
}
bool Account::makeWithdrawal(int withdrawal)
{
int p_amount = this->_amount;
bool allow = withdrawal <= this->_amount;
_displayTimestamp();
std::cout << "index:" << this->_accountIndex << ";";
std::cout << "p_amount:" << p_amount << ";";
std::cout << "withdrawal:";
if (allow)
{
this->_amount -= withdrawal;
this->_nbWithdrawals++;
Account::_totalAmount -= withdrawal;
Account::_totalNbWithdrawals++;
std::cout << withdrawal << ";";
std::cout << "amount:" << this->_amount << ";";
std::cout << "nb_withdrawals:" << this->_nbWithdrawals;
std::cout << std::endl;
return (true);
}
else
{
std::cout << "refused\n";
return (false);
}
}
int Account::checkAmount() const
{
return (this->_amount);
}
| [
"hartright@bitbucket.org"
] | hartright@bitbucket.org |
f3203921cadf78d4fff5b1970ba513caa28088f2 | 86db324c6a039369ef9d904defd9a15c944c429c | /thrift/lib/cpp2/test/FlagsTest.cpp | be64a14bd8d7e9c9e60b117a95bb49dd478c68ab | [
"Apache-2.0"
] | permissive | curoky/fbthrift | 1eb3cecfee5f72748a5787e792c63276f7734f76 | 199ca4b1807a705fc55e6fa099c39b7e90ef03e0 | refs/heads/master | 2023-04-29T21:19:41.027102 | 2023-04-25T16:23:11 | 2023-04-25T16:23:11 | 242,927,696 | 0 | 0 | Apache-2.0 | 2020-02-25T06:31:35 | 2020-02-25T06:31:34 | null | UTF-8 | C++ | false | false | 9,038 | cpp | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* 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 <exception>
#include <folly/CPortability.h>
#include <folly/MapUtil.h>
#include <folly/portability/GTest.h>
#include <thrift/lib/cpp2/Flags.h>
#include <thrift/lib/cpp2/PluggableFunction.h>
#include <folly/experimental/observer/SimpleObservable.h>
THRIFT_FLAG_DEFINE_bool(test_flag_bool, true);
THRIFT_FLAG_DEFINE_int64(test_flag_int, 42);
THRIFT_FLAG_DECLARE_bool(test_flag_bool_external);
THRIFT_FLAG_DECLARE_int64(test_flag_int_external);
class TestFlagsBackend : public apache::thrift::detail::FlagsBackend {
public:
folly::observer::Observer<folly::Optional<bool>> getFlagObserverBool(
folly::StringPiece name) override {
return getFlagObservableBool(name).getObserver();
}
folly::observer::Observer<folly::Optional<int64_t>> getFlagObserverInt64(
folly::StringPiece name) override {
return getFlagObservableInt64(name).getObserver();
}
folly::observer::SimpleObservable<folly::Optional<bool>>&
getFlagObservableBool(folly::StringPiece name) {
if (auto observablePtr = folly::get_ptr(boolObservables_, name.str())) {
return **observablePtr;
}
return *(
boolObservables_[name.str()] = std::make_unique<
folly::observer::SimpleObservable<folly::Optional<bool>>>(
folly::Optional<bool>{}));
}
folly::observer::SimpleObservable<folly::Optional<int64_t>>&
getFlagObservableInt64(folly::StringPiece name) {
if (auto observablePtr = folly::get_ptr(int64Observables_, name.str())) {
return **observablePtr;
}
return *(
int64Observables_[name.str()] = std::make_unique<
folly::observer::SimpleObservable<folly::Optional<int64_t>>>(
folly::Optional<int64_t>{}));
}
private:
std::unordered_map<
std::string,
std::unique_ptr<folly::observer::SimpleObservable<folly::Optional<bool>>>>
boolObservables_;
std::unordered_map<
std::string,
std::unique_ptr<
folly::observer::SimpleObservable<folly::Optional<int64_t>>>>
int64Observables_;
};
namespace {
TestFlagsBackend* testBackendPtr;
bool useDummyBackend{false};
} // namespace
namespace apache::thrift::detail {
THRIFT_PLUGGABLE_FUNC_SET(
std::unique_ptr<apache::thrift::detail::FlagsBackend>, createFlagsBackend) {
if (useDummyBackend) {
return {};
}
auto testBackend = std::make_unique<TestFlagsBackend>();
testBackendPtr = testBackend.get();
return testBackend;
}
} // namespace apache::thrift::detail
TEST(Flags, Get) {
EXPECT_EQ(true, THRIFT_FLAG(test_flag_bool));
EXPECT_EQ(42, THRIFT_FLAG(test_flag_int));
EXPECT_EQ(true, THRIFT_FLAG(test_flag_bool_external));
EXPECT_EQ(42, THRIFT_FLAG(test_flag_int_external));
testBackendPtr->getFlagObservableBool("test_flag_bool").setValue(false);
testBackendPtr->getFlagObservableInt64("test_flag_int").setValue(41);
testBackendPtr->getFlagObservableBool("test_flag_bool_external")
.setValue(false);
testBackendPtr->getFlagObservableInt64("test_flag_int_external").setValue(41);
folly::observer_detail::ObserverManager::waitForAllUpdates();
EXPECT_EQ(false, THRIFT_FLAG(test_flag_bool));
EXPECT_EQ(41, THRIFT_FLAG(test_flag_int));
EXPECT_EQ(false, THRIFT_FLAG(test_flag_bool_external));
EXPECT_EQ(41, THRIFT_FLAG(test_flag_int_external));
}
TEST(Flags, Observe) {
auto test_flag_bool_observer = THRIFT_FLAG_OBSERVE(test_flag_bool);
auto test_flag_int_observer = THRIFT_FLAG_OBSERVE(test_flag_int);
auto test_flag_bool_external_observer =
THRIFT_FLAG_OBSERVE(test_flag_bool_external);
auto test_flag_int_extenal_observer =
THRIFT_FLAG_OBSERVE(test_flag_int_external);
EXPECT_EQ(true, **test_flag_bool_observer);
EXPECT_EQ(42, **test_flag_int_observer);
EXPECT_EQ(true, **test_flag_bool_external_observer);
EXPECT_EQ(42, **test_flag_int_extenal_observer);
testBackendPtr->getFlagObservableBool("test_flag_bool").setValue(false);
testBackendPtr->getFlagObservableInt64("test_flag_int").setValue(41);
testBackendPtr->getFlagObservableBool("test_flag_bool_external")
.setValue(false);
testBackendPtr->getFlagObservableInt64("test_flag_int_external").setValue(41);
folly::observer_detail::ObserverManager::waitForAllUpdates();
EXPECT_EQ(false, **test_flag_bool_observer);
EXPECT_EQ(41, **test_flag_int_observer);
EXPECT_EQ(false, **test_flag_bool_external_observer);
EXPECT_EQ(41, **test_flag_int_extenal_observer);
}
TEST(Flags, NoBackend) {
useDummyBackend = true;
EXPECT_EQ(true, THRIFT_FLAG(test_flag_bool));
EXPECT_EQ(42, THRIFT_FLAG(test_flag_int));
EXPECT_EQ(true, THRIFT_FLAG(test_flag_bool_external));
EXPECT_EQ(42, THRIFT_FLAG(test_flag_int_external));
}
TEST(Flags, MockGet) {
EXPECT_EQ(true, THRIFT_FLAG(test_flag_bool));
EXPECT_EQ(42, THRIFT_FLAG(test_flag_int));
EXPECT_EQ(true, THRIFT_FLAG(test_flag_bool_external));
EXPECT_EQ(42, THRIFT_FLAG(test_flag_int_external));
THRIFT_FLAG_SET_MOCK(test_flag_bool, false);
THRIFT_FLAG_SET_MOCK(test_flag_int, 41);
THRIFT_FLAG_SET_MOCK(test_flag_bool_external, false);
THRIFT_FLAG_SET_MOCK(test_flag_int_external, 41);
folly::observer_detail::ObserverManager::waitForAllUpdates();
EXPECT_EQ(false, THRIFT_FLAG(test_flag_bool));
EXPECT_EQ(41, THRIFT_FLAG(test_flag_int));
EXPECT_EQ(false, THRIFT_FLAG(test_flag_bool_external));
EXPECT_EQ(41, THRIFT_FLAG(test_flag_int_external));
THRIFT_FLAG_SET_MOCK(test_flag_bool, true);
THRIFT_FLAG_SET_MOCK(test_flag_int, 9);
THRIFT_FLAG_SET_MOCK(test_flag_bool_external, true);
THRIFT_FLAG_SET_MOCK(test_flag_int_external, 61);
folly::observer_detail::ObserverManager::waitForAllUpdates();
EXPECT_EQ(true, THRIFT_FLAG(test_flag_bool));
EXPECT_EQ(9, THRIFT_FLAG(test_flag_int));
EXPECT_EQ(true, THRIFT_FLAG(test_flag_bool_external));
EXPECT_EQ(61, THRIFT_FLAG(test_flag_int_external));
}
TEST(Flags, MockObserve) {
EXPECT_EQ(true, THRIFT_FLAG(test_flag_bool));
EXPECT_EQ(42, THRIFT_FLAG(test_flag_int));
EXPECT_EQ(true, THRIFT_FLAG(test_flag_bool_external));
EXPECT_EQ(42, THRIFT_FLAG(test_flag_int_external));
auto test_flag_bool_observer = THRIFT_FLAG_OBSERVE(test_flag_bool);
auto test_flag_int_observer = THRIFT_FLAG_OBSERVE(test_flag_int);
auto test_flag_bool_external_observer =
THRIFT_FLAG_OBSERVE(test_flag_bool_external);
auto test_flag_int_extenal_observer =
THRIFT_FLAG_OBSERVE(test_flag_int_external);
THRIFT_FLAG_SET_MOCK(test_flag_bool, false);
THRIFT_FLAG_SET_MOCK(test_flag_int, 41);
THRIFT_FLAG_SET_MOCK(test_flag_bool_external, false);
THRIFT_FLAG_SET_MOCK(test_flag_int_external, 41);
folly::observer_detail::ObserverManager::waitForAllUpdates();
EXPECT_EQ(false, **test_flag_bool_observer);
EXPECT_EQ(41, **test_flag_int_observer);
EXPECT_EQ(false, **test_flag_bool_external_observer);
EXPECT_EQ(41, **test_flag_int_extenal_observer);
THRIFT_FLAG_SET_MOCK(test_flag_bool, true);
THRIFT_FLAG_SET_MOCK(test_flag_int, 9);
THRIFT_FLAG_SET_MOCK(test_flag_bool_external, true);
THRIFT_FLAG_SET_MOCK(test_flag_int_external, 61);
folly::observer_detail::ObserverManager::waitForAllUpdates();
EXPECT_EQ(true, **test_flag_bool_observer);
EXPECT_EQ(9, **test_flag_int_observer);
EXPECT_EQ(true, **test_flag_bool_external_observer);
EXPECT_EQ(61, **test_flag_int_extenal_observer);
}
TEST(Flags, MockValuePreferred) {
EXPECT_EQ(true, THRIFT_FLAG(test_flag_bool));
EXPECT_EQ(42, THRIFT_FLAG(test_flag_int));
EXPECT_EQ(true, THRIFT_FLAG(test_flag_bool_external));
EXPECT_EQ(42, THRIFT_FLAG(test_flag_int_external));
THRIFT_FLAG_SET_MOCK(test_flag_bool, true);
THRIFT_FLAG_SET_MOCK(test_flag_int, 73);
THRIFT_FLAG_SET_MOCK(test_flag_bool_external, true);
THRIFT_FLAG_SET_MOCK(test_flag_int_external, 49);
folly::observer_detail::ObserverManager::waitForAllUpdates();
testBackendPtr->getFlagObservableBool("test_flag_bool").setValue(false);
testBackendPtr->getFlagObservableInt64("test_flag_int").setValue(41);
testBackendPtr->getFlagObservableBool("test_flag_bool_external")
.setValue(false);
testBackendPtr->getFlagObservableInt64("test_flag_int_external").setValue(41);
folly::observer_detail::ObserverManager::waitForAllUpdates();
EXPECT_EQ(true, THRIFT_FLAG(test_flag_bool));
EXPECT_EQ(73, THRIFT_FLAG(test_flag_int));
EXPECT_EQ(true, THRIFT_FLAG(test_flag_bool_external));
EXPECT_EQ(49, THRIFT_FLAG(test_flag_int_external));
}
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
f7683e4a33d2ce2c6339ed8a1e953cc5494809fb | a2853414268447c37d448570ee648e8d45ed706c | /core/Data.hpp | 058d69dfa7f5a744a925958cbd3c1c593c66465c | [] | no_license | acherkaoui/HTOP | 5f61057a6a478925d32ebea82e0e99f6fe0f6afa | 3577c1ea7aebba85cdd7364229ca6c5a69318589 | refs/heads/master | 2021-04-09T14:11:22.022810 | 2018-03-16T23:03:12 | 2018-03-16T23:03:12 | 125,578,109 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 622 | hpp | /*
** EPITECH PROJECT, 2021
** cpp_rush3
** File description:
** Created by abderrahim.cherkaoui@epitech.eu,
*/
#ifndef CPP_RUSH3_DATA_HPP
#define CPP_RUSH3_DATA_HPP
#include "../modules/Clock.hpp"
#include "../modules/Network.hpp"
#include "../modules/OperatingSystem.hpp"
#include "../modules/Processes.hpp"
#include "../modules/RAM.hpp"
#include "../modules/User.hpp"
#include "../modules/CPU.hpp"
class Data
{
public:
Data() = default;
virtual ~Data() = default;
public:
Cpu cpu;
Clock clock;
Network network;
OperatingSystem os;
Processes processes;
RAM ram;
User user;
};
#endif //CPP_RUSH3_DATA_HPP
| [
"abderrahim.cherkaoui@epitech.eu"
] | abderrahim.cherkaoui@epitech.eu |
cbfcb606d5f189a8cf61b489d266329447a4fa9d | d522a93c6d573c1b2f8b559d8a88269bad4130d3 | /shellcode/loader/loader.cpp | 2d34ede6a93edbf5ad114acd8d763c30d8e3f0ce | [] | no_license | floomby/framework | d7699947027bb440f82e033655f03f51335c631e | d08e5f54381393acb08c85317caaf841c574c35d | refs/heads/master | 2016-09-06T17:28:16.754564 | 2014-06-07T01:44:07 | 2014-06-07T01:44:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 306 | cpp | #include <cstdio>
#include <cstdint>
#include "reflect/reflect.h"
int main(int argc, char *argv[])
{
uint8_t *it = (uint8_t *)&ReflectiveLoad;
printf("print \"");
for(size_t i = 0; i < ReflectiveLoad_size; ++i){
printf("\\x%02x", it[i]);
}
puts("\"");
return 0;
}
| [
"caboodlennm@gmail.com"
] | caboodlennm@gmail.com |
5b336b02c651da3ae7f044af55b5dd6371291715 | 33aa51db560b5b1f0af1e442f2cf11bee538e9fc | /VipClient/UpdateIpDlg.h | 1cc82121260d176145309d4989b7e37d937a656c | [] | no_license | hanggithub/vipshell | 529f7652d5ec8480dd679f0e79cfc7ef589020c6 | a34593d7a6865fa06d098137c04e4cbab0050065 | refs/heads/master | 2021-01-22T21:32:50.236517 | 2014-11-16T08:27:06 | 2014-11-16T08:27:06 | 26,708,064 | 4 | 3 | null | null | null | null | GB18030 | C++ | false | false | 618 | h | #pragma once
// CUpdateIpDlg 对话框
class CUpdateIpDlg : public CDialog
{
DECLARE_DYNAMIC(CUpdateIpDlg)
public:
CUpdateIpDlg(CWnd* pParent = NULL); // 标准构造函数
virtual ~CUpdateIpDlg();
// 对话框数据
enum { IDD = IDD_DIALOG_UPDATEIP };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnBnClickedOk();
CString m_strFtpServer;
DWORD m_dwPortFtp;
DWORD m_dwPortMy;
CString m_strMyIp;
CString m_strFile;
CString m_strUser;
CString m_strPass;
virtual BOOL OnInitDialog();
};
| [
"ignccvv@163.com"
] | ignccvv@163.com |
68c48eb9c3083acb80a04939595049812c31dcf1 | 969a3f74a957b7fa3685ac5ae5f94ac225af9522 | /Rendering/OpenGL2/vtkOpenGLES30PolyDataMapper2D.h | 49e1411fb205556b4e466bb573cabaac34e81028 | [
"BSD-3-Clause"
] | permissive | gview/VTK | 61adbce5b78e0fdf8069e2384c0fc1899a723df5 | 17c664f1c3bdb84997aa2c9bfdf51ba77171672e | refs/heads/master | 2023-06-01T11:56:23.857210 | 2023-05-30T04:01:23 | 2023-05-30T04:01:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,929 | h | /*=========================================================================
Program: Visualization Toolkit
Module: vtkOpenGLES30PolyDataMapper2D.h
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
/**
* @class vtkOpenGLES30PolyDataMapper2D
* @brief 2D PolyData support for OpenGL ES 3.0
*
* This mapper provides a GLES 3.0 compatible implementation of the 2D OpenGL
* polydata mapper. Since GLES30 3.0 lacks geometry shaders and texture buffers,
* `vtkOpenGLPolyDataMapper2D` will not function
* correctly when VTK is configured with `VTK_OPENGL_USE_GLES=ON` since that mapper
* works with GLES30 >= 3.2 or desktop GL 3.2 contexts.
*
* @note This class replaces the default OpenGL factory override for `vtkOpenGLPolyDataMapper2D`
* when VTK targets GLES 3.0 contexts with `VTK_OPENGL_USE_GLES=ON`.
*
* @sa
* vtkPolyDataMapper2D, vtkOpenGLPolyDataMapper2D
*/
#ifndef vtkOpenGLES30PolyDataMapper2D_h
#define vtkOpenGLES30PolyDataMapper2D_h
#include "vtkOpenGLPolyDataMapper2D.h"
#include "vtkOpenGLVertexBufferObjectGroup.h" // for ivar
#include "vtkRenderingOpenGL2Module.h" // for export macro
VTK_ABI_NAMESPACE_BEGIN
class VTKRENDERINGOPENGL2_EXPORT vtkOpenGLES30PolyDataMapper2D : public vtkOpenGLPolyDataMapper2D
{
public:
vtkTypeMacro(vtkOpenGLES30PolyDataMapper2D, vtkOpenGLPolyDataMapper2D);
static vtkOpenGLES30PolyDataMapper2D* New();
void PrintSelf(ostream& os, vtkIndent indent) override;
enum PrimitiveTypes
{
PrimitiveStart = 0,
PrimitivePoints = 0,
PrimitiveLines,
PrimitiveTris,
PrimitiveTriStrips,
PrimitiveEnd
};
/**
* Actually draw the poly data.
*/
void RenderOverlay(vtkViewport* viewport, vtkActor2D* actor) override;
/**
* Release any graphics resources that are being consumed by this mapper.
* The parameter window could be used to determine which graphic
* resources to release.
*/
void ReleaseGraphicsResources(vtkWindow*) override;
protected:
vtkOpenGLES30PolyDataMapper2D();
~vtkOpenGLES30PolyDataMapper2D() override;
/**
* Build the shader source code
*/
void BuildShaders(std::string& VertexCode, std::string& fragmentCode, std::string& geometryCode,
vtkViewport* ren, vtkActor2D* act) override;
/**
* In GLES 3.0, point size is set from the vertex shader.
*/
void ReplaceShaderPointSize(std::string& VSSource, vtkViewport* ren, vtkActor2D* act);
/**
* GLES 3.0 does not support wide lines (width > 1). Shader computations combined with
* instanced rendering is used to emulate wide lines.
*/
void ReplaceShaderWideLines(std::string& VSSource, vtkViewport* ren, vtkActor2D* act);
/**
* Determine what shader to use and compile/link it
*/
void UpdateShaders(vtkOpenGLHelper& cellBO, vtkViewport* viewport, vtkActor2D* act) override;
/**
* Set the shader parameters related to the mapper/input data, called by UpdateShader
*/
void SetMapperShaderParameters(
vtkOpenGLHelper& cellBO, vtkViewport* viewport, vtkActor2D* act) override;
/**
* Update the scene when necessary.
*/
void UpdateVBO(vtkActor2D* act, vtkViewport* viewport);
std::vector<unsigned int> PrimitiveIndexArrays[PrimitiveEnd];
vtkNew<vtkOpenGLVertexBufferObjectGroup> PrimitiveVBOGroup[PrimitiveEnd];
PrimitiveTypes CurrentDrawCallPrimtiveType = PrimitiveEnd;
private:
vtkOpenGLES30PolyDataMapper2D(const vtkOpenGLES30PolyDataMapper2D&) = delete;
void operator=(const vtkOpenGLES30PolyDataMapper2D&) = delete;
};
VTK_ABI_NAMESPACE_END
#endif
| [
"jaswant.panchumarti@kitware.com"
] | jaswant.panchumarti@kitware.com |
b8ce8dac5ae09e0d7b54a6b10d797ec31f79748c | cb2b64e9cdf6fbde8ea49e9fd04eeae6e7690acc | /pokemon-battle.cpp | b9d5af724498aedd5992f4c9499a34d5f773ecc2 | [] | no_license | bdavis171/Pokemon-Battle | 327d5b181d53b6e65683d786c541ee713254609e | bf277272688d5729232c399a99dddce36fc6e3e0 | refs/heads/master | 2022-08-19T17:45:46.783296 | 2020-05-21T23:29:25 | 2020-05-21T23:29:25 | 263,171,171 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,511 | cpp | #include <cstdlib> // imports rand() and srand()
#include <ctime> // import time()
#include <iostream>
// NOTE: To get a decimal value when divided two int values, one of them must be casted to a double
using namespace std;
// create a class for Moves that has the following properties: name,type,pwr,and acc.
class Moves
{
public:
string name, type;
int pwr, acc;
void setValues(string, string, int, int);
};
// method to set values for Moves class
void Moves::setValues(string moveName, string moveType, int power, int accuracy)
{
name = moveName;
type = moveType;
pwr = power;
acc = accuracy;
};
// create a class for Pokemon that has the following properties: name, type, hp, atk, def, spAtk, spDef, and spd
class Pokemon
{
public:
string name, type;
int hp, atk, def, spAtk, spDef, spd;
Moves move1, move2, move3, move4;
void setValues(string, string, int, int, int, int, int, int, Moves, Moves, Moves, Moves);
void changeHp(int);
};
// method to set values for Pokemon class
void Pokemon::setValues(string pokeName, string pokeType, int health, int attack, int defense, int specialAttack, int specialDefense, int speed, Moves pokeMove1, Moves pokeMove2, Moves pokeMove3, Moves pokeMove4)
{
name = pokeName;
type = pokeType;
hp = health;
atk = attack;
def = defense;
spAtk = specialAttack;
spDef = specialDefense;
spd = speed;
move1 = pokeMove1;
move2 = pokeMove2;
move3 = pokeMove3;
move4 = pokeMove4;
};
// method to change the pokemon's hp
void Pokemon::changeHp(int newHealth)
{
hp = newHealth;
};
// create a function for Typhlosion to use Flamthrower (Move 1)
int useFlamthrower(Pokemon typhlosion, Pokemon blastoise)
{
srand((unsigned)time(0)); // prevent rand() from returning the same number
// modifier
float modifier = 0.5;
// critical hit modifier
float criticalModifier = 2;
// possible damage dealt
int damage = ((((2 * 100 / 5) + 2) + 2) * typhlosion.move1.pwr * ((double)typhlosion.spAtk / blastoise.spDef) / 50 + 2) * modifier;
// calculate accuracy
int hitChance = rand() % 100 + 1;
// calculate critical hit
int criticalChance = (rand() % 100) + 1;
cout << "Typholsion used Flamthrower!"
<< "\n";
if (hitChance > typhlosion.move1.acc)
{
cout << "The attack missed..."
<< "\n";
}
else
{
if (criticalChance <= 6)
{
damage = damage * criticalModifier;
cout << "Critical hit!"
<< "\n";
}
cout << "It's not very effective!"
<< "\n";
return damage;
}
}
// function for Wild Charge (Move 2)
int useWildCharge(Pokemon typhlosion, Pokemon blastoise)
{
srand((unsigned)time(0)); // prevent rand() from returning the same number
// modifier
float modifier = 1.5;
// critical hit modifier
float criticalModifier = 2;
// possible damage dealt
int damage = ((((2 * 100 / 5) + 2) + 2) * typhlosion.move2.pwr * (((double)typhlosion.atk / blastoise.def)) / 50 + 2) * modifier;
cout << typhlosion.atk << "\n";
// calculate accuracy
int hitChance = rand() % 100 + 1;
// calculate critical hit
int criticalChance = (rand() % 100) + 1;
cout << "Typholsion used Wild Charge!"
<< "\n";
if (hitChance > typhlosion.move2.acc)
{
cout << "The attack missed..."
<< "\n";
}
else
{
if (criticalChance <= 6)
{
damage = damage * criticalModifier;
cout << "Critical hit!"
<< "\n";
}
cout << "It's super effective!"
<< "\n";
return damage;
}
}
// create a function for Typhlosion to use Extrasensory (Move 3)
int useExtrasensory(Pokemon typhlosion, Pokemon blastoise)
{
srand((unsigned)time(0)); // prevent rand() from returning the same number
// modifier
float modifier = 1;
// critical hit modifier
float criticalModifier = 2;
// possible damage dealt
int damage = ((((2 * 100 / 5) + 2) + 2) * typhlosion.move3.pwr * ((double)typhlosion.spAtk / blastoise.spDef) / 50 + 2) * modifier;
// calculate accuracy
int hitChance = rand() % 100 + 1;
// calculate critical hit
int criticalChance = (rand() % 100) + 1;
cout << "Typholsion used Extrasensory!"
<< "\n";
if (hitChance > typhlosion.move3.acc)
{
cout << "The attack missed..."
<< "\n";
}
else
{
if (criticalChance <= 6)
{
damage = damage * criticalModifier;
cout << "Critical hit!"
<< "\n";
}
return damage;
}
}
// create a function for Typhlosion to use Brick Break (Move 4)
int useBrickBreak(Pokemon typhlosion, Pokemon blastoise)
{
srand((unsigned)time(0)); // prevent rand() from returning the same number
// modifier
float modifier = 1;
// critical hit modifier
float criticalModifier = 2;
// possible damage dealt
int damage = ((((2 * 100 / 5) + 2) + 2) * typhlosion.move4.pwr * ((double)typhlosion.atk / blastoise.def) / 50 + 2) * modifier;
// calculate accuracy
int hitChance = rand() % 100 + 1;
// calculate critical hit
int criticalChance = (rand() % 100) + 1;
cout << "Typholsion used Brick Break!"
<< "\n";
if (hitChance > typhlosion.move4.acc)
{
cout << "The attack missed..."
<< "\n";
}
else
{
if (criticalChance <= 6)
{
damage = damage * criticalModifier;
cout << "Critical hit!"
<< "\n";
}
return damage;
}
}
// declaration function
int main()
{
// create a new instance of the Pokemon class called Typhlosion
Pokemon typhlosion;
// create a new instance of the Pokemon class called Blastoise
Pokemon blastoise;
// (Typhlosion) create new instances of the Moves class for the following moves and set their values to the appropriate ones: Flamethrower,Wild Charge,Extrasensory, and Brick Break
Moves flamethrower, wildCharge, extrasensory, brickBreak;
// (Typhlosion) Move 1
flamethrower.setValues("Flamethrower", "Fire", 90, 100);
// (Typhlosion) Move 2
wildCharge.setValues("Wild Charge", "Electric", 90, 100);
// (Typhlosion) Move 3
extrasensory.setValues("Extrasensory", "Psychic", 80, 100);
// (Typhlosion) Move 4
brickBreak.setValues("Brick Break", "Fighting", 75, 100);
// (Blastoise) create new instances of the Moves class for the following moves and set their values to the appropriate ones: Hydro Pump, Dragon Pulse, Flash Cannon, and Dark Pulse
Moves hydroPump, dragonPulse, flashCannon, darkPulse;
// (Blastoise) Move 1
hydroPump.setValues("Hydro Pump", "Water", 110, 80);
// (Blastoise) Move 2
dragonPulse.setValues("Dragon Pulse", "Dragon", 85, 100);
// (Blastoise) Move 3
flashCannon.setValues("Flash Cannon", "Steel", 80, 100);
// (Blastoise) Move 4
darkPulse.setValues("Dark Pulse", "Dark", 80, 100);
// set typhlosion's values to the appropriate ones
typhlosion.setValues("Typhlosion", "Fire", 322, 204, 192, 254, 231, 236, flamethrower, wildCharge, extrasensory, brickBreak);
// set blastoise's values to the appropriate ones
blastoise.setValues("Blastoise", "Water", 299, 171, 236, 206, 246, 192, hydroPump, dragonPulse, flashCannon, darkPulse);
// get the original hp for both pokemon each
int typhlosionOriginHp = typhlosion.hp;
int blastoiseOriginHp = blastoise.hp;
// variable for user commands
string command;
while (typhlosion.hp >= 0 && blastoise.hp >= 0)
{
cout << "Enter a command for Typhlosion."
<< "\n";
getline(cin,command);
if (command == "Flamethrower")
{
int damageDealt = blastoise.hp - useFlamthrower(typhlosion, blastoise);
blastoise.changeHp(damageDealt);
cout << blastoise.hp << "/" << blastoiseOriginHp << "\n";
} else if (command == "Wild Charge"){
int damageDealt = blastoise.hp - useWildCharge(typhlosion, blastoise);
blastoise.changeHp(damageDealt);
cout << blastoise.hp << "/" << blastoiseOriginHp << "\n";
} else {
cout << "That is not a command!!!" << "\n";
continue;
}
}
cout << "You win!" << "\n";
} | [
"bdavis171@gmail.com"
] | bdavis171@gmail.com |
576ef45d4369a754d9c22d53b8274301c48f4156 | 1cf3c0bda1eeec186c21363ee514957d4215c9cb | /backgrounds/Sorting/Comparison_functions.cpp | 228f6240802fd456bd6e967f7e4909a62589c51e | [] | no_license | jaguarcode/algorithms | 5aeb6d6a46e6658a9fbc04186313f46d4135ac86 | 222b65dcfb245292ad10663039a8406871cb2a43 | refs/heads/master | 2023-05-04T08:09:24.246394 | 2021-05-27T23:32:40 | 2021-05-27T23:32:40 | 307,350,248 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 421 | cpp | /**
* author: jaguarcode
* date:
**/
#include <bits/stdc++.h>
using namespace std;
template<typename T>
auto print(T& t) {
for(auto value : t) cout << value << " ";
cout << "\n";
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
vector<int> v { 2,3,4,5,6,2,1,8,2,3,6,9 };
sort(v.begin(), v.end(), [](int a, int b) {
return (a < b); // incr
//return (a > b); // decr
});
print(v);
return 0;
}
| [
"behonz@gmail.com"
] | behonz@gmail.com |
3e5baed33044cae6f0be029cc5e2de087081b9c2 | b22819d39a788b046e9a475f655b005ac478b1ef | /src/439.Ternary_Expression_Parser.cpp | 8ac8efc4558da0dd448393c28a2ceb81cd0a9cdc | [] | no_license | chouchoudiudiu/LeetCode | 81424dd12c6ec7ff0c801b6c4786a6e567b1cdec | a5af14f948db04a2e5a1adfefe033a872fd8f0ed | refs/heads/master | 2021-01-11T07:45:53.672062 | 2019-05-14T21:26:35 | 2019-05-14T21:26:35 | 72,676,179 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 739 | cpp | class Solution {
public:
string parseTernary(string expression) {
stack<char> stk;
bool evaluate = false;
for (int i = expression.size() - 1; i >= 0; --i) {
char c = expression[i];
if (!evaluate && c != ':' && c != '?') //not adding the T or F before the ?
stk.push(c);
if (evaluate) {
char T = stk.top();
stk.pop();
char F = stk.top();
stk.pop();
stk.push(c == 'T' ? T:F);
evaluate = false;
}
if (c == '?')
evaluate = true;
}
string s = "";
return expression.empty() ? s : s + stk.top();
}
};
| [
"noreply@github.com"
] | chouchoudiudiu.noreply@github.com |
73b82e3e8ae1271dc90b868329daec6dae21cde4 | 946e56abf2e2de724aab9d575a94accb2184c88c | /openmp/ring/ring.cpp | 00e22bb05e8a8514f65e9d6a87fcba45b8b827b2 | [
"MIT"
] | permissive | pavelkryukov/paraprog | e71137d196a26fe74c7748efec4ecba6208aea00 | 9a3307f75019543dfd24fc9b5c1a3c0ea1dcd3be | refs/heads/master | 2021-01-20T14:52:37.855913 | 2017-05-08T23:29:43 | 2017-05-08T23:37:30 | 90,681,013 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,442 | cpp | /**
* ring.cpp
*
* Send/Recv messages with pthreads in ring using pthreads
*
* @author pikryukov
* @version 1.0
*
* e-mail: kryukov@frtk.ru
*
* Copyright (C) Kryukov Pavel 2012
* for MIPT MPI course.
*/
#include <cstdlib>
#include <iostream>
#include <vector>
#include <pthread.h>
/**
* Mutex class wrapper
*/
class Mutex
{
private:
friend class Cond;
pthread_mutex_t m;
public:
inline Mutex() { pthread_mutex_init(&m, NULL); }
inline ~Mutex() { pthread_mutex_destroy(&m); }
inline int Lock() { return pthread_mutex_lock(&m); }
inline int Unlock() { return pthread_mutex_unlock(&m); }
inline int TryLock() { return pthread_mutex_trylock(&m); }
};
/**
* Condition class wrapper
*/
class Cond
{
private:
pthread_cond_t c;
public:
inline Cond() { pthread_cond_init(&c, NULL); }
inline ~Cond() { pthread_cond_destroy(&c); }
inline int Wait(Mutex& mutex)
{
return pthread_cond_wait(&c, &mutex.m);
}
inline int TimedWait(Mutex& mutex, const timespec* time)
{
return pthread_cond_timedwait(&c, &mutex.m, time);
}
inline int Signal() { return pthread_cond_signal(&c); }
inline int Broadcast() { return pthread_cond_broadcast(&c); }
};
/**
* Simple port between two threads
*/
template<typename T>
class Port
{
private:
Mutex mutex;
T data;
bool isValid;
Cond full;
Cond free;
public:
Port() : isValid(false) { }
void Write(const T& what)
{
mutex.Lock();
while (isValid)
free.Wait(mutex);
data = what;
isValid = true;
full.Broadcast();
mutex.Unlock();
}
T Read()
{
mutex.Lock();
while(!isValid)
full.Wait(mutex);
T result = data;
isValid = false;
free.Broadcast();
mutex.Unlock();
return result;
}
};
/**
* Thread unit
*/
class Unit
{
private:
Port<unsigned>* readPort;
Port<unsigned>* writePort;
static Mutex printMutex; ///< Mutex for locking stdout
int rank;
unsigned maxAmount;
public:
Unit(int rank, int maxAmount)
: readPort(NULL)
, writePort(NULL)
, rank(rank)
, maxAmount(maxAmount)
{ }
~Unit() { delete readPort; }
inline int GetRank() { return rank; }
inline unsigned GetAmount() { return maxAmount; }
static void Connect(Unit* to, Unit* from)
{
to->readPort = from->writePort = new Port<unsigned>;
}
/// Method for forwarding from previous to next
void Forward()
{
unsigned i = readPort->Read() + 1;
printMutex.Lock();
std::cout << "[" << rank << "] received data (" << i << " time)" << std::endl;
printMutex.Unlock();
writePort->Write(i);
}
inline void Pulse() { writePort->Write(0); }
inline void Catch() { readPort->Read(); }
};
Mutex Unit::printMutex = Mutex();
void* unitRun(void* ptr)
{
Unit* unit = reinterpret_cast<Unit*>(ptr);
int rank = unit->GetRank();
unsigned amount = unit->GetAmount();
// Creating pulse
if (rank == 0)
unit->Pulse();
// Pulse is going around the threads
for (size_t i = 0; i < amount; ++i)
unit->Forward();
// Catching pulse
if (rank == 1)
unit->Catch();
return static_cast<void*>(0);
}
void ring(unsigned size, int counter)
{
// Creating units (thread tasks)
std::vector<Unit*> units(size);
for (size_t i = 0; i < size; ++i)
units[i] = new Unit(i, counter);
// Units connection
for (size_t i = 0; i < size - 1; ++i)
Unit::Connect(units[i + 1], units[i]);
// Looping
Unit::Connect(units[0], units[size - 1]);
// Creating threads
std::vector<pthread_t> threads(size);
for (size_t i = 0; i < size; ++i)
pthread_create(&threads[i], 0, unitRun, reinterpret_cast<void*>(units[i]));
for (size_t i = 0; i < size; ++i)
{
pthread_join(threads[i], NULL);
delete units[i];
}
}
int main(int argc, char** argv)
{
if (argc != 3)
{
std::cerr << "Syntax error! First argument is number of threads,"
<< " second is amount of operations" << std::endl;
return 1;
}
unsigned size = strtoul(argv[1], NULL, 0);
int counter = strtoul(argv[2], NULL, 0);
ring(size, counter);
return 0;
}
| [
"kryukov@frtk.ru"
] | kryukov@frtk.ru |
1c259c53f596bebd4c0d756c05cb2e09b3b342a9 | 08ed3720f797ab761f9d627601896ee7a3f7f14b | /LuaSQLite3/LuaSQLite3.cpp | 2c203a1a291aab7320a7dfeda47658d6fb91135b | [] | no_license | fcccode/LuaUI2 | 2df357681a1f6df8c9c42a73a56ed96efc5212fd | daba4835c848261943fd9ce6d2df0bac0140bd95 | refs/heads/master | 2020-03-14T12:37:28.846054 | 2017-06-09T11:15:11 | 2017-06-09T11:15:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 108 | cpp | // LuaSQLite3.cpp : Defines the exported functions for the DLL application.
//
#include "stdafx.h"
| [
"6659907@gmail.com"
] | 6659907@gmail.com |
73a7eb67e6bf2490552a798ea3c128d1a3c86ed4 | b8482403496a1b2ff50310e2074bebdbea942a68 | /training/2018/winterTraining/3-U.cpp | 11aff0c45c40df7d283188edf1392d1f8f99d8ce | [] | no_license | TangliziGit/icpc-code | 02cc8d70cb5da893ec18c79052f16d7976be98ee | cb0986e12af34d1624e534671f97bd540d412de9 | refs/heads/master | 2021-08-07T09:41:01.999446 | 2020-07-05T02:08:22 | 2020-07-05T02:08:22 | 197,133,978 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,059 | cpp | #include <cstdio>
#include <queue>
using namespace std;
int nx, ny, dir[4][2]={1, 0, 0, 1, -1, 0, 0, -1};
char map[25][25];
struct Point{
int x, y;
Point(int x=0, int y=0):
x(x),y(y) {}
}points[400+5];
int bfs(int x, int y){
queue<int> que; int size=1;
points[0].x=x; points[0].y=y;
que.push(0); map[y][x]='#';
while (que.size()){
int idx=que.front(); que.pop();
for (int i=0; i<4; i++){
int xx=points[idx].x+dir[i][0], yy=points[idx].y+dir[i][1];
if (xx<0 || xx>=nx || yy<0 || yy>=ny) continue;
if (map[yy][xx]=='#') continue;
map[yy][xx]='#';
points[size].x=xx; points[size].y=yy;
que.push(size++);
}
}return size;
}
int main(void){
while (scanf("%d%d", &nx, &ny)==2 && nx){
for (int y=0; y<ny; y++) scanf("%s", map[y]);
int ans;
for (int y=0; y<ny; y++)
for (int x=0; x<nx; x++)
if (map[y][x]=='@') ans=bfs(x, y);
printf("%d\n", ans);
}
return 0;
}
| [
"tanglizimail@foxmail.com"
] | tanglizimail@foxmail.com |
5fb8da5217f1e4cf5ead0e1de197592896394db4 | 39cdb6ff35231538ef25c565181981ccf237cc30 | /BOJ/14225.cpp | 0d0ffcdbfae96ffefcc514c6f12855288e86c191 | [] | no_license | dittoo8/algorithm_cpp | 51b35321f6cf16c8c1c259af746a9f35d5ba8b76 | d9cdda322d3658ffc07744e4080c71faeee6370c | refs/heads/master | 2023-08-03T14:49:08.808253 | 2021-02-16T04:13:53 | 2021-02-16T04:13:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 515 | cpp | #include <cstdio>
using namespace std;
int n;
int a[21];
bool ck[20*100000];
void backtrack(int idx, int sum){
if (idx == n){
ck[sum]= true;
return;
}
backtrack(idx+1, sum+a[idx]);
backtrack(idx+1, sum);
}
int main(){
scanf("%d", &n);
for(int i=0;i<n;i++){
scanf("%d", &a[i]);
}
backtrack(0,0);
int start =1;
while(true){
if(!ck[start]){
printf("%d\n", start);
return 0;
}
start++;
}
return 0;
} | [
"sohyun1018@gmail.com"
] | sohyun1018@gmail.com |
71b2bc5e6b14568b6e6753cfe175cdf22d7acf08 | 9c025e695dfeab531a47c68b1373811bed94b1da | /BC一周年B.cpp | 8b543e8e434e0b6dc9c3e716f5a553c5eb8c8b05 | [] | no_license | shipoyewu/code | 8ecfa66f5a82976327ec649e9fe142efe0293e28 | 54bcf1623d6eef87109c6c34148a6072f419dfa8 | refs/heads/master | 2021-01-23T21:34:34.113351 | 2015-09-17T11:58:31 | 2015-09-17T11:58:31 | 39,375,222 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,803 | cpp | #include <cstdio>
#include <iostream>
#include <algorithm>
#include <queue>
#include <cmath>
#include <cstring>
#include <stack>
#include <set>
#include <map>
#include <vector>
using namespace std;
#define INF 0x4fffffff
#define LL long long
#define MAX(a,b) ((a)>(b))?(a):(b)
#define MIN(a,b) ((a)<(b))?(a):(b)
char str[] = "anniversary";
int a[300][4] = {};
char st[105];
int main(){
int t;
cin >> t;
int len = strlen(str);
int w = 0;
for(int i = 0;i < len-2;i++){
for(int j = i+1;j < len-1;j++){
a[w][0] = i;
a[w][1] = j;
a[w][2] = len-1;
w++;
}
}
while(t--){
scanf("%s",st);
len = strlen(st);
int flag = 0;
int s,e,g,f;
for(int i = 0;i < w;i++){
s = 0;
f = 0;
g = 0;
for(int j = 0;j < 3;j++){
e = a[i][j];
for(int k = g;k < len;k++){
int d = 0;
int status = 0;
while(str[s+d] == st[k+d] && s+d <= e && k+d < len){
if(s+d == e){
f ++;
s = a[i][j]+1;
g = k+d+1;
status = 1;
break;
}
d ++;
}
if(status){
break;
}
}
}
if(f == 3){
flag = 1;
break;
}
}
if(flag){
printf("YES\n");
}
else{
printf("NO\n");
}
}
return 0;
}
| [
"871650575@qq.com"
] | 871650575@qq.com |
27afcc0d8d527c6eecf1a5143451b4f2070f9089 | 3a7b4600778f147a24d49fe5264f96e46db57e10 | /32_3.cpp | d422030a249a597c6a5f63596f3948d656a1c2ee | [] | no_license | CanRui-Wu/PointToOffer | 9f5fea82f7d8796a95ecbbf1fb6b01e998ca46c0 | 88204fb67a4dc29373dcb94980857d6210dcf176 | refs/heads/master | 2021-04-26T23:54:09.474574 | 2018-03-24T12:21:52 | 2018-03-24T12:21:52 | 123,877,220 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,571 | cpp | #include <iostream>
#include <vector>
#include <queue>
using namespace std;
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
class Solution {
public:
vector<vector<int> > Print(TreeNode* pRoot) {
vector<vector<int> > result;
if(pRoot == NULL)
return result;
queue<pair<TreeNode*,int> > myqueue;
myqueue.push(make_pair(pRoot,0));
vector<int> temp;
int current = 0;
while(!myqueue.empty()) {
pair<TreeNode*,int> mypair = myqueue.front();
myqueue.pop();
if(mypair.second != current) {
if(current & 1 == 1) {
for(int i = 0;i < temp.size()/2;i++) {
swap(temp[i],temp[temp.size()-1-i]);
}
}
result.push_back(temp);
temp.clear();
current++;
}
temp.push_back(mypair.first->val);
if(mypair.first->left != NULL)
myqueue.push(make_pair(mypair.first->left,mypair.second+1));
if(mypair.first->right != NULL)
myqueue.push(make_pair(mypair.first->right,mypair.second+1));
}
if(current & 1 == 1) {
for(int i = 0;i < temp.size()/2;i++) {
swap(temp[i],temp[temp.size()-1-i]);
}
}
result.push_back(temp);
return result;
}
};
int main() {
Solution solution;
// vector<int> sequence = {4,8,6,12,16,14,10};
// cout << solution.VerifySquenceOfBST(sequence) << endl;
} | [
"434858383@qq.com"
] | 434858383@qq.com |
518622424b9903c5be5cd2f1ebd5c72f45f16105 | 7edeec5310bf96c435c287f59be66fb78be556b9 | /OSDesign/main.cpp | d4ad4d7949c906f240b014c0a2f3331fc13ee4c1 | [] | no_license | typeme/daily-study | e145824eb4dab77a7e862003a133d4a3ffdf9c1f | e149cde065c84285bacb6c7012bf5e7d54432efc | refs/heads/master | 2020-08-03T20:23:33.019127 | 2020-07-13T15:54:48 | 2020-07-13T15:54:48 | 211,875,489 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 79,681 | cpp | #include <iostream>
#include<termios.h>
#include<unistd.h>
#include<assert.h>
#include<time.h>
#include <stdio.h>//c语言的的unix文件输入输出库
#include <fcntl.h>//根据文件描述词操作文件的特性
#include <string>
#include <cstring>
using namespace std;
//常量定义
// NADDR为文件可使用的最大数量节点
const unsigned int NADDR = 6;
// BLOCK_SIZE为一个block的大小
const unsigned short BLOCK_SIZE = 512;
//文件最大尺寸
const unsigned int FILE_SIZE_MAX = (NADDR - 2) * BLOCK_SIZE + BLOCK_SIZE / sizeof(int) * BLOCK_SIZE;
//block的数量
const unsigned short BLOCK_NUM = 512;
//inode 索引节点大小
const unsigned short INODE_SIZE = 128;
//inode数量
const unsigned short INODE_NUM = 256;
//inode的起始位置
const unsigned int INODE_START = 3 * BLOCK_SIZE;
//数据起始位置
const unsigned int DATA_START = INODE_START + INODE_NUM * INODE_SIZE;
//文件系统支持的用户数量
const unsigned int ACCOUNT_NUM = 10;
//子目录的最大数量
const unsigned int DIRECTORY_NUM = 16;
//文件名的最大长度
const unsigned short FILE_NAME_LENGTH = 14;
//用户名的最大长度
const unsigned short USER_NAME_LENGTH = 14;
//用户密码的最大长度
const unsigned short USER_PASSWORD_LENGTH = 14;
//文件最大权限
const unsigned short MAX_PERMISSION = 511;
//用户最大权限
const unsigned short MAX_OWNER_PERMISSION = 448;
//权限
const unsigned short ELSE_E = 1;
const unsigned short ELSE_W = 1 << 1;
const unsigned short ELSE_R = 1 << 2;
const unsigned short GRP_E = 1 << 3;
const unsigned short GRP_W = 1 << 4;
const unsigned short GRP_R = 1 << 5;
const unsigned short OWN_E = 1 << 6;
const unsigned short OWN_W = 1 << 7;
const unsigned short OWN_R = 1 << 8;
//inode设计 索引节点
struct inode
{
unsigned int i_ino; //inode号.
unsigned int di_addr[NADDR]; // 存储文件的数据块数。
unsigned short di_number; // 关联文件数。
unsigned short di_mode; //文件类型.
unsigned short icount; //连接数
unsigned short permission; //文件权限
unsigned short di_uid; //文件所属用户id.
unsigned short di_grp; //文件所属组
unsigned short di_size; //文件大小.
char time[100];
};
//超级块设置
struct filsys
{
unsigned short s_num_inode; //inode总数
unsigned short s_num_finode; //空闲inode数.
unsigned short s_size_inode; //inode大小.
unsigned short s_num_block; //block的数量.
unsigned short s_num_fblock; //空闲块的数量.
unsigned short s_size_block; //block的大小.
unsigned int special_stack[50]; //栈中元素为空闲块指针
int special_free; //下一组中空闲块数量
};
//目录设计
struct directory
{
char fileName[20][FILE_NAME_LENGTH]; //目录名称
unsigned int inodeID[DIRECTORY_NUM]; //inode号
};
//账户设计
struct userPsw
{
unsigned short userID[ACCOUNT_NUM]; //用户id
char userName[ACCOUNT_NUM][USER_NAME_LENGTH]; //用户名
char password[ACCOUNT_NUM][USER_PASSWORD_LENGTH]; //用户密码
unsigned short groupID[ACCOUNT_NUM]; //用户所在组id
};
//功能函数声明
void CommParser(inode*&); // 选取功能
void Help(); //帮助信息
void Sys_start(); //启动文件系统
//全局变量
FILE* fd = NULL; //文件系统位置
//超级块
filsys superBlock;
//1代表已经使用,0表示空闲
unsigned short inode_bitmap[INODE_NUM];
//用户
userPsw users;
//用户id
unsigned short userID = ACCOUNT_NUM;
//用户名
char userName[USER_NAME_LENGTH + 6];
//当前目录
directory currentDirectory;
char ab_dir[100][14];
unsigned short dir_pointer;
//寻找空闲块
void find_free_block(unsigned int &inode_number)
{
// 设置文件系统的位置为从SEEK_SET 开始偏移BLOCK_SIZE开始
fseek(fd, BLOCK_SIZE, SEEK_SET);
// 读取文件系统中的大小为filsys的内容到superBlock
fread(&superBlock, sizeof(filsys), 1, fd);
// 如果当前空闲块数量为0
if (superBlock.special_free == 0)
{
// 如果系统中不存在空闲块
if (superBlock.special_stack[0] == 0)
{
printf("No value block!\n");
return;
}
// 只剩下最上方元素,则将最上方元素栈的信息和N保存到超级块中,接着将原最上方元素作为普通元素分配出去即可
unsigned int stack[51];
for (int i = 0; i < 50; i++)
{
stack[i] = superBlock.special_stack[i];
}
stack[50] = superBlock.special_free;
fseek(fd, DATA_START + (superBlock.special_stack[0] - 50) * BLOCK_SIZE, SEEK_SET);
// 将stack内容写到文件系统
fwrite(stack, sizeof(stack), 1, fd);
fseek(fd, DATA_START + superBlock.special_stack[0] * BLOCK_SIZE, SEEK_SET);
fread(stack, sizeof(stack), 1, fd);
for (int i = 0; i < 50; i++)
{
superBlock.special_stack[i] = stack[i];
}
superBlock.special_free = stack[50];
}
// 出栈最后一个块 作为分配的block
inode_number = superBlock.special_stack[superBlock.special_free];
superBlock.special_free--;
superBlock.s_num_fblock--;
fseek(fd, BLOCK_SIZE, SEEK_SET);
fwrite(&superBlock, sizeof(filsys), 1, fd);
}
//重置block
void recycle_block(unsigned int &inode_number)
{
fseek(fd, BLOCK_SIZE, SEEK_SET);
fread(&superBlock, sizeof(filsys), 1, fd);
// 若栈满了,则把超级块中的内容复制到新来的块中,包括N,栈信息 接着更新超级块信息,超级块N变为1,第一个元素指向刚才新来的磁盘块
if (superBlock.special_free == 49)
{
unsigned int block_num;
unsigned int stack[51];
if (superBlock.special_stack[0] == 0)
block_num = 499;
else
block_num = superBlock.special_stack[0] - 50;
for (int i = 0; i < 50; i++)
{
stack[i] = superBlock.special_stack[i];
}
stack[50] = superBlock.special_free;
fseek(fd, DATA_START + block_num*BLOCK_SIZE, SEEK_SET);
fwrite(stack, sizeof(stack), 1, fd);
block_num -= 50;
fseek(fd, DATA_START + block_num*BLOCK_SIZE, SEEK_SET);
fread(stack, sizeof(stack), 1, fd);
for (int i = 0; i < 50; i++)
{
superBlock.special_stack[i] = stack[i];
}
superBlock.special_free = stack[50];
}
superBlock.special_free++;
superBlock.s_num_fblock++;
superBlock.special_stack[superBlock.special_free] = inode_number;
fseek(fd, BLOCK_SIZE, SEEK_SET);
fwrite(&superBlock, sizeof(filsys), 1, fd);
}
//初始化文件系统
bool Format()
{
//在当前目录新建一个文件作为文件卷
FILE* fd = fopen("root.tianye", "wb+");
if (fd == NULL)
{
printf("初始化文件系统失败!\n");
return false;
}
//初始化超级块
filsys superBlock;
superBlock.s_num_inode = INODE_NUM;
superBlock.s_num_block = BLOCK_NUM + 3 + 64; //3代表,0空闲块、1超级块、2Inode位示图表,64块存inode 位示图,记录文件存储器的使用情况
superBlock.s_size_inode = INODE_SIZE;
superBlock.s_size_block = BLOCK_SIZE;
superBlock.s_num_fblock = BLOCK_NUM - 2;
superBlock.s_num_finode = INODE_NUM - 2;
superBlock.special_stack[0] = 99;
for (int i = 1; i < 50; i++)
{
superBlock.special_stack[i] = 49 - i;
}
superBlock.special_free = 47;
//Write super block into file.
fseek(fd, BLOCK_SIZE, SEEK_SET);
fwrite(&superBlock, sizeof(filsys), 1, fd);
fseek(fd, BLOCK_SIZE, SEEK_SET);
fread(&superBlock, sizeof(filsys), 1, fd);
//初始化位示图
unsigned short inode_bitmap[INODE_NUM];
memset(inode_bitmap, 0, INODE_NUM);
inode_bitmap[0] = 1;
inode_bitmap[1] = 1;
//Write bitmaps into file.
fseek(fd, 2 * BLOCK_SIZE, SEEK_SET);
fwrite(inode_bitmap, sizeof(unsigned short) * INODE_NUM, 1, fd);
//成组链接
unsigned int stack[51];
for (int i = 0; i < BLOCK_NUM / 50; i++)
{
memset(stack, 0, sizeof(stack));
for (unsigned int j = 0; j < 50; j++)
{
stack[j] = (49 + i * 50) - j;
}
stack[0] = 49 + (i + 1) * 50;
stack[50] = 49;
fseek(fd, DATA_START + (49 + i * 50)*BLOCK_SIZE, SEEK_SET);
fwrite(stack, sizeof(unsigned int) * 51, 1, fd);
}
memset(stack, 0, sizeof(stack));
for (int i = 0; i < 12; i++)
{
stack[i] = 511 - i;
}
stack[0] = 0;
stack[50] = 11;
fseek(fd, DATA_START + 511 * BLOCK_SIZE, SEEK_SET);
fwrite(stack, sizeof(unsigned int) * 51, 1, fd);
fseek(fd, DATA_START + 49 * BLOCK_SIZE, SEEK_SET);
fread(stack, sizeof(unsigned int) * 51, 1, fd);
fseek(fd, DATA_START + 99 * BLOCK_SIZE, SEEK_SET);
fread(stack, sizeof(unsigned int) * 51, 1, fd);
fseek(fd, DATA_START + 149 * BLOCK_SIZE, SEEK_SET);
fread(stack, sizeof(unsigned int) * 51, 1, fd);
fseek(fd, DATA_START + 199 * BLOCK_SIZE, SEEK_SET);
fread(stack, sizeof(unsigned int) * 51, 1, fd);
fseek(fd, DATA_START + 249 * BLOCK_SIZE, SEEK_SET);
fread(stack, sizeof(unsigned int) * 51, 1, fd);
fseek(fd, DATA_START + 299 * BLOCK_SIZE, SEEK_SET);
fread(stack, sizeof(unsigned int) * 51, 1, fd);
fseek(fd, DATA_START + 349 * BLOCK_SIZE, SEEK_SET);
fread(stack, sizeof(unsigned int) * 51, 1, fd);
fseek(fd, DATA_START + 399 * BLOCK_SIZE, SEEK_SET);
fread(stack, sizeof(unsigned int) * 51, 1, fd);
fseek(fd, DATA_START + 449 * BLOCK_SIZE, SEEK_SET);
fread(stack, sizeof(unsigned int) * 51, 1, fd);
fseek(fd, DATA_START + 499 * BLOCK_SIZE, SEEK_SET);
fread(stack, sizeof(unsigned int) * 51, 1, fd);
fseek(fd, DATA_START + 511 * BLOCK_SIZE, SEEK_SET);
fread(stack, sizeof(unsigned int) * 51, 1, fd);
//创建根目录
inode iroot_tmp;
iroot_tmp.i_ino = 0;
iroot_tmp.di_number = 2;
iroot_tmp.di_mode = 0; //0 =目录
iroot_tmp.di_size = 0; //目录大小为0
memset(iroot_tmp.di_addr, -1, sizeof(unsigned int) * NADDR);
iroot_tmp.di_addr[0] = 0;
iroot_tmp.permission = MAX_OWNER_PERMISSION;
iroot_tmp.di_grp = 1;
iroot_tmp.di_uid = 0; //Root user id.
iroot_tmp.icount = 0;
time_t t = time(0);
strftime(iroot_tmp.time, sizeof(iroot_tmp.time), "%Y/%m/%d %X", localtime(&t));
iroot_tmp.time[64] = 0;
fseek(fd, INODE_START, SEEK_SET);
fwrite(&iroot_tmp, sizeof(inode), 1, fd);
//直接创建文件
directory droot_tmp;
memset(droot_tmp.fileName, 0, sizeof(char) * DIRECTORY_NUM * FILE_NAME_LENGTH);
memset(droot_tmp.inodeID, -1, sizeof(unsigned int) * DIRECTORY_NUM);
strcpy(droot_tmp.fileName[0], ".");
droot_tmp.inodeID[0] = 0;
strcpy(droot_tmp.fileName[1], "..");
droot_tmp.inodeID[1] = 0;
//A sub directory for accounting files
strcpy(droot_tmp.fileName[2], "system");
droot_tmp.inodeID[2] = 1;
//写入
fseek(fd, DATA_START, SEEK_SET);
fwrite(&droot_tmp, sizeof(directory), 1, fd);
//创建用户文件
//先创建 inode
inode iaccouting_tmp;
iaccouting_tmp.i_ino = 1;
iaccouting_tmp.di_number = 1;
iaccouting_tmp.di_mode = 1; //1 代表文件
iaccouting_tmp.di_size = sizeof(userPsw); //文件大小
memset(iaccouting_tmp.di_addr, -1, sizeof(unsigned int) * NADDR);
iaccouting_tmp.di_addr[0] = 1; //根目录存在第一块
iaccouting_tmp.di_uid = 0; //Root user id.
iaccouting_tmp.di_grp = 1;
iaccouting_tmp.permission = 320;
iaccouting_tmp.icount = 0;
t = time(0);
strftime(iaccouting_tmp.time, sizeof(iaccouting_tmp.time), "%Y/%m/%d %X", localtime(&t));
iaccouting_tmp.time[64] = 0;
fseek(fd, INODE_START + INODE_SIZE, SEEK_SET);
fwrite(&iaccouting_tmp, sizeof(inode), 1, fd);
//创建账户.
userPsw paccouting_tmp;
memset(paccouting_tmp.userName, 0, sizeof(char) * USER_NAME_LENGTH * ACCOUNT_NUM);
memset(paccouting_tmp.password, 0, sizeof(char) * USER_PASSWORD_LENGTH * ACCOUNT_NUM);
strcpy(paccouting_tmp.userName[0], "root");
strcpy(paccouting_tmp.userName[1], "tianye");
strcpy(paccouting_tmp.password[0], "123");
strcpy(paccouting_tmp.password[1], "123");
//0 代表管理员,其他数字就是userid
for (unsigned short i = 0; i < ACCOUNT_NUM; i++)
{
paccouting_tmp.userID[i] = i;
}
paccouting_tmp.groupID[0] = 1;
paccouting_tmp.groupID[1] = 2;
//写入文件
fseek(fd, DATA_START + BLOCK_SIZE, SEEK_SET);
fwrite(&paccouting_tmp, sizeof(userPsw), 1, fd);
//关闭文件.
fclose(fd);
return true;
};
//初始化文件系统的各项功能
bool Mount()
{
//打开文件卷
fd = fopen("root.tianye", "rb+");
if (fd == NULL)
{
printf("文件系统没有找到!\n");
return false;
}
//读取超级块信息
fseek(fd, BLOCK_SIZE, SEEK_SET);
fread(&superBlock, sizeof(superBlock), 1, fd);
//读取节点映射表
fseek(fd, 2 * BLOCK_SIZE, SEEK_SET);
fread(inode_bitmap, sizeof(unsigned short) * INODE_NUM, 1, fd);
//读取当前目录
fseek(fd, DATA_START, SEEK_SET);
fread(¤tDirectory, sizeof(directory), 1, fd);
//读取账户资料
fseek(fd, DATA_START + BLOCK_SIZE, SEEK_SET);
fread(&users, sizeof(userPsw), 1, fd);
return true;
};
//登录模块
bool Login(const char* user, const char* password)
{
//检测参数
if (user == NULL || password == NULL)
{
printf("用户名或密码不合法!\n\n");
return false;
}
if (strlen(user) > USER_NAME_LENGTH || strlen(password) > USER_PASSWORD_LENGTH)
{
printf("用户名或密码不合法!\n");
return false;
}
//检测是否登录
if (userID != ACCOUNT_NUM)
{
printf("用户已经登录,请先退出.\n");
return false;
}
//在账户文件中搜相应的账户名
for (int i = 0; i < ACCOUNT_NUM; i++)
{
if (strcmp(users.userName[i], user) == 0)
{
//验证相应的密码
if (strcmp(users.password[i], password) == 0)
{
//登录成功提示
printf("登录成功!.\n");
userID = users.userID[i];
//个性化设置
memset(userName, 0, USER_NAME_LENGTH + 6);
if (userID == 0)
{
strcat(userName, "mamnager ");
strcat(userName, users.userName[i]);
strcat(userName, "$");
}
else
{
strcat(userName, users.userName[i]);
strcat(userName, "#");
}
return true;
}
else
{
//密码错误的提示
printf("密码错误.\n");
return false;
}
}
}
//用户名未找到
printf("登录失败,没有相应的用户.\n");
return false;
};
//登出功能
void Logout()
{
userID = ACCOUNT_NUM;
memset(&users, 0, sizeof(users));
memset(userName, 0, 6 + USER_NAME_LENGTH);
Mount();
};
//根据文件名创建文件
bool CreateFile(const char* filename)
{
//文件名合法性检测
if (filename == NULL || strlen(filename) > FILE_NAME_LENGTH)
{
printf("不合法的文件名.\n");
return false;
}
//检测是否还有空闲的block
if (superBlock.s_num_fblock <= 0 || superBlock.s_num_finode <= 0)
{
printf("没有空间创建新文件了.\n");
return false;
}
//若有空闲block,则找新的inode
int new_ino = 0;
unsigned int new_block_addr = -1;
for (; new_ino < INODE_NUM; new_ino++)
{
if (inode_bitmap[new_ino] == 0)
{
break;
}
}
//检测当前目录是否有同名文件
for (int i = 0; i < DIRECTORY_NUM; i++)
{
if (strcmp(currentDirectory.fileName[i], filename) == 0)
{
inode* tmp_file_inode = new inode;
int tmp_file_ino = currentDirectory.inodeID[i];
fseek(fd, INODE_START + tmp_file_ino * INODE_SIZE, SEEK_SET);
fread(tmp_file_inode, sizeof(inode), 1, fd);
if (tmp_file_inode->di_mode == 0) continue;
else {
printf("文件名'%s' 有重复.\n", currentDirectory.fileName[i]);
return false;
}
}
}
//检测当前目录的文件数量是否达到限制
int itemCounter = 0;
for (int i = 0; i < DIRECTORY_NUM; i++)
{
if (strlen(currentDirectory.fileName[i]) > 0)
{
itemCounter++;
}
}
if (itemCounter >= DIRECTORY_NUM)
{
printf("文件创建错误:当前文件夹中存在太多文件或文件夹。\n");
return false;
}
//创建新的inode
inode ifile_tmp;
ifile_tmp.i_ino = new_ino;
ifile_tmp.di_number = 1;
ifile_tmp.di_mode = 1; //1 表示文件
ifile_tmp.di_size = 0; //新文件大小为0
memset(ifile_tmp.di_addr, -1, sizeof(unsigned int) * NADDR);
ifile_tmp.di_uid = userID; //当前用户id.
ifile_tmp.di_grp = users.groupID[userID];//当前用户的组
ifile_tmp.permission = MAX_PERMISSION;
ifile_tmp.icount = 0;
time_t t = time(0);
strftime(ifile_tmp.time, sizeof(ifile_tmp.time), "%Y/%m/%d %X", localtime(&t));
ifile_tmp.time[64];
fseek(fd, INODE_START + new_ino * INODE_SIZE, SEEK_SET);
fwrite(&ifile_tmp, sizeof(inode), 1, fd);
//更新映射表
inode_bitmap[new_ino] = 1;
fseek(fd, 2 * BLOCK_SIZE, SEEK_SET);
fwrite(inode_bitmap, sizeof(unsigned short) * INODE_NUM, 1, fd);
//更新目录
//查找当前目录的inode
int pos_directory_inode = 0;
pos_directory_inode = currentDirectory.inodeID[0]; //"."
inode tmp_directory_inode;
fseek(fd, INODE_START + pos_directory_inode * INODE_SIZE, SEEK_SET);
fread(&tmp_directory_inode, sizeof(inode), 1, fd);
//加入当前目录
for (int i = 2; i < DIRECTORY_NUM; i++)
{
if (strlen(currentDirectory.fileName[i]) == 0)
{
strcat(currentDirectory.fileName[i], filename);
currentDirectory.inodeID[i] = new_ino;
break;
}
}
//写入文件
fseek(fd, DATA_START + tmp_directory_inode.di_addr[0] * BLOCK_SIZE, SEEK_SET);
fwrite(¤tDirectory, sizeof(directory), 1, fd);
//更新相关信息
directory tmp_directory = currentDirectory;
int tmp_pos_directory_inode = pos_directory_inode;
while (true)
{
tmp_directory_inode.di_number++;
fseek(fd, INODE_START + tmp_pos_directory_inode * INODE_SIZE, SEEK_SET);
fwrite(&tmp_directory_inode, sizeof(inode), 1, fd);
//如果到了根目录就停止更新
if (tmp_directory.inodeID[1] == tmp_directory.inodeID[0])
{
break;
}
tmp_pos_directory_inode = tmp_directory.inodeID[1]; //".."
fseek(fd, INODE_START + tmp_pos_directory_inode * INODE_SIZE, SEEK_SET);
fread(&tmp_directory_inode, sizeof(inode), 1, fd);
fseek(fd, DATA_START + tmp_directory_inode.di_addr[0] * BLOCK_SIZE, SEEK_SET);
fread(&tmp_directory, sizeof(directory), 1, fd);
}
//更新超级块
superBlock.s_num_finode--;
fseek(fd, BLOCK_SIZE, SEEK_SET);
fwrite(&superBlock, sizeof(filsys), 1, fd);
return true;
};
//删除文件
bool DeleteFile(const char* filename)
{
//文件名合法性检测
if (filename == NULL || strlen(filename) > FILE_NAME_LENGTH)
{
printf("错误:非法文件名\n");
return false;
}
//1.检测文件名是否存在当前目录
int pos_in_directory = -1, tmp_file_ino;
inode tmp_file_inode;
do {
pos_in_directory++;
for (; pos_in_directory < DIRECTORY_NUM; pos_in_directory++)
{
if (strcmp(currentDirectory.fileName[pos_in_directory], filename) == 0)
{
break;
}
}
if (pos_in_directory == DIRECTORY_NUM)
{
printf("错误:当前目录未找到删除文件\n");
return false;
}
//2.看inode是否为文件还是目录
tmp_file_ino = currentDirectory.inodeID[pos_in_directory];
fseek(fd, INODE_START + tmp_file_ino * INODE_SIZE, SEEK_SET);
fread(&tmp_file_inode, sizeof(inode), 1, fd);
//检测目录
} while (tmp_file_inode.di_mode == 0);
//权限检测
if (userID == tmp_file_inode.di_uid)
{
if (!(tmp_file_inode.permission & OWN_E)) {
printf("不好意思,你没有权限删除.\n");
return -1;
}
}
else if (users.groupID[userID] == tmp_file_inode.di_grp) {
if (!(tmp_file_inode.permission & GRP_E)) {
printf("不好意思,没有权限删除.\n");
return -1;
}
}
else {
if (!(tmp_file_inode.permission & ELSE_E)) {
printf("不好意思,没有权限删除.\n");
return -1;
}
}
//3.开始删除,inode赋值为0
if (tmp_file_inode.icount > 0) {
tmp_file_inode.icount--;
fseek(fd, INODE_START + tmp_file_inode.i_ino * INODE_SIZE, SEEK_SET);
fwrite(&tmp_file_inode, sizeof(inode), 1, fd);
//更新目录
int pos_directory_inode = currentDirectory.inodeID[0]; //"."
inode tmp_directory_inode;
fseek(fd, INODE_START + pos_directory_inode * INODE_SIZE, SEEK_SET);
fread(&tmp_directory_inode, sizeof(inode), 1, fd);
memset(currentDirectory.fileName[pos_in_directory], 0, FILE_NAME_LENGTH);
currentDirectory.inodeID[pos_in_directory] = -1;
fseek(fd, DATA_START + tmp_directory_inode.di_addr[0] * BLOCK_SIZE, SEEK_SET);
fwrite(¤tDirectory, sizeof(directory), 1, fd);
//更新相关信息
directory tmp_directory = currentDirectory;
int tmp_pos_directory_inode = pos_directory_inode;
while (true)
{
tmp_directory_inode.di_number--;
fseek(fd, INODE_START + tmp_pos_directory_inode * INODE_SIZE, SEEK_SET);
fwrite(&tmp_directory_inode, sizeof(inode), 1, fd);
if (tmp_directory.inodeID[1] == tmp_directory.inodeID[0])
{
break;
}
tmp_pos_directory_inode = tmp_directory.inodeID[1]; //".."
fseek(fd, INODE_START + tmp_pos_directory_inode * INODE_SIZE, SEEK_SET);
fread(&tmp_directory_inode, sizeof(inode), 1, fd);
fseek(fd, DATA_START + tmp_directory_inode.di_addr[0] * BLOCK_SIZE, SEEK_SET);
fread(&tmp_directory, sizeof(directory), 1, fd);
}
return true;
}
int tmp_fill[sizeof(inode)];
memset(tmp_fill, 0, sizeof(inode));
fseek(fd, INODE_START + tmp_file_ino * INODE_SIZE, SEEK_SET);
fwrite(&tmp_fill, sizeof(inode), 1, fd);
//4.更新映射
inode_bitmap[tmp_file_ino] = 0;
fseek(fd, 2 * BLOCK_SIZE, SEEK_SET);
fwrite(&inode_bitmap, sizeof(unsigned short) * INODE_NUM, 1, fd);
for (int i = 0; i < NADDR - 2; i++)
{
if(tmp_file_inode.di_addr[i] != -1)
recycle_block(tmp_file_inode.di_addr[i]);
else break;
}
if (tmp_file_inode.di_addr[NADDR - 2] != -1) {
unsigned int f1[128];
fseek(fd, DATA_START + tmp_file_inode.di_addr[NADDR - 2] * BLOCK_SIZE, SEEK_SET);
fread(f1, sizeof(f1), 1, fd);
for (int k = 0; k < 128; k++) {
recycle_block(f1[k]);
}
recycle_block(tmp_file_inode.di_addr[NADDR - 2]);
}
// 5. 更新目录
int pos_directory_inode = currentDirectory.inodeID[0]; //"."
inode tmp_directory_inode;
fseek(fd, INODE_START + pos_directory_inode * INODE_SIZE, SEEK_SET);
fread(&tmp_directory_inode, sizeof(inode), 1, fd);
//更新目录项
memset(currentDirectory.fileName[pos_in_directory], 0, FILE_NAME_LENGTH);
currentDirectory.inodeID[pos_in_directory] = -1;
fseek(fd, DATA_START + tmp_directory_inode.di_addr[0] * BLOCK_SIZE, SEEK_SET);
fwrite(¤tDirectory, sizeof(directory), 1, fd);
directory tmp_directory = currentDirectory;
int tmp_pos_directory_inode = pos_directory_inode;
while (true)
{
tmp_directory_inode.di_number--;
fseek(fd, INODE_START + tmp_pos_directory_inode * INODE_SIZE, SEEK_SET);
fwrite(&tmp_directory_inode, sizeof(inode), 1, fd);
if (tmp_directory.inodeID[1] == tmp_directory.inodeID[0])
{
break;
}
tmp_pos_directory_inode = tmp_directory.inodeID[1]; //".."
fseek(fd, INODE_START + tmp_pos_directory_inode * INODE_SIZE, SEEK_SET);
fread(&tmp_directory_inode, sizeof(inode), 1, fd);
fseek(fd, DATA_START + tmp_directory_inode.di_addr[0] * BLOCK_SIZE, SEEK_SET);
fread(&tmp_directory, sizeof(directory), 1, fd);
}
//6.更新超级块
superBlock.s_num_finode++;
fseek(fd, BLOCK_SIZE, SEEK_SET);
fwrite(&superBlock, sizeof(filsys), 1, fd);
return true;
}
//根据文件名打开文件
inode* OpenFile(const char* filename)
{
//文件名检测
if (filename == NULL || strlen(filename) > FILE_NAME_LENGTH)
{
printf("不合法文件名.\n");
return NULL;
}
//1. 查找是否存在该文件.
int pos_in_directory = -1;
inode* tmp_file_inode = new inode;
do {
pos_in_directory++;
for (; pos_in_directory < DIRECTORY_NUM; pos_in_directory++)
{
if (strcmp(currentDirectory.fileName[pos_in_directory], filename) == 0)
{
break;
}
}
if (pos_in_directory == DIRECTORY_NUM)
{
printf("没有找到该文件.\n");
return NULL;
}
// 2. 判断inode是否是目录
int tmp_file_ino = currentDirectory.inodeID[pos_in_directory];
fseek(fd, INODE_START + tmp_file_ino * INODE_SIZE, SEEK_SET);
fread(tmp_file_inode, sizeof(inode), 1, fd);
} while (tmp_file_inode->di_mode == 0);
return tmp_file_inode;
};
//在文件尾添加数据
int Write(inode& ifile, const char* content)
{
if (content == NULL)
{
printf("不合法的内容.\n");
return -1;
}
//权限检测
if (userID == ifile.di_uid)
{
if (!(ifile.permission & OWN_W)) {
printf("权限不够.\n");
return -1;
}
}
else if (users.groupID[userID] == ifile.di_grp) {
if (!(ifile.permission & GRP_W)) {
printf("权限不够.\n");
return -1;
}
}
else {
if (!(ifile.permission & ELSE_W)) {
printf("权限不够.\n");
return -1;
}
}
// 1.检测文件是否达到了最大大小
int len_content = strlen(content);
unsigned int new_file_length = len_content + ifile.di_size;
if (new_file_length >= FILE_SIZE_MAX)
{
printf("文件不能再大了.\n");
return -1;
}
//2. 取得所需的inode,并查看是否有空闲.
unsigned int block_num;
if (ifile.di_addr[0] == -1)block_num = -1;
else
{
for (int i = 0; i < NADDR - 2; i++)
{
if (ifile.di_addr[i] != -1)
block_num = ifile.di_addr[i];
else break;
}
int f1[128];
fseek(fd, DATA_START + ifile.di_addr[NADDR - 2] * BLOCK_SIZE, SEEK_SET);
int num;
if (ifile.di_size%BLOCK_SIZE == 0)
num = ifile.di_size / BLOCK_SIZE;
else num = ifile.di_size / BLOCK_SIZE + 1;
if (num > 4 && num <=132)
{
fseek(fd, DATA_START + ifile.di_addr[NADDR - 2] * BLOCK_SIZE, SEEK_SET);
fread(f1, sizeof(f1), 1, fd);
block_num = f1[num - 4];
}
}
int free_space_firstBlock = BLOCK_SIZE - ifile.di_size % BLOCK_SIZE;
unsigned int num_block_needed;
if (len_content - free_space_firstBlock > 0)
{
num_block_needed = (len_content - free_space_firstBlock) / BLOCK_SIZE + 1;
}
else
{
num_block_needed = 0;
}
//检查是否有空闲
if (num_block_needed > superBlock.s_num_fblock)
{
printf("内存不够.\n");
return -1;
}
//3. 写入第一块.
if (ifile.di_addr[0] == -1)
{
find_free_block(block_num);
ifile.di_addr[0] = block_num;
fseek(fd, DATA_START + block_num * BLOCK_SIZE, SEEK_SET);
}
else
fseek(fd, DATA_START + block_num * BLOCK_SIZE + ifile.di_size % BLOCK_SIZE, SEEK_SET);
char data[BLOCK_SIZE];
if (num_block_needed == 0)
{
fwrite(content, len_content, 1, fd);
fseek(fd, DATA_START + block_num * BLOCK_SIZE, SEEK_SET);
fread(data, sizeof(data), 1, fd);
ifile.di_size += len_content;
}
else
{
fwrite(content, free_space_firstBlock, 1, fd);
fseek(fd, DATA_START + block_num * BLOCK_SIZE, SEEK_SET);
fread(data, sizeof(data), 1, fd);
ifile.di_size += free_space_firstBlock;
}
//4. 写入其他块,更新文件信息。
char write_buf[BLOCK_SIZE];
unsigned int new_block_addr = -1;
unsigned int content_write_pos = free_space_firstBlock;
//循环写入
if ((len_content + ifile.di_size) / BLOCK_SIZE + ((len_content + ifile.di_size) % BLOCK_SIZE == 0 ? 0 : 1) <= NADDR - 2) {
for (int i = 0; i < num_block_needed; i++)
{
find_free_block(new_block_addr);
if (new_block_addr == -1)return -1;
for (int j = 0; j < NADDR - 2; j++)
{
if (ifile.di_addr[j] == -1)
{
ifile.di_addr[j] = new_block_addr;
break;
}
}
memset(write_buf, 0, BLOCK_SIZE);
unsigned int tmp_counter = 0;
for (; tmp_counter < BLOCK_SIZE; tmp_counter++)
{
if (content[content_write_pos + tmp_counter] == '\0')
break;
write_buf[tmp_counter] = content[content_write_pos + tmp_counter];
}
content_write_pos += tmp_counter;
fseek(fd, DATA_START + new_block_addr * BLOCK_SIZE, SEEK_SET);
fwrite(write_buf, tmp_counter, 1, fd);
fseek(fd, DATA_START + new_block_addr * BLOCK_SIZE, SEEK_SET);
fread(data, sizeof(data), 1, fd);
ifile.di_size += tmp_counter;
}
}
else if ((len_content+ifile.di_size)/BLOCK_SIZE+((len_content + ifile.di_size) % BLOCK_SIZE == 0 ? 0 : 1)> NADDR - 2) {
for (int i = 0; i < NADDR - 2; i++)
{
if (ifile.di_addr[i] != -1)continue;
memset(write_buf, 0, BLOCK_SIZE);
new_block_addr = -1;
find_free_block(new_block_addr);
if (new_block_addr == -1)return -1;
ifile.di_addr[i] = new_block_addr;
unsigned int tmp_counter = 0;
for (; tmp_counter < BLOCK_SIZE; tmp_counter++)
{
if (content[content_write_pos + tmp_counter] == '\0') {
break;
}
write_buf[tmp_counter] = content[content_write_pos + tmp_counter];
}
content_write_pos += tmp_counter;
fseek(fd, DATA_START + new_block_addr * BLOCK_SIZE, SEEK_SET);
fwrite(write_buf, tmp_counter, 1, fd);
ifile.di_size += tmp_counter;
}
unsigned int f1[BLOCK_SIZE / sizeof(unsigned int)] = { 0 };
new_block_addr = -1;
find_free_block(new_block_addr);
if (new_block_addr == -1)return -1;
ifile.di_addr[NADDR - 2] = new_block_addr;
for (int i = 0;i < BLOCK_SIZE / sizeof(unsigned int);i++)
{
new_block_addr = -1;
find_free_block(new_block_addr);
if (new_block_addr == -1)return -1;
else
f1[i] = new_block_addr;
}
fseek(fd, DATA_START + ifile.di_addr[4] * BLOCK_SIZE, SEEK_SET);
fwrite(f1, sizeof(f1), 1, fd);
bool flag = 0;
for (int j = 0; j < BLOCK_SIZE / sizeof(int); j++) {
fseek(fd, DATA_START + f1[j] * BLOCK_SIZE, SEEK_SET);
unsigned int tmp_counter = 0;
for (; tmp_counter < BLOCK_SIZE; tmp_counter++)
{
if (content[content_write_pos + tmp_counter] == '\0') {
//tmp_counter--;
flag = 1;
break;
}
write_buf[tmp_counter] = content[content_write_pos + tmp_counter];
}
content_write_pos += tmp_counter;
fwrite(write_buf, tmp_counter, 1, fd);
ifile.di_size += tmp_counter;
if (flag == 1) break;
}
}
time_t t = time(0);
strftime(ifile.time, sizeof(ifile.time), "%Y/%m/%d %X", localtime(&t));
ifile.time[64] = 0;
fseek(fd, INODE_START + ifile.i_ino * INODE_SIZE, SEEK_SET);
fwrite(&ifile, sizeof(inode), 1, fd);
//5.更新超级块
fseek(fd, BLOCK_SIZE, SEEK_SET);
fwrite(&superBlock, sizeof(superBlock), 1, fd);
return len_content;
};
//输出文件信息
void PrintFile(inode& ifile)
{
//权限检测
if (userID == ifile.di_uid)
{
if (!(ifile.permission & OWN_R)) {
printf("没有读取权限.\n");
return;
}
}
else if (users.groupID[userID] == ifile.di_grp) {
if (!(ifile.permission & GRP_R)) {
printf("没有读取权限.\n");
return;
}
}
else {
if (!(ifile.permission & ELSE_R)) {
printf("没有读取权限.\n");
return;
}
}
int block_num = ifile.di_size / BLOCK_SIZE + 1;
int print_line_num = 0; //16 bytes 每一行.
//从块中读取文件
char stack[BLOCK_SIZE];
if (block_num <= NADDR - 2)
{
for (int i = 0; i < block_num; i++)
{
fseek(fd, DATA_START + ifile.di_addr[i] * BLOCK_SIZE, SEEK_SET);
fread(stack, sizeof(stack), 1, fd);
for (int j = 0; j < BLOCK_SIZE; j++)
{
if (stack[j] == '\0')break;
if (j % 16 == 0)
{
printf("\n");
printf("%d\t", ++print_line_num);
}
printf("%c", stack[j]);
}
}
}
else if (block_num > NADDR - 2) {
for (int i = 0; i < NADDR - 2; i++)
{
fseek(fd, DATA_START + ifile.di_addr[i] * BLOCK_SIZE, SEEK_SET);
fread(stack, sizeof(stack), 1, fd);
for (int j = 0; j < BLOCK_SIZE; j++)
{
if (stack[j] == '\0')break;
if (j % 16 == 0)
{
printf("\n");
printf("%d\t", ++print_line_num);
}
printf("%c", stack[j]);
}
}
unsigned int f1[BLOCK_SIZE / sizeof(unsigned int)] = { 0 };
fseek(fd, DATA_START + ifile.di_addr[NADDR - 2] * BLOCK_SIZE, SEEK_SET);
fread(f1, sizeof(f1), 1, fd);
for (int i = 0; i < block_num - (NADDR - 2); i++) {
fseek(fd, DATA_START + f1[i] * BLOCK_SIZE, SEEK_SET);
fread(stack, sizeof(stack), 1, fd);
for (int j = 0; j < BLOCK_SIZE; j++)
{
if (stack[j] == '\0')break;
if (j % 16 == 0)
{
printf("\n");
printf("%d\t", ++print_line_num);
}
printf("%c", stack[j]);
}
}
}
printf("\n\n\n");
};
//创建新目录,新目录包含. ..
bool MakeDir(const char* dirname)
{
//参数检测
if (dirname == NULL || strlen(dirname) > FILE_NAME_LENGTH)
{
printf("不合法的目录名.\n");
return false;
}
// 1. 检查inode是否用光了。
if (superBlock.s_num_fblock <= 0 || superBlock.s_num_finode <= 0)
{
printf("没有足够空间创建目录了.\n");
return false;
}
int new_ino = 0;
unsigned int new_block_addr = 0;
for (; new_ino < INODE_NUM; new_ino++)
{
if (inode_bitmap[new_ino] == 0)
{
break;
}
}
find_free_block(new_block_addr);
if (new_block_addr == -1) return false;
if (new_ino == INODE_NUM || new_block_addr == BLOCK_NUM)
{
printf("文件创建错误:剩余空间不足\n");
return false;
}
//2. 检查目录名在当前目录是否有重名.
for (int i = 0; i < DIRECTORY_NUM; i++)
{
if (strcmp(currentDirectory.fileName[i], dirname) == 0)
{
inode* tmp_file_inode = new inode;
int tmp_file_ino = currentDirectory.inodeID[i];
fseek(fd, INODE_START + tmp_file_ino * INODE_SIZE, SEEK_SET);
fread(tmp_file_inode, sizeof(inode), 1, fd);
if (tmp_file_inode->di_mode == 1) continue;
else {
printf("文件创建错误:文件名 '%s' 已经被使用了。\n", currentDirectory.fileName[i]);
return false;
}
}
}
//3. 检查当前目录项是否太多了.
int itemCounter = 0;
for (int i = 0; i < DIRECTORY_NUM; i++)
{
if (strlen(currentDirectory.fileName[i]) > 0)
{
itemCounter++;
}
}
if (itemCounter >= DIRECTORY_NUM)
{
printf("文件创建错误:当前文件夹中存在太多文件或文件夹。\n");
return false;
}
//4. 创建新inode.
inode idir_tmp;
idir_tmp.i_ino = new_ino;
idir_tmp.di_number = 1;
idir_tmp.di_mode = 0; //0 代表目录
idir_tmp.di_size = sizeof(directory);
memset(idir_tmp.di_addr, -1, sizeof(unsigned int) * NADDR);
idir_tmp.di_addr[0] = new_block_addr;
idir_tmp.di_uid = userID;
idir_tmp.di_grp = users.groupID[userID];
time_t t = time(0);
strftime(idir_tmp.time, sizeof(idir_tmp.time), "%Y/%m/%d %X", localtime(&t));
idir_tmp.time[64] = 0;
idir_tmp.icount = 0;
idir_tmp.permission = MAX_PERMISSION;
fseek(fd, INODE_START + new_ino * INODE_SIZE, SEEK_SET);
fwrite(&idir_tmp, sizeof(inode), 1, fd);
//5. 创建目录文件.
directory tmp_dir;
memset(tmp_dir.fileName, 0, sizeof(char) * DIRECTORY_NUM * FILE_NAME_LENGTH);
memset(tmp_dir.inodeID, -1, sizeof(unsigned int) * DIRECTORY_NUM);
strcpy(tmp_dir.fileName[0], ".");
tmp_dir.inodeID[0] = new_ino;
strcpy(tmp_dir.fileName[1], "..");
tmp_dir.inodeID[1] = currentDirectory.inodeID[0];
fseek(fd, DATA_START + new_block_addr * BLOCK_SIZE, SEEK_SET);
fwrite(&tmp_dir, sizeof(directory), 1, fd);
//6. 更新映射表.
inode_bitmap[new_ino] = 1;
fseek(fd, 2 * BLOCK_SIZE, SEEK_SET);
fwrite(inode_bitmap, sizeof(unsigned short) * INODE_NUM, 1, fd);
//7. 更新目录.
int pos_directory_inode = 0;
pos_directory_inode = currentDirectory.inodeID[0]; //"."
inode tmp_directory_inode;
fseek(fd, INODE_START + pos_directory_inode * INODE_SIZE, SEEK_SET);
fread(&tmp_directory_inode, sizeof(inode), 1, fd);
for (int i = 2; i < DIRECTORY_NUM; i++)
{
if (strlen(currentDirectory.fileName[i]) == 0)
{
strcat(currentDirectory.fileName[i], dirname);
currentDirectory.inodeID[i] = new_ino;
break;
}
}
fseek(fd, DATA_START + tmp_directory_inode.di_addr[0] * BLOCK_SIZE, SEEK_SET);
fwrite(¤tDirectory, sizeof(directory), 1, fd);
directory tmp_directory = currentDirectory;
int tmp_pos_directory_inode = pos_directory_inode;
while (true)
{
tmp_directory_inode.di_number++;
fseek(fd, INODE_START + tmp_pos_directory_inode * INODE_SIZE, SEEK_SET);
fwrite(&tmp_directory_inode, sizeof(inode), 1, fd);
if (tmp_directory.inodeID[1] == tmp_directory.inodeID[0])
{
break;
}
tmp_pos_directory_inode = tmp_directory.inodeID[1]; //".."
fseek(fd, INODE_START + tmp_pos_directory_inode * INODE_SIZE, SEEK_SET);
fread(&tmp_directory_inode, sizeof(inode), 1, fd);
fseek(fd, DATA_START + tmp_directory_inode.di_addr[0] * BLOCK_SIZE, SEEK_SET);
fread(&tmp_directory, sizeof(directory), 1, fd);
}
// 8. 更新超级块.
superBlock.s_num_finode--;
fseek(fd, BLOCK_SIZE, SEEK_SET);
fwrite(&superBlock, sizeof(filsys), 1, fd);
return true;
};
//删除一个目录和目录下的所有文件
bool RemoveDir(const char* dirname)
{
if (dirname == NULL || strlen(dirname) > FILE_NAME_LENGTH)
{
printf("目录不合法.\n");
return false;
}
//1. 检查目录是否存在
int pos_in_directory = 0;
int tmp_dir_ino;
inode tmp_dir_inode;
do {
pos_in_directory++;
for (; pos_in_directory < DIRECTORY_NUM; pos_in_directory++)
{
if (strcmp(currentDirectory.fileName[pos_in_directory], dirname) == 0)
{
break;
}
}
if (pos_in_directory == DIRECTORY_NUM)
{
printf("没有找到该目录.\n");
return false;
}
// 2. 查看inode是否是文件.
tmp_dir_ino = currentDirectory.inodeID[pos_in_directory];
fseek(fd, INODE_START + tmp_dir_ino * INODE_SIZE, SEEK_SET);
fread(&tmp_dir_inode, sizeof(inode), 1, fd);
//Directory check
} while (tmp_dir_inode.di_mode == 1);
//3. 权限检
if (userID == tmp_dir_inode.di_uid)
{
if (!(tmp_dir_inode.permission & OWN_E)) {
printf("权限不够.\n");
return false;
}
}
else if (users.groupID[userID] == tmp_dir_inode.di_grp) {
if (!(tmp_dir_inode.permission & GRP_E)) {
printf("权限不够.\n");
return false;
}
}
else {
if (!(tmp_dir_inode.permission & ELSE_E)) {
printf("权限不够.\n");
return false;
}
}
//4. 开始删除
if (tmp_dir_inode.icount > 0) {
tmp_dir_inode.icount--;
fseek(fd, INODE_START + tmp_dir_inode.i_ino * INODE_SIZE, SEEK_SET);
fwrite(&tmp_dir_inode, sizeof(inode), 1, fd);
//更新目录
int pos_directory_inode = currentDirectory.inodeID[0]; //"."
inode tmp_directory_inode;
fseek(fd, INODE_START + pos_directory_inode * INODE_SIZE, SEEK_SET);
fread(&tmp_directory_inode, sizeof(inode), 1, fd);
memset(currentDirectory.fileName[pos_in_directory], 0, FILE_NAME_LENGTH);
currentDirectory.inodeID[pos_in_directory] = -1;
fseek(fd, DATA_START + tmp_directory_inode.di_addr[0] * BLOCK_SIZE, SEEK_SET);
fwrite(¤tDirectory, sizeof(directory), 1, fd);
directory tmp_directory = currentDirectory;
int tmp_pos_directory_inode = pos_directory_inode;
while (true)
{
tmp_directory_inode.di_number--;
fseek(fd, INODE_START + tmp_pos_directory_inode * INODE_SIZE, SEEK_SET);
fwrite(&tmp_directory_inode, sizeof(inode), 1, fd);
if (tmp_directory.inodeID[1] == tmp_directory.inodeID[0])
{
break;
}
tmp_pos_directory_inode = tmp_directory.inodeID[1]; //".."
fseek(fd, INODE_START + tmp_pos_directory_inode * INODE_SIZE, SEEK_SET);
fread(&tmp_directory_inode, sizeof(inode), 1, fd);
fseek(fd, DATA_START + tmp_directory_inode.di_addr[0] * BLOCK_SIZE, SEEK_SET);
fread(&tmp_directory, sizeof(directory), 1, fd);
}
return true;
}
directory tmp_dir;
fseek(fd, DATA_START + tmp_dir_inode.di_addr[0] * BLOCK_SIZE, SEEK_SET);
fread(&tmp_dir, sizeof(directory), 1, fd);
//查找所有的子文件目录,并删除.
inode tmp_sub_inode;
char tmp_sub_filename[FILE_NAME_LENGTH];
memset(tmp_sub_filename, 0, FILE_NAME_LENGTH);
for (int i = 2; i < DIRECTORY_NUM; i++)
{
if (strlen(tmp_dir.fileName[i]) > 0)
{
strcpy(tmp_sub_filename, tmp_dir.fileName[i]);
fseek(fd, INODE_START + tmp_dir.inodeID[i] * INODE_SIZE, SEEK_SET);
fread(&tmp_sub_inode, sizeof(inode), 1, fd);
directory tmp_swp;
tmp_swp = currentDirectory;
currentDirectory = tmp_dir;
tmp_dir = tmp_swp;
if (tmp_sub_inode.di_mode == 1)
{
DeleteFile(tmp_sub_filename);
}
else if (tmp_sub_inode.di_mode == 0)
{
RemoveDir(tmp_sub_filename);
}
tmp_swp = currentDirectory;
currentDirectory = tmp_dir;
tmp_dir = tmp_swp;
}
}
//5.将inode赋为0.
int tmp_fill[sizeof(inode)];
memset(tmp_fill, 0, sizeof(inode));
fseek(fd, INODE_START + tmp_dir_ino * INODE_SIZE, SEEK_SET);
fwrite(&tmp_fill, sizeof(inode), 1, fd);
//6. 更新映射
inode_bitmap[tmp_dir_ino] = 0;
fseek(fd, 2 * BLOCK_SIZE, SEEK_SET);
fwrite(&inode_bitmap, sizeof(unsigned short) * INODE_NUM, 1, fd);
for (int i = 0; i < (tmp_dir_inode.di_size / BLOCK_SIZE + 1); i++)
{
recycle_block(tmp_dir_inode.di_addr[i]);
}
//7. 更新目录
int pos_directory_inode = currentDirectory.inodeID[0]; //"."
inode tmp_directory_inode;
fseek(fd, INODE_START + pos_directory_inode * INODE_SIZE, SEEK_SET);
fread(&tmp_directory_inode, sizeof(inode), 1, fd);
memset(currentDirectory.fileName[pos_in_directory], 0, FILE_NAME_LENGTH);
currentDirectory.inodeID[pos_in_directory] = -1;
fseek(fd, DATA_START + tmp_directory_inode.di_addr[0] * INODE_SIZE, SEEK_SET);
fwrite(¤tDirectory, sizeof(directory), 1, fd);
directory tmp_directory = currentDirectory;
int tmp_pos_directory_inode = pos_directory_inode;
while (true)
{
tmp_directory_inode.di_number--;
fseek(fd, INODE_START + tmp_pos_directory_inode * INODE_SIZE, SEEK_SET);
fwrite(&tmp_directory_inode, sizeof(inode), 1, fd);
if (tmp_directory.inodeID[1] == tmp_directory.inodeID[0])
{
break;
}
tmp_pos_directory_inode = tmp_directory.inodeID[1]; //".."
fseek(fd, INODE_START + tmp_pos_directory_inode * INODE_SIZE, SEEK_SET);
fread(&tmp_directory_inode, sizeof(inode), 1, fd);
fseek(fd, DATA_START + tmp_directory_inode.di_addr[0] * BLOCK_SIZE, SEEK_SET);
fread(&tmp_directory, sizeof(directory), 1, fd);
}
//8 更新超级块
superBlock.s_num_finode++;
fseek(fd, BLOCK_SIZE, SEEK_SET);
fwrite(&superBlock, sizeof(filsys), 1, fd);
return true;
};
//打开一个目录
bool OpenDir(const char* dirname)
{
//参数检测
if (dirname == NULL || strlen(dirname) > FILE_NAME_LENGTH)
{
printf("不合法名称.\n");
return false;
}
//1. 检查是否存在该目录.
int pos_in_directory = 0;
inode tmp_dir_inode;
int tmp_dir_ino;
do {
for (; pos_in_directory < DIRECTORY_NUM; pos_in_directory++)
{
if (strcmp(currentDirectory.fileName[pos_in_directory], dirname) == 0)
{
break;
}
}
if (pos_in_directory == DIRECTORY_NUM)
{
printf("删除错误:文件夹不存在。\n");
return false;
}
//2. 查找inode,查看是否为目录.
tmp_dir_ino = currentDirectory.inodeID[pos_in_directory];
fseek(fd, INODE_START + tmp_dir_ino * INODE_SIZE, SEEK_SET);
fread(&tmp_dir_inode, sizeof(inode), 1, fd);
} while (tmp_dir_inode.di_mode == 1);
if (userID == tmp_dir_inode.di_uid)
{
if (tmp_dir_inode.permission & OWN_E != OWN_E) {
printf("权限不够.\n");
return NULL;
}
}
else if (users.groupID[userID] == tmp_dir_inode.di_grp) {
if (tmp_dir_inode.permission & GRP_E != GRP_E) {
printf("权限不够.\n");
return NULL;
}
}
else {
if (tmp_dir_inode.permission & ELSE_E != ELSE_E) {
printf("权限不够.\n");
return NULL;
}
}
//3. 更新当前目录.
directory new_current_dir;
fseek(fd, DATA_START + tmp_dir_inode.di_addr[0] * BLOCK_SIZE, SEEK_SET);
fread(&new_current_dir, sizeof(directory), 1, fd);
currentDirectory = new_current_dir;
if (dirname[0] == '.' && dirname[1] == 0) {
dir_pointer;
}
else if (dirname[0] == '.' && dirname[1] == '.' && dirname[2] == 0) {
if (dir_pointer != 0) dir_pointer--;
}
else {
for (int i = 0; i < 14; i++) {
ab_dir[dir_pointer][i] = dirname[i];
}
dir_pointer++;
}
return true;
};
//显示当前目录下的文件信息
void List()
{
printf("\n name\tuser\tgroup\tinodeID\tIcount\tsize\tpermission\ttime\n");
for (int i = 0; i < DIRECTORY_NUM; i++)
{
if (strlen(currentDirectory.fileName[i]) > 0)
{
inode tmp_inode;
fseek(fd, INODE_START + currentDirectory.inodeID[i] * INODE_SIZE, SEEK_SET);
fread(&tmp_inode, sizeof(inode), 1, fd);
const char* tmp_type = tmp_inode.di_mode == 0 ? "d" : "-";
const char* tmp_user = users.userName[tmp_inode.di_uid];
const int tmp_grpID = tmp_inode.di_grp;
printf("%10s\t%s\t%d\t%d\t%d\t%u\t%s", currentDirectory.fileName[i], tmp_user, tmp_grpID, tmp_inode.i_ino, tmp_inode.icount, tmp_inode.di_size, tmp_type);
for (int x = 8; x > 0; x--) {
if (tmp_inode.permission & (1 << x)) {
if ((x + 1) % 3 == 0) printf("r");
else if ((x + 1) % 3 == 2) printf("w");
else printf("x");
}
else printf("-");
}
if(tmp_inode.permission & 1) printf("x\t");
else printf("-\t");
printf("%s\n", tmp_inode.time);
}
}
printf("\n\n");
}
//显示绝对目录.
void Ab_dir() {
for (int i = 0; i < dir_pointer; i++)
printf("%s/", ab_dir[i]);
printf("\n");
}
//修改文件权限
void Chmod(char* filename) {
printf("0=文件,1=目录,请输入:");
int tt;
scanf("%d", &tt);
if (filename == NULL || strlen(filename) > FILE_NAME_LENGTH)
{
printf("不合法.\n");
return;
}
//1. 检查是否存在.
int pos_in_directory = -1;
inode* tmp_file_inode = new inode;
do {
pos_in_directory++;
for (; pos_in_directory < DIRECTORY_NUM; pos_in_directory++)
{
if (strcmp(currentDirectory.fileName[pos_in_directory], filename) == 0)
{
break;
}
}
if (pos_in_directory == DIRECTORY_NUM)
{
printf("没有找到.\n");
return;
}
//2. 检查是否存在目录.
int tmp_file_ino = currentDirectory.inodeID[pos_in_directory];
fseek(fd, INODE_START + tmp_file_ino * INODE_SIZE, SEEK_SET);
fread(tmp_file_inode, sizeof(inode), 1, fd);
} while (tmp_file_inode->di_mode == tt);
printf("请输入 0&1 串给予权限\n");
printf("格式: rwerwerwe\n");
char str[10];
scanf("%s", &str);
if (userID == tmp_file_inode->di_uid)
{
if (!(tmp_file_inode->permission & OWN_E)) {
printf("权限不够.\n");
return;
}
}
else if (users.groupID[userID] == tmp_file_inode->di_grp) {
if (!(tmp_file_inode->permission & GRP_E)) {
printf("权限不够.\n");
return;
}
}
else {
if (!(tmp_file_inode->permission & ELSE_E)) {
printf("权限不够.\n");
return;
}
}
int temp = 0;
for (int i = 0; i < 8; i++) {
if (str[i] == '1')
temp += 1 << (8 - i);
}
if (str[8] == '1') temp += 1;
tmp_file_inode->permission = temp;
fseek(fd, INODE_START + tmp_file_inode->i_ino * INODE_SIZE, SEEK_SET);
fwrite(tmp_file_inode, sizeof(inode), 1, fd);
return;
}
//改变文件所属
void Chown(char* filename) {
printf("0=文件,1=目录,请选择:");
int tt;
scanf("%d", &tt);
//参数检测
if (filename == NULL || strlen(filename) > FILE_NAME_LENGTH)
{
printf("参数不合法.\n");
return;
}
// 1. 检查文件是否存在.
int pos_in_directory = -1;
inode* tmp_file_inode = new inode;
do {
pos_in_directory++;
for (; pos_in_directory < DIRECTORY_NUM; pos_in_directory++)
{
if (strcmp(currentDirectory.fileName[pos_in_directory], filename) == 0)
{
break;
}
}
if (pos_in_directory == DIRECTORY_NUM)
{
printf("Not found.\n");
return;
}
int tmp_file_ino = currentDirectory.inodeID[pos_in_directory];
fseek(fd, INODE_START + tmp_file_ino * INODE_SIZE, SEEK_SET);
fread(tmp_file_inode, sizeof(inode), 1, fd);
} while (tmp_file_inode->di_mode == tt);
if (userID == tmp_file_inode->di_uid)
{
if (!(tmp_file_inode->permission & OWN_E)) {
printf("权限不够.\n");
return;
}
}
else if (users.groupID[userID] == tmp_file_inode->di_grp) {
if (!(tmp_file_inode->permission & GRP_E)) {
printf("权限不够.\n");
return;
}
}
else {
if (!(tmp_file_inode->permission & ELSE_E)) {
printf("权限不够.\n");
return;
}
}
printf("请输入用户名:");
char str[USER_NAME_LENGTH];
int i;
scanf("%s", str);
for (i = 0; i < ACCOUNT_NUM; i++) {
if (strcmp(users.userName[i], str) == 0) break;
}
if (i == ACCOUNT_NUM) {
printf("不合法用户!\n");
return;
}
tmp_file_inode->di_uid = i;
fseek(fd, INODE_START + tmp_file_inode->i_ino * INODE_SIZE, SEEK_SET);
fwrite(tmp_file_inode, sizeof(inode), 1, fd);
return;
}
//改变文件所属组.
void Chgrp(char* filename) {
printf("0=文件,1=目录,请选择:");
int tt;
scanf("%d", &tt);
if (filename == NULL || strlen(filename) > FILE_NAME_LENGTH)
{
printf("不合法.\n");
return;
}
int pos_in_directory = -1;
inode* tmp_file_inode = new inode;
do {
pos_in_directory++;
for (; pos_in_directory < DIRECTORY_NUM; pos_in_directory++)
{
if (strcmp(currentDirectory.fileName[pos_in_directory], filename) == 0)
{
break;
}
}
if (pos_in_directory == DIRECTORY_NUM)
{
printf("Not found.\n");
return;
}
int tmp_file_ino = currentDirectory.inodeID[pos_in_directory];
fseek(fd, INODE_START + tmp_file_ino * INODE_SIZE, SEEK_SET);
fread(tmp_file_inode, sizeof(inode), 1, fd);
} while (tmp_file_inode->di_mode == tt);
if (userID == tmp_file_inode->di_uid)
{
if (!(tmp_file_inode->permission & OWN_E)) {
printf("权限不够.\n");
return;
}
}
else if (users.groupID[userID] == tmp_file_inode->di_grp) {
if (!(tmp_file_inode->permission & GRP_E)) {
printf("权限不够.\n");
return;
}
}
else {
if (!(tmp_file_inode->permission & ELSE_E)) {
printf("权限不够.\n");
return;
}
}
printf("请输入组号:");
int ttt, i;
scanf("%d", &ttt);
for (i = 0; i < ACCOUNT_NUM; i++) {
if (users.groupID[i] == ttt) break;
}
if (i == ACCOUNT_NUM) {
printf("用户错误!\n");
return;
}
tmp_file_inode->di_grp = ttt;
fseek(fd, INODE_START + tmp_file_inode->i_ino * INODE_SIZE, SEEK_SET);
fwrite(tmp_file_inode, sizeof(inode), 1, fd);
return;
}
//修改密码
void Passwd() {
printf("请输入旧密码:");
char str[USER_PASSWORD_LENGTH];
scanf("%s", str);
str[USER_PASSWORD_LENGTH] = 0;
if (strcmp(users.password[userID], str) == 0) {
printf("请输入新密码:");
scanf("%s", str);
if (strcmp(users.password[userID], str) == 0) {
printf("两次密码相同!\n");
}
else {
strcpy(users.password[userID], str);
fseek(fd, DATA_START + BLOCK_SIZE, SEEK_SET);
fwrite(&users, sizeof(users), 1, fd);
printf("修改成功\n");
}
}
else {
printf("密码错误!!!\n");
}
}
//用户管理
void User_management() {
if (userID != 0) {
printf("只有管理员才可以管理用户!\n");
return;
}
printf("欢迎来到用户管理!\n");
char c;
scanf("%c", &c);
while (c != '0') {
printf("\n1.查看 2.创建 3.删除 0.保存 & 退出\n");
scanf("%c", &c);
switch (c) {
case '1':
for (int i = 0; i < ACCOUNT_NUM; i++) {
if (users.userName[i][0] != 0)
printf("%d\t%s\t%d\n", users.userID[i], users.userName[i], users.groupID[i]);
else break;
}
scanf("%c", &c);
break;
case '2':
int i;
for (i = 0; i < ACCOUNT_NUM; i++) {
if (users.userName[i][0] == 0) break;
}
if (i == ACCOUNT_NUM) {
printf("用户太多了!\n");
break;
}
printf("请输入用户名:");
char str[USER_NAME_LENGTH];
scanf("%s", str);
for (i = 0; i < ACCOUNT_NUM; i++) {
if (strcmp(users.userName[i], str) == 0) {
printf("已经有同名的用户名了!\n");
}
if (users.userName[i][0] == 0) {
strcpy(users.userName[i], str);
printf("请输入密码:");
scanf("%s", str);
strcpy(users.password[i], str);
printf("请输入 group ID:");
int t;
scanf("%d", &t);
scanf("%c", &c);
if (t > 0) {
users.groupID[i] = t;
printf("成功!\n");
}
else {
printf("创建失败!\n");
strcpy(users.userName[i], 0);
strcpy(users.password[i], 0);
}
break;
}
}
break;
case '3':
printf("请输入userID:");
int tmp;
scanf("%d", &tmp);scanf("%c", &c);
for (int j = tmp; j < ACCOUNT_NUM - 1; j++) {
strcpy(users.userName[j], users.userName[j + 1]);
strcpy(users.password[j], users.password[j + 1]);
users.groupID[j] = users.groupID[j+1];
}
printf("成功!\n");
}
}
fseek(fd, DATA_START + BLOCK_SIZE, SEEK_SET);
fwrite(&users, sizeof(users), 1, fd);
}
//对文件或目录重命名
void Rename(char* filename) {
printf("0=文件,1=目录,请选择:");
int tt;
scanf("%d", &tt);
if (filename == NULL || strlen(filename) > FILE_NAME_LENGTH)
{
printf("参数不合法.\n");
return;
}
int pos_in_directory = -1;
inode* tmp_file_inode = new inode;
do {
pos_in_directory++;
for (; pos_in_directory < DIRECTORY_NUM; pos_in_directory++)
{
if (strcmp(currentDirectory.fileName[pos_in_directory], filename) == 0)
{
break;
}
}
if (pos_in_directory == DIRECTORY_NUM)
{
printf("没有找到.\n");
return;
}
int tmp_file_ino = currentDirectory.inodeID[pos_in_directory];
fseek(fd, INODE_START + tmp_file_ino * INODE_SIZE, SEEK_SET);
fread(tmp_file_inode, sizeof(inode), 1, fd);
} while (tmp_file_inode->di_mode == tt);
printf("请输入新的用户名:");
char str[14];
scanf("%s", str);
str[14] = 0;
for (int i = 0; i < DIRECTORY_NUM; i++)
{
if (currentDirectory.inodeID[i] == tmp_file_inode->i_ino)
{
strcpy(currentDirectory.fileName[i], str);
break;
}
}
fseek(fd, DATA_START + tmp_file_inode->di_addr[0] * BLOCK_SIZE, SEEK_SET);
fwrite(¤tDirectory, sizeof(directory), 1, fd);
return;
}
//文件复制
bool Copy(char* filename, inode*& currentInode) {
currentInode = OpenFile(filename);
int block_num = currentInode->di_size / BLOCK_SIZE + 1;
//读取文件
char stack[BLOCK_SIZE];
char str[100000];
int cnt = 0;
if (block_num <= NADDR - 2)
{
for (int i = 0; i < block_num; i++)
{
if (currentInode->di_addr[i] == -1) break;
fseek(fd, DATA_START + currentInode->di_addr[i] * BLOCK_SIZE, SEEK_SET);
fread(stack, sizeof(stack), 1, fd);
for (int j = 0; j < BLOCK_SIZE; j++)
{
if (stack[j] == '\0') {
str[cnt] = 0;
break;
}
str[cnt++] = stack[j];
}
}
}
else if (block_num > NADDR - 2) {
for (int i = 0; i < NADDR - 2; i++)
{
fseek(fd, DATA_START + currentInode->di_addr[i] * BLOCK_SIZE, SEEK_SET);
fread(stack, sizeof(stack), 1, fd);
for (int j = 0; j < BLOCK_SIZE; j++)
{
if (stack[j] == '\0') {
str[cnt] = 0;
break;
}
str[cnt++] = stack[j];
}
}
unsigned int f1[BLOCK_SIZE / sizeof(unsigned int)] = { 0 };
fseek(fd, DATA_START + currentInode->di_addr[NADDR - 2] * BLOCK_SIZE, SEEK_SET);
fread(f1, sizeof(f1), 1, fd);
for (int i = 0; i < block_num - (NADDR - 2); i++) {
fseek(fd, DATA_START + f1[i] * BLOCK_SIZE, SEEK_SET);
fread(stack, sizeof(stack), 1, fd);
for (int j = 0; j < BLOCK_SIZE; j++)
{
if (stack[j] == '\0') {
str[cnt] = 0;
break;
}
str[cnt++] = stack[j];
}
}
}
int pos_in_directory = -1;
inode* tmp_file_inode = new inode;
do {
pos_in_directory++;
for (; pos_in_directory < DIRECTORY_NUM; pos_in_directory++)
{
if (strcmp(currentDirectory.fileName[pos_in_directory], filename) == 0)
{
break;
}
}
if (pos_in_directory == DIRECTORY_NUM)
{
printf("没有找到.\n");
return false;
}
int tmp_file_ino = currentDirectory.inodeID[pos_in_directory];
fseek(fd, INODE_START + tmp_file_ino * INODE_SIZE, SEEK_SET);
fread(tmp_file_inode, sizeof(inode), 1, fd);
} while (tmp_file_inode->di_mode == 0);
//权限检测
if (userID == tmp_file_inode->di_uid)
{
if (!(tmp_file_inode->permission & OWN_E)) {
printf("权限不够.\n");
return false;
}
}
else if (users.groupID[userID] == tmp_file_inode->di_grp) {
if (!(tmp_file_inode->permission & GRP_E)) {
printf("权限不够.\n");
return false;
}
}
else {
if (!(tmp_file_inode->permission & ELSE_E)) {
printf("权限不够.\n");
return false;
}
}
//取绝对地址
char absolute[1024];
int path_pos = 0;
printf("请输入绝对地址:");
scanf("%s", absolute);
char dirname[14];
int pos_dir = 0;
bool root = false;
inode dir_inode;
directory cur_dir;
int i;
for (i = 0; i < 5; i++)
{
dirname[i] = absolute[i];
}
dirname[i] = 0;
if (strcmp("root/", dirname) != 0)
{
printf("路径错误!\n");
return false;
}
fseek(fd, INODE_START, SEEK_SET);
fread(&dir_inode, sizeof(inode), 1, fd);
for (int i = 5; absolute[i] != '\n'; i++)
{
if (absolute[i] == '/')
{
dirname[pos_dir++] = 0;
pos_dir = 0;
fseek(fd, DATA_START + dir_inode.di_addr[0] * BLOCK_SIZE, SEEK_SET);
fread(&cur_dir, sizeof(directory), 1, fd);
int i;
for (i = 0; i < DIRECTORY_NUM; i++)
{
if (strcmp(cur_dir.fileName[i], dirname) == 0)
{
fseek(fd, INODE_START + cur_dir.inodeID[i] * INODE_SIZE, SEEK_SET);
fread(&dir_inode, sizeof(inode), 1, fd);
if (dir_inode.di_mode == 0)break;
}
}
if (i == DIRECTORY_NUM)
{
printf("路径错误!\n");
return false;
}
}
else
dirname[pos_dir++] = absolute[i];
}
//更新当前目录
fseek(fd, DATA_START + dir_inode.di_addr[0] * BLOCK_SIZE, SEEK_SET);
fread(&cur_dir, sizeof(directory), 1, fd);
for (i = 0; i < DIRECTORY_NUM; i++)
{
if (strlen(cur_dir.fileName[i]) == 0)
{
strcat(cur_dir.fileName[i], filename);
int new_ino = 0;
for (; new_ino < INODE_NUM; new_ino++)
{
if (inode_bitmap[new_ino] == 0)
{
break;
}
}
inode ifile_tmp;
ifile_tmp.i_ino = new_ino;
ifile_tmp.icount = 0;
ifile_tmp.di_uid = tmp_file_inode->di_uid;
ifile_tmp.di_grp = tmp_file_inode->di_grp;
ifile_tmp.di_mode = tmp_file_inode->di_mode;
memset(ifile_tmp.di_addr, -1, sizeof(unsigned int) * NADDR);
ifile_tmp.di_size = 0;
ifile_tmp.permission = tmp_file_inode->permission;
time_t t = time(0);
strftime(ifile_tmp.time, sizeof(ifile_tmp.time), "%Y/%m/%d %X", localtime(&t));
cur_dir.inodeID[i] = new_ino;
Write(ifile_tmp, str);
//Update bitmaps
inode_bitmap[new_ino] = 1;
fseek(fd, 2 * BLOCK_SIZE, SEEK_SET);
fwrite(inode_bitmap, sizeof(unsigned short) * INODE_NUM, 1, fd);
superBlock.s_num_finode--;
fseek(fd, BLOCK_SIZE, SEEK_SET);
fwrite(&superBlock, sizeof(filsys), 1, fd);
break;
}
}
if (i == DIRECTORY_NUM)
{
printf("No value iterms!\n");
return false;
}
fseek(fd, DATA_START + dir_inode.di_addr[0] * BLOCK_SIZE, SEEK_SET);
fwrite(&cur_dir, sizeof(directory), 1, fd);
dir_inode.di_number++;
fseek(fd, INODE_START + tmp_file_inode->i_ino*INODE_SIZE, SEEK_SET);
fwrite(tmp_file_inode, sizeof(inode), 1, fd);
return true;
}
//系统启动
void Sys_start() {
//载入文件系统
Mount();
printf("**************************************************************\n");
printf("* *\n");
printf("* 多用户文件管理系统 *\n");
printf("* *\n");
printf("**************************************************************\n");
}
//自定义不回显字符
int getch()
{
int c = 0;
struct termios org_opts, new_opts;
int res = 0;
res = tcgetattr(STDIN_FILENO, &org_opts);
assert(res == 0);
memcpy(&new_opts, &org_opts, sizeof(new_opts));
new_opts.c_lflag &= ~(ICANON | ECHO | ECHOE | ECHOK | ECHONL | ECHOPRT | ECHOKE | ICRNL);
tcsetattr(STDIN_FILENO, TCSANOW, &new_opts);
c = getchar();
res = tcsetattr(STDIN_FILENO, TCSANOW, &org_opts);
assert(res == 0);
if(c == '\n') c = '\r';
else if(c == 127) c = '\b';
return c;
}
void CommParser(inode*& currentInode)
{
char para1[11];
char para2[1024];
bool flag = false;
while (true)
{
unsigned int f1[BLOCK_SIZE / sizeof(unsigned int)] = { 0 };
fseek(fd, DATA_START + 8 * BLOCK_SIZE, SEEK_SET);
fread(f1, sizeof(f1), 1, fd);
memset(para1, 0, 11);
memset(para2, 0, 1024);
printf("%s>", userName);
scanf("%s", para1);
para1[10] = 0;
//选择功能
if (strcmp("ls", para1) == 0)//显示当前文件
{
flag = false;
List();
}
else if (strcmp("cp", para1) == 0) {//文件复制
flag = false;
scanf("%s", para2);
para2[1023] = 0; //安全保护
Copy(para2, currentInode);
}
else if (strcmp("mv", para1) == 0) {//重命名
flag = false;
scanf("%s", para2);
para2[1023] = 0; //安全保护
Rename(para2);
}
else if (strcmp("pwd", para1) == 0) {//显示当前目录
flag = false;
Ab_dir();
}
else if (strcmp("passwd", para1) == 0) {
flag = false;
Passwd();
}
else if (strcmp("chmod", para1) == 0) {//用户权限
flag = false;
scanf("%s", para2);
para2[1023] = 0;
Chmod(para2);
}
else if (strcmp("chown", para1) == 0) {//更改用户权限
flag = false;
scanf("%s", para2);
para2[1023] = 0;
Chown(para2);
}
else if (strcmp("chgrp", para1) == 0) {//更改所属组
flag = false;
scanf("%s", para2);
para2[1023] = 0;
Chgrp(para2);
}
else if (strcmp("info", para1) == 0) {
printf("系统信息:\n总共的block:%d\n 空闲block:%d\n总inode:%d\n剩余inode:%d\n\n", superBlock.s_num_block, superBlock.s_num_fblock, superBlock.s_num_inode, superBlock.s_num_finode);
for (int i = 0; i < 50; i++)
{
if (i>superBlock.special_free)printf("-1\t");
else printf("%d\t", superBlock.special_stack[i]);
if (i % 10 == 9)printf("\n");
}
printf("\n\n");
}
//创建文件
else if (strcmp("create", para1) == 0)
{
flag = false;
scanf("%s", para2);
para2[1023] = 0;
CreateFile(para2);
}
//删除文件
else if (strcmp("rm", para1) == 0)
{
flag = false;
scanf("%s", para2);
para2[1023] = 0;
DeleteFile(para2);
}
//打开文件
else if (strcmp("open", para1) == 0){
flag = true;
scanf("%s", para2);
para2[1023] = 0;
currentInode = OpenFile(para2);
}
//写文件
else if (strcmp("write", para1) == 0 && flag){
scanf("%s", para2);
para2[1023] = 0;
Write(*currentInode, para2);
}
//读文件
else if (strcmp("read", para1) == 0 && flag) {
PrintFile(*currentInode);
}
//打开一个目录
else if (strcmp("cd", para1) == 0){
flag = false;
scanf("%s", para2);
para2[1023] = 0;
OpenDir(para2);
}
//创建目录
else if (strcmp("mkdir", para1) == 0){
flag = false;
scanf("%s", para2);
para2[1023] = 0; //security protection
MakeDir(para2);
}
//删除目录
else if (strcmp("rmdir", para1) == 0){
flag = false;
scanf("%s", para2);
para2[1023] = 0; //security protection
RemoveDir(para2);
}
//登出系统
else if (strcmp("logout", para1) == 0){
flag = false;
Logout();
char tmp_userName[USER_NAME_LENGTH], tmp_userPassword[USER_PASSWORD_LENGTH * 5];
do {
memset(tmp_userName, 0, USER_NAME_LENGTH);
memset(tmp_userPassword, 0, USER_PASSWORD_LENGTH * 5);
printf("用户登录\n\n");
printf("用户名:\t");
scanf("%s", tmp_userName);
printf("密码:\t");
char c;
scanf("%c", &c);
int i = 0;
while (1) {
char ch;
ch = getch();
if (ch == '\b') {
if (i != 0) {
printf("\b \b");
i--;
}
else {
tmp_userPassword[i] = '\0';
}
}
else if (ch == '\r') {
tmp_userPassword[i] = '\0';
printf("\n\n");
break;
}
else {
putchar('*');
tmp_userPassword[i++] = ch;
}
}
} while (Login(tmp_userName, tmp_userPassword) != true);
}
//登录
else if (strcmp("su", para1) == 0){
Logout();
flag = false;
char para3[USER_PASSWORD_LENGTH * 5];
memset(para3, 0, USER_PASSWORD_LENGTH + 1);
scanf("%s", para2);
para2[1023] = 0;
printf("密码: ");
char c;
scanf("%c", &c);
int i = 0;
while (1) {
char ch;
ch = getch();
if (ch == '\b') {
if (i != 0) {
printf("\b \b");
i--;
}
}
else if (ch == '\r') {
para3[i] = '\0';
printf("\n\n");
break;
}
else {
putchar('*');
para3[i++] = ch;
}
}
para3[USER_PASSWORD_LENGTH] = 0; //安全保护
Login(para2, para3);
}
else if (strcmp("manage", para1) == 0) {
flag = false;
User_management();
}
//退出系统
else if (strcmp("quit", para1) == 0){
flag = false;
break;
}
//help
else{
flag = false;
Help();
}
}
};
void Help(){
printf("系统当前支持指令:\n");
printf("\t01.quit...........................退出系统\n");
printf("\t02.help...........................显示帮助信息\n");
printf("\t03.pwd............................显示当前目录\n");
printf("\t04.ls.............................列出文件或目录\n");
printf("\t05.cd + dirname...................cd到其他目录\n");
printf("\t06.mkdir + dirname................创建新目录\n");
printf("\t07.rmdir + dirname................删除目录\n");
printf("\t08.create + filename..............新建文件\n");
printf("\t09.open + filename................打开文件\n");
printf("\t10.read + filename................读取文件\n");
printf("\t11.write + content................写入文件\n");
printf("\t12.rm + filename..................删除文件\n");
printf("\t13.logout.........................退出当前用户\n");
printf("\t14.chmod + filename...............改变文件权限\n");
printf("\t15.chown + filename...............改变文件所有者\n");
printf("\t16.chgrp + filename...............改变所属组\n");
printf("\t17.mv + filename..................重命名\n");
printf("\t18.passwd.........................改密码\n");
printf("\t19.manage.........................用户管理界面\n");
};
int main()
{
memset(ab_dir, 0, sizeof(ab_dir));
dir_pointer = 0;
//先查找文件卷.
FILE* fs_test = fopen("root.tianye", "r");
if (fs_test == NULL)
{
printf("文件卷没找到... 请稍后,正在新建文件卷...\n\n");
Format();
}
Sys_start();
ab_dir[dir_pointer][0] = 'r';ab_dir[dir_pointer][1] = 'o';ab_dir[dir_pointer][2] = 'o';ab_dir[dir_pointer][3] = 't';ab_dir[dir_pointer][4] = '\0';
dir_pointer++;
//登录
char tmp_userName[USER_NAME_LENGTH];
char tmp_userPassword[USER_PASSWORD_LENGTH * 5];
do {
memset(tmp_userName, 0, USER_NAME_LENGTH);
memset(tmp_userPassword, 0, USER_PASSWORD_LENGTH * 5);
printf("用户登录\n\n");
printf("用户名:\t");
scanf("%s", tmp_userName);
printf("密码:\t");
char c;
scanf("%c", &c);
int i = 0;
while (1) {
char ch;
ch = getch();
if (ch == '\b') {
if (i != 0) {
printf("\b \b");
i--;
}
else {
tmp_userPassword[i] = '\0';
}
}
else if (ch == '\r') {
tmp_userPassword[i] = '\0';
printf("\n\n");
break;
}
else {
putchar('*');
tmp_userPassword[i++] = ch;
}
}
} while (Login(tmp_userName, tmp_userPassword) != true);
inode* currentInode = new inode;
CommParser(currentInode);
return 0;
}
| [
"typeme3@163.com"
] | typeme3@163.com |
2d5b9967b371d88f4cbccb3f786a0091ced74dce | fffc0e7860910ed1c7689b5c1349a35bdd5426da | /pitzDaily/100/p | 4dabb0df764655f05dc85debeb8a35eeb646d3b5 | [] | no_license | asAmrita/adjointShapeOptimization | 001fa7361c9a856dd0ebdf2b118af78c9fa4a5b4 | 2ffee0fc27832104ffc8535a784eba0e1e5d1e44 | refs/heads/master | 2020-07-31T12:33:51.409116 | 2019-09-28T15:06:34 | 2019-09-28T15:06:34 | 210,605,738 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 96,607 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: v1806 |
| \\ / A nd | Web: www.OpenFOAM.com |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "100";
object p;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 2 -2 0 0 0 0];
internalField nonuniform List<scalar>
6400
(
0.257061053697
0.256940073014
0.256861364005
0.256884776888
0.256889989922
0.256692987247
0.256113417636
0.255115578056
0.253710575656
0.251896833988
0.249803967818
0.247630545101
0.245467411123
0.243366429592
0.241376766087
0.239536531115
0.237872144737
0.236398424365
0.235119947594
0.234032448011
0.233124455488
0.232379166471
0.231776748345
0.231296962
0.230921615206
0.230636097355
0.230429457269
0.230293092915
0.23021892151
0.230198291761
0.230222632617
0.230285848541
0.230387348261
0.23053384196
0.230738535727
0.231018241648
0.231390828106
0.231875446015
0.232495072914
0.23328121014
0.23427644722
0.235533478718
0.237113160832
0.239081086746
0.24150444578
0.244446767283
0.2479578116
0.252058610446
0.256726113274
0.261883274376
0.267394893982
0.273071275237
0.278679743541
0.283966947819
0.288701511157
0.292701275568
0.295819463118
0.297928632941
0.299069868638
0.299722922531
0.299980243728
0.299563024964
0.2986509053
0.297517761914
0.296349830452
0.295284619503
0.29443293106
0.293867448567
0.29363238758
0.293744345813
0.294166901981
0.294831123707
0.295652341552
0.296537389567
0.297391453719
0.298127601699
0.29867839861
0.298996525808
0.299124840961
0.299194327337
0.257053358421
0.256925167409
0.256876644297
0.256875983978
0.256798547014
0.256522612285
0.255870632268
0.254788428928
0.253330208156
0.251527979173
0.249481002958
0.24732740001
0.245164006204
0.243060312431
0.241071992248
0.239239158395
0.237588111946
0.236132693815
0.234876131969
0.233812768131
0.232929850937
0.232209527588
0.231631159985
0.231173875199
0.230818851826
0.230550761389
0.230357914107
0.230231196171
0.230162506812
0.23014375981
0.230167307207
0.23022780083
0.23032463001
0.230463349561
0.230654984538
0.230914008855
0.2312575842
0.231707288365
0.232288381449
0.233029510683
0.233969105258
0.235157624059
0.23665450438
0.23852565248
0.240840282082
0.243665155135
0.247054168469
0.251033820781
0.25558791721
0.260645149785
0.266073474754
0.271683676272
0.277245320447
0.282512956722
0.287255405151
0.291266769996
0.294363827305
0.29648163516
0.297882803301
0.298776988117
0.299048626468
0.298682604478
0.297878382825
0.296849459808
0.295768646045
0.29477436963
0.293977473915
0.29345621598
0.293255302148
0.293396710824
0.293852986637
0.294557350193
0.295424374018
0.296358888081
0.297262778984
0.298044376316
0.298632173849
0.298978503248
0.299148488271
0.299296922959
0.257189823091
0.256991870331
0.2568703169
0.256728385004
0.256434996801
0.255905731956
0.255053718353
0.253827427025
0.252270832053
0.250434936108
0.248402045905
0.246275910247
0.24414831398
0.242091703602
0.240161253111
0.238395547258
0.236818430319
0.235440933279
0.23426344391
0.233277726058
0.232468950526
0.231817805299
0.231302767973
0.23090239185
0.230597294113
0.230371419982
0.230212298499
0.230110365375
0.230057818847
0.230047792541
0.230074410962
0.230133920902
0.230226189549
0.230355470602
0.230530324166
0.230764020911
0.231076046898
0.231485832016
0.232012104382
0.232682475014
0.233535054966
0.234617427536
0.235987122722
0.237710762333
0.239861479934
0.242512762634
0.245727661324
0.249543646638
0.253955103895
0.258898033946
0.264241314954
0.269791377039
0.275316668303
0.280571579025
0.285309442955
0.289288160796
0.292332844568
0.294551580856
0.296215337919
0.297287916773
0.297639595999
0.297396923305
0.296724875177
0.295805086668
0.29480770457
0.293876554615
0.293125719065
0.292635091185
0.292453672471
0.292614119761
0.293095770481
0.293834304773
0.294746702206
0.29574087116
0.296722173455
0.297603421525
0.298321193305
0.298844697235
0.299210407077
0.299501399489
0.257463246589
0.257187420237
0.25689483187
0.256479934608
0.255886461713
0.255065984241
0.253967908254
0.252559665207
0.250877758065
0.248983397313
0.246950704044
0.244861964909
0.242795404587
0.240817992058
0.238980819007
0.237318179728
0.235849650019
0.234582323085
0.233513069346
0.232630712407
0.231918202891
0.231354804095
0.23091824164
0.230586725631
0.230340624364
0.23016350228
0.230042425023
0.229967592278
0.229931604846
0.22992877817
0.229955009062
0.230008167784
0.230088529107
0.2301993945
0.230348357992
0.230549438879
0.230818066194
0.231167122248
0.231614797372
0.232188054048
0.232921304612
0.233858391682
0.235054169567
0.236575328521
0.238499052469
0.240907771819
0.243878407671
0.247465264105
0.251678817305
0.256465395344
0.261696963996
0.267174210131
0.27266315945
0.27790624005
0.282622778945
0.286561940809
0.289659809106
0.29215539763
0.294066136439
0.29521481379
0.295666623683
0.295538698058
0.294980746054
0.294162773679
0.293250956889
0.292390377233
0.291697405796
0.291254319069
0.29111480072
0.291319875769
0.291852296913
0.292650290273
0.293634873119
0.29471917691
0.295814943199
0.296842734663
0.297745886763
0.298497927333
0.299096591829
0.299616308027
0.257743400002
0.257325084437
0.256781399708
0.256062293658
0.255152493189
0.254030306125
0.252683298831
0.251092110999
0.2492850435
0.247323326543
0.245281078076
0.243231747129
0.241241325078
0.239365432986
0.237646299154
0.236111522256
0.234775257013
0.233640050611
0.232698956786
0.231937689579
0.231336843509
0.230874107135
0.230526378913
0.230271612153
0.230090215802
0.229965897379
0.229885894703
0.229840732968
0.229823609553
0.229829877577
0.229856841394
0.229903567591
0.229971012807
0.230063414888
0.230189899643
0.230361429243
0.230584823049
0.230870292144
0.2312364282
0.231706447687
0.23231044416
0.233087677826
0.234089185989
0.235380117798
0.237040470728
0.239161988176
0.241837720482
0.245142894309
0.249108182796
0.253692969294
0.258775328652
0.264147041236
0.269565529231
0.274748892907
0.279392030354
0.283315464101
0.286630412157
0.289365631073
0.291353101129
0.292586037458
0.293133636389
0.293106665751
0.292649703506
0.291925626418
0.291096306991
0.290307030635
0.289676784486
0.289291182859
0.289208098279
0.289475334195
0.290077958408
0.290957960075
0.292041076959
0.293245149679
0.294486476028
0.295689091087
0.296793818109
0.297764694788
0.298551578639
0.299244238221
0.257691331119
0.257078346031
0.256288072305
0.25530510488
0.25413827708
0.252773697753
0.251209610453
0.249456654174
0.247552921399
0.245553354553
0.243523802171
0.24153054309
0.239631344315
0.237871847549
0.236284872903
0.234890609756
0.233697504473
0.232703593235
0.231898226495
0.231264055894
0.230779236138
0.230419732415
0.230161499385
0.229982266333
0.229862803841
0.229787510171
0.229744450391
0.229725032818
0.229723350848
0.229735678093
0.229760261577
0.229797664003
0.229850849721
0.229926861787
0.230032765693
0.230170725139
0.230346364594
0.230571434822
0.230860276025
0.231231489722
0.231709836531
0.232328776703
0.233133799094
0.234186293668
0.235567016488
0.237375922676
0.239723067106
0.24270693468
0.246383083867
0.250725652834
0.255623665069
0.26085216539
0.266147623048
0.271209389925
0.275771660698
0.279805775817
0.283297950591
0.286092668267
0.288127004972
0.289415849358
0.290025444159
0.290065532821
0.289677763101
0.289020706439
0.288253797631
0.287523151055
0.286950968744
0.286627278867
0.286613552866
0.286963130503
0.287660928797
0.288651564415
0.289863831368
0.291217428673
0.292629179594
0.29402131486
0.295325995841
0.296494817099
0.297429040996
0.298246137835
0.256955253709
0.256237641512
0.255322453187
0.254176770284
0.252833660368
0.2512974443
0.249579496039
0.247714106804
0.245752995247
0.243750409546
0.241763575792
0.239849322236
0.238057030988
0.236424526351
0.234977388904
0.233729596482
0.232684470545
0.231835757333
0.231169068605
0.230663757042
0.230295230338
0.230037498384
0.229865520324
0.229756993145
0.229693497202
0.229660749174
0.229648231704
0.229648976637
0.229658626659
0.229674656001
0.229696931375
0.229729027615
0.229775465582
0.229837851472
0.229918436387
0.230022610008
0.230157327534
0.230330960937
0.230554026287
0.230840317719
0.231208648148
0.231685484997
0.232308807783
0.233133493959
0.2342374654
0.235726033673
0.237725214809
0.240357157801
0.243708845508
0.24776908262
0.252441399167
0.257470305593
0.262565783219
0.267459325833
0.272006305399
0.276111285504
0.279607355204
0.282391807639
0.284422630111
0.285714738756
0.286335284844
0.28639388306
0.286030550081
0.285401879839
0.284666929348
0.283973945547
0.283449350179
0.283188663967
0.28325431923
0.283701949105
0.284514932406
0.285640074535
0.287007214394
0.288534574789
0.290135493569
0.29172637713
0.293227751739
0.294581442853
0.295646495536
0.296576388878
0.255529412462
0.254823632979
0.253918923439
0.252718681773
0.251285157144
0.249648720264
0.247846291107
0.245928588522
0.243954827976
0.241981734491
0.240062888818
0.238247275878
0.236575856029
0.235079249837
0.233777104404
0.23267842201
0.231782179441
0.231078115869
0.230548000256
0.230167589283
0.229909259141
0.229745064647
0.229649314986
0.229600237682
0.229581087644
0.229579805481
0.22958817067
0.22960189037
0.229619103114
0.229638935632
0.229661927773
0.229688639719
0.229721684065
0.22976577329
0.2298250613
0.229904097341
0.230008208642
0.230143582798
0.230317626705
0.230539798828
0.230823101778
0.231186569952
0.231659292052
0.232286680394
0.233139044199
0.234322034596
0.235975693988
0.238244163335
0.241252375885
0.244999522497
0.249395480977
0.25414986064
0.258975125827
0.263703688869
0.268187528041
0.272205231357
0.275615209422
0.278318993557
0.280275942314
0.281503172651
0.282069166929
0.28208369313
0.28168624326
0.281033141188
0.280285138401
0.279594856056
0.279095533526
0.278890705066
0.279040124945
0.279595871795
0.280540184695
0.281821741049
0.28336792576
0.28509124448
0.28689801205
0.288696416215
0.290394162624
0.291926606594
0.293116258775
0.294157233583
0.253625087175
0.253017588061
0.252196678367
0.251010035455
0.249557159415
0.247888842674
0.246065589042
0.244150892461
0.242208512085
0.240297147392
0.238468911226
0.236767577017
0.235227405599
0.233872838884
0.232718504302
0.231769261118
0.231020265903
0.230457305258
0.230058045664
0.229794384438
0.229635678848
0.229552342226
0.229519003642
0.229515901279
0.229529486959
0.229551308615
0.22957507823
0.22959600551
0.229612673695
0.229626951639
0.229641562456
0.229658955226
0.229681832611
0.22971359102
0.229758009795
0.229819321708
0.22990212271
0.230011257939
0.230151960365
0.230330400043
0.230554828477
0.230837544285
0.231198398813
0.231671516164
0.232314714509
0.233228187295
0.234565452902
0.236486796562
0.23915197371
0.242555580057
0.246595483618
0.250988566747
0.255519300777
0.260031345551
0.264315484356
0.268154142237
0.271391601635
0.273930106709
0.275731558124
0.27681520567
0.277250799887
0.27714844355
0.276647706485
0.275905424562
0.275085382749
0.274346646323
0.27383377266
0.273667466055
0.27390021248
0.274568726472
0.275655202445
0.277109962188
0.278854295471
0.280791069211
0.28281656915
0.28482909804
0.286723015724
0.288429703514
0.289737376669
0.290885576253
0.251562989234
0.25105985621
0.250312075376
0.249159598274
0.247731311156
0.246083167295
0.244289824539
0.242422948815
0.240549559588
0.238728977414
0.237011512202
0.235437041387
0.23403500548
0.232825217672
0.2318183241
0.231015617263
0.230408618356
0.229979193014
0.229700610558
0.22954052475
0.229465866841
0.22944713819
0.22946120643
0.22949174561
0.229525775661
0.229554473553
0.229575897029
0.229591524869
0.229603072033
0.229612492551
0.229621726269
0.229632751741
0.229648005155
0.229670573129
0.229704119332
0.229752748968
0.229820731501
0.229912240935
0.230031302114
0.230182083464
0.230369624834
0.230601182884
0.230888475755
0.231255205494
0.23174480989
0.232447634896
0.233527545938
0.235145979491
0.237467080022
0.240480934677
0.244055100996
0.24806134483
0.252250273265
0.256468320192
0.260465362703
0.264028334465
0.267000201768
0.269284264194
0.270844528365
0.271702011164
0.271927485458
0.271631049503
0.270952243054
0.27004831536
0.269086644006
0.268233731532
0.26765060274
0.267481325999
0.26777135798
0.268541276706
0.269776903054
0.271423076816
0.273385026615
0.275550545575
0.277803822055
0.280032978935
0.282119618875
0.283994054301
0.285411940607
0.286661261467
0.249572589035
0.249114471446
0.248393570121
0.247273802663
0.24589164792
0.244296150146
0.242568086237
0.24078193309
0.239005839617
0.237298218354
0.235706755818
0.234267809842
0.233007176431
0.231941285946
0.23107768599
0.230414637654
0.229940228823
0.229631968568
0.229458667975
0.229384947829
0.229376488723
0.229405470951
0.229450983692
0.229496263776
0.229532330418
0.229558079828
0.229575560742
0.229587148377
0.229594797101
0.229600187175
0.229604865564
0.229610538115
0.229619353959
0.229634150199
0.229658505973
0.229696553528
0.229752610894
0.229830757244
0.229934572692
0.23006718891
0.230231741734
0.230432510778
0.230675227342
0.230977321308
0.231371282336
0.231933609771
0.232819797448
0.234176169496
0.236111287532
0.238690920792
0.241812048027
0.245396931903
0.249222975414
0.253063771753
0.256685410508
0.259882225487
0.262500025002
0.264444668414
0.265682603361
0.266236456924
0.266177375707
0.26561377481
0.264683115273
0.263540459083
0.262355588678
0.261305279582
0.260590910888
0.26038488453
0.260698122912
0.261527923506
0.262890083492
0.264726374034
0.266914000678
0.269315374382
0.271797348442
0.274237063761
0.276505079312
0.278534902964
0.280051791186
0.281395716933
0.247684092619
0.247232379612
0.246515248624
0.245429032418
0.244104696786
0.2425814752
0.240941724512
0.239258430098
0.237598463341
0.236017875989
0.234561130959
0.233261192927
0.232140785896
0.23121364175
0.230484853628
0.229950036564
0.229593849023
0.229389820955
0.22930325768
0.229296446103
0.229336090823
0.229395957516
0.229455254114
0.229503034607
0.229537381277
0.22956003472
0.229574085822
0.229582284962
0.229586726818
0.229588981095
0.229590297094
0.229591956193
0.229595659829
0.229603908975
0.229620170541
0.22964873457
0.229694259708
0.229761086479
0.229852730646
0.22997178996
0.230120210566
0.23030119221
0.230516702545
0.230781067476
0.231121017401
0.231592723406
0.232303899117
0.233407988063
0.234993800464
0.237159856531
0.239887299522
0.243048108665
0.246438939632
0.249832845149
0.253004816828
0.255758384628
0.2579461765
0.259479200587
0.260327783292
0.260516760098
0.260117052799
0.259232799884
0.257996178594
0.256555362161
0.255075686667
0.253712346313
0.25271616103
0.252359964919
0.252641879343
0.2535182829
0.255013540133
0.257043228058
0.259454120066
0.262083344023
0.264777847521
0.26740394452
0.269824566229
0.27198282178
0.27357854844
0.275006737956
0.245853932349
0.245412181642
0.244709473525
0.243668594221
0.242413341454
0.240976452265
0.239440154909
0.237873508289
0.236340434289
0.234893570848
0.233573851387
0.232410974211
0.231424910532
0.230627141752
0.230020799838
0.229599274972
0.229344247395
0.229225845468
0.229206135378
0.229247164509
0.229317657446
0.229392214048
0.2294556147
0.229503398592
0.229536432597
0.229557434048
0.229569880607
0.229576560446
0.229579558825
0.229580350623
0.229579910786
0.229579158436
0.2295793549
0.229582599443
0.22959218871
0.229612555184
0.229648762435
0.229705487425
0.229786246715
0.229893316419
0.230027561401
0.230191712853
0.230386537112
0.230619935074
0.230914571584
0.231309754651
0.2318763695
0.232761168664
0.234080277786
0.2359132586
0.238244630791
0.240960596198
0.243875126896
0.246771918951
0.249438049538
0.251689731808
0.253390415983
0.254459680994
0.254874560744
0.25466396668
0.253899486774
0.252683656636
0.251152571997
0.249461373712
0.247790594165
0.246256568141
0.244964336534
0.244142973412
0.243957254168
0.2446772637
0.246251678484
0.24846701254
0.251087179477
0.253916192177
0.256780884946
0.259539171835
0.262052709969
0.264284093925
0.265916819878
0.267409808862
0.244076951473
0.243662919686
0.242996357646
0.242017129082
0.240842972913
0.239503708429
0.238080795688
0.236638376664
0.235236628342
0.233924222298
0.232738487432
0.231706038449
0.23084438565
0.230163159553
0.229664011241
0.22933862795
0.229166297797
0.22911373587
0.229140616188
0.229211836369
0.229300018347
0.229380753616
0.229444733906
0.229492281978
0.229525595954
0.229547278102
0.229560704102
0.229568447403
0.229572391578
0.2295738023
0.229573453649
0.22957209861
0.229570730392
0.229571090961
0.229576142669
0.229590176182
0.229618473053
0.229665865497
0.229735692304
0.229830006222
0.22994893279
0.230093274102
0.230265666349
0.23046693
0.230713715124
0.231039706213
0.231510204902
0.232236572991
0.233329881443
0.234858927395
0.236809510907
0.23907851162
0.2414969328
0.243865937727
0.245990060214
0.247702422161
0.248881430896
0.249459358441
0.249423608071
0.248809403307
0.247693872022
0.246195404478
0.244482372245
0.24273412176
0.241025990933
0.239389389692
0.238020937105
0.236996671662
0.236382721717
0.23650492038
0.237683856998
0.239741360235
0.242327144642
0.245158582563
0.248020882523
0.250756132099
0.253222313913
0.255406345363
0.256986958885
0.258502410259
0.242389595387
0.242014444491
0.241398719806
0.240493262612
0.239409622698
0.238175880024
0.236871845138
0.235556321144
0.234285447323
0.233103710938
0.232044907729
0.231132766153
0.230382592521
0.229802449062
0.229392852203
0.22914430868
0.229034291043
0.229027115034
0.229085231392
0.229178278179
0.229277282746
0.229360169675
0.229423727829
0.229471784269
0.229507080392
0.229531563185
0.229547870897
0.22955810691
0.229564040518
0.229566936099
0.229567689794
0.229567067226
0.22956586602
0.229565467093
0.229568360168
0.22957831651
0.229600266202
0.22963880614
0.229696912419
0.229776238245
0.229877551572
0.230000040181
0.230146212879
0.23031782232
0.230524679672
0.230794660842
0.231184602001
0.231782969268
0.232681634902
0.233934036973
0.235521831139
0.237350146966
0.239267292473
0.241095498858
0.242661139602
0.243818346733
0.244464626368
0.244549210493
0.244072784605
0.243079686646
0.241666592968
0.239988643934
0.238210700306
0.23641000698
0.234604409129
0.233025722385
0.23182031824
0.230904867854
0.230266802888
0.230020057141
0.230458175045
0.23176386731
0.233841359034
0.236310818116
0.238844827182
0.241262781579
0.243417846223
0.24532483165
0.246676085387
0.248126945094
0.240833356867
0.240499215494
0.23993906715
0.239112468379
0.238123894628
0.236999188816
0.235815252015
0.234625218812
0.233481045439
0.232422968406
0.231481371118
0.230677271687
0.230023944547
0.229528061082
0.229189319934
0.228997911529
0.228930982755
0.228952339137
0.229032671898
0.229145230585
0.22925256374
0.229335435445
0.229398018259
0.22944718004
0.229485429673
0.229513686906
0.229533267458
0.229546051121
0.229554007598
0.229558612615
0.229560925168
0.229561720522
0.229561657044
0.229561745817
0.229563895799
0.2295711978
0.229587630553
0.229617164425
0.229663001692
0.229727081103
0.229810518451
0.229913223828
0.230035197449
0.230177342399
0.230346920722
0.230567700292
0.230887516763
0.231374919522
0.232098572487
0.233093391776
0.234334075473
0.235732215702
0.237153226989
0.23844230407
0.239450732946
0.240057110179
0.240181831603
0.239794065203
0.23890897085
0.237589937555
0.235975200377
0.2342196036
0.232360940487
0.230500060174
0.228782804013
0.227382897371
0.226293354655
0.225428036404
0.224762185126
0.224333776982
0.22422127827
0.224775927052
0.225917648835
0.227679870887
0.229527333508
0.231252006963
0.232712707355
0.233969833146
0.234773582371
0.235985179664
0.23943471523
0.239138803947
0.238632993004
0.237884988614
0.236991427183
0.235975066089
0.234908705429
0.233839537399
0.232815235771
0.231871776435
0.231036269035
0.230327166898
0.229755832566
0.229327645646
0.22904185613
0.228889463682
0.228849316893
0.228888290493
0.228984701238
0.229112696637
0.229227056078
0.229310782535
0.229373734528
0.229424269348
0.22946470626
0.229495535969
0.229517399429
0.229532209053
0.229542088392
0.229548580084
0.229552740634
0.229555257113
0.229556614358
0.229557593202
0.229559585228
0.229564884754
0.229576645904
0.229598522086
0.229633720599
0.229684375916
0.229751358181
0.229834357116
0.229932515266
0.23004587533
0.230180306992
0.230356269193
0.230611847434
0.230996399669
0.231555375249
0.232304583375
0.233210841697
0.234191455351
0.235128893707
0.235892350648
0.236359971131
0.236437531826
0.236070967271
0.235249576259
0.234005574443
0.232440634936
0.230721363928
0.228846210545
0.226993080871
0.225186090214
0.223635418836
0.222377369312
0.221341222078
0.22046305648
0.219732198437
0.219139705286
0.218677324392
0.218483943792
0.218832347583
0.219502481563
0.220257200884
0.220861663752
0.221126559977
0.221167303588
0.220863973786
0.221469686098
0.2382034619
0.237941674401
0.237486860374
0.236814406383
0.236012693906
0.235100858858
0.234146788523
0.233191633499
0.232278757677
0.231439930741
0.230699155923
0.230072491309
0.229569537354
0.229194489661
0.228946390972
0.228817985292
0.228791024441
0.228838934676
0.228944364177
0.229083037347
0.229202109323
0.229289623646
0.229354218469
0.229405151668
0.229446151298
0.229478044814
0.229501585395
0.229518252174
0.229529943302
0.229538186581
0.229543988977
0.229547957586
0.229550506292
0.229552214375
0.229554124878
0.229558047
0.229566533303
0.229582579437
0.229608945528
0.229647501642
0.229698952719
0.22976284272
0.229837923867
0.229923583374
0.230024715688
0.230158509247
0.23035229761
0.230636518477
0.231034748314
0.231544995305
0.232127032611
0.232704251508
0.233176452915
0.233437362082
0.233393151506
0.23297873545
0.232165928338
0.230963079951
0.229432217909
0.227715704007
0.225868833735
0.224013802019
0.222182320523
0.22052514019
0.219138608012
0.217979960974
0.216963974788
0.216036575101
0.215194175895
0.21439758038
0.213605655233
0.212825094861
0.212320951862
0.211730600977
0.211085365704
0.210162502879
0.20861685202
0.206594043909
0.20417576783
0.20331878612
0.237138049461
0.236906558749
0.236499222613
0.23589820276
0.235183501899
0.234370491205
0.233521760848
0.232672539497
0.231861969628
0.231117749357
0.230461000595
0.229905619999
0.229459733071
0.229126589729
0.228905124258
0.228789613338
0.228763017423
0.228812024602
0.228916016706
0.229060821308
0.229185774328
0.22927499468
0.229338457163
0.229388030849
0.229428790447
0.229461700361
0.229487093412
0.229505607208
0.229518827831
0.229528382772
0.229535396221
0.229540475616
0.229543961884
0.229546274313
0.229548233101
0.229551226568
0.229557246118
0.22956858482
0.229587388327
0.229615110845
0.229652206847
0.229698024425
0.229751041054
0.229810193835
0.229879663191
0.229972759648
0.230104679719
0.230287367083
0.230524606728
0.230799140249
0.231065822126
0.231255408632
0.231285609383
0.231074926589
0.230558230514
0.22970012825
0.228495852943
0.226976805611
0.225254926632
0.223482017418
0.221542685334
0.21974118282
0.218025425566
0.21654161112
0.215279879106
0.214173575334
0.213144660137
0.212142012481
0.211146569701
0.21010161997
0.208942801927
0.207601408621
0.206099891043
0.204493408336
0.202085223972
0.199261589463
0.195164015127
0.189801167873
0.183357774241
0.178698977801
0.236230827363
0.236026409059
0.235663361764
0.235129348378
0.234496074733
0.233775282755
0.233024203289
0.232272451278
0.231555141408
0.230896110966
0.230313869733
0.229820421482
0.229422897268
0.229124121479
0.228923396613
0.228818464362
0.228783559547
0.228811649124
0.228914086511
0.22906391128
0.229185793546
0.229268174199
0.229326285933
0.229372604109
0.229411938575
0.229445186537
0.229472628894
0.229493623882
0.229508721385
0.229519410842
0.229527216646
0.229533037259
0.229537265654
0.229540193483
0.229542338652
0.229544628575
0.229548538916
0.229555827768
0.229568070464
0.229586191894
0.229610218259
0.22963918665
0.22967132088
0.229705254945
0.229744539767
0.229797385417
0.229865379173
0.22994286368
0.230016422952
0.230056801696
0.23001686552
0.229836589001
0.229452371177
0.22880770609
0.227866420316
0.226620783225
0.225086677781
0.223333163001
0.22150107066
0.219557451225
0.217793451398
0.216068208895
0.214515273342
0.213186320103
0.212015026418
0.210927526787
0.209855194298
0.208751084571
0.207574696582
0.206253226759
0.204700111143
0.202809101322
0.200460574165
0.197547697407
0.193468185581
0.188455205284
0.180984236694
0.170496374836
0.156542276016
0.141704044595
0.235470950236
0.235291003228
0.234969393822
0.234497905104
0.233940225082
0.233304771642
0.232643564409
0.231981034182
0.231348529639
0.230766266767
0.230250434583
0.229811215853
0.229455389567
0.229185931427
0.228999947274
0.228894918568
0.228853679644
0.228865264257
0.228970646414
0.229108587131
0.229216273926
0.229288296345
0.229338846542
0.229378057832
0.229410220425
0.229436976205
0.229460335751
0.229481608183
0.229499011847
0.229511204365
0.229519621635
0.229525869375
0.229530646223
0.229534166495
0.22953658689
0.229538361247
0.229540437072
0.229544130666
0.229550537183
0.229560072877
0.229572252434
0.22958568142
0.229598247279
0.229608339501
0.229618720598
0.229630719369
0.229631149367
0.229598234683
0.229504306138
0.229311782502
0.228974840243
0.228444749751
0.22767747985
0.22664189378
0.225330137781
0.223758047015
0.22196586802
0.220076647013
0.218220762751
0.216251327466
0.214553092281
0.21298264066
0.211612639888
0.210409270068
0.209297330284
0.208202537715
0.207063602003
0.205836669254
0.204461971415
0.202852425472
0.200900344274
0.198466298933
0.195349993161
0.191166594684
0.185851964413
0.178342146011
0.16684360412
0.148960995646
0.119619759426
0.0592651020798
0.234846432843
0.234688676095
0.234405763522
0.233992279444
0.23350432832
0.232947400256
0.232368577741
0.231787607139
0.231232363879
0.230719610538
0.230263753156
0.229872310858
0.229550876767
0.229303091315
0.22912804713
0.229024839452
0.228987174849
0.229002567843
0.229097092817
0.229207600014
0.229293390294
0.229352063823
0.229391846623
0.229419072547
0.229437803226
0.229450676272
0.229460774981
0.229473344763
0.229489741627
0.229503659567
0.22951290138
0.229519455016
0.229524628668
0.229528623906
0.22953132788
0.229532732664
0.229533282823
0.22953375754
0.229534824442
0.229536518916
0.229537893997
0.229537058612
0.229531424233
0.22951911959
0.229501596289
0.229471068145
0.229399089745
0.229249816795
0.228984520389
0.228561104859
0.227938360314
0.22708083432
0.225965064813
0.224585663402
0.222960237482
0.221125482156
0.219160507157
0.217205966422
0.21518469039
0.213498955617
0.211901768511
0.210485123372
0.20925986228
0.208145867528
0.207065098495
0.205943547566
0.204722905967
0.20336020047
0.201780953648
0.199887309165
0.197555188415
0.194619183724
0.190853626413
0.185776440118
0.179350278356
0.1696221135
0.155173353355
0.132499051966
0.0975125860401
0.0431214525603
0.234344626971
0.234207077286
0.233960125113
0.233600067819
0.233176023095
0.232691010418
0.232187537619
0.231681218501
0.231196827468
0.23074697687
0.230342874892
0.229991971706
0.229699849657
0.229471873727
0.229312192058
0.229221933315
0.229193741451
0.229207051405
0.229278331511
0.229356901657
0.229416740747
0.229455991017
0.229478634413
0.22948851499
0.229489500764
0.229485171581
0.229479052183
0.229475761094
0.229482790113
0.22949666306
0.229507293757
0.229514431714
0.229519959702
0.229524264343
0.229527067942
0.229528143485
0.229527443098
0.229525102323
0.229521289242
0.229515719486
0.229507110586
0.229493131383
0.229470612846
0.229437380007
0.229392540852
0.229316736456
0.229166701065
0.228895018893
0.228455246624
0.227804522266
0.226909237918
0.225748872352
0.22432165177
0.222647733157
0.220765580313
0.218736569163
0.216690504889
0.214745910096
0.212746510592
0.211158237545
0.209725799547
0.208480286807
0.207371436353
0.206317735123
0.205245527112
0.204083642146
0.202772705604
0.201267748524
0.199487195288
0.197325892072
0.194647789428
0.191269639341
0.186950571164
0.181222044739
0.173659531078
0.162770027042
0.147382311629
0.123932274444
0.0894406555156
0.042893593683
0.233953204629
0.233833888065
0.233619982292
0.233308644109
0.232942698646
0.232523175309
0.232088445594
0.2316505333
0.231229490417
0.230834272411
0.230474365481
0.230159263255
0.22989669244
0.229692935636
0.22955368358
0.229480179846
0.229454825125
0.229457932682
0.229499011028
0.229543106857
0.229574125685
0.229589632299
0.229590785168
0.229579868821
0.229560470457
0.229536701628
0.229512475463
0.229492335041
0.229483382051
0.229490899072
0.229502887257
0.229511375645
0.229517339525
0.229521782179
0.229524457862
0.229525045506
0.229523202198
0.229518465083
0.229510338243
0.229498090633
0.229480175811
0.229453973775
0.22941574548
0.229363001543
0.229290854497
0.229166063024
0.228931961268
0.228532328494
0.227916432558
0.227044160322
0.225891994933
0.224455624134
0.222755754898
0.220835704246
0.218752968599
0.216610838832
0.21453813988
0.212447984011
0.210804722323
0.209322704509
0.208026782707
0.206907238006
0.205875796008
0.20485232303
0.203767753522
0.202556022667
0.201155803343
0.199506615322
0.197531795001
0.195124199437
0.192138654519
0.188379519803
0.183585635354
0.177321384025
0.168891353389
0.157790962653
0.142348613383
0.119341607301
0.0855409913238
0.0427657639074
0.233659935158
0.233556982641
0.23337303179
0.233105547178
0.232791837001
0.232431417994
0.232058951359
0.231681698767
0.231315397964
0.23096728749
0.230648209955
0.230368461094
0.230136592309
0.229958893428
0.229840082543
0.229781593764
0.229751846416
0.22973772563
0.229746380011
0.229755786709
0.229756541773
0.229745850454
0.229722962457
0.229689360843
0.229648328582
0.229603933632
0.229560299684
0.229522030865
0.229495414037
0.229489624888
0.229500163646
0.229510651605
0.229517381707
0.229521808717
0.229524204335
0.229524076066
0.229520957837
0.229514078072
0.229502247542
0.229484023139
0.22945748349
0.22941983864
0.229366912635
0.229295938971
0.229195731414
0.229017487352
0.228693394807
0.228161302844
0.2273696089
0.226284092408
0.224893305542
0.223210308396
0.221278141174
0.219157888491
0.216929927465
0.214760079665
0.212736807626
0.210681719238
0.209174435842
0.207850009189
0.206702537069
0.205678392817
0.204693403064
0.203675011102
0.202559715719
0.201286995496
0.199795993984
0.198016042092
0.195861253262
0.193230304903
0.189977594556
0.185901375594
0.180730209018
0.174074538058
0.165213322853
0.154084837256
0.138612913464
0.116418958349
0.0835324584361
0.0432245028207
0.233453424037
0.233364880408
0.233207515418
0.232978808018
0.232711314734
0.23240351013
0.232085663338
0.23176043061
0.231441920108
0.231136925872
0.230856634768
0.230611812523
0.230410075989
0.230257391329
0.230156452744
0.230108874373
0.230070716539
0.2300358217
0.230011398391
0.22998647979
0.229956746613
0.229918836522
0.229870942698
0.229814163954
0.229751284752
0.229685999428
0.229622364527
0.229565182618
0.229520565854
0.229496888408
0.229499602978
0.229512226125
0.229520541402
0.229524977651
0.229527041016
0.229526097483
0.229521432473
0.229512332255
0.229497216007
0.229473754245
0.229439368988
0.229391037473
0.229324333566
0.22923619933
0.229106284653
0.228869650131
0.228450135576
0.22778252433
0.226817645518
0.225529814247
0.223921235855
0.22202337392
0.219899789995
0.217626248315
0.215319964787
0.21315816355
0.211020182089
0.209360735964
0.207953776709
0.206740961719
0.205697587585
0.20473171812
0.203763258877
0.20272661205
0.201563496318
0.200217794555
0.198631945229
0.196741428479
0.194435433923
0.191603653794
0.188115865648
0.183778757302
0.178319497221
0.171378883433
0.162365941156
0.150795354949
0.135311568508
0.114409541489
0.0829511528922
0.0444508704596
0.233322705498
0.233246831719
0.233112429185
0.232917215818
0.232689672843
0.232427519459
0.232156213063
0.231875954637
0.231599987227
0.23133506092
0.23109152905
0.230879658261
0.230706065485
0.230575617728
0.230490061917
0.230447615764
0.230398370279
0.230342075719
0.230285635075
0.230228046766
0.230168756267
0.230103932518
0.230031388297
0.229951901366
0.229867651278
0.229781832775
0.229698179715
0.229621644038
0.229558469305
0.229516502347
0.229505145804
0.229516972969
0.229527706792
0.229532304187
0.229533841986
0.229532096891
0.229525678725
0.229513988441
0.229495601768
0.229467464743
0.229426072205
0.229367872321
0.22928833962
0.229183831785
0.229021635693
0.228721523089
0.228201983408
0.227397532769
0.226264461764
0.224787729234
0.22298465099
0.22090529502
0.218628539242
0.216248058486
0.213944749709
0.211873540882
0.209734350619
0.208255738509
0.206997498841
0.205911202957
0.204943424739
0.204007666104
0.203032707491
0.201959662388
0.200735244514
0.199307116179
0.197620346589
0.195617487625
0.193198190203
0.190218737864
0.186526661884
0.181959746786
0.176259489669
0.169068658744
0.159863406491
0.147819401856
0.132758638745
0.113173748587
0.0832405122172
0.0458666375892
0.233258133803
0.233193087242
0.233077781511
0.232910651475
0.232716673031
0.232492695601
0.232261004085
0.232019919939
0.231782104049
0.231553792237
0.231344376255
0.231162444742
0.231014072695
0.230902430544
0.23082932295
0.230787256698
0.23072602183
0.230649322797
0.230563089422
0.230475407244
0.23038827096
0.230297769326
0.230201723857
0.230100592603
0.229995872683
0.229890205751
0.229786967976
0.229691001586
0.229608931336
0.229548891647
0.229520222036
0.229526097859
0.22953968755
0.22954489725
0.229545523896
0.229542956375
0.229534833254
0.22952017664
0.229498155801
0.229465539372
0.229417886705
0.229350685243
0.229259400238
0.22913892299
0.228941040367
0.228572536672
0.227949461188
0.227008758255
0.225714755822
0.224064671778
0.222092423555
0.219865601399
0.217473528745
0.215035429897
0.212754543644
0.210648598954
0.208868665414
0.207476890949
0.206313707965
0.205319686731
0.204397172164
0.203466572714
0.202465866644
0.201342206704
0.20004633256
0.198528351517
0.196734196607
0.194602399103
0.192060745562
0.188982892419
0.185189742562
0.180469878777
0.17457251253
0.167162859624
0.15777762445
0.145530469569
0.130893450412
0.112323960672
0.0837744689845
0.0469164491284
0.233251045896
0.233195006472
0.23309474874
0.232950252228
0.232783523379
0.232590616511
0.232392148285
0.232185058316
0.231981332029
0.231785702712
0.231607127825
0.231451738253
0.231325401333
0.23122948747
0.231166565006
0.231122583667
0.231049565572
0.23095345026
0.230840246492
0.230725351073
0.230612558523
0.230498197749
0.230380183248
0.230258677982
0.230134652636
0.230009981721
0.229887840489
0.22977275441
0.229671560547
0.229592900273
0.229546293171
0.229541479595
0.229556968868
0.229563480808
0.229562894136
0.229559374701
0.229549903396
0.229532242627
0.229506109336
0.229468822102
0.229415399197
0.229340000748
0.229238181944
0.229101604818
0.228864013688
0.228422677934
0.227693856007
0.226619471458
0.225173874708
0.223367813228
0.221252526471
0.218909221697
0.216441229753
0.214020743328
0.211802191361
0.209575973164
0.208132529571
0.206900976653
0.205849010351
0.204920219349
0.204019239146
0.203075982264
0.202036455702
0.200853268964
0.199480523906
0.197870024509
0.195967822621
0.193710548555
0.19102029477
0.187799000291
0.183905636657
0.179124905016
0.173188280946
0.165755046874
0.156360826846
0.144198018973
0.129969366376
0.112182407018
0.0848899622255
0.0480972093075
0.233294028158
0.233245576525
0.233155873402
0.233028537697
0.232882797419
0.232714569374
0.232543200939
0.232364976012
0.232191069095
0.232023988215
0.231872578375
0.23174048645
0.231633046451
0.231550751701
0.231496819005
0.231450722907
0.231366958805
0.231252344768
0.231115243814
0.230976124824
0.230840173575
0.230704042466
0.230565761282
0.230425276678
0.230283090309
0.230140383019
0.229999982988
0.229866320601
0.229746218041
0.229648682973
0.229583864147
0.229564379868
0.229579116467
0.229588126183
0.229586659162
0.229582056706
0.22957178119
0.229551572637
0.229521063175
0.229478689872
0.229419655145
0.229336666251
0.229225590853
0.229072051429
0.228790409745
0.228272530435
0.2274372271
0.226233706764
0.224647747281
0.222704890362
0.220472863792
0.218040078482
0.215533144228
0.213179682553
0.211033999531
0.208989406908
0.207651177647
0.206537743186
0.205577165225
0.204686314208
0.203785547482
0.202815553682
0.201728660132
0.200481645797
0.199031157604
0.197330177391
0.195324672156
0.192949811767
0.190124977019
0.186746765861
0.182678586502
0.177757108338
0.171736210116
0.164289634791
0.154963163369
0.143121013957
0.129257893476
0.111844095539
0.0853735144494
0.0487899893799
0.233381296046
0.23333924586
0.233255115441
0.2331394668
0.233008468146
0.232858853077
0.232708713524
0.232554079868
0.232405336193
0.232262712904
0.232134322454
0.232022644849
0.231931445306
0.23186113724
0.231815990018
0.231768982515
0.231676392286
0.231544853938
0.231387096058
0.231226876902
0.231070407582
0.230914748228
0.230757973418
0.230599911567
0.230440641568
0.230280966367
0.230123012928
0.229971254099
0.229832683797
0.229716646952
0.229634242425
0.229598437848
0.229608392564
0.229620355544
0.229618326866
0.229612180714
0.229601403872
0.229579434
0.229544709448
0.22949687944
0.229432119096
0.229341879358
0.229222743953
0.229050474197
0.228720440487
0.228123246675
0.22718234951
0.22585616286
0.22414281049
0.222083610968
0.219759672033
0.217266028062
0.214772579433
0.21248555975
0.210239825874
0.208666772455
0.207421785833
0.206376444512
0.205466633305
0.204590211323
0.203675356286
0.202670445007
0.201532732441
0.200222223257
0.198697564699
0.196912722163
0.194813752618
0.192335092871
0.189394786479
0.18588808235
0.181678624106
0.176588643384
0.170374865669
0.162725548068
0.153131553926
0.141526843244
0.127719978883
0.109550992051
0.0825226627551
0.0465216837609
0.233509372117
0.233471699218
0.233387998785
0.233278392703
0.233155768808
0.233018742634
0.232884037898
0.232747671734
0.232618789614
0.232496668562
0.232387149474
0.232292741199
0.232215896374
0.232156092818
0.232120088918
0.232073753587
0.231974991074
0.231829226571
0.231654380354
0.23147653401
0.231302521571
0.231129767769
0.230956442362
0.230782285024
0.230607103866
0.230431364855
0.230256796859
0.230087492024
0.229930756497
0.229796536302
0.229696529544
0.229644396106
0.229647360587
0.229662148522
0.229659684985
0.229651111503
0.22963960504
0.229616739435
0.229578463367
0.22952513021
0.229454436502
0.229357073103
0.229230840469
0.22903710006
0.228654638895
0.227976453646
0.226932544667
0.225492031797
0.223666192014
0.221511797546
0.219116097614
0.216588604685
0.214170821818
0.212000364449
0.209788186479
0.208439773847
0.207328068706
0.206365768524
0.20548897527
0.204612495005
0.203675274051
0.202632028563
0.201444106863
0.200074202821
0.198482687701
0.196624530191
0.194446212401
0.191882140049
0.188850064963
0.185245011567
0.180930935539
0.175729610592
0.169404769595
0.161615410539
0.151766489182
0.14016419071
0.126080457137
0.106522700019
0.0781109647727
0.0427634842587
0.23367620743
0.233640262422
0.233552344889
0.233442211064
0.233321155092
0.233190415377
0.233065190533
0.232941737109
0.232827257439
0.232721301262
0.232627046069
0.232546397881
0.232481755224
0.232431400497
0.232404364439
0.232360618204
0.232259272945
0.232102815505
0.231914884583
0.23172319197
0.23153501461
0.23134812994
0.231160612374
0.230972109968
0.230782406295
0.230591615148
0.230401231868
0.230215198495
0.230040671831
0.229888208254
0.229770314177
0.22970072393
0.229694968687
0.229713104077
0.229711384254
0.22969984886
0.229686991588
0.229663957576
0.229623204968
0.22956481832
0.229488096869
0.229383707254
0.229250987093
0.229032177509
0.228593811619
0.227834136861
0.226691400879
0.225146532883
0.22322509528
0.220997607871
0.218550628658
0.216019607731
0.21367612261
0.211508457236
0.209687748225
0.208428465056
0.207386960707
0.206483622755
0.205625204852
0.204739667722
0.203776140654
0.20269487384
0.201460680616
0.200038606438
0.19839066929
0.196473016954
0.194232999104
0.19160570583
0.18850955957
0.18484037412
0.180462694473
0.175199372084
0.168814974824
0.160920985727
0.151285752291
0.139475497002
0.124579634436
0.10394424021
0.0747894257077
0.0402611692462
0.233880400701
0.233843941498
0.23374774126
0.233630771937
0.233502881231
0.233371053619
0.233248976171
0.23313299061
0.233028008857
0.232933120286
0.232850526477
0.232780421555
0.232725147216
0.232682800269
0.232664139725
0.232623422975
0.232524435113
0.232363255702
0.232166690149
0.231964832537
0.231766101859
0.231568465553
0.231369711894
0.231169108979
0.230966535523
0.230761927233
0.230556551095
0.230354401134
0.230162730625
0.229992138455
0.229855891156
0.229767645934
0.229750034656
0.229771564701
0.229773074543
0.229759073966
0.229744108621
0.229721246414
0.229679224547
0.229616732845
0.229534177965
0.229423085571
0.229284041642
0.22903601358
0.228539026336
0.227698582123
0.226462634502
0.224824679139
0.222825309459
0.220544480693
0.218071380083
0.215597501082
0.213343132635
0.211072875485
0.209642729965
0.208528361625
0.207569368814
0.206708859097
0.205859490703
0.204961094795
0.203971227215
0.202855290719
0.201581371684
0.200116784715
0.198425287267
0.196464506328
0.194183176343
0.191517805574
0.188388409165
0.184692415357
0.180295492027
0.175021825361
0.168592044731
0.160512840995
0.151042357651
0.139373949043
0.123469580915
0.101802681339
0.0720296904533
0.0378218984338
0.234122391789
0.234083311559
0.233974282917
0.233844949804
0.233702699699
0.233561082365
0.233433745126
0.233319589499
0.233219324433
0.233130346234
0.233055025635
0.23299230123
0.232943580788
0.232906935816
0.232895127115
0.232856720896
0.232764921587
0.232606622007
0.232407541352
0.232199458938
0.231993973311
0.231789563956
0.231583008323
0.231373032471
0.231159551563
0.230942481793
0.2307231977
0.23050555577
0.230297086448
0.230108767433
0.229953964672
0.229846652542
0.229812878687
0.229836052851
0.229843971154
0.229829249931
0.229811525368
0.229788621784
0.229746354714
0.229681087171
0.229593274529
0.229476297257
0.229330580166
0.229049074167
0.22849164443
0.227572347705
0.226250078482
0.224531758114
0.22247237636
0.22015257856
0.217674298476
0.215307750849
0.213178073014
0.211011050773
0.209753264104
0.208745811408
0.207862096329
0.207030819803
0.206182636098
0.205269369235
0.204255276263
0.203110076478
0.201804842774
0.200309147364
0.198588685942
0.196602971951
0.194302736952
0.19162670774
0.188497343882
0.184814111195
0.180445668499
0.175219146834
0.168816987673
0.161089978823
0.1513756036
0.139308311062
0.122707855554
0.100359941178
0.0701322181749
0.0357128896021
0.234403937916
0.234360480935
0.23423360216
0.234085592948
0.233922754115
0.233763724735
0.233622895944
0.233501806313
0.23340028452
0.233312734982
0.233240047653
0.233180605362
0.23313513356
0.233101865748
0.23309387121
0.233056815641
0.232975740192
0.232828441985
0.232634411132
0.232425554026
0.23221779343
0.232010637449
0.23179978643
0.231583597737
0.231361555381
0.231133608309
0.230901441126
0.230669296328
0.23044456206
0.230238819825
0.230065665788
0.229939747479
0.22988599689
0.229906333879
0.22992321894
0.229910395355
0.229889631551
0.229866061778
0.229824270904
0.229757803316
0.229665690762
0.229544295576
0.22939095848
0.229072089906
0.228453405579
0.227458287791
0.226057564836
0.224272974604
0.222172070114
0.219828164492
0.217368035804
0.215096239521
0.212985786321
0.211215204887
0.210041623565
0.209086126299
0.208249236334
0.207435533286
0.206584617786
0.205657150729
0.204622932595
0.203455442808
0.202128572353
0.200614254724
0.198880443222
0.19688908089
0.194593685133
0.191936294668
0.188843000883
0.185216161797
0.180925752243
0.175757803063
0.169304288174
0.161900468123
0.152622116301
0.140090858644
0.123012299399
0.100243241155
0.0696456708601
0.034287071801
0.234728975219
0.2346794673
0.234529876955
0.234356252582
0.234165276188
0.233981735197
0.233820799471
0.233684371917
0.233573385106
0.233481085887
0.233407030811
0.23334671119
0.2332999107
0.233266541794
0.233258028662
0.233221629381
0.233152600355
0.233024571492
0.232845288747
0.232642627153
0.232437449763
0.232231324692
0.232019778003
0.231800551603
0.231572580022
0.231335646801
0.231091785653
0.230845898183
0.230605848306
0.230383253531
0.230192106315
0.230048102692
0.229972837798
0.229983479912
0.230009790081
0.230001774791
0.229978483364
0.229953726924
0.229912960755
0.229846964958
0.229751752715
0.229628041302
0.229465432492
0.229106084952
0.228426457212
0.227359702308
0.225889213585
0.224052659139
0.221926210091
0.219578052018
0.217186157438
0.215004203847
0.212790971214
0.211442014584
0.210407012008
0.20951905251
0.208715724993
0.207912119665
0.207057032818
0.206117708033
0.205068593263
0.203886567017
0.202548264938
0.201028153479
0.199296842195
0.197319361891
0.195052983499
0.192444523484
0.189425861897
0.185907323456
0.181767420488
0.176770427854
0.170751832451
0.163300476976
0.154273788856
0.141816129704
0.124797086781
0.101965313342
0.0712205962542
0.0340910555835
0.235101952497
0.23504536238
0.234869046976
0.234663224654
0.234436136443
0.234219419642
0.234030509464
0.233872570534
0.23374499851
0.233641030336
0.23355932535
0.233493557723
0.233441399173
0.233403277073
0.233389470474
0.233351475948
0.233295578125
0.233190905393
0.233037101594
0.232850092088
0.232653051468
0.232451579495
0.232242622538
0.232023503819
0.231792533428
0.231548864058
0.231294774198
0.231036149834
0.23078145841
0.23054277927
0.230334274955
0.230171783463
0.230074870134
0.230069186907
0.230102831085
0.23010246011
0.230078312456
0.230052449522
0.230013215609
0.229949234493
0.229852104551
0.229728560636
0.229554200917
0.229152207941
0.228413085672
0.227280202015
0.225750109671
0.223875862558
0.221733546454
0.219397659457
0.217129188785
0.215080476433
0.212909178204
0.21176938048
0.210845886314
0.210026609446
0.209249505883
0.208451371085
0.207591938142
0.20664393657
0.205585636342
0.204396974004
0.203057307248
0.20154385422
0.199830336135
0.197885615169
0.195671785468
0.193142014343
0.190236004689
0.18687439478
0.182932403766
0.178189164909
0.172786766113
0.165954616948
0.157256405109
0.145318714556
0.128886265712
0.106268525708
0.0752739222395
0.0348602853349
0.235528736255
0.23546424077
0.235258164091
0.235014502919
0.234743942411
0.234485093088
0.234258951284
0.234071436525
0.23392134272
0.233800322129
0.233705059341
0.233628828916
0.233566668303
0.23351893872
0.233492928461
0.233450676947
0.233408073921
0.233328413168
0.233208428356
0.233046844105
0.232864356396
0.232671857698
0.232468432998
0.232251991753
0.23202075183
0.23177331071
0.231510826627
0.231240689733
0.230972481804
0.230718579597
0.230493461427
0.230312255133
0.2301938596
0.230166873659
0.230203826242
0.230213294912
0.230190643941
0.230164219723
0.230126840633
0.230065946646
0.229967777431
0.229846916476
0.229657447737
0.229211485041
0.228415122384
0.227222671195
0.225645243241
0.22374914055
0.221598202583
0.219283979195
0.21713551488
0.215169945438
0.213332137868
0.212249952527
0.21137300339
0.210597565835
0.209838627228
0.209043742023
0.208181014518
0.207227919781
0.20616605784
0.204978191732
0.203646422595
0.202150969313
0.200469150874
0.198574472902
0.196435050912
0.194012511804
0.191257411482
0.188101515415
0.184421663966
0.180175510127
0.175297993704
0.169514692447
0.161800321138
0.151280953404
0.136596879639
0.115409855703
0.0840266282434
0.0359692957113
0.236014043027
0.235941743869
0.23570439701
0.235418782388
0.235098812048
0.234789814928
0.234517196382
0.234290805836
0.234110331586
0.233966457472
0.233853644071
0.233763411363
0.2336882135
0.233628148134
0.233582079697
0.233533144163
0.23349770749
0.233442741508
0.233360757981
0.233233352451
0.233072884627
0.232893549925
0.232698366083
0.232486550696
0.23225714702
0.232008708667
0.231740775972
0.231460426092
0.231179588225
0.230911639144
0.230671247578
0.230472227652
0.230333296401
0.230283333844
0.230318091436
0.230338048967
0.230318727036
0.230292055766
0.230256351759
0.230198878751
0.230100088954
0.229984073677
0.229775424522
0.229284817512
0.228433718578
0.227188243312
0.225576437975
0.223675146083
0.221529463269
0.219262037008
0.217193014256
0.21516344867
0.213778126474
0.212791483728
0.211963055442
0.21121796241
0.210471818596
0.209679573255
0.208815302935
0.20786061761
0.206800192377
0.205619495977
0.204303422519
0.202835435447
0.201196926783
0.199366845785
0.197320502434
0.195030344483
0.192459953473
0.189556569799
0.186273824093
0.182730323488
0.178634844222
0.174036784001
0.168008108681
0.16001167314
0.149071853946
0.133368094091
0.107673180692
0.053603046279
0.236562493293
0.236482821442
0.236214194444
0.235884442219
0.235511218738
0.235145970895
0.234818923994
0.234544622678
0.234325060587
0.23415117738
0.23401558153
0.233908251004
0.233819540388
0.233747433323
0.233676744935
0.233617135581
0.233580747593
0.233547527298
0.233504063187
0.233415524422
0.233282690252
0.233120060239
0.232935051289
0.232729343289
0.232503312505
0.232255680737
0.231985446377
0.231697081198
0.231404432376
0.231123021892
0.230867990681
0.230652789999
0.230494994169
0.230423409038
0.230451699654
0.230481412373
0.23046623809
0.23043907299
0.230404304531
0.230349797165
0.230250434833
0.230140807498
0.229908623115
0.229373323243
0.22847006431
0.227177264717
0.225541764775
0.223646583506
0.221524880821
0.219359144938
0.217379449043
0.215249201474
0.214215341223
0.213358774934
0.212595803431
0.211876773563
0.211139752426
0.210349568358
0.209485217149
0.208531747288
0.207476595848
0.206307816341
0.20501311589
0.203579393302
0.20199251342
0.200237621873
0.198298334688
0.196159603816
0.193794883149
0.191182009985
0.188423434658
0.185621703495
0.182686871535
0.179415824155
0.175403277225
0.17044591202
0.164217705992
0.156575495448
0.146751519826
0.138632704388
0.237175482574
0.237089941914
0.236791954314
0.236418257386
0.235990622978
0.23556579142
0.235178813101
0.234849276923
0.234582632089
0.234371450891
0.234207281627
0.234078987667
0.233975923409
0.233890263242
0.233796227308
0.233725186473
0.233684554136
0.233666756966
0.233655603029
0.233604645245
0.233501393676
0.23335720575
0.233182955559
0.2329839444
0.232762028336
0.232516036104
0.232245455225
0.23195201772
0.231648499091
0.231354140209
0.231084907069
0.230853980686
0.230678564916
0.230586940749
0.23060702825
0.230645812655
0.230635417744
0.230607417043
0.230572672848
0.230520143696
0.230420126037
0.230317550455
0.230057779575
0.229478554289
0.228526343036
0.227192019904
0.225540691326
0.223652525646
0.221563906061
0.219544551289
0.2176973736
0.215683472743
0.214757991295
0.213975492861
0.21326314184
0.212563793053
0.211832822593
0.211043911572
0.210180226728
0.209229640081
0.20818199288
0.20702775215
0.205757384976
0.204361286648
0.202830016322
0.201155565845
0.199330904641
0.19735421723
0.195209883634
0.192977257904
0.190837847337
0.188800049785
0.187041539086
0.185198604097
0.183194351326
0.181021224975
0.17863305666
0.176304713875
0.173753513186
0.174282181399
0.237852530072
0.237762882016
0.237439039967
0.237024063272
0.236543909145
0.236059586872
0.235610637862
0.235221615454
0.23490218659
0.234647882663
0.234450285216
0.234298061754
0.23418048445
0.234076785751
0.233965366332
0.233885101966
0.233838167327
0.233826158152
0.233836500771
0.233816041496
0.233739590979
0.233612688752
0.233448096542
0.23325500503
0.233036816701
0.232792487743
0.232521884998
0.232226232372
0.231913385681
0.231605760671
0.231322506292
0.231076054614
0.230883571478
0.230772669595
0.230783848708
0.230831355145
0.230826682197
0.230797917853
0.230762604909
0.230710851561
0.230610301092
0.230514307648
0.230223599489
0.229601982517
0.228605246662
0.227237501786
0.225579198608
0.223694423746
0.221634927514
0.219741137239
0.217968402509
0.216331350384
0.215404526907
0.214642092256
0.213955666727
0.21326822463
0.21254065283
0.211751989646
0.210888752251
0.209941212094
0.208901289355
0.2077616502
0.206515366237
0.20515621477
0.203679375299
0.202083948908
0.200371732016
0.19855325151
0.196647668853
0.194864112806
0.19336741577
0.192227132276
0.191491990278
0.190988977516
0.190745725252
0.190809872207
0.191187066968
0.192104492885
0.193113014114
0.196208805732
0.238588230656
0.23849709336
0.238152565345
0.237701413134
0.237173744099
0.236633760514
0.236124932541
0.235676343763
0.235302190258
0.235002037809
0.234768760655
0.234592949592
0.234460393068
0.234333060296
0.234208415663
0.234120733737
0.234066038653
0.234050579045
0.234068814064
0.234066788204
0.234009489381
0.233895313471
0.233737167613
0.233547636307
0.233331501651
0.233087783742
0.232816387351
0.232519497152
0.232200502803
0.231879355223
0.231581114383
0.231319307085
0.23110969575
0.230979845224
0.230981248481
0.231036922342
0.2310391573
0.231010315146
0.230974508431
0.230922424465
0.230821886087
0.230730553751
0.230406329648
0.229743992365
0.228707871376
0.227317760051
0.225666027229
0.223790840387
0.221768900471
0.219939394527
0.218095554074
0.216920594822
0.216059105382
0.215329311878
0.214660445467
0.213979625838
0.213252754435
0.212462544468
0.211598174911
0.21065195044
0.209617546068
0.208489563687
0.207263440272
0.205936105465
0.204507208449
0.202982722782
0.201368757678
0.19968907845
0.198059900213
0.19677634494
0.195871337082
0.195578987262
0.195744159238
0.196389843508
0.197561925153
0.199278247059
0.201493442543
0.204257468385
0.20692201722
0.210646813944
0.23937421491
0.239284064425
0.238924934424
0.238444653296
0.237877228828
0.237288955743
0.236726556634
0.236222973722
0.235796855589
0.235452444053
0.23518547182
0.234990946449
0.234837634144
0.234684098594
0.234547601513
0.234452399283
0.234388068657
0.234360587016
0.234371829706
0.234372680225
0.23432275778
0.234213510858
0.234056445422
0.233866540577
0.233649591885
0.233404496583
0.233130947219
0.232831537583
0.232508852438
0.232175804843
0.231861602284
0.231583889778
0.231357303811
0.231208544901
0.23119856466
0.23126108684
0.231271387566
0.231243714024
0.231208233868
0.23115494474
0.231055609507
0.230965362736
0.230605632999
0.229903457367
0.22883218134
0.227430960952
0.22580090474
0.223956498528
0.222017579195
0.220237257093
0.2182578185
0.217446899144
0.216700779602
0.21602113765
0.215367252119
0.214688412707
0.213958563539
0.213163648702
0.212294806614
0.211345890828
0.210311901061
0.209189030018
0.20797472758
0.206668835213
0.205275611865
0.203807656526
0.202272234566
0.200738125616
0.199364305559
0.19847290085
0.19824179795
0.198593861219
0.199515583077
0.201076919152
0.20330080008
0.20615354347
0.209517400936
0.21327697523
0.216695149283
0.220492581312
0.240196923572
0.240110523157
0.239743517067
0.239242492491
0.23864513949
0.238018806564
0.237412755076
0.236863002522
0.236392292581
0.236009630416
0.2357159232
0.235508483915
0.235326733529
0.235147907498
0.23499853509
0.23489296083
0.234815278068
0.234767569568
0.234757489908
0.234744668659
0.234688085978
0.234573693688
0.234410703281
0.234215258664
0.233993719252
0.233744577619
0.233466957891
0.233163328239
0.232837045126
0.232494339793
0.232164330375
0.231870263514
0.231626771689
0.231459299819
0.231435686124
0.231502767139
0.231521901177
0.231496889744
0.231463172868
0.231408121094
0.231311916545
0.231217613653
0.230820997614
0.230078762351
0.228974491086
0.227569322578
0.225967567747
0.224174187354
0.222377590529
0.220697131166
0.218742309859
0.218031139515
0.217353972418
0.216711674186
0.216066311348
0.215384338319
0.214646875916
0.213842599708
0.212963942576
0.212005723023
0.210963656996
0.209834996697
0.208618559923
0.207316627013
0.205937831656
0.204498967591
0.203016511425
0.201682214636
0.20063220674
0.199986040306
0.200201627278
0.201047879093
0.202559431353
0.204791514891
0.207733209799
0.211303897711
0.215328180591
0.219575278248
0.223333759092
0.227061416113
0.241040329817
0.240959728274
0.240591268945
0.240078342343
0.239462036267
0.238809709014
0.238172392357
0.237588332789
0.237083775591
0.236671945546
0.236361320461
0.236142040032
0.235931331909
0.235729146496
0.23556389842
0.23544243021
0.235346026812
0.235270790942
0.235227451739
0.235186126872
0.235109161794
0.234979076375
0.234802479545
0.234595687885
0.234365261879
0.234109052966
0.233825243983
0.233515819573
0.233184680892
0.232834301298
0.232488732348
0.232178156479
0.231918052913
0.231732583597
0.231692976983
0.231761491573
0.231789566145
0.231768512605
0.23173825328
0.231681181992
0.23159096117
0.231486346556
0.231052403535
0.230269604991
0.229133287988
0.227725656429
0.226142927151
0.22439699807
0.222751856955
0.221173875059
0.219482679485
0.218697634974
0.218021150208
0.217391195871
0.21674608668
0.216055999911
0.215305726463
0.214485993997
0.213590035719
0.212613069397
0.211550714381
0.210400470998
0.209161246595
0.207836503061
0.206436900327
0.20498031778
0.2035295599
0.202349958738
0.201496128108
0.201229240887
0.201645980496
0.202784750077
0.204683768346
0.207345024197
0.21071665405
0.214677420129
0.21901348205
0.223429829797
0.227330214771
0.230956840263
0.241884860623
0.241811707321
0.241447506126
0.24093124325
0.240307233924
0.239641753668
0.238986721299
0.23838170798
0.237855651938
0.237424967588
0.237106626684
0.236874760473
0.236640708585
0.236416859561
0.236231539149
0.236087273597
0.235966240241
0.235858165967
0.235773137037
0.235692210848
0.235583769413
0.23542893602
0.235231660938
0.235007833975
0.234764169164
0.234497830702
0.234205728107
0.23388895412
0.233551401507
0.233194672687
0.232835068913
0.232507842886
0.232231400256
0.232028950407
0.231971444212
0.232037609329
0.232073862273
0.232057381804
0.232032140011
0.231973029042
0.23189253477
0.231770926211
0.23130060243
0.23047785211
0.229311767438
0.227900980223
0.226318376765
0.224595707068
0.22304139621
0.221472958239
0.220190835871
0.219360377554
0.218676669505
0.218046786335
0.217395401264
0.216692069272
0.215922866427
0.215079899221
0.21415678369
0.213148624784
0.212049997248
0.21085766187
0.20956857335
0.208185247305
0.206716694343
0.205188276887
0.20369206608
0.202510741714
0.201839927752
0.2017442836
0.202303209571
0.203622580793
0.205737938453
0.208621585056
0.212190572755
0.216292060521
0.220685819157
0.22504696484
0.228911832272
0.232209082839
0.242710541178
0.242645152775
0.242289276053
0.24177730716
0.241156458395
0.240490610187
0.239831474173
0.239218983918
0.2386838511
0.238244769081
0.237926711455
0.237683953235
0.237432954813
0.23718821833
0.236978385956
0.236805307646
0.236653748282
0.236508905207
0.236377805522
0.236251166926
0.236104434371
0.235918783251
0.235695552435
0.235449891601
0.235189046385
0.234909752357
0.23460747824
0.234281963314
0.233936468163
0.233573081737
0.233201839632
0.232858827104
0.23256703153
0.232349010922
0.232272787097
0.23233242414
0.232375118733
0.232362836166
0.232343585781
0.232282479352
0.232216200686
0.232071012157
0.231566537878
0.230706190495
0.229516004078
0.228105301507
0.226512292492
0.224801775863
0.223262801184
0.221579456403
0.220747565823
0.219973542243
0.219304026658
0.218670070411
0.218005690738
0.217282267548
0.216486116703
0.215609848493
0.214646838114
0.213591574812
0.212436696424
0.211177440426
0.209806324619
0.208323698276
0.206744141835
0.205134832436
0.203567421472
0.202195920229
0.201562531979
0.201501299457
0.202105414492
0.203482189575
0.205658352345
0.208591500881
0.212177892504
0.216241825545
0.220526390333
0.224699762175
0.228333648547
0.230838659279
0.243496659042
0.243437889755
0.24309235359
0.24259125619
0.241983840504
0.241329937011
0.240679684906
0.240072342264
0.239539394413
0.239101266383
0.238787134153
0.238537084839
0.238277749532
0.238013740052
0.237776315385
0.237570316553
0.237383203557
0.237199243912
0.237021897593
0.236848307736
0.23666071351
0.236441531845
0.236189442727
0.235918611158
0.23563739285
0.23534276392
0.23502885191
0.23469368202
0.234339442829
0.233968463188
0.233586918813
0.233229536894
0.232923596542
0.232691545237
0.232596949623
0.232646985374
0.232694173078
0.232684988277
0.232671960278
0.232608656098
0.232561240095
0.232386174996
0.231850161016
0.230955331263
0.229749649623
0.22834946598
0.226758044704
0.225091577654
0.223552089286
0.221730339877
0.221209299647
0.220541537508
0.219899112539
0.219256162601
0.218570024981
0.217817098331
0.21698340103
0.216060839472
0.215041456125
0.213918360968
0.212681368552
0.211324014171
0.209832267601
0.208213913259
0.206510449855
0.204707130401
0.202881943045
0.201470401082
0.200655867232
0.200477710922
0.201014587064
0.202332869003
0.204443228098
0.207294232734
0.210771093059
0.214685424247
0.218775716484
0.22270937494
0.226026810414
0.228428241377
0.244225616882
0.244167781161
0.24383205149
0.243347924958
0.242763978253
0.242133918105
0.241504678852
0.240913772587
0.240392361143
0.239961804873
0.239650976755
0.239400011528
0.239142056387
0.238862484011
0.238596893573
0.23835597867
0.238131032616
0.237908021072
0.237687154284
0.237468667619
0.237240912853
0.236988474635
0.236707223007
0.236409682722
0.236105954235
0.235794183995
0.235467613857
0.235122408488
0.234759310127
0.23438059836
0.233989252617
0.233618511385
0.233299534448
0.233054534471
0.232942083231
0.232981259773
0.233031923182
0.233024711526
0.233017296866
0.232951044615
0.232926610826
0.232715446682
0.232149484311
0.231221999177
0.230009289026
0.228633458694
0.227073238436
0.225515069687
0.224021630227
0.222195048867
0.221703804731
0.221090799293
0.220461288809
0.219799556937
0.219081027576
0.218287098861
0.21740283467
0.216417976544
0.215321413964
0.214103035283
0.212747713372
0.211246371758
0.209578590241
0.207786998218
0.205852978383
0.203663431812
0.201614389774
0.200005285287
0.198990989097
0.198649420819
0.199041757997
0.200211196222
0.202159508688
0.204833831309
0.208119507598
0.211827016181
0.215701913389
0.219395175594
0.222560521339
0.225206558399
0.244885840206
0.244811179647
0.244483716066
0.244023840443
0.243474036485
0.24287968561
0.242282822279
0.241718352809
0.241216240317
0.24079805033
0.240490109556
0.240247860005
0.239996690959
0.239707130341
0.239415591535
0.239140312573
0.238877838507
0.238618008135
0.238357791572
0.238098251771
0.237833271596
0.237550132024
0.237241905802
0.236918212977
0.236591092384
0.23626100561
0.235921146394
0.235565951431
0.235194436552
0.234808448554
0.23440836519
0.234024840678
0.233693518002
0.233436158459
0.233306119364
0.233334239268
0.233388718224
0.23338288399
0.233379854744
0.233309108486
0.233310574489
0.233057031998
0.232460764052
0.231499688811
0.230284561765
0.22894083148
0.227435509717
0.22603104292
0.224607447536
0.222924962099
0.222265204245
0.221628589833
0.220984716715
0.220291881233
0.219529821045
0.218682342691
0.217732821192
0.216667499519
0.215469781095
0.214122554501
0.212600798387
0.210887768871
0.208956524725
0.206870871025
0.204458375082
0.20196274899
0.199690345281
0.197866774603
0.196639071364
0.196090230943
0.196273805012
0.197222649823
0.198936280315
0.20136783504
0.204412709639
0.207895560727
0.211594959118
0.215097009986
0.218080494882
0.220129760292
0.24543703696
0.245331202694
0.245022298186
0.244599186819
0.244096071514
0.243549484321
0.242995599695
0.242466423733
0.241990345815
0.241588958664
0.241287183204
0.241055751495
0.240811466932
0.240523207053
0.240212585941
0.239906219663
0.239608829695
0.239314921862
0.239019337058
0.238724249306
0.238426851738
0.238117223544
0.23778615845
0.237438993232
0.237089063616
0.23674016162
0.236386662746
0.236021763897
0.235642597197
0.235250076506
0.234843032726
0.234447824001
0.234104021905
0.233834330797
0.23368664306
0.233703470458
0.23376296531
0.233758835108
0.2337587994
0.233681634336
0.233710630006
0.233408536618
0.232779834853
0.231781835818
0.230563379338
0.229245728428
0.227791659031
0.226526229303
0.2251316033
0.223685102082
0.222836604772
0.22213809187
0.221458481259
0.220723146004
0.219906650657
0.218992424342
0.217961553226
0.21679609736
0.215472324592
0.213962231547
0.212226095691
0.210236800759
0.207932590965
0.205290162072
0.202414114764
0.199684519338
0.197200887569
0.195156975695
0.1937016678
0.192915837368
0.192847690113
0.193526274319
0.1949555676
0.19710174013
0.199875891108
0.203124196891
0.20664527688
0.209910650692
0.212207071924
0.213798519709
0.245803430905
0.245687766366
0.245428669715
0.245062237459
0.244620116693
0.244132612673
0.243630911981
0.243144432549
0.242699898017
0.242318582729
0.242024614755
0.241797917861
0.241566487299
0.241292118285
0.24097227809
0.240640712117
0.240312542485
0.239987608752
0.239661890292
0.23933736025
0.239012822378
0.238681466534
0.238332861527
0.237966830534
0.237596269709
0.237228866177
0.236861575532
0.236487289828
0.236101302183
0.23570293074
0.235290309335
0.234885351219
0.234528950463
0.23424627931
0.234080115917
0.234083794103
0.234149500839
0.234148793534
0.234151387195
0.234066342878
0.234123735976
0.23376768464
0.233103837235
0.232065127877
0.230838342478
0.229527768822
0.228093424904
0.226894431677
0.22544097119
0.224321821617
0.223364547068
0.222600737855
0.221872573569
0.221084558576
0.220202478746
0.219207120192
0.218076379371
0.216787590377
0.215309774908
0.213605417054
0.211632486443
0.209354011156
0.206541133854
0.203185227821
0.200005673071
0.196996495186
0.194275295934
0.192011348836
0.190327520907
0.18929366279
0.188952014099
0.189331694929
0.190448076129
0.192289329682
0.194795984118
0.197844648121
0.201102004908
0.203974438983
0.205800057698
0.207118694065
0.245983853143
0.245899100076
0.245711539058
0.245417584186
0.245047331238
0.244626680418
0.244183594699
0.24374513599
0.243336265487
0.242977694805
0.24269207884
0.242466875239
0.242255563404
0.241999551267
0.24168281621
0.241335022152
0.240981640341
0.240629931652
0.240279409468
0.239930443696
0.239583867166
0.239235498735
0.238874985021
0.23849632281
0.23810914761
0.237724700069
0.237343780674
0.236960358424
0.236568421225
0.23616544006
0.235748651003
0.23533593969
0.234967094827
0.234670150744
0.234483778216
0.234469227713
0.234540954813
0.234546840443
0.234553460174
0.234460549507
0.234547185461
0.234133115494
0.233432194908
0.232350707264
0.231109958708
0.22978396708
0.228332206345
0.227115913781
0.225517401916
0.22476211396
0.223810151639
0.223002052625
0.222220375369
0.221370282824
0.220410586864
0.219318067956
0.218065507046
0.216622885733
0.214952018612
0.213014897507
0.210791213094
0.208062257719
0.204561490438
0.200847939941
0.197293863084
0.193992535145
0.191051234781
0.188590524336
0.186699838223
0.185431581205
0.184818815421
0.184892013698
0.185682986935
0.187214517737
0.189488010473
0.192360539435
0.195326421798
0.197533867427
0.199146466331
0.200381108177
0.246060044404
0.246033939201
0.245904562742
0.245684633394
0.245388265602
0.245036399063
0.244654564544
0.244266941872
0.24389641287
0.243562811319
0.243286504256
0.243065328051
0.242868999912
0.2426322774
0.242333732619
0.241982237468
0.241611224062
0.241237987552
0.24086689087
0.240498167435
0.240134598925
0.239773630653
0.23940620677
0.239021771462
0.238623956635
0.238225512309
0.237831770239
0.237439395288
0.237042172464
0.236635854059
0.236216502519
0.23579841334
0.235418388187
0.235106337159
0.234898028778
0.234857355207
0.234932227584
0.234948455149
0.234961965432
0.234862356343
0.234979246018
0.234504623272
0.233766327063
0.232642910626
0.231385404064
0.230029794309
0.228545137464
0.227276423382
0.225524657129
0.225040034336
0.224165876371
0.223336887566
0.222499770191
0.221577818193
0.220527125742
0.219320001563
0.217921266518
0.216288786505
0.214376528552
0.21214925428
0.209514567924
0.206047226093
0.202129555161
0.198133866758
0.194307202996
0.190790537094
0.187686004893
0.185080193992
0.183031811178
0.181571143699
0.18071818425
0.180502560733
0.180970378954
0.182190112696
0.184229873442
0.186837048965
0.189307950868
0.191256716005
0.192800083367
0.193946819648
0.246096480876
0.24611938555
0.246028063934
0.245880644219
0.245655164738
0.245370034484
0.245048761837
0.244712428181
0.244381531518
0.244074548676
0.243809082066
0.243592828141
0.243402392412
0.243191323223
0.242917749291
0.24257679704
0.242198352988
0.241809732447
0.241422163523
0.241038625285
0.240661983639
0.240291944967
0.239921387405
0.239537412873
0.239136515848
0.238729102181
0.238324545459
0.237923596896
0.237521450643
0.237112833982
0.2366924281
0.236270944254
0.235881750485
0.235555312276
0.235325739255
0.235252904921
0.235324797206
0.235353999669
0.235376788903
0.235271555154
0.23541915653
0.234882511807
0.234108259868
0.23294657861
0.231674105653
0.230289188907
0.228786819853
0.227491921555
0.225683212189
0.225262007513
0.224456132615
0.223610453963
0.222712600838
0.221707192956
0.220550309269
0.219209409558
0.21763838623
0.215783869871
0.213603173614
0.211006161127
0.207606909947
0.203561132184
0.199399167249
0.195204795223
0.191194327637
0.187543401878
0.184352037581
0.181679028818
0.179550574695
0.177969673711
0.176939578548
0.176484001946
0.176664909558
0.177633173482
0.17941759456
0.181621766012
0.183627384895
0.185554160705
0.187107001869
0.188149353256
0.246129158858
0.24616823465
0.246111990556
0.246023568797
0.245860849861
0.245637538675
0.245373455639
0.245086904757
0.244795740347
0.244516652595
0.244264951959
0.244053274662
0.243867110187
0.24367540852
0.243428556958
0.243113033094
0.242740607378
0.242344524848
0.241945289495
0.241550867955
0.241164183053
0.240787947452
0.240417147311
0.240038249574
0.239641681378
0.239232502405
0.238821118278
0.238412830434
0.238006005144
0.237595679247
0.237175647227
0.236752961558
0.23635686012
0.236017811974
0.235769608759
0.235664925943
0.235724957695
0.235767177151
0.235799892268
0.235688726725
0.235866208837
0.235266599544
0.234459114925
0.233264435658
0.231982511051
0.230580620322
0.229092615178
0.227810283907
0.226033912293
0.225500793079
0.224709589566
0.223832326929
0.22286269042
0.221759764749
0.220479407213
0.218982381988
0.217209925707
0.215114930863
0.212680073801
0.209496979225
0.205317174894
0.20096988144
0.196553583852
0.192190914411
0.188083026368
0.184395375379
0.181217999599
0.178582656343
0.176479574492
0.174879190237
0.173759511322
0.173120921114
0.173071661524
0.173905207383
0.175373116625
0.177068243328
0.1789771683
0.180910026022
0.182387259707
0.183213853348
0.246170553208
0.246200000676
0.24618400534
0.246128809637
0.24601772616
0.245849045138
0.245636887035
0.245397185702
0.245144855651
0.244894382671
0.244659105338
0.244451297442
0.244268954159
0.244087659638
0.243869988372
0.24358426678
0.243233667263
0.242841181379
0.242436322659
0.242034448593
0.24164144444
0.241260970912
0.240891605921
0.24052065156
0.240134056329
0.239731392989
0.239319643415
0.238907092649
0.238496447675
0.23808478434
0.23766581081
0.237243843901
0.23684330504
0.236493551274
0.236227924067
0.236094149614
0.236134422223
0.236188276942
0.23623127813
0.236113702062
0.236319170886
0.235655791578
0.234818382318
0.233595883807
0.232311265186
0.230909906814
0.22946801236
0.228218656602
0.226492737844
0.225772194092
0.224943417007
0.224011072568
0.222954053381
0.221737416468
0.220314256404
0.218634541443
0.216630427417
0.214279890516
0.211425167311
0.207434847571
0.202952582073
0.198311961416
0.193671289461
0.189203248866
0.185091356218
0.181478751143
0.17843611979
0.175964929667
0.174016480149
0.172525142143
0.171423470183
0.170669394028
0.170500937027
0.17111053021
0.172392866198
0.173956289684
0.175803443612
0.177586766461
0.178843788463
0.179261346703
0.246210877814
0.246221555436
0.246235638626
0.24619762512
0.246132396592
0.246012408783
0.245847085406
0.245650666554
0.24543555304
0.245213907211
0.244997206968
0.244795847515
0.244616153193
0.244441432102
0.244243842996
0.24399250569
0.243675042568
0.243298930884
0.242896361017
0.242491308128
0.242094952712
0.241711816409
0.241344494676
0.240982394233
0.240609341076
0.24021995108
0.239816305807
0.239405257761
0.238993409455
0.238581375525
0.238164235157
0.237744300156
0.237341096563
0.2369820053
0.236699056513
0.23653562173
0.236547314117
0.236611578868
0.236667919844
0.236545301017
0.236776833924
0.236048569796
0.23518420608
0.233937398783
0.232655521982
0.231270407986
0.22989442326
0.228679849231
0.227005519945
0.226076278183
0.225166092366
0.224152352372
0.222989808136
0.221642008294
0.220055295471
0.218167973806
0.215917543699
0.213243436078
0.209561214249
0.205112555712
0.200429621953
0.195599299772
0.190825975917
0.186337596172
0.182321944071
0.178901840349
0.176121155157
0.173946197614
0.172290247513
0.171054101578
0.170108388289
0.169429918767
0.169488310665
0.169962161757
0.170805629182
0.172348066716
0.174020960577
0.175509887682
0.176477517722
0.17651785807
0.246243724344
0.246243901088
0.246267783431
0.246249055745
0.246215788794
0.246136288647
0.246012315221
0.24585499921
0.245674851237
0.245481772634
0.245285380288
0.245094378158
0.244916128538
0.244746854977
0.244564200878
0.244342358618
0.244057925865
0.243713307212
0.243325283576
0.24292312717
0.242525913937
0.242142350377
0.241776975853
0.241423665666
0.241066256255
0.24069384093
0.24030536348
0.239903852811
0.239495946863
0.239085901001
0.238671829796
0.238255339834
0.23785126874
0.237484016425
0.237184008038
0.236990338333
0.236962970724
0.23703339905
0.237107633694
0.236983443129
0.237239099178
0.236443523203
0.235554007096
0.234283768221
0.233006920054
0.231646569344
0.230338226022
0.22914616927
0.227527570058
0.226397637108
0.22537630066
0.224257668194
0.222971673011
0.221474549787
0.219701621542
0.217595867944
0.215125275177
0.211904086343
0.207435616071
0.202776695942
0.197892333463
0.192912123043
0.188084923047
0.183666936818
0.179850566164
0.176734921314
0.174328679344
0.172556957831
0.171300668663
0.170438794035
0.169814187071
0.169491277869
0.169462778827
0.169953445881
0.170782833191
0.172007050441
0.173290749321
0.174392460443
0.175028209131
0.174987906299
0.246273821731
0.246273743738
0.246290984371
0.246293039692
0.246274526173
0.246227824689
0.246139858037
0.246017378228
0.245869550389
0.245704308959
0.245529399709
0.245352019422
0.245178321812
0.245011678948
0.244838322855
0.244637228603
0.244387114629
0.244078640296
0.243719833403
0.243330463811
0.242936788968
0.242554680711
0.242190482333
0.241845422627
0.241504590486
0.241151433625
0.240782081841
0.240397213293
0.240000502778
0.239597127001
0.239188604809
0.238776982718
0.238373928416
0.238000272469
0.23768488846
0.237464056595
0.237393486714
0.237458151056
0.237552174081
0.237429749918
0.237706583809
0.23683914305
0.235924952239
0.234629461376
0.233356185406
0.232019627339
0.230762892119
0.2295716011
0.228017504154
0.226713016391
0.225566437703
0.224325490488
0.222900328268
0.221235846605
0.219256631029
0.216929375563
0.214108478495
0.21004086318
0.205359699451
0.200481824003
0.195397816565
0.190308552474
0.185499514705
0.181243695834
0.177725232392
0.175007297639
0.173050927108
0.171732746212
0.170909290619
0.170436730187
0.170102913303
0.169876884401
0.17010600384
0.170584856194
0.171287079077
0.172202307475
0.173142251471
0.173913095402
0.174256375279
0.174338625207
0.246302443949
0.246303712409
0.246309048305
0.246325027164
0.246316250082
0.246293612478
0.246236082186
0.246144458492
0.24602605971
0.245887448625
0.24573466629
0.245573463006
0.245408698752
0.245244023639
0.245077865078
0.244892802718
0.244668972316
0.244397372487
0.244076337646
0.243712529363
0.24332960983
0.242951333219
0.242590097942
0.242251168615
0.241924621779
0.241592416567
0.24124484712
0.240880578963
0.240501414706
0.240110870658
0.239712184473
0.239308303235
0.238908438373
0.238530754424
0.238202405208
0.237958060956
0.237848201558
0.237892041819
0.238003464737
0.237885757922
0.238179730101
0.23723371616
0.236294372826
0.234969700082
0.233695472191
0.232373713162
0.231141553468
0.229926590849
0.228445420616
0.227001503241
0.225728527797
0.224354275903
0.222776338763
0.220926802911
0.218736155915
0.216185719516
0.212704120929
0.20803253484
0.203210774054
0.198197694872
0.192969286065
0.187827189747
0.183110135952
0.179104111275
0.175969400102
0.173712687824
0.172233723984
0.171357602054
0.170914987134
0.170664527562
0.170431155033
0.170391944484
0.17068245965
0.171157917266
0.17177675039
0.172513061649
0.173239346544
0.173809379193
0.174010165505
0.174202845768
0.246328521994
0.246329609855
0.246331217156
0.246349080473
0.246351579169
0.246339943293
0.246306648906
0.246242058776
0.246150134814
0.246036542945
0.245906007786
0.245762902679
0.245611052647
0.245453312461
0.24529140473
0.245118579187
0.244917900504
0.24467572053
0.244391046208
0.244065343261
0.243705296962
0.243336288383
0.242979480039
0.242643970152
0.242329198446
0.242018292977
0.241694865598
0.241353996775
0.240996185219
0.240623828948
0.24023966016
0.239847055184
0.239453553741
0.239074725611
0.238736035792
0.238470360612
0.23832382909
0.238332874597
0.238458258066
0.238350803327
0.238659127212
0.237626201022
0.236660337903
0.235301024713
0.234019665771
0.232699754964
0.23146474314
0.230208920914
0.228802884359
0.227252768137
0.225859381775
0.224345096561
0.222601792811
0.220557612481
0.218170475746
0.215227344799
0.210911718872
0.206127645432
0.201132068338
0.195986355058
0.190638776806
0.185497450709
0.180947569301
0.177271338831
0.174586332332
0.172818685436
0.171794800332
0.171299920883
0.171104736651
0.170940899435
0.170763993351
0.170828656252
0.17118006198
0.171644109976
0.172206198155
0.172832059291
0.173425879343
0.173887877318
0.174060616173
0.174289967961
0.246352506355
0.246353888623
0.246356725735
0.246365538617
0.246376855558
0.246371950277
0.246356266062
0.246315088801
0.246246958383
0.246156442797
0.246047671569
0.245923860443
0.24578786201
0.245641768219
0.245486765987
0.24532244224
0.24513927109
0.244924004527
0.244670384664
0.244381799518
0.24405905055
0.243710510152
0.24336144809
0.243030299456
0.242724039326
0.242431556595
0.242133447413
0.241818903279
0.241485862913
0.241135606415
0.240770424188
0.240393118661
0.240009304721
0.239632426595
0.239286095221
0.239001082952
0.238819161765
0.238781526584
0.238913092242
0.238823375769
0.239146142785
0.238016649187
0.237021919185
0.235621517106
0.234326597804
0.232995236818
0.231737348065
0.230435826538
0.229100056035
0.227467156136
0.225961245913
0.224302656905
0.222383105806
0.220143643729
0.217524154277
0.213885138686
0.209097875079
0.204210833881
0.199105643864
0.193869235573
0.188424658749
0.183342237866
0.179037004781
0.175762935942
0.173569480159
0.172265710315
0.171629442603
0.171420882862
0.171347314502
0.171182236633
0.171062170266
0.171201845171
0.171593286449
0.172051503606
0.172573665453
0.173123958025
0.17362993861
0.174030691558
0.174225109455
0.174459803811
0.246374338698
0.246375751092
0.246378447595
0.246382453436
0.246395559178
0.246398189103
0.246389442439
0.246367699591
0.24632085559
0.2462513391
0.246163301636
0.246059233641
0.245941085561
0.245810276242
0.245667245999
0.245511600441
0.245341899225
0.245149192812
0.244924313846
0.244666961051
0.244382756514
0.244070274276
0.243739610322
0.243416015013
0.24311411198
0.242835547632
0.242562686034
0.242276950121
0.241971946748
0.241647405797
0.241304858852
0.24094653963
0.240576433349
0.240204842176
0.239853922545
0.23955279116
0.239340078509
0.23925369821
0.239370510291
0.23930201017
0.239641439416
0.238405120329
0.237378947186
0.235931025135
0.234617211649
0.233262666102
0.231970019989
0.230624462353
0.229352875459
0.227649895795
0.226037884632
0.224232354862
0.222141628362
0.219736792228
0.216686445868
0.212231939183
0.207385614493
0.202377788494
0.197170123195
0.191869000674
0.186342603778
0.181382001554
0.177400869409
0.174595521009
0.172904772233
0.171961110021
0.171644984072
0.171637339955
0.171526394152
0.171397369385
0.171332444505
0.171524627706
0.171928731754
0.172379036487
0.172870404456
0.173367954578
0.173816040051
0.174181434888
0.174412733867
0.174639193614
0.246394161605
0.24639553623
0.246398099837
0.246401931153
0.246408412929
0.246416599477
0.246411103169
0.246403657293
0.246375253934
0.24632478794
0.246256060655
0.246171470137
0.246072311874
0.245959391742
0.245832666473
0.245691121785
0.245533538428
0.245358920988
0.245160472648
0.244932342654
0.244679143865
0.244406130504
0.244109930093
0.243802268697
0.243507486567
0.243238101782
0.242985991747
0.242730232775
0.242456327233
0.242160879824
0.241844556706
0.241508747682
0.241156112635
0.240793738993
0.240441429152
0.240127922422
0.239889005874
0.239759369394
0.239835592367
0.239784429221
0.240142883153
0.238790411972
0.237731484741
0.236230817813
0.234894899649
0.23350866338
0.232178187062
0.230794426239
0.229580633883
0.227810147308
0.226092558552
0.224136629541
0.221889244755
0.219287735822
0.215544081398
0.210639795243
0.205703513672
0.200619171224
0.195336104884
0.189993245168
0.184399642621
0.179631557506
0.176054105344
0.173765826826
0.172538070211
0.171845908554
0.171866053949
0.1717947688
0.171707158198
0.171601413127
0.171574837006
0.171790103693
0.172193757677
0.172635187994
0.173101470605
0.173561699521
0.173973065531
0.174320323655
0.174590293279
0.17481189374
0.246412190008
0.246413506812
0.246415754613
0.246418783963
0.246421777639
0.246428648851
0.246430416899
0.246428037918
0.246413727902
0.246379871869
0.246328651127
0.246262648091
0.246182813433
0.246089424317
0.245982042254
0.245859306058
0.245719278649
0.245560697245
0.245383597928
0.24518443313
0.24496004645
0.24471771823
0.244461402833
0.244187315753
0.243908385594
0.243645457701
0.243408900708
0.243181992758
0.242941366028
0.242678186101
0.24239117723
0.242081279042
0.241750503041
0.241402172544
0.241052211148
0.240729594415
0.240468611696
0.24030019964
0.240317957722
0.240272299773
0.240649358995
0.23917143376
0.238079283069
0.236521656801
0.235161589247
0.233739994778
0.232385432739
0.230983825439
0.229813493795
0.227961665583
0.226131502926
0.224028161043
0.221645155178
0.218639221425
0.214088254982
0.209145490825
0.204100720254
0.198948854061
0.193612555476
0.188249750798
0.182603452807
0.178111978912
0.175012026923
0.173208370306
0.172318807938
0.172150506306
0.172051259811
0.171969766583
0.171886159118
0.171796105632
0.171789661327
0.172005512462
0.172400919339
0.172834275914
0.173280490093
0.173714596565
0.174104200783
0.174444980265
0.174749071
0.174986856954
0.246428722243
0.246429960471
0.246431867321
0.246434242043
0.246436551813
0.246438944205
0.246446303581
0.246443916469
0.246439028603
0.246418933138
0.24638334901
0.246334600901
0.246273706354
0.246200581723
0.246114381611
0.246013459927
0.245895514445
0.245758281529
0.245600861047
0.245424334289
0.245229525205
0.245015737001
0.244790542496
0.244556765797
0.244310915597
0.244065656255
0.243839502323
0.24363341869
0.243427122443
0.243199704118
0.242945121499
0.242663412226
0.242357310305
0.242028604641
0.241686516364
0.24135899596
0.241080911273
0.240882048673
0.24084323566
0.240781410851
0.241170504967
0.239550118664
0.23842110511
0.236801227587
0.235412624478
0.233954906077
0.232601694252
0.231202688162
0.230073118719
0.228118515926
0.226164226021
0.223934189268
0.221330683397
0.217498206947
0.212608211481
0.207649991684
0.202554258052
0.19736545187
0.191998526802
0.186638484641
0.180958229496
0.17685423141
0.174301140029
0.172896950861
0.172348774425
0.172417589083
0.172240183636
0.172137529786
0.172054866766
0.171977615251
0.171979935959
0.172182909694
0.172564628357
0.172991166882
0.173422286198
0.173839284165
0.174217841824
0.174558786408
0.174884756354
0.175158141025
0.246444000688
0.246445084128
0.246446623867
0.246448258021
0.246449587983
0.246450313332
0.246453586749
0.246456139329
0.246454467433
0.246444571949
0.246422380072
0.246389162528
0.246346205262
0.246293248759
0.246229014134
0.246151482333
0.246058067051
0.24594602696
0.24581325888
0.245659387466
0.245486496359
0.245301264151
0.245105753527
0.24490431142
0.244698912097
0.244488040472
0.244280524969
0.244093318747
0.243917408932
0.243727585153
0.243507363713
0.24325495162
0.242973500046
0.242666531747
0.242337774808
0.242010774511
0.241721357839
0.241499729303
0.241417287555
0.241327273496
0.241718940175
0.239928370037
0.238753157166
0.237063135222
0.235636978307
0.234141902162
0.232797766039
0.231372361223
0.230341440001
0.228290358306
0.226208466177
0.223877616601
0.220870854679
0.216089405119
0.211203559121
0.20620662126
0.201073806029
0.195871698596
0.190494507681
0.185154122996
0.179465455479
0.175881792183
0.173874118152
0.172739452626
0.172716974209
0.172541834832
0.172394683606
0.172288188085
0.172210616874
0.172146197454
0.172150438591
0.172332494142
0.172696677382
0.173118451525
0.173539905398
0.17394768633
0.174322893361
0.174666370381
0.174997762931
0.175324229874
0.246458147196
0.246458985925
0.246460182009
0.246460982771
0.246461242856
0.246460560761
0.24645994651
0.246463779682
0.246462590337
0.246459001362
0.246447755322
0.246428325227
0.246401888305
0.246368297261
0.246325895759
0.246272170236
0.246204144829
0.246118758404
0.246013403043
0.245886641353
0.245738951966
0.245573802015
0.245404178276
0.245234213047
0.245061336775
0.244891989857
0.244723714374
0.244559000743
0.244409474778
0.2442585994
0.24407568929
0.243852894144
0.243594432763
0.243307562214
0.242995047506
0.242673950156
0.242379337699
0.242141679752
0.24202345859
0.241905866078
0.242291951966
0.240302039087
0.23906748049
0.237295986807
0.235816688423
0.234280771751
0.232934709561
0.231472420078
0.230621228087
0.228506863855
0.226290129949
0.223673865193
0.219686406894
0.214733155588
0.20983075527
0.204802938334
0.19965458892
0.194461942174
0.189094633732
0.183784677569
0.178132429141
0.175182323097
0.173576829859
0.173002852205
0.172953142596
0.17271373036
0.172544267606
0.172429629528
0.172356625077
0.172305052793
0.172308355646
0.172466890668
0.172808118788
0.173225981937
0.173643983952
0.174050008422
0.174427991834
0.174778293467
0.175124279885
0.175504666581
0.246471175834
0.246471727939
0.24647264276
0.246472561998
0.246471757474
0.246469839553
0.246467770461
0.246466746121
0.246467446899
0.246464767436
0.246461628515
0.246454151744
0.246442691908
0.246427226364
0.246405817591
0.246375373695
0.246332383214
0.246273402752
0.246195544745
0.246097030363
0.245977805629
0.245840060603
0.245691051311
0.245536753745
0.245391001987
0.245256792544
0.24513081148
0.24501112008
0.244896975167
0.244782472553
0.244640602491
0.244449014473
0.244211101829
0.243939887382
0.243642297498
0.243331207882
0.243038299724
0.242792284895
0.242646730604
0.242506752977
0.24287928898
0.240663635424
0.239354108747
0.237484766069
0.235923454969
0.234325031365
0.232943667947
0.231496964158
0.23089888214
0.228790922314
0.226345697025
0.22299480782
0.218105463605
0.21329138003
0.208449338525
0.203432693479
0.198295291074
0.193133526859
0.187789471137
0.182517579145
0.176984008535
0.174729507126
0.173355687601
0.173382926903
0.173068645059
0.172842420865
0.172670672058
0.172559710088
0.1724986434
0.172465147553
0.172470298348
0.172606642791
0.172910903092
0.173315948755
0.17374217174
0.17415557244
0.174546096596
0.174923227589
0.175316499959
0.17573850358
0.246483120147
0.246483370869
0.246484037481
0.246483166444
0.246481314719
0.246478409053
0.246474971016
0.2464715001
0.246469191935
0.246467238644
0.246467082342
0.246469027554
0.246470946385
0.246472117068
0.246470388527
0.246462009005
0.246442760791
0.246408689098
0.246356590413
0.246284470427
0.246192027429
0.246080985367
0.245956022182
0.245823068744
0.24569141608
0.24557032427
0.24547240519
0.24539773452
0.245332307025
0.24526809702
0.245176056543
0.245022468194
0.244805774805
0.244545476055
0.244258860219
0.243959802668
0.243676007835
0.243431457519
0.243269709384
0.24311415072
0.243466446184
0.241005841716
0.239606097232
0.237620017291
0.235933211305
0.234218813517
0.232715493271
0.231237601923
0.230738084623
0.228831750121
0.225888830737
0.221503554628
0.216632183863
0.211870215577
0.207087547149
0.202106487492
0.196997344388
0.191881118958
0.186559679351
0.18133738007
0.176002795548
0.174292016853
0.173334942242
0.173447576744
0.173127509568
0.172909162955
0.172756359506
0.172668150909
0.172633677297
0.172630248291
0.172653263935
0.172772329521
0.173037176993
0.173416212148
0.173843687202
0.174278517674
0.174704290284
0.175141470231
0.175607898516
0.17605894318
0.246493985071
0.246493993087
0.246494338598
0.246492899251
0.246490191952
0.246486725672
0.246482572954
0.24647804235
0.246473065379
0.246470156537
0.246469047245
0.24647662106
0.246489594972
0.24650559194
0.246521868969
0.246533866193
0.246536423811
0.246524900631
0.246495697045
0.246446570125
0.246377007563
0.246288532775
0.246185073304
0.246072321102
0.245957766932
0.245849721783
0.245757286306
0.245689582387
0.245653804357
0.245642661393
0.245620053759
0.245529014554
0.245347812593
0.245099250235
0.244818534089
0.24453145558
0.244263919316
0.244032948017
0.24386919708
0.243704372208
0.244032439361
0.241322186853
0.239822802285
0.237707799611
0.235854565988
0.233968897584
0.232235628515
0.230503910447
0.22942927787
0.227564404849
0.224115468252
0.219609453693
0.215060809972
0.210453548776
0.205773048466
0.200843330089
0.195767702141
0.190696271066
0.185371107539
0.180205446706
0.175104779311
0.173770813546
0.173487662064
0.173261131719
0.173043350516
0.172875029458
0.172773657691
0.172736137834
0.172754635172
0.172806977097
0.172873623503
0.172984480402
0.173214372218
0.173571363322
0.173998593099
0.174458864076
0.174943136391
0.175468483455
0.176025033466
0.176494791481
0.246503722522
0.246503658768
0.246503457519
0.246501707481
0.246498638445
0.246495039797
0.246490839122
0.246485970063
0.246480165533
0.24647415689
0.246474189537
0.246482184173
0.246502751836
0.246531104661
0.246563229777
0.246593411585
0.246615344126
0.246623481588
0.246613723078
0.246583518034
0.246532172103
0.246461124685
0.246374071808
0.2462765061
0.246175283399
0.246077932723
0.245992204409
0.245925428543
0.245883486054
0.245872352512
0.245900261003
0.245906089976
0.245797328981
0.245574881687
0.245298159458
0.245023006271
0.244779083765
0.244574664152
0.244424441676
0.244251631162
0.244555425722
0.241612979873
0.240012701654
0.237771384586
0.235732853666
0.233656801665
0.23164585602
0.229523249964
0.227621111252
0.225320049865
0.221793688507
0.217809419893
0.21355092545
0.209107877691
0.204544273596
0.1996684707
0.194623715544
0.189581416909
0.184196456142
0.179029325783
0.173907098524
0.172729195365
0.173248459277
0.173039601195
0.172871545204
0.172737069478
0.172692825476
0.17272259535
0.172822667888
0.172962213484
0.173104974327
0.173256938515
0.173484170686
0.173829032129
0.174261484933
0.174757492308
0.17531080309
0.175932266047
0.176582750368
0.1770630063
0.246512131576
0.246512202986
0.246511423425
0.24650956583
0.24650673527
0.246503538909
0.246499791563
0.246494873329
0.246488546575
0.246481809272
0.246480154856
0.246489855514
0.246515826148
0.246553359661
0.246598531701
0.246643805973
0.24668196006
0.246706399747
0.246712393694
0.246696922885
0.246659048082
0.246600244014
0.246524274413
0.246436629802
0.24634386027
0.246252961667
0.24617088804
0.246104108029
0.24605813725
0.246037552221
0.246045980713
0.246090798485
0.246090244325
0.245931358998
0.245666712006
0.245404441517
0.245197188665
0.245043158975
0.24494077672
0.244777364615
0.245064840139
0.241911128686
0.240199229883
0.237847365582
0.235630759351
0.233373463886
0.231054609487
0.228478556791
0.226017889586
0.223242620702
0.21983330544
0.216063029316
0.212008915611
0.207766158946
0.203395657892
0.198615534737
0.193611079194
0.188577873814
0.183075579218
0.177834942534
0.172378352963
0.171651008443
0.172514507793
0.172530316564
0.172523604785
0.1725025857
0.172540489757
0.172672327818
0.172894862971
0.173147528703
0.173384446472
0.173617762354
0.173889380621
0.174234717537
0.174671991207
0.175202931975
0.17582637216
0.176540243239
0.177277423163
0.17776018729
0.246518795674
0.246519052321
0.246518170596
0.246516605636
0.24651459111
0.246512390015
0.246509338204
0.246504563532
0.246498233365
0.246491637772
0.246489239773
0.246501804904
0.246530349082
0.246575647418
0.24663210403
0.246688876684
0.246739390142
0.246775968327
0.246793657614
0.246788733775
0.246759865895
0.246708625722
0.246639073391
0.246556926576
0.246468615768
0.246380708827
0.246299543348
0.246231009197
0.246180247493
0.246151409897
0.246148114093
0.2461754597
0.246217991557
0.246143129132
0.245906384704
0.245659281219
0.245512060589
0.24546626461
0.245492606726
0.24539796735
0.245697699777
0.242292580088
0.240411247244
0.237975854645
0.235620117184
0.233211577471
0.230533558004
0.227374046327
0.224416972552
0.221363800092
0.217937788691
0.214252197099
0.210357107559
0.206406449575
0.202394745521
0.197786603568
0.192820522647
0.187760152659
0.182121762799
0.176902168941
0.171385682464
0.17151745324
0.171812379181
0.172053011393
0.172256957308
0.172407879026
0.172561837249
0.17279610475
0.173081555107
0.1733816805
0.173674562318
0.173972190573
0.174303257551
0.174700918535
0.175190121391
0.175782484863
0.176481613655
0.177279375145
0.178085445281
0.178552242026
0.24652330202
0.246523576528
0.246523210721
0.24652263773
0.246522066602
0.246521280788
0.246519211183
0.246515233211
0.24651001422
0.24650524214
0.246504756857
0.246516686793
0.246547762583
0.246598966414
0.246662049708
0.246728551776
0.246789364571
0.246834323754
0.246859844676
0.246861152028
0.24683683551
0.246788878577
0.246721936028
0.246642060539
0.246555544063
0.24646845804
0.246386566792
0.24631519428
0.246259100922
0.246222762057
0.246208809775
0.246212642283
0.246208882505
0.246157552158
0.246022579898
0.245812909678
0.245721890409
0.245814753139
0.246006558255
0.246065903789
0.246483312444
0.242775202813
0.240637183431
0.238163021376
0.235750332109
0.233299689644
0.230437865116
0.227025120067
0.223822995427
0.22068731245
0.217250127778
0.213540612647
0.209634112754
0.205781129427
0.201900718389
0.197345437947
0.192324843473
0.187170316287
0.18149172843
0.176482640183
0.170516905292
0.171484645001
0.171595129842
0.171868224652
0.172137559961
0.172379927998
0.172621699237
0.17289005256
0.173185943074
0.173501900256
0.173838694082
0.174214219534
0.174662859633
0.17521138703
0.175820740883
0.176473933428
0.177214676063
0.178084856846
0.178938298729
0.179365294358
0.246525505809
0.246525609146
0.246525874178
0.246526589143
0.246527629758
0.246528277061
0.246527423667
0.246524817337
0.246521486175
0.246519375336
0.246522017559
0.24653562947
0.246567748523
0.246620912049
0.24668920158
0.246761210511
0.246826062977
0.246878316772
0.246910975452
0.246916277226
0.24689291968
0.246844140505
0.246776265686
0.2466961021
0.246609680404
0.246522390461
0.246439306516
0.246365020507
0.246303180194
0.246255819889
0.246221741763
0.246195404138
0.246165341616
0.246116242821
0.246042456559
0.245970937717
0.245963814531
0.246058422583
0.24625124803
0.246412798531
0.246797502314
0.243187130476
0.240811154111
0.238339432086
0.235946646208
0.233611262201
0.231137994277
0.229092628623
0.226364859535
0.223412665149
0.220015863899
0.21620145138
0.211960517087
0.207361770537
0.202236471201
0.197278453617
0.192068877765
0.186746295486
0.181196492029
0.176749466662
0.169324276369
0.170726675211
0.171201775004
0.171659289503
0.172017237702
0.172329875622
0.172630131929
0.172939042424
0.173263554219
0.173606017776
0.173972081887
0.174377104079
0.174848741909
0.175419145017
0.176103553262
0.17689285572
0.177795168177
0.178817052213
0.17974095564
0.180151737395
0.246525894609
0.246526025108
0.246526749383
0.246528157019
0.246529825924
0.246530869508
0.246530348271
0.246528322372
0.2465263363
0.246526808621
0.246533245337
0.246550885076
0.246585395307
0.246639598564
0.246709553355
0.246785110859
0.246854051003
0.246906199036
0.246939377509
0.246949665501
0.246927975129
0.246877289006
0.246806774714
0.246724638149
0.246636884108
0.246548468533
0.246464042593
0.246387767178
0.246322543575
0.246269391362
0.246227502802
0.246193045467
0.246158468284
0.246116573949
0.246068073894
0.246030259119
0.246034479109
0.246097929565
0.246192066925
0.24622032891
0.246546258042
0.243432175956
0.240890380313
0.238420036965
0.236048200086
0.233802390837
0.231734905199
0.230594980877
0.228349737538
0.225540937582
0.222175470783
0.218293554845
0.213817402503
0.208640846192
0.202666909232
0.197313040273
0.19196871287
0.186498694365
0.180715454206
0.174566520462
0.165102723066
0.169537992983
0.170781115543
0.171464948596
0.171918671196
0.172286782693
0.172622365376
0.172952916182
0.17329292096
0.173651155506
0.174037306373
0.174466473202
0.174959672536
0.175540224417
0.176232160282
0.177076811047
0.178144576496
0.179408125323
0.180482155093
0.180885012921
)
;
boundaryField
{
frontAndBack
{
type empty;
}
upperWall
{
type zeroGradient;
}
lowerWall
{
type zeroGradient;
}
inlet
{
type zeroGradient;
}
outlet
{
type fixedValue;
value uniform 0;
}
}
// ************************************************************************* //
| [
"as998@snu.edu.in"
] | as998@snu.edu.in | |
814f1289e8c958c485b7ec1308550c397b77c0aa | 6924d84805ef11ae874c50bf5cea64152e296750 | /refBoxComm/src/explorationInfoListenerNode.cpp | 13fee157820279c16cf1be451be8275d1027f77b | [] | no_license | ValentinVERGEZ/RBQT_communication | 95ad18cea7f2328411e3728fd58b68fc895bf4c1 | b3eabac8d33c0cd591ad64e1c569d11ff1f687cb | refs/heads/master | 2020-05-19T21:31:54.834701 | 2014-12-14T15:53:38 | 2014-12-14T15:53:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 629 | cpp |
#include "ros/ros.h"
#include "std_msgs/String.h"
#include "geometry_msgs/Pose2D.h"
#include "refBoxComm/ExplorationInfo.h"
void eiCallback(const refBoxComm::ExplorationInfo &ei)
{
for(int idx=0; idx < ei.signals.size(); idx++)
{
ROS_INFO("signal %d : %s", idx, ei.signals[idx].type.c_str());
}
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "explorationInfoListener");
ros::NodeHandle n;
ros::Subscriber sub = n.subscribe("/refBoxComm/ExplorationInfo", 1000, eiCallback);
ros::Rate loop_rate(50);
ros::spin();
return 0;
}
| [
"vincent.coelen@polytech-lille.net"
] | vincent.coelen@polytech-lille.net |
c37031c4d39298c4280ec1fa2d29a2c105dfd582 | 93db044eb00abbd18b75eeb0617dd1e054f2b199 | /Engine/Source/ThirdParty/PhysX/PhysX-3.3/include/PxQueryReport.h | 9aed019b55ecb2458ae8b1817b541217151a5809 | [] | no_license | cadviz/AHRUnrealEngine | 9c003bf9988d58ece42be4af030ec6ec092cd12e | e0c1a65098f4a86b4d0538535b5a85dd1544fd30 | refs/heads/release | 2021-01-01T15:59:31.497876 | 2015-04-13T22:03:55 | 2015-04-13T22:03:55 | 34,035,641 | 9 | 19 | null | 2015-04-16T05:12:05 | 2015-04-16T05:12:05 | null | UTF-8 | C++ | false | false | 16,776 | h | // This code contains NVIDIA Confidential Information and is disclosed to you
// under a form of NVIDIA software license agreement provided separately to you.
//
// Notice
// NVIDIA Corporation and its licensors retain all intellectual property and
// proprietary rights in and to this software and related documentation and
// any modifications thereto. Any use, reproduction, disclosure, or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA Corporation is strictly prohibited.
//
// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
//
// Information and code furnished is believed to be accurate and reliable.
// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
// information or for any infringement of patents or other rights of third parties that may
// result from its use. No license is granted by implication or otherwise under any patent
// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
// This code supersedes and replaces all information previously supplied.
// NVIDIA Corporation products are not authorized for use as critical
// components in life support devices or systems without express written approval of
// NVIDIA Corporation.
//
// Copyright (c) 2008-2013 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_PHYSICS_NX_SCENEQUERYREPORT
#define PX_PHYSICS_NX_SCENEQUERYREPORT
/** \addtogroup scenequery
@{
*/
#include "PxPhysXConfig.h"
#include "foundation/PxVec3.h"
#include "foundation/PxFlags.h"
#ifndef PX_DOXYGEN
namespace physx
{
#endif
class PxShape;
class PxRigidActor;
/**
\brief Scene query and geometry query behavior flags.
PxHitFlags are used for 3 different purposes:
1) To request hit fields to be filled in by scene queries (such as hit position, normal, distance or UVs).
2) Once query is completed, to indicate which fields are valid (note that a query may produce more valid fields than requested).
3) To specify additional options for the narrow phase and mid-phase intersection routines.
All these flags apply to both scene queries and geometry queries (PxGeometryQuery).
@see PxRaycastHit PxSweepHit PxOverlapHit PxScene.raycast PxScene.sweep PxScene.overlap PxGeometryQuery
*/
struct PxHitFlag
{
enum Enum
{
ePOSITION = (1<<0), //!< "position" member of #PxQueryHit is valid
eIMPACT = ePOSITION,//!< \deprecated Deprecated alias PX_DEPRECATED
eNORMAL = (1<<1), //!< "normal" member of #PxQueryHit is valid
eDISTANCE = (1<<2), //!< "distance" member of #PxQueryHit is valid
eUV = (1<<3), //!< "u" and "v" barycentric coordinates of #PxQueryHit are valid. Not applicable to sweep queries.
eASSUME_NO_INITIAL_OVERLAP = (1<<4), //!< Performance hint flag for sweeps when it is known upfront there's no initial overlap.
//!< NOTE: using this flag may cause undefined results if shapes are initially overlapping.
eMESH_MULTIPLE = (1<<5), //!< Report all hits for meshes rather than just the first.
//!< On SPU the number of reported hits per mesh is limited to 16 in no specific order.
eMESH_ANY = (1<<6), //!< Report any first hit for meshes. If neither eMESH_MULTIPLE or eMESH_ANY is specified,
//!< a single closest hit will be reported for meshes.
eMESH_BOTH_SIDES = (1<<7), //!< Report hits with back faces of triangles. Also report hits for raycast
//!< originating on mesh surface and facing away from the surface normal.
ePRECISE_SWEEP = (1<<8), //!< Use more accurate but slower narrow phase sweep tests.
//!< May provide better compatibility with PhysX 3.2 sweep behavior. Ignored on SPU.
eMTD = (1<<9), //!< Report the minimum translation depth, normal and contact point. Ignored on SPU.
eDIRECT_SWEEP = ePRECISE_SWEEP, //!< \deprecated Deprecated alias. PX_DEPRECATED
eDEFAULT = ePOSITION|eNORMAL|eDISTANCE,
/** \brief Only this subset of flags can be modified by pre-filter. Other modifications will be discarded. */
eMODIFIABLE_FLAGS = eMESH_MULTIPLE|eMESH_BOTH_SIDES|eASSUME_NO_INITIAL_OVERLAP|ePRECISE_SWEEP
};
};
/**
\brief collection of set bits defined in PxHitFlag.
@see PxHitFlag
*/
PX_FLAGS_TYPEDEF(PxHitFlag, PxU16)
/** \deprecated Deprecated definition for backwards compatibility with PhysX 3.2 */
#define PxSceneQueryFlag PxHitFlag // PX_DEPRECATED
/** \deprecated Deprecated definition for backwards compatibility with PhysX 3.2 */
#define PxSceneQueryFlags PxHitFlags // PX_DEPRECATED
/**
\brief Combines a shape pointer and the actor the shape belongs to into one memory location.
Used with PxVolumeCache iterator and serves as a base class for PxQueryHit.
@see PxVolumeCache PxQueryHit
*/
struct PxActorShape
{
PX_INLINE PxActorShape() : actor(NULL), shape(NULL) {}
PX_INLINE PxActorShape(PxRigidActor* a, PxShape* s) : actor(a), shape(s) {}
PxRigidActor* actor;
PxShape* shape;
};
/**
\brief Scene query hit information.
*/
struct PxQueryHit : PxActorShape
{
PX_INLINE PxQueryHit() : faceIndex(0xFFFFffff) {}
/**
Face index of touched triangle, for triangle meshes, convex meshes and height fields.
\note This index will default to 0xFFFFffff value for overlap queries and sweeps with initial overlap.
\note This index is remapped by mesh cooking. Use #PxTriangleMesh::getTrianglesRemap() to convert to original mesh index.
\note For convex meshes use #PxConvexMesh::getPolygonData() to retrieve touched polygon data.
*/
PxU32 faceIndex;
};
/** \deprecated Deprecated definition for backwards compatibility with PhysX 3.2 */
#define PxSceneQueryHit PxQueryHit
/**
\brief Scene query hit information for raycasts and sweeps returning hit position and normal information.
::PxHitFlag flags can be passed to scene query functions, as an optimization, to cause the SDK to
only generate specific members of this structure.
*/
struct PxLocationHit : public PxQueryHit
{
PX_INLINE PxLocationHit() : flags(0), position(PxVec3(0)), normal(PxVec3(0)), distance(PX_MAX_REAL) {}
/**
\note For raycast hits: true for shapes overlapping with raycast origin.
\note For sweep hits: true for shapes overlapping at zero sweep distance.
@see PxRaycastHit PxSweepHit
*/
PX_INLINE bool hadInitialOverlap() const { return (distance <= 0.0f); }
// the following fields are set in accordance with the #PxHitFlags
PxHitFlags flags; //!< Hit flags specifying which members contain valid values.
PxVec3 position; //!< World-space hit position (flag: #PxHitFlag::ePOSITION)
//!< Formerly known as .impact, renamed for clarity.
PxVec3 normal; //!< World-space hit normal (flag: #PxHitFlag::eNORMAL)
/**
\brief Distance to hit.
\note If the eMTD flag is used, distance will be a negative value if shapes are overlapping indicating the penetration depth.
\note Otherwise, this value will be >= 0 (flag: #PxHitFlag::eDISTANCE) */
PxF32 distance;
};
/**
\brief Stores results of raycast queries.
::PxHitFlag flags can be passed to raycast function, as an optimization, to cause the SDK to only compute specified members of this
structure.
Some members like barycentric coordinates are currently only computed for triangle meshes and convexes, but next versions
might provide them in other cases. The client code should check #flags to make sure returned values are valid.
@see PxScene.raycast PxBatchQuery.raycast PxVolumeCache.raycast
*/
struct PxRaycastHit : public PxLocationHit
{
PX_INLINE PxRaycastHit() : u(0.0f), v(0.0f) {}
// the following fields are set in accordance with the #PxHitFlags
PxReal u, v; //!< barycentric coordinates of hit point, for triangle mesh and height field (flag: #PxHitFlag::eUV)
#if !defined(PX_X64) && !defined(PX_ARM64)
PxU32 padTo16Bytes[3];
#endif
};
/**
\brief Stores results of overlap queries.
@see PxScene.overlap and PxBatchQuery.overlap PxVolumeCache.overlap
*/
struct PxOverlapHit: public PxQueryHit { PxU32 padTo16Bytes; };
/**
\brief Stores results of sweep queries.
@see PxScene.sweep PxBatchQuery.sweep PxVolumeCache.sweep
*/
struct PxSweepHit : public PxLocationHit
{
PX_INLINE PxSweepHit() {}
PxU32 padTo16Bytes;
};
/**
\brief Describes query behavior after returning a partial query result via a callback.
If callback returns true, traversal will continue and callback can be issued again.
If callback returns false, traversal will stop, callback will not be issued again.
@see PxHitCallback
*/
typedef bool PxAgain;
/**
\brief This callback class facilitates reporting scene query hits (intersections) to the user.
User overrides the virtual processTouches function to receive hits in (possibly multiple) fixed size blocks.
\note PxHitBuffer derives from this class and is used to receive touching hits in a fixed size buffer.
\note Since the compiler doesn't look in template dependent base classes when looking for non-dependent names
\note with some compilers it will be necessary to use "this->hasBlock" notation to access a parent variable
\note in a child callback class.
\note Pre-made typedef shorthands, such as ::PxRaycastCallback can be used for raycast, overlap and sweep queries.
@see PxHitBuffer PxRaycastHit PxSweepHit PxOverlapHit PxRaycastCallback PxOverlapCallback PxSweepCallback
*/
template<typename HitType>
struct PxHitCallback
{
HitType block; //<! Holds the closest blocking hit result for the query. Invalid if hasBlock is false.
bool hasBlock; //<! Set to true if there was a blocking hit during query.
HitType* touches; //<! User specified buffer for touching hits.
/**
\brief Size of the user specified touching hits buffer.
\note If set to 0 all hits will default to PxQueryHitType::eBLOCK, otherwise to PxQueryHitType::eTOUCH
\note Hit type returned from pre-filter overrides this default */
PxU32 maxNbTouches;
/**
\brief Number of touching hits returned by the query. Used with PxHitBuffer.
\note If true (PxAgain) is returned from the callback, nbTouches will be reset to 0. */
PxU32 nbTouches;
/**
\brief Initializes the class with user provided buffer.
\param[in] aTouches Optional buffer for recording PxQueryHitType::eTOUCH type hits.
\param[in] aMaxNbTouches Size of touch buffer.
\note if aTouches is NULL and aMaxNbTouches is 0, only the closest blocking hit will be recorded by the query.
\note If PxQueryFlag::eANY_HIT flag is used as a query parameter, hasBlock will be set to true and blockingHit will be used to receive the result.
\note Both eTOUCH and eBLOCK hits will be registered as hasBlock=true and stored in PxHitCallback.block when eANY_HIT flag is used.
@see PxHitCallback.hasBlock PxHitCallback.block */
PxHitCallback(HitType* aTouches, PxU32 aMaxNbTouches)
: hasBlock(false), touches(aTouches), maxNbTouches(aMaxNbTouches), nbTouches(0)
{}
/**
\brief virtual callback function used to communicate query results to the user.
This callback will always be invoked with aTouches as a buffer if aTouches was specified as non-NULL.
All reported touch hits are guaranteed to be closer than the closest blocking hit.
\param[in] buffer Callback will report touch hits to the user in this buffer. This pointer will be the same as aTouches parameter.
\param[in] nbHits Number of touch hits reported in buffer. This number will not exceed aMaxNbTouches constructor parameter.
\note There is a significant performance penalty in case multiple touch callbacks are issued (up to 2x)
\note to avoid the penalty use a bigger buffer so that all touching hits can be reported in a single buffer.
\note If true (again) is returned from the callback, nbTouches will be reset to 0,
\note If false is returned, nbTouched will remain unchanged.
\note By the time processTouches is first called, the globally closest blocking hit is already determined,
\note values of hasBlock and block are final and all touch hits are guaranteed to be closer than the blocking hit.
\note touches and maxNbTouches can be modified inside of processTouches callback.
\return true to continue receiving callbacks in case there are more hits or false to stop.
@see PxAgain PxRaycastHit PxSweepHit PxOverlapHit */
virtual PxAgain processTouches(const HitType* buffer, PxU32 nbHits) = 0;
virtual void finalizeQuery() {} //<! Query finalization callback, called after the last processTouches callback.
virtual ~PxHitCallback() {}
/** \brief Returns true if any blocking or touching hits were encountered during a query. */
PX_FORCE_INLINE bool hasAnyHits() { return (hasBlock || (nbTouches > 0)); }
};
/**
\brief Returns scene query hits (intersections) to the user in a preallocated buffer.
Will clip touch hits to maximum buffer capacity. When clipped, an arbitrary subset of touching hits will be discarded.
Overflow does not trigger warnings or errors. block and hasBlock will be valid in finalizeQuery callback and after query completion.
Touching hits are guaranteed to have closer or same distance ( <= condition) as the globally nearest blocking hit at the time any processTouches()
callback is issued.
\note Pre-made typedef shorthands, such as ::PxRaycastBuffer can be used for raycast, overlap and sweep queries.
@see PxHitCallback
@see PxRaycastBuffer PxOverlapBuffer PxSweepBuffer PxRaycastBufferN PxOverlapBufferN PxSweepBufferN
*/
template<typename HitType>
struct PxHitBuffer : public PxHitCallback<HitType>
{
/**
\brief Initializes the buffer with user memory.
The buffer is initialized with 0 touch hits by default => query will only report a single closest blocking hit.
Use PxQueryFlag::eANY_HIT to tell the query to abort and return any first hit encoutered as blocking.
\param[in] aTouches Optional buffer for recording PxQueryHitType::eTOUCH type hits.
\param[in] aMaxNbTouches Size of touch buffer.
@see PxHitCallback */
PxHitBuffer(HitType* aTouches = NULL, PxU32 aMaxNbTouches = 0) : PxHitCallback<HitType>(aTouches, aMaxNbTouches) {}
/** \brief Computes the number of any hits in this result, blocking or touching. */
PX_INLINE PxU32 getNbAnyHits() const { return getNbTouches() + PxU32(this->hasBlock); }
/** \brief Convenience iterator used to access any hits in this result, blocking or touching. */
PX_INLINE const HitType& getAnyHit(const PxU32 index) const { PX_ASSERT(index < getNbTouches() + PxU32(this->hasBlock));
return index < getNbTouches() ? getTouches()[index] : this->block; }
PX_INLINE PxU32 getNbTouches() const { return this->nbTouches; }
PX_INLINE const HitType* getTouches() const { return this->touches; }
PX_INLINE const HitType& getTouch(const PxU32 index) const { PX_ASSERT(index < getNbTouches()); return getTouches()[index]; }
PX_INLINE PxU32 getMaxNbTouches() const { return this->maxNbTouches; }
virtual ~PxHitBuffer() {}
protected:
// stops after the first callback
virtual PxAgain processTouches(const HitType* buffer, PxU32 nbHits) { PX_UNUSED(buffer); PX_UNUSED(nbHits); return false; }
};
/** \brief Raycast query callback. */
typedef PxHitCallback<PxRaycastHit> PxRaycastCallback;
/** \brief Overlap query callback. */
typedef PxHitCallback<PxOverlapHit> PxOverlapCallback;
/** \brief Sweep query callback. */
typedef PxHitCallback<PxSweepHit> PxSweepCallback;
/** \brief Raycast query buffer. */
typedef PxHitBuffer<PxRaycastHit> PxRaycastBuffer;
/** \brief Overlap query buffer. */
typedef PxHitBuffer<PxOverlapHit> PxOverlapBuffer;
/** \brief Sweep query buffer. */
typedef PxHitBuffer<PxSweepHit> PxSweepBuffer;
/** \brief Returns touching raycast hits to the user in a fixed size array embedded in the buffer class. **/
template <int N>
struct PxRaycastBufferN : PxHitBuffer<PxRaycastHit>
{
PxRaycastHit hits[N];
PxRaycastBufferN() : PxHitBuffer<PxRaycastHit>(hits, N) {}
};
/** \brief Returns touching overlap hits to the user in a fixed size array embedded in the buffer class. **/
template <int N>
struct PxOverlapBufferN : PxHitBuffer<PxOverlapHit>
{
PxOverlapHit hits[N];
PxOverlapBufferN() : PxHitBuffer<PxOverlapHit>(hits, N) {}
};
/** \brief Returns touching sweep hits to the user in a fixed size array embedded in the buffer class. **/
template <int N>
struct PxSweepBufferN : PxHitBuffer<PxSweepHit>
{
PxSweepHit hits[N];
PxSweepBufferN() : PxHitBuffer<PxSweepHit>(hits, N) {}
};
#ifndef PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| [
"unrealbot@users.noreply.github.com"
] | unrealbot@users.noreply.github.com |
4e71e77596d3329e2592052b42712c56c9e13ea5 | 983515294c903355d6574e9c73db6a84d9bd65c8 | /test/modules/sequencizer/sequence-controller-idle-suite.cpp | 5c364bff0466c0ee72e909caeb5f33eaeb4b1d79 | [
"MIT"
] | permissive | dhemery/DHE-Modules | 80c10f54219633d356ed922aa014bf94e3dcbd00 | 1d1c286fc69babdb36dfe5fa4fe2856b0f707854 | refs/heads/main | 2022-12-23T20:46:49.810184 | 2022-02-05T20:50:38 | 2022-02-05T20:50:38 | 117,472,503 | 36 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 8,590 | cpp | #include "components/latch.h"
#include "fixtures/sequence-controller-fixture.h"
#include <functional>
namespace test {
namespace sequencizer {
using dhe::unit::Suite;
using dhe::unit::Tester;
using TestFunc = std::function<void(Tester &)>;
static inline void when_idle(Signals &signals, StepSelector & /*step_selector*/,
StepController & /*step_controller*/,
SequenceController &sequence_controller) {
signals.running_ = false;
signals.reset_ = false;
sequence_controller.execute(0.F);
}
class SequenceControllerIdleSuite : Suite {
public:
SequenceControllerIdleSuite()
: Suite{"dhe::sequencizer::SequenceController: idle"} {}
void run(Tester &t) override {
t.run("with run high: with reset low: does nothing",
test(when_idle, [](Tester &t, Signals &signals,
StepSelector &step_selector,
StepController &step_controller,
SequenceController &sequence_controller) {
signals.running_ = true;
signals.reset_ = false;
auto constexpr original_output = -99342.2F;
signals.output_ = original_output;
sequence_controller.execute(0.1F);
if (step_selector.called_) {
t.error("step selector was called");
}
if (step_controller.called_) {
t.error("step controller was called");
}
if (signals.output_ != original_output) {
t.errorf("signals output was changed (to {})", signals.output_);
}
}));
t.run("with run high: with gate low: does nothing",
test(when_idle, [](Tester &t, Signals &signals,
StepSelector &step_selector,
StepController &step_controller,
SequenceController &sequence_controller) {
signals.running_ = true;
signals.gate_ = false;
auto constexpr original_output = -992.223F;
signals.output_ = original_output;
sequence_controller.execute(0.1F);
if (step_selector.called_) {
t.error("step selector was called");
}
if (step_controller.called_) {
t.error("step controller was called");
}
if (signals.output_ != original_output) {
t.errorf("signals output was changed (to {})", signals.output_);
}
}));
t.run("with run high: "
"if gate rises: executes first step with gate edge cleared",
test(when_idle,
[](Tester &t, Signals &signals, StepSelector &step_selector,
StepController &step_controller,
SequenceController &sequence_controller) {
signals.running_ = true;
signals.gate_ = true;
auto constexpr first_enabled_step = 3;
step_selector.first_ = first_enabled_step;
step_controller.status_ = StepStatus::Generating;
auto constexpr sample_time = 0.39947F;
sequence_controller.execute(sample_time);
if (step_controller.entered_step_ != first_enabled_step) {
t.errorf("Entered step {}, want step {}",
step_controller.entered_step_, first_enabled_step);
}
if (step_controller.executed_latch_ != dhe::latch::high) {
t.errorf("Executed latch was {}, want {}",
step_controller.executed_latch_, dhe::latch::high);
}
if (step_controller.executed_sample_time_ != sample_time) {
t.errorf("Executed sample time was {}, want {}",
step_controller.executed_sample_time_, sample_time);
}
}));
t.run("with run high: "
"if gate rises: does nothing if no first step",
test(when_idle, [](Tester &t, Signals &signals,
StepSelector &step_selector,
StepController &step_controller,
SequenceController &sequence_controller) {
signals.running_ = true;
signals.gate_ = true;
step_selector.first_ = -1;
auto constexpr original_output = -2340.223F;
signals.output_ = original_output;
sequence_controller.execute(0.F);
if (step_controller.called_) {
t.error("step controller was called");
}
if (signals.output_ != original_output) {
t.errorf("signals output was changed (to {})", signals.output_);
}
}));
t.run("with run low: with reset low: does nothing",
test(when_idle, [](Tester &t, Signals &signals,
StepSelector &step_selector,
StepController &step_controller,
SequenceController &sequence_controller) {
signals.running_ = false;
signals.reset_ = false;
auto constexpr original_output = 349.319F;
signals.output_ = original_output;
sequence_controller.execute(0.1F);
if (step_selector.called_) {
t.error("step selector was called");
}
if (step_controller.called_) {
t.error("step controller was called");
}
if (signals.output_ != original_output) {
t.errorf("signals output was changed (to {})", signals.output_);
}
}));
t.run("with run low: "
"if reset rises: "
"does nothing",
test(when_idle, [](Tester &t, Signals &signals,
StepSelector &step_selector,
StepController &step_controller,
SequenceController &sequence_controller) {
signals.running_ = false;
signals.reset_ = true;
auto constexpr original_output = 349.319F;
signals.output_ = original_output;
sequence_controller.execute(0.1F);
if (step_selector.called_) {
t.error("step selector was called");
}
if (step_controller.called_) {
t.error("step controller was called");
}
if (signals.output_ != original_output) {
t.errorf("signals output was changed (to {})", signals.output_);
}
}));
t.run("with run low: with gate low: does nothing",
test(when_idle, [](Tester &t, Signals &signals,
StepSelector &step_selector,
StepController &step_controller,
SequenceController &sequence_controller) {
signals.running_ = false;
signals.gate_ = false;
auto constexpr original_output = 349.319F;
signals.output_ = original_output;
sequence_controller.execute(0.1F);
if (step_selector.called_) {
t.error("step selector was called");
}
if (step_controller.called_) {
t.error("step controller was called");
}
if (signals.output_ != original_output) {
t.errorf("signals output was changed (to {})", signals.output_);
}
}));
t.run("with run low: if gate rises: does nothing",
test(when_idle, [](Tester &t, Signals &signals,
StepSelector &step_selector,
StepController &step_controller,
SequenceController &sequence_controller) {
signals.gate_ = true;
auto constexpr original_output = 349.319F;
signals.output_ = original_output;
sequence_controller.execute(0.1F);
if (step_selector.called_) {
t.error("step selector was called");
}
if (step_controller.called_) {
t.error("step controller was called");
}
if (signals.output_ != original_output) {
t.errorf("signals output was changed (to {})", signals.output_);
}
}));
}
};
static auto _ = SequenceControllerIdleSuite{};
} // namespace sequencizer
} // namespace test
| [
"dale@dhemery.com"
] | dale@dhemery.com |
013e48952bf2b2fb19473eb8cec8cc84c5502e48 | bf9318969029963bc8f790798aa62769334a3026 | /16- Majority Element II/sol1.cpp | 33b721619432d8c1b792d072cba5ced7f5693301 | [] | no_license | wandering-sage/dsa-practice | b7e16daf51f9c5cffb846a75cc50fa10ea54ee92 | c63d832731f254c47a905f243d266f703bfefa79 | refs/heads/main | 2023-07-16T04:07:04.170288 | 2021-08-25T05:38:22 | 2021-08-25T05:38:22 | 379,991,570 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 811 | cpp | #include <bits/stdc++.h>
using namespace std;
// Using Moore Voting Algorithm
// time-->O(N) space-->O(1)
vector<int> majorityElement(vector<int> &nums)
{
int me1 = -1, me2 = -2;
int c1 = 0, c2 = 0;
vector<int> ret;
int i = 0;
for (int i = 0; i < nums.size(); i++)
{
if (nums[i] == me1)
c1++;
else if (nums[i] == me2)
c2++;
else if (c1 == 0)
{
me1 = nums[i];
c1++;
}
else if (c2 == 0)
{
me2 = nums[i];
c2++;
}
else
{
c1--;
c2--;
}
}
c1 = 0;
c2 = 0;
for (int i = 0; i < nums.size(); i++)
{
if (nums[i] == me1)
c1++;
if (nums[i] == me2)
c2++;
}
if (c1 > nums.size() / 3)
ret.push_back(me1);
if (c2 > nums.size() / 3)
ret.push_back(me2);
return ret;
}
| [
"shivam4503@gmail.com"
] | shivam4503@gmail.com |
bad3392ec9536a873d23fb973e1f553ca41c6a4e | 8e854323d86b97057ee199e545f508d933d3a5be | /src/privatesend-client.h | adc49bc0ab1737349aae9d95b72cf510718cc85a | [
"MIT"
] | permissive | julivn/.github | 362789f251e73846441028cf4de5a8279fc40f0e | 6d544f99d9ba53d386863cb58e749af163c30294 | refs/heads/master | 2020-04-14T13:18:14.444317 | 2019-01-02T16:31:03 | 2019-01-02T16:31:03 | 163,864,804 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,991 | h | // Copyright (c) 2014-2017 The Dash Core developers
// Copyright (c) 2018 The Bitmonix Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef PRIVATESENDCLIENT_H
#define PRIVATESENDCLIENT_H
#include "masternode.h"
#include "privatesend.h"
#include "wallet/wallet.h"
#include "privatesend-util.h"
class CPrivateSendClient;
class CConnman;
static const int DENOMS_COUNT_MAX = 100;
static const int MIN_PRIVATESEND_ROUNDS = 2;
static const int MIN_PRIVATESEND_AMOUNT = 2;
static const int MIN_PRIVATESEND_LIQUIDITY = 0;
static const int MAX_PRIVATESEND_ROUNDS = 16;
static const int MAX_PRIVATESEND_AMOUNT = MAX_MONEY / COIN;
static const int MAX_PRIVATESEND_LIQUIDITY = 100;
static const int DEFAULT_PRIVATESEND_ROUNDS = 2;
static const int DEFAULT_PRIVATESEND_AMOUNT = 1000;
static const int DEFAULT_PRIVATESEND_LIQUIDITY = 0;
static const bool DEFAULT_PRIVATESEND_MULTISESSION = false;
// Warn user if mixing in gui or try to create backup if mixing in daemon mode
// when we have only this many keys left
static const int PRIVATESEND_KEYS_THRESHOLD_WARNING = 100;
// Stop mixing completely, it's too dangerous to continue when we have only this many keys left
static const int PRIVATESEND_KEYS_THRESHOLD_STOP = 50;
// The main object for accessing mixing
extern CPrivateSendClient privateSendClient;
class CPendingDsaRequest
{
private:
static const int TIMEOUT = 15;
CService addr;
CDarksendAccept dsa;
int64_t nTimeCreated;
public:
CPendingDsaRequest():
addr(CService()),
dsa(CDarksendAccept()),
nTimeCreated(0)
{};
CPendingDsaRequest(const CService& addr_, const CDarksendAccept& dsa_):
addr(addr_),
dsa(dsa_)
{ nTimeCreated = GetTime(); }
CService GetAddr() { return addr; }
CDarksendAccept GetDSA() { return dsa; }
bool IsExpired() { return GetTime() - nTimeCreated > TIMEOUT; }
friend bool operator==(const CPendingDsaRequest& a, const CPendingDsaRequest& b)
{
return a.addr == b.addr && a.dsa == b.dsa;
}
friend bool operator!=(const CPendingDsaRequest& a, const CPendingDsaRequest& b)
{
return !(a == b);
}
explicit operator bool() const
{
return *this != CPendingDsaRequest();
}
};
/** Used to keep track of current status of mixing pool
*/
class CPrivateSendClient : public CPrivateSendBase
{
private:
// Keep track of the used Masternodes
std::vector<COutPoint> vecMasternodesUsed;
std::vector<CAmount> vecDenominationsSkipped;
std::vector<COutPoint> vecOutPointLocked;
int nCachedLastSuccessBlock;
int nMinBlocksToWait; // how many blocks to wait after one successful mixing tx in non-multisession mode
// Keep track of current block height
int nCachedBlockHeight;
int nEntriesCount;
bool fLastEntryAccepted;
std::string strLastMessage;
std::string strAutoDenomResult;
masternode_info_t infoMixingMasternode;
CMutableTransaction txMyCollateral; // client side collateral
CPendingDsaRequest pendingDsaRequest;
CKeyHolderStorage keyHolderStorage; // storage for keys used in PrepareDenominate
/// Check for process
void CheckPool();
void CompletedTransaction(PoolMessage nMessageID);
bool IsDenomSkipped(CAmount nDenomValue);
bool WaitForAnotherBlock();
// Make sure we have enough keys since last backup
bool CheckAutomaticBackup();
bool JoinExistingQueue(CAmount nBalanceNeedsAnonymized, CConnman& connman);
bool StartNewQueue(CAmount nValueMin, CAmount nBalanceNeedsAnonymized, CConnman& connman);
/// Create denominations
bool CreateDenominated(CConnman& connman);
bool CreateDenominated(const CompactTallyItem& tallyItem, bool fCreateMixingCollaterals, CConnman& connman);
/// Split up large inputs or make fee sized inputs
bool MakeCollateralAmounts(CConnman& connman);
bool MakeCollateralAmounts(const CompactTallyItem& tallyItem, bool fTryDenominated, CConnman& connman);
/// As a client, submit part of a future mixing transaction to a Masternode to start the process
bool SubmitDenominate(CConnman& connman);
/// step 1: prepare denominated inputs and outputs
bool PrepareDenominate(int nMinRounds, int nMaxRounds, std::string& strErrorRet, std::vector<CTxDSIn>& vecTxDSInRet, std::vector<CTxOut>& vecTxOutRet);
/// step 2: send denominated inputs and outputs prepared in step 1
bool SendDenominate(const std::vector<CTxDSIn>& vecTxDSIn, const std::vector<CTxOut>& vecTxOut, CConnman& connman);
/// Get Masternode updates about the progress of mixing
bool CheckPoolStateUpdate(PoolState nStateNew, int nEntriesCountNew, PoolStatusUpdate nStatusUpdate, PoolMessage nMessageID, int nSessionIDNew=0);
// Set the 'state' value, with some logging and capturing when the state changed
void SetState(PoolState nStateNew);
/// As a client, check and sign the final transaction
bool SignFinalTransaction(const CTransaction& finalTransactionNew, CNode* pnode, CConnman& connman);
void RelayIn(const CDarkSendEntry& entry, CConnman& connman);
void SetNull();
public:
int nPrivateSendRounds;
int nPrivateSendAmount;
int nLiquidityProvider;
bool fEnablePrivateSend;
bool fPrivateSendMultiSession;
int nCachedNumBlocks; //used for the overview screen
bool fCreateAutoBackups; //builtin support for automatic backups
CPrivateSendClient() :
nCachedLastSuccessBlock(0),
nMinBlocksToWait(1),
txMyCollateral(CMutableTransaction()),
nPrivateSendRounds(DEFAULT_PRIVATESEND_ROUNDS),
nPrivateSendAmount(DEFAULT_PRIVATESEND_AMOUNT),
nLiquidityProvider(DEFAULT_PRIVATESEND_LIQUIDITY),
fEnablePrivateSend(false),
fPrivateSendMultiSession(DEFAULT_PRIVATESEND_MULTISESSION),
nCachedNumBlocks(std::numeric_limits<int>::max()),
fCreateAutoBackups(true) { SetNull(); }
void ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStream& vRecv, CConnman& connman);
void ClearSkippedDenominations() { vecDenominationsSkipped.clear(); }
void SetMinBlocksToWait(int nMinBlocksToWaitIn) { nMinBlocksToWait = nMinBlocksToWaitIn; }
void ResetPool();
void UnlockCoins();
std::string GetStatus();
bool GetMixingMasternodeInfo(masternode_info_t& mnInfoRet);
bool IsMixingMasternode(const CNode* pnode);
/// Passively run mixing in the background according to the configuration in settings
bool DoAutomaticDenominating(CConnman& connman, bool fDryRun=false);
void ProcessPendingDsaRequest(CConnman& connman);
void CheckTimeout();
void UpdatedBlockTip(const CBlockIndex *pindex);
};
void ThreadCheckPrivateSendClient(CConnman& connman);
#endif
| [
"46324696+julivn@users.noreply.github.com"
] | 46324696+julivn@users.noreply.github.com |
1d966df9d536890fb52dac2ca613e317888d1d05 | c717b260750d9c733b40e668d2841dee92167699 | /software/libs/mctl/ft_sensor_cal.hpp | 2aad94ea629536606217071b13fc275da9c3e267 | [
"Apache-2.0"
] | permissive | hanhanhan-kim/noah_motion_system | b68e3fc6db1a0faea272ead7a22a043dfb80a6c8 | 5bea2750eac638b9f90720b10b5e2516f108c65b | refs/heads/master | 2022-11-06T08:20:49.977792 | 2017-10-06T00:12:05 | 2017-10-06T00:12:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,293 | hpp | #ifndef FT_SENSOR_CAL_HPP
#define FT_SENSOR_CAL_HPP
#include "rtn_status.hpp"
#include "ft_tool_transform.hpp"
#include <memory>
#include <vector>
#include <iostream>
#include <armadillo>
namespace atidaq
{
extern "C"
{
struct Calibration;
}
}
namespace mctl
{
class FT_SensorCal
{
public:
static const std::string DefaultForceUnits;
static const std::string DefaultTorqueUnits;
static const FT_ToolTransform DefaultToolTransform;
static const int FT_VectorSize;
static const int AinVectorSize;
static const int DisplayFloatPrecision;
static const int DisplayMatrixColumnWidth;
FT_SensorCal();
RtnStatus load(std::string filename);
RtnStatus set_force_units(std::string units);
RtnStatus set_torque_units(std::string units);
RtnStatus set_tool_transform(FT_ToolTransform trans);
RtnStatus set_temperature_comp(bool value);
RtnStatus set_bias(std::vector<double> bias_vec);
RtnStatus set_bias(arma::Row<double> bias_vec);
RtnStatus set_bias(double fx, double fy, double fz, double tx, double ty, double tz);
RtnStatus get_units(std::vector<std::string> &units_vec);
RtnStatus get_force_units(std::string &units);
RtnStatus get_torque_units(std::string &units);
RtnStatus get_tool_transform(FT_ToolTransform &tran);
RtnStatus get_filename(std::string &filename);
RtnStatus get_info_string(std::string &info);
RtnStatus has_temperature_comp(bool &value);
void print_info_string();
RtnStatus convert(std::vector<double> ain_vec, std::vector<double> &ft_vec);
RtnStatus convert(arma::Row<double> ain_vec, arma::Row<double> &ft_vec);
RtnStatus convert(arma::Mat<double> ain_mat, arma::Mat<double> &ft_mat);
bool is_initialized();
bool is_initialized(RtnStatus &rtn_status);
protected:
std::string filename_ = std::string("");
std::shared_ptr<atidaq::Calibration> cal_ = nullptr;
RtnStatus check_atidaq_rtn(short rtn_code);
};
}
#endif
| [
"will@iorodeo.com"
] | will@iorodeo.com |
b9c87feb0de7dbe5a32a2e087c775691a79f4df8 | 07afe5a4ea3946a8891348783530dc7a33a9fcbd | /Source/v3ctor.cpp | 4db1ddc834bd355ab2ef0ad0343777e885da496f | [] | no_license | dvulakh/GalaxyMap | b1a9beb89f8f08a6e7bba6397263ae298fe0055a | 0cbfcce8bee886c73fc98797447069f112485020 | refs/heads/master | 2020-08-21T09:05:55.574090 | 2019-10-19T23:40:47 | 2019-10-19T23:40:47 | 216,127,176 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,149 | cpp |
#include "v3ctor.h"
#include <string>
#include <cmath>
#define PI 3.141592635897931
// Constructors
/// Given components
v3ctor::v3ctor(double x, double y, double z)
{
this->x = x;
this->y = y;
this->z = z;
}
/// Default
v3ctor::v3ctor() {
this->x = 0;
this->y = 0;
this->z = 0;
}
// Overloaded operators
/// Vector increment
v3ctor v3ctor::operator+=(const v3ctor& v)
{
v3ctor s = v3ctor(*this);
this->x += v.x;
this->y += v.y;
this->z += v.z;
return s;
}
/// Vector decrement
v3ctor v3ctor::operator-=(const v3ctor& v)
{
v3ctor s = v3ctor(*this);
this->x -= v.x;
this->y -= v.y;
this->z -= v.z;
return s;
}
/// Vector add
v3ctor v3ctor::operator+(const v3ctor& v) const
{
v3ctor s = v3ctor();
s.x = this->x + v.x;
s.y = this->y + v.y;
s.z = this->z + v.z;
return s;
}
/// Vector subtract
v3ctor v3ctor::operator-(const v3ctor& v) const
{
v3ctor s = v3ctor();
s.x = this->x - v.x;
s.y = this->y - v.y;
s.z = this->z - v.z;
return s;
}
/// Scalar multiply
v3ctor v3ctor::operator*(double d) const
{
v3ctor s = v3ctor();
s.x = this->x * d;
s.y = this->y * d;
s.z = this->z * d;
return s;
}
/// Scalar divide
v3ctor v3ctor::operator/(double d) const
{
v3ctor s = v3ctor();
s.x = this->x / d;
s.y = this->y / d;
s.z = this->z / d;
return s;
}
/// Scalar multiply and assign
v3ctor v3ctor::operator*=(double d)
{
v3ctor s = v3ctor(*this);
this->x *= d;
this->y *= d;
this->z *= d;
return s;
}
/// Scalar divide and assign
v3ctor v3ctor::operator/=(double d)
{
v3ctor s = v3ctor(*this);
this->x /= d;
this->y /= d;
this->z /= d;
return s;
}
// Basic math
/// Magnitude of vector
double abs(const v3ctor& v) { return sqrt(dot(v, v)); }
/// Dot product
double dot(const v3ctor& v, const v3ctor& w) { return v.x * w.x + v.y * w.y + v.z * w.z; }
/// Cross product
v3ctor cross(const v3ctor& v, const v3ctor& w) {
return v3ctor(
v.y * w.z - v.z * w.y,
v.z * w.x - v.x * w.z,
v.x * w.y - v.y * w.x
);
}
/// Angle between two vectors
double angle(const v3ctor& v, const v3ctor& w) {
double c = dot(v, w) / abs(v) / abs(w);
return c >= -1 ? c <= 1 ? acos(c) : acos(1) : acos(-1);
}
/// Projection of v onto w
v3ctor project(const v3ctor& v, const v3ctor& w) { return w * (dot(v, w) / dot(w, w)); }
/// Unit vector in direction of v
v3ctor unit(const v3ctor& v) { return v / abs(v); }
/// Rotate vector v about u by r radians
v3ctor rot(const v3ctor& v, v3ctor u, double r)
{
u = unit(u);
double c = cos(r);
double s = sin(r);
return v3ctor(
v.x * (c + u.x * u.x * (1 - c)) + v.y * (u.x * u.y * (1 - c) - u.z * s) + v.z * (u.x * u.z * (1 - c) + u.y * s),
v.x * (u.y * u.x * (1 - c) + u.z * s) + v.y * (c + u.y * u.y * (1 - c)) + v.z * (u.y * u.z * (1 - c) - u.x * s),
v.x * (u.z * u.x * (1 - c) - u.y * s) + v.y * (u.z * u.y * (1 - c) + u.x * s) + v.z * (c + u.z * u.z * (1 - c))
);
}
// To string
string to_string(const v3ctor& v)
{
string s = "<";
s += to_string(v.x) + ", ";
s += to_string(v.y) + ", ";
s += to_string(v.z);
return s + ">";
} | [
"noreply@github.com"
] | dvulakh.noreply@github.com |
ee1fd5a7032a390d5aab81dc81182035df8ccf50 | 923d0c8d9e4578c9a77e6f5fab207ba706ad61c4 | /simplect_cpp/width-height_image.cpp | 6c7e7c955c0520e5a8497863eaa2ee72f0b2da60 | [] | no_license | yuni-net/simplect | d19a73c39af660bf69fc25dd655efe8067f632bf | 9bdb75eb08652ad37a43555827228d4b5eb72ba3 | refs/heads/master | 2021-01-21T10:09:19.623786 | 2015-06-28T08:45:10 | 2015-06-28T08:45:10 | 38,192,343 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 391 | cpp | #include "includes.h"
#include "image.h"
float sim::image::width() const
{
return base_width()*magni();
}
float sim::image::height() const
{
return base_height()*magni();
}
uint sim::image::base_width() const
{
if (pImageData == NULL) return 0;
return pImageData->width();
}
uint sim::image::base_height() const
{
if (pImageData == NULL) return 0;
return pImageData->height();
}
| [
"yuni.net.liberty@gmail.com"
] | yuni.net.liberty@gmail.com |
9c6897ad10c77e78913865041aeee2163b784c79 | 28a961d8524aa1fe84cfdd2b6e124f39eb1b5237 | /net/Server.h | 94e9064756774cab14e2f46269b76916da660f3b | [] | no_license | yanpd1228/Yedis | 0765607ef26cb03d416ab76262109d2f6ab2a658 | d137a68636637599ebe78e35a403fc145a22450c | refs/heads/master | 2023-05-12T20:39:01.805463 | 2021-05-30T05:01:30 | 2021-05-30T05:01:30 | 363,556,674 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,910 | h | #ifndef _YPD_SERVER_H_
#define _YPD_SERVER_H_
#include <functional>
#include "SocketAddr.h"
#include "TcpConnection.h"
#include <atomic>
#include <memory>
#include <map>
class AcceptNew;
class EventLoop;
class EventLoopThreadPool;
class Server
{
public:
enum Option
{
kNoReusePort,
kReusePort,
};
Server(EventLoop* loop,
const SocketAddr& listenAddr,
const std::string& nameArg,
Option option = kReusePort);
~Server();
public:
void setConnectionCallback(const ConnectionCallback& cb){m_NewConnectionCallback = cb; }
const std::string& hostport() const { return m_strHostPort; }
const std::string& name() const { return m_strName; }
EventLoop* getLoop() const { return m_ptrLoop; }
typedef std::map<std::string, TcpConnectionPtr> ConnectionMap;
void start(int nWorkThreadCount);
void newConnection(int nSockfd, SocketAddr& peerAdder);
void removeConnection(const TcpConnectionPtr& conn);
void removeConnectionInLoop(const TcpConnectionPtr& conn);
private:
EventLoop* m_ptrLoop; // the acceptor loop
std::string m_strHostPort;
std::string m_strName;
std::unique_ptr<AcceptNew> m_ptrAccepNewConn;
std::unique_ptr<EventLoopThreadPool> m_ptrEventLoopThreadPool;
ConnectionCallback m_NewConnectionCallback;
MessageCallback m_MessageCallback;
WriteCompleteCallback m_WriteCompleteCallback;
ThreadInitCallback m_ThreadInitCallback;
std::atomic<int> m_nStarted;
int m_nNextConnId;
ConnectionMap m_mapConnections;
};
#endif //!_YPD_SERVER_H_
| [
"1654309840@qq.com"
] | 1654309840@qq.com |
f7e3598ca2384268d722850c20e9a5a91ca71484 | 8c6e11ae739ba9da168c991a166855d3b84206ca | /arduino_rfid/arduino_rfid.ino | 075f578ed3b3d812ee18a4e6d4353fd89c8c5579 | [
"BSD-2-Clause"
] | permissive | mrozo/RFIDScreenLock | 8c8d633564b6b30c8b210ab8f7e3a916f7ed6448 | 15bb335df594cea70094a97556c1149b4b3f1cf7 | refs/heads/master | 2021-04-26T04:54:03.361584 | 2017-10-22T21:25:29 | 2017-10-22T21:25:29 | 107,031,216 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,022 | ino | /*
* Initial Author: ryand1011 (https://github.com/ryand1011)
*
* Reads data written by a program such as "rfid_write_personal_data.ino"
*
* See: https://github.com/miguelbalboa/rfid/tree/master/examples/rfid_write_personal_data
*
* Uses MIFARE RFID card using RFID-RC522 reader
* Uses MFRC522 - Library
* -----------------------------------------------------------------------------------------
* MFRC522 Arduino Arduino Arduino Arduino Arduino
* Reader/PCD Uno/101 Mega Nano v3 Leonardo/Micro Pro Micro
* Signal Pin Pin Pin Pin Pin Pin
* -----------------------------------------------------------------------------------------
* RST/Reset RST 9 5 D9 RESET/ICSP-5 RST
* SPI SS SDA(SS) 10 53 D10 10 10
* SPI MOSI MOSI 11 / ICSP-4 51 D11 ICSP-4 16
* SPI MISO MISO 12 / ICSP-1 50 D12 ICSP-1 14
* SPI SCK SCK 13 / ICSP-3 52 D13 ICSP-3 15
*/
#include <SPI.h>
#include <MFRC522.h>
#define RST_PIN 9 // Configurable, see typical pin layout above
#define SS_PIN 10 // Configurable, see typical pin layout above
MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance
//*****************************************************************************************//
void setup() {
Serial.begin(9600); // Initialize serial communications with the PC
SPI.begin(); // Init SPI bus
mfrc522.PCD_Init(); // Init MFRC522 card
}
void PrintHex(uint8_t *data, uint8_t length) // prints 8-bit data in hex with leading zeroes
{
char tmp[16];
for (int i=0; i<length; i++) {
sprintf(tmp, "0x%.2X",data[i]);
Serial.print(tmp); Serial.print(" ");
}
}
uint8_t buf[10]= {};
MFRC522::Uid id;
MFRC522::Uid id2;
bool is_card_present = false;
//*****************************************************************************************//
void cpid(MFRC522::Uid *id){
memset(id, 0, sizeof(MFRC522::Uid));
memcpy(id->uidByte, mfrc522.uid.uidByte, mfrc522.uid.size);
id->size = mfrc522.uid.size;
id->sak = mfrc522.uid.sak;
}
bool cmpid(MFRC522::Uid *id1, MFRC522::Uid *id2){
return memcmp(id1, id2, sizeof(MFRC522::Uid));
}
void deregister_card(){
is_card_present = false;
memset(&id,0, sizeof(id));
}
uint8_t control = 0x00;
void loop() {
MFRC522::MIFARE_Key key;
for (byte i = 0; i < 6; i++) key.keyByte[i] = 0xFF;
MFRC522::StatusCode status;
//-------------------------------------------
// Look for new cards
if ( !mfrc522.PICC_IsNewCardPresent()) {
return;
}
if ( !mfrc522.PICC_ReadCardSerial()) {
return;
}
//PrintHex(id.uidByte, id.size);
//Serial.println("hello");
bool result = true;
uint8_t buf_len=4;
cpid(&id);
Serial.print("NewCard ");
qPrintHex(id.uidByte, id.size);
Serial.println("");
while(true){
control=0;
for(int i=0; i<3; i++){
if(!mfrc522.PICC_IsNewCardPresent()){
if(mfrc522.PICC_ReadCardSerial()){
//Serial.print('a');
control |= 0x16;
}
if(mfrc522.PICC_ReadCardSerial()){
//Serial.print('b');
control |= 0x16;
}
//Serial.print('c');
control += 0x1;
}
//Serial.print('d');
control += 0x4;
}
//Serial.println(control);
if(control == 13 || control == 14){
//card is still there
} else {
break;
}
}
Serial.println("CardRemoved");
delay(500); //change value if you want to read cards faster
mfrc522.PICC_HaltA();
mfrc522.PCD_StopCrypto1();
}
//*****************************************************************************************//a
| [
"private@mrozo.pl"
] | private@mrozo.pl |
e85b42250df1e8b140ef72ed94e8c252c9cca7dc | ed4a91fd9b4fefca40cc5118b485c0ec7d4ba40c | /louluosrc/template_tcp/src/main/main.cpp | 5899d2047fb7fefadf9a5c96726d9d393835a488 | [] | no_license | hkduke/my_src | 165035db12481d36bedb48cf2c1c1759ce2af42f | 2282fff562fd14c972e7ce66a615a7125cb4a877 | refs/heads/master | 2020-06-13T08:14:34.674528 | 2017-04-09T12:47:57 | 2017-04-09T12:48:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,575 | cpp |
//#include "module_test.h"
#include "SDConfigurationSingleton.h"
#include <log4cplus/configurator.h>
using namespace log4cplus;
#include "common/SDLogger.h"
#include "dispatcher.h"
//#include "service_stat.h"
//#include "http_server.h"
#include <sys/types.h>
#include <sys/wait.h>
//#include "log_codec_wrapper.h"
#include "http_server.h"
#include "mycommon.h"
void init_config(void)
{
std::string config_file;
config_file ="../conf/notify_adapter.conf";
SDConfiguration* config = new SDConfiguration(config_file.c_str());
if (!config->load())
{
//LOG4CPLUS_ERROR(logger, "read config_file \"" << m_conf_file << "\" fail: " << strerror(errno));
printf("failed to load config file path=%s\n", config_file.c_str());
delete config;
exit(0);
}
SDConfigurationSingleton::get_instance()->init(config);
}
void sign_t(int sign)
{
printf("error!! in thread %u\n", (unsigned int) pthread_self());
abort();
}
int main(int argc, char* argv[])
{
if (argc >= 2)
{
char *pparam = argv[1];
std::string str_param=pparam;
if (!str_param.compare("daemon"))
{
printf("become guard\n");
printf("become daemon\n");
daemon(1, 1);
do
{
pid_t pid;
pid = fork();
if (pid == 0)
{// child process
break;
}
else
{
int status=0;
waitpid(pid, &status, 0);
printf("child process exit, restart child process\n");
}
} while (true);
}
else
{
printf("becom app \n");
}
}
PropertyConfigurator::doConfigure("../conf/log4cplus.conf");
Logger logger=Logger::getInstance("MY");
LOG4CPLUS_INFO(logger,"======main======");
EnableCoreFile();
EnableFileLimit();
init_config();
//const SDConfiguration& config = SDConfigurationSingleton::get_instance()->get_config();
//std::string test = config.getString("hello","xxxx");
//module_test mytest;
//mytest.general_test();
/*if (argc < 2)
{
printf("username is needed \n");
exit(0);
}
mytest.usernametouid(argv[1]);
exit(0);*/
//log_codec_wrapper::log_codec_wrapper_init();
//general_log_client *plogclient = general_log_client::get_instance();
//plogclient->init();
signal(SIGPIPE, SIG_IGN);
//debug
signal(SIGSEGV, sign_t);
signal(SIGIO, SIG_IGN);
//signal(SIGINT, SIG_IGN);
signal(SIGALRM, SIG_IGN);
http_server diagnose_server;
diagnose_server.init();
dispatcher service;
service.init();
while(true)
{
sleep(1000000);
}
return 0;
}
| [
"18915413902@163.com"
] | 18915413902@163.com |
2113963c0eb66e7db7bf43f697480962f577be4a | e18a51c1bd1425f22db15700a88e8c66f3552d93 | /packages/lagrangian/intermediateNew/parcels/Templates/KinematicParcel/KinematicParcel.H | ee860ad478dc325305b57ba1d41997a831391526 | [] | no_license | trinath2rao/fireFoam-2.2.x | 6253191db406405683e15da2263d19f4b16181ba | 5f28904ffd7e82a9a55cb3f67fafb32f8f889d58 | refs/heads/master | 2020-12-29T01:42:16.305833 | 2014-11-24T21:53:39 | 2014-11-24T21:53:39 | 34,248,660 | 1 | 0 | null | 2015-04-20T08:37:28 | 2015-04-20T08:37:27 | null | UTF-8 | C++ | false | false | 20,385 | h | /*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | Copyright (C) 2011-2012 OpenFOAM Foundation
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
Class
Foam::KinematicParcel
Description
Kinematic parcel class with rotational motion (as spherical
particles only) and one/two-way coupling with the continuous
phase.
Sub-models include:
- drag
- turbulent dispersion
- wall interactions
SourceFiles
KinematicParcelI.H
KinematicParcel.C
KinematicParcelIO.C
\*---------------------------------------------------------------------------*/
#ifndef KinematicParcel_H
#define KinematicParcel_H
#include "particle.H"
#include "IOstream.H"
#include "autoPtr.H"
#include "interpolation.H"
// #include "ParticleForceList.H" // TODO
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
template<class ParcelType>
class KinematicParcel;
// Forward declaration of friend functions
template<class ParcelType>
Ostream& operator<<
(
Ostream&,
const KinematicParcel<ParcelType>&
);
/*---------------------------------------------------------------------------*\
Class KinematicParcel Declaration
\*---------------------------------------------------------------------------*/
template<class ParcelType>
class KinematicParcel
:
public ParcelType
{
public:
//- Class to hold kinematic particle constant properties
class constantProperties
{
// Private data
//- Constant properties dictionary
const dictionary dict_;
//- Parcel type id - used for post-processing to flag the type
// of parcels issued by this cloud
label parcelTypeId_;
//- Minimum density [kg/m3]
scalar rhoMin_;
//- Particle density [kg/m3] (constant)
scalar rho0_;
//- Minimum particle mass [kg]
scalar minParticleMass_;
//- Young's modulus [N/m2]
scalar youngsModulus_;
//- Poisson's ratio
scalar poissonsRatio_;
public:
// Constructors
//- Null constructor
constantProperties();
//- Copy constructor
constantProperties(const constantProperties& cp);
//- Constructor from dictionary
constantProperties
(
const dictionary& parentDict,
const bool readFields = true
);
//- Construct from components
constantProperties
(
const label parcelTypeId,
const scalar rhoMin,
const scalar rho0,
const scalar minParticleMass,
const scalar youngsModulus,
const scalar poissonsRatio
);
// Member functions
//- Return const access to the constant properties dictionary
inline const dictionary& dict() const;
//- Return const access to the parcel type id
inline label parcelTypeId() const;
//- Return const access to the minimum density
inline scalar rhoMin() const;
//- Return const access to the particle density
inline scalar rho0() const;
//- Return const access to the minimum particle mass
inline scalar minParticleMass() const;
//- Return const access to Young's Modulus
inline scalar youngsModulus() const;
//- Return const access to Poisson's ratio
inline scalar poissonsRatio() const;
};
template<class CloudType>
class TrackingData
:
public ParcelType::template TrackingData<CloudType>
{
public:
enum trackPart
{
tpVelocityHalfStep,
tpLinearTrack,
tpRotationalTrack
};
private:
// Private data
// Interpolators for continuous phase fields
//- Density interpolator
autoPtr<interpolation<scalar> > rhoInterp_;
//- Velocity interpolator
autoPtr<interpolation<vector> > UInterp_;
//- Dynamic viscosity interpolator
autoPtr<interpolation<scalar> > muInterp_;
//- Local gravitational or other body-force acceleration
const vector& g_;
// label specifying which part of the integration
// algorithm is taking place
trackPart part_;
public:
// Constructors
//- Construct from components
inline TrackingData
(
CloudType& cloud,
trackPart part = tpLinearTrack
);
// Member functions
//- Return conat access to the interpolator for continuous
// phase density field
inline const interpolation<scalar>& rhoInterp() const;
//- Return conat access to the interpolator for continuous
// phase velocity field
inline const interpolation<vector>& UInterp() const;
//- Return conat access to the interpolator for continuous
// phase dynamic viscosity field
inline const interpolation<scalar>& muInterp() const;
// Return const access to the gravitational acceleration vector
inline const vector& g() const;
//- Return the part of the tracking operation taking place
inline trackPart part() const;
//- Return access to the part of the tracking operation taking place
inline trackPart& part();
};
protected:
// Protected data
// Parcel properties
//- Active flag - tracking inactive when active = false
bool active_;
//- Parcel type id
label typeId_;
//- Number of particles in Parcel
scalar nParticle_;
//- Diameter [m]
scalar d_;
//- Target diameter [m]
scalar dTarget_;
//- Velocity of Parcel [m/s]
vector U_;
//- Force on particle due to collisions [N]
vector f_;
//- Angular momentum of Parcel in global reference frame
// [kg m2/s]
vector angularMomentum_;
//- Torque on particle due to collisions in global
// reference frame [Nm]
vector torque_;
//- Density [kg/m3]
scalar rho_;
//- Age [s]
scalar age_;
//- Time spent in turbulent eddy [s]
scalar tTurb_;
//- Turbulent velocity fluctuation [m/s]
vector UTurb_;
// Cell-based quantities
//- Density [kg/m3]
scalar rhoc_;
//- Velocity [m/s]
vector Uc_;
//- Viscosity [Pa.s]
scalar muc_;
// Protected Member Functions
//- Calculate new particle velocity
template<class TrackData>
const vector calcVelocity
(
TrackData& td,
const scalar dt, // timestep
const label cellI, // owner cell
const scalar Re, // Reynolds number
const scalar mu, // local carrier viscosity
const scalar mass, // mass
const vector& Su, // explicit particle momentum source
vector& dUTrans, // momentum transfer to carrier
scalar& Spu // linearised drag coefficient
) const;
public:
// Static data members
//- Runtime type information
TypeName("KinematicParcel");
//- String representation of properties
AddToPropertyList
(
ParcelType,
" active"
+ " typeId"
+ " nParticle"
+ " d"
+ " dTarget "
+ " (Ux Uy Uz)"
+ " (fx fy fz)"
+ " (angularMomentumx angularMomentumy angularMomentumz)"
+ " (torquex torquey torquez)"
+ " rho"
+ " age"
+ " tTurb"
+ " (UTurbx UTurby UTurbz)"
);
// Constructors
//- Construct from owner, position, and cloud owner
// Other properties initialised as null
inline KinematicParcel
(
const polyMesh& mesh,
const vector& position,
const label cellI,
const label tetFaceI,
const label tetPtI
);
//- Construct from components
inline KinematicParcel
(
const polyMesh& mesh,
const vector& position,
const label cellI,
const label tetFaceI,
const label tetPtI,
const label typeId,
const scalar nParticle0,
const scalar d0,
const scalar dTarget0,
const vector& U0,
const vector& f0,
const vector& angularMomentum0,
const vector& torque0,
const constantProperties& constProps
);
//- Construct from Istream
KinematicParcel
(
const polyMesh& mesh,
Istream& is,
bool readFields = true
);
//- Construct as a copy
KinematicParcel(const KinematicParcel& p);
//- Construct as a copy
KinematicParcel(const KinematicParcel& p, const polyMesh& mesh);
//- Construct and return a (basic particle) clone
virtual autoPtr<particle> clone() const
{
return autoPtr<particle>(new KinematicParcel(*this));
}
//- Construct and return a (basic particle) clone
virtual autoPtr<particle> clone(const polyMesh& mesh) const
{
return autoPtr<particle>(new KinematicParcel(*this, mesh));
}
//- Factory class to read-construct particles used for
// parallel transfer
class iNew
{
const polyMesh& mesh_;
public:
iNew(const polyMesh& mesh)
:
mesh_(mesh)
{}
autoPtr<KinematicParcel<ParcelType> > operator()(Istream& is) const
{
return autoPtr<KinematicParcel<ParcelType> >
(
new KinematicParcel<ParcelType>(mesh_, is, true)
);
}
};
// Member Functions
// Access
//- Return const access to active flag
inline bool active() const;
//- Return const access to type id
inline label typeId() const;
//- Return const access to number of particles
inline scalar nParticle() const;
//- Return const access to diameter
inline scalar d() const;
//- Return const access to target diameter
inline scalar dTarget() const;
//- Return const access to velocity
inline const vector& U() const;
//- Return const access to force
inline const vector& f() const;
//- Return const access to angular momentum
inline const vector& angularMomentum() const;
//- Return const access to torque
inline const vector& torque() const;
//- Return const access to density
inline scalar rho() const;
//- Return const access to the age
inline scalar age() const;
//- Return const access to time spent in turbulent eddy
inline scalar tTurb() const;
//- Return const access to turbulent velocity fluctuation
inline const vector& UTurb() const;
//- Return const access to carrier density [kg/m3]
inline scalar rhoc() const;
//- Return const access to carrier velocity [m/s]
inline const vector& Uc() const;
//- Return const access to carrier viscosity [Pa.s]
inline scalar muc() const;
// Edit
//- Return const access to active flag
inline bool& active();
//- Return access to type id
inline label& typeId();
//- Return access to number of particles
inline scalar& nParticle();
//- Return access to diameter
inline scalar& d();
//- Return access to target diameter
inline scalar& dTarget();
//- Return access to velocity
inline vector& U();
//- Return access to force
inline vector& f();
//- Return access to angular momentum
inline vector& angularMomentum();
//- Return access to torque
inline vector& torque();
//- Return access to density
inline scalar& rho();
//- Return access to the age
inline scalar& age();
//- Return access to time spent in turbulent eddy
inline scalar& tTurb();
//- Return access to turbulent velocity fluctuation
inline vector& UTurb();
// Helper functions
//- Return the index of the face to be used in the interpolation
// routine
inline label faceInterpolation() const;
//- Cell owner mass
inline scalar massCell(const label cellI) const;
//- Particle mass
inline scalar mass() const;
//- Particle moment of inertia around diameter axis
inline scalar momentOfInertia() const;
//- Particle angular velocity
inline vector omega() const;
//- Particle volume
inline scalar volume() const;
//- Particle volume for a given diameter
inline static scalar volume(const scalar d);
//- Particle projected area
inline scalar areaP() const;
//- Projected area for given diameter
inline static scalar areaP(const scalar d);
//- Particle surface area
inline scalar areaS() const;
//- Surface area for given diameter
inline static scalar areaS(const scalar d);
//- Reynolds number
inline scalar Re
(
const vector& U, // particle velocity
const scalar d, // particle diameter
const scalar rhoc, // carrier density
const scalar muc // carrier dynamic viscosity
) const;
//- Weber number
inline scalar We
(
const vector& U, // particle velocity
const scalar d, // particle diameter
const scalar rhoc, // carrier density
const scalar sigma // particle surface tension
) const;
//- Eotvos number
inline scalar Eo
(
const vector& a, // acceleration
const scalar d, // particle diameter
const scalar sigma // particle surface tension
) const;
// Main calculation loop
//- Set cell values
template<class TrackData>
void setCellValues
(
TrackData& td,
const scalar dt,
const label cellI
);
//- Correct cell values using latest transfer information
template<class TrackData>
void cellValueSourceCorrection
(
TrackData& td,
const scalar dt,
const label cellI
);
//- Update parcel properties over the time interval
template<class TrackData>
void calc
(
TrackData& td,
const scalar dt,
const label cellI
);
// Tracking
//- Move the parcel
template<class TrackData>
bool move(TrackData& td, const scalar trackTime);
// Patch interactions
//- Overridable function to handle the particle hitting a face
// without trackData
void hitFace(int& td);
//- Overridable function to handle the particle hitting a face
template<class TrackData>
void hitFace(TrackData& td);
//- Overridable function to handle the particle hitting a patch
// Executed before other patch-hitting functions
template<class TrackData>
bool hitPatch
(
const polyPatch& p,
TrackData& td,
const label patchI,
const scalar trackFraction,
const tetIndices& tetIs
);
//- Overridable function to handle the particle hitting a
// processorPatch
template<class TrackData>
void hitProcessorPatch
(
const processorPolyPatch&,
TrackData& td
);
//- Overridable function to handle the particle hitting a wallPatch
template<class TrackData>
void hitWallPatch
(
const wallPolyPatch&,
TrackData& td,
const tetIndices&
);
//- Overridable function to handle the particle hitting a polyPatch
template<class TrackData>
void hitPatch
(
const polyPatch&,
TrackData& td
);
//- Transform the physical properties of the particle
// according to the given transformation tensor
virtual void transformProperties(const tensor& T);
//- Transform the physical properties of the particle
// according to the given separation vector
virtual void transformProperties(const vector& separation);
//- The nearest distance to a wall that the particle can be
// in the n direction
virtual scalar wallImpactDistance(const vector& n) const;
// I-O
//- Read
template<class CloudType>
static void readFields(CloudType& c);
//- Write
template<class CloudType>
static void writeFields(const CloudType& c);
// Ostream Operator
friend Ostream& operator<< <ParcelType>
(
Ostream&,
const KinematicParcel<ParcelType>&
);
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace Foam
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#include "KinematicParcelI.H"
#include "KinematicParcelTrackingDataI.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#ifdef NoRepository
#include "KinematicParcel.C"
#endif
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //
| [
"karl.meredith@fmglobal.com"
] | karl.meredith@fmglobal.com |
ddbe164296fe772daef73bdf76842991f7d7c89b | bd56aece437cd598f929ca4df96138e8c2a5713e | /2DPlatformer/Fighter.h | dbf58cd453f60d8b9bff5931303adc8bfd2f0789 | [] | no_license | dbncourt/SpaceFighter | 9bb5b1585459cef5f81d59e208c38b20815e9890 | 84c4fa2428dad8573e8eabf23180610c83d2229a | refs/heads/master | 2021-01-01T06:05:05.102586 | 2015-10-01T01:41:27 | 2015-10-01T01:41:27 | 42,380,702 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 960 | h | ////////////////////////////////////////////////////////////////////////////////
// Filename: Fighter.h
////////////////////////////////////////////////////////////////////////////////
#ifndef _FIGHTER_H_
#define _FIGHTER_H_
//////////////
// INCLUDES //
//////////////
#include <list>
///////////////////////
// MY CLASS INCLUDES //
///////////////////////
#include "GameObject.h"
#include "BoxCollider.h"
class Fighter : public GameObject
{
public:
Fighter();
Fighter(const Fighter& other);
~Fighter();
virtual bool Initialize(ID3D11Device* device, HWND hwnd, Bitmap::DimensionType screen, bool drawCollider) override;
virtual bool Render(ID3D11DeviceContext* deviceContext, D3DXMATRIX wordMatrix, D3DXMATRIX viewMatrix, D3DXMATRIX projectionMatrix) override;
virtual void Frame(const InputHandler::ControlsType& controls) override;
private:
BoxCollider* m_boxCollider;
const int SHIP_SPEED = 3;
const float ANIMATION_DELAY = 20.0f;
};
#endif | [
"dbncourt@gmail.com"
] | dbncourt@gmail.com |
62f48f8c1e86d61f8c3caaf55e1eeb5f9c7f9d26 | ac1c9fbc1f1019efb19d0a8f3a088e8889f1e83c | /out/release/gen/third_party/blink/renderer/bindings/modules/v8/v8_data_transfer_item_partial.cc | dc2be783a55ea6cbfac2593cfd4102495af82a30 | [
"BSD-3-Clause"
] | permissive | xueqiya/chromium_src | 5d20b4d3a2a0251c063a7fb9952195cda6d29e34 | d4aa7a8f0e07cfaa448fcad8c12b29242a615103 | refs/heads/main | 2022-07-30T03:15:14.818330 | 2021-01-16T16:47:22 | 2021-01-16T16:47:22 | 330,115,551 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,253 | cc | // Copyright 2014 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.
// This file has been auto-generated from the Jinja2 template
// third_party/blink/renderer/bindings/templates/partial_interface.cc.tmpl
// by the script code_generator_v8.py.
// DO NOT MODIFY!
// clang-format off
#include "third_party/blink/renderer/bindings/modules/v8/v8_data_transfer_item_partial.h"
#include <algorithm>
#include "base/memory/scoped_refptr.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_data_transfer_item.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_dom_configuration.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_entry.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/frame/web_feature.h"
#include "third_party/blink/renderer/modules/filesystem/data_transfer_item_file_system.h"
#include "third_party/blink/renderer/platform/bindings/exception_messages.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/bindings/runtime_call_stats.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
#include "third_party/blink/renderer/platform/bindings/v8_object_constructor.h"
#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/scheduler/public/cooperative_scheduling_manager.h"
#include "third_party/blink/renderer/platform/wtf/get_ptr.h"
namespace blink {
namespace data_transfer_item_partial_v8_internal {
static void WebkitGetAsEntryMethod(const v8::FunctionCallbackInfo<v8::Value>& info) {
DataTransferItem* impl = V8DataTransferItem::ToImpl(info.Holder());
ScriptState* script_state = ScriptState::ForRelevantRealm(info);
Entry* result = DataTransferItemFileSystem::webkitGetAsEntry(script_state, *impl);
V8SetReturnValue(info, result);
}
} // namespace data_transfer_item_partial_v8_internal
void V8DataTransferItemPartial::WebkitGetAsEntryMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) {
BLINK_BINDINGS_TRACE_EVENT("DataTransferItem.webkitGetAsEntry");
RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_DataTransferItem_webkitGetAsEntry");
ExecutionContext* execution_context_for_measurement = CurrentExecutionContext(info.GetIsolate());
UseCounter::Count(execution_context_for_measurement, WebFeature::kV8DataTransferItem_WebkitGetAsEntry_Method);
data_transfer_item_partial_v8_internal::WebkitGetAsEntryMethod(info);
}
static constexpr V8DOMConfiguration::MethodConfiguration kV8DataTransferItemMethods[] = {
{"webkitGetAsEntry", V8DataTransferItemPartial::WebkitGetAsEntryMethodCallback, 0, v8::None, V8DOMConfiguration::kOnPrototype, V8DOMConfiguration::kCheckHolder, V8DOMConfiguration::kDoNotCheckAccess, V8DOMConfiguration::kHasSideEffect, V8DOMConfiguration::kAllWorlds},
};
void V8DataTransferItemPartial::InstallV8DataTransferItemTemplate(
v8::Isolate* isolate,
const DOMWrapperWorld& world,
v8::Local<v8::FunctionTemplate> interface_template) {
// Initialize the interface object's template.
V8DataTransferItem::InstallV8DataTransferItemTemplate(isolate, world, interface_template);
v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interface_template);
ALLOW_UNUSED_LOCAL(signature);
v8::Local<v8::ObjectTemplate> instance_template = interface_template->InstanceTemplate();
ALLOW_UNUSED_LOCAL(instance_template);
v8::Local<v8::ObjectTemplate> prototype_template = interface_template->PrototypeTemplate();
ALLOW_UNUSED_LOCAL(prototype_template);
// Register IDL constants, attributes and operations.
V8DOMConfiguration::InstallMethods(
isolate, world, instance_template, prototype_template, interface_template,
signature, kV8DataTransferItemMethods, base::size(kV8DataTransferItemMethods));
// Custom signature
V8DataTransferItemPartial::InstallRuntimeEnabledFeaturesOnTemplate(
isolate, world, interface_template);
}
void V8DataTransferItemPartial::InstallRuntimeEnabledFeaturesOnTemplate(
v8::Isolate* isolate,
const DOMWrapperWorld& world,
v8::Local<v8::FunctionTemplate> interface_template) {
V8DataTransferItem::InstallRuntimeEnabledFeaturesOnTemplate(isolate, world, interface_template);
v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interface_template);
ALLOW_UNUSED_LOCAL(signature);
v8::Local<v8::ObjectTemplate> instance_template = interface_template->InstanceTemplate();
ALLOW_UNUSED_LOCAL(instance_template);
v8::Local<v8::ObjectTemplate> prototype_template = interface_template->PrototypeTemplate();
ALLOW_UNUSED_LOCAL(prototype_template);
// Register IDL constants, attributes and operations.
// Custom signature
}
void V8DataTransferItemPartial::Initialize() {
// Should be invoked from ModulesInitializer.
V8DataTransferItem::UpdateWrapperTypeInfo(
&V8DataTransferItemPartial::InstallV8DataTransferItemTemplate,
nullptr,
&V8DataTransferItemPartial::InstallRuntimeEnabledFeaturesOnTemplate,
nullptr);
}
} // namespace blink
| [
"xueqi@zjmedia.net"
] | xueqi@zjmedia.net |
5091df236918ca918efa34e83268eee3fcc6fdbe | 43a2fbc77f5cea2487c05c7679a30e15db9a3a50 | /Cpp/Internal (Offsets Only)/SDK/AD_ThirdPerson_PlayerPirate_Female_Athletic_classes.h | b64e2dc918f5e7079a5eb84bd930626e57974fdd | [] | no_license | zH4x/SoT-Insider-SDK | 57e2e05ede34ca1fd90fc5904cf7a79f0259085c | 6bff738a1b701c34656546e333b7e59c98c63ad7 | refs/heads/main | 2023-06-09T23:10:32.929216 | 2021-07-07T01:34:27 | 2021-07-07T01:34:27 | 383,638,719 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 901 | h | #pragma once
// Name: SoT-Insider, Version: 1.102.2382.0
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass AD_ThirdPerson_PlayerPirate_Female_Athletic.AD_ThirdPerson_PlayerPirate_Female_Athletic_C
// 0x0000 (FullSize[0x0750] - InheritedSize[0x0750])
class UAD_ThirdPerson_PlayerPirate_Female_Athletic_C : public UAD_ThirdPerson_PlayerPirate_Female_Default_C
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass AD_ThirdPerson_PlayerPirate_Female_Athletic.AD_ThirdPerson_PlayerPirate_Female_Athletic_C");
return ptr;
}
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"Massimo.linker@gmail.com"
] | Massimo.linker@gmail.com |
efd68d2dded62d980338d0eb39b3682c8b5b1e99 | 1835bc57373845971613cda3f66b88813c139fc2 | /examples/Cylindrical/tracker.cc | 9c2ef9360fdf68c2eafe505390268eb1ec37ccc5 | [] | no_license | jtalman/ual-sandbox_SL7.4Plus | 4cf8037a0b289d9a29b9e8918ca15e40d4eca8a4 | decdce8e9e42b51be4ced1174811bcb14427353a | refs/heads/master | 2020-03-09T19:36:51.464651 | 2019-11-12T12:57:52 | 2019-11-12T12:57:52 | 128,962,122 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,565 | cc | #include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
#include "UAL/APDF/APDF_Builder.hh"
#include "PAC/Beam/Position.hh"
#include "SMF/PacSmf.h"
#include "PAC/Beam/Bunch.hh"
#include "Main/Teapot.h"
#include "UAL/UI/Shell.hh"
#include "PAC/Beam/Particle.hh"
#include "PAC/Beam/Spin.hh"
#include "UAL/SMF/AcceleratorNodeFinder.hh"
#include "Optics/PacTMap.h"
#include "Integrator/TeapotElemBend.h"
#include "positionPrinter.hh"
#include "xmgracePrint.hh"
#include "ETEAPOT/Integrator/DipoleTracker.hh"
using namespace UAL;
int main(int argc,char * argv[]){
if(argc!=2){
std::cout << "usage: ./tracker ./data/pre-E_pEDm.sxf (> ! myOut)\n";
std::cout << "argv[0] is this executable: ./tracker\n";
std::cout << "argv[1] is the input sxf file - ./data/pre-E_pEDm.sxf\n";
exit(0);
}
std::string mysxf =argv[1];
std::string mysxfbase=mysxf.substr(7,mysxf.size()-11);
std::cout << "mysxf " << mysxf.c_str() << "\n";
std::cout << "mysxfbase " << mysxfbase.c_str() << "\n";
#include "designBeamValues.hh"
#include "extractParameters.h"
UAL::Shell shell;
// ************************************************************************
std::cout << "\nDefine the space of Taylor maps." << std::endl;
// ************************************************************************
shell.setMapAttributes(UAL::Args() << UAL::Arg("order", 5));
// ************************************************************************
std::cout << "\nBuild lattice." << std::endl;
// ************************************************************************
shell.readSXF(UAL::Args() << UAL::Arg("file", sxfFile.c_str()));
// ************************************************************************
std::cout << "\nAdd split ." << std::endl;
// ************************************************************************
shell.addSplit(UAL::Args() << UAL::Arg("lattice", "ring") << UAL::Arg("types", "Sbend") << UAL::Arg("ir", split));
shell.addSplit(UAL::Args() << UAL::Arg("lattice", "ring") << UAL::Arg("types", "Quadrupole") << UAL::Arg("ir", 0));
shell.addSplit(UAL::Args() << UAL::Arg("lattice", "ring") << UAL::Arg("types", "Sextupole") << UAL::Arg("ir", 0));
// ************************************************************************
std::cout << "Select lattice." << std::endl;
// ************************************************************************
shell.use(UAL::Args() << UAL::Arg("lattice", "ring"));
// ************************************************************************
std::cout << "\nWrite SXF file ." << std::endl;
// ************************************************************************
shell.writeSXF(UAL::Args() << UAL::Arg("file", outputFile.c_str()));
// ************************************************************************
std::cout << "\nDefine beam parameters." << std::endl;
// ************************************************************************
#include "setBeamAttributes.hh"
PAC::BeamAttributes& ba = shell.getBeamAttributes();
// ************************************************************************
std::cout << "\nLinear analysis." << std::endl;
// ************************************************************************
// Make linear matrix
std::cout << " matrix" << std::endl;
shell.map(UAL::Args() << UAL::Arg("order", 1) << UAL::Arg("print", mapFile.c_str()));
// Calculate twiss
std::cout << " twiss (ring )" << std::endl;
shell.twiss(UAL::Args() << UAL::Arg("print", twissFile.c_str()));
std::cout << " calculate suml" << std::endl;
shell.analysis(UAL::Args());
// ************************************************************************
std::cout << "\nAlgorithm Part. " << std::endl;
// ************************************************************************
UAL::APDF_Builder apBuilder;
apBuilder.setBeamAttributes(ba);
UAL::AcceleratorPropagator* ap = apBuilder.parse(apdfFile);
if(ap == 0) {
std::cout << "Accelerator Propagator has not been created " << std::endl;
return 1;
}
std::cout << "\n SXF_TRACKER tracker, ";
std::cout << "size : " << ap->getRootNode().size() << " propagators " << endl;
// ************************************************************************
std::cout << "\nBunch Part." << std::endl;
// ************************************************************************
// ba.setG(1.7928474); // adds proton G factor
PAC::Bunch bunch(4); // bunch with 4 particles
bunch.setBeamAttributes(ba);
PAC::Spin spin;
spin.setSX(0.0);
spin.setSY(0.0);
spin.setSZ(1.0);
//bunch[0].getPosition().set(1.e-4,0. ,0. ,0. ,0.,0.);
bunch[0].getPosition().set(1.e-4,0. ,1.e-4,0. ,0.,0.);
bunch[1].getPosition().set(0. ,0.5e-5,0. ,0. ,0.,0.);
bunch[2].getPosition().set(0. ,0. ,1.e-4,0. ,0.,0.);
bunch[3].getPosition().set(0. ,0. ,0. ,0.5e-6,0.,0.);
// ************************************************************************
std::cout << "\nTracking. " << std::endl;
// ************************************************************************
double t; // time variable
int turns = 16;
positionPrinter pP;
pP.open(orbitFile.c_str());
xmgracePrint xP;
xP.open("bunchSub0");
ba.setElapsedTime(0.0);
for(int iturn = 1; iturn <= turns; iturn++){
ap -> propagate(bunch);
for(int ip=0; ip < bunch.size(); ip++){
pP.write(iturn, ip, bunch);
}
xP.write(iturn, 0, bunch);
}
pP.close();
xP.close();
return 1;
}
| [
"JohnDTalman@gmail.com"
] | JohnDTalman@gmail.com |
8401e26f288c6be46a17019049f6a1bccfd9212d | 525ae58ba7555323e5b3fa751f1713c264d8ec1b | /Advanced/1003.cpp | 6b60a0c85fcd0dd0d0dc79c088e66b612010bd01 | [] | no_license | zzwzxmm/PAT | 5515e304b660eab4cffe23389d30c38aec4245a1 | 2813efbc50a4f62c631e0111f72703509e9bc875 | refs/heads/master | 2020-08-07T17:34:28.632026 | 2019-12-07T03:04:19 | 2019-12-07T03:04:19 | 213,539,022 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,896 | cpp | #include<stdio.h>
#include<algorithm>
#include<iostream>
#include<vector>
using namespace std;
//Using vector node as adjacency table
struct node{
int v;
int dis;
};
//Variables define num[max] to count, num[max]=num[now]+num[pre] or num[pre];
//Using t[max] and w[max] to store maximum weight
const int MAX=500;
const int INF=1000000000;
vector<node> adj[MAX];
int t[MAX]={0};
int w[MAX]={0};
bool vis[MAX]={false};
int d[MAX];
int n,m;
int num[MAX];
//dijkstra algorithm
void dijkstra(int s){
fill(d,d+MAX,INF);
fill(num,num+MAX,INF);
d[s]=0;
num[s]=1; //initialize num;
t[s]=w[s]; //initialize t;
for(int i=0;i<n;i++){
int u=-1,MIN=INF;
for(int j=0;j<n;j++){
if(vis[j]==false && d[j]<MIN){
u=j;
MIN=d[j];
}
}
if(u==-1) return; // all visited;
vis[u]=true;
// update distance and weight, and count num;
for(int j=0;j<adj[u].size();j++){
int v=adj[u][j].v;
if(vis[v]==false && d[u]+adj[u][j].dis<d[v]){
d[v]=d[u]+adj[u][j].dis;
t[v]=t[u]+w[v];
num[v]=num[u];
} else if(d[u]+adj[u][j].dis == d[v]){
if(w[v]+t[u]>t[v]) t[v]=t[u]+w[v];
num[v]+=num[u];
}
}
}
}
int main(){
int s,dest;
scanf("%d%d%d%d",&n,&m,&s,&dest);
for(int i=0;i<n;i++) scanf("%d",&w[i]);
int city1,city2,l;
for(int i=0;i<m;i++) {
scanf("%d%d%d",&city1,&city2,&l);
node test;
test.v=city2;
test.dis=l;
adj[city1].push_back(test); //push one node in city1;
test.v=city1;
test.dis=l;
adj[city2].push_back(test); //push one node in city2; MUST!!! if not, something will be wrong;
}
dijkstra(s);
printf("%d %d",num[dest],t[dest]);
return 0;
}
| [
"noreply@github.com"
] | zzwzxmm.noreply@github.com |
b730cbb19015ce885de50335d0c25cbd314c5ada | b6ccb7529cd311c953b208e5200f26bdb3cb1d67 | /41.First Missing Positive.cpp | 0e413c0be7a093144f464da6d686b72f9e0745de | [] | no_license | swang109/Leetcode-1 | 2c5b3b6d9a7223c9f791d8972cb0da8c07e33eee | 9243f05ddd1fdcc0de2a6d57148c7df33affc627 | refs/heads/master | 2020-12-01T11:41:23.955464 | 2015-11-08T22:40:40 | 2015-11-08T22:40:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 427 | cpp | #include <iostream>
#include <vector>
using namespace std;
int firstMissingPositive(vector<int>& nums) {
for (int i = 0; i < nums.size(); i++)
while (nums[i] > 0 && nums[i] <= nums.size() && nums[i] != nums[nums[i] - 1])
swap(nums[i], nums[nums[i] - 1]);
for (int i = 0; i < nums.size(); i++)
if (nums[i] != i + 1)
return i + 1;
return nums.size() + 1;
}
int main() {
}
| [
"roddykou@gmail.com"
] | roddykou@gmail.com |
7a3fefa58ce5fe985874f035fd6424270fdece2a | ad6e3ddf624e444820972845ed70d84a7628dd0b | /Cpp/442.cpp | 4f9bf154dc8a744eadcaedc2571a40f526f2e852 | [] | no_license | ZoeyeoZ/LeetCode-Program-Learning | 4c1d422a0d10e03ebce4154a8a400f6523e0da22 | 5369d7ed4eaeaa95542244aad1bce598e01e1386 | refs/heads/master | 2021-07-13T18:27:43.634167 | 2019-01-27T00:33:48 | 2019-01-27T00:33:48 | 114,710,884 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 849 | cpp | /*
no extra space & O(n) time
1.
mark with highest bit
int index = nums[i] & 0x7fffffff;
if (nums[index - 1] < 0) {
r.push_back(index);
}
else {
nums[index - 1] |= 0x80000000;
}
2.
mark using negative
nums[abs(nums[i])-1] = -nums[abs(nums[i])-1];
if(nums[abs(nums[i])-1] > 0) res.push_back(abs(nums [i]));
3.
put x in nums[x-1] -> swap(nums[i], nums[nums[i]-1]);
then check if x doesn’t present in nums[x - 1], then x is absent.
we */
class Solution {
public:
vector<int> findDuplicates(vector<int>& nums) {
vector<int> ans;
for (auto num:nums){
if (nums[abs(num)-1]<0)
ans.push_back(abs(num));
else
nums[abs(num)-1] *= -1;
}
return ans;
}
};
// We can caculate n = abs(n), then do the same thing, it will be faster
// But the problem is what if it appear 4 times?
| [
"noreply@github.com"
] | ZoeyeoZ.noreply@github.com |
9deda26c98829c6f09c81085d08900cffc1ea5c3 | 3c2217a9e512b0f0cc9158729bf29117673d60fa | /uva 1185 solution.cpp | d774e54a4d5cfed7c5ce0b80ebca095f939f20ff | [] | no_license | tanveerislam/UVASolution | 84b0f443ae435dabe09189ba5ed7a2b550b66415 | 9c03e59fc0a93f319ff17e85a5012823ace16166 | refs/heads/master | 2020-07-22T00:00:41.956658 | 2019-09-07T18:12:57 | 2019-09-07T18:12:57 | 207,007,229 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 441 | cpp | #include<iostream>
#include<cstdio>
using namespace std;
long long a[100000];
int main()
{
long long m,t,i,j,k,l,c;
double n;
cin>>t;
for(i=0;i<t;i++)
{
cin>>a[i];
n=(double)a[i];
c=1;
for(j=n-1;j>0;j--)
{
while(n>=10.0)
{
c++;
n/=10.0;
}
n*=j;
}
cout<<c<<endl;
}
return 0;
}
| [
"tanveerlab10ragshahi@gmail.com"
] | tanveerlab10ragshahi@gmail.com |
39e5fca2873f87f549dc7d7e8a5a8158864f5d8d | e3f4283e488dabbc45cbeeb6309503f8334571e9 | /Wire/Wire.cpp | 881b31bcaa0cefad701933da997fea6b0d75e47d | [] | no_license | igouss/RobotProto | 139a81fe4fc2faa9b3520749bf9bf716c6de3264 | 74833be50b68eb7dc27ec2e60ef9cfa9cb128064 | refs/heads/master | 2021-01-17T06:33:41.452786 | 2011-09-10T01:43:01 | 2011-09-10T01:43:01 | 2,166,120 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,904 | cpp | ///*
// TwoWire.cpp - TWI/I2C library for Wiring & Arduino
// Copyright (c) 2006 Nicholas Zambetti. All right reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//*/
//
//extern "C" {
// #include <stdlib.h>
// #include <string.h>
// #include <inttypes.h>
// #include "utility/twi.h"
//}
//
//#include "Wire.h"
//
//// Initialize Class Variables //////////////////////////////////////////////////
//
//uint8_t TwoWire::rxBuffer[BUFFER_LENGTH];
//uint8_t TwoWire::rxBufferIndex = 0;
//uint8_t TwoWire::rxBufferLength = 0;
//
//uint8_t TwoWire::txAddress = 0;
//uint8_t TwoWire::txBuffer[BUFFER_LENGTH];
//uint8_t TwoWire::txBufferIndex = 0;
//uint8_t TwoWire::txBufferLength = 0;
//
//uint8_t TwoWire::transmitting = 0;
//void (*TwoWire::user_onRequest)(void);
//void (*TwoWire::user_onReceive)(int);
//
//// Constructors ////////////////////////////////////////////////////////////////
//
//TwoWire::TwoWire()
//{
//}
//
//// Public Methods //////////////////////////////////////////////////////////////
//
//void TwoWire::begin(void)
//{
// rxBufferIndex = 0;
// rxBufferLength = 0;
//
// txBufferIndex = 0;
// txBufferLength = 0;
//
// twi_init();
//}
//
//void TwoWire::begin(uint8_t address)
//{
// twi_setAddress(address);
// twi_attachSlaveTxEvent(onRequestService);
// twi_attachSlaveRxEvent(onReceiveService);
// begin();
//}
//
//void TwoWire::begin(int address)
//{
// begin((uint8_t)address);
//}
//
//uint8_t TwoWire::requestFrom(uint8_t address, uint8_t quantity)
//{
// // clamp to buffer length
// if(quantity > BUFFER_LENGTH){
// quantity = BUFFER_LENGTH;
// }
// // perform blocking read into buffer
// uint8_t read = twi_readFrom(address, rxBuffer, quantity);
// // set rx buffer iterator vars
// rxBufferIndex = 0;
// rxBufferLength = read;
//
// return read;
//}
//
//uint8_t TwoWire::requestFrom(int address, int quantity)
//{
// return requestFrom((uint8_t)address, (uint8_t)quantity);
//}
//
//void TwoWire::beginTransmission(uint8_t address)
//{
// // indicate that we are transmitting
// transmitting = 1;
// // set address of targeted slave
// txAddress = address;
// // reset tx buffer iterator vars
// txBufferIndex = 0;
// txBufferLength = 0;
//}
//
//void TwoWire::beginTransmission(int address)
//{
// beginTransmission((uint8_t)address);
//}
//
//uint8_t TwoWire::endTransmission(void)
//{
// // transmit buffer (blocking)
// int8_t ret = twi_writeTo(txAddress, txBuffer, txBufferLength, 1);
// // reset tx buffer iterator vars
// txBufferIndex = 0;
// txBufferLength = 0;
// // indicate that we are done transmitting
// transmitting = 0;
// return ret;
//}
//
//// must be called in:
//// slave tx event callback
//// or after beginTransmission(address)
//void TwoWire::send(uint8_t data)
//{
// if(transmitting){
// // in master transmitter mode
// // don't bother if buffer is full
// if(txBufferLength >= BUFFER_LENGTH){
// return;
// }
// // put byte in tx buffer
// txBuffer[txBufferIndex] = data;
// ++txBufferIndex;
// // update amount in buffer
// txBufferLength = txBufferIndex;
// }else{
// // in slave send mode
// // reply to master
// twi_transmit(&data, 1);
// }
//}
//
//// must be called in:
//// slave tx event callback
//// or after beginTransmission(address)
//void TwoWire::send(uint8_t* data, uint8_t quantity)
//{
// if(transmitting){
// // in master transmitter mode
// for(uint8_t i = 0; i < quantity; ++i){
// send(data[i]);
// }
// }else{
// // in slave send mode
// // reply to master
// twi_transmit(data, quantity);
// }
//}
//
//// must be called in:
//// slave tx event callback
//// or after beginTransmission(address)
//void TwoWire::send(char* data)
//{
// send((uint8_t*)data, strlen(data));
//}
//
//// must be called in:
//// slave tx event callback
//// or after beginTransmission(address)
//void TwoWire::send(int data)
//{
// send((uint8_t)data);
//}
//
//// must be called in:
//// slave rx event callback
//// or after requestFrom(address, numBytes)
//uint8_t TwoWire::available(void)
//{
// return rxBufferLength - rxBufferIndex;
//}
//
//// must be called in:
//// slave rx event callback
//// or after requestFrom(address, numBytes)
//uint8_t TwoWire::receive(void)
//{
// // default to returning null char
// // for people using with char strings
// uint8_t value = '\0';
//
// // get each successive byte on each call
// if(rxBufferIndex < rxBufferLength){
// value = rxBuffer[rxBufferIndex];
// ++rxBufferIndex;
// }
//
// return value;
//}
//
//// behind the scenes function that is called when data is received
//void TwoWire::onReceiveService(uint8_t* inBytes, int numBytes)
//{
// // don't bother if user hasn't registered a callback
// if(!user_onReceive){
// return;
// }
// // don't bother if rx buffer is in use by a master requestFrom() op
// // i know this drops data, but it allows for slight stupidity
// // meaning, they may not have read all the master requestFrom() data yet
// if(rxBufferIndex < rxBufferLength){
// return;
// }
// // copy twi rx buffer into local read buffer
// // this enables new reads to happen in parallel
// for(uint8_t i = 0; i < numBytes; ++i){
// rxBuffer[i] = inBytes[i];
// }
// // set rx iterator vars
// rxBufferIndex = 0;
// rxBufferLength = numBytes;
// // alert user program
// user_onReceive(numBytes);
//}
//
//// behind the scenes function that is called when data is requested
//void TwoWire::onRequestService(void)
//{
// // don't bother if user hasn't registered a callback
// if(!user_onRequest){
// return;
// }
// // reset tx buffer iterator vars
// // !!! this will kill any pending pre-master sendTo() activity
// txBufferIndex = 0;
// txBufferLength = 0;
// // alert user program
// user_onRequest();
//}
//
//// sets function called on slave write
//void TwoWire::onReceive( void (*function)(int) )
//{
// user_onReceive = function;
//}
//
//// sets function called on slave read
//void TwoWire::onRequest( void (*function)(void) )
//{
// user_onRequest = function;
//}
//
//// Preinstantiate Objects //////////////////////////////////////////////////////
//
//TwoWire Wire = TwoWire();
| [
"i.gouss@gmail.com"
] | i.gouss@gmail.com |
f087a53e54beb2bd8e9ef1ce76eb3d5530a6c867 | ece2011fdb20670f76b6b970df54bc818c6b313b | /Sources/Inputs/AxisCompound.cpp | 121c741d5954050f89ad73628f721e636f61926f | [
"MIT"
] | permissive | FirstLoveLife/Acid | eda32711a0cfdcc9f596e547e2880e9edfffda5a | b7ce821a6a2b2d4bc441b724fabe1bbd9b9c6b8d | refs/heads/master | 2020-04-28T04:20:02.863648 | 2019-03-15T19:26:27 | 2019-03-15T19:26:27 | 174,974,067 | 0 | 0 | null | 2019-03-11T10:09:23 | 2019-03-11T10:09:22 | null | UTF-8 | C++ | false | false | 372 | cpp | #include "AxisCompound.hpp"
namespace acid
{
AxisCompound::AxisCompound(const std::vector<IAxis *> &axes)
{
for (const auto &axis : axes)
{
m_axes.emplace_back(axis);
}
}
float AxisCompound::GetAmount() const
{
auto result = 0.0f;
for (const auto &axis : m_axes)
{
result += axis->GetAmount();
}
return std::clamp(result, -1.0f, 1.0f);
}
}
| [
"mattparks5855@gmail.com"
] | mattparks5855@gmail.com |
d0779c97dc47d49d93a3454332e4a2f479e30d3e | 841776845974ba2645eff58ff8fabedd873093f0 | /8.最短路径/P2829大逃离.cpp | 278d68a6e0ebfde1361e94ca98674ad04e9183cd | [] | no_license | hello-sources/Coding-Training | f2652c9b8e58d244a172922e56897fa2a3ad52fb | d885ca23676cb712243640169cf2e5bef2d8c70e | refs/heads/master | 2023-01-19T11:17:36.097846 | 2023-01-01T00:49:09 | 2023-01-01T00:49:09 | 246,630,755 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,805 | cpp | /*************************************************************************
> File Name: P2829大逃离.cpp
> Author: ltw
> Mail: 3245849061@qq.com
> Github: https://github.com/hello-sources
> Created Time: Thu 02 Jul 2020 03:31:59 PM CST
************************************************************************/
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
struct edge {
int from, to, val, next;
};
edge edg[200005];
int n, m, k, edg_cnt, head[5005], ans[5005], ans2[5005], mark[5005], connect[5005];
char edg_mark[5005][5005];
void add_edge(int a, int b, int c) {
edg[edg_cnt].from = a;
edg[edg_cnt].to = b;
edg[edg_cnt].val = c;
edg[edg_cnt].next = head[a];
head[a] = edg_cnt;
edg_cnt++;
}
int main() {
memset(ans, 0x3F, sizeof(ans));
memset(ans2, 0x3F, sizeof(ans2));
memset(head, -1, sizeof(head));
cin >> n >> m >> k;
for (int i = 1; i <= m; i++) {
int a, b, c;
cin >> a >> b >> c;
if (edg_mark[a][b] == 0) {
connect[a]++;
connect[b]++;
}
edg_mark[a][b] = 1;
edg_mark[b][a] = 1;
add_edge(a, b, c);
add_edge(b, a, c);
}
queue<int> que;
que.push(1);
ans[1] = 0;
mark[1] = 1;
while (!que.empty()) {
int t = que.front();
que.pop();
mark[t] = 0;
for (int cnt = head[t]; cnt != -1; cnt = edg[cnt].next) {
if (ans[edg[cnt].to] > ans[t] + edg[cnt].val && (edg[cnt].to == n || connect[edg[cnt].to] >= k)) {
ans[edg[cnt].to] = ans[t] + edg[cnt].val;
if (mark[edg[cnt].to] == 0) {
mark[edg[cnt].to] = 1;
que.push(edg[cnt].to);
}
}
}
}
que.push(n);
ans2[n] = 0;
mark[n] = 1;
while (!que.empty()) {
int t = que.front();
que.pop();
mark[t] = 0;
for (int cnt = head[t]; cnt != -1; cnt = edg[cnt].next) {
if (ans2[edg[cnt].to] > ans2[t] + edg[cnt].val && (edg[cnt].to == 1 || connect[edg[cnt].to] >= k)) {
ans2[edg[cnt].to] = ans2[t] + edg[cnt].val;
if (mark[edg[cnt].to] == 0) {
mark[edg[cnt].to] = 1;
que.push(edg[cnt].to);
}
}
}
}
int fin = 999999999;
for (int i = 0; i < edg_cnt; i++) {
int t = ans[edg[i].from] + ans2[edg[i].to] + edg[i].val;
int a = edg[i].from, b = edg[i].to;
if (fin > t && t != ans[n] && ((connect[a] >= k && connect[b] >= k) || a == 1 || b == 1 || a == n || b == n)) {
fin = t;
}
}
if (fin != 999999999) {
cout << fin << endl;
} else {
cout << -1 << endl;
}
return 0;
}
| [
"3245849061@qq.com"
] | 3245849061@qq.com |
713a1a0e1514d669dc3af66b65ee30e7530d8298 | 7842405af3bb3224de1790d75822e22a034cc584 | /ClassRoster/Code_Files/softwareStudent.h | 4fdb945d5e0f5bfeddb17550c5d2b7b68d611a0f | [] | no_license | Joseph-Maulin/Class_Roster | 9d25ea9ddb5ca75529d2966b1b456adc6220e57c | f370b434e2e435f5dbba05761ab914cb03877256 | refs/heads/master | 2023-01-25T05:16:25.227642 | 2020-12-07T03:29:41 | 2020-12-07T03:29:41 | 293,864,421 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 720 | h | #ifndef softwareStudent_H
#define softwareStudent_H
#include <string>
#include "Student.h"
#include "degree.h"
using namespace std;
class SoftwareStudent: public Student{
public:
//Constructors
SoftwareStudent(string input);
SoftwareStudent(string studentID, string firstName, string lastName, string emailAddress, int age, int daysInCourse1,
int daysInCourse2, int daysInCourse3, Degrees degreeProgram);
//print methods
void printStudentData();
void printDaysInCourse();
void printDegreeProgram();
//accessor
string GetDegreeProgram();
//mutator
void SetDegreeProgram(Degrees newDegree);
private:
Degrees degree;
};
#endif | [
"noreply@github.com"
] | Joseph-Maulin.noreply@github.com |
4bad78897ff2cc64284e87972bbf4e3990e2e7a1 | f53c6b3045e89b6674808e1c41495a020af48484 | /test/sy/angle/angle.ino | ba29651295de0c87b3fa57143129e7b7f4ffdb30 | [] | no_license | Team-Achi/Electric-Toothbrush | 73783a78c7d2b319718277e93fd5161b671e9fec | 74a4ec49851a60d0e93f84cbbfe2d76d159114fa | refs/heads/master | 2020-03-28T19:42:15.625659 | 2018-12-10T14:18:33 | 2018-12-10T14:18:33 | 149,001,579 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,052 | ino | #include<Wire.h>
const int MPU=0x68;//MPU6050 I2C주소
int AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ;
void get6050();
void setup()
{
Wire.begin();
Wire.beginTransmission(MPU);
Wire.write(0x6B);
Wire.write(0);//MPU6050 을 동작 대기 모드로 변경
Wire.endTransmission(true);
Serial.begin(9600);
}
void loop()
{
get6050();//센서값 갱신
//받아온 센서값을 출력합니다.
Serial.print(AcX);
Serial.print("\t");
Serial.print(AcY);
Serial.print("\t");
Serial.print(AcZ);
Serial.println();
delay(500);
}
void get6050(){
Wire.beginTransmission(MPU);//MPU6050 호출
Wire.write(0x3B);//AcX 레지스터 위치 요청
Wire.endTransmission(false);
Wire.requestFrom(MPU,14,true);//14byte의 데이터를 요청
AcX=Wire.read()<<8|Wire.read();//두개의 나뉘어진 바이트를 하나로 이어붙입니다.
AcY=Wire.read()<<8|Wire.read();
AcZ=Wire.read()<<8|Wire.read();
Tmp=Wire.read()<<8|Wire.read();
GyX=Wire.read()<<8|Wire.read();
GyY=Wire.read()<<8|Wire.read();
GyZ=Wire.read()<<8|Wire.read();
}
| [
"gfsusan@naver.com"
] | gfsusan@naver.com |
b1bc9ea4a932837fe65731fe52349fbafa30c4ed | 7dd9149a4518ac21e3e2ba500f7cdc9823ddaf06 | /T1/CardT1.cpp | fd5f133cf6f9011be375e835ba767906cd671df9 | [
"MIT"
] | permissive | bcspragu/Casino | d34848ae60631cd05de9c249c9f7d7e734375fc3 | eaa106432b6e8ecdd5860d5007f1404e0150e154 | refs/heads/master | 2021-01-21T02:11:13.193473 | 2015-05-05T00:09:29 | 2015-05-05T00:09:29 | 14,091,812 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,652 | cpp | #include <string>
#include "CardT1.h"
using std::string;
CardT1::CardT1(Suit s, Value v){
suit = s;
value = v;
}
CardT1::CardT1(string s){
string su;
string va;
va += s[0];
if(s[0] == '1'){
va += s[1];
}
//Last character
su = *s.rbegin();
if(va == "2"){
value = (Value)0;
}else if(va == "3"){
value = (Value)1;
}else if(va == "4"){
value = (Value)2;
}else if(va == "5"){
value = (Value)3;
}else if(va == "6"){
value = (Value)4;
}else if(va == "7"){
value = (Value)5;
}else if(va == "8"){
value = (Value)6;
}else if(va == "9"){
value = (Value)7;
}else if(va == "10"){
value = (Value)8;
}else if(va == "J"){
value = (Value)9;
}else if(va == "Q"){
value = (Value)10;
}else if(va == "K"){
value = (Value)11;
}else if(va == "A"){
value = (Value)12;
}
if(su == "S"){
suit = (Suit)0;
}else if(su == "D"){
suit = (Suit)1;
}else if(su == "H"){
suit = (Suit)2;
}else if(su == "C"){
suit = (Suit)3;
}
}
CardT1::~CardT1(){}
Suit CardT1::suitFromInt(int i){
Suit s;
switch(i){
case 0:
s = SPADES;
break;
case 1:
s = DIAMONDS;
break;
case 2:
s = HEARTS;
break;
case 3:
s = CLUBS;
break;
}
return s;
}
Value CardT1::valueFromInt(int i){
Value v;
switch(i){
case 0:
v = TWO;
break;
case 1:
v = THREE;
break;
case 2:
v = FOUR;
break;
case 3:
v = FIVE;
break;
case 4:
v = SIX;
break;
case 5:
v = SEVEN;
break;
case 6:
v = EIGHT;
break;
case 7:
v = NINE;
break;
case 8:
v = TEN;
break;
case 9:
v = JACK;
break;
case 10:
v = QUEEN;
break;
case 11:
v = KING;
break;
case 12:
v = ACE;
break;
}
return v;
}
string CardT1::cardString(){
string suitString;
switch(suit){
case HEARTS:
suitString = "Hearts";
break;
case DIAMONDS:
suitString = "Diamonds";
break;
case SPADES:
suitString = "Spades";
break;
case CLUBS:
suitString = "Clubs";
break;
}
string valString;
switch(value){
case TWO:
valString = "2 of";
break;
case THREE:
valString = "3 of";
break;
case FOUR:
valString = "4 of";
break;
case FIVE:
valString = "5 of";
break;
case SIX:
valString = "6 of";
break;
case SEVEN:
valString = "7 of";
break;
case EIGHT:
valString = "8 of";
break;
case NINE:
valString = "9 of";
break;
case TEN:
valString = "10 of";
break;
case JACK:
valString = "Jack of";
break;
case QUEEN:
valString = "Queen of";
break;
case KING:
valString = "King of";
break;
case ACE:
valString = "Ace of";
break;
}
return valString+" "+suitString;
}
//Take the original cardString, and shorten it. ex King of Hearts = KH
string CardT1::shortCardString(){
string cardString = CardT1::cardString();
string shortString;
int spaceCount = 0;
string::iterator itr;
shortString += cardString[0];
if(cardString[0] == '1'){
shortString += cardString[1];
}
for(itr = cardString.begin(); itr < cardString.end(); itr++){
if(spaceCount == 2){
shortString += (*itr);
break;
}
//Character is a space
if((*itr) == ' '){
spaceCount++;
}
}
return shortString;
}
bool CardT1::operator<(const CardT1 &other) const {
return value < other.value;
}
| [
"brandon00sprague@gmail.com"
] | brandon00sprague@gmail.com |
b96791c7ba47fa615a92e6ab8ca47a7e13e5d7bb | e07e3f41c9774c9684c4700a9772712bf6ac3533 | /app/Temp/StagingArea/Data/il2cppOutput/mscorlib_System_Collections_Generic_Dictionary_2_T2723200652.h | 1e9b71d374786c2e5775168166d7c9f1d70cc086 | [] | 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,148 | h | #pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
// System.ComponentModel.WeakObjectWrapper
struct WeakObjectWrapper_t2012978780;
// System.Collections.Generic.LinkedList`1<System.ComponentModel.TypeDescriptionProvider>
struct LinkedList_1_t2743332604;
// System.IAsyncResult
struct IAsyncResult_t1999651008;
// System.AsyncCallback
struct AsyncCallback_t163412349;
// System.Object
struct Il2CppObject;
#include "mscorlib_System_MulticastDelegate3201952435.h"
#include "mscorlib_System_Collections_DictionaryEntry3048875398.h"
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Collections.Generic.Dictionary`2/Transform`1<System.ComponentModel.WeakObjectWrapper,System.Collections.Generic.LinkedList`1<System.ComponentModel.TypeDescriptionProvider>,System.Collections.DictionaryEntry>
struct Transform_1_t2723200652 : public MulticastDelegate_t3201952435
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| [
"gdesmarais@gsngames.com"
] | gdesmarais@gsngames.com |
62e834969f9caf4ea346d078db2eee2a19074293 | 9008c55d40a55adf6432152fc4fb9bfc71824c42 | /src/Overlook/SystemQueue.cpp | 1e5708c3418448aeb9a5aa2ad3cf19163e36222c | [
"BSD-3-Clause"
] | permissive | IanMadlenya/Overlook | 6a9c46483c5ce651b3f4caac4b41b3e1f1aba8a8 | e62ef353e72d9513f43652d027c546547195a143 | refs/heads/master | 2021-04-25T07:20:49.668491 | 2018-02-19T21:30:50 | 2018-02-19T21:30:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,736 | cpp | #include "Overlook.h"
namespace Overlook {
void System::InitRegistry() {
ASSERT(regs.IsEmpty());
ASSERT_(System::GetCoreFactories().GetCount() > 0, "Recompile Overlook.icpp to fix this stupid and weird problem");
// Register factories
for(int i = 0; i < System::GetCoreFactories().GetCount(); i++) {
// unfortunately one object must be created, because IO can't be static and virtual at the same time and it is cleaner to use virtual.
Ptr<Core> core = System::GetCoreFactories()[i].c();
FactoryRegister& reg = regs.Add();
core->IO(reg);
}
// Resize databank
data.SetCount(symbols.GetCount());
for(int i = 0; i < data.GetCount(); i++) {
data[i].SetCount(periods.GetCount());
for(int j = 0; j < periods.GetCount(); j++)
data[i][j].SetCount(regs.GetCount());
}
}
// This function is only a demonstration how to make work queues
void System::GetWorkQueue(Vector<Ptr<CoreItem> >& ci_queue) {
Index<int> sym_ids, tf_ids;
Vector<FactoryDeclaration> indi_ids;
bool all = false;
if (all) {
for(int i = 0; i < symbols.GetCount(); i++)
sym_ids.Add(i);
for(int i = periods.GetCount()-1; i >= 0; i--)
tf_ids.Add(i);
int indi_limit = Find<PeriodicalChange>();
ASSERT(indi_limit != -1);
indi_limit++;
for(int i = 0; i < indi_limit; i++)
indi_ids.Add().Set(i);
} else {
for(int i = 0; i < symbols.GetCount(); i++)
sym_ids.Add(i);
for(int i = periods.GetCount()-1; i >= periods.GetCount()-1; i--)
tf_ids.Add(i);
int indi_limit = Find<MovingAverage>() + 1;
ASSERT(indi_limit != 0);
for(int i = 0; i < indi_limit; i++)
indi_ids.Add().Set(i);
}
GetCoreQueue(ci_queue, sym_ids, tf_ids, indi_ids);
}
int System::GetCoreQueue(Vector<Ptr<CoreItem> >& ci_queue, const Index<int>& sym_ids, const Index<int>& tf_ids, const Vector<FactoryDeclaration>& indi_ids) {
const int tf_count = GetPeriodCount();
Vector<FactoryDeclaration> path;
int total = tf_ids.GetCount() * indi_ids.GetCount() + 2;
int actual = 0;
for (int i = 0; i < tf_ids.GetCount(); i++) {
int tf = tf_ids[i];
ASSERT(tf >= 0 && tf < tf_count);
for(int j = 0; j < indi_ids.GetCount(); j++) {
path.Add(indi_ids[j]);
GetCoreQueue(path, ci_queue, tf, sym_ids);
path.Pop();
WhenProgress(actual++, total);
}
}
// Sort queue by priority
struct PrioritySorter {
bool operator()(const Ptr<CoreItem>& a, const Ptr<CoreItem>& b) const {
if (a->priority == b->priority)
return a->factory < b->factory;
return a->priority < b->priority;
}
};
Sort(ci_queue, PrioritySorter());
WhenProgress(actual++, total);
// Remove duplicates
Vector<int> rem_list;
for(int i = 0; i < ci_queue.GetCount(); i++) {
CoreItem& a = *ci_queue[i];
for(int j = i+1; j < ci_queue.GetCount(); j++) {
CoreItem& b = *ci_queue[j];
if (a.sym == b.sym && a.tf == b.tf && a.factory == b.factory && a.hash == b.hash) {
rem_list.Add(j);
i++;
}
else break;
}
}
ci_queue.Remove(rem_list);
WhenProgress(actual++, total);
for(int i = 0; i < ci_queue.GetCount(); i++) {
CoreItem& ci = *ci_queue[i];
//LOG(Format("%d: sym=%d tf=%d factory=%d hash=%d", i, ci.sym, ci.tf, ci.factory, ci.hash));
}
return 0;
}
int System::GetCoreQueue(Vector<FactoryDeclaration>& path, Vector<Ptr<CoreItem> >& ci_queue, int tf, const Index<int>& sym_ids) {
const int factory = path.Top().factory;
const int tf_count = GetPeriodCount();
const int sym_count = GetTotalSymbolCount();
const int factory_count = GetFactoryCount();
// Loop inputs of the factory
const FactoryRegister& reg = regs[factory];
Vector<Vector<FactoryHash> > input_hashes;
input_hashes.SetCount(reg.in.GetCount());
// Get the unique hash for core item
Vector<int> args;
CombineHash ch;
const FactoryDeclaration& factory_decl = path.Top();
for(int i = 0; i < reg.args.GetCount(); i++) {
const ArgType& arg = reg.args[i];
int value;
ASSERT(factory_decl.arg_count >= 0 && factory_decl.arg_count <= 8);
if (i < factory_decl.arg_count) {
value = factory_decl.args[i];
ASSERT(value >= arg.min && value <= arg.max);
} else {
value = arg.def;
}
args.Add(value);
ch << value << 1;
}
int hash = ch;
// Connect input sources
// Loop all inputs of the custom core-class
for (int l = 0; l < reg.in.GetCount(); l++) {
Index<int> sub_sym_ids, sub_tf_ids;
const RegisterInput& input = reg.in[l];
ASSERT(input.factory >= 0);
FilterFunction fn = (FilterFunction)input.data;
// If equal timeframe is accepted as input
for(int i = 0; i < tf_count; i++) {
if (fn(this, -1, tf, -1, i)) {
sub_tf_ids.Add(i);
}
}
if (!sub_tf_ids.IsEmpty()) {
for(int k = 0; k < sub_tf_ids.GetCount(); k++) {
int used_tf = sub_tf_ids[k];
// Get all symbols what input requires
sub_sym_ids.Clear();
for(int i = 0; i < sym_ids.GetCount(); i++) {
int in_sym = sym_ids[i];
for(int j = 0; j < GetTotalSymbolCount(); j++) {
if (fn(this, in_sym, -1, j, -1))
sub_sym_ids.FindAdd(j);
}
}
if (!sub_sym_ids.IsEmpty()) {
FactoryDeclaration& decl = path.Add();
// Optional: add arguments by calling defined function
decl.Set(input.factory);
if (input.data2)
((ArgsFn)input.data2)(l, decl, args);
int h = GetCoreQueue(path, ci_queue, used_tf, sub_sym_ids);
path.Pop();
input_hashes[l].Add(FactoryHash(input.factory, h));
}
}
}
}
for (int i = 0; i < sym_ids.GetCount(); i++) {
int sym = sym_ids[i];
// Get CoreItem
CoreItem& ci = data[sym][tf][factory].GetAdd(hash);
// Init object if it was just created
if (ci.sym == -1) {
int path_priority = 0;//GetPathPriority(path);
ci.sym = sym;
ci.tf = tf;
if (System::PrioritySlowTf().Find(factory) == -1)
ci.priority = (factory * tf_count + tf) * sym_count + sym;
else
ci.priority = (factory * tf_count + (tf_count - 1 - tf)) * sym_count + sym;
ci.factory = factory;
ci.hash = hash;
ci.input_hashes <<= input_hashes;
ci.args <<= args;
//LOG(Format("%X\tfac=%d\tpath_priority=%d\tprio=%d", (int64)&ci, ci.factory, path_priority, ci.priority));
//DUMPC(args);
// Connect core inputs
ConnectCore(ci);
}
ci_queue.Add(&ci);
}
return hash;
}
int System::GetHash(const Vector<byte>& vec) {
CombineHash ch;
int full_ints = vec.GetCount() / 4;
int int_mod = vec.GetCount() % 4;
int* i = (int*)vec.Begin();
for(int j = 0; j < full_ints; j++) {
ch << *i << 1;
i++;
}
byte* b = (byte*)i;
for(int j = 0; j < int_mod; j++) {
ch << *b << 1;
b++;
}
return ch;
}
void System::ConnectCore(CoreItem& ci) {
const FactoryRegister& part = regs[ci.factory];
Vector<int> enabled_input_factories;
Vector<byte> unique_slot_comb;
// Connect input sources
// Loop all inputs of the custom core-class
ci.inputs.SetCount(part.in.GetCount());
ASSERT(ci.input_hashes.GetCount() == part.in.GetCount());
for (int l = 0; l < part.in.GetCount(); l++) {
const RegisterInput& input = part.in[l];
for(int k = 0; k < ci.input_hashes[l].GetCount(); k++) {
int factory = ci.input_hashes[l][k].a;
int hash = ci.input_hashes[l][k].b;
// Regular inputs
if (input.input_type == REGIN_NORMAL) {
ASSERT(input.factory == factory);
ConnectInput(l, 0, ci, input.factory, hash);
}
// Optional factory inputs
else if (input.input_type == REGIN_OPTIONAL) {
// Skip disabled
if (factory == -1)
continue;
ConnectInput(l, 0, ci, factory, hash);
}
else Panic("Invalid input type");
}
}
}
void System::ConnectInput(int input_id, int output_id, CoreItem& ci, int factory, int hash) {
Vector<int> symlist, tflist;
const RegisterInput& input = regs[ci.factory].in[input_id];
const int sym_count = GetTotalSymbolCount();
const int tf_count = GetPeriodCount();
FilterFunction fn = (FilterFunction)input.data;
if (fn) {
// Filter timeframes
for(int i = 0; i < tf_count; i++) {
if (fn(this, -1, ci.tf, -1, i)) {
tflist.Add(i);
}
}
// Filter symbols
for(int i = 0; i < sym_count; i++) {
if (fn(this, ci.sym, -1, i, -1)) {
symlist.Add(i);
}
}
}
else {
tflist.Add(ci.tf);
symlist.Add(ci.sym);
}
for(int i = 0; i < symlist.GetCount(); i++) {
int sym = symlist[i];
for(int j = 0; j < tflist.GetCount(); j++) {
int tf = tflist[j];
CoreItem& src_ci = data[sym][tf][factory].GetAdd(hash);
ASSERT_(src_ci.sym != -1, "Source CoreItem was not yet initialized");
ASSERT_(src_ci.priority <= ci.priority, "Source didn't have higher priority than current");
// Source found
ci.SetInput(input_id, src_ci.sym, src_ci.tf, src_ci, output_id);
}
}
}
void System::CreateCore(CoreItem& ci) {
ASSERT(ci.core.IsEmpty());
// Create core-object
ci.core = System::GetCoreFactories()[ci.factory].b();
Core& c = *ci.core;
// Set attributes
c.RefreshIO();
c.SetSymbol(ci.sym);
c.SetTimeframe(ci.tf, GetPeriod(ci.tf));
c.SetFactory(ci.factory);
c.SetHash(ci.hash);
// Connect object
int obj_count = c.inputs.GetCount();
int def_count = ci.inputs.GetCount();
ASSERT(obj_count == def_count);
for(int i = 0; i < ci.inputs.GetCount(); i++) {
const VectorMap<int, SourceDef>& src_list = ci.inputs[i];
Input& in = c.inputs[i];
for(int j = 0; j < src_list.GetCount(); j++) {
int key = src_list.GetKey(j);
const SourceDef& src_def = src_list[j];
Source& src_obj = in.Add(key);
CoreItem& src_ci = *src_def.coreitem;
ASSERT_(!src_ci.core.IsEmpty(), "Core object must be created before this point");
src_obj.core = &*src_ci.core;
src_obj.output = &src_obj.core->outputs[src_def.output];
src_obj.sym = src_def.sym;
src_obj.tf = src_def.tf;
}
}
// Set arguments
ArgChanger arg;
arg.SetLoading();
c.IO(arg);
if (ci.args.GetCount() > 0) {
ASSERT(ci.args.GetCount() <= arg.keys.GetCount());
for(int i = 0; i < ci.args.GetCount(); i++)
arg.args[i] = ci.args[i];
arg.SetStoring();
c.IO(arg);
}
// Initialize
c.InitAll();
c.LoadCache();
c.AllowJobs();
}
Core* System::CreateSingle(int factory, int sym, int tf) {
// Enable factory
Vector<FactoryDeclaration> path;
path.Add().Set(factory);
// Enable symbol
ASSERT(sym >= 0 && sym < symbols.GetCount());
Index<int> sym_ids;
sym_ids.Add(sym);
// Enable timeframe
ASSERT(tf >= 0 && tf < periods.GetCount());
// Get working queue
Vector<Ptr<CoreItem> > ci_queue;
GetCoreQueue(path, ci_queue, tf, sym_ids);
// Process job-queue
for(int i = 0; i < ci_queue.GetCount(); i++) {
WhenProgress(i, ci_queue.GetCount());
Process(*ci_queue[i], true);
}
return &*ci_queue.Top()->core;
}
void System::Process(CoreItem& ci, bool store_cache) {
// Load dependencies to the scope
if (ci.core.IsEmpty())
CreateCore(ci);
// Process core-object
ci.core->Refresh();
// Store cache file
if (store_cache)
ci.core->StoreCache();
}
#ifdef flagGUITASK
void System::ProcessJobs() {
bool break_loop = false;
TimeStop ts;
do {
if (job_threads.IsEmpty())
break;
break_loop = ProcessJob(gui_job_thread++);
if (gui_job_thread >= job_threads.GetCount())
gui_job_thread = 0;
}
while (ts.Elapsed() < 200 && !break_loop);
jobs_tc.Set(10, THISBACK(PostProcessJobs));
}
#else
void System::ProcessJobs() {
jobs_stopped = false;
while (jobs_running && !Thread::IsShutdownThreads()) {
LOCK(job_lock) {
int running = 0;
int max_running = GetUsedCpuCores();
for (auto& job : job_threads)
if (!job.IsStopped())
running++;
for(int i = 0; i < job_threads.GetCount() && running < max_running; i++) {
if (job_thread_iter >= job_threads.GetCount())
job_thread_iter = 0;
JobThread& job = job_threads[job_thread_iter++];
if (job.IsStopped()) {
job.Start();
if (!job.IsStopped())
running++;
}
}
}
for(int i = 0; i < 10 && jobs_running; i++)
Sleep(100);
}
LOCK(job_lock) {
for (auto& job : job_threads) job.PutStop(); // Don't wait
for (auto& job : job_threads) job.Stop();
}
jobs_stopped = true;
}
#endif
bool System::ProcessJob(int job_thread) {
return job_threads[job_thread].ProcessJob();
}
bool JobThread::ProcessJob() {
bool r = true;
READLOCK(job_lock) {
if (!jobs.IsEmpty()) {
Job& job = *jobs[job_iter];
if (job.IsFinished()) {
job_iter++;
if (job_iter >= jobs.GetCount()) {
job_iter = 0;
r = false;
}
}
else {
if (job.core->IsInitialized()) {
job.core->EnterJob(&job, this);
bool succ = job.Process();
job.core->LeaveJob();
if (!succ && job.state == Job::INIT)
r = false;
// FIXME: postponing returns false also if (!succ) is_fail = true;
}
// Resist useless fast loop here
else Sleep(100);
}
// Resist useless fast loop here
if (job.state != Job::RUNNING) Sleep(100);
}
else r = false;
}
// Resist useless fast loop here
if (r == false) Sleep(100);
return r;
}
void System::StopJobs() {
#ifndef flagGUITASK
jobs_running = false;
while (!jobs_stopped) Sleep(100);
#endif
StoreJobCores();
}
void System::StoreJobCores() {
Index<Core*> job_cores;
for(int i = 0; i < job_threads.GetCount(); i++) {
JobThread& job_thrd = job_threads[i];
for(int j = 0; j < job_thrd.jobs.GetCount(); j++) {
Job& job = *job_thrd.jobs[j];
Core* core = job.core;
if (!core) continue;
job_cores.FindAdd(core);
}
}
for(int i = 0; i < job_cores.GetCount(); i++)
job_cores[i]->StoreCache();
}
bool Job::Process() {
if (!allow_processing)
return false;
bool r = true;
int begin_state = state;
core->serialization_lock.Enter();
switch (state) {
case INIT: core->RefreshSources();
if ((r=begin()) || !begin) state++; break;
case RUNNING: if ((r=iter()) && actual >= total || !iter) state++; break;
case STOPPING: if ((r=end()) || !end) state++; break;
case INSPECTING: if ((r=inspect()) || !inspect) state++; break;
}
core->serialization_lock.Leave();
if (begin_state < state || ts.Elapsed() >= 5 * 60 * 1000) {
core->StoreCache();
ts.Reset();
}
return r;
}
String Job::GetStateString() const {
switch (state) {
case INIT: return "Init";
case RUNNING: return "Running";
case STOPPING: return "Stopping";
case INSPECTING: return "Inspecting";
case STOPPED: return "Finished";
}
return "";
}
void System::InspectionFailed(const char* file, int line, int symbol, int tf, String msg) {
LOCK(inspection_lock) {
bool found = false;
for(int i = 0; i < inspection_results.GetCount(); i++) {
InspectionResult& r = inspection_results[i];
if (r.file == file &&
r.line == line &&
r.symbol == symbol &&
r.tf == tf &&
r.msg == msg) {
found = true;
break;
}
}
if (!found) {
InspectionResult& r = inspection_results.Add();
r.file = file;
r.line = line;
r.symbol = symbol;
r.tf = tf;
r.msg = msg;
}
}
}
void System::StoreCores() {
for (auto& s : data) {
for (auto& t : s) {
for (auto& f : t) {
for (auto& ci : f) {
if (!ci.core.IsEmpty())
ci.core->StoreCache();
}
}
}
}
}
bool System::RefreshReal() {
Time now = GetUtcTime();
int wday = DayOfWeek(now);
Time after_3hours = now + 3 * 60 * 60;
int wday_after_3hours = DayOfWeek(after_3hours);
now.second = 0;
MetaTrader& mt = GetMetaTrader();
// Skip weekends and first hours of monday
if (wday == 0 || wday == 6 || (wday == 1 && now.hour < 1)) {
LOG("Skipping weekend...");
return true;
}
// Inspect for market closing (weekend and holidays)
else if (wday == 5 && wday_after_3hours == 6) {
WhenInfo("Closing all orders before market break");
for (int i = 0; i < mt.GetSymbolCount(); i++) {
mt.SetSignal(i, 0);
mt.SetSignalFreeze(i, false);
}
mt.SignalOrders(true);
return true;
}
WhenInfo("Updating MetaTrader");
WhenPushTask("Putting latest signals");
// Reset signals
if (realtime_count == 0) {
for (int i = 0; i < mt.GetSymbolCount(); i++)
mt.SetSignal(i, 0);
}
realtime_count++;
try {
mt.Data();
mt.RefreshLimits();
int open_count = 0;
const int MAX_SYMOPEN = 4;
const double FMLEVEL = 0.6;
for (int sym_id = 0; sym_id < GetSymbolCount(); sym_id++) {
int sig = signals[sym_id];
int prev_sig = mt.GetSignal(sym_id);
if (sig == prev_sig && sig != 0)
mt.SetSignalFreeze(sym_id, true);
else {
if ((!prev_sig && sig) || (prev_sig && sig != prev_sig)) {
if (open_count >= MAX_SYMOPEN)
sig = 0;
else
open_count++;
}
mt.SetSignal(sym_id, sig);
mt.SetSignalFreeze(sym_id, false);
}
LOG("Real symbol " << sym_id << " signal " << sig);
}
mt.SetFreeMarginLevel(FMLEVEL);
mt.SetFreeMarginScale(MAX_SYMOPEN);
mt.SignalOrders(true);
}
catch (UserExc e) {
LOG(e);
return false;
}
catch (...) {
return false;
}
WhenRealtimeUpdate();
WhenPopTask();
return true;
}
}
| [
"seppo.pakonen@yandex.com"
] | seppo.pakonen@yandex.com |
0660949b4c216d61dc21b0c38ee7b2e829bb7cfa | a1a0518781ec8bb41acb853850e115005bdc7c8c | /BOJ/11719_그대로 출력하기 2.cpp | e5a4be9ed311dc99db02c1b2fa516bd6f11b2c78 | [] | no_license | JJungs-lee/problem-solving | e71ccbcab58b6c2444a4b343a138a3082ed09c0c | aa61f2311a7a93fbcb87d2356d15188ea729ee7c | refs/heads/master | 2023-09-03T16:48:31.640762 | 2023-08-31T09:05:39 | 2023-08-31T09:05:39 | 106,645,163 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 141 | cpp | #include <iostream>
using namespace std;
int main(){
char str[101];
while(cin.getline(str, 101)){
cout << str << endl;
}
return 0;
} | [
"loveljhs2@gmail.com"
] | loveljhs2@gmail.com |
845708b1c6df58776b9b009fbd438edc9b48082f | 56b94ffc8f4dcb39908399201d38b78f4f8c2376 | /tests/parser/030.cpp | c51fafa069c5ce8a8202ee091331561857aea6ac | [] | no_license | helviett/Tiny_C_Compiler | 99f7a5187eea701bf95f090c2efbb34e6326baf9 | 0968c89884e50386911913b3c6703fe4ce31e10f | refs/heads/master | 2021-09-07T06:58:44.035998 | 2018-02-19T05:53:30 | 2018-02-19T05:53:30 | 106,104,684 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 202 | cpp | int main(void)
{
int a, b, c, d, e, f, g[5];
int max = c > d ? c : d;
5 + 12 * 8 <= 5 | 9 << 3 + 1 > 4 ? (123 ^ 7) - d >> 8 << 7 & 12 + ~1 == 9 <= 5 && f + ++g[5] - 15 : 12;
return 0;
} | [
"keltarhelviett@gmail.com"
] | keltarhelviett@gmail.com |
097a2834319794b216c1d29684b8190038ebd097 | 509aa79f8b1054a37c0eaf5786826b140695980a | /Lab/Lab/src/shortestPath2D/ShortestPath.h | afc1937c98f39e56c52fd98b9c94e100312c62ad | [] | no_license | MariKush/MFCG | e5171c0ec38f5fc86819174fb962dfdc30ed0b09 | a2bc141216c6e630c329f346de6041120a3f3506 | refs/heads/master | 2022-07-31T22:01:50.722977 | 2020-05-19T19:31:03 | 2020-05-19T19:31:03 | 262,397,477 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 443 | h | #ifndef SHORTESTPATH2D_SHORTESTPATH_H
#define SHORTESTPATH2D_SHORTESTPATH_H
#include <vector>
#include "Common.h"
#include "Point.h"
#include "Polygon.h"
#include "Path.h"
#include "Graph.h"
namespace shortestPath2D {
class ShortestPath {
struct SPNode {
real distance;
Point point;
Point parent;
};
public:
static Path find(const Point &start, const Point &destination, const Graph<Point> &visibilityGraph);
};
}
#endif
| [
"43176370+MariKush@users.noreply.github.com"
] | 43176370+MariKush@users.noreply.github.com |
75546bca3da92d9b4f8c736035389a52c583824d | 4fd9f29b20e26b7cc80d748abd8f1dcd94fbbfdd | /File exploration/Ernst Kleiberg/BotanicVis/SoBotanicalBranch.h | 0d5b2bac01551946e7fcd0a15cf16b6192ab54f2 | [] | no_license | Kochise/3dglrtvr | 53208109ca50e53d8380bed0ebdcb7682a2e9438 | dcc2bf847ca26cd6bbd5644190096c27432b542a | refs/heads/master | 2021-12-28T03:24:51.116120 | 2021-08-02T18:55:21 | 2021-08-02T18:55:21 | 77,951,439 | 8 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 9,312 | h | /* ========================================================================
* Copyright (C) 2000 Vienna University of Technology
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* For further information please contact Dieter Schmalstieg under
* <schmalstieg@ims.tuwien.ac.at> or write to Dieter Schmalstieg,
* Vienna University of Technology, Favoritenstr. 9-11/188, A1040 Vienna,
* Austria.
* ========================================================================
* PROJECT: Studierstube
* ======================================================================== */
/* ======================================================================= */
/** Header file for API definitions of SoBotanicalBranch
*
* @author Valerie Maquil
*
* $Header:
* @file */
/* ======================================================================= */
#ifndef SoBotanicalBranch_H
#define SoBotanicalBranch_H
#include "SoBotanicalBase.h"
#include <stbapi/util/ivio.h>
#include <string>
/**
* implements a branch of a botanic tree. Each branch is defined with means of a SoCylinder
* and a SoCone making the connection between this and the previous branch. The bottom radius
* of the SoCone corresponds to the radius of the SoCylinder and its peak is sheared in the
* direction of the branch.
*
* The direction of the branch is definded with 3 rotations. rotBranch defines the rotation
* of THIS branch around the Y-axis, rotBeta defines the rotation of ALL the branches
* of this hierarchy around the Y-axis. rotAlpha defines the rotation or this branch around the
* Z-axis.
CATALOG PARTS
All Parts
<table>
<tr> <td>Part Name</td><td>Part Type</td><td>Default Type</td><td>NULL Default</td></tr>
<tr> <td>geometry </td><td>SoSeparator</td><td>SoSeparator</td><td>YES</td></tr>
<tr> <td>hiddenGeometry </td><td>SoAbortGroup</td><td>SoAbortGroup</td><td>YES</td></tr>
<tr> <td>subbranches </td><td>SoNodeKitListPart</td><td>---</td><td>NO</td></tr>
<tr> <td>rotBranch </td><td>SoRotationXYZ</td><td>SoRotationXYZ</td><td>NO</td></tr>
<tr> <td>ext</td><td>SoSeparator</td><td>SoSeparator</td><td>NO</td></tr>
<tr> <td>shear </td><td>SoMatrixTransform</td><td>SoMatrixTransform</td><td>NO</td></tr>
<tr> <td>transCone </td><td>SoTranslation</td><td>SoTranslation</td><td>NO</td></tr>
<tr> <td>extBranch </td><td>SoCone</td><td>SoCone</td><td>NO</td></tr>
<tr> <td>rotAlpha </td><td>SoRotationXYZ</td><td>SoRotationXYZ</td><td>NO</td></tr>
<tr> <td>transAfter </td><td>SoTranslation</td><td>SoTranslation</td><td>NO</td></tr>
<tr> <td>branch </td><td>SoCylinder</td><td>SoCylinder</td><td>NO</td></tr>
<tr> <td>rotBeta </td><td>SoRotationXYZ</td><td>SoRotationXYZ</td><td>NO</td></tr>
<tr> <td>transBefore </td><td>SoTranslation</td><td>SoTranslation</td><td>NO</td></tr>
<tr> <td>subgeometry </td><td>SoCylinder</td><td>SoCylinder</td><td>NO</td></tr>
</table>
Extra Information for List Parts from Above Table
<table>
<tr> <td>Part Name</td><td>Container Type</td><td>Possible Types</td></tr>
<tr> <td>subbranches</td><td>SoGroup</td><td>SoBotanicalBase</td></tr>
</table>
File Format / defaults:
@verbatim
SoBotanicalBranch {
SoSFFloat direction 0
SoSFFloat alpha 0
SoSFFloat beta 1.62 #golden section
SoSFInt32 strands 0
# from SoBotanicalBase
SoSFInt32 strands 0
SoSFFloat lengthOfBranch 10.0
}
@endverbatim
@ingroup bot
*/
class BOTANIC_VIS_API SoBotanicalBranch : public SoBotanicalBase
{
SO_KIT_HEADER(SoBotanicalBranch);
/**
* children of this branch
*/
SO_KIT_CATALOG_ENTRY_HEADER(subbranches);
/**
* in this part the information is stored that shouldn't be rendered
*/
SO_KIT_CATALOG_ENTRY_HEADER(hiddenGeometry);
/**
* rotation of this branch around the Y-axis, relative to the first branch
* of this hierarchical level
*/
SO_KIT_CATALOG_ENTRY_HEADER(rotBranch);
/**
* translation of the cylinder BEFORE any rotations are performed. This
* translation goes in Y-direction with a value of half of the height of
* the cylinder.
*/
SO_KIT_CATALOG_ENTRY_HEADER(transBefore);
/**
* rotation of this branch around the Z-axis. The angle of rotation depends
* on the number of strands and on the field alpha
*/
SO_KIT_CATALOG_ENTRY_HEADER(rotAlpha);
/**
* rotation of all the branches of this hierarchical level around the Y-axis,
* relative to the branches of the previous hierarchical level
*/
SO_KIT_CATALOG_ENTRY_HEADER(rotBeta);
/**
* translation of the cylinder AFTER all rotations have been performed. This
* translation goes in Y-direction with a value of half of the height of the
* cylinder.
*/
SO_KIT_CATALOG_ENTRY_HEADER(transAfter);
/**
* SoCylinder representing the branch
*/
SO_KIT_CATALOG_ENTRY_HEADER(branch);
/**
* geometry of the cone making the connection between this and the previous branch
*/
SO_KIT_CATALOG_ENTRY_HEADER(ext);
/**
* rotation of the cone around the Y-axis
*/
SO_KIT_CATALOG_ENTRY_HEADER(rotExtBranch);
/**
* the cone itself
*/
SO_KIT_CATALOG_ENTRY_HEADER(extBranch);
/**
* the translation of the cone in Y-direction, to put it at the bottom of the cylinder.
* This translation corresponds to half the height of the cylinder
*/
SO_KIT_CATALOG_ENTRY_HEADER(transCone);
/**
* the shearing of the cone: the peak of the cone is sheared in direction of the rotation
* of the branch
*/
SO_KIT_CATALOG_ENTRY_HEADER(shear);
/**
* pointers of the elements of "subbranches" are stored here to ensure that the above
* transformations will be performed on these children too.
*/
SO_KIT_CATALOG_ENTRY_HEADER(subgeometry);
public:
/**
* inventor class initialization
*/
static void initClass();
/**
* constructor
*/
SoBotanicalBranch();
/**
* rotation angle of THIS branch around the Y-axis. Is chosen such that the branches are
* distributed equally around the previous branch.
*/
SoSFFloat direction;
/**
* this angle constitutes a reference for the rotation of each branch around
* the Z-axis. The angles of rotAlpha are chosen such that their sum equals the angle
* alpha.
*/
SoSFFloat alpha;
/**
* rotation angle of ALL the branches of this level around the Y-axis. Often the angle
* 360/phi is chosen where phi = (1 + sqrt(5)/2) is the golden section.
*/
SoSFFloat beta;
/**
* this field stores the number of strands of the father branch. Is used to calculate rotAlpha
* and the bottom radius of the cone.
*/
SoSFInt32 previousStrand;
/**
* sets the connections of the sensors
*/
virtual SbBool setUpConnections( SbBool onOff, SbBool doItAlways = FALSE );
/**
* sets the scaling value for the radius of this branch
*/
void setThickness(float size) {thickness = size;};
/**
* sets the alpha of this branch
*/
void setAlpha(float angle) {alphaStart = angle;};
/**
* calculates the correct parameters for its subbranches and sets their fields.
*/
int adjustSubbranches();
/**
* if TRUE this branch has as only child a SoBotanicalFruit
*/
bool isFruit;
protected:
/**
* destructor
*/
virtual ~SoBotanicalBranch();
/**
* adapts all parts depending on the length of the branch
*/
virtual void resizeHeightCB();
/**
* adapts all parts depending on the thickness of the branch
*/
virtual void resizeThicknessCB();
/**
* field sensor attached to alpha; calls angleSensorCB
*/
SoFieldSensor alphaSensor;
/**
* field sensor attached to direction; calls angleSensorCB
*/
SoFieldSensor directionSensor;
/**
* adapts rotAlpha, rotBranch and the shearing transformation of the cone
*/
static void angleSensorCB(void *, SoSensor*);
/**
* field sensor attached to previousStrand; calls previousStrandSensorCB
*/
SoFieldSensor previousStrandSensor;
/**
* adapts the bottom radius, the height and the translation of the cone
*/
static void previousStrandSensorCB(void *, SoSensor*);
/**
* thickness of this branch
*/
float thickness;
/**
* rotation angle of rotAlpha
*/
float alphaStart;
};
//----------------------------------------------------------------------------
#endif // SoBotanicalBranch_H | [
"noreply@github.com"
] | Kochise.noreply@github.com |
8cbb720c82303474b24892f2f50098f7e228ee7c | 838bc678fc99413b914fdc69b508f77e6c59b66c | /VGP334/17_HelloSkinnedMesh/WinMian.cpp | 8f825318ceb3c1a0986f261fd31cbde8d08dc6ea | [] | no_license | NeilChongSun/SBEngine | 34a6969b1c59226a096986d267265ff2f4479b05 | a2659bb3c40ae7154dfadaeb8c7b1d5fb71fc366 | refs/heads/master | 2023-05-26T06:52:36.933092 | 2021-06-10T23:47:51 | 2021-06-10T23:47:51 | 376,198,320 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 226 | cpp | #include<SB/Inc/SB.h>
#include"GameState.h"
int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
{
SB::MainApp().AddState<GameState>("GameState");
SB::MainApp().Run({ "Hello Skinned Mesh", 1280, 720 });
return 0;
} | [
"ImportService@microsoft.com"
] | ImportService@microsoft.com |
747e0748264a21b3471120c028e14041c0c8fb1e | d60c368af917b102962ca4f63fb4f906bf488906 | /CS15 Object-Oriented Programming Methods Workplace/Assignment 5/Assignment 5/Trapezoid.cpp | a56bee3410e1fbc4074eb2520b0cc0ac1cf88d55 | [] | no_license | mahdikhaliki/CS-Classes | f36d3092abf17553bbd75cfe21312edfc403deaf | ef52cc430e3dd778e20c6b59dd6261d193bc59cb | refs/heads/master | 2021-01-15T02:02:59.361191 | 2020-12-11T06:43:14 | 2020-12-11T06:43:14 | 242,841,624 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,092 | cpp | #include "Trapezoid.hpp"
using namespace std;
Trapezoid::Trapezoid() {
_a.setAll(4.0, 0.0);
_b.setAll(0.0, 0.0);
_c.setAll(1.0, 5.0);
_d.setAll(3.0, 5.0);
}
double Trapezoid::area() {
return ((_a.Distance(_b) + _c.Distance(_d)) / 2) * (_c.getY() - _b.getY());
}
double Trapezoid::perimeter() {
return Quadrilateral::perimeter();
}
void Trapezoid::validate() {
Quadrilateral::validate();
if (!Equals(_a.Slope(_b), _d.Slope(_c))) {
cout << "The points do not make a trapezoid." << endl;
_a.setAll(4.0, 0.0);
_b.setAll(0.0, 0.0);
_c.setAll(1.0, 5.0);
_d.setAll(3.0, 5.0);
cout << "New points: " << _a << _b << _c << _d << endl;
}
}
void Trapezoid::read(istream &in) {
in >> _a >> _b >> _c >> _d;
validate();
}
void Trapezoid::print(ostream &out) {
cout << "This is a trapezoid." << endl;
Quadrilateral::print(out);
}
istream &operator >>(istream &in, Trapezoid &p) {
p.read(in);
return in;
}
ostream &operator <<(ostream &out, Trapezoid &p) {
p.print(out);
return out;
}
| [
"mahdi.khaliki@sjsu.edu"
] | mahdi.khaliki@sjsu.edu |
0b0ad3df71d876d345786439f20ae167f28ec32f | 1100c43ab96da22bcfd1003c8472fb568b5b4675 | /examples/src/Core/OverrideFinal/XX_OverrideFinal.cpp | e9923f943784abfe0b4159c8ee30be059a5a1dec | [] | no_license | xcysuccess/CPlusPlus11 | ba6d91655a391d739dc5bd17983d92dc715614fe | 991c71a158777856033414d38bcd3aa2a461aa77 | refs/heads/master | 2020-04-06T09:28:11.683155 | 2018-11-19T13:17:38 | 2018-11-19T13:17:38 | 157,343,810 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 997 | cpp | //
// XX_OverrideFinal.cpp
// XXCPlusPlus
//
// Created by tomxiang on 2018/11/16.
// Copyright © 2018年 tomxiang. All rights reserved.
//
// 1.继承的时候会有无意重写父类方法的问题---
// 2.virtual中如果方法一样,参数类型不同可能会被重复调用---
#include "XX_OverrideFinal.hpp"
#include <XXTiles/XXTiles.h>
//第一种情况----accidentally overrides A::func
class A
{
public:
virtual void func();
};
class B: A{};
class F{};
class D: A, F
{
public:
void func();//meant to declare a new function but
};
//第二种情况----
class G
{
public:
virtual void func(double x){
cout << "G: " << x << endl;
};
};
class H: public G
{
public:
void func(double x) override final{
cout << "H: " << x << endl;
};
};
class Q: public H
{
public:
// void func(double x){
// cout << "H: " << x << endl;
// };
};
void testOverrideFinal(){
H *p=new H;
p->func(5.0);
// p->func(5.0); // calls H::f
}
| [
"tomxiang@tencent.com"
] | tomxiang@tencent.com |
052ec59dc5e0d70b055de852a4c0e9d7992144bd | a1bfdad4489b2ef379330ddb7ce41d279406ea30 | /src/7zipAndroid/CPP/7zip/UI/Console/PercentPrinter.cpp | bce0ba7875b286484b93f6e138d80542d54c1648 | [] | no_license | wcrosmun/simple-7zip-wrapper | 996eb4dafd6255904a411e61707d3e86a970edbf | e14b6bda0af6662905788b88274152d209a4e97b | refs/heads/master | 2021-09-07T01:25:33.889372 | 2018-02-15T00:07:46 | 2018-02-15T00:07:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,470 | cpp | // PercentPrinter.cpp
#include "7zStdAfx.h"
#include "../../../Common/IntToString.h"
#include "PercentPrinter.h"
static const unsigned kPercentsSize = 4;
CPercentPrinter::~CPercentPrinter()
{
ClosePrint(false);
}
void CPercentPrinterState::ClearCurState()
{
Completed = 0;
Total = ((UInt64)(Int64)-1);
Files = 0;
Command.Empty();
FileName.Empty();
}
void CPercentPrinter::ClosePrint(bool needFlush)
{
unsigned num = _printedString.Len();
if (num != 0)
{
unsigned i;
/* '\r' in old MAC OS means "new line".
So we can't use '\r' in some systems */
#ifdef _WIN32
char *start = _temp.GetBuf(num + 2);
char *p = start;
*p++ = '\r';
for (i = 0; i < num; i++) *p++ = ' ';
*p++ = '\r';
#else
char *start = _temp.GetBuf(num * 3);
char *p = start;
for (i = 0; i < num; i++) *p++ = '\b';
for (i = 0; i < num; i++) *p++ = ' ';
for (i = 0; i < num; i++) *p++ = '\b';
#endif
*p = 0;
_temp.ReleaseBuf_SetLen((unsigned)(p - start));
*_so << _temp;
}
if (needFlush)
_so->Flush();
_printedString.Empty();
}
void CPercentPrinter::GetPercents()
{
char s[32];
unsigned size;
{
char c = '%';
UInt64 val = 0;
if (Total == (UInt64)(Int64)-1)
{
val = Completed >> 20;
c = 'M';
}
else if (Total != 0)
val = Completed * 100 / Total;
ConvertUInt64ToString(val, s);
size = (unsigned)strlen(s);
s[size++] = c;
s[size] = 0;
}
while (size < kPercentsSize)
{
_s += ' ';
size++;
}
_s += s;
}
void CPercentPrinter::Print()
{
DWORD tick = 0;
if (_tickStep != 0)
tick = GetTickCount();
bool onlyPercentsChanged = false;
if (!_printedString.IsEmpty())
{
if (_tickStep != 0 && (UInt32)(tick - _prevTick) < _tickStep)
return;
CPercentPrinterState &st = *this;
if (_printedState.Command == st.Command
&& _printedState.FileName == st.FileName
&& _printedState.Files == st.Files)
{
if (_printedState.Total == st.Total
&& _printedState.Completed == st.Completed)
return;
onlyPercentsChanged = true;
}
}
_s.Empty();
GetPercents();
if (onlyPercentsChanged && _s == _printedPercents)
return;
_printedPercents = _s;
if (Files != 0)
{
char s[32];
ConvertUInt64ToString(Files, s);
// unsigned size = (unsigned)strlen(s);
// for (; size < 3; size++) _s += ' ';
_s += ' ';
_s += s;
// _s += "f";
}
if (!Command.IsEmpty())
{
_s += ' ';
_s += Command;
}
if (!FileName.IsEmpty() && _s.Len() < MaxLen)
{
_s += ' ';
StdOut_Convert_UString_to_AString(FileName, _temp);
_temp.Replace('\n', ' ');
if (_s.Len() + _temp.Len() > MaxLen)
{
unsigned len = FileName.Len();
for (; len != 0;)
{
unsigned delta = len / 8;
if (delta == 0)
delta = 1;
len -= delta;
_tempU = FileName;
_tempU.Delete(len / 2, FileName.Len() - len);
_tempU.Insert(len / 2, L" . ");
StdOut_Convert_UString_to_AString(_tempU, _temp);
if (_s.Len() + _temp.Len() <= MaxLen)
break;
}
if (len == 0)
_temp.Empty();
}
_s += _temp;
}
if (_printedString != _s)
{
ClosePrint(false);
*_so << _s;
if (NeedFlush)
_so->Flush();
_printedString = _s;
}
_printedState = *this;
if (_tickStep != 0)
_prevTick = tick;
}
| [
"cryptobees@gmail.com"
] | cryptobees@gmail.com |
6c3cb6fc5dcdd297386a5fd11b41e311e41218e0 | cc2cd06b8ed582d8363ca0998d5fd1a77e70cd0c | /MFISH.cpp | a03c2a4e9719623f8ef106bbcd37dde219543e98 | [] | no_license | gittyvarshney/DP | 625aaa73ef984fd557db629bdae30c540baa79da | 12798f3211508f8b030671efed6fce85172a74e2 | refs/heads/master | 2022-12-15T01:26:20.591380 | 2020-09-16T14:57:24 | 2020-09-16T14:57:24 | 285,312,858 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,013 | cpp | #include<bits/stdc++.h>
using namespace std;
//Very nice 1D DP Problem of SPOJ
//In original problem their is a constraint that you have to use all the ships but
//if their is no constraint on ships
//you can replace the //with constraint <--between--> //End of constraint With
/*
map<int, int>::reverse_iterator it;
for (it = an.rbegin(); it != an.rend(); it++)
{
//cout << it->first << " ";
for(i=it->first;i<=it->first+it->second-1;i++)
{
if(m[i]==0)
{
m[i] = it->second;
}
}
}
*/
int n;
vector<int>arr_sum(1000000,0);
vector<int>vec(1000000,-1);
map<int,int>m;
int recurr_dp(int i)
{
if(i<=0)
{
//cout << "returning 0\n";
return 0;
}
if(vec[i]!= -1)
{
//cout << "DP Used\n";
return vec[i];
}
int val_1,val_2;
if(m[i]==0)
{
val_1 = recurr_dp(i-1);
vec[i] = val_1;
//cout << "vec[" << i << "]: " << vec[i] << "\n";
return vec[i];
}
if(i-m[i] < 0)
{
val_1 = 0;
}
else
{
val_1 = (arr_sum[i] - arr_sum[i - m[i]]) + recurr_dp(i-m[i]);
}
val_2 = recurr_dp(i-1);
vec[i] = max(val_1,val_2);
//cout << "vec[" << i << "]: " << vec[i] << "\n";
return vec[i];
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("D:\\Project sunrise\\input.txt", "r", stdin);
freopen("D:\\Project sunrise\\output.txt", "w", stdout);
#endif
ios::sync_with_stdio(0);
cin.tie(NULL);
cout.tie(NULL);
cin >> n;
int sum=0;
int fishes;
int i;
for(i=1;i<n+1;i++)
{
cin >> fishes;
arr_sum[i] = fishes+sum;
sum = arr_sum[i];
}
int ships;
int anchor,length;
cin >> ships;
map<int,int>an;
while(ships--)
{
cin >> anchor >> length;
an[anchor] = length;
}
//With constraint
int last = -645;
for(auto it: an)
{
for(i=it.first;i<=it.first+it.second-1;i++)
{
if(i-it.second>=last)
{
m[i] = it.second;
}
else
{
m[i] = 0;
}
}
last = it.first;
}
//End of constraint
cout << recurr_dp(n) << "\n";
}
| [
"pv66645@gmail.com"
] | pv66645@gmail.com |
990c74fae962413d962825c19a3658d2853fd003 | 70c1d93fd809d767e7a10611a83425234d1f7a77 | /Study/KOI_Book/KOI/9.cc | 2b3ee01200dcd74e1dbbd5faa873053fefe3c77f | [] | no_license | BlinkingStar7/Problem_Solving | 1e52348d3f013ab1849697894d7e30cf540697f8 | 9f115c831ffb70cd3dfedf6fbee782fba4cfc11a | refs/heads/master | 2021-01-21T04:27:40.184818 | 2016-08-26T09:24:40 | 2016-08-26T09:24:40 | 51,363,595 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,096 | cc | #include <stdio.h>
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
vector<int> Prime;
typedef struct Node {int num, height; vector<Node> child;} Node;
queue <Node*> Q;
int C[4] = {1, 3, 7, 9};
void findPrime(int num) {
for (int i=3; i<num; i+=2) {
bool flag = true;
for (int k=0; k<Prime.size(); ++k)
if (i % Prime[k] == 0) {
flag = false;
break;
}
if (flag) Prime.push_back(i);
}
}
bool isPrime(int num) {
if (num == 1) return false;
for (int i=0; i<Prime.size() && Prime[i]*Prime[i] <= num; ++i) {
if (num % Prime[i] == 0)
return false;
}
return true;
}
int main() {
findPrime (100000);
Node* root = new Node();
root->child.push_back((Node) {2, 1});
Q.push(root); Q.push(&root->child[0]);
while (1) {
Node* cur = Q.front(); Q.pop();
cout << cur->num << endl;
if (cur->height > 10) break;
for (int c=0; c<4; ++c) {
int cand = cur->num * 10 + C[c];
if (isPrime(cand)) {
Node* newNode = &(Node) {cand, cur->height};
cur->child.push_back(*newNode);
Q.push(newNode);
}
}
}
return 0;
}
| [
"steadies@naver.com"
] | steadies@naver.com |
927111a3af4e3dd2c7c047d5881697b93de1437e | 62f22ff727b6437362cfdb9d23afb99bed517290 | /libraries/PowerPin/PowerPin.h | d46d073e221c5efa99404b718581f990274d1bd2 | [] | no_license | tezmo/OpenPuzzleBox | 0902c19d7c3f2288b75d03208e044571ddf1d3a6 | a707a0257d7dd13790d1dfc3dc433e7d47ecd3d8 | refs/heads/master | 2016-09-05T10:50:52.258158 | 2015-05-12T17:59:41 | 2015-05-12T17:59:41 | 35,000,074 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 606 | h | /*
PowerPin - Simple Arduino library for powering things, with timeouts.
Juerd Waalboer
*/
#ifndef PowerPin_h
#define PowerPin_h
#include <inttypes.h>
#include <Arduino.h>
class PowerPin {
public:
PowerPin(uint8_t pin, uint8_t off_state = LOW);
void on();
void off();
void on(unsigned int ms);
void off(unsigned int ms);
void toggle();
void check();
private:
void _set(unsigned long end_time, uint8_t state);
uint8_t _pin;
uint8_t _off_state;
unsigned long _end_time;
uint8_t _state;
};
#endif
| [
"jvanderroest@gmail.com"
] | jvanderroest@gmail.com |
05d291af83204389f33026a48248ccfd791e43f0 | 0fc9ad6ba0b4fd5590d7d471fed6881277d192fd | /code/Lulea/Rib.cpp | 5955eec0ec463b7831a46b2f62e122d5df3874b2 | [] | no_license | jijinfanhua/MyBitmap | fda92926a3382c5ba59aefcd7d9742d198cff46b | 6ed7a0731492fdf07c3a9c30b7a6e44f86e41c3c | refs/heads/master | 2020-04-26T13:27:34.950420 | 2019-03-03T14:09:06 | 2019-03-03T14:09:06 | 173,579,913 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,564 | cpp | /*
============================================================================
Name : Lulea.c
Author : Mzaort
Version :
Copyright : Your copyright notice
Description : Hello World in C, Ansi-style
============================================================================
*/
#include "rib.h"
#include "global.h"
static Node root;
void freeNode(Node * node){
if(!node){
freeNode(node->left);
freeNode(node->right);
free(node);
node = 0;
}
}
void freeRoot(){
freeNode(root.left);
freeNode(root.right);
}
int inputRib(RouterEntryRib * rentry, FILE * fp) {
uint u1, u2, u3, u4, u5, u6;
ushort f8 = 0x00ff;
rentry->ipnet = 0;
if ((fscanf(fp, "%d.%d.%d.%d/%d\t%d", &u1, &u2, &u3, &u4, &u5, &u6)) == 6) {
rentry->ipnet = ((u1 & f8) << 24) + ((u2 & f8) << 16)
+ ((u3 & f8) << 8) + ((u4 & f8));
rentry->length = u5 & f8;
rentry->port = u6;
return 1;
}
return 0;
}
int inputUpdateRib(RouterEntryRib * rentry, char * c, FILE *fp) {
uint t1, t2;
char ch;
uint u1, u2, u3, u4, u5, u6 = 0;
ushort f8 = 0x00ff;
rentry->ipnet = 0;
if (fscanf(fp, "%c", &ch) == 1) {
*c = ch;
if (ch == 'A') {
fscanf(fp, "%d.%d.%d.%d/%d\t%d\n", &u1, &u2, &u3, &u4, &u5, &u6);
rentry->port = u6;
} else if (ch == 'W') {
fscanf(fp, "%d.%d.%d.%d/%d\n", &u1, &u2, &u3, &u4, &u5);
}else{
return 1;
}
rentry->ipnet = ((u1 & f8) << 24) + ((u2 & f8) << 16)
+ ((u3 & f8) << 8) + ((u4 & f8));
rentry->length = u5 & f8;
return 1;
}
return 0;
}
void initRoot(){
root.nexthop = DEFAULT;
root.left = 0;
root.right = 0;
}
void withdrawNode(RouterEntryRib rentry){
Node *p;
int i = 0;
uint ip = rentry.ipnet;
p = &root;
int flag = 1;
while(i < rentry.length){
if(ip & 0x80000000){
if(!p->right){
flag = 0;
break;
}
p = p->right;
}else{
if (!p->left) {
flag = 0;
break;
}
p = p->left;
}
ip <<= 1;
i++;
}
if(flag){
p->nexthop = 0;
}
}
void addNode(RouterEntryRib rentry){
Node *p;
int i = 0;
uint ip = rentry.ipnet;
p = &root;
while(i < rentry.length){
if(ip & 0x80000000){
if(!p->right){
p->right = (Node *)calloc(1, sizeof(Node));
}
p = p->right;
}else{
if (!p->left) {
p->left = (Node *) calloc(1, sizeof(Node));
}
p = p->left;
}
ip <<= 1;
i++;
}
p->nexthop = rentry.port;
}
void announceNode(RouterEntryRib rentry){
addNode(rentry);
}
void makeWholeTrie(char * file){
initRoot();
RouterEntryRib rentry;
FILE *fp;
fp = fopen(file, "r");
if (fp == NULL) {
perror("Open file...");
//printf("err no: %d\n", errno);
exit(1);
}
while (inputRib(&rentry, fp)) {
addNode(rentry);
}
fclose(fp);
}
uint lookupNode(uint ip){
Node *p;
p = &root;
uint port = 0;
int i = 0;
while(p){
if(p->nexthop != 0){
port = p->nexthop;
}
if (ip & 0x80000000) {
if (!p->right) {
break;
}
p = p->right;
} else {
if (!p->left) {
break;
}
p = p->left;
}
ip <<= 1;
i++;
}
return port;
}
void modifyWholeTrie(char * file){
RouterEntryRib rentry;
FILE * fp;
char c;
fp = fopen(file, "r");
if (fp == NULL) {
perror("Open file");
//printf("err no: %d\n", errno);
exit(1);
}
int j = 1;
while (inputUpdateRib(&rentry, &c, fp) && j++ <= UPDATEMAX) {
if (c == 'A') {
announceNode(rentry);
} else if (c == 'W') {
withdrawNode(rentry);
}
}
fclose(fp);
}
| [
"noreply@github.com"
] | jijinfanhua.noreply@github.com |
e226e2080c54721f229fa4539455a944904d9488 | 575731c1155e321e7b22d8373ad5876b292b0b2f | /examples/native/ios/Pods/boost-for-react-native/boost/mpl/bitand.hpp | 844cc1a2669f853b0fef30c07dcada5a7f89cf03 | [
"BSL-1.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | Nozbe/zacs | 802a84ffd47413a1687a573edda519156ca317c7 | c3d455426bc7dfb83e09fdf20781c2632a205c04 | refs/heads/master | 2023-06-12T20:53:31.482746 | 2023-06-07T07:06:49 | 2023-06-07T07:06:49 | 201,777,469 | 432 | 10 | MIT | 2023-01-24T13:29:34 | 2019-08-11T14:47:50 | JavaScript | UTF-8 | C++ | false | false | 1,191 | hpp |
#ifndef BOOST_MPL_BITAND_HPP_INCLUDED
#define BOOST_MPL_BITAND_HPP_INCLUDED
// Copyright Aleksey Gurtovoy 2000-2009
// Copyright Jaap Suter 2003
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Id$
// $Date$
// $Revision$
// agurt, 23/jan/10: workaround a conflict with <iso646.h> header's
// macros, see http://tinyurl.com/ycwdxco; 'defined(bitand)'
// has to be checked in a separate condition, otherwise GCC complains
// about 'bitand' being an alternative token
#if defined(_MSC_VER) && !defined(__clang__)
#ifndef __GCCXML__
#if defined(bitand)
# pragma push_macro("bitand")
# undef bitand
# define bitand(x)
#endif
#endif
#endif
#define AUX778076_OP_NAME bitand_
#define AUX778076_OP_PREFIX bitand
#define AUX778076_OP_TOKEN &
#include <boost/mpl/aux_/arithmetic_op.hpp>
#if defined(_MSC_VER) && !defined(__clang__)
#ifndef __GCCXML__
#if defined(bitand)
# pragma pop_macro("bitand")
#endif
#endif
#endif
#endif // BOOST_MPL_BITAND_HPP_INCLUDED
| [
"radexpl@gmail.com"
] | radexpl@gmail.com |
9f534a1748b38c981fa29ef589f2293681312296 | 1f171eacac79739625a0500b0097871d40d61a2d | /test/unit/pdf/PdfMappingTest.cpp | f1164040e2ba01583f7f0d97c640f0ba7d309ff1 | [] | no_license | BillyLiggins/oxsx_old | b41a44bf77da859c342843f61d7a5495452089df | 67c23cf2c616a4a637bdda21e3d94e57cc5007b5 | refs/heads/master | 2021-05-02T16:48:47.383871 | 2017-03-02T01:52:36 | 2017-03-02T01:52:36 | 72,468,919 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,171 | cpp | #include <catch.hpp>
#include <PdfMapping.h>
#include <BinnedPdf.h>
TEST_CASE("Check Initialisation of 3x3 -> 3x3"){
AxisCollection ax;
ax.AddAxis(PdfAxis("axis 1", 2.3, 4.5, 90));
ax.AddAxis(PdfAxis("axis 2", 1.3, 4.7, 11));
PdfMapping map;
REQUIRE(map.GetNBins() == 0);
map.SetAxes(ax);
REQUIRE(map.GetNBins() == 90 * 11);
std::vector<double> initalVals;
for(size_t i = 0; i < map.GetNBins(); i++)
for(size_t j = 0; j < map.GetNBins(); j++)
initalVals.push_back(map.GetComponent(i, j));
// should all be initialised to zero
REQUIRE(initalVals == std::vector<double>((90*11) * (90 * 11), 0));
}
TEST_CASE("Identity Matrix Multiplication on 100 long vector"){
AxisCollection axes;
axes.AddAxis(PdfAxis("", 0, 100, 100));
BinnedPdf binnedPdf(axes);
for(size_t i = 0; i < 100; i++)
binnedPdf.SetBinContent(i, 1.1);
PdfMapping map;
map.SetAxes(axes);
for(size_t i = 0; i < 100; i++)
map.SetComponent(i, i, 1);
BinnedPdf mappedPdf = map(binnedPdf);
REQUIRE(mappedPdf.GetBinContents() == std::vector<double> (100, 1.1));
}
| [
"jack.dunger@physics.ox.ax.uk"
] | jack.dunger@physics.ox.ax.uk |
358240356f030dfdb855874ba5bc2b9a7efd1b07 | d4acab203c402bc5f8f412b47be13c73f2324b31 | /cdcl/Templates/vbl_smart_ptr+cdcl_feature_with_shape+3--.cxx | af476f679de3973a09e44dcbddee9f77a6f7285f | [
"Apache-2.0"
] | permissive | msofka/LRR | 18b69cb0fd2f98844fa47337e660541c65b7f953 | 8c04ab9d27980c98a201943c1fe46e7e451df367 | refs/heads/master | 2021-05-15T05:35:51.686646 | 2018-01-14T02:36:32 | 2018-01-14T02:36:32 | 116,441,547 | 2 | 0 | Apache-2.0 | 2018-01-06T02:43:14 | 2018-01-06T00:50:29 | C++ | UTF-8 | C++ | false | false | 134 | cxx | #include <vbl/vbl_smart_ptr.txx>
#include <cdcl/cdcl_feature_with_shape.h>
VBL_SMART_PTR_INSTANTIATE( cdcl_feature_with_shape<3> );
| [
"msofka@4catalyzer.com"
] | msofka@4catalyzer.com |
3c4664fed709c824c07031ac9e26ac127b4a72ee | 88e6a52c56ce251f01a19736b1ff95649b884cb2 | /p1.cpp | e97e64a02e878a5820138d4f8e4475176138b88d | [] | no_license | MYLNANDHU/mn | 5c12e95a213e08f2b32263ff756cd60db90f0286 | 90899f8a74506e15812a75b17da5459c471907a7 | refs/heads/master | 2021-04-26T14:38:48.381492 | 2018-07-06T14:54:10 | 2018-07-06T14:54:10 | 121,203,676 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 252 | cpp | #include <iostream>
using namespace std;
int main(int argc, char *argv[]){
size_t maxlen = 0, leng;
int i;
int longest;
for (i = 1; i < argc; i++)
{
len = strlen(argv[i]);
if (leng>maxlen)
longest = argv[i];
}
cout<<longest;
return 0;
}
| [
"noreply@github.com"
] | MYLNANDHU.noreply@github.com |
f0f18c51a1711afe3a6bfe37929757e7ef2167d8 | 7c3705990d82f10c9c5a789c9c8442da51f232f5 | /AmbifluxRobotARNL/AmbifluxRobot/Frame.cpp | 88a1bb6a53a2a93aa56b15e52016af6acdb857aa | [] | no_license | onartz/AmbifluxRobot | 7d30b3c6cbd6364bbf4ec7990cbaf45c9510159d | 7a7331bcf3d81997a073d0abcb8c84a508a266ed | refs/heads/master | 2021-01-21T10:09:08.567781 | 2015-05-28T09:15:06 | 2015-05-28T09:15:06 | 41,915,516 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 102 | cpp | #include "Frame.h"
Frame::Frame(){}
Frame::Frame(char** msg, int nbArgs):msg( msg, msg + nbArgs )
{} | [
"olivier.nartz@univ-lorraine.fr"
] | olivier.nartz@univ-lorraine.fr |
386fc1cd7d378e4d6d18d62752528d972416fd82 | 9ec67e83200f643f9f55ed90e0b2cae4581ebcb6 | /CppParserLib/PPTokenList.h | 26cf01369c79b1d9f102b0f10cd2339843d503c2 | [] | no_license | andrewpaterson/Codaphela.Library | 465770eaf2839589fc305660725abb38033f8aa2 | 2a4722ba0a4b98a304a297a9d74c9b6811fa4ac5 | refs/heads/master | 2023-05-25T13:01:45.587888 | 2023-05-14T11:46:36 | 2023-05-14T11:46:36 | 3,248,841 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,521 | h | /** ---------------- COPYRIGHT NOTICE, DISCLAIMER, and LICENSE ------------- **
Copyright (c) 2022 Andrew Paterson
This file is part of The Codaphela Project: Codaphela CppParserLib
Codaphela CppParserLib is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Codaphela CppParserLib is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Codaphela CppParserLib. If not, see <http://www.gnu.org/licenses/>.
** ------------------------------------------------------------------------ **/
#ifndef __P_P_TOKEN_LIST_H__
#define __P_P_TOKEN_LIST_H__
#include "BaseLib/Chars.h"
#include "PPToken.h"
class CPPTokenList
{
protected:
CArrayPPTokenPtrs mcArray;
public:
void Init(void);
void Kill(void);
char* Print(CChars* psz, bool bShowFileAndLine = false);
void Add(CPPToken* ppcToken);
bool Equals(CPPTokenList* pcOther);
void SavageAppend(CChars* psz, int iDepth);
int NumTokens(void);
CPPToken* Get(int iTokenIndex);
void Dump(void);
};
typedef CArrayTemplate<CPPTokenList> CArrayPPTokenLists;
#endif // !__P_P_TOKEN_LIST_H__
| [
"andrew.ian.paterson@gmail.com"
] | andrew.ian.paterson@gmail.com |
bb6175870dea2b7f11c56317950356e40c570b47 | ff123a817c5b831005b8208f0ba635f631cd8ee4 | /Chapter 6/Code/6.45.cpp | 4fb66086abc0e523873037bcce690d59c764babf | [
"MIT"
] | permissive | VKorpela/EIC0691-Homework | c7699bd406513f4f0a402adb6ce4a117ddc603fd | d1080a212ec526551a9ac7cba61864e5ef2e1575 | refs/heads/main | 2023-04-18T13:38:56.978162 | 2021-05-05T01:37:49 | 2021-05-05T01:37:49 | 357,939,530 | 1 | 0 | MIT | 2021-04-28T01:52:41 | 2021-04-14T14:44:51 | C++ | UTF-8 | C++ | false | false | 1,372 | cpp | #include <iostream>
#include <cstdlib>
#include <cstdio>
#include <algorithm>
#include <queue>
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
typedef int Status;
using namespace std;
typedef struct TNode {
int tag;
TNode *LC, *RC;
} *BiTree;
BiTree treeBuild() {
int id;
scanf("%d", &id);
if (id == 0) return NULL;
BiTree p = (BiTree) malloc(sizeof(TNode));
p->tag = id;
p->LC = treeBuild();
p->RC = treeBuild();
return p;
}
Status treePrint(BiTree T) {
if (T == NULL) {
printf("^ ");
return OK;
}
printf("%d ", T->tag);
treePrint(T->LC);
treePrint(T->RC);
return OK;
}
Status treeNodeDelete(BiTree T) {
if (T->LC != NULL) treeNodeDelete(T->LC);
if (T->RC != NULL) treeNodeDelete(T->RC);
free(T);
return OK;
}
bool treeDelete(BiTree T, int x) {
if (T->tag == x) {
treeNodeDelete(T);
return true;
}
if (T->LC != NULL && treeDelete(T->LC, x)) T->LC = NULL;
if (T->RC != NULL && treeDelete(T->RC, x)) T->RC = NULL;
return false;
}
int main() {
int x;
BiTree T = NULL;
printf("Describe the binary tree: \n");
T = treeBuild();
printf("Input x: \n");
scanf("%d", &x);
if (treeDelete(T, x)) T = NULL;
printf("Result: \n");
treePrint(T);
printf("\n");
return 0;
}
| [
"noreply@github.com"
] | VKorpela.noreply@github.com |
6508690ec1d94a20d85d58f51ac918b4b2aefe18 | 5bee3ec75e44bfc15fc181bb51248e81e6d5e83c | /Currentsensor.h | a45c374fd7af20b41d6220ec8368e062052d03a0 | [] | no_license | Luumo/microgrid-iot-platform | ad9f568d19458bbe0d1726d527200cb23f3611ce | fc727b1ef5d5af53d8e2c94c98285f9eed43b32b | refs/heads/master | 2023-02-21T17:54:11.118478 | 2020-07-03T22:30:15 | 2020-07-03T22:30:15 | 224,829,758 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 648 | h | #ifndef CURRENTSENSOR_H
#define CURRENTSENSOR_H
class CurrentSensor{
public:
CurrentSensor(int pin, float sensitivity);
float readCurrent(); // returns Ampere
float currentValue = 0.000;
private:
int m_pin;
float m_sensitivity; //66mV/A for 30A sensor, 100mV/A for 20A sensor
float m_offsetVoltage = 2500.0; // VIOT 2.5V when no load on ammeter
float m_adcValue = 0.0;
float m_adcVoltage = 0.0;
void calcAdcVoltage(); // helper-function, converts to mV
void getAdcValue(int m_pin); // helper-function, to get raw input value
};
#endif // CURRENTSENSOR_H
| [
"34240620+Luumo@users.noreply.github.com"
] | 34240620+Luumo@users.noreply.github.com |
66445abbba295b65d82cfe21ef535dd423fdc7c4 | e104892af303d85c5e661d099b500dc1e35b882d | /Sample12_4/app/src/main/cpp/bndev/MyVulkanManager.cpp | 08bf6e60198a5bdbb2fe66627cb03c2966f6ae67 | [
"Unlicense"
] | permissive | siwangqishiq/Vulkan_Develpment_Samples | 624900dabaca75c9ad21ef5a1ee5af6709dcc9a8 | 409c973e0b37086c854cde07b1e620c3d8d9f15d | refs/heads/master | 2023-08-16T04:13:54.777841 | 2021-10-14T06:53:11 | 2021-10-14T06:53:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 30,672 | cpp | #include <vulkan/vulkan.h>
#include "MatrixState3D.h"
#include "MyVulkanManager.h"
#include "../util/FileUtil.h"
#include "../util/TextureManager.h"
#include "../util/HelpFunction.h"
#include <thread>
#include <iostream>
#include <assert.h>
#include <chrono>
#include "ThreadTask.h"
#include "../util/FPSUtil.h"
#include "FlatData.h"
#include <sys/time.h>
android_app* MyVulkanManager::Android_application;
bool MyVulkanManager::loopDrawFlag=true;
std::vector<const char *> MyVulkanManager::instanceExtensionNames;
VkInstance MyVulkanManager::instance;
uint32_t MyVulkanManager::gpuCount;
std::vector<VkPhysicalDevice> MyVulkanManager::gpus;
uint32_t MyVulkanManager::queueFamilyCount;
std::vector<VkQueueFamilyProperties> MyVulkanManager::queueFamilyprops;
uint32_t MyVulkanManager::queueGraphicsFamilyIndex;
VkQueue MyVulkanManager::queueGraphics;
uint32_t MyVulkanManager::queuePresentFamilyIndex;
std::vector<const char *> MyVulkanManager::deviceExtensionNames;
VkDevice MyVulkanManager::device;
VkCommandPool MyVulkanManager::cmdPool;
VkCommandBuffer MyVulkanManager::cmdBuffer;
VkCommandBufferBeginInfo MyVulkanManager::cmd_buf_info;
VkCommandBuffer MyVulkanManager::cmd_bufs[1];
VkSubmitInfo MyVulkanManager::submit_info[1];
uint32_t MyVulkanManager::screenWidth;
uint32_t MyVulkanManager::screenHeight;
VkSurfaceKHR MyVulkanManager::surface;
std::vector<VkFormat> MyVulkanManager::formats;
VkSurfaceCapabilitiesKHR MyVulkanManager::surfCapabilities;
uint32_t MyVulkanManager::presentModeCount;
std::vector<VkPresentModeKHR> MyVulkanManager::presentModes;
VkExtent2D MyVulkanManager::swapchainExtent;
VkSwapchainKHR MyVulkanManager::swapChain;
uint32_t MyVulkanManager::swapchainImageCount;
std::vector<VkImage> MyVulkanManager::swapchainImages;
std::vector<VkImageView> MyVulkanManager::swapchainImageViews;
VkFormat MyVulkanManager::depthFormat;
VkFormatProperties MyVulkanManager::depthFormatProps;
VkImage MyVulkanManager::depthImage;
VkPhysicalDeviceMemoryProperties MyVulkanManager::memoryroperties;
VkDeviceMemory MyVulkanManager::memDepth;
VkImageView MyVulkanManager::depthImageView;
VkSemaphore MyVulkanManager::imageAcquiredSemaphore;
uint32_t MyVulkanManager::currentBuffer;
VkRenderPass MyVulkanManager::renderPass;
VkClearValue MyVulkanManager::clear_values[2];
VkRenderPassBeginInfo MyVulkanManager::rp_begin;
VkFence MyVulkanManager::taskFinishFence;
VkPresentInfoKHR MyVulkanManager::present;
VkFramebuffer* MyVulkanManager::framebuffers;
ShaderQueueSuit_CommonTex* MyVulkanManager::sqsCT;
ShaderQueueSuit_CommonTexImage* MyVulkanManager::sqsImage;
TexDrawableObject* MyVulkanManager::texTri;
float MyVulkanManager::yAngle=0;
float MyVulkanManager::zAngle=0;
void MyVulkanManager::init_vulkan_instance()
{
AAssetManager* aam=MyVulkanManager::Android_application->activity->assetManager;
FileUtil::setAAssetManager(aam);
if (!vk::loadVulkan())
{
LOGI("加载Vulkan API失败!");
return ;
}
instanceExtensionNames.push_back(VK_KHR_SURFACE_EXTENSION_NAME);
instanceExtensionNames.push_back(VK_KHR_ANDROID_SURFACE_EXTENSION_NAME);
VkApplicationInfo app_info = {};
app_info.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
app_info.pNext = NULL;
app_info.pApplicationName = "HelloVulkan";
app_info.applicationVersion = 1;
app_info.pEngineName = "HelloVulkan";
app_info.engineVersion = 1;
app_info.apiVersion = VK_API_VERSION_1_0;
VkInstanceCreateInfo inst_info = {};
inst_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
inst_info.pNext = NULL;
inst_info.flags = 0;
inst_info.pApplicationInfo = &app_info;
inst_info.enabledExtensionCount = instanceExtensionNames.size();
inst_info.ppEnabledExtensionNames = instanceExtensionNames.data();;
inst_info.enabledLayerCount = 0;
inst_info.ppEnabledLayerNames = NULL;
VkResult result;
result = vk::vkCreateInstance(&inst_info, NULL, &instance);
if(result== VK_SUCCESS)
{
LOGE("Vulkan实例创建成功!");
}
else
{
LOGE("Vulkan实例创建失败!");
}
}
void MyVulkanManager::destroy_vulkan_instance()
{
vk::vkDestroyInstance(instance, NULL);
LOGE("Vulkan实例销毁完毕!");
}
void MyVulkanManager::enumerate_vulkan_phy_devices()
{
gpuCount=0;
VkResult result = vk::vkEnumeratePhysicalDevices(instance, &gpuCount, NULL);
assert(result==VK_SUCCESS);
LOGE("[Vulkan硬件设备数量为%d个]",gpuCount);
gpus.resize(gpuCount);
result = vk::vkEnumeratePhysicalDevices(instance, &gpuCount, gpus.data());
assert(result==VK_SUCCESS);
vk::vkGetPhysicalDeviceMemoryProperties(gpus[0],&memoryroperties);
}
void MyVulkanManager::create_vulkan_devices()
{
vk::vkGetPhysicalDeviceQueueFamilyProperties(gpus[0], &queueFamilyCount, NULL);
LOGE("[Vulkan硬件设备0支持的队列家族数量为%d]",queueFamilyCount);
queueFamilyprops.resize(queueFamilyCount);
vk::vkGetPhysicalDeviceQueueFamilyProperties(gpus[0], &queueFamilyCount, queueFamilyprops.data());
LOGE("[成功获取Vulkan硬件设备0支持的队列家族属性列表]");
VkDeviceQueueCreateInfo queueInfo = {};
bool found = false;
for (unsigned int i = 0; i < queueFamilyCount; i++)
{
if (queueFamilyprops[i].queueFlags & VK_QUEUE_GRAPHICS_BIT)
{
queueInfo.queueFamilyIndex = i;
queueGraphicsFamilyIndex=i;
LOGE("[支持GRAPHICS工作的一个队列家族的索引为%d]",i);
LOGE("[此家族中的实际队列数量是%d]",queueFamilyprops[i].queueCount);
found = true;
break;
}
}
float queue_priorities[1] = {0.0};
queueInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
queueInfo.pNext = NULL;
queueInfo.queueCount = 1;
queueInfo.pQueuePriorities = queue_priorities;
queueInfo.queueFamilyIndex = queueGraphicsFamilyIndex;
deviceExtensionNames.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME);
VkPhysicalDeviceFeatures pdf;
vk::vkGetPhysicalDeviceFeatures(gpus[0],&pdf);
VkDeviceCreateInfo deviceInfo = {};
deviceInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
deviceInfo.pNext = NULL;
deviceInfo.queueCreateInfoCount = 1;
deviceInfo.pQueueCreateInfos = &queueInfo;
deviceInfo.enabledExtensionCount = deviceExtensionNames.size();
deviceInfo.ppEnabledExtensionNames = deviceExtensionNames.data();
deviceInfo.enabledLayerCount = 0;
deviceInfo.ppEnabledLayerNames = NULL;
deviceInfo.pEnabledFeatures = &pdf;
VkResult result = vk::vkCreateDevice(gpus[0], &deviceInfo, NULL, &device);
assert(result==VK_SUCCESS);
}
void MyVulkanManager::destroy_vulkan_devices()
{
vk::vkDestroyDevice(device, NULL);
LOGE("逻辑设备销毁完毕!");
}
void MyVulkanManager::create_vulkan_CommandBuffer()
{
VkCommandPoolCreateInfo cmd_pool_info = {};
cmd_pool_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
cmd_pool_info.pNext = NULL;
cmd_pool_info.queueFamilyIndex = queueGraphicsFamilyIndex;
cmd_pool_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
VkResult result = vk::vkCreateCommandPool(device, &cmd_pool_info, NULL, &cmdPool);
assert(result==VK_SUCCESS);
VkCommandBufferAllocateInfo cmdBAI = {};
cmdBAI.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
cmdBAI.pNext = NULL;
cmdBAI.commandPool = cmdPool;
cmdBAI.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
cmdBAI.commandBufferCount = 1;
result = vk::vkAllocateCommandBuffers(device, &cmdBAI, &cmdBuffer);
assert(result==VK_SUCCESS);
cmd_buf_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
cmd_buf_info.pNext = NULL;
cmd_buf_info.flags = 0;
cmd_buf_info.pInheritanceInfo = NULL;
cmd_bufs[0] = cmdBuffer;
VkPipelineStageFlags* pipe_stage_flags = new VkPipelineStageFlags();
*pipe_stage_flags=VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
submit_info[0].pNext = NULL;
submit_info[0].sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info[0].pWaitDstStageMask = pipe_stage_flags;
submit_info[0].commandBufferCount = 1;
submit_info[0].pCommandBuffers = cmd_bufs;
submit_info[0].signalSemaphoreCount = 0;
submit_info[0].pSignalSemaphores = NULL;
}
void MyVulkanManager::destroy_vulkan_CommandBuffer()
{
VkCommandBuffer cmdBufferArray[1] = {cmdBuffer};
vk::vkFreeCommandBuffers
(
device,
cmdPool,
1,
cmdBufferArray
);
vk::vkDestroyCommandPool(device, cmdPool, NULL);
}
void MyVulkanManager::create_vulkan_swapChain()
{
screenWidth = ANativeWindow_getWidth(Android_application->window);
screenHeight = ANativeWindow_getHeight(Android_application->window);
LOGE("窗体宽度%d 窗体高度%d",screenWidth,screenHeight);
VkAndroidSurfaceCreateInfoKHR createInfo;
createInfo.sType = VK_STRUCTURE_TYPE_ANDROID_SURFACE_CREATE_INFO_KHR;
createInfo.pNext = nullptr;
createInfo.flags = 0;
createInfo.window = Android_application->window;
PFN_vkCreateAndroidSurfaceKHR fpCreateAndroidSurfaceKHR=(PFN_vkCreateAndroidSurfaceKHR)vk::vkGetInstanceProcAddr(instance, "vkCreateAndroidSurfaceKHR");
if (fpCreateAndroidSurfaceKHR == NULL)
{
LOGE( "找不到vkvkCreateAndroidSurfaceKHR扩展函数!" );
}
VkResult result = fpCreateAndroidSurfaceKHR(instance, &createInfo, nullptr, &surface);
assert(result==VK_SUCCESS);
VkBool32 *pSupportsPresent = (VkBool32 *)malloc(queueFamilyCount * sizeof(VkBool32));
for (uint32_t i = 0; i < queueFamilyCount; i++)
{
vk::vkGetPhysicalDeviceSurfaceSupportKHR(gpus[0], i, surface, &pSupportsPresent[i]);
LOGE("队列家族索引=%d %s显示",i,(pSupportsPresent[i]==1?"支持":"不支持"));
}
queueGraphicsFamilyIndex = UINT32_MAX;
queuePresentFamilyIndex = UINT32_MAX;
for (uint32_t i = 0; i <queueFamilyCount; ++i)
{
if ((queueFamilyprops[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) != 0)
{
if (queueGraphicsFamilyIndex== UINT32_MAX) queueGraphicsFamilyIndex = i;
if (pSupportsPresent[i] == VK_TRUE)
{
queueGraphicsFamilyIndex = i;
queuePresentFamilyIndex = i;
LOGE("队列家族索引=%d 同时支持Graphis(图形)和Present(显示)工作",i);
break;
}
}
}
if (queuePresentFamilyIndex == UINT32_MAX)
{
for (size_t i = 0; i < queueFamilyCount; ++i)
{
if (pSupportsPresent[i] == VK_TRUE)
{
queuePresentFamilyIndex= i;
break;
}
}
}
free(pSupportsPresent);
if (queueGraphicsFamilyIndex == UINT32_MAX || queuePresentFamilyIndex == UINT32_MAX)
{
LOGE("没有找到支持Graphis(图形)或Present(显示)工作的队列家族");
assert(false);
}
uint32_t formatCount;
result = vk::vkGetPhysicalDeviceSurfaceFormatsKHR(gpus[0], surface, &formatCount, NULL);
LOGE("支持的格式数量为 %d",formatCount);
VkSurfaceFormatKHR *surfFormats = (VkSurfaceFormatKHR *)malloc(formatCount * sizeof(VkSurfaceFormatKHR));
formats.resize(formatCount);
result = vk::vkGetPhysicalDeviceSurfaceFormatsKHR(gpus[0], surface, &formatCount, surfFormats);
for(int i=0;i<formatCount;i++)
{
formats[i]=surfFormats[i].format;
LOGE("[%d]支持的格式为%d",i,formats[i]);
}
if (formatCount == 1 && surfFormats[0].format == VK_FORMAT_UNDEFINED)
{
formats[0] = VK_FORMAT_B8G8R8A8_UNORM;
}
free(surfFormats);
result = vk::vkGetPhysicalDeviceSurfaceCapabilitiesKHR(gpus[0], surface, &surfCapabilities);
assert(result == VK_SUCCESS);
result = vk::vkGetPhysicalDeviceSurfacePresentModesKHR(gpus[0], surface, &presentModeCount, NULL);
assert(result == VK_SUCCESS);
LOGE("显示模式数量为%d",presentModeCount);
presentModes.resize(presentModeCount);
result = vk::vkGetPhysicalDeviceSurfacePresentModesKHR(gpus[0], surface, &presentModeCount, presentModes.data());
for(int i=0;i<presentModeCount;i++)
{
LOGE("显示模式[%d]编号为%d",i,presentModes[i]);
}
VkPresentModeKHR swapchainPresentMode = VK_PRESENT_MODE_FIFO_KHR;
for (size_t i = 0; i < presentModeCount; i++)
{
if (presentModes[i] == VK_PRESENT_MODE_MAILBOX_KHR)
{
swapchainPresentMode = VK_PRESENT_MODE_MAILBOX_KHR;
break;
}
if ((swapchainPresentMode != VK_PRESENT_MODE_MAILBOX_KHR)&&(presentModes[i] == VK_PRESENT_MODE_IMMEDIATE_KHR))
{
swapchainPresentMode = VK_PRESENT_MODE_IMMEDIATE_KHR;
}
}
if (surfCapabilities.currentExtent.width == 0xFFFFFFFF)
{
swapchainExtent.width = screenWidth;
swapchainExtent.height = screenHeight;
if (swapchainExtent.width < surfCapabilities.minImageExtent.width)
{
swapchainExtent.width = surfCapabilities.minImageExtent.width;
}
else if (swapchainExtent.width > surfCapabilities.maxImageExtent.width)
{
swapchainExtent.width = surfCapabilities.maxImageExtent.width;
}
if (swapchainExtent.height < surfCapabilities.minImageExtent.height)
{
swapchainExtent.height = surfCapabilities.minImageExtent.height;
} else if (swapchainExtent.height > surfCapabilities.maxImageExtent.height)
{
swapchainExtent.height = surfCapabilities.maxImageExtent.height;
}
LOGE("使用自己设置的 宽度 %d 高度 %d",swapchainExtent.width,swapchainExtent.height);
}
else
{
swapchainExtent = surfCapabilities.currentExtent;
LOGE("使用获取的surface能力中的 宽度 %d 高度 %d",swapchainExtent.width,swapchainExtent.height);
}
screenWidth=swapchainExtent.width;
screenHeight=swapchainExtent.height;
uint32_t desiredMinNumberOfSwapChainImages = surfCapabilities.minImageCount+1;
if ((surfCapabilities.maxImageCount > 0) &&(desiredMinNumberOfSwapChainImages > surfCapabilities.maxImageCount))
{
desiredMinNumberOfSwapChainImages = surfCapabilities.maxImageCount;
}
VkSurfaceTransformFlagBitsKHR preTransform;
if (surfCapabilities.supportedTransforms & VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR)
{
preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
}
else
{
preTransform = surfCapabilities.currentTransform;
}
VkSwapchainCreateInfoKHR swapchain_ci = {};
swapchain_ci.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
swapchain_ci.pNext = NULL;
swapchain_ci.surface = surface;
swapchain_ci.minImageCount = desiredMinNumberOfSwapChainImages;
swapchain_ci.imageFormat = formats[0];
swapchain_ci.imageExtent.width = swapchainExtent.width;
swapchain_ci.imageExtent.height = swapchainExtent.height;
swapchain_ci.preTransform = preTransform;
swapchain_ci.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
swapchain_ci.imageArrayLayers = 1;
swapchain_ci.presentMode = swapchainPresentMode;
swapchain_ci.oldSwapchain = VK_NULL_HANDLE;
swapchain_ci.clipped = true;
swapchain_ci.imageColorSpace = VK_COLORSPACE_SRGB_NONLINEAR_KHR;
swapchain_ci.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
swapchain_ci.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
swapchain_ci.queueFamilyIndexCount = 0;
swapchain_ci.pQueueFamilyIndices = NULL;
if (queueGraphicsFamilyIndex != queuePresentFamilyIndex)
{
swapchain_ci.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
swapchain_ci.queueFamilyIndexCount = 2;
uint32_t queueFamilyIndices[2] = {queueGraphicsFamilyIndex,queuePresentFamilyIndex};
swapchain_ci.pQueueFamilyIndices = queueFamilyIndices;
}
result = vk::vkCreateSwapchainKHR(device, &swapchain_ci, NULL, &swapChain);
assert(result == VK_SUCCESS);
result = vk::vkGetSwapchainImagesKHR(device, swapChain, &swapchainImageCount, NULL);
assert(result == VK_SUCCESS);
LOGE("[SwapChain中的Image数量为%d]",swapchainImageCount);
swapchainImages.resize(swapchainImageCount);
result = vk::vkGetSwapchainImagesKHR(device, swapChain, &swapchainImageCount, swapchainImages.data());
assert(result == VK_SUCCESS);
swapchainImageViews.resize(swapchainImageCount);
for (uint32_t i = 0; i < swapchainImageCount; i++)
{
VkImageViewCreateInfo color_image_view = {};
color_image_view.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
color_image_view.pNext = NULL;
color_image_view.flags = 0;
color_image_view.image = swapchainImages[i];
color_image_view.viewType = VK_IMAGE_VIEW_TYPE_2D;
color_image_view.format = formats[0];
color_image_view.components.r = VK_COMPONENT_SWIZZLE_R;
color_image_view.components.g = VK_COMPONENT_SWIZZLE_G;
color_image_view.components.b = VK_COMPONENT_SWIZZLE_B;
color_image_view.components.a = VK_COMPONENT_SWIZZLE_A;
color_image_view.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
color_image_view.subresourceRange.baseMipLevel = 0;
color_image_view.subresourceRange.levelCount = 1;
color_image_view.subresourceRange.baseArrayLayer = 0;
color_image_view.subresourceRange.layerCount = 1;
result = vk::vkCreateImageView(device, &color_image_view, NULL, &swapchainImageViews[i]);
assert(result == VK_SUCCESS);
}
}
void MyVulkanManager::destroy_vulkan_swapChain()
{
for (uint32_t i = 0; i < swapchainImageCount; i++)
{
vk::vkDestroyImageView(device, swapchainImageViews[i], NULL);
LOGE("[销毁SwapChain ImageView %d 成功]",i);
}
vk::vkDestroySwapchainKHR(device, swapChain, NULL);
LOGE("销毁SwapChain成功!");
}
void MyVulkanManager::create_vulkan_DepthBuffer()
{
depthFormat = VK_FORMAT_D16_UNORM;
VkImageCreateInfo image_info = {};
vk::vkGetPhysicalDeviceFormatProperties(gpus[0], depthFormat, &depthFormatProps);
if (depthFormatProps.linearTilingFeatures & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT)
{
image_info.tiling = VK_IMAGE_TILING_LINEAR;
LOGE("tiling为VK_IMAGE_TILING_LINEAR!");
}
else if (depthFormatProps.optimalTilingFeatures & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT)
{
image_info.tiling = VK_IMAGE_TILING_OPTIMAL;
LOGE("tiling为VK_IMAGE_TILING_OPTIMAL!");
}
else
{
LOGE("不支持VK_FORMAT_D16_UNORM!");
}
image_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
image_info.pNext = NULL;
image_info.imageType = VK_IMAGE_TYPE_2D;
image_info.format = depthFormat;
image_info.extent.width = screenWidth;
image_info.extent.height =screenHeight;
image_info.extent.depth = 1;
image_info.mipLevels = 1;
image_info.arrayLayers = 1;
image_info.samples = VK_SAMPLE_COUNT_1_BIT;
image_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
image_info.usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
image_info.queueFamilyIndexCount = 0;
image_info.pQueueFamilyIndices = NULL;
image_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
image_info.flags = 0;
VkMemoryAllocateInfo mem_alloc = {};
mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
mem_alloc.pNext = NULL;
mem_alloc.allocationSize = 0;
mem_alloc.memoryTypeIndex = 0;
VkImageViewCreateInfo view_info = {};
view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
view_info.pNext = NULL;
view_info.image = VK_NULL_HANDLE;
view_info.format = depthFormat;
view_info.components.r = VK_COMPONENT_SWIZZLE_R;
view_info.components.g = VK_COMPONENT_SWIZZLE_G;
view_info.components.b = VK_COMPONENT_SWIZZLE_B;
view_info.components.a = VK_COMPONENT_SWIZZLE_A;
view_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
view_info.subresourceRange.baseMipLevel = 0;
view_info.subresourceRange.levelCount = 1;
view_info.subresourceRange.baseArrayLayer = 0;
view_info.subresourceRange.layerCount = 1;
view_info.viewType = VK_IMAGE_VIEW_TYPE_2D;
view_info.flags = 0;
VkResult result = vk::vkCreateImage(device, &image_info, NULL, &depthImage);
assert(result == VK_SUCCESS);
VkMemoryRequirements mem_reqs;
vk::vkGetImageMemoryRequirements(device, depthImage, &mem_reqs);
mem_alloc.allocationSize = mem_reqs.size;
VkFlags requirements_mask=0;
bool flag=memoryTypeFromProperties(memoryroperties, mem_reqs.memoryTypeBits,requirements_mask,&mem_alloc.memoryTypeIndex);
assert(flag);
LOGE("确定内存类型成功 类型索引为%d",mem_alloc.memoryTypeIndex);
result = vk::vkAllocateMemory(device, &mem_alloc, NULL, &memDepth);
assert(result == VK_SUCCESS);
result = vk::vkBindImageMemory(device, depthImage, memDepth, 0);
assert(result == VK_SUCCESS);
view_info.image = depthImage;
result = vk::vkCreateImageView(device, &view_info, NULL, &depthImageView);
assert(result == VK_SUCCESS);
}
void MyVulkanManager::destroy_vulkan_DepthBuffer()
{
vk::vkDestroyImageView(device, depthImageView, NULL);
vk::vkDestroyImage(device, depthImage, NULL);
vk::vkFreeMemory(device, memDepth, NULL);
LOGE("销毁深度缓冲相关成功!");
}
void MyVulkanManager::create_render_pass()
{
VkSemaphoreCreateInfo imageAcquiredSemaphoreCreateInfo;
imageAcquiredSemaphoreCreateInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
imageAcquiredSemaphoreCreateInfo.pNext = NULL;
imageAcquiredSemaphoreCreateInfo.flags = 0;
VkResult result = vk::vkCreateSemaphore(device, &imageAcquiredSemaphoreCreateInfo, NULL, &imageAcquiredSemaphore);
assert(result == VK_SUCCESS);
VkAttachmentDescription attachments[2];
attachments[0].format = formats[0];
attachments[0].samples = VK_SAMPLE_COUNT_1_BIT;
attachments[0].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
attachments[0].storeOp = VK_ATTACHMENT_STORE_OP_STORE;
attachments[0].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
attachments[0].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
attachments[0].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
attachments[0].finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
attachments[0].flags = 0;
attachments[1].format = depthFormat;
attachments[1].samples = VK_SAMPLE_COUNT_1_BIT;
attachments[1].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
attachments[1].storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
attachments[1].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
attachments[1].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
attachments[1].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
attachments[1].finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
attachments[1].flags = 0;
VkAttachmentReference color_reference = {};
color_reference.attachment = 0;
color_reference.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
VkAttachmentReference depth_reference = {};
depth_reference.attachment = 1;
depth_reference.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
VkSubpassDescription subpass = {};
subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpass.flags = 0;
subpass.inputAttachmentCount = 0;
subpass.pInputAttachments = NULL;
subpass.colorAttachmentCount = 1;
subpass.pColorAttachments = &color_reference;
subpass.pResolveAttachments = NULL;
subpass.pDepthStencilAttachment = &depth_reference;
subpass.preserveAttachmentCount = 0;
subpass.pPreserveAttachments = NULL;
VkRenderPassCreateInfo rp_info = {};
rp_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
rp_info.pNext = NULL;
rp_info.attachmentCount = 2;
rp_info.pAttachments = attachments;
rp_info.subpassCount = 1;
rp_info.pSubpasses = &subpass;
rp_info.dependencyCount = 0;
rp_info.pDependencies = NULL;
result = vk::vkCreateRenderPass(device, &rp_info, NULL, &renderPass);
assert(result == VK_SUCCESS);
clear_values[0].color.float32[0] = 0.0f;
clear_values[0].color.float32[1] = 0.0f;
clear_values[0].color.float32[2] = 0.0f;
clear_values[0].color.float32[3] = 0.0f;
clear_values[1].depthStencil.depth = 1.0f;
clear_values[1].depthStencil.stencil = 0;
rp_begin.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
rp_begin.pNext = NULL;
rp_begin.renderPass = renderPass;
rp_begin.renderArea.offset.x = 0;
rp_begin.renderArea.offset.y = 0;
rp_begin.renderArea.extent.width = screenWidth;
rp_begin.renderArea.extent.height = screenHeight;
rp_begin.clearValueCount = 2;
rp_begin.pClearValues = clear_values;
}
void MyVulkanManager::destroy_render_pass()
{
vk::vkDestroyRenderPass(device, renderPass, NULL);
vk::vkDestroySemaphore(device, imageAcquiredSemaphore, NULL);
}
void MyVulkanManager::init_queue()
{
vk::vkGetDeviceQueue(device, queueGraphicsFamilyIndex, 0,&queueGraphics);
}
void MyVulkanManager::create_frame_buffer()
{
VkImageView attachments[2];
attachments[1] = depthImageView;
VkFramebufferCreateInfo fb_info = {};
fb_info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
fb_info.pNext = NULL;
fb_info.renderPass = renderPass;
fb_info.attachmentCount = 2;
fb_info.pAttachments = attachments;
fb_info.width = screenWidth;
fb_info.height = screenHeight;
fb_info.layers = 1;
uint32_t i;
framebuffers = (VkFramebuffer *)malloc(swapchainImageCount * sizeof(VkFramebuffer));
assert(framebuffers);
for (i = 0; i < swapchainImageCount; i++)
{
attachments[0] = swapchainImageViews[i];
VkResult result = vk::vkCreateFramebuffer(device, &fb_info, NULL, &framebuffers[i]);
assert(result == VK_SUCCESS);
LOGE("[创建帧缓冲%d成功!]",i);
}
}
void MyVulkanManager::destroy_frame_buffer()
{
for (int i = 0; i < swapchainImageCount; i++)
{
vk::vkDestroyFramebuffer(device, framebuffers[i], NULL);
}
free(framebuffers);
LOGE("销毁帧缓冲成功!");
}
void MyVulkanManager::createDrawableObject()
{
FlatData::genVertexData();
texTri=new TexDrawableObject(FlatData::vdata,FlatData::dataByteCount,FlatData::vCount,device, memoryroperties);
}
void MyVulkanManager::destroyDrawableObject()
{
delete texTri;
}
void MyVulkanManager::createFence()
{
VkFenceCreateInfo fenceInfo;
fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
fenceInfo.pNext = NULL;
fenceInfo.flags = 0;
vk::vkCreateFence(device, &fenceInfo, NULL, &taskFinishFence);
}
void MyVulkanManager::destroyFence()
{
vk::vkDestroyFence(device, taskFinishFence, NULL);
}
void MyVulkanManager::initPresentInfo()
{
present.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
present.pNext = NULL;
present.swapchainCount = 1;
present.pSwapchains = &swapChain;
present.pWaitSemaphores = NULL;
present.waitSemaphoreCount = 0;
present.pResults = NULL;
}
void MyVulkanManager::initMatrixAndLight()
{
MatrixState3D::setCamera(0,0,5.5,0,0,0,0,1,0);
MatrixState3D::setInitStack();
float ratio=(float)screenWidth/(float)screenHeight;
MatrixState3D::setProjectFrustum(-ratio,ratio,-1,1,1.5f,1000);
}
void MyVulkanManager::flushUniformBuffer() {
}
void MyVulkanManager::flushTexToDesSet()
{
for(int i=0;i<TextureManager::texNames.size();i++)
{
sqsCT->writes[0].dstSet = sqsCT->descSet[i];
sqsCT->writes[1].dstSet = sqsCT->descSet[i];
sqsCT->writes[1].pImageInfo = &(TextureManager::texImageInfoList[TextureManager::texNames[i]]);
vk::vkUpdateDescriptorSets(device, 2, sqsCT->writes, 0, NULL);
sqsImage->writes[0].dstSet = sqsImage->descSet[i];
sqsImage->writes[1].dstSet = sqsImage->descSet[i];
sqsImage->writes[1].pImageInfo = &(TextureManager::texImageInfoList[TextureManager::texNames[i]]);
vk::vkUpdateDescriptorSets(device, 2, sqsImage->writes, 0, NULL);
}
}
void MyVulkanManager::drawObject()
{
FPSUtil::init();
while(MyVulkanManager::loopDrawFlag)
{
FPSUtil::calFPS();
FPSUtil::before();
VkResult result = vk::vkAcquireNextImageKHR(device, swapChain, UINT64_MAX, imageAcquiredSemaphore, VK_NULL_HANDLE,¤tBuffer);
rp_begin.framebuffer = framebuffers[currentBuffer];
vk::vkResetCommandBuffer(cmdBuffer, 0);
result = vk::vkBeginCommandBuffer(cmdBuffer, &cmd_buf_info);
MyVulkanManager::flushUniformBuffer();
MyVulkanManager::flushTexToDesSet();
vk::vkCmdBeginRenderPass(cmdBuffer, &rp_begin, VK_SUBPASS_CONTENTS_INLINE);
MatrixState3D::pushMatrix();
MatrixState3D::translate(3.3,0,0);//处理后的图像
texTri->drawSelf(cmdBuffer,sqsImage->pipelineLayout,sqsImage->pipeline, &(sqsImage->descSet[TextureManager::getVkDescriptorSetIndex("texture/pm.bntex")]));
MatrixState3D::translate(-6.6,0,0);//正常图像
texTri->drawSelf(cmdBuffer,sqsCT->pipelineLayout,sqsCT->pipeline, &(sqsCT->descSet[TextureManager::getVkDescriptorSetIndex("texture/pm.bntex")]));
MatrixState3D::popMatrix();
vk::vkCmdEndRenderPass(cmdBuffer);
result = vk::vkEndCommandBuffer(cmdBuffer);
submit_info[0].waitSemaphoreCount = 1;
submit_info[0].pWaitSemaphores = &imageAcquiredSemaphore;
result = vk::vkQueueSubmit(queueGraphics, 1, submit_info, taskFinishFence);
do
{
result = vk::vkWaitForFences(device, 1, &taskFinishFence, VK_TRUE, FENCE_TIMEOUT);
}
while (result == VK_TIMEOUT);
vk::vkResetFences(device,1,&taskFinishFence);
present.pImageIndices = ¤tBuffer;
result = vk::vkQueuePresentKHR(queueGraphics, &present);
FPSUtil::after(60);
}
}
void MyVulkanManager::doVulkan()
{
ThreadTask* tt=new ThreadTask();
thread t1(&ThreadTask::doTask,tt);
t1.detach();
}
void MyVulkanManager::init_texture()
{
TextureManager::initTextures(device,gpus[0],memoryroperties,cmdBuffer,queueGraphics);
}
void MyVulkanManager::destroy_textures()
{
TextureManager::deatroyTextures(device);
}
void MyVulkanManager::initPipeline()
{
sqsCT=new ShaderQueueSuit_CommonTex(&device,renderPass,memoryroperties);
sqsImage=new ShaderQueueSuit_CommonTexImage(&device,renderPass,memoryroperties);
}
void MyVulkanManager::destroyPipeline()
{
delete sqsCT;
delete sqsImage;
}
| [
"709165253@qq.com"
] | 709165253@qq.com |
8eefc0be7fd82bc76974dd74b77623edb98f4b48 | f13d58b82ab70b42ff017432272e4e9fc3d8d99a | /online-judge/CodeForces/CodeForces 1093C.cpp | 94b28e10eac469fb9c000f7987fb7a0993a35f7b | [] | no_license | WEGFan/Algorithm-Contest-Code | 3586d6edba03165a9e243a10566fedcc6bcf1315 | a5b53605c0ec7161d12d48335171763a2ddf12b0 | refs/heads/master | 2020-11-26T10:33:02.807386 | 2019-12-19T12:05:17 | 2019-12-19T12:05:17 | 229,043,842 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 659 | cpp | #include <iostream>
using namespace std;
long long arr[200007];
long long brr[200007];
int main()
{
int n;
cin >> n;
for (int i = 0; i < n / 2; i++)
{
cin >> brr[i];
}
arr[0] = 0;
arr[n - 1] = brr[0];
for (int i = 1; i < n / 2; i++)
{
long long tmp = arr[n - i];
if (brr[i] - arr[i - 1] <= tmp)
{
arr[i] = arr[i - 1];
arr[n - i - 1] = brr[i] - arr[i - 1];
}
else
{
arr[n - i - 1] = tmp;
arr[i] = brr[i] - tmp;
}
}
for (int i = 0; i < n; i++)
{
cout << arr[i] << ' ';
}
return 0;
} | [
"goofans@qq.com"
] | goofans@qq.com |
0f0a4329caeca28272ba9b782a665fcffba36a76 | 438d9dde1d13a7b49da7ab4599a7ea5a046ccb88 | /Semester5-F/BTP305/Workshop8/Workshop8/w8.cpp | 1701c4586daceeb551c6de5bf8266215b9d7feea | [] | no_license | phanthanhkhai480/school-work | b99e1b11642a9929bbb5a83d3d0e3b6480669d92 | f95831e0d36a461bd0eb00c61946cff526fdbf60 | refs/heads/main | 2023-08-06T00:21:05.091992 | 2021-09-27T02:31:31 | 2021-09-27T02:31:31 | 394,076,848 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,434 | cpp | // Workshop 9 - Smart Pointers
// w9.cpp
#include <iostream>
#include <fstream>
#include <iomanip>
#include <memory>
#include <utility>
#include "Element.h"
#include "List.h"
const int FWC = 5;
const int FWD = 12;
const int FWP = 8;
w9::List<w9::Product> merge(const w9::List<w9::Description>& desc,
const w9::List<w9::Price>& price)
{
w9::List<w9::Product> priceList;
//******* YOUR CODE GOES HERE ***********//
//Part 1
//search for array with common attributes
int desc_size = desc.size();
int price_size = price.size();
for (int a = 0; a < desc_size; a++)
//loop through array of description (code, description)
{
for (int b = 0; b < price_size; b++)
//loop through array price (code,price)
{
if (desc[a].code == price[b].code)
//comparing common attribute
{
//Product(const std::string& str, double p)
//raw pointer
w9::Product* temp = new w9::Product(desc[a].desc, price[b].price);
priceList += temp;
delete temp;
temp = nullptr;
//smart pointer
//std::unique_ptr<w9::Product> same
//( new w9::Product(desc[a].desc, price[b].price) );
//same->validate();
//priceList += std::move(same);
}
}
}
return priceList;
}
int main(int argc, char** argv) {
std::ofstream ofs("Lab8Output.txt");
std::cout << "\nCommand Line : ";
for (int i = 0; i < argc; i++) {
std::cout << argv[i] << ' ';
}
std::cout << std::endl;
if (argc != 3) {
std::cerr << "\n***Incorrect number of arguments***\n";
return 1;
}
try {
w9::List<w9::Description> desc(argv[1]);
ofs << std::endl;
ofs << std::setw(FWC) << "Code" << std::setw(FWD) << "Description" << std::endl;
ofs << desc << std::endl;
w9::List<w9::Price> price(argv[2]);
ofs << std::endl;
ofs << std::setw(FWC) << "Code" << std::setw(FWP) << "Price" << std::endl;
ofs << price << std::endl;
w9::List<w9::Product> priceList = merge(desc, price);
ofs << std::endl;
ofs << std::setw(FWD) << "Description" << std::setw(FWP) << "Price" << std::endl;
ofs << priceList << std::endl;
}
catch (const std::string& msg) {
ofs << msg << std::endl;
}
catch (const char* msg) {
ofs << msg << std::endl;
}
std::cout << "Results can be found in the Lab8Output.txt file\nPress any key to continue ... ";
std::cin.get();
ofs.close();
}
| [
"50007190+phanthanhkhai480@users.noreply.github.com"
] | 50007190+phanthanhkhai480@users.noreply.github.com |
229fef720611cacd523d8fbc4f2d5853417bc653 | 87b48e7b8d80e11fa8ac762a5327b9877ec5a1ff | /configure/configure_edge/main.cpp | 47f7d8cd35d7e0dc11fc49c80f8577ff0711f1d0 | [] | no_license | junyiliu/innovation-diffusion | 0d5fb38e0ae16f802d223a1f420c22c19bfa330f | d27b0d1689324fb9c3b8cf170e8c0255e64e23b4 | refs/heads/master | 2021-01-10T19:32:58.600105 | 2014-05-10T08:00:46 | 2014-05-10T08:00:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,651 | cpp | #include "my_vector.h"
#include "epidemic.h"
#include <cstdio>
#include <iostream>
#include <fstream>
#include <vector>
#include "include/igraph.h"
#include "migraph.h"
#pragma comment(lib,"igraph.lib")
igraph_rng_t *mrng=igraph_rng_default();
extern void gen_graph(igraph_t* res,
const string & name);
int main(int argc,char*argv[])
{
if(argc!=2)
{
cout<<"USAGE:SIS datafile "<<endl;
exit(1);
}
//define the entry
string networkname(argv[1]); //network name
double a=1;
double alpha=0.4;
double beta=0.1;
int game_rounds=500; //MC rounds
int aver_rounds=10; //do average
double delta=1;//delta
string output_name_pre; //the network name
for(int i=0;i!=networkname.size()-4;i++)
{
output_name_pre.push_back(networkname[i]);
}
//random generator
//to initialize the random seed
igraph_rng_init(mrng,&igraph_rngtype_mt19937);
unsigned long idum; // random number seed
idum=(unsigned long)time(NULL);
igraph_rng_seed(mrng,idum);
//construct the graph
igraph_t network;
gen_graph(&network,networkname);
int nwsize=igraph_vcount(&network); //the size of the network
//to generate the name of the output file
//output file name
string resname("res.txt");
string totalname=output_name_pre+resname;
FILE *outfile;
outfile = fopen(totalname.c_str(), "w");
//construct the population
for(a=-6;a<6.1;a+=0.1 )
{
population popu(output_name_pre,&network,delta,0.01,a,1,3*nwsize,3*nwsize);
double res=0;
popu.population_dynamics(&res,alpha,beta,1000);
fprintf(outfile,"%f\t%f\n",a,res/ nwsize);
fflush(outfile);
}
fclose(outfile);
/*
igraph_t network;
int nwsize = igraph_vcount(&network); //the size of the network
igraph_watts_strogatz_game(&network, 1, 500, 4, 0.1, false, false);
string output_name_pre("small_world");
population test(output_name_pre,&network, 1, 0.01, 1, 0, 3 * nwsize, 3 * nwsize);
test.initial_state();
double res = 0;
test.population_dynamics(&res,0.3,0.1,300);
*/
//for (a=-5;a!=5;a+=0.2)
//
//{
// population test(&network,delta,0.01,a,type,3*nwsize,3*nwsize);
// vector<double> average_rres;
// for(int i=0;i!=aver_rounds;++i)
// {
// double rres=0;
// test.initial_state();
// test.population_dynamics(&rres,0.4,0.1,game_rounds);
//// printf("%f\n", rres);
// average_rres.push_back(rres);
// }
// fprintf(outfile,"%f\t%f\n",a,double (accumulate(average_rres.begin(),\
// average_rres.end(),0)/average_rres.size()));
// fflush(outfile);
//}
//fclose(outfile);
igraph_destroy(&network);
return 0;
}
| [
"qikuijun@gmail.com"
] | qikuijun@gmail.com |
663d3de5060c32b3f52419900f2d0b9350ad630c | 384b61b16a703e28093dd07e8d4d74f053e4c582 | /src/Magnum/Trade/imageconverter.cpp | e2d5dce54452e9adeccecc6175e283d70b27e698 | [
"MIT"
] | permissive | fauder/magnum | 6d11a2aa00efbf56a08e41a36ec75b975d5712e0 | f79a9dfecfc042520704f9ad7e563114ee6ed5f7 | refs/heads/master | 2023-07-29T02:29:10.712611 | 2023-07-05T13:19:49 | 2023-07-05T13:24:51 | 264,703,677 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 60,389 | cpp | /*
This file is part of Magnum.
Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019,
2020, 2021, 2022, 2023 Vladimír Vondruš <mosra@centrum.cz>
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <Corrade/Containers/Optional.h>
#include <Corrade/Containers/GrowableArray.h>
#include <Corrade/Containers/Pair.h>
#include <Corrade/Containers/StaticArray.h>
#include <Corrade/Containers/StridedArrayView.h>
#include <Corrade/PluginManager/Manager.h>
#include <Corrade/Utility/Arguments.h>
#include <Corrade/Utility/Algorithms.h>
#include <Corrade/Utility/ConfigurationGroup.h>
#include <Corrade/Utility/DebugStl.h> /** @todo remove once Arguments is std::string-free */
#include <Corrade/Utility/Format.h>
#include <Corrade/Utility/Path.h>
#include "Magnum/ImageView.h"
#include "Magnum/PixelFormat.h"
#include "Magnum/Implementation/converterUtilities.h"
#include "Magnum/Trade/AbstractImporter.h"
#include "Magnum/Trade/AbstractImageConverter.h"
#include "Magnum/Trade/ImageData.h"
#include "Magnum/Trade/Implementation/converterUtilities.h"
namespace Magnum {
/** @page magnum-imageconverter Image conversion utility
@brief Converts images of different formats
@tableofcontents
@m_footernavigation
@m_keywords{magnum-imageconverter imageconverter}
This utility is built if `MAGNUM_WITH_IMAGECONVERTER` is enabled when building
Magnum. To use this utility with CMake, you need to request the
`imageconverter` component of the `Magnum` package and use the
`Magnum::imageconverter` target for example in a custom command:
@code{.cmake}
find_package(Magnum REQUIRED imageconverter)
add_custom_command(OUTPUT ... COMMAND Magnum::imageconverter ...)
@endcode
See @ref building, @ref cmake and the @ref Trade namespace for more
information. There's also a corresponding @ref magnum-sceneconverter "scene conversion utility".
@section magnum-imageconverter-example Example usage
Listing contents of a cubemap DDS file with mipmaps, implicitly using
@relativeref{Trade,AnyImageImporter} that delegates to
@relativeref{Trade,DdsImporter} or
@ref file-formats "any other plugin capable of DDS import" depending on what's
available:
@m_class{m-code-figure}
@parblock
@code{.sh}
magnum-imageconverter --info cubemap.dds
@endcode
<b></b>
@m_class{m-nopad}
@include imageconverter-info.ansi
@endparblock
Converting a JPEG file to a PNG, implicitly using
@relativeref{Trade,AnyImageConverter} that delegates to
@relativeref{Trade,PngImageConverter}, @relativeref{Trade,StbImageConverter} or
@ref file-formats "any other plugin capable of PNG export" depending on what's
available:
@code{.sh}
magnum-imageconverter image.jpg image.png
@endcode
Creating a JPEG file with 95% quality from a PNG, by setting a plugin-specific
configuration option that's recognized by both
@ref Trade-JpegImageConverter-configuration "JpegImageConverter" and
@ref Trade-StbImageConverter-configuration "StbImageConverter":
@code{.sh}
magnum-imageconverter image.png image.jpg -c jpegQuality=0.95
@endcode
Extracting raw (uncompressed or block-compressed) data from a DDS file for
manual inspection:
@code{.sh}
magnum-imageconverter image.dds --converter raw data.dat
@endcode
Extracting an arbitrary image from a glTF file. Note that only image formats
are considered by default so you have to explicitly supply a scene importer,
either the generic @relativeref{Trade,AnySceneImporter} or for example directly
the @relativeref{Trade,GltfImporter}. First printing a list of images to choose
from:
@m_class{m-code-figure}
@parblock
@code{.sh}
magnum-imageconverter -I GltfImporter --info file.gltf
@endcode
<b></b>
@m_class{m-nopad}
@include imageconverter-info-gltf.ansi
@endparblock
@m_class{m-noindent}
... and then extracting the third image to a PNG file for inspection:
@code{.sh}
magnum-imageconverter -I GltfImporter --image 2 file.gltf image.png
@endcode
Converting a PNG file to a KTX2, resizing it to 512x512 with
@relativeref{Trade,StbResizeImageConverter}, block-compressing its data to BC3
using @relativeref{Trade,StbDxtImageConverter} with high-quality output.
Because the plugin implements image-to-image conversion, the @relativeref{Trade,AnyImageConverter} plugin is implicitly used after it,
proxying to @relativeref{Trade,KtxImageConverter} as the `*.ktx2` extension was
chosen:
@code{.sh}
magnum-imageconverter image.png image.ktx2 \
-C StbResizeImageConverter -c size="512 512" \
-C StbDxtImageConverter -c highQuality
@endcode
Printing features and documented options of a particular image converter
plugin. For debugging convenience the printed configuration file will reflect
also all options specified via `-c`:
@m_class{m-code-figure}
@parblock
@code{.sh}
magnum-imageconverter --info-converter -C StbResizeImageConverter -c size="512 512"
@endcode
<b></b>
@m_class{m-nopad}
@include imageconverter-info-converter.ansi
@endparblock
@subsection magnum-imageconverter-example-levels-layers Dealing with image levels and layers
Converting six 2D images to a 3D cube map file using @relativeref{Trade,OpenExrImageConverter}. Note the `-c envmap-cube` which the
plugin needs to produce an actual cube map file, the `--` is then used to avoid
`-x.exr` and others to be treated as options instead of files. On Unix shells
you could also use `./-x.exr` etc. to circumvent that ambiguity.
@code{.sh}
magnum-imageconverter --layers -c envmap=cube -- \
+x.exr -x.exr +y.exr -y.exr +z.exr -z.exr cube.exr
@endcode
Creating a multi-level OpenEXR cube map file from a set of input files. Note
the use of `-D3` which switches to dealing with 3D images instead of 2D:
@code{.sh}
magnum-imageconverter --levels -c envmap=cube -D3 \
cube-256.exr cube-128.exr cube-64.exr cube-mips.exr
@endcode
Extracting the second level of a +Y face (third layer) of the above cube map
file again:
@code{.sh}
magnum-imageconverter cube-mips.exr --layer 2 --level 1 +x-128.exr
@endcode
@section magnum-imageconverter-usage Full usage documentation
@code{.sh}
magnum-imageconverter [-h|--help] [-I|--importer PLUGIN]
[-C|--converter PLUGIN]... [--plugin-dir DIR] [--map]
[-i|--importer-options key=val,key2=val2,…]
[-c|--converter-options key=val,key2=val2,…]... [-D|--dimensions N]
[--image N] [--level N] [--layer N] [--layers] [--levels] [--in-place]
[--info-importer] [--info-converter] [--info] [--color on|off|auto]
[-v|--verbose] [--profile] [--] input output
@endcode
Arguments:
- `input` --- input image
- `output` --- output image; ignored if `--info` is present, disallowed for
`--in-place`
- `-h`, `--help` --- display this help message and exit
- `-I`, `--importer PLUGIN` --- image importer plugin (default:
@ref Trade::AnyImageImporter "AnyImageImporter")
- `-C`, `--converter PLUGIN` --- image converter plugin (default:
@ref Trade::AnyImageConverter "AnyImageConverter")
- `--plugin-dir DIR` --- override base plugin dir
- `--map` --- memory-map the input for zero-copy import (works only for
standalone files)
- `-i`, `--importer-options key=val,key2=val2,…` --- configuration options to
pass to the importer
- `-c`, `--converter-options key=val,key2=val2,…` --- configuration options
to pass to the converter(s)
- `-D`, `--dimensions N` --- import and convert image of given dimensions
(default: `2`)
- `--image N` --- image to import (default: `0`)
- `--level N` --- import given image level instead of all
- `--layer N` --- extract a layer into an image with one dimension less
- `--layers` --- combine multiple layers into an image with one dimension
more
- `--levels` --- combine multiple image levels into a single file
- `--in-place` --- overwrite the input image with the output
- `--info-importer` --- print info about the importer plugin and exit
- `--info-converter` --- print info about the image converter plugin and exit
- `--info` --- print info about the input file and exit
- `--color` --- colored output for `--info` (default: `auto`)
- `-v`, `--verbose` --- verbose output from importer and converter plugins
- `--profile` --- measure import and conversion time
Specifying `--importer raw:<format>` will treat the input as a raw
tightly-packed square of pixels in given @ref PixelFormat. Specifying `-C` /
`--converter raw` will save raw imported data instead of using a converter
plugin.
If the `--info-importer` or `--info-converter` option is given, the utility
will print information about given plugin specified via the `-I` or `-C`
option, including its configuration options potentially overriden with
`-i` or `-c`. In this case no file is read and no conversion is done and
neither the input nor the output file needs to be specified.
If `--info` is given, the utility will print information about given data,
independently of the `-D` / `--dimensions` option. In this case the input file
is read but no no conversion is done and output file doesn't need to be
specified.
The `-i` / `--importer-options` and `-c` / `--converter-options` arguments
accept a comma-separated list of key/value pairs to set in the importer /
converter plugin configuration. If the `=` character is omitted, it's
equivalent to saying `key=true`; configuration subgroups are delimited with
`/`. Prefix the key with `+` to add new options or multiple options of the same
name.
It's possible to specify the `-C` / `--converter` option (and correspondingly
also `-c` / `--converter-options`) multiple times in order to chain more
converters together. All converters in the chain have to support image-to-image
conversion, the last converter has to be either `raw` or support either
image-to-image or image-to-file conversion. If the last converter doesn't
support conversion to a file, @relativeref{Trade,AnyImageConverter} is used to
save its output; if no `-C` / `--converter` is specified,
@relativeref{Trade,AnyImageConverter} is used.
*/
}
using namespace Magnum;
using namespace Containers::Literals;
namespace {
bool isPluginInfoRequested(const Utility::Arguments& args) {
return args.isSet("info-importer") ||
args.isSet("info-converter");
}
template<UnsignedInt dimensions> bool checkCommonFormatFlags(const Utility::Arguments& args, const Containers::Array<Trade::ImageData<dimensions>>& images) {
CORRADE_INTERNAL_ASSERT(!images.isEmpty());
const bool compressed = images.front().isCompressed();
PixelFormat format{};
CompressedPixelFormat compressedFormat{};
if(!compressed) format = images.front().format();
else compressedFormat = images.front().compressedFormat();
ImageFlags<dimensions> flags = images.front().flags();
for(std::size_t i = 1; i != images.size(); ++i) {
if(images[i].isCompressed() != compressed ||
(!compressed && images[i].format() != format) ||
(compressed && images[i].compressedFormat() != compressedFormat))
{
Error e;
e << "Images have different formats," << args.arrayValue("input", i) << "has";
if(images[i].isCompressed())
e << images[i].compressedFormat();
else
e << images[i].format();
e << Debug::nospace << ", expected";
if(compressed)
e << compressedFormat;
else
e << format;
return false;
}
if(images[i].flags() != flags) {
Error{} << "Images have different flags," << args.arrayValue("input", i) << "has" << images[i].flags() << Debug::nospace << ", expected" << flags;
return false;
}
}
return true;
}
template<UnsignedInt dimensions> bool checkCommonFormatAndSize(const Utility::Arguments& args, const Containers::Array<Trade::ImageData<dimensions>>& images) {
if(!checkCommonFormatFlags(args, images)) return false;
CORRADE_INTERNAL_ASSERT(!images.isEmpty());
Math::Vector<dimensions, Int> size = images.front().size();
for(std::size_t i = 1; i != images.size(); ++i) {
if(images[i].size() != size) {
Error{} << "Images have different sizes," << args.arrayValue("input", i) << "has a size of" << images[i].size() << Debug::nospace << ", expected" << size;
return false;
}
}
return true;
}
template<template<UnsignedInt, class> class View, UnsignedInt dimensions> bool convertOneOrMoreImagesToFile(Trade::AbstractImageConverter& converter, const Containers::Array<Trade::ImageData<dimensions>>& outputImages, const Containers::StringView output) {
Containers::Array<View<dimensions, const char>> views;
arrayReserve(views, outputImages.size());
for(const Trade::ImageData<dimensions>& outputImage: outputImages)
arrayAppend(views, View<dimensions, const char>{outputImage});
return converter.convertToFile(views, output);
}
template<UnsignedInt dimensions> bool convertOneOrMoreImagesToFile(Trade::AbstractImageConverter& converter, const Containers::Array<Trade::ImageData<dimensions>>& outputImages, const Containers::StringView output) {
/* If there's just one image, convert it using the single-level API.
Otherwise the multi-level entrypoint would require the plugin to support
multi-level conversion, and only some file formats have that. */
if(outputImages.size() == 1)
return converter.convertToFile(outputImages.front(), output);
CORRADE_INTERNAL_ASSERT(!outputImages.isEmpty());
if(outputImages.front().isCompressed())
return convertOneOrMoreImagesToFile<CompressedImageView, dimensions>(converter, outputImages, output);
else
return convertOneOrMoreImagesToFile<ImageView, dimensions>(converter, outputImages, output);
}
template<UnsignedInt dimensions> bool convertImages(Trade::AbstractImageConverter& converter, Containers::Array<Trade::ImageData<dimensions>>& images) {
CORRADE_INTERNAL_ASSERT(!images.isEmpty());
for(Trade::ImageData<dimensions>& image: images) {
Containers::Optional<Trade::ImageData<dimensions>> output = converter.convert(image);
if(!output) return false;
image = *std::move(output);
}
return true;
}
}
int main(int argc, char** argv) {
Utility::Arguments args;
args.addArrayArgument("input").setHelp("input", "input image(s)")
.addArgument("output").setHelp("output", "output image; ignored if --info is present, disallowed for --in-place")
.addOption('I', "importer", "AnyImageImporter").setHelp("importer", "image importer plugin", "PLUGIN")
.addArrayOption('C', "converter").setHelp("converter", "image converter plugin(s)", "PLUGIN")
.addOption("plugin-dir").setHelp("plugin-dir", "override base plugin dir", "DIR")
#if defined(CORRADE_TARGET_UNIX) || (defined(CORRADE_TARGET_WINDOWS) && !defined(CORRADE_TARGET_WINDOWS_RT))
.addBooleanOption("map").setHelp("map", "memory-map the input for zero-copy import (works only for standalone files)")
#endif
.addOption('i', "importer-options").setHelp("importer-options", "configuration options to pass to the importer", "key=val,key2=val2,…")
.addArrayOption('c', "converter-options").setHelp("converter-options", "configuration options to pass to the converter(s)", "key=val,key2=val2,…")
.addOption('D', "dimensions", "2").setHelp("dimensions", "import and convert image of given dimensions", "N")
.addOption("image", "0").setHelp("image", "image to import", "N")
.addOption("level").setHelp("level", "import given image level instead of all", "N")
.addOption("layer").setHelp("layer", "extract a layer into an image with one dimension less", "N")
.addBooleanOption("layers").setHelp("layers", "combine multiple layers into an image with one dimension more")
.addBooleanOption("levels").setHelp("layers", "combine multiple image levels into a single file")
.addBooleanOption("in-place").setHelp("in-place", "overwrite the input image with the output")
.addBooleanOption("info-importer").setHelp("info-importer", "print info about the importer plugin and exit")
.addBooleanOption("info-converter").setHelp("info-converter", "print info about the image converter plugin and exit")
.addBooleanOption("info").setHelp("info", "print info about the input file and exit")
.addOption("color", "auto").setHelp("color", "colored output for --info", "on|off|auto")
.addBooleanOption('v', "verbose").setHelp("verbose", "verbose output from importer and converter plugins")
.addBooleanOption("profile").setHelp("profile", "measure import and conversion time")
.setParseErrorCallback([](const Utility::Arguments& args, Utility::Arguments::ParseError error, const std::string& key) {
/* If --info for plugins is passed, we don't need the input */
if(error == Utility::Arguments::ParseError::MissingArgument &&
key == "input" && isPluginInfoRequested(args))
return true;
/* If --in-place or --info for plugins or data is passed, we don't
need the output argument */
if(error == Utility::Arguments::ParseError::MissingArgument &&
key == "output" && (args.isSet("in-place") || isPluginInfoRequested(args) || args.isSet("info")))
return true;
/* Handle all other errors as usual */
return false;
})
.setGlobalHelp(R"(Converts images of different formats.
Specifying --importer raw:<format> will treat the input as a raw tightly-packed
square of pixels in given pixel format. Specifying -C / --converter raw will
save raw imported data instead of using a converter plugin.
If the --info-importer or --info-converter option is given, the utility will
print information about given plugin specified via the -I or -C option,
including its configuration options potentially overriden with -i or -c. In
this case no file is read and no conversion is done and neither the input nor
the output file needs to be specified.
If --info is given, the utility will print information about given data, independently of the -D / --dimensions option. In this case the input file is
read but no conversion is done and output file doesn't need to be specified.
The -i / --importer-options and -c / --converter-options arguments accept a
comma-separated list of key/value pairs to set in the importer / converter
plugin configuration. If the = character is omitted, it's equivalent to saying
key=true; configuration subgroups are delimited with /. Prefix the key with +
to add new options or multiple options of the same name.
It's possible to specify the -C / --converter option (and correspondingly also
-c / --converter-options) multiple times in order to chain more converters
together. All converters in the chain have to support image-to-image
conversion, the last converter has to be either raw or support either
image-to-image or image-to-file conversion. If the last converter doesn't
support conversion to a file, AnyImageConverter is used to save its output; if
no -C / --converter is specified, AnyImageConverter is used.)")
.parse(argc, argv);
/* Colored output. Enable only if a TTY. */
Debug::Flags useColor;
if(args.value("color") == "on")
useColor = Debug::Flags{};
else if(args.value("color") == "off")
useColor = Debug::Flag::DisableColors;
else
useColor = Debug::isTty() ? Debug::Flags{} : Debug::Flag::DisableColors;
/* Generic checks */
if(const std::size_t inputCount = args.arrayValueCount("input")) {
/* Not an error in this case, it should be possible to just append
--info* to existing command line without having to remove anything.
But print a warning at least, it could also be a mistyped option. */
if(isPluginInfoRequested(args)) {
Warning w;
w << "Ignoring input files for --info:";
for(std::size_t i = 0; i != inputCount; ++i)
w << args.arrayValue<Containers::StringView>("input", i);
}
}
if(args.value<Containers::StringView>("output")) {
if(args.isSet("in-place")) {
Error{} << "Output file shouldn't be set for --in-place:" << args.value<Containers::StringView>("output");
return 1;
}
/* Same as above, it should be possible to just append --info* to
existing command line */
if(isPluginInfoRequested(args) || args.isSet("info"))
Warning{} << "Ignoring output file for --info:" << args.value<Containers::StringView>("output");
}
/* Mutually incompatible options */
if(args.isSet("layers") && args.isSet("levels")) {
Error{} << "The --layers and --levels options can't be used together. First combine layers of each level and then all levels in a second step.";
return 1;
}
if((args.isSet("layers") || args.isSet("levels")) && args.isSet("in-place")) {
Error{} << "The --layers / --levels option can't be combined with --in-place";
return 1;
}
if((args.isSet("layers") || args.isSet("levels")) && args.isSet("info")) {
Error{} << "The --layers / --levels option can't be combined with --info";
return 1;
}
/* It can be combined with --levels though. This could potentially be
possible to implement, but I don't see a reason, all it would do is
picking Nth image from the input set and recompress it. OTOH, combining
--levels and --level "works", the --level picks Nth level from each
input image, although the usefulness of that is also doubtful. Why
create multi-level images from images that are already multi-level? */
if(args.isSet("layers") && !args.value("layer").empty()) {
Error{} << "The --layers option can't be combined with --layer.";
return 1;
}
if(args.isSet("levels") && args.arrayValueCount("converter") && args.arrayValue("converter", args.arrayValueCount("converter") - 1) == "raw") {
Error{} << "The --levels option can't be combined with raw data output";
return 1;
}
if(!args.isSet("layers") && !args.isSet("levels") && args.arrayValueCount("input") > 1 && !isPluginInfoRequested(args)) {
Error{} << "Multiple input files require the --layers / --levels option to be set";
return 1;
}
/* Importer and converter manager */
PluginManager::Manager<Trade::AbstractImporter> importerManager{
args.value("plugin-dir").empty() ? Containers::String{} :
Utility::Path::join(args.value("plugin-dir"), Utility::Path::split(Trade::AbstractImporter::pluginSearchPaths().back()).second())};
PluginManager::Manager<Trade::AbstractImageConverter> converterManager{
args.value("plugin-dir").empty() ? Containers::String{} :
Utility::Path::join(args.value("plugin-dir"), Utility::Path::split(Trade::AbstractImageConverter::pluginSearchPaths().back()).second())};
/* Print plugin info, if requested */
if(args.isSet("info-importer")) {
Containers::Pointer<Trade::AbstractImporter> importer = importerManager.loadAndInstantiate(args.value("importer"));
if(!importer) {
Debug{} << "Available importer plugins:" << ", "_s.join(importerManager.aliasList());
return 1;
}
/* Set options, if passed */
if(args.isSet("verbose")) importer->addFlags(Trade::ImporterFlag::Verbose);
Implementation::setOptions(*importer, "AnyImageImporter", args.value("importer-options"));
Trade::Implementation::printImporterInfo(useColor, *importer);
return 0;
}
if(args.isSet("info-converter")) {
Containers::Pointer<Trade::AbstractImageConverter> converter = converterManager.loadAndInstantiate(args.arrayValueCount("converter") ? args.arrayValue("converter", 0) : "AnyImageConverter");
if(!converter) {
Debug{} << "Available converter plugins:" << ", "_s.join(converterManager.aliasList());
return 1;
}
/* Set options, if passed */
if(args.isSet("verbose")) converter->addFlags(Trade::ImageConverterFlag::Verbose);
if(args.arrayValueCount("converter-options"))
Implementation::setOptions(*converter, "AnyImageConverter", args.arrayValue("converter-options", 0));
Trade::Implementation::printImageConverterInfo(useColor, *converter);
return 0;
}
const Int dimensions = args.value<Int>("dimensions");
/** @todo make them array options as well? */
const UnsignedInt image = args.value<UnsignedInt>("image");
Containers::Optional<UnsignedInt> level;
if(!args.value("level").empty()) level = args.value<UnsignedInt>("level");
#if defined(CORRADE_TARGET_UNIX) || (defined(CORRADE_TARGET_WINDOWS) && !defined(CORRADE_TARGET_WINDOWS_RT))
Containers::Array<Containers::Array<const char, Utility::Path::MapDeleter>> mapped;
#endif
Containers::Array<Trade::ImageData1D> images1D;
Containers::Array<Trade::ImageData2D> images2D;
Containers::Array<Trade::ImageData3D> images3D;
/* Wow, C++, you suck. This implicitly initializes to random shit?! */
std::chrono::high_resolution_clock::duration importTime{};
for(std::size_t i = 0, max = args.arrayValueCount("input"); i != max; ++i) {
const Containers::StringView input = args.arrayValue<Containers::StringView>("input", i);
/* Load raw data, if requested; assume it's a tightly-packed square of
given format */
/** @todo implement image slicing and then use `--slice "0 0 w h"` to
specify non-rectangular size (and +x +y to specify padding?) */
if(args.value<Containers::StringView>("importer").hasPrefix("raw:"_s)) {
if(dimensions != 2) {
Error{} << "Raw data inputs can be only used for 2D images";
return 1;
}
/** @todo Any chance to do this without using internal APIs? */
const PixelFormat format = Utility::ConfigurationValue<PixelFormat>::fromString(args.value("importer").substr(4), {});
if(format == PixelFormat{}) {
Error{} << "Invalid raw pixel format" << args.value("importer");
return 4;
}
const UnsignedInt pixelSize = pixelFormatSize(format);
/* Read the file or map it if requested */
Containers::Array<char> data;
#if defined(CORRADE_TARGET_UNIX) || (defined(CORRADE_TARGET_WINDOWS) && !defined(CORRADE_TARGET_WINDOWS_RT))
if(args.isSet("map")) {
arrayAppend(mapped, InPlaceInit);
Trade::Implementation::Duration d{importTime};
Containers::Optional<Containers::Array<const char, Utility::Path::MapDeleter>> mappedMaybe = Utility::Path::mapRead(input);
if(!mappedMaybe) {
Error() << "Cannot memory-map file" << input;
return 3;
}
/* Fake a mutable array with a non-owning deleter to have the
same type as from Path::read(). The actual memory is owned
by the `mapped` array. */
mapped.back() = *std::move(mappedMaybe);
data = Containers::Array<char>{const_cast<char*>(mapped.back().data()), mapped.back().size(), [](char*, std::size_t){}};
} else
#endif
{
Trade::Implementation::Duration d{importTime};
Containers::Optional<Containers::Array<char>> dataMaybe = Utility::Path::read(input);
if(!dataMaybe) {
Error{} << "Cannot read file" << input;
return 3;
}
data = *std::move(dataMaybe);
}
auto side = Int(std::sqrt(data.size()/pixelSize));
if(data.size() % pixelSize || side*side*pixelSize != data.size()) {
Error{} << "File of size" << data.size() << "is not a tightly-packed square of" << format;
return 5;
}
/* Print image info, if requested */
if(args.isSet("info")) {
Debug{} << "Image 0:" << format << Vector2i{side};
if(args.isSet("profile")) {
Debug{} << "Import took" << UnsignedInt(std::chrono::duration_cast<std::chrono::milliseconds>(importTime).count())/1.0e3f << "seconds";
}
return 0;
}
arrayAppend(images2D, InPlaceInit, format, Vector2i{side}, std::move(data));
/* Otherwise load it using an importer plugin */
} else {
Containers::Pointer<Trade::AbstractImporter> importer = importerManager.loadAndInstantiate(args.value("importer"));
if(!importer) {
Debug{} << "Available importer plugins:" << ", "_s.join(importerManager.aliasList());
return 1;
}
/* Set options, if passed */
if(args.isSet("verbose")) importer->addFlags(Trade::ImporterFlag::Verbose);
Implementation::setOptions(*importer, "AnyImageImporter", args.value("importer-options"));
/* Open the file or map it if requested */
#if defined(CORRADE_TARGET_UNIX) || (defined(CORRADE_TARGET_WINDOWS) && !defined(CORRADE_TARGET_WINDOWS_RT))
if(args.isSet("map")) {
arrayAppend(mapped, InPlaceInit);
Trade::Implementation::Duration d{importTime};
Containers::Optional<Containers::Array<const char, Utility::Path::MapDeleter>> mappedMaybe = Utility::Path::mapRead(input);
if(!mappedMaybe || !importer->openMemory(*mappedMaybe)) {
Error() << "Cannot memory-map file" << input;
return 3;
}
mapped.back() = *std::move(mappedMaybe);
} else
#endif
{
Trade::Implementation::Duration d{importTime};
if(!importer->openFile(input)) {
Error{} << "Cannot open file" << input;
return 3;
}
}
/* Print image info, if requested. This is always done for just one
file, checked above. */
if(args.isSet("info")) {
/* Don't fail when there's no image -- we could be asking for
info on a scene file without images, after all */
if(!importer->image1DCount() && !importer->image2DCount() && !importer->image3DCount()) {
Debug{} << "No images found in" << input;
return 0;
}
/* Parse everything first to avoid errors interleaved with
output */
bool error = false;
Containers::Array<Trade::Implementation::ImageInfo> infos =
Trade::Implementation::imageInfo(*importer, error, importTime);
Trade::Implementation::printImageInfo(useColor, infos, nullptr, nullptr, nullptr);
if(args.isSet("profile")) {
Debug{} << "Import took" << UnsignedInt(std::chrono::duration_cast<std::chrono::milliseconds>(importTime).count())/1.0e3f << "seconds";
}
return error ? 1 : 0;
}
/* Bail early if there's no image whatsoever. More detailed errors
with hints are provided for each dimension below. */
if(!importer->image1DCount() && !importer->image2DCount() && !importer->image3DCount()) {
Error{} << "No images found in" << input;
return 1;
}
bool imported = false;
if(dimensions == 1) {
if(!importer->image1DCount()) {
Error{} << "No 1D images found in" << input << Debug::nospace << ". Specify -D2 or -D3 for 2D or 3D image conversion.";
return 1;
}
if(image >= importer->image1DCount()) {
Error{} << "1D image number" << image << "not found in" << input << Debug::nospace << ", the file has only" << importer->image1DCount() << "1D images";
return 1;
}
/* Import all levels of the input or just one if specified */
UnsignedInt minLevel, maxLevel;
if(level) {
minLevel = *level;
maxLevel = *level + 1;
if(*level >= importer->image1DLevelCount(image)) {
Error{} << "1D image" << image << "in" << input << "doesn't have a level number" << level << Debug::nospace << ", only" << importer->image1DLevelCount(image) << "levels";
return 1;
}
} else {
minLevel = 0;
maxLevel = importer->image1DLevelCount(image);
if(maxLevel > 1 && (args.isSet("layers") || args.isSet("levels") || (args.arrayValueCount("converter") && args.arrayValue("converter", args.arrayValueCount("converter") - 1) == "raw"))) {
Error{} << "Cannot use --layers / --levels or raw output with multi-level input images. Specify --level N to extract just one level from each.";
return 1;
}
}
for(; minLevel != maxLevel; ++minLevel) {
if(Containers::Optional<Trade::ImageData1D> image1D = importer->image1D(image, minLevel)) {
/* The --layer option is only for 2D/3D, not checking
any bounds here. If the option is present, the
extraction code below will fail. */
arrayAppend(images1D, std::move(*image1D));
imported = true;
}
}
} else if(dimensions == 2) {
if(!importer->image2DCount()) {
Error{} << "No 2D images found in" << input << Debug::nospace << ". Specify -D1 or -D3 for 1D or 3D image conversion.";
return 1;
}
if(image >= importer->image2DCount()) {
Error{} << "2D image number" << image << "not found in" << input << Debug::nospace << ", the file has only" << importer->image2DCount() << "2D images";
return 1;
}
/* Import all levels of the input or just one if specified */
UnsignedInt minLevel, maxLevel;
if(level) {
minLevel = *level;
maxLevel = *level + 1;
if(*level >= importer->image2DLevelCount(image)) {
Error{} << "2D image" << image << "in" << input << "doesn't have a level number" << level << Debug::nospace << ", only" << importer->image2DLevelCount(image) << "levels";
return 1;
}
} else {
minLevel = 0;
maxLevel = importer->image2DLevelCount(image);
if(maxLevel > 1 && (args.isSet("layers") || args.isSet("levels") || (args.arrayValueCount("converter") && args.arrayValue("converter", args.arrayValueCount("converter") - 1) == "raw"))) {
Error{} << "Cannot use --layers / --levels or raw output with multi-level input images. Specify --level N to extract just one level from each.";
return 1;
}
}
for(; minLevel != maxLevel; ++minLevel) {
if(Containers::Optional<Trade::ImageData2D> image2D = importer->image2D(image, minLevel)) {
/* Check bounds for the --layer option here, as we
won't have the filename etc. later */
if(!args.value("layer").empty() && args.value<Int>("layer") >= image2D->size().y()) {
Error{} << "2D image" << image << Debug::nospace << ":" << Debug::nospace << minLevel << "in" << input << "doesn't have a layer number" << args.value<Int>("layer") << Debug::nospace << ", only" << image2D->size().y() << "layers";
return 1;
}
arrayAppend(images2D, std::move(*image2D));
imported = true;
}
}
} else if(dimensions == 3) {
if(!importer->image3DCount()) {
Error{} << "No 3D images found in" << input << Debug::nospace << ". Specify -D1 or -D2 for 1D or 2D image conversion.";
return 1;
}
if(image >= importer->image3DCount()) {
Error{} << "3D image number" << image << "not found in" << input << Debug::nospace << ", the file has only" << importer->image3DCount() << "3D images";
return 1;
}
/* Import all levels of the input or just one if specified */
UnsignedInt minLevel, maxLevel;
if(level) {
minLevel = *level;
maxLevel = *level + 1;
if(*level >= importer->image3DLevelCount(image)) {
Error{} << "3D image" << image << "in" << input << "doesn't have a level number" << level << Debug::nospace << ", only" << importer->image3DLevelCount(image) << "levels";
return 1;
}
} else {
minLevel = 0;
maxLevel = importer->image3DLevelCount(image);
if(maxLevel > 1 && (args.isSet("layers") || args.isSet("levels") || (args.arrayValueCount("converter") && args.arrayValue("converter", args.arrayValueCount("converter") - 1) == "raw"))) {
Error{} << "Cannot use --layers / --levels or raw output with multi-level input images. Specify --level N to extract just one level from each.";
return 1;
}
}
for(; minLevel != maxLevel; ++minLevel) {
if(Containers::Optional<Trade::ImageData3D> image3D = importer->image3D(image, minLevel)) {
/* Check bounds for the --layer option here, as we
won't have the filename etc. later */
if(!args.value("layer").empty() && args.value<Int>("layer") >= image3D->size().z()) {
Error{} << "3D image" << image << Debug::nospace << ":" << Debug::nospace << minLevel << "in" << input << "doesn't have a layer number" << args.value<Int>("layer") << Debug::nospace << ", only" << image3D->size().z() << "layers";
return 1;
}
arrayAppend(images3D, std::move(*image3D));
imported = true;
}
}
} else {
Error{} << "Invalid --dimensions option:" << args.value("dimensions");
return 1;
}
if(!imported) {
Error{} << "Cannot import image" << image << Debug::nospace << ":" << Debug::nospace << level << "from" << input;
return 4;
}
}
}
/* Wow, C++, you suck. This implicitly initializes to random shit?! */
std::chrono::high_resolution_clock::duration conversionTime{};
Containers::StringView output;
if(args.isSet("in-place")) {
/* Should have been checked in a graceful way above */
CORRADE_INTERNAL_ASSERT(args.arrayValueCount("input") == 1);
output = args.arrayValue<Containers::StringView>("input", 0);
} else output = args.value<Containers::StringView>("output");
Int outputDimensions;
Containers::Array<Trade::ImageData1D> outputImages1D;
Containers::Array<Trade::ImageData2D> outputImages2D;
Containers::Array<Trade::ImageData3D> outputImages3D;
/* Combine multiple layers into an image of one dimension more */
if(args.isSet("layers")) {
/* To include allocation + copy costs in the output */
Trade::Implementation::Duration d{conversionTime};
if(dimensions == 1) {
if(!checkCommonFormatAndSize(args, images1D)) return 1;
outputDimensions = 2;
if(!images1D.front().isCompressed()) {
/* Allocate a new image */
/** @todo simplify once ImageData is able to allocate on its
own, including correct padding etc */
const Vector2i size{images1D.front().size()[0], Int(images1D.size())};
arrayAppend(outputImages2D, InPlaceInit,
/* Don't want to bother with row padding, it's temporary
anyway */
PixelStorage{}.setAlignment(1),
images1D.front().format(),
size,
Containers::Array<char>{NoInit, size.product()*images1D.front().pixelSize()}
);
/* Copy the pixel data over */
const Containers::StridedArrayView3D<char> outputPixels = outputImages2D.front().mutablePixels();
for(std::size_t i = 0; i != images1D.size(); ++i)
Utility::copy(images1D[i].pixels(), outputPixels[i]);
} else {
Error{} << "The --layers option isn't implemented for compressed images yet.";
return 1;
}
} else if(dimensions == 2) {
if(!checkCommonFormatAndSize(args, images2D)) return 1;
outputDimensions = 3;
if(!images2D.front().isCompressed()) {
/* Allocate a new image */
/** @todo simplify once ImageData is able to allocate on its
own, including correct padding etc */
const Vector3i size{images2D.front().size(), Int(images2D.size())};
arrayAppend(outputImages3D, InPlaceInit,
/* Don't want to bother with row padding, it's temporary
anyway */
PixelStorage{}.setAlignment(1),
images2D.front().format(),
size,
Containers::Array<char>{NoInit, size.product()*images2D.front().pixelSize()}
);
/* Copy the pixel data over */
const Containers::StridedArrayView4D<char> outputPixels = outputImages3D.front().mutablePixels();
for(std::size_t i = 0; i != images2D.size(); ++i)
Utility::copy(images2D[i].pixels(), outputPixels[i]);
} else {
Error{} << "The --layers option isn't implemented for compressed images yet.";
return 1;
}
} else if(dimensions == 3) {
Error{} << "The --layers option can be only used with 1D and 2D inputs, not 3D";
return 1;
} else CORRADE_INTERNAL_ASSERT_UNREACHABLE();
/* Extracting a layer, inverse of the above */
} else if(!args.value("layer").empty()) {
const Int layer = args.value<Int>("layer");
if(dimensions == 1) {
Error{} << "The --layer option can be only used with 2D and 3D inputs, not 1D";
return 1;
} else if(dimensions == 2) {
outputDimensions = 1;
/* There can be multiple input levels, and a layer should get
extracted from each level, forming a multi-level image again */
if(!checkCommonFormatFlags(args, images2D)) return 1;
if(!images2D.front().isCompressed()) {
for(std::size_t i = 0; i != images2D.size(); ++i) {
/* Diagnostic printed in the import loop above, as here we
don't have the filename etc. anymore */
CORRADE_INTERNAL_ASSERT(layer < images2D[i].size().y());
/* Copy the layer to a newly alllocated image */
/** @todo if the GL-inspired PixelStorage API wasn't CRAP,
we could just reuse the original memory and slice it.
But because Y skip is ignored for 1D images, it just
won't work. Rework once it's in a better shape. */
Trade::ImageData1D copy{PixelStorage{}.setAlignment(1),
images2D[i].format(), images2D[i].formatExtra(),
images2D[i].pixelSize(), images2D[i].size().x(),
Containers::Array<char>{NoInit, std::size_t(images2D[i].size().x()*images2D[i].pixelSize())}};
Utility::copy(images2D[i].pixels()[layer], copy.mutablePixels());
arrayAppend(outputImages1D, std::move(copy));
}
} else {
Error{} << "The --layer option isn't implemented for compressed images yet.";
return 1;
}
} else if(dimensions == 3) {
outputDimensions = 2;
/* There can be multiple input levels, and a layer should get
extracted from each level, forming a multi-level image again */
if(!checkCommonFormatFlags(args, images3D)) return 1;
if(!images3D.front().isCompressed()) {
for(std::size_t i = 0; i != images3D.size(); ++i) {
/* Diagnostic printed in the import loop above, as here we
don't have the filename etc. anymore */
CORRADE_INTERNAL_ASSERT(layer < images3D[i].size().z());
/* Copy the layer to a newly alllocated image */
/** @todo if the GL-inspired PixelStorage API wasn't CRAP,
we could just reuse the original memory and slice it.
But because Y skip is ignored for 1D images, it just
won't work. Rework once it's in a better shape. */
Trade::ImageData2D copy{PixelStorage{}.setAlignment(1),
images3D[i].format(), images3D[i].formatExtra(),
images3D[i].pixelSize(), images3D[i].size().xy(),
Containers::Array<char>{NoInit, std::size_t(images3D[i].size().xy().product()*images3D[i].pixelSize())}};
Utility::copy(images3D[i].pixels()[layer], copy.mutablePixels());
arrayAppend(outputImages2D, std::move(copy));
}
} else {
Error{} << "The --layer option isn't implemented for compressed images yet.";
return 1;
}
} else CORRADE_INTERNAL_ASSERT_UNREACHABLE();
/* Single-image (potentially multi-level) conversion, verify that all have
the same format and pass the input through. This happens either if
--levels is set or if the (single) input image is multi-level. */
} else {
if(dimensions == 1) {
if(!checkCommonFormatFlags(args, images1D)) return 1;
outputDimensions = 1;
outputImages1D = std::move(images1D);
} else if(dimensions == 2) {
if(!checkCommonFormatFlags(args, images2D)) return 1;
outputDimensions = 2;
outputImages2D = std::move(images2D);
} else if(dimensions == 3) {
if(!checkCommonFormatFlags(args, images3D)) return 1;
outputDimensions = 3;
outputImages3D = std::move(images3D);
} else CORRADE_INTERNAL_ASSERT_UNREACHABLE();
}
const bool outputIsMultiLevel =
outputImages1D.size() > 1 ||
outputImages2D.size() > 1 ||
outputImages3D.size() > 1;
/* Assume there's always one passed --converter option less, and the last
is implicitly AnyImageConverter. All converters except the last one are
expected to support ConvertMesh and the mesh is "piped" from one to the
other. If the last converter supports ConvertMeshToFile instead of
ConvertMesh, it's used instead of the last implicit AnySceneConverter. */
for(std::size_t i = 0, converterCount = args.arrayValueCount("converter"); i <= converterCount; ++i) {
const Containers::StringView converterName = i == converterCount ?
"AnyImageConverter"_s : args.arrayValue<Containers::StringView>("converter", i);
const bool outputIsCompressed =
(outputDimensions == 1 && outputImages1D.front().isCompressed()) ||
(outputDimensions == 2 && outputImages2D.front().isCompressed()) ||
(outputDimensions == 3 && outputImages3D.front().isCompressed());
/* Load converter plugin if a raw conversion is not requested */
Containers::Pointer<Trade::AbstractImageConverter> converter;
if(converterName != "raw"_s) {
if(!(converter = converterManager.loadAndInstantiate(converterName))) {
Debug{} << "Available converter plugins:" << ", "_s.join(converterManager.aliasList());
return 2;
}
/* Set options, if passed */
if(args.isSet("verbose")) converter->addFlags(Trade::ImageConverterFlag::Verbose);
if(i < args.arrayValueCount("converter-options"))
Implementation::setOptions(*converter, "AnyImageConverter", args.arrayValue("converter-options", i));
}
/* This is the last --converter (a raw output, a file-capable converter
or the implicit AnyImageConverter at the end), output to a file and
exit the loop */
if(i + 1 >= converterCount && (converterName == "raw"_s || (converter->features() & (
Trade::ImageConverterFeature::Convert1DToFile|
Trade::ImageConverterFeature::Convert2DToFile|
Trade::ImageConverterFeature::Convert3DToFile|
Trade::ImageConverterFeature::ConvertCompressed1DToFile|
Trade::ImageConverterFeature::ConvertCompressed2DToFile|
Trade::ImageConverterFeature::ConvertCompressed3DToFile))))
{
/* Decide what converter feature we should look for for given
dimension count. This has to be redone each iteration, as a
converted could have converted an uncompressed image to a
compressed one and vice versa. */
if(converterName != "raw"_s) {
Trade::ImageConverterFeatures expectedFeatures;
if(outputDimensions == 1) {
expectedFeatures = outputIsCompressed ?
Trade::ImageConverterFeature::ConvertCompressed1DToFile :
Trade::ImageConverterFeature::Convert1DToFile;
} else if(outputDimensions == 2) {
expectedFeatures = outputIsCompressed ?
Trade::ImageConverterFeature::ConvertCompressed2DToFile :
Trade::ImageConverterFeature::Convert2DToFile;
} else if(outputDimensions == 3) {
expectedFeatures = outputIsCompressed ?
Trade::ImageConverterFeature::ConvertCompressed3DToFile :
Trade::ImageConverterFeature::Convert3DToFile;
} else CORRADE_INTERNAL_ASSERT_UNREACHABLE();
if(outputIsMultiLevel)
expectedFeatures |= Trade::ImageConverterFeature::Levels;
if(!(converter->features() >= expectedFeatures)) {
Error err;
err << converterName << "doesn't support";
if(outputIsMultiLevel)
err << "multi-level";
if(outputIsCompressed)
err << "compressed";
err << outputDimensions << Debug::nospace << "D image to file conversion, only" << converter->features();
return 6;
}
}
if(args.isSet("verbose")) {
Debug d;
if(converterName == "raw")
d << "Writing raw image data of size";
else
d << "Saving output of size";
d << Debug::packed;
if(outputDimensions == 1) {
d << outputImages1D.front().size();
if(outputImages1D.size() > 1)
d << "(and" << outputImages1D.size() - 1 << "more levels)";
} else if(outputDimensions == 2) {
d << outputImages2D.front().size();
if(outputImages2D.size() > 1)
d << "(and" << outputImages2D.size() - 1 << "more levels)";
} else if(outputDimensions == 3) {
d << outputImages3D.front().size();
if(outputImages3D.size() > 1)
d << "(and" << outputImages3D.size() - 1 << "more levels)";
}
else CORRADE_INTERNAL_ASSERT_UNREACHABLE();
d << "and" << (outputIsCompressed ? "compressed format" : "format") << Debug::packed;
if(outputDimensions == 1) {
if(outputImages1D.front().isCompressed())
d << outputImages1D.front().compressedFormat();
else d << outputImages1D.front().format();
} else if(outputDimensions == 2) {
if(outputImages2D.front().isCompressed())
d << outputImages2D.front().compressedFormat();
else d << outputImages2D.front().format();
} else if(outputDimensions == 3) {
if(outputImages3D.front().isCompressed())
d << outputImages3D.front().compressedFormat();
else d << outputImages3D.front().format();
} else CORRADE_INTERNAL_ASSERT_UNREACHABLE();
if(converterName != "raw")
d << "with" << converterName;
d << Debug::nospace << "...";
}
/* Save raw data, if requested. Only for single-level images as the
data layout would be messed up otherwise. */
if(converterName == "raw") {
Containers::ArrayView<const char> data;
if(outputDimensions == 1) {
CORRADE_INTERNAL_ASSERT(outputImages1D.size() == 1);
data = outputImages1D.front().data();
} else if(outputDimensions == 2) {
CORRADE_INTERNAL_ASSERT(outputImages2D.size() == 1);
data = outputImages2D.front().data();
} else if(outputDimensions == 3) {
CORRADE_INTERNAL_ASSERT(outputImages3D.size() == 1);
data = outputImages3D.front().data();
} else CORRADE_INTERNAL_ASSERT_UNREACHABLE();
{
Trade::Implementation::Duration d{conversionTime};
if(!Utility::Path::write(output, data)) return 1;
}
/* Convert to a file */
} else {
bool converted;
Trade::Implementation::Duration d{conversionTime};
if(outputDimensions == 1)
converted = convertOneOrMoreImagesToFile(*converter, outputImages1D, output);
else if(outputDimensions == 2)
converted = convertOneOrMoreImagesToFile(*converter, outputImages2D, output);
else if(outputDimensions == 3)
converted = convertOneOrMoreImagesToFile(*converter, outputImages3D, output);
else CORRADE_INTERNAL_ASSERT_UNREACHABLE();
if(!converted) {
Error{} << "Cannot save file" << output;
return 5;
}
}
break;
/* This is not the last converter, expect that it's capable of
image-to-image conversion */
} else {
if(converterName == "raw"_s) {
Error{} << "Only the very last --converter can be raw";
return 1;
}
CORRADE_INTERNAL_ASSERT(i < converterCount);
if(converterCount > 1 && args.isSet("verbose"))
Debug{} << "Processing (" << Debug::nospace << (i+1) << Debug::nospace << "/" << Debug::nospace << converterCount << Debug::nospace << ") with" << converterName << Debug::nospace << "...";
/* Decide what converter feature we should look for for given
dimension count. This has to be redone each iteration, as a
converted could have converted an uncompressed image to a
compressed one and vice versa. */
Trade::ImageConverterFeature expectedFeature;
if(outputDimensions == 1) {
expectedFeature = outputIsCompressed ?
Trade::ImageConverterFeature::ConvertCompressed1D :
Trade::ImageConverterFeature::Convert1D;
} else if(outputDimensions == 2) {
expectedFeature = outputIsCompressed ?
Trade::ImageConverterFeature::ConvertCompressed2D :
Trade::ImageConverterFeature::Convert2D;
} else if(outputDimensions == 3) {
expectedFeature = outputIsCompressed ?
Trade::ImageConverterFeature::ConvertCompressed3D :
Trade::ImageConverterFeature::Convert3D;
} else CORRADE_INTERNAL_ASSERT_UNREACHABLE();
if(!(converter->features() >= expectedFeature)) {
Error err;
err << converterName << "doesn't support";
if(outputIsCompressed)
err << "compressed";
err << outputDimensions << Debug::nospace << "D image conversion, only" << converter->features();
return 6;
}
bool converted;
Trade::Implementation::Duration d{conversionTime};
if(outputDimensions == 1)
converted = convertImages(*converter, outputImages1D);
else if(outputDimensions == 2)
converted = convertImages(*converter, outputImages2D);
else if(outputDimensions == 3)
converted = convertImages(*converter, outputImages3D);
else CORRADE_INTERNAL_ASSERT_UNREACHABLE();
if(!converted) {
Error{} << converterName << "cannot convert the image";
return 5;
}
}
}
if(args.isSet("profile")) {
Debug{} << "Import took" << UnsignedInt(std::chrono::duration_cast<std::chrono::milliseconds>(importTime).count())/1.0e3f << "seconds, conversion"
<< UnsignedInt(std::chrono::duration_cast<std::chrono::milliseconds>(conversionTime).count())/1.0e3f << "seconds";
}
}
| [
"mosra@centrum.cz"
] | mosra@centrum.cz |
3d774fefd010ea4393a5da76b5add4841b07913b | a8cd091c684b79676841ef4778fbcc27bdefdfa3 | /Walker/Walker.ino | 583ff65b9856453def67501eb98d9e5fad99adcd | [] | no_license | ericgemnay/Robot | dabaaf6370f1b3c99f509eeff0b78627aa396045 | e12a88ced2bcc9a08ec475457a640c287d286a50 | refs/heads/master | 2021-01-02T08:32:37.179615 | 2015-06-27T00:10:46 | 2015-06-27T00:10:46 | 38,139,893 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,439 | ino |
//including libraries
#include <Servo.h>
#include "Legs.h"
//makes the objects for servos
Servo Coxa1;
Servo Femur1;
Servo Tibia1;
Servo Coxa2;
Servo Femur2; //alt
Servo Tibia2; //alt
Servo Coxa3;
Servo Femur3;
Servo Tibia3;
Servo Coxa4;
Servo Femur4; //alt
Servo Tibia4; //alt
//starting angles
/*
int startingposCoxa = 90;
int startingposTibia = 110;
int startingposFemur = 70;
*/
int startingposCoxa = 90;
int startingposTibia = 110;
int startingposFemur = 70;
int startingposCoxaalt = 180-startingposCoxa;
int startingposTibiaalt = 180-startingposTibia;
int startingposFemuralt = 180-startingposFemur;
//Making an object for each leg
//(Servo Tibia, Servo Coxa, Servo Femur, float tibia, float coxa, float femur, float zoffset, float deflength)
OddLeg FrontLeft = OddLeg(Coxa1, Femur1, Tibia1, 5.468, 6.557, 7.681, 8.2, 8.2);
EvenLeg FrontRight = EvenLeg(Coxa2, Femur2, Tibia2, 5.468, 6.557, 7.681, 8, 8.2);
OddLeg BackRight = OddLeg(Coxa3, Femur3, Tibia3, 5.468, 6.557, 7.681, 8, 8.2);
EvenLeg BackLeft = EvenLeg(Coxa4, Femur4, Tibia4, 5.468, 6.557, 7.681, 8, 8.2);
void setup(){
//only needed for troubleshooting, starting a serial connection
//between the board and the computer
Serial.begin(9600);
//Assings servo objects to pins
Coxa1.attach(2);
Femur1.attach(3);
Tibia1.attach(4);
Coxa2.attach(7);
Femur2.attach(6);
Tibia2.attach(5);
Coxa3.attach(10);
Femur3.attach(8);
Tibia3.attach(9);
Coxa4.attach(13);
Femur4.attach(12);
Tibia4.attach(11);
//Sets the servos to starting positions
Coxa1.write(startingposCoxaalt);
Femur1.write(startingposFemur);
Tibia1.write(startingposTibia);
Coxa2.write(startingposCoxa);
Femur2.write(startingposFemuralt);
Tibia2.write(startingposTibiaalt);
Coxa3.write(startingposCoxaalt);
Femur3.write(startingposFemur);
Tibia3.write(startingposTibia);
Coxa4.write(startingposCoxa);
Femur4.write(startingposFemuralt);
Tibia4.write(startingposTibiaalt);
}
//function that makes the stable tripod for gait
//and causes them to drift backwards
//exception is which leg is not in the tripod
//stride is how far they drift back (use 10 for now)
void drift(int exception, int stride){
//the original stride, the variable is changed by the loop
int ostride = stride;
//the number you enter is the leg that moves forward
switch (exception){
case 1:{
//ostride-stride causes the leg to go in the opposite direction.
//Some even legs need to be inverted because of how they were built mechanically
for (;stride > 0; stride -= 0.5){
FrontLeft.swing(stride); //taking a step
FrontRight.drag(ostride-stride);
BackRight.drag(stride);
BackLeft.drag(stride);
}
//plant causes the leg to go to a low z-level (hopefully makes it touch the ground)
FrontLeft.plant();
break;
}
case 2:{
//calls the drag function with a different stride distance everytime in a for loop
//drag function calculates the angles of the three motors on each leg depending on a stride length
//swing does the same thing but in the other direction
//look in Legs.cpp foir more info
for (;stride > 0; stride -= 0.5){
FrontLeft.drag(ostride-stride);
FrontRight.swing(stride); //taking a step
BackRight.drag(stride);
BackLeft.drag(stride);
}
FrontRight.plant();
break;
}
case 3:{
for (;stride > 0; stride -= 0.5){
FrontLeft.drag(ostride-stride);
FrontRight.drag(ostride-stride);
BackRight.swing(ostride-stride); //taking a step
BackLeft.drag(stride);
}
BackRight.plant();
break;
}
case 4:{
for (;stride > 0; stride -= 0.5){
FrontLeft.drag(ostride-stride);
FrontRight.drag(ostride-stride);
BackRight.drag(stride);
BackLeft.swing(ostride-stride); //taking a step
}
BackLeft.plant();
break;
}
}
}
//puts all the motors in their starting positions
void reset(){
FrontLeft.reset();
FrontRight.reset();
BackLeft.reset();
BackRight.reset();
delay(500);
}
void loop(){
drift(1, 10);
delay(1000);
reset();
drift(2, 10);
delay(1000);
reset();
drift(3, 10);
delay(1000);
reset();
drift(4, 10);
delay(1000);
reset();
delay(10000);
}
| [
"egemnay@gmail.com"
] | egemnay@gmail.com |
1e531ed1be17a8ef274b456b18740fbd76aaab01 | 03303888daff8e46fac3d333a747adb7a3742d2d | /Core/fun.h | 6d1900949b734f46c5cef30f41b7fb05d1a39ae1 | [
"MIT"
] | permissive | pvmoore/cpp-core | 015c6385c3c2c7428f27cf4816edab85788b22d1 | 6dba63f12415fec5fe2e50dd18c52cac07a14d04 | refs/heads/master | 2021-10-19T13:26:10.372074 | 2019-02-21T11:53:42 | 2019-02-21T11:53:42 | 123,930,155 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 467 | h | #pragma once
namespace core {
template<typename COLLECTION, typename LAMBDA>
void forEach(COLLECTION collection, LAMBDA lambda) {
std::for_each(collection.begin(), collection.end(), lambda);
}
/// Transforms elements of same type within the collection.
template <typename COLLECTION, typename LAMBDA>
COLLECTION map(COLLECTION collection, LAMBDA lambda) {
std::transform(collection.begin(), collection.end(), collection.begin(), lambda);
return collection;
}
} | [
"1926576+pvmoore@users.noreply.github.com"
] | 1926576+pvmoore@users.noreply.github.com |
7e7252a91c740f5331c75770749578c5432d499c | f622e20ed72dcc6a11b6de365dc7f62d34af4995 | /TP.h | c13b1947c144c082d55a5cbb64e523cf716edc0e | [] | no_license | MarcosRolando/tp2taller | d637ac425127d14cf0518eb896c11de181f323ee | b7bdf6e9113d5f0f3917d2a817aaf7e8ffac43f6 | refs/heads/master | 2022-07-13T01:35:36.088076 | 2020-05-13T13:57:36 | 2020-05-13T13:57:36 | 262,163,479 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 272 | h | //
// Created by marcos on 12/5/20.
//
#ifndef TP2TALLER_TP_H
#define TP2TALLER_TP_H
#include "King.h"
#include "FileException.h"
class TP {
public:
static int run(int argc, char** argv);
private:
static bool _validInput(int argc);
};
#endif //TP2TALLER_TP_H
| [
"marcosrolando.mr@gmail.com"
] | marcosrolando.mr@gmail.com |
e7f2363bcc2c2146d2426d119017f54bddb31722 | 5c6d2151717fcca45406321895b59505a681f25e | /examples/cli_single.cpp | 54dcde55d346bcaff5d9bd5a2720fbcf03c533ce | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | DonRazor2/libsolace | fd29266a166b8249578e7368638c6bf9305795cd | d7501d2e83b30064a0aa938e03509b4822b3b2b0 | refs/heads/master | 2020-03-23T10:01:16.064131 | 2018-07-16T14:50:32 | 2018-07-16T14:50:32 | 141,421,486 | 0 | 0 | null | 2018-07-18T10:47:33 | 2018-07-18T10:47:33 | null | UTF-8 | C++ | false | false | 1,690 | cpp | /*
* Copyright 2016 Ivan Ryabov
*
* 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.
*/
/**
* An example of command line argument parser for a single action CLI.
*/
#include <solace/cli/parser.hpp>
#include <iostream>
using namespace Solace;
static constexpr StringLiteral kAppName = "cli_single";
static const Version kAppVersion = Version(0, 0, 1, "dev");
int main(int argc, const char **argv) {
int intValue = 0;
float32 floatValue = 0.0f;
StringView userName(getenv("USER"));
const auto res = cli::Parser("Solace cli single action example", {
cli::Parser::printHelp(),
cli::Parser::printVersion(kAppName, kAppVersion),
{{"i", "intOption"}, "Some useless parameter for the demo", &intValue},
{{"fOption"}, "Foating point value for the demo", &floatValue},
{{"u", "name"}, "Greet user name", &userName}
})
.parse(argc, argv);
if (res) {
std::cout << "Hello '" << userName << "'" << std::endl;
return EXIT_SUCCESS;
} else {
std::cerr << res.getError().toString();
return EXIT_FAILURE;
}
}
| [
"abbyssoul@gmail.com"
] | abbyssoul@gmail.com |
2208c400bd5400c4ae9d38020c1721a8997deeba | d6752ac9f95da0f1bc04e70a258e9976c9ddacef | /trapfunc.cpp | 4fe330f79df5f6d06290596b1f3cc0662530ad2b | [] | no_license | Justice-/MGSmod | a486119d1d998b2adfcbb9b04f2595fdf41e7fd6 | fcc475aabc1dca04041d1c69aa88af01a3d6ad8a | refs/heads/master | 2021-01-21T08:01:35.964087 | 2013-06-09T07:04:36 | 2013-06-09T07:04:36 | 10,578,456 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 22,148 | cpp | #include "game.h"
#include "trap.h"
#include "rng.h"
void trapfunc::bubble(game *g, int x, int y)
{
g->add_msg("You step on some bubblewrap!");
g->sound(x, y, 18, "Pop!");
g->m.tr_at(x, y) = tr_null;
}
void trapfuncm::bubble(game *g, monster *z, int x, int y)
{
g->sound(x, y, 18, "Pop!");
g->m.tr_at(x, y) = tr_null;
}
void trapfuncm::cot(game *g, monster *z, int x, int y)
{
g->add_msg("The zombie stumbles over the cot");
z->moves -= 100;
}
void trapfunc::beartrap(game *g, int x, int y)
{
g->add_msg("A bear trap closes on your foot!");
g->sound(x, y, 8, "SNAP!");
g->u.hit(g, bp_legs, rng(0, 1), 10, 16);
g->u.add_disease(DI_BEARTRAP, -1, g);
g->m.tr_at(x, y) = tr_null;
g->m.add_item(x, y, g->itypes[itm_beartrap], g->turn);
}
void trapfuncm::beartrap(game *g, monster *z, int x, int y)
{
g->sound(x, y, 8, "SNAP!");
if (z->hurt(35)) {
g->kill_mon(g->mon_at(x, y));
g->m.add_item(x, y, g->itypes[itm_beartrap], 0);
} else {
z->moves = 0;
z->add_effect(ME_BEARTRAP, rng(8, 15));
}
g->m.tr_at(x, y) = tr_null;
item beartrap(g->itypes[itm_beartrap], 0);
z->add_item(beartrap);
}
void trapfunc::board(game *g, int x, int y)
{
g->add_msg("You step on a spiked board!");
g->u.hit(g, bp_feet, 0, 0, rng(6, 10));
g->u.hit(g, bp_feet, 1, 0, rng(6, 10));
}
void trapfuncm::board(game *g, monster *z, int x, int y)
{
int t;
if (g->u_see(z, t))
g->add_msg("The %s steps on a spiked board!", z->name().c_str());
if (z->hurt(rng(6, 10)))
g->kill_mon(g->mon_at(x, y));
else
z->moves -= 80;
}
void trapfunc::tripwire(game *g, int x, int y)
{
g->add_msg("You trip over a tripwire!");
std::vector<point> valid;
for (int j = x - 1; j <= x + 1; j++) {
for (int k = y - 1; k <= y + 1; k++) {
if (g->is_empty(j, k)) // No monster, NPC, or player, plus valid for movement
valid.push_back(point(j, k));
}
}
if (valid.size() > 0) {
int index = rng(0, valid.size() - 1);
g->u.posx = valid[index].x;
g->u.posy = valid[index].y;
}
g->u.moves -= 150;
if (rng(5, 20) > g->u.dex_cur)
g->u.hurtall(rng(1, 4));
}
void trapfuncm::tripwire(game *g, monster *z, int x, int y)
{
int t;
if (g->u_see(z, t))
g->add_msg("The %s trips over a tripwire!", z->name().c_str());
z->stumble(g, false);
if (rng(0, 10) > z->type->sk_dodge && z->hurt(rng(1, 4)))
g->kill_mon(g->mon_at(z->posx, z->posy));
}
void trapfunc::crossbow(game *g, int x, int y)
{
bool add_bolt = true;
g->add_msg("You trigger a crossbow trap!");
if (!one_in(4) && rng(8, 20) > g->u.dodge(g)) {
body_part hit;
switch (rng(1, 10)) {
case 1: hit = bp_feet; break;
case 2:
case 3:
case 4: hit = bp_legs; break;
case 5:
case 6:
case 7:
case 8:
case 9: hit = bp_torso; break;
case 10: hit = bp_head; break;
}
int side = rng(0, 1);
g->add_msg("Your %s is hit!", body_part_name(hit, side).c_str());
g->u.hit(g, hit, side, 0, rng(20, 30));
add_bolt = !one_in(10);
} else
g->add_msg("You dodge the shot!");
g->m.tr_at(x, y) = tr_null;
g->m.add_item(x, y, g->itypes[itm_crossbow], 0);
g->m.add_item(x, y, g->itypes[itm_string_6], 0);
if (add_bolt)
g->m.add_item(x, y, g->itypes[itm_bolt_steel], 0);
}
void trapfuncm::crossbow(game *g, monster *z, int x, int y)
{
int t;
bool add_bolt = true;
bool seen = g->u_see(z, t);
if (!one_in(4)) {
if (seen)
g->add_msg("A bolt shoots out and hits the %s!", z->name().c_str());
if (z->hurt(rng(20, 30)))
g->kill_mon(g->mon_at(x, y));
add_bolt = !one_in(10);
} else if (seen)
g->add_msg("A bolt shoots out, but misses the %s.", z->name().c_str());
g->m.tr_at(x, y) = tr_null;
g->m.add_item(x, y, g->itypes[itm_crossbow], 0);
g->m.add_item(x, y, g->itypes[itm_string_6], 0);
if (add_bolt)
g->m.add_item(x, y, g->itypes[itm_bolt_steel], 0);
}
void trapfunc::shotgun(game *g, int x, int y)
{
g->add_msg("You trigger a shotgun trap!");
int shots = (one_in(8) || one_in(20 - g->u.str_max) ? 2 : 1);
if (g->m.tr_at(x, y) == tr_shotgun_1)
shots = 1;
if (rng(5, 50) > g->u.dodge(g)) {
body_part hit;
switch (rng(1, 10)) {
case 1: hit = bp_feet; break;
case 2:
case 3:
case 4: hit = bp_legs; break;
case 5:
case 6:
case 7:
case 8:
case 9: hit = bp_torso; break;
case 10: hit = bp_head; break;
}
int side = rng(0, 1);
g->add_msg("Your %s is hit!", body_part_name(hit, side).c_str());
g->u.hit(g, hit, side, 0, rng(40 * shots, 60 * shots));
} else
g->add_msg("You dodge the shot!");
if (shots == 2 || g->m.tr_at(x, y) == tr_shotgun_1) {
g->m.add_item(x, y, g->itypes[itm_shotgun_sawn], 0);
g->m.add_item(x, y, g->itypes[itm_string_6], 0);
g->m.tr_at(x, y) = tr_null;
} else
g->m.tr_at(x, y) = tr_shotgun_1;
}
void trapfuncm::shotgun(game *g, monster *z, int x, int y)
{
int t;
bool seen = g->u_see(z, t);
int chance;
switch (z->type->size) {
case MS_TINY: chance = 100; break;
case MS_SMALL: chance = 16; break;
case MS_MEDIUM: chance = 12; break;
case MS_LARGE: chance = 8; break;
case MS_HUGE: chance = 2; break;
}
int shots = (one_in(8) || one_in(chance) ? 2 : 1);
if (g->m.tr_at(x, y) == tr_shotgun_1)
shots = 1;
if (seen)
g->add_msg("A shotgun fires and hits the %s!", z->name().c_str());
if (z->hurt(rng(40 * shots, 60 * shots)))
g->kill_mon(g->mon_at(x, y));
if (shots == 2 || g->m.tr_at(x, y) == tr_shotgun_1) {
g->m.tr_at(x, y) = tr_null;
g->m.add_item(x, y, g->itypes[itm_shotgun_sawn], 0);
g->m.add_item(x, y, g->itypes[itm_string_6], 0);
} else
g->m.tr_at(x, y) = tr_shotgun_1;
}
void trapfunc::blade(game *g, int x, int y)
{
g->add_msg("A blade swings out and hacks your torso!");
g->u.hit(g, bp_torso, 0, 12, 30);
}
void trapfuncm::blade(game *g, monster *z, int x, int y)
{
int t;
if (g->u_see(z, t))
g->add_msg("A blade swings out and hacks the %s!", z->name().c_str());
int cutdam = 30 - z->armor_cut();
int bashdam = 12 - z->armor_bash();
if (cutdam < 0)
cutdam = 0;
if (bashdam < 0)
bashdam = 0;
if (z->hurt(bashdam + cutdam))
g->kill_mon(g->mon_at(x, y));
}
void trapfunc::snare_light(game *g, int x, int y)
{
g->sound(x, y, 2, "Snap!");
g->add_msg("A snare closes on your leg.");
g->u.add_disease(DI_LIGHTSNARE, rng(10, 20), g);
g->m.tr_at(x, y) = tr_null;
g->m.add_item(x, y, g->itypes[itm_string_36], 0);
g->m.add_item(x, y, g->itypes[itm_snare_trigger], 0);
}
void trapfuncm::snare_light(game *g, monster *z, int x, int y)
{
int t;
bool seen = g->u_see(z, t);
g->sound(x, y, 2, "Snap!");
switch (z->type->size) {
case MS_TINY:
if(seen){
g->add_msg("The %s has been snared!", z->name().c_str());
}
if(z->hurt(10)){
g->kill_mon(g->mon_at(x, y));
} else {
z->add_effect(ME_BEARTRAP, -1);
}
break;
case MS_SMALL:
if(seen){
g->add_msg("The %s has been snared!", z->name().c_str());
}
z->moves = 0;
z->add_effect(ME_BEARTRAP, rng(100, 150));
break;
case MS_MEDIUM:
if(seen){
g->add_msg("The %s has been snared!", z->name().c_str());
}
z->moves = 0;
z->add_effect(ME_BEARTRAP, rng(20, 30));
break;
case MS_LARGE:
if(seen){
g->add_msg("The snare has no effect on the %s!", z->name().c_str());
}
break;
case MS_HUGE:
if(seen){
g->add_msg("The snare has no effect on the %s!", z->name().c_str());
}
break;
}
g->m.tr_at(x, y) = tr_null;
g->m.add_item(x, y, g->itypes[itm_string_36], 0);
g->m.add_item(x, y, g->itypes[itm_snare_trigger], 0);
}
void trapfunc::snare_heavy(game *g, int x, int y)
{
int side = one_in(2) ? 0 : 1;
body_part hit = bp_legs;
g->sound(x, y, 4, "Snap!");
g->add_msg("A snare closes on your %s.", body_part_name(hit, side).c_str());
g->u.hit(g, bp_legs, side, 15, 20);
g->u.add_disease(DI_HEAVYSNARE, rng(20, 30), g);
g->m.tr_at(x, y) = tr_null;
g->m.add_item(x, y, g->itypes[itm_rope_6], 0);
g->m.add_item(x, y, g->itypes[itm_snare_trigger], 0);
}
void trapfuncm::snare_heavy(game *g, monster *z, int x, int y)
{
int t;
bool seen = g->u_see(z, t);
g->sound(x, y, 4, "Snap!");
switch (z->type->size) {
case MS_TINY:
if(seen){
g->add_msg("The %s has been snared!", z->name().c_str());
}
if(z->hurt(20)){
g->kill_mon(g->mon_at(x, y));
} else {
z->moves = 0;
z->add_effect(ME_BEARTRAP, -1);
}
break;
case MS_SMALL:
if(seen){
g->add_msg("The %s has been snared!", z->name().c_str());
}
if(z->hurt(20)){
g->kill_mon(g->mon_at(x, y));
} else {
z->moves = 0;
z->add_effect(ME_BEARTRAP, -1);
}
break;
case MS_MEDIUM:
if(seen){
g->add_msg("The %s has been snared!", z->name().c_str());
}
if(z->hurt(10)){
g->kill_mon(g->mon_at(x, y));
} else {
z->moves = 0;
z->add_effect(ME_BEARTRAP, rng(100, 150));
}
break;
case MS_LARGE:
if(seen){
g->add_msg("The %s has been snared!", z->name().c_str());
}
z->moves = 0;
z->add_effect(ME_BEARTRAP, rng(20, 30));
break;
case MS_HUGE:
if(seen){
g->add_msg("The snare has no effect on the %s!", z->name().c_str());
}
break;
}
g->m.tr_at(x, y) = tr_null;
g->m.add_item(x, y, g->itypes[itm_snare_trigger], 0);
g->m.add_item(x, y, g->itypes[itm_rope_6], 0);
}
void trapfunc::landmine(game *g, int x, int y)
{
g->add_msg("You trigger a landmine!");
g->explosion(x, y, 10, 8, false);
g->m.tr_at(x, y) = tr_null;
}
void trapfuncm::landmine(game *g, monster *z, int x, int y)
{
int t;
if (g->u_see(x, y, t))
g->add_msg("The %s steps on a landmine!", z->name().c_str());
g->explosion(x, y, 10, 8, false);
g->m.tr_at(x, y) = tr_null;
}
void trapfunc::boobytrap(game *g, int x, int y)
{
g->add_msg("You trigger a boobytrap!");
g->explosion(x, y, 18, 12, false);
g->m.tr_at(x, y) = tr_null;
}
void trapfuncm::boobytrap(game *g, monster *z, int x, int y)
{
int t;
if (g->u_see(x, y, t))
g->add_msg("The %s triggers a boobytrap!", z->name().c_str());
g->explosion(x, y, 18, 12, false);
g->m.tr_at(x, y) = tr_null;
}
void trapfunc::telepad(game *g, int x, int y)
{
g->sound(x, y, 6, "vvrrrRRMM*POP!*");
g->add_msg("The air shimmers around you...");
g->teleport();
}
void trapfuncm::telepad(game *g, monster *z, int x, int y)
{
g->sound(x, y, 6, "vvrrrRRMM*POP!*");
int j;
if (g->u_see(z, j))
g->add_msg("The air shimmers around the %s...", z->name().c_str());
int tries = 0;
int newposx, newposy;
do {
newposx = rng(z->posx - SEEX, z->posx + SEEX);
newposy = rng(z->posy - SEEY, z->posy + SEEY);
tries++;
} while (g->m.move_cost(newposx, newposy) == 0 && tries != 10);
if (tries == 10)
g->explode_mon(g->mon_at(z->posx, z->posy));
else {
int mon_hit = g->mon_at(newposx, newposy), t;
if (mon_hit != -1) {
if (g->u_see(z, t))
g->add_msg("The %s teleports into a %s, killing them both!",
z->name().c_str(), g->z[mon_hit].name().c_str());
g->explode_mon(mon_hit);
} else {
z->posx = newposx;
z->posy = newposy;
}
}
}
void trapfunc::goo(game *g, int x, int y)
{
g->add_msg("You step in a puddle of thick goo.");
g->u.infect(DI_SLIMED, bp_feet, 6, 20, g);
if (one_in(3)) {
g->add_msg("The acidic goo eats away at your feet.");
g->u.hit(g, bp_feet, 0, 0, 5);
g->u.hit(g, bp_feet, 1, 0, 5);
}
g->m.tr_at(x, y) = tr_null;
}
void trapfuncm::goo(game *g, monster *z, int x, int y)
{
if (z->type->id == mon_blob) {
z->speed += 15;
z->hp = z->speed;
} else {
z->poly(g->mtypes[mon_blob]);
z->speed -= 15;
z->hp = z->speed;
}
g->m.tr_at(x, y) = tr_null;
}
void trapfunc::dissector(game *g, int x, int y)
{
g->add_msg("Electrical beams emit from the floor and slice your flesh!");
g->sound(x, y, 10, "BRZZZAP!");
g->u.hit(g, bp_head, 0, 0, 15);
g->u.hit(g, bp_torso, 0, 0, 20);
g->u.hit(g, bp_arms, 0, 0, 12);
g->u.hit(g, bp_arms, 1, 0, 12);
g->u.hit(g, bp_hands, 0, 0, 10);
g->u.hit(g, bp_hands, 1, 0, 10);
g->u.hit(g, bp_legs, 0, 0, 12);
g->u.hit(g, bp_legs, 1, 0, 12);
g->u.hit(g, bp_feet, 0, 0, 10);
g->u.hit(g, bp_feet, 1, 0, 10);
}
void trapfuncm::dissector(game *g, monster *z, int x, int y)
{
g->sound(x, y, 10, "BRZZZAP!");
if (z->hurt(60))
g->explode_mon(g->mon_at(x, y));
}
void trapfunc::pit(game *g, int x, int y)
{
g->add_msg("You fall in a pit!");
if (g->u.has_trait(PF_WINGS_BIRD))
g->add_msg("You flap your wings and flutter down gracefully.");
else {
int dodge = g->u.dodge(g);
int damage = rng(10, 20) - rng(dodge, dodge * 5);
if (damage > 0) {
g->add_msg("You hurt yourself!");
g->u.hurtall(rng(int(damage / 2), damage));
g->u.hit(g, bp_legs, 0, damage, 0);
g->u.hit(g, bp_legs, 1, damage, 0);
} else
g->add_msg("You land nimbly.");
}
g->u.add_disease(DI_IN_PIT, -1, g);
}
void trapfuncm::pit(game *g, monster *z, int x, int y)
{
int junk;
if (g->u_see(x, y, junk))
g->add_msg("The %s falls in a pit!", z->name().c_str());
if (z->hurt(rng(10, 20)))
g->kill_mon(g->mon_at(x, y));
else
z->moves = -1000;
}
void trapfunc::pit_spikes(game *g, int x, int y)
{
g->add_msg("You fall in a pit!");
int dodge = g->u.dodge(g);
int damage = rng(20, 50);
if (g->u.has_trait(PF_WINGS_BIRD))
g->add_msg("You flap your wings and flutter down gracefully.");
else if (rng(5, 30) < dodge)
g->add_msg("You avoid the spikes within.");
else {
body_part hit;
switch (rng(1, 10)) {
case 1:
case 2: hit = bp_legs; break;
case 3:
case 4: hit = bp_arms; break;
case 5:
case 6:
case 7:
case 8:
case 9:
case 10: hit = bp_torso; break;
}
int side = rng(0, 1);
g->add_msg("The spikes impale your %s!", body_part_name(hit, side).c_str());
g->u.hit(g, hit, side, 0, damage);
if (one_in(4)) {
g->add_msg("The spears break!");
g->m.ter(x, y) = t_pit;
g->m.tr_at(x, y) = tr_pit;
for (int i = 0; i < 4; i++) { // 4 spears to a pit
if (one_in(3))
g->m.add_item(x, y, g->itypes[itm_spear_wood], g->turn);
}
}
}
g->u.add_disease(DI_IN_PIT, -1, g);
}
void trapfuncm::pit_spikes(game *g, monster *z, int x, int y)
{
int junk;
bool sees = g->u_see(z, junk);
if (sees)
g->add_msg("The %s falls in a spiked pit!", z->name().c_str());
if (z->hurt(rng(20, 50)))
g->kill_mon(g->mon_at(x, y));
else
z->moves = -1000;
if (one_in(4)) {
if (sees)
g->add_msg("The spears break!");
g->m.ter(x, y) = t_pit;
g->m.tr_at(x, y) = tr_pit;
for (int i = 0; i < 4; i++) { // 4 spears to a pit
if (one_in(3))
g->m.add_item(x, y, g->itypes[itm_spear_wood], g->turn);
}
}
}
void trapfunc::lava(game *g, int x, int y)
{
g->add_msg("The %s burns you horribly!", g->m.tername(x, y).c_str());
g->u.hit(g, bp_feet, 0, 0, 20);
g->u.hit(g, bp_feet, 1, 0, 20);
g->u.hit(g, bp_legs, 0, 0, 20);
g->u.hit(g, bp_legs, 1, 0, 20);
}
void trapfuncm::lava(game *g, monster *z, int x, int y)
{
int junk;
bool sees = g->u_see(z, junk);
if (sees)
g->add_msg("The %s burns the %s!", g->m.tername(x, y).c_str(),
z->name().c_str());
int dam = 30;
if (z->made_of(FLESH))
dam = 50;
if (z->made_of(VEGGY))
dam = 80;
if (z->made_of(PAPER) || z->made_of(LIQUID) || z->made_of(POWDER) ||
z->made_of(WOOD) || z->made_of(COTTON) || z->made_of(WOOL))
dam = 200;
if (z->made_of(STONE))
dam = 15;
if (z->made_of(KEVLAR) || z->made_of(STEEL))
dam = 5;
z->hurt(dam);
}
void trapfunc::sinkhole(game *g, int x, int y)
{
g->add_msg("You step into a sinkhole, and start to sink down!");
if (g->u.has_amount(itm_rope_30, 1) &&
query_yn("Throw your rope to try to catch soemthing?")) {
int throwroll = rng(g->u.skillLevel("throw"),
g->u.skillLevel("throw") + g->u.str_cur + g->u.dex_cur);
if (throwroll >= 12) {
g->add_msg("The rope catches something!");
if (rng(g->u.skillLevel("unarmed"),
g->u.skillLevel("unarmed") + g->u.str_cur) > 6) {
// Determine safe places for the character to get pulled to
std::vector<point> safe;
for (int i = g->u.posx - 1; i <= g->u.posx + 1; i++) {
for (int j = g->u.posx - 1; j <= g->u.posx + 1; j++) {
if (g->m.move_cost(i, j) > 0 && g->m.tr_at(i, j) != tr_pit)
safe.push_back(point(i, j));
}
}
if (safe.size() == 0) {
g->add_msg("There's nowhere to pull yourself to, and you sink!");
g->u.use_amount(itm_rope_30, 1);
g->m.add_item(g->u.posx + rng(-1, 1), g->u.posy + rng(-1, 1),
g->itypes[itm_rope_30], g->turn);
g->m.tr_at(g->u.posx, g->u.posy) = tr_pit;
g->vertical_move(-1, true);
} else {
g->add_msg("You pull yourself to safety! The sinkhole collapses.");
int index = rng(0, safe.size() - 1);
g->u.posx = safe[index].x;
g->u.posy = safe[index].y;
g->update_map(g->u.posx, g->u.posy);
g->m.tr_at(g->u.posx, g->u.posy) = tr_pit;
}
} else {
g->add_msg("You're not strong enough to pull yourself out...");
g->u.moves -= 100;
g->u.use_amount(itm_rope_30, 1);
g->m.add_item(g->u.posx + rng(-1, 1), g->u.posy + rng(-1, 1),
g->itypes[itm_rope_30], g->turn);
g->vertical_move(-1, true);
}
} else {
g->add_msg("Your throw misses completely, and you sink!");
if (one_in((g->u.str_cur + g->u.dex_cur) / 3)) {
g->u.use_amount(itm_rope_30, 1);
g->m.add_item(g->u.posx + rng(-1, 1), g->u.posy + rng(-1, 1),
g->itypes[itm_rope_30], g->turn);
}
g->m.tr_at(g->u.posx, g->u.posy) = tr_pit;
g->vertical_move(-1, true);
}
} else {
g->add_msg("You sink into the sinkhole!");
g->vertical_move(-1, true);
}
}
void trapfunc::ledge(game *g, int x, int y)
{
g->add_msg("You fall down a level!");
g->vertical_move(-1, true);
}
void trapfunc::airhole(game *g, int x, int y)
{
g->add_msg("You fall down a level!");
g->vertical_move(-1, true);
}
void trapfuncm::ledge(game *g, monster *z, int x, int y)
{
g->add_msg("The %s falls down a level!", z->name().c_str());
g->kill_mon(g->mon_at(x, y));
}
void trapfuncm::airhole(game *g, monster *z, int x, int y)
{
g->add_msg("The %s falls down a level!", z->name().c_str());
g->kill_mon(g->mon_at(x, y));
}
void trapfunc::temple_flood(game *g, int x, int y)
{
g->add_msg("You step on a loose tile, and water starts to flood the room!");
for (int i = 0; i < SEEX * MAPSIZE; i++) {
for (int j = 0; j < SEEY * MAPSIZE; j++) {
if (g->m.tr_at(i, j) == tr_temple_flood)
g->m.tr_at(i, j) = tr_null;
}
}
g->add_event(EVENT_TEMPLE_FLOOD, g->turn + 3);
}
void trapfunc::temple_toggle(game *g, int x, int y)
{
g->add_msg("You hear the grinding of shifting rock.");
ter_id type = g->m.ter(x, y);
for (int i = 0; i < SEEX * MAPSIZE; i++) {
for (int j = 0; j < SEEY * MAPSIZE; j++) {
switch (type) {
case t_floor_red:
if (g->m.ter(i, j) == t_rock_green)
g->m.ter(i, j) = t_floor_green;
else if (g->m.ter(i, j) == t_floor_green)
g->m.ter(i, j) = t_rock_green;
break;
case t_floor_green:
if (g->m.ter(i, j) == t_rock_blue)
g->m.ter(i, j) = t_floor_blue;
else if (g->m.ter(i, j) == t_floor_blue)
g->m.ter(i, j) = t_rock_blue;
break;
case t_floor_blue:
if (g->m.ter(i, j) == t_rock_red)
g->m.ter(i, j) = t_floor_red;
else if (g->m.ter(i, j) == t_floor_red)
g->m.ter(i, j) = t_rock_red;
break;
}
}
}
}
void trapfunc::glow(game *g, int x, int y)
{
if (one_in(3)) {
g->add_msg("You're bathed in radiation!");
g->u.radiation += rng(10, 30);
} else if (one_in(4)) {
g->add_msg("A blinding flash strikes you!");
g->flashbang(g->u.posx, g->u.posy);
} else
g->add_msg("Small flashes surround you.");
}
void trapfuncm::glow(game *g, monster *z, int x, int y)
{
if (one_in(3)) {
z->hurt( rng(5, 10) );
z->speed *= .9;
}
}
void trapfunc::hum(game *g, int x, int y)
{
int volume = rng(1, 200);
std::string sfx;
if (volume <= 10)
sfx = "hrm";
else if (volume <= 50)
sfx = "hrmmm";
else if (volume <= 100)
sfx = "HRMMM";
else
sfx = "VRMMMMMM";
g->sound(x, y, volume, sfx);
}
void trapfuncm::hum(game *g, monster *z, int x, int y)
{
int volume = rng(1, 200);
std::string sfx;
if (volume <= 10)
sfx = "hrm";
else if (volume <= 50)
sfx = "hrmmm";
else if (volume <= 100)
sfx = "HRMMM";
else
sfx = "VRMMMMMM";
if (volume >= 150)
z->add_effect(ME_DEAF, volume - 140);
g->sound(x, y, volume, sfx);
}
void trapfunc::shadow(game *g, int x, int y)
{
monster spawned(g->mtypes[mon_shadow]);
int tries = 0, monx, mony, junk;
do {
if (one_in(2)) {
monx = rng(g->u.posx - 5, g->u.posx + 5);
mony = (one_in(2) ? g->u.posy - 5 : g->u.posy + 5);
} else {
monx = (one_in(2) ? g->u.posx - 5 : g->u.posx + 5);
mony = rng(g->u.posy - 5, g->u.posy + 5);
}
} while (tries < 5 && !g->is_empty(monx, mony) &&
!g->m.sees(monx, mony, g->u.posx, g->u.posy, 10, junk));
if (tries < 5) {
g->add_msg("A shadow forms nearby.");
spawned.sp_timeout = rng(2, 10);
spawned.spawn(monx, mony);
g->z.push_back(spawned);
g->m.tr_at(x, y) = tr_null;
}
}
void trapfunc::drain(game *g, int x, int y)
{
g->add_msg("You feel your life force sapping away.");
g->u.hurtall(1);
}
void trapfuncm::drain(game *g, monster *z, int x, int y)
{
z->hurt(1);
}
void trapfunc::snake(game *g, int x, int y)
{
if (one_in(3)) {
monster spawned(g->mtypes[mon_shadow_snake]);
int tries = 0, monx, mony, junk;
do {
if (one_in(2)) {
monx = rng(g->u.posx - 5, g->u.posx + 5);
mony = (one_in(2) ? g->u.posy - 5 : g->u.posy + 5);
} else {
monx = (one_in(2) ? g->u.posx - 5 : g->u.posx + 5);
mony = rng(g->u.posy - 5, g->u.posy + 5);
}
} while (tries < 5 && !g->is_empty(monx, mony) &&
!g->m.sees(monx, mony, g->u.posx, g->u.posy, 10, junk));
if (tries < 5) {
g->add_msg("A shadowy snake forms nearby.");
spawned.spawn(monx, mony);
g->z.push_back(spawned);
g->m.tr_at(x, y) = tr_null;
return;
}
}
g->sound(x, y, 10, "ssssssss");
if (one_in(6))
g->m.tr_at(x, y) = tr_null;
}
void trapfuncm::snake(game *g, monster *z, int x, int y)
{
g->sound(x, y, 10, "ssssssss");
if (one_in(6))
g->m.tr_at(x, y) = tr_null;
}
bool trap::is_benign()
{
if (id == tr_rollmat || id == tr_cot)
return true;
else
return false;
}
| [
"codepublic@charter.net"
] | codepublic@charter.net |
73d390b2855ecd39f3140f85c2e73c56bb4f384f | 454c964ab7dd6a8258632bdf3ab9e6eeafd71872 | /source/TouchButton.cpp | ab08450c01cb0382783b1ec88953488c72b749f6 | [] | no_license | fizzyfrosty/FuzzyCubesUniversalHD | bebc023769173a5debd6299acd733f6477d355bf | 1d8b95f6687be5b9fad1b8cc0941ebcbca2818d6 | refs/heads/master | 2020-05-29T14:32:12.210893 | 2014-04-04T02:18:40 | 2014-04-04T02:18:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,305 | cpp | #include "TouchButton.h"
TouchButton::TouchButton(void)
{
pressed = false;
initialPressed = false;
enabled = true;
x = 0;
y = 0;
}
TouchButton::~TouchButton(void)
{
}
bool TouchButton::isPressed( int16 x, int16 y )
{
if( enabled == true )
{
// sets the hitbox for the button, determines if it's pressed
if( x > this->x - hitboxWidth/2 && x < this->x + hitboxWidth/2 && y > this->y - hitboxHeight/2 && y < this->y + hitboxHeight/2 )
return true;
else
return false;
}
else
{
return false; // set as not touched if false
}
}
void TouchButton::Render()
{
if( enabled == true ) // only render if the button is enabled
{
if( pressed == false )
{
unpressedSprite.setPosition( x, y );
unpressedSprite.Render();
}
else if( pressed == true )
{
pressedSprite.setPosition( x, y );
pressedSprite.Render();
}
}
}
void TouchButton::setLocation( int16 x, int16 y )
{
this->x = x;
this->y = y;
}
void TouchButton::setTouchSize( int16 w, int16 h )
{
hitboxWidth = w;
hitboxHeight = h;
}
void TouchButton::setRenderSize( int16 w, int16 h )
{
pressedSprite.setSize( w, h );
unpressedSprite.setSize( w, h );
}
void TouchButton::setUnpressedSprite( Sprite s )
{
unpressedSprite = s;
}
void TouchButton::setPressedSprite( Sprite s )
{
pressedSprite = s;
} | [
"fizzyfrosty@yahoo.com"
] | fizzyfrosty@yahoo.com |
9f794de3c23a5ccd76aa5e785aa032e3d73841c7 | 617296ef3936724a88be5a2e6023aa363cb93d1d | /backup/新建文件夹/word.cpp | 59b50bfb2c9eab3a55a95ca380251f05d2793291 | [] | no_license | Melos17/Lex | d2fc204fb383a9677c72cd380e410f4adc2c0a9a | 89f1e63ddee89063373cdf10744a170b57ea63a9 | refs/heads/master | 2023-01-06T03:21:10.782944 | 2020-11-03T11:51:01 | 2020-11-03T11:51:01 | 309,675,249 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,115 | cpp | #include "word.h"
enum TOKEN_TYPE {
Unknown = -1,
Parenthese_Left = '(', Parenthese_Right = ')',
Bracket_Left = '[', Bracket_Right = ']',
Star = '*',
Plus = '+',
Question = '?',
VerticalLine = '|',
Dot = '.',
Hyphen = '-',
Caret = '^',
Normal_Character = 128,
Escape_Character,
// no support currently.
Brace_Left, Brace_Right, // {}
Dollar, // $
Comma, // ,
Number, // 0-9
};
int RegexWord::runRelativeCode(int type) {
switch( type ) {
case 0:
{ return(Parenthese_Left); }
break;
case 1:
{ return(Parenthese_Right); }
break;
case 2:
{ return(Bracket_Left); }
break;
case 3:
{ return(Bracket_Right); }
break;
case 4:
{ return(Star); }
break;
case 5:
{ return(Plus); }
break;
case 6:
{ return(Question); }
break;
case 7:
{ return(VerticalLine); }
break;
case 8:
{ return(Dot); }
break;
case 9:
{ return(Hyphen); }
break;
case 10:
{ return(Caret); }
break;
case 11:
{ return(Normal_Character); }
break;
case 12:
{ return(Escape_Character); }
break;
}
return -1;
}
| [
"melos17@qq.com"
] | melos17@qq.com |
e7c3ad2d7214f48168548eee42907bd0498b6911 | 4121fe2de9aec21141bc70d52b857a8090289a40 | /Interfaz/Prueba/Tools.cpp | c1053a34adccc8fa361888f62fddf5daf330858f | [] | no_license | david-ponc/PDI | 63accf247abbc7d27ea7c92406ee9d61487cca30 | 31473ecb9909f09757cb989deacf9cd46c1e43be | refs/heads/master | 2022-06-19T15:31:24.550421 | 2020-04-19T22:54:21 | 2020-04-19T22:54:21 | 242,806,159 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,726 | cpp | #include "Tools.h"
Image Tools::HistogramRGB(Image img) {
Image histo;
histo.Create(256,256,255, "", "histogramaRGB");
int histoR[256] = {0}, histoG[256] = {0}, histoB[256] = {0};
int maxR = 0, maxG = 0, maxB = 0, max = 0;
for(int i = 0; i < img.height; i++) {
for(int j = 0; j < img.width; j++) {
histoR[img.pixels[i][j].R]++;
histoG[img.pixels[i][j].G]++;
histoB[img.pixels[i][j].B]++;
}
}
for(int i = 0; i < 256; i++) {
if(histoR[i] > maxR) {
maxR = histoR[i];
}
if(histoG[i] > maxG) {
maxG = histoG[i];
}
if(histoB[i] > maxB) {
maxB = histoB[i];
}
}
max = maxR;
if(max < maxG)
max = maxG;
if(max < maxB)
max = maxB;
for(int j = 0; j < histo.width; j++) {
int normalR = (histoR[j] * 100) / max;
normalR = histo.height - ((normalR * histo.height) / 100);
int normalG = (histoG[j] * 100) / max;
normalG = histo.height - ((normalG * histo.height) / 100);
int normalB = (histoB[j] * 100) / max;
normalB = histo.height - ((normalB * histo.height) / 100);
SolidGraph(normalR, histo, "R", j);
SolidGraph(normalG, histo, "G", j);
SolidGraph(normalB, histo, "B", j);
}
return histo;
}
void Tools::SolidGraph(int normal, Image histo, QString channel, int j) {
for(int i = normal; i < histo.height; i++) {
if(channel == "R") {
histo.pixels[i][j].R = 255;
}else if(channel == "G") {
histo.pixels[i][j].G = 255;
}else if(channel == "B") {
histo.pixels[i][j].B = 255;
}
}
}
| [
"buap.david@gmail.com"
] | buap.david@gmail.com |
5d1741e362d0165ad09e1bdb76ac79cbd6784100 | 9556ebced20e46c57e9827f671d6026b180e02bd | /ioComponents/DRAMsim/DRAM_config.cc | cc245f3c1c5b616bde3380dd6c50f3345700977a | [] | no_license | lebiednik/PhoenixSim | fedb066194da5edb4a351608e34ac536ddfab228 | c4254118cbdb07c6ff91b5bc0da7b43bd0b84a2e | refs/heads/master | 2021-01-12T04:00:43.153824 | 2017-01-26T15:27:25 | 2017-01-26T15:27:25 | 77,463,750 | 5 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 26,592 | cc | #include "DRAM_config.h"
#include "TransactionQueue.h"
DRAM_config::DRAM_config(){
dram_power_config = NULL;
init_dram_system_configuration();
}
void DRAM_config::init_dram_system_configuration(){
int i;
set_dram_type(SDRAM); /* explicitly initialize the variables */
set_dram_frequency(100); /* explicitly initialize the variables */
set_memory_frequency(100); /* explicitly initialize the variables */
set_dram_channel_count(1); /* single channel of memory */
set_dram_channel_width(8); /* 8 byte wide data bus */
set_pa_mapping_policy(SDRAM_BASE_MAP); /* generic mapping policy */
set_dram_transaction_granularity(64); /* 64 bytes long cachelines */
set_dram_row_buffer_management_policy(OPEN_PAGE);
set_cpu_memory_frequency_ratio();
set_transaction_selection_policy(FCFS);
strict_ordering_flag = FALSE;
packet_count = MAX(1,(cacheline_size / (channel_width * 8 )));
t_burst = cacheline_size / (channel_width);
auto_refresh_enabled = TRUE;
refresh_policy = REFRESH_ONE_CHAN_ONE_RANK_ALL_BANK;
refresh_issue_policy = REFRESH_OPPORTUNISTIC;
refresh_time = 100;
refresh_cycle_count = 10000;
dram_debug_flag = FALSE;
addr_debug_flag = FALSE;
wave_debug_flag = FALSE;
wave_cas_debug_flag = FALSE;
issue_debug_flag = FALSE;
var_latency_flag = FALSE;
watch_refresh = FALSE;
memory2dram_freq_ratio = 1;
arrival_threshold = 1500;
/** Just setup the default types for FBD stuff too **/
data_cmd_count = MAX(1,cacheline_size/DATA_BYTES_PER_WRITE_BUNDLE);
drive_cmd_count = 1;
num_thread_sets = 1;
thread_sets[0] = 32;
max_tq_size = MAX_TRANSACTION_QUEUE_DEPTH;
single_rank = true;
t_cmd = 0;
bus_queue_depth = 0;
set_independent_threads();
}
/* Dumps the DRAM configuration. */
void DRAM_config::dump_config(FILE *stream)
{
fprintf(stream, "===================== DRAM config ======================\n");
print_dram_type( dram_type, stream );
fprintf(stream, " dram_frequency: %d MHz\n", dram_type != FBD_DDR2 ? memory_frequency : dram_frequency );
fprintf(stream, " memory_frequency: %d MHz\n", memory_frequency);
fprintf(stream, " cpu_frequency: %d MHz\n", get_cpu_frequency());
fprintf(stream, " dram_clock_granularity: %d\n", dram_clock_granularity);
fprintf(stream, " memfreq2cpufreq ration: %f \n", (float)mem2cpu_clock_ratio);
fprintf(stream, " memfreq2dramfreq ration: %f \n", memory2dram_freq_ratio);
fprintf(stream, " critical_word_first_flag: %d\n", critical_word_first_flag);
print_pa_mapping_policy( physical_address_mapping_policy, stream);
print_row_policy( row_buffer_management_policy, stream);
print_trans_policy( get_transaction_selection_policy(), stream);
fprintf(stream, " cacheline_size: %d\n", cacheline_size);
fprintf(stream, " chan_count: %d\n", channel_count);
fprintf(stream, " rank_count: %d\n", rank_count);
fprintf(stream, " bank_count: %d\n", bank_count);
fprintf(stream, " row_count: %d\n", row_count);
fprintf(stream, " col_count: %d\n", col_count);
fprintf(stream, " buffer count: %d\n", up_buffer_cnt);
fprintf(stream, " t_rcd: %d\n", t_rcd);
fprintf(stream, " t_cac: %d\n", t_cac);
fprintf(stream, " t_cas: %d\n", t_cas);
fprintf(stream, " t_ras: %d\n", t_ras);
fprintf(stream, " t_rp: %d\n", t_rp);
fprintf(stream, " t_cwd: %d\n", t_cwd);
fprintf(stream, " t_rtr: %d\n", t_rtr);
fprintf(stream, " t_burst: %d\n", t_burst);
fprintf(stream, " t_rc: %d\n", t_rc);
fprintf(stream, " t_rfc: %d\n", t_rfc);
fprintf(stream, " t_al: %d\n", t_al);
fprintf(stream, " t_wr: %d\n", t_wr);
fprintf(stream, " t_rtp: %d\n", t_rtp);
fprintf(stream, " t_dqs: %d\n", t_dqs);
// FBDIMM RELATED
fprintf(stream, " t_amb_up: %d\n", t_amb_up);
fprintf(stream, " t_amb_down: %d\n", t_amb_down);
fprintf(stream, " t_bundle: %d\n", t_bundle);
fprintf(stream, " t_bus: %d\n", t_bus);
fprintf(stream, " posted_cas: %d\n", posted_cas_flag);
fprintf(stream, " row_command_duration: %d\n", row_command_duration);
fprintf(stream, " col_command_duration: %d\n", col_command_duration);
// REFRESH POLICY
fprintf(stream, " auto_refresh_enabled: %d\n", auto_refresh_enabled);
fprintf(stream, " auto_refresh_policy: %d\n", refresh_policy);
fprintf(stream, " refresh_time: %f\n", refresh_time);
fprintf(stream, " refresh_cycle_count: %d\n", refresh_cycle_count);
fprintf(stream, " strict_ordering_flag: %d\n", strict_ordering_flag);
// DEBUG
fprintf(stream, " dram_debug: %d\n", dram_debug_flag);
fprintf(stream, " addr_debug: %d\n", addr_debug_flag);
fprintf(stream, " wave_debug: %d\n", wave_debug_flag);
fprintf(stream, "========================================================\n\n\n");
}
/**
* All cycles in the config file are in terms of dram cycles.
* This converts everything in terms of memory controller cycles.
*/
void DRAM_config::convert_config_dram_cycles_to_mem_cycles(){
// Not sure wher to put this -> but it needs to be done
t_cac = t_cas - col_command_duration;
t_ras*=(int)memory2dram_freq_ratio; /* interval between ACT and PRECHARGE to same bank */
t_rcd*=(int)memory2dram_freq_ratio; /* RAS to CAS delay of same bank */
t_cas*=(int)memory2dram_freq_ratio; /* delay between start of CAS command and start of data burst */
t_cac*=(int)memory2dram_freq_ratio; /* delay between end of CAS command and start of data burst*/
t_rp*=(int)memory2dram_freq_ratio; /* interval between PRECHARGE and ACT to same bank */
/* t_rc is simply t_ras + t_rp */
t_rc*=(int)memory2dram_freq_ratio;
t_rfc*=(int)memory2dram_freq_ratio;
t_cwd*=(int)memory2dram_freq_ratio; /* delay between end of CAS Write command and start of data packet */
t_rtr*=(int)memory2dram_freq_ratio; /* delay between start of CAS Write command and start of write retirement command*/
t_burst*=(int)memory2dram_freq_ratio; /* number of cycles utilized per cacheline burst */
t_al*=(int)memory2dram_freq_ratio; /* additive latency = t_rcd - 2 (ddr half cycles) */
t_rl*=(int)memory2dram_freq_ratio; /* read latency = t_al + t_cas */
t_wr*=(int)memory2dram_freq_ratio; /* write recovery time latency, time to restore data o cells */
t_rtp*=(int)memory2dram_freq_ratio; /* write recovery time latency, time to restore data o cells */
//t_bus*=(int)memory2dram_freq_ratio; /* FBDIMM - bus delay */
t_amb_up*=(int)memory2dram_freq_ratio; /* FBDIMM - Amb up delay */
t_amb_down*=(int)memory2dram_freq_ratio; /* FBDIMM - Amb down delay */
//t_bundle*=(int)memory2dram_freq_ratio; /* FBDIMM number of cycles utilized to transmit a bundle */
row_command_duration*=(int)memory2dram_freq_ratio; // originally 2 -> goest to 12
col_command_duration*=(int)memory2dram_freq_ratio;
t_dqs*=(int)memory2dram_freq_ratio; /* rank hand off penalty. 0 for SDRAM, 2 for DDR, */
refresh_cycle_count*=(int)memory2dram_freq_ratio;
return;
}
/*
* set configurations for specific DRAM Systems.
*
* We set the init here so we can use 16 256Mbit parts to get 512MB of total memory
*/
void DRAM_config::set_dram_type(int type){ /* SDRAM, DDR RDRAM etc */
dram_type = type;
if (dram_type == SDRAM){ /* PC100 SDRAM -75 chips. nominal timing assumed */
channel_width = 8; /* bytes */
set_dram_frequency(100);
row_command_duration = 1; /* cycles */
col_command_duration = 1; /* cycles */
rank_count = 4; /* for SDRAM and DDR SDRAM, rank_count is DIMM-bank count */
/* Micron 256 Mbit SDRAM chip data sheet -75 specs used */
bank_count = 4; /* per rank */
row_count = 8*1024;
col_count = 512;
t_ras = 5; /* actually 44ns, so that's 5 cycles */
t_rp = 2; /* actually 20ns, so that's 2 cycles */
t_rcd = 2; /* actually 20 ns, so that's only 2 cycles */
t_cas = 2; /* this is CAS, use 2 */
t_al = 0;
t_cac = t_cas - col_command_duration; /* delay in between CAS command and start of read data burst */
t_cwd = -1; /* SDRAM has no write delay . -1 cycles between end of CASW command and data placement on data bus*/
t_rtr = 0; /* SDRAM has no write delay, no need for retire packet */
t_dqs = 0;
t_rc = t_ras + t_rp;
t_rfc = t_rc;
t_wr = 2;
t_rtp = 1;
posted_cas_flag = 0;
up_buffer_cnt = 0;
t_amb_up = 0;
t_amb_down = 0;
t_bundle = 0;
t_bus = 0;
tq_delay = 2; /* 2 DRAM ticks of delay @ 100 MHz = 20ns */
max_tq_size = MAX_TRANSACTION_QUEUE_DEPTH;
critical_word_first_flag= TRUE;
dram_clock_granularity = 1;
} else if (dram_type == DDRSDRAM){
channel_width = 8;
set_dram_frequency(200);
row_command_duration = 1 * 2; /* cycles */
col_command_duration = 1 * 2; /* cycles */
rank_count = 4; /* for SDRAM and DDR SDRAM, rank_count is DIMM-bank count */
bank_count = 4; /* per rank */
row_count = 8*1024;
col_count = 512;
t_ras = 5 * 2;
t_rp = 2 * 2;
t_al = 0;
t_rcd = 2 * 2;
t_cas = 2 * 2;
t_cac = t_cas - col_command_duration; /* delay in between CAS command and start of read data burst */
t_cwd = 0 * 2; /* not really write delay, but it's the DQS delay */
t_rtr = 0;
t_dqs = 2;
t_rc = t_ras + t_rp;
t_rfc = t_rc;
t_wr = 2; /* FIXME */
t_rtp = 2;
tq_delay =2*2; /* 4 DRAM ticks of delay @ 200 MHz = 20ns */
max_tq_size = MAX_TRANSACTION_QUEUE_DEPTH;
critical_word_first_flag= TRUE;
dram_clock_granularity = 2; /* DDR clock granularity */
} else if (dram_type == DDR2 || dram_type == DDR3 ){
channel_width = 8; /* bytes */
set_dram_frequency(400);
row_command_duration = 1 * 2; /* cycles */
col_command_duration = 1 * 2; /* cycles */
rank_count = 4; /* for SDRAM and DDR SDRAM, rank_count is DIMM-bank count */
bank_count = 4; /* per rank , 8 banks in near future.*/
row_count = 8*1024;
col_count = 512;
t_ras = 9 * 2; /* 45ns @ 400 mbps is 18 cycles */
t_rp = 3 * 2; /* 15ns @ 400 mpbs is 6 cycles */
t_rcd = 3 * 2;
t_cas = 3 * 2;
t_al = 0;
t_cac = t_cas - col_command_duration; /* delay in between CAS command and start of read data burst */
t_cwd = t_cac;
t_rtr = 0;
t_dqs = 1 * 2;
t_rc = t_ras + t_rp;
t_rfc = 51; // 127.5 ns
t_wr = 2; /* FIXME */
t_rtp = 6;
t_rl = t_al + t_cas;
t_rrd = 0;
t_faw = 0;
tq_delay =2*2; /* 4 DRAM ticks of delay @ 200 MHz = 20ns */
max_tq_size = MAX_TRANSACTION_QUEUE_DEPTH;
critical_word_first_flag= TRUE;
dram_clock_granularity = 2; /* DDR clock granularity */
cas_with_prec = true;
} else if (dram_type == FBD_DDR2) {
up_channel_width = 10; /* bits */
down_channel_width = 14; /* bits */
set_dram_channel_width(8); /* 8 byte wide data bus */
set_memory_frequency(1600);
set_dram_frequency(400);
memory2dram_freq_ratio = memory_frequency/dram_frequency;
row_command_duration = 1 * 2; /* cycles */
col_command_duration = 1 * 2; /* cycles */
rank_count = 4; /* for SDRAM and DDR SDRAM, rank_count is DIMM-bank count */
bank_count = 4; /* per rank , 8 banks in near future.*/
row_count = 8*1024;
col_count = 512;
t_ras = 9 * 2; /* 45ns @ 400 mbps is 18 cycles */
t_rp = 3 * 2; /* 15ns @ 400 mpbs is 6 cycles */
t_rcd = 3 * 2;
t_cas = 3 * 2;
t_cac = t_cas - col_command_duration; /* delay in between CAS command and start of read data burst */
t_cwd = t_cac;
t_al = 0;
t_rtr = 0;
t_dqs = 0;
t_rc = t_ras + t_rp;
t_rfc = 51; // 127.5 ns
t_wr = 12; /* FIXME */
t_rtp = 8;
t_amb_up = 6; /*** Arbitrary Value FIXME **/
t_amb_down = 6; /*** Arbitrary Value FIXME **/
up_buffer_cnt = 4; /** Set to as many up buffers as ther are banks in the rank **/
down_buffer_cnt = 4; /** Set to as many up buffers as ther are banks in the rank **/
tq_delay =2*2; /* 4 DRAM ticks of delay @ 200 MHz = 20ns */
max_tq_size = MAX_TRANSACTION_QUEUE_DEPTH;
critical_word_first_flag= FALSE;
dram_clock_granularity = 2; /* DDR clock granularity */
data_cmd_count = MAX(1,cacheline_size/DATA_BYTES_PER_WRITE_BUNDLE);
drive_cmd_count = 1;
//refresh_policy = REFRESH_ONE_CHAN_ONE_RANK_ONE_BANK;
refresh_time = 100;
refresh_cycle_count = 10000;
cas_with_prec = true;
}
else {
fprintf(stdout,"Unknown memory type %d\n",dram_type);
exit(3);
}
}
int DRAM_config::get_dram_type(){ /* SDRAM, DDR RDRAM etc */
return dram_type;
}
void DRAM_config::set_chipset_delay(int delay){
tq_delay = MAX(1,delay);
}
/*******************************************
* FBDIMM - This is the frequency of the DRAM
* For all other configurations the frequency of the
* DRAM is the freq of the memory controller.
* *****************************************/
void DRAM_config::set_dram_frequency(int freq){
if (dram_type != FBD_DDR2) {
if(freq < MIN_DRAM_FREQUENCY){
memory_frequency = MIN_DRAM_FREQUENCY; /* MIN DRAM freq */
} else if (freq > MAX_DRAM_FREQUENCY){
memory_frequency = MAX_DRAM_FREQUENCY; /* MAX DRAM freq */
} else {
memory_frequency = freq;
}
dram_frequency = memory_frequency;
}
else if(freq < MIN_DRAM_FREQUENCY){
dram_frequency = MIN_DRAM_FREQUENCY; /* MIN DRAM freq */
} else if (freq > MAX_DRAM_FREQUENCY){
dram_frequency = MAX_DRAM_FREQUENCY; /* MAX DRAM freq */
} else {
dram_frequency = freq;
}
memory2dram_freq_ratio = (float)memory_frequency/dram_frequency;
if(dram_power_config != NULL)
dram_power_config->update(freq);
}
void DRAM_config::set_posted_cas(bool flag){
posted_cas_flag = flag;
}
int DRAM_config::get_dram_frequency(){
return dram_frequency;
}
int DRAM_config::get_memory_frequency(){
return memory_frequency;
}
void DRAM_config::set_memory_frequency(int freq) { /* FBD-DIMM only*/
if(freq < MIN_DRAM_FREQUENCY){
memory_frequency = MIN_DRAM_FREQUENCY; /* MIN DRAM freq */
} else if (freq > MAX_DRAM_FREQUENCY){
memory_frequency = MAX_DRAM_FREQUENCY; /* MAX DRAM freq */
} else {
memory_frequency = freq;
}
set_cpu_memory_frequency_ratio( );
}
int DRAM_config::get_dram_channel_count(){ /* set 1 <= channel_count <= MAX_CHANNEL_COUNT */
return channel_count;
}
void DRAM_config::set_dram_channel_count(int count){ /* set 1 <= channel_count <= MAX_CHANNEL_COUNT */
channel_count = MIN(MAX(1,count),MAX_CHANNEL_COUNT);
}
int DRAM_config::get_dram_rank_count(){ /* set 1 <= channel_count <= MAX_CHANNEL_COUNT */
return rank_count;
}
void DRAM_config::set_dram_rank_count(int count){ /* set 1 <= channel_count <= MAX_CHANNEL_COUNT */
rank_count = MIN(MAX(1,count),MAX_RANK_COUNT);
}
void DRAM_config::set_dram_bank_count(int count){ /* set 1 <= channel_count <= MAX_CHANNEL_COUNT */
bank_count = count;
}
int DRAM_config::get_dram_bank_count(){ /* set 1 <= channel_count <= MAX_CHANNEL_COUNT */
return bank_count;
}
int DRAM_config::get_dram_row_buffer_management_policy(){ /* set 1 <= channel_count <= MAX_CHANNEL_COUNT */
return row_buffer_management_policy;
}
void DRAM_config::set_dram_row_count(int count){ /* set 1 <= channel_count <= MAX_CHANNEL_COUNT */
row_count = count;
}
void DRAM_config::set_dram_buffer_count(int count){ /* set 1 <= channel_count <= MAX_CHANNEL_COUNT */
up_buffer_cnt= MIN(MAX(1,count),MAX_AMB_BUFFER_COUNT);
down_buffer_cnt= MIN(MAX(1,count),MAX_AMB_BUFFER_COUNT);
}
int DRAM_config::get_dram_row_count(){
return row_count;
}
int DRAM_config::get_dram_col_count(){
return col_count;
}
void DRAM_config::set_dram_col_count(int count){ /* set 1 <= channel_count <= MAX_CHANNEL_COUNT */
col_count = count;
}
void DRAM_config::set_dram_channel_width(int width){
channel_width = MAX(MIN_CHANNEL_WIDTH,width); /* smallest width is 2 bytes */
t_burst = MAX(1,cacheline_size / channel_width);
}
void DRAM_config::set_dram_transaction_granularity(int size){
cacheline_size = MAX(MIN_CACHE_LINE_SIZE,size); /*bytes */
t_burst = MAX(1,cacheline_size / channel_width);
data_cmd_count = MAX(1,cacheline_size/DATA_BYTES_PER_WRITE_BUNDLE);
}
void DRAM_config::set_pa_mapping_policy(int policy){
physical_address_mapping_policy = policy;
}
void DRAM_config::set_dram_row_buffer_management_policy(int policy){
row_buffer_management_policy = policy;
}
void DRAM_config::set_dram_refresh_policy(int policy){
refresh_policy = policy;
refresh_cycle_count = (tick_t)((refresh_time/row_count)*dram_frequency);
/* Time between each refresh command */
if (refresh_policy == REFRESH_ONE_CHAN_ONE_RANK_ONE_BANK)
refresh_cycle_count = refresh_cycle_count/(rank_count * bank_count);
else if (refresh_policy == REFRESH_ONE_CHAN_ONE_RANK_ALL_BANK)
refresh_cycle_count = refresh_cycle_count/(rank_count);
else if (refresh_policy == REFRESH_ONE_CHAN_ALL_RANK_ONE_BANK)
refresh_cycle_count = refresh_cycle_count/(bank_count);
}
void DRAM_config::set_dram_refresh_time(int time){
refresh_time = time;
refresh_cycle_count = (refresh_time/row_count)*dram_frequency;
/* Time between each refresh command */
if (refresh_policy == REFRESH_ONE_CHAN_ONE_RANK_ONE_BANK)
refresh_cycle_count = refresh_cycle_count/(rank_count * bank_count);
if (refresh_policy == REFRESH_ONE_CHAN_ONE_RANK_ALL_BANK)
refresh_cycle_count = refresh_cycle_count/(rank_count );
else if (refresh_policy == REFRESH_ONE_CHAN_ALL_RANK_ONE_BANK)
refresh_cycle_count = refresh_cycle_count/(bank_count);
}
/* oppourtunistic vs highest priority */
void DRAM_config::set_dram_refresh_issue_policy(int policy){
refresh_issue_policy = policy;
}
void DRAM_config::set_fbd_var_latency_flag(int value) {
if (value) {
var_latency_flag = true;
}else {
var_latency_flag = false;
}
}
void DRAM_config::set_dram_debug(int debug_status){
dram_debug_flag = debug_status;
}
void DRAM_config::set_issue_debug(int debug_status){
issue_debug_flag = debug_status;
}
void DRAM_config::set_addr_debug(int debug_status){
addr_debug_flag = debug_status;
}
void DRAM_config::set_wave_debug(int debug_status){
wave_debug_flag = debug_status;
}
void DRAM_config::set_wave_cas_debug(int debug_status){
wave_cas_debug_flag = debug_status;
}
void DRAM_config::set_bundle_debug(int debug_status){
bundle_debug_flag = debug_status;
}
void DRAM_config::set_amb_buffer_debug(int debug_status){
amb_buffer_debug_flag = debug_status;
}
/** FB-DIMM : set methods **/
void DRAM_config::set_dram_up_channel_width(int width) {
up_channel_width = width;
/** FIXME : Add code to set t_burst i.e. transmission time for data
* packets*/
}
void DRAM_config::set_dram_down_channel_width(int width) {
down_channel_width = width;
/** FIXME : Add code to set t_burst i.e. transmission time for data
* packets*/
}
void DRAM_config::set_t_bundle(int bundle) {
t_bundle = bundle;
}
void DRAM_config::set_t_bus(int bus) {
t_bus = bus;
}
/* This has to be enabled late */
void DRAM_config::enable_auto_refresh(int flag, int refresh_time_ms){
if(flag == TRUE){
auto_refresh_enabled = TRUE;
refresh_time = refresh_time_ms * 1000.0; /* input is in milliseconds, keep here in microseconds */
refresh_cycle_count = (int) (refresh_time * dram_frequency/row_count);
if (refresh_policy == REFRESH_ONE_CHAN_ONE_RANK_ONE_BANK)
refresh_cycle_count = refresh_cycle_count/(rank_count * bank_count);
if (refresh_policy == REFRESH_ONE_CHAN_ONE_RANK_ALL_BANK)
refresh_cycle_count = refresh_cycle_count/(rank_count );
else if (refresh_policy == REFRESH_ONE_CHAN_ALL_RANK_ONE_BANK)
refresh_cycle_count = refresh_cycle_count/(bank_count);
} else {
auto_refresh_enabled = FALSE;
}
}
void DRAM_config::set_independent_threads(){
int i;
int j;
int num_threads = 0;
for (i=0;i<num_thread_sets;i++) {
for (j=0;j<thread_sets[i];j++) {
thread_set_map[num_threads++] = i;
}
}
}
int DRAM_config::addr_debug(){
return (addr_debug_flag &&
(tq_info.transaction_id_ctr >= tq_info.debug_tran_id_threshold));
}
int DRAM_config::dram_debug(){
return (dram_debug_flag &&
(tq_info.transaction_id_ctr >= tq_info.debug_tran_id_threshold));
}
int DRAM_config::wave_debug(){
return (wave_debug_flag &&
(tq_info.transaction_id_ctr >= tq_info.debug_tran_id_threshold));
}
int DRAM_config::cas_wave_debug(){
return (wave_cas_debug_flag);
}
int DRAM_config::bundle_debug(){
return (bundle_debug_flag &&
(tq_info.transaction_id_ctr >= tq_info.debug_tran_id_threshold));
}
int DRAM_config::amb_buffer_debug(){
return (amb_buffer_debug_flag &&
(tq_info.transaction_id_ctr >= tq_info.debug_tran_id_threshold));
}
void DRAM_config::set_strict_ordering(int flag){
strict_ordering_flag = flag;
}
void DRAM_config::set_transaction_debug(int debug_status){
tq_info.debug_flag = debug_status;
}
void DRAM_config::set_debug_tran_id_threshold(uint64_t dtit){
tq_info.debug_tran_id_threshold = dtit;
}
void DRAM_config::set_tran_watch(uint64_t tran_id){
tq_info.tran_watch_flag = TRUE;
tq_info.tran_watch_id = tran_id;
}
int DRAM_config::get_tran_watch(uint64_t tran_id) {
return tq_info.tran_watch_flag &&
tq_info.tran_watch_id == tran_id;
}
void DRAM_config::set_ref_tran_watch(uint64_t tran_id){
watch_refresh = TRUE;
ref_tran_id = tran_id;
}
int DRAM_config::get_ref_tran_watch(uint64_t tran_id) {
return watch_refresh &&
ref_tran_id == tran_id;
}
void DRAM_config::print_dram_type( int dram_type, FILE *stream ) {
fprintf(stream, " dram_type: ");
switch( dram_type ) {
case SDRAM: fprintf(stream, "sdram\n");
break;
case DDRSDRAM: fprintf(stream, "ddrsdram\n");
break;
case DDR2: fprintf(stream, "ddr2\n");
break;
case DDR3: fprintf(stream, "ddr3\n");
break;
case FBD_DDR2: fprintf(stream, "fbd_ddr2\n");
break;
default: fprintf(stream, "unknown\n");
break;
}
}
void DRAM_config::print_pa_mapping_policy( int papolicy, FILE *stream ) {
fprintf(stream, " physical address mapping_policy: ");
switch( papolicy ) {
case BURGER_BASE_MAP: fprintf(stream, "burger_base_map\n");
break;
case BURGER_ALT_MAP: fprintf(stream, "burger_alt_map\n");
break;
case SDRAM_BASE_MAP: fprintf(stream, "sdram_base_map\n");
break;
case SDRAM_HIPERF_MAP: fprintf(stream, "sdram_hiperf_map\n");
break;
case INTEL845G_MAP: fprintf(stream, "intel845g_map\n");
break;
case SDRAM_CLOSE_PAGE_MAP: fprintf(stream, "sdram_close_page_map\n");
break;
default: fprintf(stream, "unknown\n");
break;
}
}
void DRAM_config::print_row_policy( int rowpolicy, FILE *stream ) {
fprintf(stream, " row_buffer_management_policy: ");
switch( rowpolicy ) {
case OPEN_PAGE: fprintf(stream, "open_page\n");
break;
case CLOSE_PAGE: fprintf(stream, "close_page\n");
break;
case PERFECT_PAGE: fprintf(stream, "perfect_page\n");
default: fprintf(stream, "unknown\n");
break;
}
}
void DRAM_config::print_refresh_policy( int refreshpolicy, FILE *stream ) {
fprintf(stream, " row_buffer_management_policy: ");
switch( refreshpolicy ) {
case REFRESH_ONE_CHAN_ALL_RANK_ALL_BANK: fprintf(stream, "refresh_one_chan_all_rank_all_bank\n");
break;
case REFRESH_ONE_CHAN_ALL_RANK_ONE_BANK: fprintf(stream, "refresh_one_chan_all_rank_one_bank\n");
break;
case REFRESH_ONE_CHAN_ONE_RANK_ONE_BANK: fprintf(stream, "refresh_one_chan_one_rank_one_bank\n");
default: fprintf(stream, "unknown\n");
break;
}
}
void DRAM_config::print_trans_policy( int policy, FILE *stream ) {
fprintf(stream, " transaction_selection_policy: ");
switch( policy ) {
case WANG: fprintf(stream, "wang\n");
break;
case LEAST_PENDING: fprintf(stream, "least pending\n");
break;
case MOST_PENDING: fprintf(stream, "most pending\n");
break;
case OBF: fprintf(stream, "open bank first\n");
break;
case RIFF: fprintf(stream, "Read Instruction Fetch First\n");
break;
case FCFS: fprintf(stream, "First Come first Serve\n");
break;
case GREEDY: fprintf(stream, "greedy\n");
break;
default: fprintf(stream, "unknown\n");
break;
}
}
void DRAM_config::set_cpu_frequency( int freq){
if(freq < MIN_CPU_FREQUENCY){
cpu_frequency = MIN_CPU_FREQUENCY;
fprintf(stdout,"\n\n\n\n\n\n\n\nWARNING: CPU frequency set to minimum allowed frequency [%d] MHz\n\n\n\n\n\n",cpu_frequency);
} else if (freq > MAX_CPU_FREQUENCY){
cpu_frequency = MAX_CPU_FREQUENCY;
fprintf(stdout,"\n\n\n\n\n\n\n\nWARNING: CPU frequency set to maximum allowed frequency [%d] MHz\n\n\n\n\n\n",cpu_frequency);
} else {
cpu_frequency = freq;
}
set_cpu_memory_frequency_ratio( );
}
int DRAM_config::get_cpu_frequency(){
return cpu_frequency;
}
/***
* This function sets the raito of the cpu 2 memory controller frequency
* Note in FBDIMM only is the memory controller freq diff from the dram freq
* Old function in Daves original code set_cpu_dram_frequency_ratio
* **/
void DRAM_config::set_cpu_memory_frequency_ratio( ){
mem2cpu_clock_ratio = (double) memory_frequency / (double) cpu_frequency;
cpu2mem_clock_ratio = (double) cpu_frequency / (double) memory_frequency;
}
void DRAM_config::set_transaction_selection_policy( int policy){
transaction_selection_policy = policy;
}
int DRAM_config::get_transaction_selection_policy(){
return transaction_selection_policy;
}
int DRAM_config::get_num_ifetch() {
return tq_info.num_ifetch_tran;
}
int DRAM_config::get_num_prefetch() {
return tq_info.num_prefetch_tran;
}
int DRAM_config::get_num_read() {
return tq_info.num_read_tran;
}
int DRAM_config::get_num_write() {
return tq_info.num_write_tran;
}
int DRAM_config::get_biu_queue_depth (){
return bus_queue_depth;
}
void DRAM_config::set_biu_depth(int depth){
bus_queue_depth = MAX(1,depth);
}
| [
"brian.lebiednik@gmail.com"
] | brian.lebiednik@gmail.com |
0ea10fbfc307cc922163b390ac51401eee098b88 | 5565952688dd8a0619c71bfe4fdf36b333fb94de | /server/Main.cpp | 8a7bed0e0d45e2783db9d42504dafc88c77f7b73 | [] | no_license | huykaiba/YgoProServer | 131b89d2e35e2c2eba606788475e69725ad144f8 | 3ff281f2285bafb7662dc5942bd02838966dea62 | refs/heads/master | 2021-03-27T12:18:16.884009 | 2016-07-16T04:50:50 | 2016-07-16T04:50:50 | 63,411,406 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 476 | cpp | #include "Config.h"
#include <string>
#include "GameserversManager.h"
using namespace ygo;
using namespace std;
volatile bool needReboot = false;
volatile bool isFather = true;
int sfd; //server fd
int main(int argc, char**argv)
{
Config* config = Config::getInstance();
if(config->parseCommandLine(argc,argv))
return EXIT_SUCCESS;
config->LoadConfig();
GameserversManager gsm;
gsm.StartServer(config->serverport);
return 0;
}
| [
"huykaiba@gmail.com"
] | huykaiba@gmail.com |
b0f1b2bd9dff725c9e5f2d0e38b76742874b32b1 | 827405b8f9a56632db9f78ea6709efb137738b9d | /CodingWebsites/WHU_OJ/Volume1/P1050.cpp | b04b93db762767ad04efb30d1c828beb9f77f6cd | [] | no_license | MingzhenY/code-warehouse | 2ae037a671f952201cf9ca13992e58718d11a704 | d87f0baa6529f76e41a448b8056e1f7ca0ab3fe7 | refs/heads/master | 2020-03-17T14:59:30.425939 | 2019-02-10T17:12:36 | 2019-02-10T17:12:36 | 133,694,119 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,147 | cpp | #include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
using namespace std;
int D[100][100];
int F[100];
void Init(int n){for(int i=0;i<n;++i) F[i]=i;}
int Find(int x){return x==F[x]?x:Find(F[x]);}
struct Arc{
int from,to,dist;
Arc(){}
Arc(int from,int to,int dist):from(from),to(to),dist(dist){}
bool operator < (const Arc &B)const{return dist < B.dist;}
}Arcs[10000];
int main(){
freopen("P1050.txt","r",stdin);
int t,n;
scanf("%d",&t);
while(t-->0){
scanf("%d",&n);
for(int i=0;i<n;++i){
for(int j=0;j<n;++j){
scanf("%d",&D[i][j]);
}
}
Init(n);
int An = 0,Dist = 0;
for(int i=0;i<n;++i){
for(int j=i+1;j<n;++j){
Arcs[An++] = Arc(i,j,D[i][j]);
}
}
sort(Arcs,Arcs+An);
for(int i=0;i<An;++i){
int Fa=Find(Arcs[i].from),Fb=Find(Arcs[i].to);
if(Fa!=Fb){
F[Fa]=Fb;
Dist += Arcs[i].dist;
}
}
printf("%d\n",Dist);
}
return 0;
}
| [
"mingzhenyan@yahoo.com"
] | mingzhenyan@yahoo.com |
5b02a691bbd1bcc8d62c2854283ca13dba56fe5e | 63a1e65a9c66c0de59673ddd6e54367da2da12a3 | /字节跳动/5. 最长回文子串.cpp | c4ed290c68eb9b0954403021007d0f86fb23d77f | [] | no_license | Maserhe/Algorithm_practise | 58df28ce1e6ab7bd10943c022264662c2a7bbf19 | f06dc4395e1089b5d3076e3c463b59d1483f324a | refs/heads/master | 2023-03-22T10:14:27.381659 | 2021-03-15T14:44:43 | 2021-03-15T14:44:43 | 230,616,496 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 671 | cpp | class Solution {
public:
int getStr(int l, int r, string& s) {
while (l >= 0 && r < s.size() && s[l] == s[r]) {
l -- ;
r ++ ;
}
return r - l - 1;
}
string longestPalindrome(string s) {
int max = 0, start = 0;
for (int i = 0; i < s.size(); i ++ ) {
int curMax = std::max(getStr(i, i, s), getStr(i, i + 1, s));
if (curMax > max) {
max = curMax;
start = i - ((curMax - 1) / 2);
}
}
string ans;
for (int i = 0; i < max; i ++ ) ans += s[start + i];
return ans;
}
}; | [
"982289931@qq.com"
] | 982289931@qq.com |
945cc14ae145165a5fbfbefcf79808b84a99ddca | 38a724327679ba89a9a5383b79523476264c69b2 | /3 term/mipt-concurrency-course/task4/striped_hash_set/striped_hash_set.cpp | a5d64e9a87847b36b4e9f43e54555907314cd4dd | [] | no_license | alexeyqu/mipt-alexeyqu | 3f0af5534a142082d8f9b10b36bbc9ae82daf6fe | 1059b0e9a95855a95d0bc6c7da564799dfc7c449 | refs/heads/master | 2021-01-21T04:39:39.719665 | 2017-10-11T16:28:20 | 2017-10-11T16:28:20 | 51,085,003 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 589 | cpp | #include "striped_hash_set.h"
#include <thread>
const int MAX_TEST = 50000;
int main()
{
std::cin.get();
striped_hash_set<int, std::hash<int>> my_hash_set(1);
std::thread([&my_hash_set]()
{
for (int i = 0; i < MAX_TEST; ++i)
{
std::cerr << i << std::endl;
my_hash_set.contains(i);
my_hash_set.add(i);
if(!my_hash_set.contains(i)) throw;
my_hash_set.remove(i);
if(my_hash_set.contains(i)) throw;
my_hash_set.add(i);
if(!my_hash_set.contains(i)) throw;
}
}
).join();
return 0;
}
| [
"alexeyqu@gmail.com"
] | alexeyqu@gmail.com |
e206cf05236021f2c5e9eaca259134ecc1e7a4be | 58a0ba5ee99ec7a0bba36748ba96a557eb798023 | /Olympiad Solutions/SPOJ/CNTPRIME.cpp | 13a2af59f950396eff9ceb9c2813c86af182aca2 | [
"MIT"
] | permissive | adityanjr/code-DS-ALGO | 5bdd503fb5f70d459c8e9b8e58690f9da159dd53 | 1c104c33d2f56fe671d586b702528a559925f875 | refs/heads/master | 2022-10-22T21:22:09.640237 | 2022-10-18T15:38:46 | 2022-10-18T15:38:46 | 217,567,198 | 40 | 54 | MIT | 2022-10-18T15:38:47 | 2019-10-25T15:50:28 | C++ | UTF-8 | C++ | false | false | 2,164 | cpp | // Ivan Carvalho
// Solution to https://www.spoj.com/problems/CNTPRIME/
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int MAXN = 1e4 + 1;
const int MAXP = 1e6 + 1;
const int MAXS = 1e3 + 1;
int arvore[4*MAXN],lazy[4*MAXN],vetor[MAXN],n,m,TC;
int crivo[MAXP];
void build(int pos,int left,int right){
lazy[pos] = -1;
if(left == right){
arvore[pos] = !crivo[vetor[left]];
return;
}
int mid = (left+right)/2;
build(2*pos,left,mid);
build(2*pos+1,mid+1,right);
arvore[pos] = arvore[2*pos] + arvore[2*pos+1];
}
void update(int pos,int left,int right,int i,int j,int val){
if(lazy[pos] != -1){
arvore[pos] = (right - left + 1)*lazy[pos];
if(left != right){
lazy[2*pos] = lazy[pos];
lazy[2*pos+1] = lazy[pos];
}
lazy[pos] = -1;
}
if(left > right || left > j || right < i) return;
if(left >= i && right <= j){
arvore[pos] = (right - left + 1)*val;
if(left != right){
lazy[2*pos] = val;
lazy[2*pos+1] = val;
}
return;
}
int mid = (left+right)/2;
update(2*pos,left,mid,i,j,val);
update(2*pos+1,mid+1,right,i,j,val);
arvore[pos] = arvore[2*pos] + arvore[2*pos+1];
}
int query(int pos,int left,int right,int i,int j){
if(lazy[pos] != -1){
arvore[pos] = (right - left + 1)*lazy[pos];
if(left != right){
lazy[2*pos] = lazy[pos];
lazy[2*pos+1] = lazy[pos];
}
lazy[pos] = -1;
}
if(left > right || left > j || right < i) return 0;
if(left >= i && right <= j){
return arvore[pos];
}
int mid = (left+right)/2;
return query(2*pos,left,mid,i,j) + query(2*pos+1,mid+1,right,i,j);
}
int main(){
crivo[0] = crivo[1] = 1;
for(int i=2;i<MAXP;i++){
if(!crivo[i]){
if(i > MAXS) continue;
for(int j = i*i;j<MAXP;j += i){
crivo[j] = 1;
}
}
}
scanf("%d",&TC);
for(int tc=1;tc<=TC;tc++){
printf("Case %d:\n",tc);
scanf("%d %d",&n,&m);
for(int i=1;i<=n;i++){
scanf("%d",&vetor[i]);
}
build(1,1,n);
while(m--){
int op;
scanf("%d",&op);
if(op == 0){
int x,y,v;
scanf("%d %d %d",&x,&y,&v);
update(1,1,n,x,y,!crivo[v]);
}
else{
int x,y;
scanf("%d %d",&x,&y);
printf("%d\n",query(1,1,n,x,y));
}
}
}
return 0;
} | [
"samant04aditya@gmail.com"
] | samant04aditya@gmail.com |
5621aa78d51d80d8839919a31aec4946a8b92f5e | 92ebaf7ce3022a38f8ae6bb57f6f8ee4ce6d267c | /tek2/object_prog/arcade/graphical/sdl2/Menu.hpp | d09f4b81d05f47994ff92c35f92ee692d0af1731 | [] | no_license | CyrilGrosjean/Epitech | d69d6c448214c9ea17c9837fb03e0e166a73afc4 | dde6bc229dcef73d66c422e98bd300cee6d19502 | refs/heads/master | 2023-04-28T17:32:08.333950 | 2021-05-20T00:12:33 | 2021-05-20T00:12:33 | 228,628,449 | 0 | 0 | null | 2023-04-14T17:18:22 | 2019-12-17T13:59:00 | C++ | UTF-8 | C++ | false | false | 570 | hpp | /*
** EPITECH PROJECT, 2021
** B-OOP-400-MPL-4-1-arcade-cyril.grosjean
** File description:
** Menu
*/
#ifndef MENU_HPP_
#define MENU_HPP_
#include <iostream>
#include <fstream>
#include "../../includes/Vector.hpp"
#include <vector>
namespace sdl
{
class Menu
{
public:
Menu();
~Menu();
size_t _gameIdx;
size_t _graphicalIdx;
std::string _username;
void set_libraries(std::vector<std::string> games, std::vector<std::string> graphicals);
void set_highscore(void);
};
}
#endif /* !MENU_HPP_ */
| [
"cyril.grosjean@epitech.eu"
] | cyril.grosjean@epitech.eu |
908e2a75ce7a78d04b275b5372592b592f326cdb | 55cd0ea9846924b0abd1d6ae6c5d0889b2689fdb | /cny70/cny-test/cny-test.ino | 96933288d8996f70fac33754a50bf36cd678c869 | [] | no_license | rezacode01/CPS-Real-time-Embedded-Systems | 68cbaa429728f0e6b6133186e7324f1e209e52c1 | cac43967723c6b781d7f22aa3266c6eee8aa7340 | refs/heads/master | 2020-03-18T15:25:27.410866 | 2018-06-10T12:11:56 | 2018-06-10T12:11:56 | 134,906,644 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 272 | ino | int a = -1;
void setup() {
// put your setup code here, to run once:
pinMode(2, INPUT);
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
a = digitalRead(2);
Serial.print("input is");
Serial.println(a);
delay(500);
}
| [
"rezacode01@gmail.com"
] | rezacode01@gmail.com |
a5b9510b4de68fd3c47d873b87711b0b58882282 | 2c22ee6d774b40d147263ed3891f2dcf700ff9bd | /Type.cpp | 17e9664a25a54a991a7f8780af606f3206a1edfd | [] | no_license | dogilla/CompiladoresC | 9fbfa2a0bc643d06bdff361672e79ea9e611d403 | e8d6ea804a62fc4ed50a665a57aee54cc5383c97 | refs/heads/main | 2023-07-09T16:23:12.277225 | 2021-08-16T21:55:27 | 2021-08-16T21:55:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 963 | cpp | #include "Type.h"
#include "Table.h"
C0::Type::Type(){
}
C0::Type::Type(string name, int baseType, int numItems, int tam){
this->name = name;
this->baseType =baseType;
this->numItems = numItems;
this->tamBytes = tam;
}
C0::Type::Type(string name, int bytes){
this->name = name;
this->tamBytes = bytes;
}
C0::Type::~Type(){
}
int C0::Type::getBaseType(){
return baseType;
}
int C0::Type::getNumItems(){
return numItems;
}
int C0::Type::getTamBytes(){
return tamBytes;
}
string C0::Type::getName(){
return name;
}
// TODO(4) Programar la función setBase que recibe a base:*Table
void C0::Type::setBase(C0::Table* base){
this->base = base;
}
// TODO(5) Programar la función getBase que retorna a base
C0::Table* C0::Type::getBase(){
return base;
}
string C0::Type::toString(){
string cadena = name+" "+to_string(numItems)+" "+to_string(tamBytes)+" "+to_string(baseType)+"\n";
return cadena;
}
| [
"ferbpp@ciencias.unam.mx"
] | ferbpp@ciencias.unam.mx |
b0807aa9e4bae0c3134a47e57130f077d11f6fd8 | 8ad84e8c9ff528394cfaa36120a1f8a37a16f558 | /boost/shared_ptr/payload.cxx | 3fdce173d90eca0d1b0ce30f6acdaf30c4969b44 | [] | no_license | cellist/dev | 30378d031cbf2cc4ca23d8bdcd831679d6417786 | 3b59f54cafb2cfe97ff90caf127e165d866b9280 | refs/heads/master | 2023-08-19T03:43:30.494172 | 2023-08-12T14:43:46 | 2023-08-12T14:43:46 | 1,159,225 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 386 | cxx | #include <iostream>
#include "payload.h"
Payload::Payload() {
std::cout << "Payload(): "
<< this->reference.use_count() << std::endl;
}
Payload::~Payload() {
std::cout << "~Payload(): "
<< this->reference.use_count() << std::endl;
}
void Payload::inject(const PayloadPtr& ref) {
std::cout << "Payload::inject: "
<< this->reference.use_count() << std::endl;
}
| [
"cellist@squizzy.de"
] | cellist@squizzy.de |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.