blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
264
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
85
| license_type
stringclasses 2
values | repo_name
stringlengths 5
140
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 905
values | visit_date
timestamp[us]date 2015-08-09 11:21:18
2023-09-06 10:45:07
| revision_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-17 19:19:19
| committer_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-06 06:22:19
| github_id
int64 3.89k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us]date 2012-06-07 00:51:45
2023-09-14 21:58:39
⌀ | gha_created_at
timestamp[us]date 2008-03-27 23:40:48
2023-08-21 23:17:38
⌀ | gha_language
stringclasses 141
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
10.4M
| extension
stringclasses 115
values | content
stringlengths 3
10.4M
| authors
sequencelengths 1
1
| author_id
stringlengths 0
158
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a812af940eeeeaa6c64c8f39bfe6eade59e30180 | 16b115a96d74a5fee97b4ceb0048590ba817b8a5 | /RUEngine/Demos/Scene0.cpp | 5c76c805cb0252b6aa94e3e7279b15ba2ba5077c | [
"Unlicense"
] | permissive | rutgerklamer/Rugine | 823aba0a28a1d4e7dd93086096da462c9cbe5f6e | 39b7c60cfc54629ac76da33bc0e61ca9b82f7483 | refs/heads/master | 2020-06-19T09:13:53.018786 | 2018-01-25T22:02:49 | 2018-01-25T22:02:49 | 94,183,769 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,674 | cpp | #include "Scene0.h"
Scene0::Scene0(Input* input) : Superscene(input)
{
std::cout << "Scene0 initialized" << std::endl;
//Create a mesh
mesh = new Entity();
mesh->LoadObject("Assets/sponza.obj", false);
//Set a texture to it
mesh->setTexture(tex::loadTexture("Assets/szclcdi.png"));
mesh->position = glm::vec3(0,0,0);
mesh->scale = glm::vec3(30,30,30);
//Add a child to the stage
this->addChild(mesh);
light = new Light();
light->position = glm::vec3(0,15,0);
light->setPosition(light->getPosition());
light->setLightColor(glm::vec3(0.4,0.1,0.2));
light->setStrength(3.0f);
light->setSpecularStrength(3.0f);
this->addLight(light);
for (int i = 0; i < 8; i++) {
Light* light2 = new Light();
light2->position = glm::vec3(-35 + (i * 10),2,0);
light2->setPosition(light2->getPosition());
light2->setLightColor(glm::vec3(sin(i * 16.0f),cos(i*16.0f),i/16.0f));
light2->setStrength(i);
light2->setExtinction(i / 2);
light2->setSpecularStrength(2.0f);
this->addLight(light2);
}
setGamma(1.2f);
setExposure(0.20f);
skybox = new Skybox("Assets/sandtrap_rt.tga", "Assets/sandtrap_lf.tga", "Assets/sandtrap_up.tga", "Assets/sandtrap_dn.tga", "Assets/sandtrap_bk.tga", "Assets/sandtrap_ft.tga");
this->addSkybox(skybox);
}
Scene0::~Scene0()
{
delete mesh;
delete light;
}
void Scene0::Update(float deltaTime)
{
if (input->getKeyDown(GLFW_KEY_RIGHT)) {
sceneState = Superscene::NEXT;
}
if (input->getKeyDown(GLFW_KEY_LEFT)) {
sceneState = Superscene::PREV;
}
}
| [
"[email protected]"
] | |
f009b2f5a3f9f9f9d7988740353682f73cbbedf7 | e759e684c8b799a2363f435e49ea99cd6d356870 | /phys/step/integrator.cpp | bc67a49f57352a7f7613cefc3f47dfaadf76710e | [] | no_license | Jorjor70/meuh | 56e115c107cc82bfc42dbfefef1101e64b34c3b5 | 0e2ee0227281c08f6e1dd8c892c03b162d3802dc | refs/heads/master | 2021-01-18T10:10:26.416036 | 2013-01-30T12:01:30 | 2013-01-30T12:01:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 333 | cpp | #include "integrator.h"
#include <phys/system.h>
#include <phys/engine.h>
#include <sparse/prod.h>
namespace phys {
namespace step {
integrator_type integrator(const system& sys, const engine& eng) {
return [&](const dof::velocity& v, math::real dt) {
eng.integrate(v, sys.mass * v, dt);
};
}
}
}
| [
"[email protected]"
] | |
1835a89d8297a711ce1e1610771ccbd29c3cdf73 | 904d18146f3ac64b29ab9e0e8645120f379d54ad | /util_swiss.hpp | 67cc144a0b5d8ac72d4327a8a972477d318d6c37 | [] | no_license | matthewaveryusa/utils | b895848c3492fe16c143e92deb0cdc87352c3cc9 | c670060060017c7645f023be0d0b88c9dca29eaf | refs/heads/master | 2016-09-05T20:34:01.948455 | 2014-08-18T04:55:41 | 2014-08-18T04:55:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,149 | hpp | // Matthew Avery Coder 2012 - 2014.
// 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)
#pragma once
//various random _small_ functions
#include <string>
#include <sstream>
#include <ios>
#include <cstdio>
#include <iterator>
#include <limits>
#include <functional>
namespace util {
namespace swiss {
template<class P, class T>
const std::function<void(P *)> make_delete(T&& encapsulate) {
class WrappedDeleter {
public:
WrappedDeleter(T &&other): o_(std::move(other)) {
}
private:
T o_;
};
WrappedDeleter *d = new WrappedDeleter(std::move(encapsulate));
return [d](P * ptr) { delete d; };
}
template<class Function>
void for_n(size_t n, Function f)
{
while(n-- != 0) { f(); }
}
template<class SIZE, class UPDATE>
bool numeric_limit_split(UPDATE &&update, size_t size){
while(size > std::numeric_limits<SIZE>::max()) {
if(!update(std::numeric_limits<SIZE>::max())) { return false; }
size -= std::numeric_limits<SIZE>::max();
}
return update(static_cast<SIZE>(size));
}
}
}
| [
"[email protected]"
] | |
5fedb12d952b854374c7b0e2795d1db51b2f4dcf | 7112113d639b3acab7daee091afdce83f871b9d7 | /ToonTanks/Source/ToonTanks/Actors/ProjectileBase.h | 25fdeae1e5f2bf75fa198f0ac1462a83301bb420 | [] | no_license | louisgirard/UE_Tuto_Cpp | ddf1cacb5cf6dfb4fbcb28491720730a1cf4f8e4 | 64e13db54154b82dc9e8cbe1a4f3ab04501c2944 | refs/heads/main | 2023-06-02T08:09:52.558614 | 2021-06-24T21:26:27 | 2021-06-24T21:26:27 | 376,582,250 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,806 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "ProjectileBase.generated.h"
UCLASS()
class TOONTANKS_API AProjectileBase : public AActor
{
GENERATED_BODY()
private:
// Components
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Components", meta = (AllowPrivateAccess = "true"))
class UProjectileMovementComponent* ProjectileMovement;
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Components", meta = (AllowPrivateAccess = "true"))
UStaticMeshComponent* ProjectileMesh;
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Components", meta = (AllowPrivateAccess = "true"))
class UParticleSystemComponent* TrailParticles;
// Variables
UPROPERTY(EditDefaultsOnly, Category = "Damage")
TSubclassOf<UDamageType> DamageType;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Damage", meta = (AllowPrivateAccess = "true"))
float Damage = 10.f;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Movement", meta = (AllowPrivateAccess = "true"))
float ProjectileSpeed = 2000.f;
UPROPERTY(EditAnywhere, Category = "Effects")
class UParticleSystem* HitParticles;
UPROPERTY(EditAnywhere, Category = "Effects")
USoundBase* HitSound;
UPROPERTY(EditAnywhere, Category = "Effects")
USoundBase* LaunchSound;
UPROPERTY(EditDefaultsOnly, Category = "Effects")
TSubclassOf<UCameraShake> HitShake;
// Functions
UFUNCTION()
void OnHit(UPrimitiveComponent* HitComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, FVector NormalImpulse, const FHitResult& Hit);
public:
// Sets default values for this actor's properties
AProjectileBase();
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
};
| [
"[email protected]"
] | |
de5082d5390f8b81ea71f008056bad4d0c767779 | 705182c5684bd3b6902a9eafe911f8e36cccb77d | /vjoy.h | a6bd5b960f5ac2f35b4cffddcae75a9f11fdd494 | [] | no_license | jawb/MacFlyskyIBUS | 9d82c9db0dc93b1138b670ca34c4848fad63514d | d72483c8bf770206a9fcb881bb5bc61492b2fca4 | refs/heads/master | 2021-04-06T19:02:51.823579 | 2018-03-14T23:44:14 | 2018-03-14T23:44:14 | 125,287,687 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 776 | h | #include <IOKit/IOKitLib.h>
struct JoystickValues {
int8_t x;
int8_t y;
int8_t z;
int8_t rx;
int8_t buttons;
};
typedef unsigned char byte;
class FooHIDJoystick
{
public:
FooHIDJoystick(const std::string &name, const std::string &serialNumber);
~FooHIDJoystick();
bool hasError() const;
std::string errorMessage() const;
void setValue(JoystickValues newValues);
private:
bool createDevice() const;
bool sendToDevice() const;
void destroyDevice() const;
const std::string name;
const std::string serialNumber;
io_connect_t connection = 0;
JoystickValues values = {127, 127};
std::string _errorMessage;
bool _hasError = true;
bool connectionOpened = false;
bool deviceCreated = false;
};
| [
"[email protected]"
] | |
727291182849f28150cbb475b97a9265ad7c4256 | dfc1839acd109a2dde6ab0132a28adf29cc03071 | /c++/operator_type_traits/main.cpp | caf446bec18e42ab6596333d25fea8869237bd19 | [
"MIT"
] | permissive | adrianmgg/misc_little_things_i_did | 8565ef3e01da7dd60957fbf0c8b0f229260887b9 | 077a0d7728c6259c51b6cc8ce87a36144c76f97b | refs/heads/master | 2023-08-12T18:50:57.614426 | 2021-10-03T22:04:45 | 2021-10-03T22:04:45 | 296,183,518 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 201 | cpp |
struct A{
A& operator+=(const A& a){return *this;};
};
struct B{
B& operator+=(const B& b) = delete;
B operator+(const B& b){
B ret;
// some stuff
return ret;
}
};
int main(){
return 0;
}
| [
"[email protected]"
] | |
58e56c55fd17e923e1c245b5bcb3f5193326168a | 390ad6c54e1e821c79e8395a1ca1ab90f4b7ec46 | /ISteamScreenshots003.h | 69e527428ee20812a621e055ec8183869d07b4c9 | [] | no_license | fire64/opensteamworks | 71a949b0fad3ed270654616be1965023c903b4cd | 320f56f4cc9854eae686b5d8b86e79f16b8397f4 | refs/heads/master | 2023-07-08T13:40:31.478568 | 2021-08-19T19:55:09 | 2021-08-19T19:55:09 | 117,380,298 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 663 | h | class ISteamScreenshots003
{
public:
virtual unknown_ret WriteScreenshot(void*, unsigned int, int, int) = 0;
virtual unknown_ret AddScreenshotToLibrary(char const*, char const*, int, int) = 0;
virtual unknown_ret TriggerScreenshot() = 0;
virtual unknown_ret HookScreenshots(bool) = 0;
virtual unknown_ret SetLocation(unsigned int, char const*) = 0;
virtual unknown_ret TagUser(unsigned int, CSteamID) = 0;
virtual unknown_ret TagPublishedFile(unsigned int, unsigned long long) = 0;
virtual unknown_ret IsScreenshotsHooked() = 0;
virtual unknown_ret AddVRScreenshotToLibrary(EVRScreenshotType, char const*, char const*) = 0;
};
| [
"[email protected]"
] | |
9e46cb4f197ceca16b4a84c689197dca04c438f8 | 54b351141c49469112c906aec52703fe2d24fe1e | /Resolucoes_C/URI_1241 - (8894784) - Accepted.cpp | 990e0d545f54592f48a6b73541a401df005e94bc | [] | no_license | Nogueirarenato/URI | aac7316108971f091178573291a0c255da855969 | 98d15c7835de30e48d748620eb5ba186dc5f3878 | refs/heads/main | 2023-07-14T11:03:29.215938 | 2021-08-24T12:02:52 | 2021-08-24T12:02:52 | 398,541,670 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 518 | cpp | #include <stdio.h>
#include <string.h>
int main()
{
int t1,t2, t3, t4, cont, estancias, c1, c2,c3, flag, flag2;
char p1[1500], p2[1500],p3[1500],p4[1500];
cont=0;
scanf("%d", &estancias);
while(cont<estancias){
scanf("%s %s", &p1, &p2);
t3=strlen(p1);
t4=strlen(p2);
c1=t3-1;
c2=t4-1;
c3=0;
flag=0;
while(c2>=0)
{
if(p1[c1]!=p2[c2])flag++;
c2--;
c1--;
}
if(flag==0)printf("encaixa\n");
else printf("nao encaixa\n");
cont++;
}
return(0);
}
| [
"[email protected]"
] | |
bb2e730c7fefbbc746d8d68c3f249ae95566e0c5 | c0caed81b5b3e1498cbca4c1627513c456908e38 | /src/core/scoring/func/CircularHarmonicFunc.hh | 59295b89d357d8dabcf89ae48e80e7e66f8f9f4e | [] | no_license | malaifa/source | 5b34ac0a4e7777265b291fc824da8837ecc3ee84 | fc0af245885de0fb82e0a1144422796a6674aeae | refs/heads/master | 2021-01-19T22:10:22.942155 | 2017-04-19T14:13:07 | 2017-04-19T14:13:07 | 88,761,668 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,561 | hh | // -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*-
// vi: set ts=2 noet:
//
// (c) Copyright Rosetta Commons Member Institutions.
// (c) This file is part of the Rosetta software suite and is made available under license.
// (c) The Rosetta software is developed by the contributing members of the Rosetta Commons.
// (c) For more information, see http://www.rosettacommons.org. Questions about this can be
// (c) addressed to University of Washington UW TechTransfer, email: [email protected].
/// @file src/core/scoring/func/HarmonicFunc.hh
/// @brief Definition for functions used in definition of constraints.
/// @author James Thompson
#ifndef INCLUDED_core_scoring_func_CircularHarmonicFunc_hh
#define INCLUDED_core_scoring_func_CircularHarmonicFunc_hh
#include <core/scoring/func/CircularHarmonicFunc.fwd.hh>
#include <core/scoring/func/Func.hh>
#include <core/types.hh>
// C++ Headers
#ifdef SERIALIZATION
// Cereal headers
#include <cereal/access.fwd.hpp>
#include <cereal/types/polymorphic.fwd.hpp>
#endif // SERIALIZATION
namespace core {
namespace scoring {
namespace func {
/// @brief Function that operates in radians, for applications like DihedralConstraint.
/// Prevents discontinuities at 0/360 or -180/180 degrees for dihedral constraints.
class CircularHarmonicFunc : public Func {
public:
CircularHarmonicFunc(
Real const x0_radians, Real const sd_radians
): x0_( x0_radians ), sd_( sd_radians ), offset_( 0.0 ) {}
CircularHarmonicFunc(
Real const x0_radians, Real const sd_radians, Real const offset
): x0_( x0_radians ), sd_( sd_radians ), offset_( offset ) {}
FuncOP clone() const { return FuncOP( new CircularHarmonicFunc( *this ) ); }
virtual bool operator == ( Func const & other ) const;
virtual bool same_type_as_me( Func const & other ) const;
Real func( Real const x ) const;
Real dfunc( Real const x ) const;
virtual void read_data( std::istream & in );
virtual void show_definition( std::ostream & out ) const;
Real x0() const {
return x0_;
}
Real sd() const {
return sd_;
}
private:
Real x0_;
Real sd_;
Real offset_;
#ifdef SERIALIZATION
protected:
friend class cereal::access;
CircularHarmonicFunc();
public:
template< class Archive > void save( Archive & arc ) const;
template< class Archive > void load( Archive & arc );
#endif // SERIALIZATION
};
} // constraints
} // scoring
} // core
#ifdef SERIALIZATION
CEREAL_FORCE_DYNAMIC_INIT( core_scoring_func_CircularHarmonicFunc )
#endif // SERIALIZATION
#endif
| [
"[email protected]"
] | |
0178a77afae71a34223e0b18d85aa588847a4215 | 5f98d2f3ca9a71b0f374eb7d52699985cd676bed | /Project2/src/cpp/vmcsolver/VMCSolver.h | b40c05b29d93d1590a7ad54dce1a77d7cf011a8a | [] | no_license | lastis/FYS4411 | 1bf4eb6a042125ae9cf3aeb2e852c4d10a923234 | e56d692f6134effc1373f76ec5600d5466aecda2 | refs/heads/master | 2021-01-23T12:15:36.535448 | 2015-06-16T00:40:56 | 2015-06-16T00:40:56 | 29,853,378 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,961 | h | #ifndef _VMCSOLVER_H_INCLUDED
#define _VMCSOLVER_H_INCLUDED
#include <math.h>
#include <iostream>
#include <fstream>
#include <string>
#include <omp.h>
#include <random>
#include "../CPhys/CPhys.h"
#include "SingleParticleWaveFunctions.h"
class VMCSolver
{
public:
static const int LOCAL_ENERGY_GENERIC = 1;
static const int LOCAL_ENERGY_GENERIC_NOCOR = 5;
static const int LOCAL_ENERGY_HELIUM_1 = 2;
static const int LOCAL_ENERGY_HELIUM_2 = 4;
static const int LOCAL_ENERGY_HYDROGEN = 3;
static const int LOCAL_ENERGY_SLATER = 6;
static const int LOCAL_ENERGY_SLATER_NOCOR = 7;
static const int WAVE_FUNCTION_1 = 8;
static const int WAVE_FUNCTION_2 = 9;
static const int WAVE_FUNCTION_BERYLLIUM_1 = 10;
static const int WAVE_FUNCTION_BERYLLIUM_2 = 11;
static const int WAVE_FUNCTION_HELIUM_GTO = 12;
private:
void endOfSingleParticleStep(int cycle, int i);
void updateQuantumForce(double** r, double* rAbs, double** qForce,
double factor);
void updateQuantumForceSlater(double** r, double* rAbs, double** qForce,
double** pslater1, double** pslater2,
double** pslater1Inv, double** pslater2Inv);
void updateSlater(int i, double** slater1New, double** slater1Old,
double** slater2New, double** slater2Old,
double** slater1InvNew, double** slater1InvOld,
double** slater2InvNew, double** slater2InvOld);
public:
VMCSolver();
void clear();
double getAcceptanceRatio();
double getStepLength();
double getR12Mean();
double getEnergy();
double getEnergySquared();
void supressOutput();
bool initRunVariables();
void startOfCycle();
void startOfCycleQuantum();
void startOfCycleSlaterQuantum();
void runSingleStep(int i, int cycle);
void runSingleStepSlater(int i, int cycle);
void runSingleStepQuantum(int i, int cycle);
void runSingleStepSlaterQuantum(int i, int cycle);
double calc_dE_dAlpha();
double calc_dE_dBeta();
double (*getWaveFuncVal)(double** r, double* rAbs);
double (*getLocalEnergy)(double** r, double* rAbs);
double getLocalEnergySlater(double** r, double* rAbs);
double getLocalEnergySlaterNoCor(double** r, double* rAbs);
double getCorrelationRatio(int i);
void setSeed(long seed);
double alpha;
double beta;
int waveFunction;
int localEnergyFunction;
int accepts;
int rejects;
int charge;
int nDimensions;
int nCycles;
int nParticles;
double stepLength;
double h;
double hInv;
double h2Inv;
long idum;
double timeStep;
double D;
std::mt19937 gen;
std::uniform_real_distribution<double> dist_uniform;
std::normal_distribution<double> dist_gauss;
double deltaE;
double waveFuncValOld;
double waveFuncValNew;
double greensFunction;
double ratio;
double potentialEnergy;
double DD;
double CC;
double DC;
double dE_dAlpha;
double dE_dBeta;
int nHalf;
bool usingCorrelation;
bool importanceSampling;
bool efficientSlater;
// Private variables
Matrix slater1Old;
Matrix slater1New;
Matrix slater1InvOld;
Matrix slater1InvNew;
Matrix slater2Old;
Matrix slater2New;
Matrix slater2InvOld;
Matrix slater2InvNew;
double** pslater1Old;
double** pslater1New;
double** pslater1InvOld;
double** pslater1InvNew;
double** pslater2Old;
double** pslater2New;
double** pslater2InvOld;
double** pslater2InvNew;
Vector vS;
double* S;
Matrix qForceOld;
Matrix qForceNew;
double** pqForceOld;
double** pqForceNew;
Matrix rOld;
Matrix rNew;
double** prOld;
double** prNew;
Vector rAbsOldVec;
Vector rAbsNewVec;
double* rAbsOld;
double* rAbsNew;
};
#endif // VMCSOLVER_H
| [
"[email protected]"
] | |
7195d1799f721049592a358f55e5a42e2b64fa42 | 81e71315f2f9e78704b29a5688ba2889928483bb | /include/Plugin/Plugin dxf/dxfDataTypes.h | e554170c8b6519a300fb438ee08456ce54e03b73 | [] | no_license | Creature3D/Creature3DApi | 2c95c1c0089e75ad4a8e760366d0dd2d11564389 | b284e6db7e0d8e957295fb9207e39623529cdb4d | refs/heads/master | 2022-11-13T07:19:58.678696 | 2019-07-06T05:48:10 | 2019-07-06T05:48:10 | 274,064,341 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,823 | h | /* dxfReader for OpenSceneGraph Copyright (C) 2005 by GraphArchitecture ( grapharchitecture.com )
* Programmed by Paul de Repentigny <[email protected]>
*
* OpenSceneGraph is (C) 2004 Robert Osfield
*
* This library is provided as-is, without support of any kind.
*
* Read DXF docs or OSG docs for any related questions.
*
* You may contact the author if you have suggestions/corrections/enhancements.
*/
#ifndef DXF_DATATYPES
#define DXF_DATATYPES 1
#include <CRCore/crGroup.h>
typedef std::map<std::string, CRCore::ref_ptr<CRCore::crGroup> > LayerTable;
class dxfDataType {
public:
enum TYPE {
UNKNOWN,
STRING,
HEX,
BOOL,
SHORT,
INT,
LONG,
DOUBLE
};
inline static bool between(int a, int m, int x) { return (a >= m && a <= x); }
inline static int typeForCode(int gc) {
if ( between(gc, 0, 9) ||
gc == 100 || gc == 102 ||
between(gc, 300, 309) ||
between(gc, 410, 419) ||
between(gc, 430, 439) ||
between(gc, 470, 479) ||
gc == 999 ||
between(gc, 1000, 1009)
)
return STRING;
else if ( gc == 105 ||
between(gc, 310, 319) ||
between(gc, 320, 329) ||
between(gc, 330, 369) ||
between(gc, 390, 399)
)
return HEX;
else if ( between(gc, 290, 299 ) )
return BOOL;
else if ( between(gc, 70, 78 ) ) // 2005.12.13 PdR 70 to 78 should be INT, not U_SHORT
return INT;
else if ( between(gc, 60, 79) ||
between(gc, 170, 179) ||
between(gc, 270, 279) ||
between(gc, 280, 289) ||
between(gc, 370, 379) ||
between(gc, 380, 389) ||
between(gc, 400, 409)
)
return SHORT;
else if ( between(gc, 90, 99) ||
between(gc, 450, 459) ||
between(gc, 1060, 1070)
)
return LONG;
else if ( between(gc, 420, 429) ||
between(gc, 440, 449) ||
gc == 1071
)
return INT;
else if ( between(gc, 10, 39) ||
between(gc, 40, 59) ||
between(gc, 110, 119) ||
between(gc, 120, 129) ||
between(gc, 130, 139) ||
between(gc, 140, 149) ||
between(gc, 210, 239) ||
between(gc, 460, 469) ||
between(gc, 1010, 1019)
)
return DOUBLE;
else
return UNKNOWN;
}
};
#endif
| [
"wucaihua@86aba9cf-fb85-4101-ade8-2f98c1f5b361"
] | wucaihua@86aba9cf-fb85-4101-ade8-2f98c1f5b361 |
d63986c40e90ac101598637766b41eb1c4edb730 | 85b7a5f7d0362af119fabe52077907dbcb9fef08 | /Source/MyOnlineCardGame/Utils/CardGameUtils/MyCardGameInterface.h | 58b18694171c1ea81e8ebd55fd76a27c50cd0207 | [] | no_license | WenchaoXia/test | 003a7f6befcca0bc463413d521cde9de7968008e | 95cee75ea7bbe6de4c9024ab6a9cf33bf78f33bd | refs/heads/master | 2020-03-22T02:37:28.386542 | 2018-06-12T02:36:01 | 2018-06-12T02:36:01 | 139,383,124 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,041 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "Utils/CommonUtils/MyRenderUtilsLibrary.h"
#include "MyCardGameCommonDefines.h"
#include "MyCardGameInterface.generated.h"
UINTERFACE()
class UMyCardGameScreenPositionRelatedWidgetInterfaceCpp : public UInterface
{
GENERATED_BODY()
};
class IMyCardGameScreenPositionRelatedWidgetInterfaceCpp
{
GENERATED_BODY()
public:
//when calling this, offset = 0 always means the widget is at viewRole's point
UFUNCTION(BlueprintNativeEvent)
MyErrorCodeCommonPartCpp restartMainAnimation(int32 idxScreenPosition, float time, FVector2D offsetToParentCenter, FVector2D offsetShowPoint, FVector2D offsetScreenCenter);
};
#define IMyCardGameScreenPositionRelatedWidgetInterfaceCpp_DefaultImplementationForUObject() \
protected: \
virtual MyErrorCodeCommonPartCpp restartMainAnimation_Implementation(int32 idxScreenPosition, float time, FVector2D offsetToParentCenter, FVector2D offsetShowPoint, FVector2D offsetScreenCenter) override \
{ \
UE_MY_LOG(LogMyUtilsInstance, Error, TEXT("%s: restartMainAnimation only implemented in C++."), *GetClass()->GetName()); \
return MyErrorCodeCommonPartCpp::InterfaceFunctionNotImplementedByBlueprint; \
};
UINTERFACE()
class UMyCardGameCardWidgetBaseInterfaceCpp : public UInterface
{
GENERATED_BODY()
};
class IMyCardGameCardWidgetBaseInterfaceCpp
{
GENERATED_BODY()
protected:
//Must be implemented by Blueprint
UFUNCTION(BlueprintNativeEvent)
MyErrorCodeCommonPartCpp getCenterButtonFromBlueprint(UMyButton*& button);
};
#define IMyCardGameCardWidgetBaseInterfaceCpp_DefaultImplementationForUObject_Bp() \
protected: \
virtual MyErrorCodeCommonPartCpp getCenterButtonFromBlueprint_Implementation(UMyButton*& button) override \
{ \
UE_MY_LOG(LogMyUtilsInstance, Error, TEXT("%s: getCenterButtonFromBlueprint only implemented in C++."), *GetClass()->GetName()); \
return MyErrorCodeCommonPartCpp::InterfaceFunctionNotImplementedByBlueprint; \
}; | [
"[email protected]"
] | |
599f85f92465c12f25645fb49928953daa2605ff | 75899d678eae54c76bcae05becf9b5d21e667975 | /jodbc/log.hpp | 31999e9b83c1e5221e54e350c0911696a2228e9e | [] | no_license | dmitri88/jdbc-over-odbc | 5a1ace236a81c79038a7d2546ef411c7c21f8c72 | ab968cf41ed2c763034aed6c4f0af7b03c2a548d | refs/heads/master | 2022-11-23T20:02:32.757991 | 2020-07-31T12:21:08 | 2020-07-31T12:21:08 | 261,961,382 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 241 | hpp | /*
* log.hpp
*
* Created on: May 15, 2020
* Author: dmitri
*/
#ifndef JODBC_LOG_HPP_
#define JODBC_LOG_HPP_
#define LOG(level, fmt, ...) printf(fmt, ##__VA_ARGS__)
//#define LOG(level, fmt, ...)
#endif /* JODBC_LOG_HPP_ */
| [
"[email protected]"
] | |
21ba0c6760aba5ff69d28888c0fdaf4767448fc8 | fc0664a076eeb69a3a8a89e7af25329c3998dd07 | /CoreTests/STL/Test_Types_FileAddress.cpp | 74c369ddc7b5d7bf8c7f8930f9f06e47dd89ba17 | [
"BSD-2-Clause"
] | permissive | azhirnov/ModularGraphicsFramework | fabece2887da16c8438748c9dd5f3091a180058d | 348be601f1991f102defa0c99250529f5e44c4d3 | refs/heads/master | 2021-07-14T06:31:31.127788 | 2018-11-19T14:28:16 | 2018-11-19T14:28:16 | 88,896,906 | 14 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,446 | cpp | // Copyright (c) Zhirnov Andrey. For more information see 'LICENSE.txt'
#include "CoreTests/STL/Common.h"
using namespace GX_STL;
using namespace GX_STL::GXTypes;
using namespace GX_STL::GXMath;
extern void Test_Types_FileAddress ()
{
const String filename = "../11/../22/33\\44\\55.ab";
const String ext = FileAddress::GetExtension( filename ); TEST( ext == "ab" );
const String name = FileAddress::GetName( filename ); TEST( name == "55" );
const String path = FileAddress::GetPath( filename ); TEST( path == "../11/../22/33\\44" );
const String name_ext = FileAddress::GetNameAndExt( filename ); TEST( name_ext == "55.ab" );
const String ext1 = FileAddress::GetExtensions( "aa/bb.c.d" ); TEST( ext1 == "c.d" );
const String ext2 = FileAddress::GetExtensions( "bb.cx.d" ); TEST( ext2 == "cx.d" );
const String ext3 = FileAddress::GetExtension( "aabb" ); TEST( ext3 == "" );
const String ext4 = FileAddress::GetExtensions( "aabb" ); TEST( ext4 == "" );
const String ext5 = FileAddress::GetExtension( "." ); TEST( ext5 == "" );
const String ext6 = FileAddress::GetExtensions( "." ); TEST( ext6 == "" );
Array<StringCRef> path_arr;
FileAddress::DividePath( filename, path_arr );
TEST( path_arr.Count() == 7 );
TEST( path_arr[0] == ".." );
TEST( path_arr[1] == "11" );
TEST( path_arr[2] == ".." );
TEST( path_arr[3] == "22" );
TEST( path_arr[4] == "33" );
TEST( path_arr[5] == "44" );
TEST( path_arr[6] == "55.ab" );
String without_name = filename;
FileAddress::RemoveName( INOUT without_name );
TEST( without_name == "../11/../22/33\\44" );
String without_ext = filename;
FileAddress::RemoveExtension( INOUT without_ext );
TEST( without_ext == "../11/../22/33\\44\\55" );
String formated = filename;
FileAddress::FormatPath( INOUT formated );
TEST( formated == "../22/33/44/55.ab" );
formated = "aa/bb/../../../aa/bb/cc/dd";
FileAddress::FormatPath( INOUT formated );
TEST( formated == "../aa/bb/cc/dd" );
String left = filename;
FileAddress::RemoveDirectoriesFromLeft( INOUT left, 2 );
TEST( left == "../11" );
String right = filename;
FileAddress::RemoveDirectoriesFromRight( INOUT right, 2 );
TEST( right == "../11/../22/33" );
String dir_path = "path";
FileAddress::AddDirectoryToPath( INOUT dir_path, "dir" );
TEST( dir_path == "path/dir" );
dir_path = "/path/";
FileAddress::AddDirectoryToPath( INOUT dir_path, "/dir1/" );
FileAddress::AddDirectoryToPath( INOUT dir_path, "/dir2/" );
TEST( dir_path == "/path/dir1/dir2/" );
dir_path = "path";
FileAddress::AddBaseDirectoryToPath( INOUT dir_path, "dir" );
TEST( dir_path == "dir/path" );
dir_path = "/path/";
FileAddress::AddBaseDirectoryToPath( INOUT dir_path, "/dir1/" );
FileAddress::AddBaseDirectoryToPath( INOUT dir_path, "/dir2/" );
TEST( dir_path == "/dir2/dir1/path/" );
String name1 = name;
FileAddress::AddExtensionToName( INOUT name1, ".ext" ); TEST( name1 == name + ".ext" );
name1 = name + ".";
FileAddress::AddExtensionToName( INOUT name1, ".ext" ); TEST( name1 == name + ".ext" );
name1 = name;
FileAddress::AddExtensionToName( INOUT name1, "ext" ); TEST( name1 == name + ".ext" );
name1 = name + ".";
FileAddress::AddExtensionToName( INOUT name1, "ext" ); TEST( name1 == name + ".ext" );
String name2 = FileAddress::GetName( "../out/common" ); TEST( name2 == "common" );
String name3 = FileAddress::GetName( "../out/common" ); TEST( name3 == "common" );
}
| [
"[email protected]"
] | |
b29a632bb1d2ed8225ff2ff4578cdd249c9cde3f | b3ee522c89edfa67181efc7f3fa464afeb9448a2 | /_pliki/21.cpp | 3fbb90cec8812fe7953987c9a5957b8a563b44ef | [] | no_license | Micp95/MTI_ | 3d4becc3bcd3159b855e9957e84fedae4ad228ae | 6a63e9ba3c56e9a9aaac2d20113eba4fa38555f0 | refs/heads/master | 2016-08-12T17:06:30.003217 | 2016-01-12T11:43:51 | 2016-01-12T11:43:51 | 44,838,756 | 0 | 0 | null | null | null | null | WINDOWS-1250 | C++ | false | false | 97,157 | cpp | #include "AlgHuff.h"
namespace _AHuffman{
//Konstruktory i destruktory
AHuffman::~AHuffman()
{
if (znaki != NULL)
delete[] znaki;
}
//Tworzenie potrzebnych struktur
void AHuffman::StworzListe(){
string znalezione = "";
int* wystapienia = new int[MaksZnakow];
int size = 0;
//Zliczenie wystepujacych znakow
int tmp;
char znak;
for (int k = 0; k < tekst.length(); k++){
znak = tekst[k];
tmp = znalezione.find(znak);
if (tmp == -1){ //Jeśli nie znaleziono, dodajemy nowy znak do słownika/sringa
znalezione += znak;
wystapienia[size++] = 1; //Zwiększamy indeks wystapienia danego znaku(nowego)
}
else
wystapienia[tmp] ++; //Zwiekszamy indeks znalezionego znaku
}
//Tworzenie podstawowych jednostek drzew
znaki = new Node[size];
for (int k = 0; k < size; k++){
znaki[k] = Node(znalezione[k],wystapienia[k]);
}
//Porzadki
this->size = size;
tablica = znalezione;
delete[] wystapienia;
}
void AHuffman::StworzDrzewo(){
//Zapisywanie adresow wszystkich lisci
Node** drzewa = new Node*[size];
for (int k = 0; k < size; k++){
drzewa[k] = &znaki[k];
}
//Zmienne pomocnicze
int zmsize = size;
MM indeksy;
Node* tmp;
while (zmsize > 1){ //Dopoki mamy wiecej niz jeden element w tablicy
indeksy = MinMin(drzewa, zmsize); //Znalezienie najmniejszych elementow
if (indeksy.max != indeksy.min){ //dodatkowe zabezpieczenie - nie potrzebne
tmp = new Node(drzewa[indeksy.min]->wartosc + drzewa[indeksy.max]->wartosc); //Tworzenie nowego wezla
//Ustawianie zmiennych wezla
tmp->left = drzewa[indeksy.min];
tmp->right = drzewa[indeksy.max];
drzewa[indeksy.min] = tmp; //Podmiana starego elementu na wezel
swap(drzewa[indeksy.max], drzewa[--zmsize]); //Podmiana i usuniecie ostatniego elementu z tabliy (zmiejszenie rozmiaru)
\
}
}
Drzewo = drzewa[0]; //Zapamietanie adresu drzewa
delete[] drzewa; //Usuniecie pomocniczej tablicy
}
void AHuffman::StworzSlownik(){
Przechodz(Drzewo,""); //Aktualizacja elementow drzewa - zapamietuje sciezki do kazdego nodea - tworzy slownik
}
//Algorytm kodujacy
void AHuffman::Przechodz(Node* element, string kod){ //Przejscie przez drzewo typem (?)
if (element == NULL)
return;
if (element->left)
Przechodz(element->left,kod+"0");
element->Odwiedz(kod);
if (element->right)
Przechodz(element->right, kod + "1");
}
string AHuffman::Translate(){
string zwrot="";
for (int k = 0; k < tekst.length(); k++){
zwrot += znaki[tablica.find(tekst[k])].kod;
}
zakodowane = zwrot;
return zwrot;
}
//Funkcje Glowne
string AHuffman::Koduj(string tresc){
tekst = tresc;
StworzListe();
StworzDrzewo();
StworzSlownik();
//Pomocnicze wypisanie slownika
for (int k = 0; k < size; k++)
cout << znaki[k].znak << " " << znaki[k].kod << endl;
return Translate();
}
string AHuffman::Dekoduj(string tresc ){
if (tresc == "")
tresc = zakodowane;
string zwrot = "";
//Odczytywanie liter ze slownika - przechodzenie przez drzewo za pomoca podanego schamatu
Node* tmp = Drzewo;
for (int k = 0; k <= tresc.length(); k++){
if (tmp->CzyLisc){
zwrot += tmp->znak;
tmp = Drzewo;
}
if (k == tresc.length())
break;
if (tresc[k] == '0')
tmp = tmp->left;
else
tmp = tmp->right;
}
return zwrot;
}
//Funkcja pomocnicza
MM AHuffman::MinMin(Node**tab, int size){
MM MiMa, zwrot; // min = min1, max = min2
zwrot.min = 0;
zwrot.max = 0;
MiMa.max = -1;
MiMa.min = -1;
int tmp;
for (int k = 0; k < size; k++){
tmp = tab[k]->wartosc;
if (tmp < MiMa.max || MiMa.max == -1){
zwrot.max = k;
MiMa.max = tmp;
}
else if (tmp <= MiMa.min || MiMa.min == -1){
zwrot.min = k;
MiMa.min = tmp;
}
}
swap(zwrot.max, zwrot.#include "AlgHuff.h"
namespace _AHuffman{
//Konstruktory i destruktory
AHuffman::~AHuffman()
{
if (znaki != NULL)
delete[] znaki;
}
//Tworzenie potrzebnych struktur
void AHuffman::StworzListe(){
string znalezione = "";
int* wystapienia = new int[MaksZnakow];
int size = 0;
//Zliczenie wystepujacych znakow
int tmp;
char znak;
for (int k = 0; k < tekst.length(); k++){
znak = tekst[k];
tmp = znalezione.find(znak);
if (tmp == -1){ //Jeśli nie znaleziono, dodajemy nowy znak do słownika/sringa
znalezione += znak;
wystapienia[size++] = 1; //Zwiększamy indeks wystapienia danego znaku(nowego)
}
else
wystapienia[tmp] ++; //Zwiekszamy indeks znalezionego znaku
}
//Tworzenie podstawowych jednostek drzew
znaki = new Node[size];
for (int k = 0; k < size; k++){
znaki[k] = Node(znalezione[k],wystapienia[k]);
}
//Porzadki
this->size = size;
tablica = znalezione;
delete[] wystapienia;
}
void AHuffman::StworzDrzewo(){
//Zapisywanie adresow wszystkich lisci
Node** drzewa = new Node*[size];
for (int k = 0; k < size; k++){
drzewa[k] = &znaki[k];
}
//Zmienne pomocnicze
int zmsize = size;
MM indeksy;
Node* tmp;
while (zmsize > 1){ //Dopoki mamy wiecej niz jeden element w tablicy
indeksy = MinMin(drzewa, zmsize); //Znalezienie najmniejszych elementow
if (indeksy.max != indeksy.min){ //dodatkowe zabezpieczenie - nie potrzebne
tmp = new Node(drzewa[indeksy.min]->wartosc + drzewa[indeksy.max]->wartosc); //Tworzenie nowego wezla
//Ustawianie zmiennych wezla
tmp->left = drzewa[indeksy.min];
tmp->right = drzewa[indeksy.max];
drzewa[indeksy.min] = tmp; //Podmiana starego elementu na wezel
swap(drzewa[indeksy.max], drzewa[--zmsize]); //Podmiana i usuniecie ostatniego elementu z tabliy (zmiejszenie rozmiaru)
\
}
}
Drzewo = drzewa[0]; //Zapamietanie adresu drzewa
delete[] drzewa; //Usuniecie pomocniczej tablicy
}
void AHuffman::StworzSlownik(){
Przechodz(Drzewo,""); //Aktualizacja elementow drzewa - zapamietuje sciezki do kazdego nodea - tworzy slownik
}
//Algorytm kodujacy
void AHuffman::Przechodz(Node* element, string kod){ //Przejscie przez drzewo typem (?)
if (element == NULL)
return;
if (element->left)
Przechodz(element->left,kod+"0");
element->Odwiedz(kod);
if (element->right)
Przechodz(element->right, kod + "1");
}
string AHuffman::Translate(){
string zwrot="";
for (int k = 0; k < tekst.length(); k++){
zwrot += znaki[tablica.find(tekst[k])].kod;
}
zakodowane = zwrot;
return zwrot;
}
//Funkcje Glowne
string AHuffman::Koduj(string tresc){
tekst = tresc;
StworzListe();
StworzDrzewo();
StworzSlownik();
//Pomocnicze wypisanie slownika
for (int k = 0; k < size; k++)
cout << znaki[k].znak << " " << znaki[k].kod << endl;
return Translate();
}
string AHuffman::Dekoduj(string tresc ){
if (tresc == "")
tresc = zakodowane;
string zwrot = "";
//Odczytywanie liter ze slownika - przechodzenie przez drzewo za pomoca podanego schamatu
Node* tmp = Drzewo;
for (int k = 0; k <= tresc.length(); k++){
if (tmp->CzyLisc){
zwrot += tmp->znak;
tmp = Drzewo;
}
if (k == tresc.length())
break;
if (tresc[k] == '0')
tmp = tmp->left;
else
tmp = tmp->right;
}
return zwrot;
}
//Funkcja pomocnicza
MM AHuffman::MinMin(Node**tab, int size){
MM MiMa, zwrot; // min = min1, max = min2
zwrot.min = 0;
zwrot.max = 0;
MiMa.max = -1;
MiMa.min = -1;
int tmp;
for (int k = 0; k < size; k++){
tmp = tab[k]->wartosc;
if (tmp < MiMa.max || MiMa.max == -1){
zwrot.max = k;
MiMa.max = tmp;
}
else if (tmp <= MiMa.min || MiMa.min == -1){
zwrot.min = k;
MiMa.min = tmp;
}
}
swap(zwrot.max, zwrot.min);
return zwrot;
}
}#include "AlgHuff.h"
namespace _AHuffman{
//Konstruktory i destruktory
AHuffman::~AHuffman()
{
if (znaki != NULL)
delete[] znaki;
}
//Tworzenie potrzebnych struktur
void AHuffman::StworzListe(){
string znalezione = "";
int* wystapienia = new int[MaksZnakow];
int size = 0;
//Zliczenie wystepujacych znakow
int tmp;
char znak;
for (int k = 0; k < tekst.length(); k++){
znak = tekst[k];
tmp = znalezione.find(znak);
if (tmp == -1){ //Jeśli nie znaleziono, dodajemy nowy znak do słownika/sringa
znalezione += znak;
wystapienia[size++] = 1; //Zwiększamy indeks wystapienia danego znaku(nowego)
}
else
wystapienia[tmp] ++; //Zwiekszamy indeks znalezionego znaku
}
//Tworzenie podstawowych jednostek drzew
znaki = new Node[size];
for (int k = 0; k < size; k++){
znaki[k] = Node(znalezione[k],wystapienia[k]);
}
//Porzadki
this->size = size;
tablica = znalezione;
delete[] wystapienia;
}
void AHuffman::StworzDrzewo(){
//Zapisywanie adresow wszystkich lisci
Node** drzewa = new Node*[size];
for (int k = 0; k < size; k++){
drzewa[k] = &znaki[k];
}
//Zmienne pomocnicze
int zmsize = size;
MM indeksy;
Node* tmp;
while (zmsize > 1){ //Dopoki mamy wiecej niz jeden element w tablicy
indeksy = MinMin(drzewa, zmsize); //Znalezienie najmniejszych elementow
if (indeksy.max != indeksy.min){ //dodatkowe zabezpieczenie - nie potrzebne
tmp = new Node(drzewa[indeksy.min]->wartosc + drzewa[indeksy.max]->wartosc); //Tworzenie nowego wezla
//Ustawianie zmiennych wezla
tmp->left = drzewa[indeksy.min];
tmp->right = drzewa[indeksy.max];
drzewa[indeksy.min] = tmp; //Podmiana starego elementu na wezel
swap(drzewa[indeksy.max], drzewa[--zmsize]); //Podmiana i usuniecie ostatniego elementu z tabliy (zmiejszenie rozmiaru)
\
}
}
Drzewo = drzewa[0]; //Zapamietanie adresu drzewa
delete[] drzewa; //Usuniecie pomocniczej tablicy
}
void AHuffman::StworzSlownik(){
Przechodz(Drzewo,""); //Aktualizacja elementow drzewa - zapamietuje sciezki do kazdego nodea - tworzy slownik
}
//Algorytm kodujacy
void AHuffman::Przechodz(Node* element, string kod){ //Przejscie przez drzewo typem (?)
if (element == NULL)
return;
if (element->left)
Przechodz(element->left,kod+"0");
element->Odwiedz(kod);
if (element->right)
Przechodz(element->right, kod + "1");
}
string AHuffman::Translate(){
string zwrot="";
for (int k = 0; k < tekst.length(); k++){
zwrot += znaki[tablica.find(tekst[k])].kod;
}
zakodowane = zwrot;
return zwrot;
}
//Funkcje Glowne
string AHuffman::Koduj(string tresc){
tekst = tresc;
StworzListe();
StworzDrzewo();
StworzSlownik();
//Pomocnicze wypisanie slownika
for (int k = 0; k < size; k++)
cout << znaki[k].znak << " " << znaki[k].kod << endl;
return Translate();
}
string AHuffman::Dekoduj(string tresc ){
if (tresc == "")
tresc = zakodowane;
string zwrot = "";
//Odczytywanie liter ze slownika - przechodzenie przez drzewo za pomoca podanego schamatu
Node* tmp = Drzewo;
for (int k = 0; k <= tresc.length(); k++){
if (tmp->CzyLisc){
zwrot += tmp->znak;
tmp = Drzewo;
}
if (k == tresc.length())
break;
if (tresc[k] == '0')
tmp = tmp->left;
else
tmp = tmp->right;
}
return zwrot;
}
//Funkcja pomocnicza
MM AHuffman::MinMin(Node**tab, int size){
MM MiMa, zwrot; // min = min1, max = min2
zwrot.min = 0;
zwrot.max = 0;
MiMa.max = -1;
MiMa.min = -1;
int tmp;
for (int k = 0; k < size; k++){
tmp = tab[k]->wartosc;
if (tmp < MiMa.max || MiMa.max == -1){
zwrot.max = k;
MiMa.max = tmp;
}
else if (tmp <= MiMa.min || MiMa.min == -1){
zwrot.min = k;
MiMa.min = tmp;
}
}
swap(zwrot.max, zwrot.min);
return zwrot;
}
}#include "AlgHuff.h"
namespace _AHuffman{
//Konstruktory i destruktory
AHuffman::~AHuffman()
{
if (znaki != NULL)
delete[] znaki;
}
//Tworzenie potrzebnych struktur
void AHuffman::StworzListe(){
string znalezione = "";
int* wystapienia = new int[MaksZnakow];
int size = 0;
//Zliczenie wystepujacych znakow
int tmp;
char znak;
for (int k = 0; k < tekst.length(); k++){
znak = tekst[k];
tmp = znalezione.find(znak);
if (tmp == -1){ //Jeśli nie znaleziono, dodajemy nowy znak do słownika/sringa
znalezione += znak;
wystapienia[size++] = 1; //Zwiększamy indeks wystapienia danego znaku(nowego)
}
else
wystapienia[tmp] ++; //Zwiekszamy indeks znalezionego znaku
}
//Tworzenie podstawowych jednostek drzew
znaki = new Node[size];
for (int k = 0; k < size; k++){
znaki[k] = Node(znalezione[k],wystapienia[k]);
}
//Porzadki
this->size = size;
tablica = znalezione;
delete[] wystapienia;
}
void AHuffman::StworzDrzewo(){
//Zapisywanie adresow wszystkich lisci
Node** drzewa = new Node*[size];
for (int k = 0; k < size; k++){
drzewa[k] = &znaki[k];
}
//Zmienne pomocnicze
int zmsize = size;
MM indeksy;
Node* tmp;
while (zmsize > 1){ //Dopoki mamy wiecej niz jeden element w tablicy
indeksy = MinMin(drzewa, zmsize); //Znalezienie najmniejszych elementow
if (indeksy.max != indeksy.min){ //dodatkowe zabezpieczenie - nie potrzebne
tmp = new Node(drzewa[indeksy.min]->wartosc + drzewa[indeksy.max]->wartosc); //Tworzenie nowego wezla
//Ustawianie zmiennych wezla
tmp->left = drzewa[indeksy.min];
tmp->right = drzewa[indeksy.max];
drzewa[indeksy.min] = tmp; //Podmiana starego elementu na wezel
swap(drzewa[indeksy.max], drzewa[--zmsize]); //Podmiana i usuniecie ostatniego elementu z tabliy (zmiejszenie rozmiaru)
\
}
}
Drzewo = drzewa[0]; //Zapamietanie adresu drzewa
delete[] drzewa; //Usuniecie pomocniczej tablicy
}
void AHuffman::StworzSlownik(){
Przechodz(Drzewo,""); //Aktualizacja elementow drzewa - zapamietuje sciezki do kazdego nodea - tworzy slownik
}
//Algorytm kodujacy
void AHuffman::Przechodz(Node* element, string kod){ //Przejscie przez drzewo typem (?)
if (element == NULL)
return;
if (element->left)
Przechodz(element->left,kod+"0");
element->Odwiedz(kod);
if (element->right)
Przechodz(element->right, kod + "1");
}
string AHuffman::Translate(){
string zwrot="";
for (int k = 0; k < tekst.length(); k++){
zwrot += znaki[tablica.find(tekst[k])].kod;
}
zakodowane = zwrot;
return zwrot;
}
//Funkcje Glowne
string AHuffman::Koduj(string tresc){
tekst = tresc;
StworzListe();
StworzDrzewo();
StworzSlownik();
//Pomocnicze wypisanie slownika
for (int k = 0; k < size; k++)
cout << znaki[k].znak << " " << znaki[k].kod << endl;
return Translate();
}
string AHuffman::Dekoduj(string tresc ){
if (tresc == "")
tresc = zakodowane;
string zwrot = "";
//Odczytywanie liter ze slownika - przechodzenie przez drzewo za pomoca podanego schamatu
Node* tmp = Drzewo;
for (int k = 0; k <= tresc.length(); k++){
if (tmp->CzyLisc){
zwrot += tmp->znak;
tmp = Drzewo;
}
if (k == tresc.length())
break;
if (tresc[k] == '0')
tmp = tmp->left;
else
tmp = tmp->right;
}
return zwrot;
}
//Funkcja pomocnicza
MM AHuffman::MinMin(Node**tab, int size){
MM MiMa, zwrot; // min = min1, max = min2
zwrot.min = 0;
zwrot.max = 0;
MiMa.max = -1;
MiMa.min = -1;
int tmp;
for (int k = 0; k < size; k++){
tmp = tab[k]->wartosc;
if (tmp < MiMa.max || MiMa.max == -1){
zwrot.max = k;
MiMa.max = tmp;
}
else if (tmp <= MiMa.min || MiMa.min == -1){
zwrot.min = k;
MiMa.min = tmp;
}
}
swap(zwrot.max, zwrot.min);
return zwrot;
}
}#include "AlgHuff.h"
namespace _AHuffman{
//Konstruktory i destruktory
AHuffman::~AHuffman()
{
if (znaki != NULL)
delete[] znaki;
}
//Tworzenie potrzebnych struktur
void AHuffman::StworzListe(){
string znalezione = "";
int* wystapienia = new int[MaksZnakow];
int size = 0;
//Zliczenie wystepujacych znakow
int tmp;
char znak;
for (int k = 0; k < tekst.length(); k++){
znak = tekst[k];
tmp = znalezione.find(znak);
if (tmp == -1){ //Jeśli nie znaleziono, dodajemy nowy znak do słownika/sringa
znalezione += znak;
wystapienia[size++] = 1; //Zwiększamy indeks wystapienia danego znaku(nowego)
}
else
wystapienia[tmp] ++; //Zwiekszamy indeks znalezionego znaku
}
//Tworzenie podstawowych jednostek drzew
znaki = new Node[size];
for (int k = 0; k < size; k++){
znaki[k] = Node(znalezione[k],wystapienia[k]);
}
//Porzadki
this->size = size;
tablica = znalezione;
delete[] wystapienia;
}
void AHuffman::StworzDrzewo(){
//Zapisywanie adresow wszystkich lisci
Node** drzewa = new Node*[size];
for (int k = 0; k < size; k++){
drzewa[k] = &znaki[k];
}
//Zmienne pomocnicze
int zmsize = size;
MM indeksy;
Node* tmp;
while (zmsize > 1){ //Dopoki mamy wiecej niz jeden element w tablicy
indeksy = MinMin(drzewa, zmsize); //Znalezienie najmniejszych elementow
if (indeksy.max != indeksy.min){ //dodatkowe zabezpieczenie - nie potrzebne
tmp = new Node(drzewa[indeksy.min]->wartosc + drzewa[indeksy.max]->wartosc); //Tworzenie nowego wezla
//Ustawianie zmiennych wezla
tmp->left = drzewa[indeksy.min];
tmp->right = drzewa[indeksy.max];
drzewa[indeksy.min] = tmp; //Podmiana starego elementu na wezel
swap(drzewa[indeksy.max], drzewa[--zmsize]); //Podmiana i usuniecie ostatniego elementu z tabliy (zmiejszenie rozmiaru)
\
}
}
Drzewo = drzewa[0]; //Zapamietanie adresu drzewa
delete[] drzewa; //Usuniecie pomocniczej tablicy
}
void AHuffman::StworzSlownik(){
Przechodz(Drzewo,""); //Aktualizacja elementow drzewa - zapamietuje sciezki do kazdego nodea - tworzy slownik
}
//Algorytm kodujacy
void AHuffman::Przechodz(Node* element, string kod){ //Przejscie przez drzewo typem (?)
if (element == NULL)
return;
if (element->left)
Przechodz(element->left,kod+"0");
element->Odwiedz(kod);
if (element->right)
Przechodz(element->right, kod + "1");
}
string AHuffman::Translate(){
string zwrot="";
for (int k = 0; k < tekst.length(); k++){
zwrot += znaki[tablica.find(tekst[k])].kod;
}
zakodowane = zwrot;
return zwrot;
}
//Funkcje Glowne
string AHuffman::Koduj(string tresc){
tekst = tresc;
StworzListe();
StworzDrzewo();
StworzSlownik();
//Pomocnicze wypisanie slownika
for (int k = 0; k < size; k++)
cout << znaki[k].znak << " " << znaki[k].kod << endl;
return Translate();
}
string AHuffman::Dekoduj(string tresc ){
if (tresc == "")
tresc = zakodowane;
string zwrot = "";
//Odczytywanie liter ze slownika - przechodzenie przez drzewo za pomoca podanego schamatu
Node* tmp = Drzewo;
for (int k = 0; k <= tresc.length(); k++){
if (tmp->CzyLisc){
zwrot += tmp->znak;
tmp = Drzewo;
}
if (k == tresc.length())
break;
if (tresc[k] == '0')
tmp = tmp->left;
else
tmp = tmp->right;
}
return zwrot;
}
//Funkcja pomocnicza
MM AHuffman::MinMin(Node**tab, int size){
MM MiMa, zwrot; // min = min1, max = min2
zwrot.min = 0;
zwrot.max = 0;
MiMa.max = -1;
MiMa.min = -1;
int tmp;
for (int k = 0; k < size; k++){
tmp = tab[k]->wartosc;
if (tmp < MiMa.max || MiMa.max == -1){
zwrot.max = k;
MiMa.max = tmp;
}
else if (tmp <= MiMa.min || MiMa.min == -1){
zwrot.min = k;
MiMa.min = tmp;
}
}
swap(zwrot.max, zwrot.min);
return zwrot;
}
}#include "AlgHuff.h"
namespace _AHuffman{
//Konstruktory i destruktory
AHuffman::~AHuffman()
{
if (znaki != NULL)
delete[] znaki;
}
//Tworzenie potrzebnych struktur
void AHuffman::StworzListe(){
string znalezione = "";
int* wystapienia = new int[MaksZnakow];
int size = 0;
//Zliczenie wystepujacych znakow
int tmp;
char znak;
for (int k = 0; k < tekst.length(); k++){
znak = tekst[k];
tmp = znalezione.find(znak);
if (tmp == -1){ //Jeśli nie znaleziono, dodajemy nowy znak do słownika/sringa
znalezione += znak;
wystapienia[size++] = 1; //Zwiększamy indeks wystapienia danego znaku(nowego)
}
else
wystapienia[tmp] ++; //Zwiekszamy indeks znalezionego znaku
}
//Tworzenie podstawowych jednostek drzew
znaki = new Node[size];
for (int k = 0; k < size; k++){
znaki[k] = Node(znalezione[k],wystapienia[k]);
}
//Porzadki
this->size = size;
tablica = znalezione;
delete[] wystapienia;
}
void AHuffman::StworzDrzewo(){
//Zapisywanie adresow wszystkich lisci
Node** drzewa = new Node*[size];
for (int k = 0; k < size; k++){
drzewa[k] = &znaki[k];
}
//Zmienne pomocnicze
int zmsize = size;
MM indeksy;
Node* tmp;
while (zmsize > 1){ //Dopoki mamy wiecej niz jeden element w tablicy
indeksy = MinMin(drzewa, zmsize); //Znalezienie najmniejszych elementow
if (indeksy.max != indeksy.min){ //dodatkowe zabezpieczenie - nie potrzebne
tmp = new Node(drzewa[indeksy.min]->wartosc + drzewa[indeksy.max]->wartosc); //Tworzenie nowego wezla
//Ustawianie zmiennych wezla
tmp->left = drzewa[indeksy.min];
tmp->right = drzewa[indeksy.max];
drzewa[indeksy.min] = tmp; //Podmiana starego elementu na wezel
swap(drzewa[indeksy.max], drzewa[--zmsize]); //Podmiana i usuniecie ostatniego elementu z tabliy (zmiejszenie rozmiaru)
\
}
}
Drzewo = drzewa[0]; //Zapamietanie adresu drzewa
delete[] drzewa; //Usuniecie pomocniczej tablicy
}
void AHuffman::StworzSlownik(){
Przechodz(Drzewo,""); //Aktualizacja elementow drzewa - zapamietuje sciezki do kazdego nodea - tworzy slownik
}
//Algorytm kodujacy
void AHuffman::Przechodz(Node* element, string kod){ //Przejscie przez drzewo typem (?)
if (element == NULL)
return;
if (element->left)
Przechodz(element->left,kod+"0");
element->Odwiedz(kod);
if (element->right)
Przechodz(element->right, kod + "1");
}
string AHuffman::Translate(){
string zwrot="";
for (int k = 0; k < tekst.length(); k++){
zwrot += znaki[tablica.find(tekst[k])].kod;
}
zakodowane = zwrot;
return zwrot;
}
//Funkcje Glowne
string AHuffman::Koduj(string tresc){
tekst = tresc;
StworzListe();
StworzDrzewo();
StworzSlownik();
//Pomocnicze wypisanie slownika
for (int k = 0; k < size; k++)
cout << znaki[k].znak << " " << znaki[k].kod << endl;
return Translate();
}
string AHuffman::Dekoduj(string tresc ){
if (tresc == "")
tresc = zakodowane;
string zwrot = "";
//Odczytywanie liter ze slownika - przechodzenie przez drzewo za pomoca podanego schamatu
Node* tmp = Drzewo;
for (int k = 0; k <= tresc.length(); k++){
if (tmp->CzyLisc){
zwrot += tmp->znak;
tmp = Drzewo;
}
if (k == tresc.length())
break;
if (tresc[k] == '0')
tmp = tmp->left;
else
tmp = tmp->right;
}
return zwrot;
}
//Funkcja pomocnicza
MM AHuffman::MinMin(Node**tab, int size){
MM MiMa, zwrot; // min = min1, max = min2
zwrot.min = 0;
zwrot.max = 0;
MiMa.max = -1;
MiMa.min = -1;
int tmp;
for (int k = 0; k < size; k++){
tmp = tab[k]->wartosc;
if (tmp < MiMa.max || MiMa.max == -1){
zwrot.max = k;
MiMa.max = tmp;
}
else if (tmp <= MiMa.min || MiMa.min == -1){
zwrot.min = k;
MiMa.min = tmp;
}
}
swap(zwrot.max, zwrot.min);
return zwrot;
}
}#include "AlgHuff.h"
namespace _AHuffman{
//Konstruktory i destruktory
AHuffman::~AHuffman()
{
if (znaki != NULL)
delete[] znaki;
}
//Tworzenie potrzebnych struktur
void AHuffman::StworzListe(){
string znalezione = "";
int* wystapienia = new int[MaksZnakow];
int size = 0;
//Zliczenie wystepujacych znakow
int tmp;
char znak;
for (int k = 0; k < tekst.length(); k++){
znak = tekst[k];
tmp = znalezione.find(znak);
if (tmp == -1){ //Jeśli nie znaleziono, dodajemy nowy znak do słownika/sringa
znalezione += znak;
wystapienia[size++] = 1; //Zwiększamy indeks wystapienia danego znaku(nowego)
}
else
wystapienia[tmp] ++; //Zwiekszamy indeks znalezionego znaku
}
//Tworzenie podstawowych jednostek drzew
znaki = new Node[size];
for (int k = 0; k < size; k++){
znaki[k] = Node(znalezione[k],wystapienia[k]);
}
//Porzadki
this->size = size;
tablica = znalezione;
delete[] wystapienia;
}
void AHuffman::StworzDrzewo(){
//Zapisywanie adresow wszystkich lisci
Node** drzewa = new Node*[size];
for (int k = 0; k < size; k++){
drzewa[k] = &znaki[k];
}
//Zmienne pomocnicze
int zmsize = size;
MM indeksy;
Node* tmp;
while (zmsize > 1){ //Dopoki mamy wiecej niz jeden element w tablicy
indeksy = MinMin(drzewa, zmsize); //Znalezienie najmniejszych elementow
if (indeksy.max != indeksy.min){ //dodatkowe zabezpieczenie - nie potrzebne
tmp = new Node(drzewa[indeksy.min]->wartosc + drzewa[indeksy.max]->wartosc); //Tworzenie nowego wezla
//Ustawianie zmiennych wezla
tmp->left = drzewa[indeksy.min];
tmp->right = drzewa[indeksy.max];
drzewa[indeksy.min] = tmp; //Podmiana starego elementu na wezel
swap(drzewa[indeksy.max], drzewa[--zmsize]); //Podmiana i usuniecie ostatniego elementu z tabliy (zmiejszenie rozmiaru)
\
}
}
Drzewo = drzewa[0]; //Zapamietanie adresu drzewa
delete[] drzewa; //Usuniecie pomocniczej tablicy
}
void AHuffman::StworzSlownik(){
Przechodz(Drzewo,""); //Aktualizacja elementow drzewa - zapamietuje sciezki do kazdego nodea - tworzy slownik
}
//Algorytm kodujacy
void AHuffman::Przechodz(Node* element, string kod){ //Przejscie przez drzewo typem (?)
if (element == NULL)
return;
if (element->left)
Przechodz(element->left,kod+"0");
element->Odwiedz(kod);
if (element->right)
Przechodz(element->right, kod + "1");
}
string AHuffman::Translate(){
string zwrot="";
for (int k = 0; k < tekst.length(); k++){
zwrot += znaki[tablica.find(tekst[k])].kod;
}
zakodowane = zwrot;
return zwrot;
}
//Funkcje Glowne
string AHuffman::Koduj(string tresc){
tekst = tresc;
StworzListe();
StworzDrzewo();
StworzSlownik();
//Pomocnicze wypisanie slownika
for (int k = 0; k < size; k++)
cout << znaki[k].znak << " " << znaki[k].kod << endl;
return Translate();
}
string AHuffman::Dekoduj(string tresc ){
if (tresc == "")
tresc = zakodowane;
string zwrot = "";
//Odczytywanie liter ze slownika - przechodzenie przez drzewo za pomoca podanego schamatu
Node* tmp = Drzewo;
for (int k = 0; k <= tresc.length(); k++){
if (tmp->CzyLisc){
zwrot += tmp->znak;
tmp = Drzewo;
}
if (k == tresc.length())
break;
if (tresc[k] == '0')
tmp = tmp->left;
else
tmp = tmp->right;
}
return zwrot;
}
//Funkcja pomocnicza
MM AHuffman::MinMin(Node**tab, int size){
MM MiMa, zwrot; // min = min1, max = min2
zwrot.min = 0;
zwrot.max = 0;
MiMa.max = -1;
MiMa.min = -1;
int tmp;
for (int k = 0; k < size; k++){
tmp = tab[k]->wartosc;
if (tmp < MiMa.max || MiMa.max == -1){
zwrot.max = k;
MiMa.max = tmp;
}
else if (tmp <= MiMa.min || MiMa.min == -1){
zwrot.min = k;
MiMa.min = tmp;
}
}
swap(zwrot.max, zwrot.min);
return zwrot;
}
}#include "AlgHuff.h"
namespace _AHuffman{
//Konstruktory i destruktory
AHuffman::~AHuffman()
{
if (znaki != NULL)
delete[] znaki;
}
//Tworzenie potrzebnych struktur
void AHuffman::StworzListe(){
string znalezione = "";
int* wystapienia = new int[MaksZnakow];
int size = 0;
//Zliczenie wystepujacych znakow
int tmp;
char znak;
for (int k = 0; k < tekst.length(); k++){
znak = tekst[k];
tmp = znalezione.find(znak);
if (tmp == -1){ //Jeśli nie znaleziono, dodajemy nowy znak do słownika/sringa
znalezione += znak;
wystapienia[size++] = 1; //Zwiększamy indeks wystapienia danego znaku(nowego)
}
else
wystapienia[tmp] ++; //Zwiekszamy indeks znalezionego znaku
}
//Tworzenie podstawowych jednostek drzew
znaki = new Node[size];
for (int k = 0; k < size; k++){
znaki[k] = Node(znalezione[k],wystapienia[k]);
}
//Porzadki
this->size = size;
tablica = znalezione;
delete[] wystapienia;
}
void AHuffman::StworzDrzewo(){
//Zapisywanie adresow wszystkich lisci
Node** drzewa = new Node*[size];
for (int k = 0; k < size; k++){
drzewa[k] = &znaki[k];
}
//Zmienne pomocnicze
int zmsize = size;
MM indeksy;
Node* tmp;
while (zmsize > 1){ //Dopoki mamy wiecej niz jeden element w tablicy
indeksy = MinMin(drzewa, zmsize); //Znalezienie najmniejszych elementow
if (indeksy.max != indeksy.min){ //dodatkowe zabezpieczenie - nie potrzebne
tmp = new Node(drzewa[indeksy.min]->wartosc + drzewa[indeksy.max]->wartosc); //Tworzenie nowego wezla
//Ustawianie zmiennych wezla
tmp->left = drzewa[indeksy.min];
tmp->right = drzewa[indeksy.max];
drzewa[indeksy.min] = tmp; //Podmiana starego elementu na wezel
swap(drzewa[indeksy.max], drzewa[--zmsize]); //Podmiana i usuniecie ostatniego elementu z tabliy (zmiejszenie rozmiaru)
\
}
}
Drzewo = drzewa[0]; //Zapamietanie adresu drzewa
delete[] drzewa; //Usuniecie pomocniczej tablicy
}
void AHuffman::StworzSlownik(){
Przechodz(Drzewo,""); //Aktualizacja elementow drzewa - zapamietuje sciezki do kazdego nodea - tworzy slownik
}
//Algorytm kodujacy
void AHuffman::Przechodz(Node* element, string kod){ //Przejscie przez drzewo typem (?)
if (element == NULL)
return;
if (element->left)
Przechodz(element->left,kod+"0");
element->Odwiedz(kod);
if (element->right)
Przechodz(element->right, kod + "1");
}
string AHuffman::Translate(){
string zwrot="";
for (int k = 0; k < tekst.length(); k++){
zwrot += znaki[tablica.find(tekst[k])].kod;
}
zakodowane = zwrot;
return zwrot;
}
//Funkcje Glowne
string AHuffman::Koduj(string tresc){
tekst = tresc;
StworzListe();
StworzDrzewo();
StworzSlownik();
//Pomocnicze wypisanie slownika
for (int k = 0; k < size; k++)
cout << znaki[k].znak << " " << znaki[k].kod << endl;
return Translate();
}
string AHuffman::Dekoduj(string tresc ){
if (tresc == "")
tresc = zakodowane;
string zwrot = "";
//Odczytywanie liter ze slownika - przechodzenie przez drzewo za pomoca podanego schamatu
Node* tmp = Drzewo;
for (int k = 0; k <= tresc.length(); k++){
if (tmp->CzyLisc){
zwrot += tmp->znak;
tmp = Drzewo;
}
if (k == tresc.length())
break;
if (tresc[k] == '0')
tmp = tmp->left;
else
tmp = tmp->right;
}
return zwrot;
}
//Funkcja pomocnicza
MM AHuffman::MinMin(Node**tab, int size){
MM MiMa, zwrot; // min = min1, max = min2
zwrot.min = 0;
zwrot.max = 0;
MiMa.max = -1;
MiMa.min = -1;
int tmp;
for (int k = 0; k < size; k++){
tmp = tab[k]->wartosc;
if (tmp < MiMa.max || MiMa.max == -1){
zwrot.max = k;
MiMa.max = tmp;
}
else if (tmp <= MiMa.min || MiMa.min == -1){
zwrot.min = k;
MiMa.min = tmp;
}
}
swap(zwrot.max, zwrot.min);
return zwrot;
}
}#include "AlgHuff.h"
namespace _AHuffman{
//Konstruktory i destruktory
AHuffman::~AHuffman()
{
if (znaki != NULL)
delete[] znaki;
}
//Tworzenie potrzebnych struktur
void AHuffman::StworzListe(){
string znalezione = "";
int* wystapienia = new int[MaksZnakow];
int size = 0;
//Zliczenie wystepujacych znakow
int tmp;
char znak;
for (int k = 0; k < tekst.length(); k++){
znak = tekst[k];
tmp = znalezione.find(znak);
if (tmp == -1){ //Jeśli nie znaleziono, dodajemy nowy znak do słownika/sringa
znalezione += znak;
wystapienia[size++] = 1; //Zwiększamy indeks wystapienia danego znaku(nowego)
}
else
wystapienia[tmp] ++; //Zwiekszamy indeks znalezionego znaku
}
//Tworzenie podstawowych jednostek drzew
znaki = new Node[size];
for (int k = 0; k < size; k++){
znaki[k] = Node(znalezione[k],wystapienia[k]);
}
//Porzadki
this->size = size;
tablica = znalezione;
delete[] wystapienia;
}
void AHuffman::StworzDrzewo(){
//Zapisywanie adresow wszystkich lisci
Node** drzewa = new Node*[size];
for (int k = 0; k < size; k++){
drzewa[k] = &znaki[k];
}
//Zmienne pomocnicze
int zmsize = size;
MM indeksy;
Node* tmp;
while (zmsize > 1){ //Dopoki mamy wiecej niz jeden element w tablicy
indeksy = MinMin(drzewa, zmsize); //Znalezienie najmniejszych elementow
if (indeksy.max != indeksy.min){ //dodatkowe zabezpieczenie - nie potrzebne
tmp = new Node(drzewa[indeksy.min]->wartosc + drzewa[indeksy.max]->wartosc); //Tworzenie nowego wezla
//Ustawianie zmiennych wezla
tmp->left = drzewa[indeksy.min];
tmp->right = drzewa[indeksy.max];
drzewa[indeksy.min] = tmp; //Podmiana starego elementu na wezel
swap(drzewa[indeksy.max], drzewa[--zmsize]); //Podmiana i usuniecie ostatniego elementu z tabliy (zmiejszenie rozmiaru)
\
}
}
Drzewo = drzewa[0]; //Zapamietanie adresu drzewa
delete[] drzewa; //Usuniecie pomocniczej tablicy
}
void AHuffman::StworzSlownik(){
Przechodz(Drzewo,""); //Aktualizacja elementow drzewa - zapamietuje sciezki do kazdego nodea - tworzy slownik
}
//Algorytm kodujacy
void AHuffman::Przechodz(Node* element, string kod){ //Przejscie przez drzewo typem (?)
if (element == NULL)
return;
if (element->left)
Przechodz(element->left,kod+"0");
element->Odwiedz(kod);
if (element->right)
Przechodz(element->right, kod + "1");
}
string AHuffman::Translate(){
string zwrot="";
for (int k = 0; k < tekst.length(); k++){
zwrot += znaki[tablica.find(tekst[k])].kod;
}
zakodowane = zwrot;
return zwrot;
}
//Funkcje Glowne
string AHuffman::Koduj(string tresc){
tekst = tresc;
StworzListe();
StworzDrzewo();
StworzSlownik();
//Pomocnicze wypisanie slownika
for (int k = 0; k < size; k++)
cout << znaki[k].znak << " " << znaki[k].kod << endl;
return Translate();
}
string AHuffman::Dekoduj(string tresc ){
if (tresc == "")
tresc = zakodowane;
string zwrot = "";
//Odczytywanie liter ze slownika - przechodzenie przez drzewo za pomoca podanego schamatu
Node* tmp = Drzewo;
for (int k = 0; k <= tresc.length(); k++){
if (tmp->CzyLisc){
zwrot += tmp->znak;
tmp = Drzewo;
}
if (k == tresc.length())
break;
if (tresc[k] == '0')
tmp = tmp->left;
else
tmp = tmp->right;
}
return zwrot;
}
//Funkcja pomocnicza
MM AHuffman::MinMin(Node**tab, int size){
MM MiMa, zwrot; // min = min1, max = min2
zwrot.min = 0;
zwrot.max = 0;
MiMa.max = -1;
MiMa.min = -1;
int tmp;
for (int k = 0; k < size; k++){
tmp = tab[k]->wartosc;
if (tmp < MiMa.max || MiMa.max == -1){
zwrot.max = k;
MiMa.max = tmp;
}
else if (tmp <= MiMa.min || MiMa.min == -1){
zwrot.min = k;
MiMa.min = tmp;
}
}
swap(zwrot.max, zwrot.min);
return zwrot;
}
}#include "AlgHuff.h"
namespace _AHuffman{
//Konstruktory i destruktory
AHuffman::~AHuffman()
{
if (znaki != NULL)
delete[] znaki;
}
//Tworzenie potrzebnych struktur
void AHuffman::StworzListe(){
string znalezione = "";
int* wystapienia = new int[MaksZnakow];
int size = 0;
//Zliczenie wystepujacych znakow
int tmp;
char znak;
for (int k = 0; k < tekst.length(); k++){
znak = tekst[k];
tmp = znalezione.find(znak);
if (tmp == -1){ //Jeśli nie znaleziono, dodajemy nowy znak do słownika/sringa
znalezione += znak;
wystapienia[size++] = 1; //Zwiększamy indeks wystapienia danego znaku(nowego)
}
else
wystapienia[tmp] ++; //Zwiekszamy indeks znalezionego znaku
}
//Tworzenie podstawowych jednostek drzew
znaki = new Node[size];
for (int k = 0; k < size; k++){
znaki[k] = Node(znalezione[k],wystapienia[k]);
}
//Porzadki
this->size = size;
tablica = znalezione;
delete[] wystapienia;
}
void AHuffman::StworzDrzewo(){
//Zapisywanie adresow wszystkich lisci
Node** drzewa = new Node*[size];
for (int k = 0; k < size; k++){
drzewa[k] = &znaki[k];
}
//Zmienne pomocnicze
int zmsize = size;
MM indeksy;
Node* tmp;
while (zmsize > 1){ //Dopoki mamy wiecej niz jeden element w tablicy
indeksy = MinMin(drzewa, zmsize); //Znalezienie najmniejszych elementow
if (indeksy.max != indeksy.min){ //dodatkowe zabezpieczenie - nie potrzebne
tmp = new Node(drzewa[indeksy.min]->wartosc + drzewa[indeksy.max]->wartosc); //Tworzenie nowego wezla
//Ustawianie zmiennych wezla
tmp->left = drzewa[indeksy.min];
tmp->right = drzewa[indeksy.max];
drzewa[indeksy.min] = tmp; //Podmiana starego elementu na wezel
swap(drzewa[indeksy.max], drzewa[--zmsize]); //Podmiana i usuniecie ostatniego elementu z tabliy (zmiejszenie rozmiaru)
\
}
}
Drzewo = drzewa[0]; //Zapamietanie adresu drzewa
delete[] drzewa; //Usuniecie pomocniczej tablicy
}
void AHuffman::StworzSlownik(){
Przechodz(Drzewo,""); //Aktualizacja elementow drzewa - zapamietuje sciezki do kazdego nodea - tworzy slownik
}
//Algorytm kodujacy
void AHuffman::Przechodz(Node* element, string kod){ //Przejscie przez drzewo typem (?)
if (element == NULL)
return;
if (element->left)
Przechodz(element->left,kod+"0");
element->Odwiedz(kod);
if (element->right)
Przechodz(element->right, kod + "1");
}
string AHuffman::Translate(){
string zwrot="";
for (int k = 0; k < tekst.length(); k++){
zwrot += znaki[tablica.find(tekst[k])].kod;
}
zakodowane = zwrot;
return zwrot;
}
//Funkcje Glowne
string AHuffman::Koduj(string tresc){
tekst = tresc;
StworzListe();
StworzDrzewo();
StworzSlownik();
//Pomocnicze wypisanie slownika
for (int k = 0; k < size; k++)
cout << znaki[k].znak << " " << znaki[k].kod << endl;
return Translate();
}
string AHuffman::Dekoduj(string tresc ){
if (tresc == "")
tresc = zakodowane;
string zwrot = "";
//Odczytywanie liter ze slownika - przechodzenie przez drzewo za pomoca podanego schamatu
Node* tmp = Drzewo;
for (int k = 0; k <= tresc.length(); k++){
if (tmp->CzyLisc){
zwrot += tmp->znak;
tmp = Drzewo;
}
if (k == tresc.length())
break;
if (tresc[k] == '0')
tmp = tmp->left;
else
tmp = tmp->right;
}
return zwrot;
}
//Funkcja pomocnicza
MM AHuffman::MinMin(Node**tab, int size){
MM MiMa, zwrot; // min = min1, max = min2
zwrot.min = 0;
zwrot.max = 0;
MiMa.max = -1;
MiMa.min = -1;
int tmp;
for (int k = 0; k < size; k++){
tmp = tab[k]->wartosc;
if (tmp < MiMa.max || MiMa.max == -1){
zwrot.max = k;
MiMa.max = tmp;
}
else if (tmp <= MiMa.min || MiMa.min == -1){
zwrot.min = k;
MiMa.min = tmp;
}
}
swap(zwrot.max, zwrot.min);
return zwrot;
}
}#include "AlgHuff.h"
namespace _AHuffman{
//Konstruktory i destruktory
AHuffman::~AHuffman()
{
if (znaki != NULL)
delete[] znaki;
}
//Tworzenie potrzebnych struktur
void AHuffman::StworzListe(){
string znalezione = "";
int* wystapienia = new int[MaksZnakow];
int size = 0;
//Zliczenie wystepujacych znakow
int tmp;
char znak;
for (int k = 0; k < tekst.length(); k++){
znak = tekst[k];
tmp = znalezione.find(znak);
if (tmp == -1){ //Jeśli nie znaleziono, dodajemy nowy znak do słownika/sringa
znalezione += znak;
wystapienia[size++] = 1; //Zwiększamy indeks wystapienia danego znaku(nowego)
}
else
wystapienia[tmp] ++; //Zwiekszamy indeks znalezionego znaku
}
//Tworzenie podstawowych jednostek drzew
znaki = new Node[size];
for (int k = 0; k < size; k++){
znaki[k] = Node(znalezione[k],wystapienia[k]);
}
//Porzadki
this->size = size;
tablica = znalezione;
delete[] wystapienia;
}
void AHuffman::StworzDrzewo(){
//Zapisywanie adresow wszystkich lisci
Node** drzewa = new Node*[size];
for (int k = 0; k < size; k++){
drzewa[k] = &znaki[k];
}
//Zmienne pomocnicze
int zmsize = size;
MM indeksy;
Node* tmp;
while (zmsize > 1){ //Dopoki mamy wiecej niz jeden element w tablicy
indeksy = MinMin(drzewa, zmsize); //Znalezienie najmniejszych elementow
if (indeksy.max != indeksy.min){ //dodatkowe zabezpieczenie - nie potrzebne
tmp = new Node(drzewa[indeksy.min]->wartosc + drzewa[indeksy.max]->wartosc); //Tworzenie nowego wezla
//Ustawianie zmiennych wezla
tmp->left = drzewa[indeksy.min];
tmp->right = drzewa[indeksy.max];
drzewa[indeksy.min] = tmp; //Podmiana starego elementu na wezel
swap(drzewa[indeksy.max], drzewa[--zmsize]); //Podmiana i usuniecie ostatniego elementu z tabliy (zmiejszenie rozmiaru)
\
}
}
Drzewo = drzewa[0]; //Zapamietanie adresu drzewa
delete[] drzewa; //Usuniecie pomocniczej tablicy
}
void AHuffman::StworzSlownik(){
Przechodz(Drzewo,""); //Aktualizacja elementow drzewa - zapamietuje sciezki do kazdego nodea - tworzy slownik
}
//Algorytm kodujacy
void AHuffman::Przechodz(Node* element, string kod){ //Przejscie przez drzewo typem (?)
if (element == NULL)
return;
if (element->left)
Przechodz(element->left,kod+"0");
element->Odwiedz(kod);
if (element->right)
Przechodz(element->right, kod + "1");
}
string AHuffman::Translate(){
string zwrot="";
for (int k = 0; k < tekst.length(); k++){
zwrot += znaki[tablica.find(tekst[k])].kod;
}
zakodowane = zwrot;
return zwrot;
}
//Funkcje Glowne
string AHuffman::Koduj(string tresc){
tekst = tresc;
StworzListe();
StworzDrzewo();
StworzSlownik();
//Pomocnicze wypisanie slownika
for (int k = 0; k < size; k++)
cout << znaki[k].znak << " " << znaki[k].kod << endl;
return Translate();
}
string AHuffman::Dekoduj(string tresc ){
if (tresc == "")
tresc = zakodowane;
string zwrot = "";
//Odczytywanie liter ze slownika - przechodzenie przez drzewo za pomoca podanego schamatu
Node* tmp = Drzewo;
for (int k = 0; k <= tresc.length(); k++){
if (tmp->CzyLisc){
zwrot += tmp->znak;
tmp = Drzewo;
}
if (k == tresc.length())
break;
if (tresc[k] == '0')
tmp = tmp->left;
else
tmp = tmp->right;
}
return zwrot;
}
//Funkcja pomocnicza
MM AHuffman::MinMin(Node**tab, int size){
MM MiMa, zwrot; // min = min1, max = min2
zwrot.min = 0;
zwrot.max = 0;
MiMa.max = -1;
MiMa.min = -1;
int tmp;
for (int k = 0; k < size; k++){
tmp = tab[k]->wartosc;
if (tmp < MiMa.max || MiMa.max == -1){
zwrot.max = k;
MiMa.max = tmp;
}
else if (tmp <= MiMa.min || MiMa.min == -1){
zwrot.min = k;
MiMa.min = tmp;
}
}
swap(zwrot.max, zwrot.min);
return zwrot;
}
}#include "AlgHuff.h"
namespace _AHuffman{
//Konstruktory i destruktory
AHuffman::~AHuffman()
{
if (znaki != NULL)
delete[] znaki;
}
//Tworzenie potrzebnych struktur
void AHuffman::StworzListe(){
string znalezione = "";
int* wystapienia = new int[MaksZnakow];
int size = 0;
//Zliczenie wystepujacych znakow
int tmp;
char znak;
for (int k = 0; k < tekst.length(); k++){
znak = tekst[k];
tmp = znalezione.find(znak);
if (tmp == -1){ //Jeśli nie znaleziono, dodajemy nowy znak do słownika/sringa
znalezione += znak;
wystapienia[size++] = 1; //Zwiększamy indeks wystapienia danego znaku(nowego)
}
else
wystapienia[tmp] ++; //Zwiekszamy indeks znalezionego znaku
}
//Tworzenie podstawowych jednostek drzew
znaki = new Node[size];
for (int k = 0; k < size; k++){
znaki[k] = Node(znalezione[k],wystapienia[k]);
}
//Porzadki
this->size = size;
tablica = znalezione;
delete[] wystapienia;
}
void AHuffman::StworzDrzewo(){
//Zapisywanie adresow wszystkich lisci
Node** drzewa = new Node*[size];
for (int k = 0; k < size; k++){
drzewa[k] = &znaki[k];
}
//Zmienne pomocnicze
int zmsize = size;
MM indeksy;
Node* tmp;
while (zmsize > 1){ //Dopoki mamy wiecej niz jeden element w tablicy
indeksy = MinMin(drzewa, zmsize); //Znalezienie najmniejszych elementow
if (indeksy.max != indeksy.min){ //dodatkowe zabezpieczenie - nie potrzebne
tmp = new Node(drzewa[indeksy.min]->wartosc + drzewa[indeksy.max]->wartosc); //Tworzenie nowego wezla
//Ustawianie zmiennych wezla
tmp->left = drzewa[indeksy.min];
tmp->right = drzewa[indeksy.max];
drzewa[indeksy.min] = tmp; //Podmiana starego elementu na wezel
swap(drzewa[indeksy.max], drzewa[--zmsize]); //Podmiana i usuniecie ostatniego elementu z tabliy (zmiejszenie rozmiaru)
\
}
}
Drzewo = drzewa[0]; //Zapamietanie adresu drzewa
delete[] drzewa; //Usuniecie pomocniczej tablicy
}
void AHuffman::StworzSlownik(){
Przechodz(Drzewo,""); //Aktualizacja elementow drzewa - zapamietuje sciezki do kazdego nodea - tworzy slownik
}
//Algorytm kodujacy
void AHuffman::Przechodz(Node* element, string kod){ //Przejscie przez drzewo typem (?)
if (element == NULL)
return;
if (element->left)
Przechodz(element->left,kod+"0");
element->Odwiedz(kod);
if (element->right)
Przechodz(element->right, kod + "1");
}
string AHuffman::Translate(){
string zwrot="";
for (int k = 0; k < tekst.length(); k++){
zwrot += znaki[tablica.find(tekst[k])].kod;
}
zakodowane = zwrot;
return zwrot;
}
//Funkcje Glowne
string AHuffman::Koduj(string tresc){
tekst = tresc;
StworzListe();
StworzDrzewo();
StworzSlownik();
//Pomocnicze wypisanie slownika
for (int k = 0; k < size; k++)
cout << znaki[k].znak << " " << znaki[k].kod << endl;
return Translate();
}
string AHuffman::Dekoduj(string tresc ){
if (tresc == "")
tresc = zakodowane;
string zwrot = "";
//Odczytywanie liter ze slownika - przechodzenie przez drzewo za pomoca podanego schamatu
Node* tmp = Drzewo;
for (int k = 0; k <= tresc.length(); k++){
if (tmp->CzyLisc){
zwrot += tmp->znak;
tmp = Drzewo;
}
if (k == tresc.length())
break;
if (tresc[k] == '0')
tmp = tmp->left;
else
tmp = tmp->right;
}
return zwrot;
}
//Funkcja pomocnicza
MM AHuffman::MinMin(Node**tab, int size){
MM MiMa, zwrot; // min = min1, max = min2
zwrot.min = 0;
zwrot.max = 0;
MiMa.max = -1;
MiMa.min = -1;
int tmp;
for (int k = 0; k < size; k++){
tmp = tab[k]->wartosc;
if (tmp < MiMa.max || MiMa.max == -1){
zwrot.max = k;
MiMa.max = tmp;
}
else if (tmp <= MiMa.min || MiMa.min == -1){
zwrot.min = k;
MiMa.min = tmp;
}
}
swap(zwrot.max, zwrot.min);
return zwrot;
}
}#include "AlgHuff.h"
namespace _AHuffman{
//Konstruktory i destruktory
AHuffman::~AHuffman()
{
if (znaki != NULL)
delete[] znaki;
}
//Tworzenie potrzebnych struktur
void AHuffman::StworzListe(){
string znalezione = "";
int* wystapienia = new int[MaksZnakow];
int size = 0;
//Zliczenie wystepujacych znakow
int tmp;
char znak;
for (int k = 0; k < tekst.length(); k++){
znak = tekst[k];
tmp = znalezione.find(znak);
if (tmp == -1){ //Jeśli nie znaleziono, dodajemy nowy znak do słownika/sringa
znalezione += znak;
wystapienia[size++] = 1; //Zwiększamy indeks wystapienia danego znaku(nowego)
}
else
wystapienia[tmp] ++; //Zwiekszamy indeks znalezionego znaku
}
//Tworzenie podstawowych jednostek drzew
znaki = new Node[size];
for (int k = 0; k < size; k++){
znaki[k] = Node(znalezione[k],wystapienia[k]);
}
//Porzadki
this->size = size;
tablica = znalezione;
delete[] wystapienia;
}
void AHuffman::StworzDrzewo(){
//Zapisywanie adresow wszystkich lisci
Node** drzewa = new Node*[size];
for (int k = 0; k < size; k++){
drzewa[k] = &znaki[k];
}
//Zmienne pomocnicze
int zmsize = size;
MM indeksy;
Node* tmp;
while (zmsize > 1){ //Dopoki mamy wiecej niz jeden element w tablicy
indeksy = MinMin(drzewa, zmsize); //Znalezienie najmniejszych elementow
if (indeksy.max != indeksy.min){ //dodatkowe zabezpieczenie - nie potrzebne
tmp = new Node(drzewa[indeksy.min]->wartosc + drzewa[indeksy.max]->wartosc); //Tworzenie nowego wezla
//Ustawianie zmiennych wezla
tmp->left = drzewa[indeksy.min];
tmp->right = drzewa[indeksy.max];
drzewa[indeksy.min] = tmp; //Podmiana starego elementu na wezel
swap(drzewa[indeksy.max], drzewa[--zmsize]); //Podmiana i usuniecie ostatniego elementu z tabliy (zmiejszenie rozmiaru)
\
}
}
Drzewo = drzewa[0]; //Zapamietanie adresu drzewa
delete[] drzewa; //Usuniecie pomocniczej tablicy
}
void AHuffman::StworzSlownik(){
Przechodz(Drzewo,""); //Aktualizacja elementow drzewa - zapamietuje sciezki do kazdego nodea - tworzy slownik
}
//Algorytm kodujacy
void AHuffman::Przechodz(Node* element, string kod){ //Przejscie przez drzewo typem (?)
if (element == NULL)
return;
if (element->left)
Przechodz(element->left,kod+"0");
element->Odwiedz(kod);
if (element->right)
Przechodz(element->right, kod + "1");
}
string AHuffman::Translate(){
string zwrot="";
for (int k = 0; k < tekst.length(); k++){
zwrot += znaki[tablica.find(tekst[k])].kod;
}
zakodowane = zwrot;
return zwrot;
}
//Funkcje Glowne
string AHuffman::Koduj(string tresc){
tekst = tresc;
StworzListe();
StworzDrzewo();
StworzSlownik();
//Pomocnicze wypisanie slownika
for (int k = 0; k < size; k++)
cout << znaki[k].znak << " " << znaki[k].kod << endl;
return Translate();
}
string AHuffman::Dekoduj(string tresc ){
if (tresc == "")
tresc = zakodowane;
string zwrot = "";
//Odczytywanie liter ze slownika - przechodzenie przez drzewo za pomoca podanego schamatu
Node* tmp = Drzewo;
for (int k = 0; k <= tresc.length(); k++){
if (tmp->CzyLisc){
zwrot += tmp->znak;
tmp = Drzewo;
}
if (k == tresc.length())
break;
if (tresc[k] == '0')
tmp = tmp->left;
else
tmp = tmp->right;
}
return zwrot;
}
//Funkcja pomocnicza
MM AHuffman::MinMin(Node**tab, int size){
MM MiMa, zwrot; // min = min1, max = min2
zwrot.min = 0;
zwrot.max = 0;
MiMa.max = -1;
MiMa.min = -1;
int tmp;
for (int k = 0; k < size; k++){
tmp = tab[k]->wartosc;
if (tmp < MiMa.max || MiMa.max == -1){
zwrot.max = k;
MiMa.max = tmp;
}
else if (tmp <= MiMa.min || MiMa.min == -1){
zwrot.min = k;
MiMa.min = tmp;
}
}
swap(zwrot.max, zwrot.min);
return zwrot;
}
}#include "AlgHuff.h"
namespace _AHuffman{
//Konstruktory i destruktory
AHuffman::~AHuffman()
{
if (znaki != NULL)
delete[] znaki;
}
//Tworzenie potrzebnych struktur
void AHuffman::StworzListe(){
string znalezione = "";
int* wystapienia = new int[MaksZnakow];
int size = 0;
//Zliczenie wystepujacych znakow
int tmp;
char znak;
for (int k = 0; k < tekst.length(); k++){
znak = tekst[k];
tmp = znalezione.find(znak);
if (tmp == -1){ //Jeśli nie znaleziono, dodajemy nowy znak do słownika/sringa
znalezione += znak;
wystapienia[size++] = 1; //Zwiększamy indeks wystapienia danego znaku(nowego)
}
else
wystapienia[tmp] ++; //Zwiekszamy indeks znalezionego znaku
}
//Tworzenie podstawowych jednostek drzew
znaki = new Node[size];
for (int k = 0; k < size; k++){
znaki[k] = Node(znalezione[k],wystapienia[k]);
}
//Porzadki
this->size = size;
tablica = znalezione;
delete[] wystapienia;
}
void AHuffman::StworzDrzewo(){
//Zapisywanie adresow wszystkich lisci
Node** drzewa = new Node*[size];
for (int k = 0; k < size; k++){
drzewa[k] = &znaki[k];
}
//Zmienne pomocnicze
int zmsize = size;
MM indeksy;
Node* tmp;
while (zmsize > 1){ //Dopoki mamy wiecej niz jeden element w tablicy
indeksy = MinMin(drzewa, zmsize); //Znalezienie najmniejszych elementow
if (indeksy.max != indeksy.min){ //dodatkowe zabezpieczenie - nie potrzebne
tmp = new Node(drzewa[indeksy.min]->wartosc + drzewa[indeksy.max]->wartosc); //Tworzenie nowego wezla
//Ustawianie zmiennych wezla
tmp->left = drzewa[indeksy.min];
tmp->right = drzewa[indeksy.max];
drzewa[indeksy.min] = tmp; //Podmiana starego elementu na wezel
swap(drzewa[indeksy.max], drzewa[--zmsize]); //Podmiana i usuniecie ostatniego elementu z tabliy (zmiejszenie rozmiaru)
\
}
}
Drzewo = drzewa[0]; //Zapamietanie adresu drzewa
delete[] drzewa; //Usuniecie pomocniczej tablicy
}
void AHuffman::StworzSlownik(){
Przechodz(Drzewo,""); //Aktualizacja elementow drzewa - zapamietuje sciezki do kazdego nodea - tworzy slownik
}
//Algorytm kodujacy
void AHuffman::Przechodz(Node* element, string kod){ //Przejscie przez drzewo typem (?)
if (element == NULL)
return;
if (element->left)
Przechodz(element->left,kod+"0");
element->Odwiedz(kod);
if (element->right)
Przechodz(element->right, kod + "1");
}
string AHuffman::Translate(){
string zwrot="";
for (int k = 0; k < tekst.length(); k++){
zwrot += znaki[tablica.find(tekst[k])].kod;
}
zakodowane = zwrot;
return zwrot;
}
//Funkcje Glowne
string AHuffman::Koduj(string tresc){
tekst = tresc;
StworzListe();
StworzDrzewo();
StworzSlownik();
//Pomocnicze wypisanie slownika
for (int k = 0; k < size; k++)
cout << znaki[k].znak << " " << znaki[k].kod << endl;
return Translate();
}
string AHuffman::Dekoduj(string tresc ){
if (tresc == "")
tresc = zakodowane;
string zwrot = "";
//Odczytywanie liter ze slownika - przechodzenie przez drzewo za pomoca podanego schamatu
Node* tmp = Drzewo;
for (int k = 0; k <= tresc.length(); k++){
if (tmp->CzyLisc){
zwrot += tmp->znak;
tmp = Drzewo;
}
if (k == tresc.length())
break;
if (tresc[k] == '0')
tmp = tmp->left;
else
tmp = tmp->right;
}
return zwrot;
}
//Funkcja pomocnicza
MM AHuffman::MinMin(Node**tab, int size){
MM MiMa, zwrot; // min = min1, max = min2
zwrot.min = 0;
zwrot.max = 0;
MiMa.max = -1;
MiMa.min = -1;
int tmp;
for (int k = 0; k < size; k++){
tmp = tab[k]->wartosc;
if (tmp < MiMa.max || MiMa.max == -1){
zwrot.max = k;
MiMa.max = tmp;
}
else if (tmp <= MiMa.min || MiMa.min == -1){
zwrot.min = k;
MiMa.min = tmp;
}
}
swap(zwrot.max, zwrot.min);
return zwrot;
}
}#include "AlgHuff.h"
namespace _AHuffman{
//Konstruktory i destruktory
AHuffman::~AHuffman()
{
if (znaki != NULL)
delete[] znaki;
}
//Tworzenie potrzebnych struktur
void AHuffman::StworzListe(){
string znalezione = "";
int* wystapienia = new int[MaksZnakow];
int size = 0;
//Zliczenie wystepujacych znakow
int tmp;
char znak;
for (int k = 0; k < tekst.length(); k++){
znak = tekst[k];
tmp = znalezione.find(znak);
if (tmp == -1){ //Jeśli nie znaleziono, dodajemy nowy znak do słownika/sringa
znalezione += znak;
wystapienia[size++] = 1; //Zwiększamy indeks wystapienia danego znaku(nowego)
}
else
wystapienia[tmp] ++; //Zwiekszamy indeks znalezionego znaku
}
//Tworzenie podstawowych jednostek drzew
znaki = new Node[size];
for (int k = 0; k < size; k++){
znaki[k] = Node(znalezione[k],wystapienia[k]);
}
//Porzadki
this->size = size;
tablica = znalezione;
delete[] wystapienia;
}
void AHuffman::StworzDrzewo(){
//Zapisywanie adresow wszystkich lisci
Node** drzewa = new Node*[size];
for (int k = 0; k < size; k++){
drzewa[k] = &znaki[k];
}
//Zmienne pomocnicze
int zmsize = size;
MM indeksy;
Node* tmp;
while (zmsize > 1){ //Dopoki mamy wiecej niz jeden element w tablicy
indeksy = MinMin(drzewa, zmsize); //Znalezienie najmniejszych elementow
if (indeksy.max != indeksy.min){ //dodatkowe zabezpieczenie - nie potrzebne
tmp = new Node(drzewa[indeksy.min]->wartosc + drzewa[indeksy.max]->wartosc); //Tworzenie nowego wezla
//Ustawianie zmiennych wezla
tmp->left = drzewa[indeksy.min];
tmp->right = drzewa[indeksy.max];
drzewa[indeksy.min] = tmp; //Podmiana starego elementu na wezel
swap(drzewa[indeksy.max], drzewa[--zmsize]); //Podmiana i usuniecie ostatniego elementu z tabliy (zmiejszenie rozmiaru)
\
}
}
Drzewo = drzewa[0]; //Zapamietanie adresu drzewa
delete[] drzewa; //Usuniecie pomocniczej tablicy
}
void AHuffman::StworzSlownik(){
Przechodz(Drzewo,""); //Aktualizacja elementow drzewa - zapamietuje sciezki do kazdego nodea - tworzy slownik
}
//Algorytm kodujacy
void AHuffman::Przechodz(Node* element, string kod){ //Przejscie przez drzewo typem (?)
if (element == NULL)
return;
if (element->left)
Przechodz(element->left,kod+"0");
element->Odwiedz(kod);
if (element->right)
Przechodz(element->right, kod + "1");
}
string AHuffman::Translate(){
string zwrot="";
for (int k = 0; k < tekst.length(); k++){
zwrot += znaki[tablica.find(tekst[k])].kod;
}
zakodowane = zwrot;
return zwrot;
}
//Funkcje Glowne
string AHuffman::Koduj(string tresc){
tekst = tresc;
StworzListe();
StworzDrzewo();
StworzSlownik();
//Pomocnicze wypisanie slownika
for (int k = 0; k < size; k++)
cout << znaki[k].znak << " " << znaki[k].kod << endl;
return Translate();
}
string AHuffman::Dekoduj(string tresc ){
if (tresc == "")
tresc = zakodowane;
string zwrot = "";
//Odczytywanie liter ze slownika - przechodzenie przez drzewo za pomoca podanego schamatu
Node* tmp = Drzewo;
for (int k = 0; k <= tresc.length(); k++){
if (tmp->CzyLisc){
zwrot += tmp->znak;
tmp = Drzewo;
}
if (k == tresc.length())
break;
if (tresc[k] == '0')
tmp = tmp->left;
else
tmp = tmp->right;
}
return zwrot;
}
//Funkcja pomocnicza
MM AHuffman::MinMin(Node**tab, int size){
MM MiMa, zwrot; // min = min1, max = min2
zwrot.min = 0;
zwrot.max = 0;
MiMa.max = -1;
MiMa.min = -1;
int tmp;
for (int k = 0; k < size; k++){
tmp = tab[k]->wartosc;
if (tmp < MiMa.max || MiMa.max == -1){
zwrot.max = k;
MiMa.max = tmp;
}
else if (tmp <= MiMa.min || MiMa.min == -1){
zwrot.min = k;
MiMa.min = tmp;
}
}
swap(zwrot.max, zwrot.min);
return zwrot;
}
}#include "AlgHuff.h"
namespace _AHuffman{
//Konstruktory i destruktory
AHuffman::~AHuffman()
{
if (znaki != NULL)
delete[] znaki;
}
//Tworzenie potrzebnych struktur
void AHuffman::StworzListe(){
string znalezione = "";
int* wystapienia = new int[MaksZnakow];
int size = 0;
//Zliczenie wystepujacych znakow
int tmp;
char znak;
for (int k = 0; k < tekst.length(); k++){
znak = tekst[k];
tmp = znalezione.find(znak);
if (tmp == -1){ //Jeśli nie znaleziono, dodajemy nowy znak do słownika/sringa
znalezione += znak;
wystapienia[size++] = 1; //Zwiększamy indeks wystapienia danego znaku(nowego)
}
else
wystapienia[tmp] ++; //Zwiekszamy indeks znalezionego znaku
}
//Tworzenie podstawowych jednostek drzew
znaki = new Node[size];
for (int k = 0; k < size; k++){
znaki[k] = Node(znalezione[k],wystapienia[k]);
}
//Porzadki
this->size = size;
tablica = znalezione;
delete[] wystapienia;
}
void AHuffman::StworzDrzewo(){
//Zapisywanie adresow wszystkich lisci
Node** drzewa = new Node*[size];
for (int k = 0; k < size; k++){
drzewa[k] = &znaki[k];
}
//Zmienne pomocnicze
int zmsize = size;
MM indeksy;
Node* tmp;
while (zmsize > 1){ //Dopoki mamy wiecej niz jeden element w tablicy
indeksy = MinMin(drzewa, zmsize); //Znalezienie najmniejszych elementow
if (indeksy.max != indeksy.min){ //dodatkowe zabezpieczenie - nie potrzebne
tmp = new Node(drzewa[indeksy.min]->wartosc + drzewa[indeksy.max]->wartosc); //Tworzenie nowego wezla
//Ustawianie zmiennych wezla
tmp->left = drzewa[indeksy.min];
tmp->right = drzewa[indeksy.max];
drzewa[indeksy.min] = tmp; //Podmiana starego elementu na wezel
swap(drzewa[indeksy.max], drzewa[--zmsize]); //Podmiana i usuniecie ostatniego elementu z tabliy (zmiejszenie rozmiaru)
\
}
}
Drzewo = drzewa[0]; //Zapamietanie adresu drzewa
delete[] drzewa; //Usuniecie pomocniczej tablicy
}
void AHuffman::StworzSlownik(){
Przechodz(Drzewo,""); //Aktualizacja elementow drzewa - zapamietuje sciezki do kazdego nodea - tworzy slownik
}
//Algorytm kodujacy
void AHuffman::Przechodz(Node* element, string kod){ //Przejscie przez drzewo typem (?)
if (element == NULL)
return;
if (element->left)
Przechodz(element->left,kod+"0");
element->Odwiedz(kod);
if (element->right)
Przechodz(element->right, kod + "1");
}
string AHuffman::Translate(){
string zwrot="";
for (int k = 0; k < tekst.length(); k++){
zwrot += znaki[tablica.find(tekst[k])].kod;
}
zakodowane = zwrot;
return zwrot;
}
//Funkcje Glowne
string AHuffman::Koduj(string tresc){
tekst = tresc;
StworzListe();
StworzDrzewo();
StworzSlownik();
//Pomocnicze wypisanie slownika
for (int k = 0; k < size; k++)
cout << znaki[k].znak << " " << znaki[k].kod << endl;
return Translate();
}
string AHuffman::Dekoduj(string tresc ){
if (tresc == "")
tresc = zakodowane;
string zwrot = "";
//Odczytywanie liter ze slownika - przechodzenie przez drzewo za pomoca podanego schamatu
Node* tmp = Drzewo;
for (int k = 0; k <= tresc.length(); k++){
if (tmp->CzyLisc){
zwrot += tmp->znak;
tmp = Drzewo;
}
if (k == tresc.length())
break;
if (tresc[k] == '0')
tmp = tmp->left;
else
tmp = tmp->right;
}
return zwrot;
}
//Funkcja pomocnicza
MM AHuffman::MinMin(Node**tab, int size){
MM MiMa, zwrot; // min = min1, max = min2
zwrot.min = 0;
zwrot.max = 0;
MiMa.max = -1;
MiMa.min = -1;
int tmp;
for (int k = 0; k < size; k++){
tmp = tab[k]->wartosc;
if (tmp < MiMa.max || MiMa.max == -1){
zwrot.max = k;
MiMa.max = tmp;
}
else if (tmp <= MiMa.min || MiMa.min == -1){
zwrot.min = k;
MiMa.min = tmp;
}
}
swap(zwrot.max, zwrot.min);
return zwrot;
}
}#include "AlgHuff.h"
namespace _AHuffman{
//Konstruktory i destruktory
AHuffman::~AHuffman()
{
if (znaki != NULL)
delete[] znaki;
}
//Tworzenie potrzebnych struktur
void AHuffman::StworzListe(){
string znalezione = "";
int* wystapienia = new int[MaksZnakow];
int size = 0;
//Zliczenie wystepujacych znakow
int tmp;
char znak;
for (int k = 0; k < tekst.length(); k++){
znak = tekst[k];
tmp = znalezione.find(znak);
if (tmp == -1){ //Jeśli nie znaleziono, dodajemy nowy znak do słownika/sringa
znalezione += znak;
wystapienia[size++] = 1; //Zwiększamy indeks wystapienia danego znaku(nowego)
}
else
wystapienia[tmp] ++; //Zwiekszamy indeks znalezionego znaku
}
//Tworzenie podstawowych jednostek drzew
znaki = new Node[size];
for (int k = 0; k < size; k++){
znaki[k] = Node(znalezione[k],wystapienia[k]);
}
//Porzadki
this->size = size;
tablica = znalezione;
delete[] wystapienia;
}
void AHuffman::StworzDrzewo(){
//Zapisywanie adresow wszystkich lisci
Node** drzewa = new Node*[size];
for (int k = 0; k < size; k++){
drzewa[k] = &znaki[k];
}
//Zmienne pomocnicze
int zmsize = size;
MM indeksy;
Node* tmp;
while (zmsize > 1){ //Dopoki mamy wiecej niz jeden element w tablicy
indeksy = MinMin(drzewa, zmsize); //Znalezienie najmniejszych elementow
if (indeksy.max != indeksy.min){ //dodatkowe zabezpieczenie - nie potrzebne
tmp = new Node(drzewa[indeksy.min]->wartosc + drzewa[indeksy.max]->wartosc); //Tworzenie nowego wezla
//Ustawianie zmiennych wezla
tmp->left = drzewa[indeksy.min];
tmp->right = drzewa[indeksy.max];
drzewa[indeksy.min] = tmp; //Podmiana starego elementu na wezel
swap(drzewa[indeksy.max], drzewa[--zmsize]); //Podmiana i usuniecie ostatniego elementu z tabliy (zmiejszenie rozmiaru)
\
}
}
Drzewo = drzewa[0]; //Zapamietanie adresu drzewa
delete[] drzewa; //Usuniecie pomocniczej tablicy
}
void AHuffman::StworzSlownik(){
Przechodz(Drzewo,""); //Aktualizacja elementow drzewa - zapamietuje sciezki do kazdego nodea - tworzy slownik
}
//Algorytm kodujacy
void AHuffman::Przechodz(Node* element, string kod){ //Przejscie przez drzewo typem (?)
if (element == NULL)
return;
if (element->left)
Przechodz(element->left,kod+"0");
element->Odwiedz(kod);
if (element->right)
Przechodz(element->right, kod + "1");
}
string AHuffman::Translate(){
string zwrot="";
for (int k = 0; k < tekst.length(); k++){
zwrot += znaki[tablica.find(tekst[k])].kod;
}
zakodowane = zwrot;
return zwrot;
}
//Funkcje Glowne
string AHuffman::Koduj(string tresc){
tekst = tresc;
StworzListe();
StworzDrzewo();
StworzSlownik();
//Pomocnicze wypisanie slownika
for (int k = 0; k < size; k++)
cout << znaki[k].znak << " " << znaki[k].kod << endl;
return Translate();
}
string AHuffman::Dekoduj(string tresc ){
if (tresc == "")
tresc = zakodowane;
string zwrot = "";
//Odczytywanie liter ze slownika - przechodzenie przez drzewo za pomoca podanego schamatu
Node* tmp = Drzewo;
for (int k = 0; k <= tresc.length(); k++){
if (tmp->CzyLisc){
zwrot += tmp->znak;
tmp = Drzewo;
}
if (k == tresc.length())
break;
if (tresc[k] == '0')
tmp = tmp->left;
else
tmp = tmp->right;
}
return zwrot;
}
//Funkcja pomocnicza
MM AHuffman::MinMin(Node**tab, int size){
MM MiMa, zwrot; // min = min1, max = min2
zwrot.min = 0;
zwrot.max = 0;
MiMa.max = -1;
MiMa.min = -1;
int tmp;
for (int k = 0; k < size; k++){
tmp = tab[k]->wartosc;
if (tmp < MiMa.max || MiMa.max == -1){
zwrot.max = k;
MiMa.max = tmp;
}
else if (tmp <= MiMa.min || MiMa.min == -1){
zwrot.min = k;
MiMa.min = tmp;
}
}
swap(zwrot.max, zwrot.min);
return zwrot;
}
}#include "AlgHuff.h"
namespace _AHuffman{
//Konstruktory i destruktory
AHuffman::~AHuffman()
{
if (znaki != NULL)
delete[] znaki;
}
//Tworzenie potrzebnych struktur
void AHuffman::StworzListe(){
string znalezione = "";
int* wystapienia = new int[MaksZnakow];
int size = 0;
//Zliczenie wystepujacych znakow
int tmp;
char znak;
for (int k = 0; k < tekst.length(); k++){
znak = tekst[k];
tmp = znalezione.find(znak);
if (tmp == -1){ //Jeśli nie znaleziono, dodajemy nowy znak do słownika/sringa
znalezione += znak;
wystapienia[size++] = 1; //Zwiększamy indeks wystapienia danego znaku(nowego)
}
else
wystapienia[tmp] ++; //Zwiekszamy indeks znalezionego znaku
}
//Tworzenie podstawowych jednostek drzew
znaki = new Node[size];
for (int k = 0; k < size; k++){
znaki[k] = Node(znalezione[k],wystapienia[k]);
}
//Porzadki
this->size = size;
tablica = znalezione;
delete[] wystapienia;
}
void AHuffman::StworzDrzewo(){
//Zapisywanie adresow wszystkich lisci
Node** drzewa = new Node*[size];
for (int k = 0; k < size; k++){
drzewa[k] = &znaki[k];
}
//Zmienne pomocnicze
int zmsize = size;
MM indeksy;
Node* tmp;
while (zmsize > 1){ //Dopoki mamy wiecej niz jeden element w tablicy
indeksy = MinMin(drzewa, zmsize); //Znalezienie najmniejszych elementow
if (indeksy.max != indeksy.min){ //dodatkowe zabezpieczenie - nie potrzebne
tmp = new Node(drzewa[indeksy.min]->wartosc + drzewa[indeksy.max]->wartosc); //Tworzenie nowego wezla
//Ustawianie zmiennych wezla
tmp->left = drzewa[indeksy.min];
tmp->right = drzewa[indeksy.max];
drzewa[indeksy.min] = tmp; //Podmiana starego elementu na wezel
swap(drzewa[indeksy.max], drzewa[--zmsize]); //Podmiana i usuniecie ostatniego elementu z tabliy (zmiejszenie rozmiaru)
\
}
}
Drzewo = drzewa[0]; //Zapamietanie adresu drzewa
delete[] drzewa; //Usuniecie pomocniczej tablicy
}
void AHuffman::StworzSlownik(){
Przechodz(Drzewo,""); //Aktualizacja elementow drzewa - zapamietuje sciezki do kazdego nodea - tworzy slownik
}
//Algorytm kodujacy
void AHuffman::Przechodz(Node* element, string kod){ //Przejscie przez drzewo typem (?)
if (element == NULL)
return;
if (element->left)
Przechodz(element->left,kod+"0");
element->Odwiedz(kod);
if (element->right)
Przechodz(element->right, kod + "1");
}
string AHuffman::Translate(){
string zwrot="";
for (int k = 0; k < tekst.length(); k++){
zwrot += znaki[tablica.find(tekst[k])].kod;
}
zakodowane = zwrot;
return zwrot;
}
//Funkcje Glowne
string AHuffman::Koduj(string tresc){
tekst = tresc;
StworzListe();
StworzDrzewo();
StworzSlownik();
//Pomocnicze wypisanie slownika
for (int k = 0; k < size; k++)
cout << znaki[k].znak << " " << znaki[k].kod << endl;
return Translate();
}
string AHuffman::Dekoduj(string tresc ){
if (tresc == "")
tresc = zakodowane;
string zwrot = "";
//Odczytywanie liter ze slownika - przechodzenie przez drzewo za pomoca podanego schamatu
Node* tmp = Drzewo;
for (int k = 0; k <= tresc.length(); k++){
if (tmp->CzyLisc){
zwrot += tmp->znak;
tmp = Drzewo;
}
if (k == tresc.length())
break;
if (tresc[k] == '0')
tmp = tmp->left;
else
tmp = tmp->right;
}
return zwrot;
}
//Funkcja pomocnicza
MM AHuffman::MinMin(Node**tab, int size){
MM MiMa, zwrot; // min = min1, max = min2
zwrot.min = 0;
zwrot.max = 0;
MiMa.max = -1;
MiMa.min = -1;
int tmp;
for (int k = 0; k < size; k++){
tmp = tab[k]->wartosc;
if (tmp < MiMa.max || MiMa.max == -1){
zwrot.max = k;
MiMa.max = tmp;
}
else if (tmp <= MiMa.min || MiMa.min == -1){
zwrot.min = k;
MiMa.min = tmp;
}
}
swap(zwrot.max, zwrot.min);
return zwrot;
}
}#include "AlgHuff.h"
namespace _AHuffman{
//Konstruktory i destruktory
AHuffman::~AHuffman()
{
if (znaki != NULL)
delete[] znaki;
}
//Tworzenie potrzebnych struktur
void AHuffman::StworzListe(){
string znalezione = "";
int* wystapienia = new int[MaksZnakow];
int size = 0;
//Zliczenie wystepujacych znakow
int tmp;
char znak;
for (int k = 0; k < tekst.length(); k++){
znak = tekst[k];
tmp = znalezione.find(znak);
if (tmp == -1){ //Jeśli nie znaleziono, dodajemy nowy znak do słownika/sringa
znalezione += znak;
wystapienia[size++] = 1; //Zwiększamy indeks wystapienia danego znaku(nowego)
}
else
wystapienia[tmp] ++; //Zwiekszamy indeks znalezionego znaku
}
//Tworzenie podstawowych jednostek drzew
znaki = new Node[size];
for (int k = 0; k < size; k++){
znaki[k] = Node(znalezione[k],wystapienia[k]);
}
//Porzadki
this->size = size;
tablica = znalezione;
delete[] wystapienia;
}
void AHuffman::StworzDrzewo(){
//Zapisywanie adresow wszystkich lisci
Node** drzewa = new Node*[size];
for (int k = 0; k < size; k++){
drzewa[k] = &znaki[k];
}
//Zmienne pomocnicze
int zmsize = size;
MM indeksy;
Node* tmp;
while (zmsize > 1){ //Dopoki mamy wiecej niz jeden element w tablicy
indeksy = MinMin(drzewa, zmsize); //Znalezienie najmniejszych elementow
if (indeksy.max != indeksy.min){ //dodatkowe zabezpieczenie - nie potrzebne
tmp = new Node(drzewa[indeksy.min]->wartosc + drzewa[indeksy.max]->wartosc); //Tworzenie nowego wezla
//Ustawianie zmiennych wezla
tmp->left = drzewa[indeksy.min];
tmp->right = drzewa[indeksy.max];
drzewa[indeksy.min] = tmp; //Podmiana starego elementu na wezel
swap(drzewa[indeksy.max], drzewa[--zmsize]); //Podmiana i usuniecie ostatniego elementu z tabliy (zmiejszenie rozmiaru)
\
}
}
Drzewo = drzewa[0]; //Zapamietanie adresu drzewa
delete[] drzewa; //Usuniecie pomocniczej tablicy
}
void AHuffman::StworzSlownik(){
Przechodz(Drzewo,""); //Aktualizacja elementow drzewa - zapamietuje sciezki do kazdego nodea - tworzy slownik
}
//Algorytm kodujacy
void AHuffman::Przechodz(Node* element, string kod){ //Przejscie przez drzewo typem (?)
if (element == NULL)
return;
if (element->left)
Przechodz(element->left,kod+"0");
element->Odwiedz(kod);
if (element->right)
Przechodz(element->right, kod + "1");
}
string AHuffman::Translate(){
string zwrot="";
for (int k = 0; k < tekst.length(); k++){
zwrot += znaki[tablica.find(tekst[k])].kod;
}
zakodowane = zwrot;
return zwrot;
}
//Funkcje Glowne
string AHuffman::Koduj(string tresc){
tekst = tresc;
StworzListe();
StworzDrzewo();
StworzSlownik();
//Pomocnicze wypisanie slownika
for (int k = 0; k < size; k++)
cout << znaki[k].znak << " " << znaki[k].kod << endl;
return Translate();
}
string AHuffman::Dekoduj(string tresc ){
if (tresc == "")
tresc = zakodowane;
string zwrot = "";
//Odczytywanie liter ze slownika - przechodzenie przez drzewo za pomoca podanego schamatu
Node* tmp = Drzewo;
for (int k = 0; k <= tresc.length(); k++){
if (tmp->CzyLisc){
zwrot += tmp->znak;
tmp = Drzewo;
}
if (k == tresc.length())
break;
if (tresc[k] == '0')
tmp = tmp->left;
else
tmp = tmp->right;
}
return zwrot;
}
//Funkcja pomocnicza
MM AHuffman::MinMin(Node**tab, int size){
MM MiMa, zwrot; // min = min1, max = min2
zwrot.min = 0;
zwrot.max = 0;
MiMa.max = -1;
MiMa.min = -1;
int tmp;
for (int k = 0; k < size; k++){
tmp = tab[k]->wartosc;
if (tmp < MiMa.max || MiMa.max == -1){
zwrot.max = k;
MiMa.max = tmp;
}
else if (tmp <= MiMa.min || MiMa.min == -1){
zwrot.min = k;
MiMa.min = tmp;
}
}
swap(zwrot.max, zwrot.min);
return zwrot;
}
}#include "AlgHuff.h"
namespace _AHuffman{
//Konstruktory i destruktory
AHuffman::~AHuffman()
{
if (znaki != NULL)
delete[] znaki;
}
//Tworzenie potrzebnych struktur
void AHuffman::StworzListe(){
string znalezione = "";
int* wystapienia = new int[MaksZnakow];
int size = 0;
//Zliczenie wystepujacych znakow
int tmp;
char znak;
for (int k = 0; k < tekst.length(); k++){
znak = tekst[k];
tmp = znalezione.find(znak);
if (tmp == -1){ //Jeśli nie znaleziono, dodajemy nowy znak do słownika/sringa
znalezione += znak;
wystapienia[size++] = 1; //Zwiększamy indeks wystapienia danego znaku(nowego)
}
else
wystapienia[tmp] ++; //Zwiekszamy indeks znalezionego znaku
}
//Tworzenie podstawowych jednostek drzew
znaki = new Node[size];
for (int k = 0; k < size; k++){
znaki[k] = Node(znalezione[k],wystapienia[k]);
}
//Porzadki
this->size = size;
tablica = znalezione;
delete[] wystapienia;
}
void AHuffman::StworzDrzewo(){
//Zapisywanie adresow wszystkich lisci
Node** drzewa = new Node*[size];
for (int k = 0; k < size; k++){
drzewa[k] = &znaki[k];
}
//Zmienne pomocnicze
int zmsize = size;
MM indeksy;
Node* tmp;
while (zmsize > 1){ //Dopoki mamy wiecej niz jeden element w tablicy
indeksy = MinMin(drzewa, zmsize); //Znalezienie najmniejszych elementow
if (indeksy.max != indeksy.min){ //dodatkowe zabezpieczenie - nie potrzebne
tmp = new Node(drzewa[indeksy.min]->wartosc + drzewa[indeksy.max]->wartosc); //Tworzenie nowego wezla
//Ustawianie zmiennych wezla
tmp->left = drzewa[indeksy.min];
tmp->right = drzewa[indeksy.max];
drzewa[indeksy.min] = tmp; //Podmiana starego elementu na wezel
swap(drzewa[indeksy.max], drzewa[--zmsize]); //Podmiana i usuniecie ostatniego elementu z tabliy (zmiejszenie rozmiaru)
\
}
}
Drzewo = drzewa[0]; //Zapamietanie adresu drzewa
delete[] drzewa; //Usuniecie pomocniczej tablicy
}
void AHuffman::StworzSlownik(){
Przechodz(Drzewo,""); //Aktualizacja elementow drzewa - zapamietuje sciezki do kazdego nodea - tworzy slownik
}
//Algorytm kodujacy
void AHuffman::Przechodz(Node* element, string kod){ //Przejscie przez drzewo typem (?)
if (element == NULL)
return;
if (element->left)
Przechodz(element->left,kod+"0");
element->Odwiedz(kod);
if (element->right)
Przechodz(element->right, kod + "1");
}
string AHuffman::Translate(){
string zwrot="";
for (int k = 0; k < tekst.length(); k++){
zwrot += znaki[tablica.find(tekst[k])].kod;
}
zakodowane = zwrot;
return zwrot;
}
//Funkcje Glowne
string AHuffman::Koduj(string tresc){
tekst = tresc;
StworzListe();
StworzDrzewo();
StworzSlownik();
//Pomocnicze wypisanie slownika
for (int k = 0; k < size; k++)
cout << znaki[k].znak << " " << znaki[k].kod << endl;
return Translate();
}
string AHuffman::Dekoduj(string tresc ){
if (tresc == "")
tresc = zakodowane;
string zwrot = "";
//Odczytywanie liter ze slownika - przechodzenie przez drzewo za pomoca podanego schamatu
Node* tmp = Drzewo;
for (int k = 0; k <= tresc.length(); k++){
if (tmp->CzyLisc){
zwrot += tmp->znak;
tmp = Drzewo;
}
if (k == tresc.length())
break;
if (tresc[k] == '0')
tmp = tmp->left;
else
tmp = tmp->right;
}
return zwrot;
}
//Funkcja pomocnicza
MM AHuffman::MinMin(Node**tab, int size){
MM MiMa, zwrot; // min = min1, max = min2
zwrot.min = 0;
zwrot.max = 0;
MiMa.max = -1;
MiMa.min = -1;
int tmp;
for (int k = 0; k < size; k++){
tmp = tab[k]->wartosc;
if (tmp < MiMa.max || MiMa.max == -1){
zwrot.max = k;
MiMa.max = tmp;
}
else if (tmp <= MiMa.min || MiMa.min == -1){
zwrot.min = k;
MiMa.min = tmp;
}
}
swap(zwrot.max, zwrot.min);
return zwrot;
}
}#include "AlgHuff.h"
namespace _AHuffman{
//Konstruktory i destruktory
AHuffman::~AHuffman()
{
if (znaki != NULL)
delete[] znaki;
}
//Tworzenie potrzebnych struktur
void AHuffman::StworzListe(){
string znalezione = "";
int* wystapienia = new int[MaksZnakow];
int size = 0;
//Zliczenie wystepujacych znakow
int tmp;
char znak;
for (int k = 0; k < tekst.length(); k++){
znak = tekst[k];
tmp = znalezione.find(znak);
if (tmp == -1){ //Jeśli nie znaleziono, dodajemy nowy znak do słownika/sringa
znalezione += znak;
wystapienia[size++] = 1; //Zwiększamy indeks wystapienia danego znaku(nowego)
}
else
wystapienia[tmp] ++; //Zwiekszamy indeks znalezionego znaku
}
//Tworzenie podstawowych jednostek drzew
znaki = new Node[size];
for (int k = 0; k < size; k++){
znaki[k] = Node(znalezione[k],wystapienia[k]);
}
//Porzadki
this->size = size;
tablica = znalezione;
delete[] wystapienia;
}
void AHuffman::StworzDrzewo(){
//Zapisywanie adresow wszystkich lisci
Node** drzewa = new Node*[size];
for (int k = 0; k < size; k++){
drzewa[k] = &znaki[k];
}
//Zmienne pomocnicze
int zmsize = size;
MM indeksy;
Node* tmp;
while (zmsize > 1){ //Dopoki mamy wiecej niz jeden element w tablicy
indeksy = MinMin(drzewa, zmsize); //Znalezienie najmniejszych elementow
if (indeksy.max != indeksy.min){ //dodatkowe zabezpieczenie - nie potrzebne
tmp = new Node(drzewa[indeksy.min]->wartosc + drzewa[indeksy.max]->wartosc); //Tworzenie nowego wezla
//Ustawianie zmiennych wezla
tmp->left = drzewa[indeksy.min];
tmp->right = drzewa[indeksy.max];
drzewa[indeksy.min] = tmp; //Podmiana starego elementu na wezel
swap(drzewa[indeksy.max], drzewa[--zmsize]); //Podmiana i usuniecie ostatniego elementu z tabliy (zmiejszenie rozmiaru)
\
}
}
Drzewo = drzewa[0]; //Zapamietanie adresu drzewa
delete[] drzewa; //Usuniecie pomocniczej tablicy
}
void AHuffman::StworzSlownik(){
Przechodz(Drzewo,""); //Aktualizacja elementow drzewa - zapamietuje sciezki do kazdego nodea - tworzy slownik
}
//Algorytm kodujacy
void AHuffman::Przechodz(Node* element, string kod){ //Przejscie przez drzewo typem (?)
if (element == NULL)
return;
if (element->left)
Przechodz(element->left,kod+"0");
element->Odwiedz(kod);
if (element->right)
Przechodz(element->right, kod + "1");
}
string AHuffman::Translate(){
string zwrot="";
for (int k = 0; k < tekst.length(); k++){
zwrot += znaki[tablica.find(tekst[k])].kod;
}
zakodowane = zwrot;
return zwrot;
}
//Funkcje Glowne
string AHuffman::Koduj(string tresc){
tekst = tresc;
StworzListe();
StworzDrzewo();
StworzSlownik();
//Pomocnicze wypisanie slownika
for (int k = 0; k < size; k++)
cout << znaki[k].znak << " " << znaki[k].kod << endl;
return Translate();
}
string AHuffman::Dekoduj(string tresc ){
if (tresc == "")
tresc = zakodowane;
string zwrot = "";
//Odczytywanie liter ze slownika - przechodzenie przez drzewo za pomoca podanego schamatu
Node* tmp = Drzewo;
for (int k = 0; k <= tresc.length(); k++){
if (tmp->CzyLisc){
zwrot += tmp->znak;
tmp = Drzewo;
}
if (k == tresc.length())
break;
if (tresc[k] == '0')
tmp = tmp->left;
else
tmp = tmp->right;
}
return zwrot;
}
//Funkcja pomocnicza
MM AHuffman::MinMin(Node**tab, int size){
MM MiMa, zwrot; // min = min1, max = min2
zwrot.min = 0;
zwrot.max = 0;
MiMa.max = -1;
MiMa.min = -1;
int tmp;
for (int k = 0; k < size; k++){
tmp = tab[k]->wartosc;
if (tmp < MiMa.max || MiMa.max == -1){
zwrot.max = k;
MiMa.max = tmp;
}
else if (tmp <= MiMa.min || MiMa.min == -1){
zwrot.min = k;
MiMa.min = tmp;
}
}
swap(zwrot.max, zwrot.min);
return zwrot;
}
}#include "AlgHuff.h"
namespace _AHuffman{
//Konstruktory i destruktory
AHuffman::~AHuffman()
{
if (znaki != NULL)
delete[] znaki;
}
//Tworzenie potrzebnych struktur
void AHuffman::StworzListe(){
string znalezione = "";
int* wystapienia = new int[MaksZnakow];
int size = 0;
//Zliczenie wystepujacych znakow
int tmp;
char znak;
for (int k = 0; k < tekst.length(); k++){
znak = tekst[k];
tmp = znalezione.find(znak);
if (tmp == -1){ //Jeśli nie znaleziono, dodajemy nowy znak do słownika/sringa
znalezione += znak;
wystapienia[size++] = 1; //Zwiększamy indeks wystapienia danego znaku(nowego)
}
else
wystapienia[tmp] ++; //Zwiekszamy indeks znalezionego znaku
}
//Tworzenie podstawowych jednostek drzew
znaki = new Node[size];
for (int k = 0; k < size; k++){
znaki[k] = Node(znalezione[k],wystapienia[k]);
}
//Porzadki
this->size = size;
tablica = znalezione;
delete[] wystapienia;
}
void AHuffman::StworzDrzewo(){
//Zapisywanie adresow wszystkich lisci
Node** drzewa = new Node*[size];
for (int k = 0; k < size; k++){
drzewa[k] = &znaki[k];
}
//Zmienne pomocnicze
int zmsize = size;
MM indeksy;
Node* tmp;
while (zmsize > 1){ //Dopoki mamy wiecej niz jeden element w tablicy
indeksy = MinMin(drzewa, zmsize); //Znalezienie najmniejszych elementow
if (indeksy.max != indeksy.min){ //dodatkowe zabezpieczenie - nie potrzebne
tmp = new Node(drzewa[indeksy.min]->wartosc + drzewa[indeksy.max]->wartosc); //Tworzenie nowego wezla
//Ustawianie zmiennych wezla
tmp->left = drzewa[indeksy.min];
tmp->right = drzewa[indeksy.max];
drzewa[indeksy.min] = tmp; //Podmiana starego elementu na wezel
swap(drzewa[indeksy.max], drzewa[--zmsize]); //Podmiana i usuniecie ostatniego elementu z tabliy (zmiejszenie rozmiaru)
\
}
}
Drzewo = drzewa[0]; //Zapamietanie adresu drzewa
delete[] drzewa; //Usuniecie pomocniczej tablicy
}
void AHuffman::StworzSlownik(){
Przechodz(Drzewo,""); //Aktualizacja elementow drzewa - zapamietuje sciezki do kazdego nodea - tworzy slownik
}
//Algorytm kodujacy
void AHuffman::Przechodz(Node* element, string kod){ //Przejscie przez drzewo typem (?)
if (element == NULL)
return;
if (element->left)
Przechodz(element->left,kod+"0");
element->Odwiedz(kod);
if (element->right)
Przechodz(element->right, kod + "1");
}
string AHuffman::Translate(){
string zwrot="";
for (int k = 0; k < tekst.length(); k++){
zwrot += znaki[tablica.find(tekst[k])].kod;
}
zakodowane = zwrot;
return zwrot;
}
//Funkcje Glowne
string AHuffman::Koduj(string tresc){
tekst = tresc;
StworzListe();
StworzDrzewo();
StworzSlownik();
//Pomocnicze wypisanie slownika
for (int k = 0; k < size; k++)
cout << znaki[k].znak << " " << znaki[k].kod << endl;
return Translate();
}
string AHuffman::Dekoduj(string tresc ){
if (tresc == "")
tresc = zakodowane;
string zwrot = "";
//Odczytywanie liter ze slownika - przechodzenie przez drzewo za pomoca podanego schamatu
Node* tmp = Drzewo;
for (int k = 0; k <= tresc.length(); k++){
if (tmp->CzyLisc){
zwrot += tmp->znak;
tmp = Drzewo;
}
if (k == tresc.length())
break;
if (tresc[k] == '0')
tmp = tmp->left;
else
tmp = tmp->right;
}
return zwrot;
}
//Funkcja pomocnicza
MM AHuffman::MinMin(Node**tab, int size){
MM MiMa, zwrot; // min = min1, max = min2
zwrot.min = 0;
zwrot.max = 0;
MiMa.max = -1;
MiMa.min = -1;
int tmp;
for (int k = 0; k < size; k++){
tmp = tab[k]->wartosc;
if (tmp < MiMa.max || MiMa.max == -1){
zwrot.max = k;
MiMa.max = tmp;
}
else if (tmp <= MiMa.min || MiMa.min == -1){
zwrot.min = k;
MiMa.min = tmp;
}
}
swap(zwrot.max, zwrot.min);
return zwrot;
}
}#include "AlgHuff.h"
namespace _AHuffman{
//Konstruktory i destruktory
AHuffman::~AHuffman()
{
if (znaki != NULL)
delete[] znaki;
}
//Tworzenie potrzebnych struktur
void AHuffman::StworzListe(){
string znalezione = "";
int* wystapienia = new int[MaksZnakow];
int size = 0;
//Zliczenie wystepujacych znakow
int tmp;
char znak;
for (int k = 0; k < tekst.length(); k++){
znak = tekst[k];
tmp = znalezione.find(znak);
if (tmp == -1){ //Jeśli nie znaleziono, dodajemy nowy znak do słownika/sringa
znalezione += znak;
wystapienia[size++] = 1; //Zwiększamy indeks wystapienia danego znaku(nowego)
}
else
wystapienia[tmp] ++; //Zwiekszamy indeks znalezionego znaku
}
//Tworzenie podstawowych jednostek drzew
znaki = new Node[size];
for (int k = 0; k < size; k++){
znaki[k] = Node(znalezione[k],wystapienia[k]);
}
//Porzadki
this->size = size;
tablica = znalezione;
delete[] wystapienia;
}
void AHuffman::StworzDrzewo(){
//Zapisywanie adresow wszystkich lisci
Node** drzewa = new Node*[size];
for (int k = 0; k < size; k++){
drzewa[k] = &znaki[k];
}
//Zmienne pomocnicze
int zmsize = size;
MM indeksy;
Node* tmp;
while (zmsize > 1){ //Dopoki mamy wiecej niz jeden element w tablicy
indeksy = MinMin(drzewa, zmsize); //Znalezienie najmniejszych elementow
if (indeksy.max != indeksy.min){ //dodatkowe zabezpieczenie - nie potrzebne
tmp = new Node(drzewa[indeksy.min]->wartosc + drzewa[indeksy.max]->wartosc); //Tworzenie nowego wezla
//Ustawianie zmiennych wezla
tmp->left = drzewa[indeksy.min];
tmp->right = drzewa[indeksy.max];
drzewa[indeksy.min] = tmp; //Podmiana starego elementu na wezel
swap(drzewa[indeksy.max], drzewa[--zmsize]); //Podmiana i usuniecie ostatniego elementu z tabliy (zmiejszenie rozmiaru)
\
}
}
Drzewo = drzewa[0]; //Zapamietanie adresu drzewa
delete[] drzewa; //Usuniecie pomocniczej tablicy
}
void AHuffman::StworzSlownik(){
Przechodz(Drzewo,""); //Aktualizacja elementow drzewa - zapamietuje sciezki do kazdego nodea - tworzy slownik
}
//Algorytm kodujacy
void AHuffman::Przechodz(Node* element, string kod){ //Przejscie przez drzewo typem (?)
if (element == NULL)
return;
if (element->left)
Przechodz(element->left,kod+"0");
element->Odwiedz(kod);
if (element->right)
Przechodz(element->right, kod + "1");
}
string AHuffman::Translate(){
string zwrot="";
for (int k = 0; k < tekst.length(); k++){
zwrot += znaki[tablica.find(tekst[k])].kod;
}
zakodowane = zwrot;
return zwrot;
}
//Funkcje Glowne
string AHuffman::Koduj(string tresc){
tekst = tresc;
StworzListe();
StworzDrzewo();
StworzSlownik();
//Pomocnicze wypisanie slownika
for (int k = 0; k < size; k++)
cout << znaki[k].znak << " " << znaki[k].kod << endl;
return Translate();
}
string AHuffman::Dekoduj(string tresc ){
if (tresc == "")
tresc = zakodowane;
string zwrot = "";
//Odczytywanie liter ze slownika - przechodzenie przez drzewo za pomoca podanego schamatu
Node* tmp = Drzewo;
for (int k = 0; k <= tresc.length(); k++){
if (tmp->CzyLisc){
zwrot += tmp->znak;
tmp = Drzewo;
}
if (k == tresc.length())
break;
if (tresc[k] == '0')
tmp = tmp->left;
else
tmp = tmp->right;
}
return zwrot;
}
//Funkcja pomocnicza
MM AHuffman::MinMin(Node**tab, int size){
MM MiMa, zwrot; // min = min1, max = min2
zwrot.min = 0;
zwrot.max = 0;
MiMa.max = -1;
MiMa.min = -1;
int tmp;
for (int k = 0; k < size; k++){
tmp = tab[k]->wartosc;
if (tmp < MiMa.max || MiMa.max == -1){
zwrot.max = k;
MiMa.max = tmp;
}
else if (tmp <= MiMa.min || MiMa.min == -1){
zwrot.min = k;
MiMa.min = tmp;
}
}
swap(zwrot.max, zwrot.min);
return zwrot;
}
}#include "AlgHuff.h"
namespace _AHuffman{
//Konstruktory i destruktory
AHuffman::~AHuffman()
{
if (znaki != NULL)
delete[] znaki;
}
//Tworzenie potrzebnych struktur
void AHuffman::StworzListe(){
string znalezione = "";
int* wystapienia = new int[MaksZnakow];
int size = 0;
//Zliczenie wystepujacych znakow
int tmp;
char znak;
for (int k = 0; k < tekst.length(); k++){
znak = tekst[k];
tmp = znalezione.find(znak);
if (tmp == -1){ //Jeśli nie znaleziono, dodajemy nowy znak do słownika/sringa
znalezione += znak;
wystapienia[size++] = 1; //Zwiększamy indeks wystapienia danego znaku(nowego)
}
else
wystapienia[tmp] ++; //Zwiekszamy indeks znalezionego znaku
}
//Tworzenie podstawowych jednostek drzew
znaki = new Node[size];
for (int k = 0; k < size; k++){
znaki[k] = Node(znalezione[k],wystapienia[k]);
}
//Porzadki
this->size = size;
tablica = znalezione;
delete[] wystapienia;
}
void AHuffman::StworzDrzewo(){
//Zapisywanie adresow wszystkich lisci
Node** drzewa = new Node*[size];
for (int k = 0; k < size; k++){
drzewa[k] = &znaki[k];
}
//Zmienne pomocnicze
int zmsize = size;
MM indeksy;
Node* tmp;
while (zmsize > 1){ //Dopoki mamy wiecej niz jeden element w tablicy
indeksy = MinMin(drzewa, zmsize); //Znalezienie najmniejszych elementow
if (indeksy.max != indeksy.min){ //dodatkowe zabezpieczenie - nie potrzebne
tmp = new Node(drzewa[indeksy.min]->wartosc + drzewa[indeksy.max]->wartosc); //Tworzenie nowego wezla
//Ustawianie zmiennych wezla
tmp->left = drzewa[indeksy.min];
tmp->right = drzewa[indeksy.max];
drzewa[indeksy.min] = tmp; //Podmiana starego elementu na wezel
swap(drzewa[indeksy.max], drzewa[--zmsize]); //Podmiana i usuniecie ostatniego elementu z tabliy (zmiejszenie rozmiaru)
\
}
}
Drzewo = drzewa[0]; //Zapamietanie adresu drzewa
delete[] drzewa; //Usuniecie pomocniczej tablicy
}
void AHuffman::StworzSlownik(){
Przechodz(Drzewo,""); //Aktualizacja elementow drzewa - zapamietuje sciezki do kazdego nodea - tworzy slownik
}
//Algorytm kodujacy
void AHuffman::Przechodz(Node* element, string kod){ //Przejscie przez drzewo typem (?)
if (element == NULL)
return;
if (element->left)
Przechodz(element->left,kod+"0");
element->Odwiedz(kod);
if (element->right)
Przechodz(element->right, kod + "1");
}
string AHuffman::Translate(){
string zwrot="";
for (int k = 0; k < tekst.length(); k++){
zwrot += znaki[tablica.find(tekst[k])].kod;
}
zakodowane = zwrot;
return zwrot;
}
//Funkcje Glowne
string AHuffman::Koduj(string tresc){
tekst = tresc;
StworzListe();
StworzDrzewo();
StworzSlownik();
//Pomocnicze wypisanie slownika
for (int k = 0; k < size; k++)
cout << znaki[k].znak << " " << znaki[k].kod << endl;
return Translate();
}
string AHuffman::Dekoduj(string tresc ){
if (tresc == "")
tresc = zakodowane;
string zwrot = "";
//Odczytywanie liter ze slownika - przechodzenie przez drzewo za pomoca podanego schamatu
Node* tmp = Drzewo;
for (int k = 0; k <= tresc.length(); k++){
if (tmp->CzyLisc){
zwrot += tmp->znak;
tmp = Drzewo;
}
if (k == tresc.length())
break;
if (tresc[k] == '0')
tmp = tmp->left;
else
tmp = tmp->right;
}
return zwrot;
}
//Funkcja pomocnicza
MM AHuffman::MinMin(Node**tab, int size){
MM MiMa, zwrot; // min = min1, max = min2
zwrot.min = 0;
zwrot.max = 0;
MiMa.max = -1;
MiMa.min = -1;
int tmp;
for (int k = 0; k < size; k++){
tmp = tab[k]->wartosc;
if (tmp < MiMa.max || MiMa.max == -1){
zwrot.max = k;
MiMa.max = tmp;
}
else if (tmp <= MiMa.min || MiMa.min == -1){
zwrot.min = k;
MiMa.min = tmp;
}
}
swap(zwrot.max, zwrot.min);
return zwrot;
}
}#include "AlgHuff.h"
namespace _AHuffman{
//Konstruktory i destruktory
AHuffman::~AHuffman()
{
if (znaki != NULL)
delete[] znaki;
}
//Tworzenie potrzebnych struktur
void AHuffman::StworzListe(){
string znalezione = "";
int* wystapienia = new int[MaksZnakow];
int size = 0;
//Zliczenie wystepujacych znakow
int tmp;
char znak;
for (int k = 0; k < tekst.length(); k++){
znak = tekst[k];
tmp = znalezione.find(znak);
if (tmp == -1){ //Jeśli nie znaleziono, dodajemy nowy znak do słownika/sringa
znalezione += znak;
wystapienia[size++] = 1; //Zwiększamy indeks wystapienia danego znaku(nowego)
}
else
wystapienia[tmp] ++; //Zwiekszamy indeks znalezionego znaku
}
//Tworzenie podstawowych jednostek drzew
znaki = new Node[size];
for (int k = 0; k < size; k++){
znaki[k] = Node(znalezione[k],wystapienia[k]);
}
//Porzadki
this->size = size;
tablica = znalezione;
delete[] wystapienia;
}
void AHuffman::StworzDrzewo(){
//Zapisywanie adresow wszystkich lisci
Node** drzewa = new Node*[size];
for (int k = 0; k < size; k++){
drzewa[k] = &znaki[k];
}
//Zmienne pomocnicze
int zmsize = size;
MM indeksy;
Node* tmp;
while (zmsize > 1){ //Dopoki mamy wiecej niz jeden element w tablicy
indeksy = MinMin(drzewa, zmsize); //Znalezienie najmniejszych elementow
if (indeksy.max != indeksy.min){ //dodatkowe zabezpieczenie - nie potrzebne
tmp = new Node(drzewa[indeksy.min]->wartosc + drzewa[indeksy.max]->wartosc); //Tworzenie nowego wezla
//Ustawianie zmiennych wezla
tmp->left = drzewa[indeksy.min];
tmp->right = drzewa[indeksy.max];
drzewa[indeksy.min] = tmp; //Podmiana starego elementu na wezel
swap(drzewa[indeksy.max], drzewa[--zmsize]); //Podmiana i usuniecie ostatniego elementu z tabliy (zmiejszenie rozmiaru)
\
}
}
Drzewo = drzewa[0]; //Zapamietanie adresu drzewa
delete[] drzewa; //Usuniecie pomocniczej tablicy
}
void AHuffman::StworzSlownik(){
Przechodz(Drzewo,""); //Aktualizacja elementow drzewa - zapamietuje sciezki do kazdego nodea - tworzy slownik
}
//Algorytm kodujacy
void AHuffman::Przechodz(Node* element, string kod){ //Przejscie przez drzewo typem (?)
if (element == NULL)
return;
if (element->left)
Przechodz(element->left,kod+"0");
element->Odwiedz(kod);
if (element->right)
Przechodz(element->right, kod + "1");
}
string AHuffman::Translate(){
string zwrot="";
for (int k = 0; k < tekst.length(); k++){
zwrot += znaki[tablica.find(tekst[k])].kod;
}
zakodowane = zwrot;
return zwrot;
}
//Funkcje Glowne
string AHuffman::Koduj(string tresc){
tekst = tresc;
StworzListe();
StworzDrzewo();
StworzSlownik();
//Pomocnicze wypisanie slownika
for (int k = 0; k < size; k++)
cout << znaki[k].znak << " " << znaki[k].kod << endl;
return Translate();
}
string AHuffman::Dekoduj(string tresc ){
if (tresc == "")
else
wystapienia[tmp] ++; //Zwiekszamy indeks znalezionego znaku
}
//Tworzenie podstawowych jednostek drzew
znaki = new Node[size];
for (int k = 0; k < size; k++){
znaki[k] = Node(znalezione[k],wystapienia[k]);
}
//Porzadki
this->size = size;
tablica = znalezione;
delete[] wystapienia;
}
void AHuffman::StworzDrzewo(){
//Zapisywanie adresow wszystkich lisci
Node** drzewa = new Node*[size];
for (int k = 0; k < size; k++){
drzewa[k] = &znaki[k];
}
//Zmienne pomocnicze
int zmsize = size;
MM indeksy;
Node* tmp;
while (zmsize > 1){ //Dopoki mamy wiecej niz jeden element w tablicy
indeksy = MinMin(drzewa, zmsize); //Znalezienie najmniejszych elementow
if (indeksy.max != indeksy.min){ //dodatkowe zabezpieczenie - nie potrzebne
tmp = new Node(drzewa[indeksy.min]->wartosc + drzewa[indeksy.max]->wartosc); //Tworzenie nowego wezla
zwrot.max = 0;
MiMa.max = -1;
MiMa.min = -1;
int tmp;
for (int k = 0; k < size; k++){
tmp = tab[k]->wartosc;
if (tmp < MiMa.max || MiMa.max == -1){
zwrot.max = k;
MiMa.max = tmp;
}
else if (tmp <= MiMa.min || MiMa.min == -1){
zwrot.min = k;
MiMa.min = tmp;
}
}
swap(zwrot.max, zwrot.min);
return zwrot;
}
}#include "AlgHuff.h"
namespace _AHuffman{
return zwrot;
}
} | [
"[email protected]"
] | |
79cdce1bf478025175740b554881c6d7c2c3d422 | 09833b30a039d497b5c818cdb9872788ca4f20ef | /FilteriCAP/Models/FilteringPlainTextListModel.cpp | 63acbd1c25940677c53327168dff7a0e30c930a2 | [] | no_license | cloudveiltech/Filter-ICAP | 7eab704c60e3be486f66a298299d9be0fd26e248 | 6772b8e33f93ed04341f6adb1922d14b89e9378e | refs/heads/master | 2021-04-29T18:44:46.971430 | 2018-02-17T05:20:31 | 2018-02-17T05:20:31 | 121,699,734 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 953 | cpp | /*
* Copyright © 2018 Cloudveil Technology Inc.
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "FilteringPlainTextListModel.hpp"
namespace CitadeliCAP
{
namespace Models
{
FilteringPlainTextListModel::FilteringPlainTextListModel(const PlainTextFilteringListType type, const std::string& relativeListPath) noexcept
:
m_type(type),
m_relativeListPath(relativeListPath)
{
}
FilteringPlainTextListModel::~FilteringPlainTextListModel() noexcept
{
}
const PlainTextFilteringListType FilteringPlainTextListModel::GetListType() const noexcept
{
return m_type;
}
const std::string& FilteringPlainTextListModel::GetListRelativePath() const noexcept
{
return m_relativeListPath;
}
} /* namespace Models */
} /* namespace CitadeliCAP */
| [
"[email protected]"
] | |
7bd7da940deaa4be3ea584794e7a0b21f60a3e3a | e76e11fdd44d47b32b8f0296dd56b5367c38ef97 | /gui/src/OpenGLSceneWidget.cpp | f1185e719645a4313ba0c8a2064f0436c3b18a91 | [
"MIT"
] | permissive | arindamrc/DDPFF | b59c914a2176451c7423b5a8862e7c8cbe982664 | 9f26069105225d7710a7352a5aa93dafe53d75af | refs/heads/main | 2023-08-22T16:40:19.272066 | 2021-09-29T07:13:05 | 2021-09-29T07:13:05 | 344,935,539 | 27 | 4 | null | 2021-09-29T07:13:05 | 2021-03-05T21:12:56 | C++ | UTF-8 | C++ | false | false | 5,402 | cpp | #include <GL/glew.h>
#include "gui/OpenGLSceneWidget.h"
#include "globals/Command.h"
#include "globals/Config.h"
#include "control/State.h"
void OpenGLSceneWidget::drawFloor() const
{
float size = 2.0*radius;
float stride = 1.0;
glBegin( GL_QUADS );
glColor3f(0.95, 0.95, 0.95);
glVertex3f(-size, -size, 0);
glVertex3f(-size, size, 0);
glVertex3f(size, size, 0);
glVertex3f(size, -size, 0);
glEnd();
glLineWidth(1);
glBegin( GL_LINES );
glColor3f(0.65, 0.65, 0.65);
for (float i = -size; i <= size + 0.0001; i = i+stride)
{
glVertex3f(i, -size, 0.001);
glVertex3f(i, size, 0.001);
glVertex3f(-size, i, 0.001);
glVertex3f(size, i, 0.001);
}
glEnd();
}
void OpenGLSceneWidget::drawCameraTransform() const
{
glPushMatrix();
glMultMatrixd(scene->getCameraPose().data());
QGLViewer::drawAxis(0.3);
glPopMatrix();
}
void OpenGLSceneWidget::init()
{
restoreStateFromFile();
setBackgroundColor(QColor(255,255,255));
setForegroundColor(QColor(0,0,0));
setFont(QFont("Helvetica", 18));
setAxisIsDrawn(false);
setSceneRadius(radius);
// Light setup
glDisable(GL_LIGHTING);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
initialized = true;
}
void OpenGLSceneWidget::draw()
{
scene->draw();
if (command.showFloor) {
drawFloor();
}
if (command.showCameraTransform) {
drawCameraTransform();
}
// Update the camera position. Probably should find a better place to do this.
// As of now, every update involves a matrix inversion as well.
scene->setCameraPose(config.sceneCameraX, config.sceneCameraY, config.sceneCameraZ, config.sceneCameraRoll, config.sceneCameraPitch, config.sceneCameraYaw);
// Update the point buffers
scene->render(curState.pointBuffer, curState.gtNormalBuffer, curState.colorBuffer, curState.depthBuffer, curState.gtPlaneBuffer);
curState.update();
emit updateUI();
}
void OpenGLSceneWidget::mousePressEvent(QMouseEvent *qme)
{
QGLViewer::mousePressEvent(qme);
}
void OpenGLSceneWidget::keyPressEvent(QKeyEvent *event)
{
if (event->isAutoRepeat()){
return;
}
bool updated = false;
if (event->key() == Qt::Key_Up && event->modifiers() & Qt::ControlModifier) {
config.sceneCameraPitch += 0.1;
updated = true;
} else if (event->key() == Qt::Key_Up && event->modifiers() & Qt::ShiftModifier) {
config.sceneCameraZ += 0.1;
updated = true;
} else if (event->key() == Qt::Key_Up) {
config.sceneCameraX += 0.1;
updated = true;
} else if (event->key() == Qt::Key_Down && event->modifiers() & Qt::ControlModifier) {
config.sceneCameraPitch -= 0.1;
updated = true;
} else if (event->key() == Qt::Key_Down && event->modifiers() & Qt::ShiftModifier) {
config.sceneCameraZ -= 0.1;
updated = true;
} else if (event->key() == Qt::Key_Down) {
config.sceneCameraX -= 0.1;
updated = true;
} else if (event->key() == Qt::Key_Left && event->modifiers() & Qt::ControlModifier) {
config.sceneCameraRoll += 0.1;
updated = true;
} else if (event->key() == Qt::Key_Left && event->modifiers() & Qt::ShiftModifier) {
config.sceneCameraYaw += 0.1;
updated = true;
} else if (event->key() == Qt::Key_Left) {
config.sceneCameraY += 0.1;
updated = true;
} else if (event->key() == Qt::Key_Right && event->modifiers() & Qt::ControlModifier) {
config.sceneCameraRoll -= 0.1;
updated = true;
} else if (event->key() == Qt::Key_Right && event->modifiers() & Qt::ShiftModifier) {
config.sceneCameraYaw -= 0.1;
updated = true;
} else if (event->key() == Qt::Key_Right) {
config.sceneCameraY -= 0.1;
updated = true;
} else if (event->key() == Qt::Key_Space) {
// Signifies no-operation; simply record the current scene and camera pose.
updated = true;
}
scene->setCameraPose(config.sceneCameraX, config.sceneCameraY, config.sceneCameraZ, config.sceneCameraRoll, config.sceneCameraPitch, config.sceneCameraYaw);
curState.cameraPose.position.x() = config.sceneCameraX; curState.cameraPose.position.y() = config.sceneCameraY; curState.cameraPose.position.z() = config.sceneCameraZ;
curState.cameraPose.orientation.x() = config.sceneCameraRoll; curState.cameraPose.orientation.y() = config.sceneCameraPitch; curState.cameraPose.orientation.z() = config.sceneCameraYaw;
update();
curState.bufferAppend(config.bufferSize);
}
void OpenGLSceneWidget::paintEvent(QPaintEvent *paintEvent)
{
QGLViewer::paintEvent(paintEvent);
}
OpenGLSceneWidget::OpenGLSceneWidget(QWidget *parent) : QGLViewer(parent)
{
radius = 6.0;
}
OpenGLSceneWidget::~OpenGLSceneWidget()
{
if (initialized) {
saveStateToFile();
}
}
void OpenGLSceneWidget::toggleAxis()
{
toggleAxisIsDrawn();
update();
}
void OpenGLSceneWidget::swapScene(const uchar& sceneId) {
Vec3 translation(config.sceneCameraX, config.sceneCameraY, config.sceneCameraZ);
Vec3 rotation(config.sceneCameraRoll, config.sceneCameraPitch, config.sceneCameraYaw);
scene = Scene::getScene(curState.unitImage, command.openGlScene, config.sceneRadius, sceneId, translation, rotation);
}
| [
"[email protected]"
] | |
71ef71626f0b32c0f126641da0a78ebbac89f5a7 | 51635684d03e47ebad12b8872ff469b83f36aa52 | /external/gcc-12.1.0/libstdc++-v3/config/locale/generic/c++locale_internal.h | 35564e3a57a04307c04174cd278c372a05fd5766 | [
"LGPL-2.1-only",
"GPL-3.0-only",
"GCC-exception-3.1",
"GPL-2.0-only",
"LGPL-3.0-only",
"LGPL-2.0-or-later",
"Zlib",
"LicenseRef-scancode-public-domain"
] | permissive | zhmu/ananas | 8fb48ddfe3582f85ff39184fc7a3c58725fe731a | 30850c1639f03bccbfb2f2b03361792cc8fae52e | refs/heads/master | 2022-06-25T10:44:46.256604 | 2022-06-12T17:04:40 | 2022-06-12T17:04:40 | 30,108,381 | 59 | 8 | Zlib | 2021-09-26T17:30:30 | 2015-01-31T09:44:33 | C | UTF-8 | C++ | false | false | 1,160 | h | // Locale internal implementation header -*- C++ -*-
// Copyright (C) 2002-2022 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library 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, 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 General Public License for more details.
// Under Section 7 of GPL version 3, you are granted additional
// permissions described in the GCC Runtime Library Exception, version
// 3.1, as published by the Free Software Foundation.
// You should have received a copy of the GNU General Public License and
// a copy of the GCC Runtime Library Exception along with this program;
// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
// <http://www.gnu.org/licenses/>.
// The generic locale code doesn't need to do anything here (yet)
| [
"[email protected]"
] | |
4ddb01ab3dddc4c336d07d79d00520135b2d8d05 | 651be001fc2414332d4022c8bc6a6467c901dc7c | /Classes/Gun.cpp | 08ca39f5589b54f1d77f7add1af6731b8a9e2a82 | [] | no_license | Yunnglin/Portal-TheLostCity | d1b309b63266edc93e14f1cf8fb04e11c3f57d3f | 9b1541be399e82b11dcba908e66b6259895b99dd | refs/heads/master | 2020-03-28T08:55:46.742540 | 2018-09-09T14:47:43 | 2018-09-09T14:47:43 | 145,393,204 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,297 | cpp | #include "Gun.h"
#include "Portal.h"
#include "config.h"
USING_NS_CC;
Gun::~Gun() {
m_bluePortal->release();
m_yellowPortal->release();
}
bool Gun::init()
{
m_bluePortal = Portal::create();
m_bluePortal->bindSprite(Sprite::create("portalblue.png"));
m_bluePortal->setName("blue");
m_bluePortal->retain();
m_yellowPortal = Portal::create();
m_yellowPortal->bindSprite(Sprite::create("portalyellow.png"));
m_yellowPortal->setName("yellow");
m_yellowPortal->retain();
return true;
}
void Gun::setSprite(Sprite* sprite)
{
m_sprite = sprite;
this->addChild(m_sprite);
this->setContentSize(m_sprite->getContentSize());
}
Sprite* Gun::getSprite()
{
return m_sprite;
}
void Gun::shot(EventMouse::MouseButton button, Vec2 vec)
{
auto scene = Director::getInstance()->getRunningScene();
if (getChildByName("TSprite") == NULL) {
return;
}
auto pos = Node::convertToWorldSpace(this->getChildByName("TSprite")->getPosition());
Vec2 v = vec.getNormalized() * 1500;
Portal* portal = NULL;
switch (button) {
case EventMouse::MouseButton::BUTTON_LEFT:
this->removeChildByName("TSprite");
if (m_bluePortal->getParent() == NULL) {
scene->addChild(m_bluePortal);
}
m_bluePortal->setScaleX(1);
m_bluePortal->setScaleY(1);
m_bluePortal->setPosition(pos);
portal = m_bluePortal;
break;
case EventMouse::MouseButton::BUTTON_RIGHT:
this->removeChildByName("TSprite");
if (m_yellowPortal->getParent() == NULL) {
scene->addChild(m_yellowPortal);
}
m_yellowPortal->setScaleX(1);
m_yellowPortal->setScaleY(1);
m_yellowPortal->setPosition(pos);
portal = m_yellowPortal;
break;
default:
return;
}
portal->getPhysicsBody()->setVelocity(v);
}
bool Gun::standBy(EventMouse::MouseButton button)
{
auto blue = Sprite::create("portalblue.png");
auto yellow = Sprite::create("portalyellow.png");
switch (button) {
case EventMouse::MouseButton::BUTTON_LEFT:
blue->setName("TSprite");
this->addChild(blue);
blue->setPosition(Vec2(this->getContentSize().width / 6 * 5, this->getContentSize().height / 2.5));
break;
case EventMouse::MouseButton::BUTTON_RIGHT:
yellow->setName("TSprite");
this->addChild(yellow);
yellow->setPosition(Vec2(this->getContentSize().width / 6 * 5, this->getContentSize().height / 2.5));
break;
}
return true;
} | [
"[email protected]"
] | |
13c9c1d9b291366bc4502f611e7c28cbe59d73ce | 7523c08d3dc062a383b06c8e03c7f79f25de3b2a | /1647/solution.cpp | e328d7b57251bdfd3521c206a68575fc75bdf234 | [] | no_license | Louis5499/leetcode-practice | 580374689717e70be34cde271b0f2c020a48ba7d | c2c80faa8d823f955e8983e67fe7a8ba801c6e85 | refs/heads/master | 2023-08-01T23:44:19.506050 | 2021-10-06T22:29:31 | 2021-10-06T22:29:31 | 326,630,594 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 591 | cpp | class Solution {
public:
int minDeletions(string s) {
vector<int> counts(26, 0);
for (char c: s) {
counts[c-'a']++;
}
unordered_map<int, int> m;
int movement = 0;
for (int i=0; i<counts.size(); i++) {
if (counts[i] == 0) continue;
int runningCount = counts[i];
while (m.find(runningCount) != m.end() && runningCount > 0) {
movement++;
runningCount--;
}
m[runningCount] = i;
}
return movement;
}
}; | [
"[email protected]"
] | |
bbfb92bf9f2826af9452d8dca18f39ff3858e09d | 154c3822e32c3fc707e775531d3973834345d270 | /OOP - Inheritance C++/7_Clases_abstractas/Planta.h | 944537e31245cd27ee415c1bdf2dbc34ffd973d5 | [] | no_license | MEng-Alejandro-Nieto/Learning-cpp | f2da6a4f46eb1f86d472d8a1469bd885eb99287c | 3d17d451cb534afdf9ea79e2fcb8e5495dc8a6d7 | refs/heads/master | 2020-07-30T13:08:22.122242 | 2019-12-05T23:20:48 | 2019-12-05T23:20:48 | 210,244,804 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 199 | h | #include <iostream>
#include "Servivo.h"
using namespace std;
class Planta : public Servivo{
public:
void alimentarse(){
cout<<"La planta se alimenta mediante la fotosintesis"<<endl;
}
};
| [
"[email protected]"
] | |
507a2567beffa8464efb17121f0b307c5b6dd51c | 5ad99bf8f500cbb2bc7d532812dc33d5f642205d | /net/Queue.h | 063cddfb5510d90042aebc651f5c320e67a89ad1 | [] | no_license | cmguo/just-p2p-trip-client | 3cd4e861586b82376a3e10e98cb6afbd17611c0d | a200fea3c5afcb1da27d8201865a1c8511e0dc98 | refs/heads/master | 2022-11-18T23:08:37.256621 | 2018-07-13T01:41:33 | 2018-07-13T02:54:52 | 280,889,464 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 957 | h | // Queue.h
#ifndef _TRIP_CLIENT_NET_QUEUE_H_
#define _TRIP_CLIENT_NET_QUEUE_H_
namespace trip
{
namespace client
{
class Cell;
class Queue
{
public:
virtual ~Queue() {}
virtual bool push(
Cell * c,
void * p);
virtual void * first(Cell *& c) const;
virtual void pop() = 0;
virtual void on_timer(
Time const & now);
virtual bool empty() const;
virtual size_t size() const = 0;
protected:
struct Packet
{
Cell * c;
void * p;
};
protected:
virtual bool push(
Packet const & pkt) = 0;
virtual Packet const * first() const = 0;
};
} // namespace client
} // namespace trip
#endif // _TRIP_CLIENT_NET_QUEUE_H_
| [
"[email protected]"
] | |
1aa480c7e34ee2970fe73b0da27e59121b9e6d75 | ac5eee316c6f9e83ba247d6993bd169f678e60fd | /MIA 2012/icow.cpp | 4eb3f52cf7497eeb7da7c30d223d0eb8c557d163 | [] | no_license | mino5/Problem-Solutions | 06ffee5bdc57b4350802560b42b507fee3f619b9 | 7774f546105a267a127dedc60ac70612811b1529 | refs/heads/master | 2021-01-12T18:14:33.206644 | 2016-10-20T00:58:01 | 2016-10-20T00:58:01 | 71,346,496 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 759 | cpp | #include <stdio.h>
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
int N, T;
int *R;
cin >> N;
cin >> T;
R = new int[N];
short int max;
short int maxPos;
short int i;
for (i = 0; i < N; i++)
{
cin >> R[i];
}
for (int i = 0; i < T; i++)
{
max = -1;
for (int j = 0; j < N; j++)
{
if (R[j] > max)
{
max = R[j];
maxPos = j;
}
}
cout << maxPos + 1 << endl;
int distrubution = max / (N - 1);
int rest = max - distrubution * (N - 1);
R[maxPos] = 0;
for (int j = 0; j < N; j++)
{
if (j != maxPos)
{
if (rest > 0)
{
R[j] += 1;
rest--;
}
R[j] += distrubution;
}
}
}
return 0;
}
| [
"[email protected]"
] | |
bce36edbdadbaea03e015921611743bb43f3f717 | 83aca81ee006fb1b4b965e746786e5276d218cb6 | /2018/include/maya/MPxPolyTweakUVInteractiveCommand.h | 961859d8af2e01e31a1a23c1974ca06b8299fc38 | [] | no_license | smart-tai/maya_SDK | cef4d73b812d294ad44e89b714b46c18929965e1 | 9549d16c028880f2c4735b7b371ca8bc427a7d0e | refs/heads/master | 2023-02-23T03:25:12.113515 | 2020-03-21T08:29:17 | 2020-03-21T08:29:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,136 | h | #ifndef _MPxPolyTweakUVInteractiveCommand
#define _MPxPolyTweakUVInteractiveCommand
//-
// ===========================================================================
// Copyright 2017 Autodesk, Inc. All rights reserved.
//
// Use of this software is subject to the terms of the Autodesk license
// agreement provided at the time of installation or download, or which
// otherwise accompanies this software in either electronic or hard copy form.
// ===========================================================================
//+
//
// CLASS: MPxPolyTweakUVInteractiveCommand
//
// ****************************************************************************
#if defined __cplusplus
// ****************************************************************************
// INCLUDED HEADER FILES
#include <maya/MTypes.h>
#include <maya/MStatus.h>
#include <maya/MPxCommand.h>
#include <maya/MPxToolCommand.h>
OPENMAYA_MAJOR_NAMESPACE_OPEN
// ****************************************************************************
// CLASS DECLARATION (MPxPolyTweakUVInteractiveCommand)
//! \ingroup OpenMayaUI MPx
//! \brief Base class used for moving polygon UV's.
/*!
This is the base class for UV editing interactive commands on polygonal objects.
The purpose of this tool command class is to simplify the process of moving
UVs on a polygonal object. The use is only required to provide the new
positions of the UVs that being modified, and finalize at the end of editing.
*/
class OPENMAYAUI_EXPORT MPxPolyTweakUVInteractiveCommand : public MPxToolCommand
{
public:
MPxPolyTweakUVInteractiveCommand();
virtual ~MPxPolyTweakUVInteractiveCommand();
void setUVs( const MObject & mesh,
MIntArray & uvList,
MFloatArray & uPos,
MFloatArray & vPos,
const MString *uvSet = NULL );
virtual bool isUndoable() const;
virtual MStatus doIt( const MArgList& args ) ;
virtual MStatus cancel();
virtual MStatus finalize();
static const char* className();
private:
void * fCommand;
};
OPENMAYA_NAMESPACE_CLOSE
#endif /* __cplusplus */
#endif /* _MPxPolyTweakUVInteractiveCommand */
| [
"123"
] | 123 |
0c484fd051583cd07921eeeae99a703b36aad773 | 29be7c52e05d32a4b02e6c0a1a6424abb2f60d57 | /fuse-qreader/Example/build/Android/Preview/app/src/main/include/Uno.Comparison-1.h | dfe6f15e79cb81c3665ad86c2468a59ce4600a5c | [
"MIT"
] | permissive | redtree0/CITOS-APP | 3b8cbc86fd88f6adb5b480035788eac08290c7a6 | 624f69770d8573dffc174f1f9540c22f19c71f14 | refs/heads/master | 2020-03-29T05:42:49.041569 | 2018-09-25T14:24:55 | 2018-09-25T14:24:55 | 149,594,359 | 0 | 0 | null | 2018-09-20T10:47:57 | 2018-09-20T10:47:57 | null | UTF-8 | C++ | false | false | 381 | h | // This file was generated based on C:/Users/채재윤융합IT학부/AppData/Local/Fusetools/Packages/UnoCore/1.9.0/Source/Uno/Comparison.uno.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Uno.Delegate.h>
namespace g{
namespace Uno{
// public delegate int Comparison<T>(T a, T b) :6
uDelegateType* Comparison_typeof();
}} // ::g::Uno
| [
"[email protected]"
] | |
dad64af6e3c9396e68d6d7408a8b100ba3e9a37d | b8aee0051f0339b9a60fda470cee0b9d7ec4d4a7 | /TBsellerclient/TBsellerclient/stdafx.cpp | 9a274561bb88f84f7d3020c9c17aaa1eec975d94 | [] | no_license | DioYeam/c-win32 | 068af85412315f9fa1a9c9f26c655b783b540f12 | f66f1b7941afe111fa2509d1a9f600f744e7d1b2 | refs/heads/master | 2021-01-25T22:33:22.422376 | 2020-02-26T08:59:48 | 2020-02-26T08:59:48 | 243,201,734 | 0 | 1 | null | null | null | null | GB18030 | C++ | false | false | 265 | cpp | // stdafx.cpp : 只包括标准包含文件的源文件
// TBsellerclient.pch 将作为预编译头
// stdafx.obj 将包含预编译类型信息
#include "stdafx.h"
// TODO: 在 STDAFX.H 中引用任何所需的附加头文件,
//而不是在此文件中引用
| [
"[email protected]"
] | |
09e8ba0cd81aa0792d874da9b6faf95b643ca4d4 | 322db0227e38a60db6541f94c305f4460b5f9573 | /51Nod/1694.cpp | 594821ee39f9e6263af281999e0e4edd93c823a6 | [] | no_license | miluplay/AlgorithmProblemList | 74eb29ff4810be1f3807d3ca37fe53bd38852b4e | 36327009afe863ad6a25ac80e2ebfddc11ef5cd9 | refs/heads/master | 2022-12-22T06:48:59.098857 | 2020-08-26T09:47:29 | 2020-08-26T09:47:29 | 269,381,987 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 214 | cpp | // Link:https://www.51nod.com/Challenge/Problem.html#problemId=1694
#include <iostream>
#define BT ios::sync_with_stdio(false), std::cin.tie(0), std::cout.tie(0);
using namespace std;
int main() { BT
return 0; } | [
"[email protected]"
] | |
a3cd6cfe653644af7447baf4ae03f7524ae7a9f9 | ccfbf5a9ee9c00282c200945bbe36b387eb38b19 | /Codeforces Solutions/codeforces 877E-5.cpp | 405416c07465ab9291993f3ef431c5861dc752a8 | [] | no_license | sakiib/OnlineJudge-Solutions | e070d4b255d036cdefaf087e9f75b69db708406c | b024352aa99efe548b48ef74c492cb69c1fa89f9 | refs/heads/master | 2023-01-07T20:57:04.259395 | 2020-11-16T08:41:27 | 2020-11-16T08:41:27 | 288,191,980 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,801 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long int LL;
typedef unsigned long long uLL;
typedef pair< int,int > ii;
typedef pair< int,ii > iii;
const int inf = 1e9;
const LL INF = 1e18;
const int N = 100005;
const int MOD = 1e9+7;
const double EPS = 1e-6;
const double PI = acos(-1.0);
vector <int> graph[ 2*N ];
int Time = 0;
int Start[ 2*N ] , Finish[ 2*N ] , Lazy[ 2*4*N ], Tree[ 2*4*N ];
char comm[ 10 ];
void dfs( int s , int p ) {
Start[s] = ++Time;
for( int i = 0; i < graph[ s ].size(); i++ ) {
int next = graph[ s ][ i ];
if( next == p ) continue;
dfs( next , s );
}
Finish[s] = Time;
}
void Build( int node , int b , int e , int pos , int val ) {
if( pos > e || pos < b || b > e ) return;
if( b == e && b == pos ) {
Tree[node] = val;
return;
}
int left = node << 1 , right = left | 1 , mid = (b+e) >> 1;
Build( left , b , mid , pos , val );
Build( right , mid+1 , e , pos , val );
Tree[node] = Tree[left] + Tree[right];
}
void Propagate( int node , int b , int e ) {
if( Lazy[node] != 0 ) {
Tree[node] = (e-b+1)-Tree[node];
if( b != e ) {
Lazy[2*node] ^= 1;
Lazy[2*node+1] ^= 1;
}
Lazy[node] = 0;
}
}
int Query( int node , int b , int e , int i , int j ) {
Propagate( node , b , e );
if( i > e || j < b || b > e ) return 0;
if( i <= b && j >= e ) return Tree[node];
int left = node << 1 , right = left | 1 , mid = (b+e) >> 1;
int q1 = Query( left , b , mid , i , j );
int q2 = Query( right , mid+1 , e , i , j );
return ( q1+q2 );
}
void Update( int node , int b , int e , int i , int j ) {
Propagate( node , b , e );
if( i > e || j < b || b > e ) return;
if( i <= b && j >= e ) {
Tree[node] = (e-b+1)-Tree[node];
if( b != e ) {
Lazy[2*node] ^= 1;
Lazy[2*node+1] ^= 1;
}
return;
}
int left = node << 1 , right = left | 1 , mid = (b+e) >> 1;
Update( left , b , mid , i , j );
Update( right , mid+1 , e , i , j );
Tree[node] = Tree[left] + Tree[right];
}
int main( int argc, char const *argv[] ) {
int n;
scanf("%d",&n);
for( int i = 2; i <= n; i++ ) {
int val;
scanf("%d",&val);
graph[ i ].push_back( val );
graph[ val ].push_back( i );
}
dfs( 1 , 0 );
for( int i = 1; i <= n; i++ ) {
int cur;
scanf("%d",&cur);
Build( 1 , 1 , n , Start[i] , cur );
}
int q , node;
scanf("%d",&q);
while( q-- ) {
scanf("%s %d",comm,&node);
if( comm[0] == 'p' ) Update( 1 , 1 , n , Start[node] , Finish[node] );
else printf("%d\n",Query( 1 , 1 , n , Start[node] , Finish[node] ));
}
return 0;
}
| [
"[email protected]"
] | |
9a98a7652fc086f191649929af9e295fdecc3955 | 764847ca56d7b12e79cf5fcd66c3e762c9250157 | /homework3_71910/Tree.hpp | 46a6e4cec05dd887471b8d5b7c87c8c284f87588 | [] | no_license | dessydonchewa99/data_structures-FMI_2019-2020 | 904e1eafb97eb00344011d63a0eced8eea03a810 | f346e7890a22b9baccf3b1f9fffc7610cee90f36 | refs/heads/master | 2022-10-09T15:10:14.524638 | 2020-06-05T16:10:21 | 2020-06-05T16:10:21 | 269,697,345 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 832 | hpp | //
// Tree.hpp
// hw3
//
// Created by Desislava Doncheva on 16.12.19.
// Copyright © 2019 Desislava Doncheva. All rights reserved.
//
#ifndef Tree_hpp
#define Tree_hpp
#include<iostream>
#include<stdio.h>
//#include<new>
#include<list>
using namespace std;
struct Node
{
int val;
list<Node*> children;
Node(int _val)
{
val = _val;
}
};
class Tree
{
private:
Node* root;
public:
Tree():root(nullptr) {}
~Tree();
void insert(int val, int path[], int l);
void dfs2(Node* root, int arr[], int &count, int& prev);
bool isOdd(int n); // n = vuzli
bool isGracious(int m, int n);
private:
void clear(Node* r);
bool insert(Node*& r, int _val, int path[], int level);
void dfs(Node* root, int arr[], int &count);
};
#endif /* Tree_hpp */
| [
"[email protected]"
] | |
d64d07e98c84625dd59c6085520073fd8ac3606c | af69e335fc0ff9632964d061833713b672abad01 | /Temp/StagingArea/Data/il2cppOutput/mscorlib_System_Reflection_Emit_GenericTypeParamet1988827940.h | b16e3fd641104c7950714e41bf0b36db2f6caa50 | [] | no_license | PruthvishMShirur/Solar-System | ca143ab38cef582705f0beb76f7fef8b28e25ef9 | 5cf3eaa66949801aa9a34cd3cf80eeefa64d2342 | refs/heads/master | 2023-05-26T17:53:37.489349 | 2021-06-16T19:56:48 | 2021-06-16T19:56:48 | 377,611,177 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,009 | h | #pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
#include "mscorlib_System_Type2483944760.h"
// System.Reflection.Emit.TypeBuilder
struct TypeBuilder_t1073948154;
// System.Reflection.Emit.MethodBuilder
struct MethodBuilder_t2807316753;
// System.String
struct String_t;
// System.Type
struct Type_t;
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Reflection.Emit.GenericTypeParameterBuilder
struct GenericTypeParameterBuilder_t1988827940 : public Type_t
{
public:
// System.Reflection.Emit.TypeBuilder System.Reflection.Emit.GenericTypeParameterBuilder::tbuilder
TypeBuilder_t1073948154 * ___tbuilder_8;
// System.Reflection.Emit.MethodBuilder System.Reflection.Emit.GenericTypeParameterBuilder::mbuilder
MethodBuilder_t2807316753 * ___mbuilder_9;
// System.String System.Reflection.Emit.GenericTypeParameterBuilder::name
String_t* ___name_10;
// System.Type System.Reflection.Emit.GenericTypeParameterBuilder::base_type
Type_t * ___base_type_11;
public:
inline static int32_t get_offset_of_tbuilder_8() { return static_cast<int32_t>(offsetof(GenericTypeParameterBuilder_t1988827940, ___tbuilder_8)); }
inline TypeBuilder_t1073948154 * get_tbuilder_8() const { return ___tbuilder_8; }
inline TypeBuilder_t1073948154 ** get_address_of_tbuilder_8() { return &___tbuilder_8; }
inline void set_tbuilder_8(TypeBuilder_t1073948154 * value)
{
___tbuilder_8 = value;
Il2CppCodeGenWriteBarrier(&___tbuilder_8, value);
}
inline static int32_t get_offset_of_mbuilder_9() { return static_cast<int32_t>(offsetof(GenericTypeParameterBuilder_t1988827940, ___mbuilder_9)); }
inline MethodBuilder_t2807316753 * get_mbuilder_9() const { return ___mbuilder_9; }
inline MethodBuilder_t2807316753 ** get_address_of_mbuilder_9() { return &___mbuilder_9; }
inline void set_mbuilder_9(MethodBuilder_t2807316753 * value)
{
___mbuilder_9 = value;
Il2CppCodeGenWriteBarrier(&___mbuilder_9, value);
}
inline static int32_t get_offset_of_name_10() { return static_cast<int32_t>(offsetof(GenericTypeParameterBuilder_t1988827940, ___name_10)); }
inline String_t* get_name_10() const { return ___name_10; }
inline String_t** get_address_of_name_10() { return &___name_10; }
inline void set_name_10(String_t* value)
{
___name_10 = value;
Il2CppCodeGenWriteBarrier(&___name_10, value);
}
inline static int32_t get_offset_of_base_type_11() { return static_cast<int32_t>(offsetof(GenericTypeParameterBuilder_t1988827940, ___base_type_11)); }
inline Type_t * get_base_type_11() const { return ___base_type_11; }
inline Type_t ** get_address_of_base_type_11() { return &___base_type_11; }
inline void set_base_type_11(Type_t * value)
{
___base_type_11 = value;
Il2CppCodeGenWriteBarrier(&___base_type_11, value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| [
"[email protected]"
] | |
2e0130c6731834d26dc295796ccda435b06b9392 | 91dff44b4200f53b6b928359ff9025f06ddc9fe5 | /Lab1_Papirnyk/Lab1_Papirnyk/Animal.h | c4ac1ea4a3081d0582189170a6729d2f6fdaa696 | [] | no_license | Gennerys/OOP_Practice_C_Plus_Plus | 3e1ff8353c1e0c8978664b683e66ed06c83ddff9 | c61890c9f4fd80ce42e3c7a57bc3ae41ab033816 | refs/heads/master | 2020-07-23T15:05:37.705913 | 2019-09-11T20:15:37 | 2019-09-11T20:15:37 | 207,603,278 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 139 | h | #pragma once
class Animal
{
public:
virtual void Move() = 0;
virtual void Sleep() = 0;
protected:
int HoursNeedToSleep = 0;
};
| [
"[email protected]"
] | |
5882c7bcbaed793f374a6e92afb1c8f0d0f11bf2 | fb1ae6bf81d7d560ae029ac6353edfec0f1b524a | /src/extract.cpp | 9c97f1fb90b50de00339f9c1437ee981a7625247 | [] | no_license | jerry2yu/geo | cf48e9bd75b77380689adb60896cc990623158a0 | a079a3253989faf6d2b98f014deb7e101bbf1e81 | refs/heads/master | 2021-06-01T10:34:29.617884 | 2019-10-10T00:34:11 | 2019-10-10T00:34:11 | 4,357,610 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 4,498 | cpp | /* weight a potential address,
if return 0 or negative number, not an us address,
otherwise return the likely address weight.
*/
#include "extract.hpp"
#include <iostream>
float SimpleExtract::is_us_address(const char* s,int len)
{
// cout<<"Searching ~"<<s<<"~"<<endl;
char token [200];
int weight=0;
bool has_state=false, has_sud=false, has_ss=false, has_others=false, has_sd=false;
/*flag for
has_state: contain state,
has_sud: contain secondary unit designator,
has_ss: street suffixes
has_others: others such as po or box
has_sd: street directions
*/
char *t;
int c=0;
if (len<=0) return -1;//empty, not address
//tokenize the potential address
while (1)
{
t=token;
while (*s&&isspace(*s)) {
// cout<<"isspace ~"<<*s<<"~"<<endl;
s++;c++;}
while (*s&&!isspace(*(s)))
{
// cout<<"not space ~"<<*s<<"~"<<endl;
*(t++)=toupper(*(s++));
c++;
}
*(t)='\0';
//cout<<"token ~"<<token<<"~"<<endl;
//look the token in dictionary
if (usstates.look(token))
{
has_state=true;
//cout<<token<<" is state"<<endl;
}
//look up the sud dictionary
if (sud.look(token))
{
has_sud=true;
//cout<<token<<" is sud"<<endl;
}
// look up the dictionary for Street Suffixes
if (ss.look(token))
{
has_ss=true;
//cout<<token<<" is ss"<<endl;
}
if (sd.look(token))
{
has_sd=true;
//cout<<token<<" is street direction"<<endl;
}
//look up the others dictionary
if (others.look(token))
{
has_others=true;
//cout<<token<<" is others"<<endl;
}
//cout<<"c "<<c<<" len "<<len<<endl;
if (c>=len)
break;
}
if (has_state) weight++;
// else return 0;
if (has_sud) weight++;
if (has_ss) weight++;
if (has_sd) weight++;
if (has_others) weight++;
/*if (weight>0)
cout<<s<<" is a us address"<<endl;
else
cout<<s<<" not a us address"<<endl;
*/
return weight;
}
/**
* Function is_state
* Usage: is_state ("WA")
* lookup state dictionary to check whether token is US State name
* Update: Jan 13, 2005 by Zheyuan Yu
*/
bool SimpleExtract::is_usstate(const char* token)
{
if (usstates.look(token))
return true;
else
return false;
}
/**
* Function: is_sud
* Usage: is_sud ("apartment")
* lookup dictionary to check whether a token is Secondary Unit Designator, such as APT, FLOOR
* Update: Jan 13, 2005 by Zheyuan Yu
*/
bool SimpleExtract::is_sud(const char* token)
{
if (sud.look(token))
return true;
else
return false;
}
/**
* Function: is_ss
* Usage: is_ss ("Street")
* lookup dictionary to check whether a token is
* Street Suffixes, such as AVE, Road
* Update: Jan 13, 2005 by Zheyuan Yu
*/
bool SimpleExtract::is_ss(const char* token)
{
if (ss.look(token))
return true;
else
return false;
}
/**
* Function: is_sd
* Usage: is_sud ("South")
* lookup dictionary to check whether a token is Street Direction, such North, south
* Update: Jan 13, 2005 by Zheyuan Yu
*/
bool SimpleExtract::is_sd(const char* token)
{
if (sd.look(token))
return true;
else
return false;
}
/**
* Function: is_others
* Usage: is_sud ("University")
* lookup dictionary to check whether a token is Other word, such University, POB ...
* Update: Jan 13, 2005 by Zheyuan Yu
*/
bool SimpleExtract::is_others(const char* token)
{
if (others.look(token))
return true;
else
return false;
}
SimpleDic SimpleExtract::usstates (59,"/home/workspace/geo/data/dictionary/USStates");
SimpleDic SimpleExtract::sud(59,"/home/workspace/geo/data/dictionary/SecondaryUnitDesignator");
SimpleDic SimpleExtract::ss(701,"/home/workspace/geo/data/dictionary/StreetSuffixes");
SimpleDic SimpleExtract::others(59,"/home/workspace/geo/data/dictionary/others");
SimpleDic SimpleExtract::sd(31,"/home/workspace/geo/data/dictionary/StreetDirections");
//SimpleDic SimpleExtract::usstates (59,"C:/Temp/extract/data/u");
//SimpleDic SimpleExtract::sud(59,"C:/Temp/extract/data/SecondaryUnitDesignator");
//SimpleDic SimpleExtract::ss(701,"C:/Temp/extract/data/StreetSuffixes");
| [
"[email protected]"
] | |
506eb8d6e8e315db83199471e1e13477439cc9b6 | 64058e1019497fbaf0f9cbfab9de4979d130416b | /c++/src/objmgr/seq_entry_edit_commands.cpp | e026763c1baedf1dd389472eb4aeebed50cc6740 | [
"MIT"
] | permissive | OpenHero/gblastn | 31e52f3a49e4d898719e9229434fe42cc3daf475 | 1f931d5910150f44e8ceab81599428027703c879 | refs/heads/master | 2022-10-26T04:21:35.123871 | 2022-10-20T02:41:06 | 2022-10-20T02:41:06 | 12,407,707 | 38 | 21 | null | 2020-12-08T07:14:32 | 2013-08-27T14:06:00 | C++ | UTF-8 | C++ | false | false | 5,133 | cpp | /* $Id: seq_entry_edit_commands.cpp 103491 2007-05-04 17:18:18Z kazimird $
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Author: Maxim Didenko
*
* File Description:
* Scope transaction
*
*/
#include <ncbi_pch.hpp>
#include <corelib/ncbiexpt.hpp>
#include <objmgr/impl/seq_entry_edit_commands.hpp>
#include <objmgr/impl/scope_impl.hpp>
BEGIN_NCBI_SCOPE
BEGIN_SCOPE(objects)
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
CSeq_entry_SelectNone_EditCommand::
CSeq_entry_SelectNone_EditCommand(const CSeq_entry_EditHandle& handle,
CScope_Impl& scope)
: m_Handle(handle), m_Scope(scope)
{
}
CSeq_entry_SelectNone_EditCommand::~CSeq_entry_SelectNone_EditCommand()
{
}
void CSeq_entry_SelectNone_EditCommand::Do(IScopeTransaction_Impl& tr)
{
if (m_Handle.IsSeq())
m_BioseqHandle = m_Handle.SetSeq();
else if(m_Handle.IsSet())
m_BioseqSetHandle = m_Handle.SetSet();
else
return;
tr.AddCommand(CRef<IEditCommand>(this));
IEditSaver* saver = GetEditSaver(m_Handle);
m_Scope.SelectNone(m_Handle);
if (saver) {
tr.AddEditSaver(saver);
if (m_BioseqHandle.IsRemoved())
saver->Detach(m_Handle, m_BioseqHandle, IEditSaver::eDo);
else if(m_BioseqSetHandle.IsRemoved())
saver->Detach(m_Handle, m_BioseqSetHandle, IEditSaver::eDo);
}
}
void CSeq_entry_SelectNone_EditCommand::Undo()
{
IEditSaver* saver = GetEditSaver(m_Handle);
CBioObjectId old_id(m_Handle.GetBioObjectId());
if (m_BioseqHandle.IsRemoved()) {
m_Scope.SelectSeq(m_Handle, m_BioseqHandle);
if (saver)
saver->Attach(old_id, m_Handle, m_BioseqHandle, IEditSaver::eUndo);
}
else if (m_BioseqSetHandle.IsRemoved()) {
m_Scope.SelectSet(m_Handle, m_BioseqSetHandle);
if (saver)
saver->Attach(old_id,m_Handle, m_BioseqSetHandle, IEditSaver::eUndo);
}
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
CSeq_entry_Remove_EditCommand::~CSeq_entry_Remove_EditCommand()
{
}
void CSeq_entry_Remove_EditCommand::Do(IScopeTransaction_Impl& tr)
{
_ASSERT(m_Handle.GetParentEntry()); // Does not handle TSE
m_ParentHandle = m_Handle.GetParentBioseq_set();
m_Index = m_ParentHandle.GetSeq_entry_Index(m_Handle);
if( m_Index < 0 )
return;
tr.AddCommand(CRef<IEditCommand>(this));
IEditSaver* saver = GetEditSaver(m_Handle);
m_Scope.RemoveEntry(m_Handle);
if (saver) {
tr.AddEditSaver(saver);
saver->Remove(m_ParentHandle, m_Handle, m_Index, IEditSaver::eDo);
}
}
void CSeq_entry_Remove_EditCommand::Undo()
{
m_Scope.AttachEntry(m_ParentHandle, m_Handle, m_Index);
IEditSaver* saver = GetEditSaver(m_Handle);
if (saver) {
saver->Attach(m_ParentHandle, m_Handle, m_Index, IEditSaver::eUndo);
}
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
CRemoveTSE_EditCommand::~CRemoveTSE_EditCommand()
{
}
void CRemoveTSE_EditCommand::Do(IScopeTransaction_Impl& tr)
{
_ASSERT(!m_Handle.GetParentEntry()); // Handles TSE only
CTSE_Handle tse = m_Handle.GetTSE_Handle();
// TODO entry.Reset();
IEditSaver* saver = GetEditSaver(m_Handle);
m_Scope.RemoveTopLevelSeqEntry(tse);
tr.AddCommand(CRef<IEditCommand>(this));
if (saver) {
tr.AddEditSaver(saver);
saver->RemoveTSE(tse, IEditSaver::eDo);
}
}
void CRemoveTSE_EditCommand::Undo()
{
_ASSERT(0);
NCBI_THROW(CException, eUnknown,
"CRemoveTSE_EditCommand::Undo() is not implemented yet");
}
END_SCOPE(objects)
END_NCBI_SCOPE
| [
"[email protected]"
] | |
3f3a5566d7364aa643b76694de913b10f3fb010f | 8c3bb5b0d68cae84ab6bb5df4ebd2a8260ead4a3 | /src/version.h | 9b2a5756c3673bd8f27395f716358bc61eb73e3a | [
"MIT"
] | permissive | tintcoin/tintcoin | cfd6d8bb9c97018b0ea47ea323e23642e9de7a9b | 818f7955c4da74e4399725ea664324f0f1fb21c9 | refs/heads/master | 2016-09-06T08:16:39.068180 | 2014-01-18T16:28:02 | 2014-01-18T16:28:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,665 | h | // Copyright (c) 2012 The Bitcoin developers
// Copyright (c) 2012 Litecoin Developers
// Copyright (c) 2013 TintCoin Developers
// Copyright (c) 2013 TintCoin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_VERSION_H
#define BITCOIN_VERSION_H
#include <string>
//
// client versioning
//
// These need to be macro's, as version.cpp's voodoo requires it
#define CLIENT_VERSION_MAJOR 1
#define CLIENT_VERSION_MINOR 5
#define CLIENT_VERSION_REVISION 0
#define CLIENT_VERSION_BUILD 0
static const int CLIENT_VERSION =
1000000 * CLIENT_VERSION_MAJOR
+ 10000 * CLIENT_VERSION_MINOR
+ 100 * CLIENT_VERSION_REVISION
+ 1 * CLIENT_VERSION_BUILD;
extern const std::string CLIENT_NAME;
extern const std::string CLIENT_BUILD;
extern const std::string CLIENT_DATE;
//
// network protocol versioning
//
static const int PROTOCOL_VERSION = 1050000;
// earlier versions not supported as of Feb 2012, and are disconnected
static const int MIN_PROTO_VERSION = 209;
// nTime field added to CAddress, starting with this version;
// if possible, avoid requesting addresses nodes older than this
static const int CADDR_TIME_VERSION = 31402;
// only request blocks from nodes outside this range of versions
static const int NOBLKS_VERSION_START = 32000;
static const int NOBLKS_VERSION_END = 32400;
// BIP 0031, pong message, is enabled for all versions AFTER this one
static const int BIP0031_VERSION = 60000;
#endif
| [
"[email protected]"
] | |
909ed1912776a26f4d9efddc7754086144398444 | a83934e9a9f2e7d413eb550d4e00353763b292d1 | /main/clock.ino | ac92b533d7ee9e5f8fa41ec6fd5a41b7d60e351d | [
"MIT"
] | permissive | mebusmein/laser.arduino | 685c7d3664cab72206626c79494a939766537a31 | c009ee0b761ac96bbe719bcecfe6e72d0cceaf1a | refs/heads/master | 2022-04-26T10:51:03.678842 | 2022-04-06T07:23:56 | 2022-04-06T07:23:56 | 141,550,254 | 0 | 1 | MIT | 2022-04-06T07:21:45 | 2018-07-19T08:42:49 | C++ | UTF-8 | C++ | false | false | 833 | ino | #include <Arduino.h>
/**
Clock functions
*/
void clockLoop()
{
elapsedTime = millis() - startTime;
if ((elapsedTime - lastSendTime) > PRINT_TIME_INTERVAL)
{
sendElapsedTimeToSerial();
}
updateDisplay();
}
// end of clockLoop
void sendElapsedTimeToSerial()
{
int seconds = (int) (elapsedTime / 1000L);
lastSendTime = elapsedTime;
Serial.print(seconds);
Serial.print(".");
fractional = (int) (elapsedTime % 1000L);
if (fractional == 0)
{
Serial.print("000");
}
else if (fractional < 10)
{
Serial.print("00");
}
else if (fractional < 100)
{
Serial.print("0");
}
Serial.println(fractional);
}
// end sendElapasedTimeToSerial
void updateDisplay()
{
int seconds = (int) (elapsedTime / 1000L);
int minutes = seconds / 60;
display.printTime(minutes, seconds % 60, true);
}
| [
"[email protected]"
] | |
1b98396d74d5ca5772258981eaaeba8d59312f0b | 66f382479a46b3c3f5fe614a52baa5ef52951cec | /DuiLib/3rd/CxImage/ximatif.h | a49474a7f04de9bf7a7f88198a19fb5f6a51e260 | [
"MIT"
] | permissive | fawdlstty/DuiLib_Faw | 80005af6b1e328818f66cdad47c06108c9ec2137 | f16f9913f027555640ec17eeb077c5be446681ae | refs/heads/master | 2023-08-22T22:51:58.377968 | 2023-05-03T13:13:51 | 2023-05-03T13:13:51 | 152,514,855 | 95 | 29 | NOASSERTION | 2023-08-06T15:09:06 | 2018-10-11T01:50:39 | C++ | UTF-8 | C++ | false | false | 2,136 | h | /*
* File: ximatif.h
* Purpose: TIFF Image Class Loader and Writer
*/
/* ==========================================================
* CxImageTIF (c) 07/Aug/2001 Davide Pizzolato - www.xdp.it
* For conditions of distribution and use, see copyright notice in ximage.h
*
* Special thanks to Troels Knakkergaard for new features, enhancements and bugfixes
*
* Special thanks to Abe <God(dot)bless(at)marihuana(dot)com> for MultiPageTIFF code.
*
* LibTIFF is:
* Copyright (c) 1988-1997 Sam Leffler
* Copyright (c) 1991-1997 Silicon Graphics, Inc.
* ==========================================================
*/
#if !defined(__ximatif_h)
#define __ximatif_h
#include "ximage.h"
#if CXIMAGE_SUPPORT_TIF
#include "../tiff/tiffio.h"
class DLL_EXP CxImageTIF: public CxImage
{
public:
CxImageTIF(): CxImage(CXIMAGE_FORMAT_TIF) {m_tif2=NULL; m_multipage=false; m_pages=0;}
~CxImageTIF();
TIFF* TIFFOpenEx(CxFile * hFile);
void TIFFCloseEx(TIFF* tif);
// bool Load(const TCHAR * imageFileName){ return CxImage::Load(imageFileName,CXIMAGE_FORMAT_TIF);}
// bool Save(const TCHAR * imageFileName){ return CxImage::Save(imageFileName,CXIMAGE_FORMAT_TIF);}
bool Decode(CxFile * hFile);
bool Decode(FILE *hFile) { CxIOFile file(hFile); return Decode(&file); }
#if CXIMAGE_SUPPORT_ENCODE
bool Encode(CxFile * hFile, bool bAppend=false);
bool Encode(CxFile * hFile, CxImage ** pImages, int32_t pagecount);
bool Encode(FILE *hFile, bool bAppend=false) { CxIOFile file(hFile); return Encode(&file,bAppend); }
bool Encode(FILE *hFile, CxImage ** pImages, int32_t pagecount)
{ CxIOFile file(hFile); return Encode(&file, pImages, pagecount); }
#endif // CXIMAGE_SUPPORT_ENCODE
protected:
void TileToStrip(uint8* out, uint8* in, uint32 rows, uint32 cols, int32_t outskew, int32_t inskew);
bool EncodeBody(TIFF *m_tif, bool multipage=false, int32_t page=0, int32_t pagecount=0);
TIFF *m_tif2;
bool m_multipage;
int32_t m_pages;
void MoveBits( uint8_t* dest, uint8_t* from, int32_t count, int32_t bpp );
void MoveBitsPal( uint8_t* dest, uint8_t*from, int32_t count, int32_t bpp, RGBQUAD* pal );
};
#endif
#endif
| [
"[email protected]"
] | |
8ea26da2e4a6a3238380b81e123f01de61b6ee32 | b10e97d29e1813c88bb3c84e1d9dfd610d4bb2ab | /ASSN2/ASSN2/src/Conv.h | 7c9b07d1f9893cf7968df3d3203d9af471eab7d3 | [] | no_license | shinychan95/CSED-232 | c1e693042ab37bccbfae511d748f341ac90c33f0 | 5049119ef74274c590e7e9313ecf466fcc8cceb4 | refs/heads/master | 2020-07-30T06:25:16.842950 | 2019-12-21T12:06:14 | 2019-12-21T12:06:14 | 210,116,775 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 717 | h | // 상속 시 발생하는 중첩 선언에 대한 오류를 해결하기 위해 사용한 부분
#ifndef BASEARRAY_H_GUARD // include guard
#define BASEARRAY_H_GUARD // include guard
#include <iostream>
#include <string>
#include <random>
using namespace std;
class Conv
{
private:
float** kernel;
int k_row;
int k_col;
public:
Conv(float**& kernel, int& k_row, int& k_col); // 선언과 동시에 kernel에 대한 데이터 저장
~Conv(); // destructor
virtual void implement(float**& input, int& i_row, int& i_col); // convolution 계산 후 시각화하는 함수
void _show(float**& matrix, int& row, int& col); // matrix 및 size를 입력받으면 출력하는 함수
};
#endif
| [
"[email protected]"
] | |
5645675ed84cb3c3460cffb835ed000b644a9d60 | 4d0abde037b0f663ef5547787c72d54b12f0bb2a | /amp-conformance/amp_test_lib/src/context.cpp | f6cc6a719a32b6e40324676be6e294723aaab1d1 | [
"LicenseRef-scancode-unknown-license-reference",
"NCSA"
] | permissive | LonghronShen/kalmar | 5275e051f62cd45830d57ee25642007a6fd624a4 | 0a1a49d60e50b70aa94c97ab3521c0dc7f72a7f2 | refs/heads/master | 2023-03-16T03:36:35.297060 | 2015-05-08T00:21:35 | 2015-05-08T00:21:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,711 | cpp | // Copyright (c) Microsoft
// All rights reserved
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
// See the Apache Version 2.0 License for specific language governing permissions and limitations under the License.
#include <amptest/context.h>
#include <amptest/logging.h>
#include <amptest/string_utils.h>
#include <sstream>
namespace Concurrency
{
namespace Test
{
int AMP_TEST_API __initialize_globals()
{
details::amptest_initialize_logging();
return 0;
}
amptest_context_t amptest_context; // The context
int __dummy_initialize_globals = __initialize_globals();
amptest_context_t::amptest_context_t() :
_cerr_logfile_override(nullptr),
_cout_logfile_override(nullptr),
_cerr_logfile_path(""),
_cout_logfile_path(""),
_using_env_cache(false),
_argc(0),
_argv(nullptr)
{
}
amptest_context_t::amptest_context_t(int argc, char** argv) :
_cerr_logfile_override(nullptr),
_cout_logfile_override(nullptr),
_cerr_logfile_path(),
_cout_logfile_path(),
_using_env_cache(false),
_argc(argc),
_argv(argv)
{
}
const std::string& amptest_context_t::get_stderr_logfile_path() const
{
return _cerr_logfile_path;
}
const std::string& amptest_context_t::get_stdout_logfile_path() const
{
return _cout_logfile_path;
}
void amptest_context_t::close_logfiles()
{
_cerr_logfile_path.clear();
_cout_logfile_path.clear();
_cerr_logfile_override.reset();
_cout_logfile_override.reset();
}
void amptest_context_t::set_stderr_logfile_path(const std::string& stderr_filename)
{
if (stderr_filename.empty())
{
throw amptest_exception("set_stderr_logfile_path() stderr_filename was an empty string");
}
if (_cerr_logfile_path != stderr_filename)
{
_cerr_logfile_path = stderr_filename;
// First determine if the new filestream already exists for stdout.
// If so, just copy it.
if (_cout_logfile_path == stderr_filename)
{
_cerr_logfile_override = _cout_logfile_override;
}
else
{
_cerr_logfile_override = std::make_shared<std::ofstream>(stderr_filename);
}
}
}
void amptest_context_t::set_stdout_logfile_path(const std::string& stdout_filename)
{
if (stdout_filename.empty())
{
throw amptest_exception("set_stdout_logfile_path() stdout_filename was an empty string");
}
if (_cout_logfile_path != stdout_filename)
{
_cout_logfile_path = stdout_filename;
// First determine if the new filestream already exists for stderr.
// If so, just copy it.
if (_cerr_logfile_path == stdout_filename)
{
_cout_logfile_override = _cerr_logfile_override;
}
else
{
_cout_logfile_override = std::make_shared<std::ofstream>(stdout_filename);
}
}
}
std::ostream& amptest_context_t::get_raw_stderr_stream() const
{
return (_cerr_logfile_override.get() == nullptr) ? std::cerr : *_cerr_logfile_override;
}
std::ostream& amptest_context_t::get_raw_stdout_stream() const
{
return (_cout_logfile_override.get() == nullptr) ? std::cout : *_cout_logfile_override;
}
void check_wgetenv_error_code(int error_code)
{
// 0 is success.
if (error_code == 0) { return; }
else if (error_code == EINVAL) { throw amptest_exception("wgetenv_s() returned EINVAL"); }
std::stringstream ss;
ss << "wgetenv_s() returned unexpected error (error code = " << error_code << ")";
throw amptest_exception(ss.str());
}
std::string amptest_context_t::get_environment_variable(const std::string& name) const {
std::string val_str;
if (!_using_env_cache)
{
#pragma warning(disable:4996)
char* env_value = getenv(name.c_str());
#pragma warning(default:4996)
if (env_value != nullptr)
{
val_str = env_value;
}
}
else
{
auto val = _env_cache.find(name);
if (val != _env_cache.end())
{
val_str = val->second;
}
}
return val_str;
}
bool amptest_context_t::get_environment_variable(const std::string& name, bool default_value) const {
std::string val_str = get_environment_variable(name);
if(val_str.empty()) {
return default_value;
} else if(val_str == "1" || val_str == "true" || val_str == "TRUE") {
return true;
} else if(val_str == "0" || val_str == "false" || val_str == "FALSE") {
return false;
}
// Unknown value, throw exception and exit
std::stringstream ss;
ss << "Environment variable " << name << " has invalid bool value '" << val_str << "'. Accepted values: 1,0,true,TRUE,false,FALSE.";
std::string errmsg = ss.str();
throw amptest_exception(errmsg.c_str());
}
bool amptest_context_t::is_buffer_aliasing_forced() const {
return get_environment_variable("CPPAMP_FORCE_ALIASED_SHADER", false);
}
int amptest_context_t::load_environment_variable_cache_from_file(const std::string& file_path)
{
int count = 0;
// Open file to import environment variables. Exceptions are not being enabled, since hitting EOF will also set/throw the failbit (below).
std::ifstream infile;
infile.open(file_path);
if (infile.fail() == 1)
{
Log(LogType::Error) << "environment variable cache file not found" << std::endl;
return count;
}
if (!_using_env_cache)
{
_using_env_cache = true;
}
else
{
throw amptest_exception("amptest_context_t::load_environment_variable_cache_from_file() cache already exists and does not support multiple loads");
}
while(infile.is_open() && !infile.eof())
{
std::string in;
std::getline(infile, in);
size_t index = in.find_first_of(L'=');
if (index != std::string::npos)
{
std::string key = in.substr(0, index);
std::string value;
// If '=' is not the last character, then do the substr() operation and trim whitespace.
if (in.size() > (index + 1) )
{
value = trim(in.substr(index+1));
}
// The last entry always wins...
auto it = _env_cache.find(key);
if (it != _env_cache.end())
{
if (!value.empty())
{
it->second = value;
}
else
{
// If value is empty, treat this as an "set <var>=", which removes the
// environment variable.
--count;
_env_cache.erase(it);
}
}
else if (!value.empty())
{
++count;
_env_cache.insert(std::make_pair(key, value));
}
}
}
return count;
}
bool amptest_context_t::using_environment_variable_cache() const
{
return _using_env_cache;
}
int amptest_context_t::dump_environment_variable_cache() const
{
if (!_using_env_cache)
{
Log() << "Environment Variable Cache is not being used" << std::endl;
return 0;
}
int count = 0;
Log() << "Environment Variable Cache: dumping entries" << std::endl;
std::for_each(_env_cache.begin(), _env_cache.end(), [&](std::pair<std::string, std::string> value)
{
Log() << " " << value.first << "=" << value.second <<std::endl;
++count;
});
return count;
}
void amptest_context_t::destroy_environment_variable_cache()
{
_using_env_cache = false;
_env_cache.clear();
}
}
}
| [
"[email protected]"
] | |
aaa5b016dbdf276cdc2113a239685d53259b8eca | 33612e281bc7e9d62df0f2a042850c331dff9c11 | /lab05/lab5.cpp | 478f229abe436d93bd5ec90c160dcac82d79da45 | [] | no_license | IgorBoyarshin/KPI_S5_ParallelProcessing | 5a13cf985896ff2768993ebb89a12c92dc6705de | f347ab8a099f957b2116fe71f962663ab80399be | refs/heads/master | 2021-08-09T00:09:22.149433 | 2017-11-11T16:57:40 | 2017-11-11T16:57:40 | 106,092,065 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,956 | cpp | // ------------------------------------------------------------------ //
// ----------------------------- Lab5 ------------------------------- //
// ------------------------------------------------------------------ //
/*
* Main Program(Lab5)
*
* Parallel and distributed Computing
* Lab work #3 "Threads in OpenMP library"
*
* Functions:
* F1: d = MAX(B + C) + MIN(A + B * (MA * ME))
* F2: MK = MA * (MA * MZ) + TRANS(MB)
* F3: T = MO * P + (MR * MS) * S
*
* Author: Igor Boyarshin, IO-52
* Date: 15.10.17
*/
#include <omp.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>
#include <iostream>
#include <memory> // smart pointers
#include "Data.h"
// ------------------------------------------------------------------ //
void thread1_func (const Data& data,
unsigned int N, unsigned int outputThreshold) {
// #pragma omp critical(data_input)
// {
int id = omp_get_thread_num();
std::cout << id << std::endl;
std::cout << ":> Starting Thread 1..." << std::endl;
const vector A = data.fillVectorOnes();
const vector B = data.fillVectorOnes();
const vector C = data.fillVectorOnes();
const matrix MA = data.fillMatrixOnes();
const matrix ME = data.fillMatrixOnes();
// }
const unsigned int d = data.func1(A, B, C, MA, ME);
if (N < outputThreshold) {
#pragma omp critical(data_output)
{
std::cout << std::endl;
std::cout << "Result of Func1: d = " << std::endl;
std::cout << d << std::endl;
std::cout << std::endl;
}
}
std::cout << ":> Finished Thread 1" << std::endl;
}
void thread2_func (const Data& data,
unsigned int N, unsigned int outputThreshold) {
// #pragma omp critical(data_input)
// {
int id = omp_get_thread_num();
std::cout << id << std::endl;
std::cout << ":> Starting Thread 2..." << std::endl;
const matrix MA = data.fillMatrixOnes();
const matrix MB = data.fillMatrixOnes();
const matrix MZ = data.fillMatrixOnes();
// }
const matrix& MK = data.func2(MA, MB, MZ);
if (N < outputThreshold) {
#pragma omp critical(data_output)
{
std::cout << std::endl;
std::cout << "Result of Func2: MK = " << std::endl;
data.outputMatrix(MK);
std::cout << std::endl;
}
}
std::cout << ":> Finished Thread 2" << std::endl;
}
void thread3_func (const Data& data,
unsigned int N, unsigned int outputThreshold) {
// #pragma omp critical(data_input)
// {
std::cout << ":> Starting Thread 3..." << std::endl;
const vector P = data.fillVectorOnes();
const vector S = data.fillVectorOnes();
const matrix MO = data.fillMatrixOnes();
const matrix MR = data.fillMatrixOnes();
const matrix MS = data.fillMatrixOnes();
// }
const vector& T = data.func3(P, S, MO, MR, MS);
if (N < outputThreshold) {
#pragma omp critical(data_output)
{
std::cout << std::endl;
std::cout << "Result of Func3: T = " << std::endl;
data.outputVector(T);
std::cout << std::endl;
}
}
std::cout << ":> Finished Thread 3" << std::endl;
}
// ------------------------------------------------------------------ //
int main() {
std::cout << ":> Main program started!" << std::endl;
unsigned int N;
std::cout << "Input N: ";
std::cin >> N;
const unsigned int OUTPUT_THRESHOLD = 7;
const Data data(N);
omp_set_num_threads(3);
#pragma omp parallel sections
{
#pragma omp section
thread1_func(data, N, OUTPUT_THRESHOLD);
#pragma omp section
thread2_func(data, N, OUTPUT_THRESHOLD);
#pragma omp section
thread3_func(data, N, OUTPUT_THRESHOLD);
}
return 0;
}
| [
"[email protected]"
] | |
ad1846249f754da19c6b64506922d6bb15929fcf | 20784eb8893aa86762cb25a10e7bfc6e2e890ee8 | /experimental/msc_test/cout_test_8.cpp | 358216717c34b3bfdfbcd2ae2a629edbdb6ef7be | [
"Apache-2.0"
] | permissive | nikolain/high-performance-string-float-random | dff0c45f56829ef012f0db680a54bc3586d47c19 | 899fb5b2b3eac85f989c500bfd525313951d1b87 | refs/heads/master | 2021-01-25T05:16:04.404451 | 2014-02-13T22:23:06 | 2014-02-13T22:23:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,677 | cpp | // Copyright 2014, ABN Software Inc (http://www.abnsoftware.com).
//
// 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.
//
// Warning:
//
// C++ is not a toy. Not suitable for children under three years old.
//
// Extreme crash hazard, please keep your head clear.
#include "stdafx.h"
#include <stdlib.h>
#include <windows.h>
#include <queue>
#define HAVE_SSE2
#include "..\stringencoders\src\modp_numtoa.h"
#include "..\SFMT-src-1.4.1\SFMT.h"
#include "..\SFMT-src-1.4.1\SFMT.c"
class WriteBuffer {
public:
WriteBuffer(size_t buffer_element_count, int max_float_digits)
: buffer_element_count_(buffer_element_count)
, buffer_byte_size_(buffer_element_count * (max_float_digits + 5))
{
ptr_ = new char[buffer_byte_size_];
memset(ptr_, 0, buffer_byte_size_);
useful_data_size_ = 0;
}
~WriteBuffer()
{
delete[] ptr_;
}
char* ptr_;
size_t useful_data_size_;
const size_t buffer_element_count_;
const size_t buffer_byte_size_;
};
CRITICAL_SECTION g_write_queue_cs;
HANDLE g_write_queue_has_more_data_event = NULL;
HANDLE g_write_queue_accepts_more_data_event = NULL;
const int kMaxQueue = 5;
std::queue<WriteBuffer*> g_write_queue;
bool g_done = false;
INT64 g_total_bytes_written = 0;
__int64 g_begin_ticks = 0;
__int64 g_end_ticks = 0;
DWORD WINAPI WriteThreadProc(LPVOID lpParameter)
{
HANDLE hFile = HANDLE(lpParameter);
do
{
WriteBuffer* write_buffer = NULL;
bool exit = false;
EnterCriticalSection(&g_write_queue_cs);
if (g_write_queue.size() > 0)
{
write_buffer = g_write_queue.front();
g_write_queue.pop();
g_total_bytes_written += write_buffer->useful_data_size_;
}
else if (g_done)
{
exit = true;
}
SetEvent(g_write_queue_accepts_more_data_event);
LeaveCriticalSection(&g_write_queue_cs);
if (write_buffer)
{
/* DWORD bytes_written = 0;
::WriteFile(hFile, write_buffer->ptr_, write_buffer->useful_data_size_,
&bytes_written, NULL);*/
delete write_buffer;
}
else if (exit) {
break;
} else {
// Wait for new(s).
WaitForSingleObject(g_write_queue_has_more_data_event, INFINITE);
}
} while (true);
return 1;
}
// Number to string lookup.
typedef char* char_ptr;
char_ptr* g_x = new char_ptr[1001];
DWORD WINAPI RandomThreadProc(LPVOID lpParameter)
{
const int buffer_element_count = 30000;
const int max_float_digits = 8;
sfmt_t sfmt;
sfmt_init_gen_rand(&sfmt, GetCurrentThreadId());
uint32_t* randoms = (uint32_t*) _aligned_malloc(sizeof(uint32_t)*buffer_element_count, 32);
short* dga = (short*) _aligned_malloc(sizeof(short)*(buffer_element_count + 32)*2, 32);
bool done = false;
// std::ofstream output();
while (!done)
{
// Prepare a block of numbers for writing.
WriteBuffer* write_buffer = new WriteBuffer(buffer_element_count, max_float_digits);
char* write_ptr = write_buffer->ptr_;
sfmt_fill_array32(&sfmt, randoms, buffer_element_count);
// Compute digits
for (int k = 0; k < buffer_element_count; ++k)
{
// Format each float to string and append to buffer.
// float random = float(rand()) / RAND_MAX;
// float random = float(randoms[k]) / 4294967296.0f;
// int fractional_part = random * 1000000000;
// this turns the fractional part of the float back into usable integer.
float f1 = randoms[k] / 4294967.296f;
short d1 = short(f1);
float f2 = (f1 - d1)*1000;
short d2 = short(f2 + 0.5);
dga[2*k] = d1;
dga[2*k+1] = d2;
}
// convert to string form.
for (int k = 0; k < 2*buffer_element_count; k+=2)
{
*(write_ptr) = '0';
*(write_ptr + 1) = '.';
//printf("%s\n", write_buffer->ptr_);
*((int*)(write_ptr + 2)) = *((int*)(g_x[dga[k]]));
//printf("%s\n", write_buffer->ptr_);
*((int*)(write_ptr + 5)) = *((int*)(g_x[dga[k + 1]]));
*(write_ptr + 8) = '\r';
*(write_ptr + 9) = '\n';
write_ptr+=10;
//printf("%s\n", write_buffer->ptr_);
}
// printf("%f => %d, %d => 0.%s%s\n", randoms[k]/4294967296.0f, d1, d2, x[d1], x[d2]);
//digits
// write_ptr += modp_dtoa(random, write_ptr, max_float_digits);
/* *(write_ptr++) = '1';
*(write_ptr++) = '1';
*(write_ptr++) = '1';
*(write_ptr++) = '1';
*(write_ptr++) = '1';
*(write_ptr++) = '1';
*(write_ptr++) = '1';
*(write_ptr++) = '1';
*(write_ptr++) = '1';
*/ //*(write_ptr++) = '\r';
//*(write_ptr++) = '\n';
//}
// Compute how many bytes to write.
write_buffer->useful_data_size_ = write_ptr - write_buffer->ptr_;
// Enqueue for writing.
while (write_buffer) {
EnterCriticalSection(&g_write_queue_cs);
if (g_write_queue.size() < kMaxQueue)
{
g_write_queue.push(write_buffer);
SetEvent(g_write_queue_has_more_data_event);
write_buffer = NULL;
} else
{
// ops.
}
done = g_done;
LeaveCriticalSection(&g_write_queue_cs);
if (write_buffer) {
// slow down writing, queue is full
// printf("S");
WaitForSingleObject(g_write_queue_accepts_more_data_event, 10);
}
}
}
_aligned_free(randoms);
_aligned_free(dga);
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
// Init critical section;
InitializeCriticalSection(&g_write_queue_cs);
g_write_queue_has_more_data_event = CreateEvent(NULL, FALSE, FALSE, NULL);
g_write_queue_accepts_more_data_event = CreateEvent(NULL, FALSE, TRUE, NULL);
for (int i = 0; i<1001; ++i)
{
g_x[i] = new char[8];
sprintf_s(g_x[i],8,"%03d", i);
}
g_x[1000] = "999";
HANDLE hFile = ::CreateFile(L"output.txt", GENERIC_WRITE, 0, 0, CREATE_ALWAYS, 0, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
printf("Oppps");
exit(-1);
}
// Launch a writer thread.
HANDLE hWriteThread = CreateThread(NULL, 0, &WriteThreadProc, hFile,0, 0);
HANDLE hRandomThread1 = CreateThread(NULL, 0, &RandomThreadProc, 0, 0, 0);
HANDLE hRandomThread2 = CreateThread(NULL, 0, &RandomThreadProc, 0, 0, 0);
HANDLE hRandomThread3 = CreateThread(NULL, 0, &RandomThreadProc, 0, 0, 0);
//HANDLE hRandomThread4 = CreateThread(NULL, 0, &RandomThreadProc, 0, 0, 0);
//HANDLE hRandomThread3 = CreateThread(NULL, 0, &RandomThreadProc, 0, 0, 0);
//HANDLE hRandomThread4 = CreateThread(NULL, 0, &RandomThreadProc, 0, 0, 0);
g_begin_ticks = GetTickCount64();
::Sleep(20000);
// Let the writing thread know we are done.
EnterCriticalSection(&g_write_queue_cs);
g_done = true;
LeaveCriticalSection(&g_write_queue_cs);
SetEvent(g_write_queue_has_more_data_event);
// Wait for writing thread to finish.
WaitForSingleObject(hRandomThread1, INFINITE);
WaitForSingleObject(hRandomThread2, INFINITE);
WaitForSingleObject(hRandomThread3, INFINITE);
// WaitForSingleObject(hRandomThread4, INFINITE);
WaitForSingleObject(hWriteThread, INFINITE);
g_end_ticks = GetTickCount64();
::CloseHandle(hFile);
__int64 delta = g_end_ticks - g_begin_ticks;
printf("Speed %f Mb per sec\n", (g_total_bytes_written * 1000.0) / (1024.0 * 1024 * delta));
char c;
scanf("%c", &c);
return 0;
}
| [
"[email protected]"
] | |
1cc243b19960f34f646de5a78bc6b09ed7a77224 | 533554cf603ef7694acf1603720753551990af92 | /dlk/python/dlk/templates/include/c2numpy.h | 22447ec03015ebbbbbbe957b43b755c8622bec33 | [
"Apache-2.0"
] | permissive | toohsk/blueoil | 6fde01f2337007c63fe0aafd26708aea66d9d03a | 596922caa939db9c5ecbac3286fbf6f703865ee6 | refs/heads/master | 2020-04-18T11:17:30.176200 | 2019-01-25T02:50:58 | 2019-01-25T02:50:58 | 167,495,119 | 0 | 0 | Apache-2.0 | 2019-01-25T06:14:03 | 2019-01-25T06:14:00 | null | UTF-8 | C++ | false | false | 18,509 | h | // Copyright 2016 Jim Pivarski
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef C2NUMPY
#define C2NUMPY
#include <inttypes.h>
#include <stdarg.h>
#include <string.h>
#include <sstream>
#include <string>
#include <vector>
const char* C2NUMPY_VERSION = "1.2";
// http://docs.scipy.org/doc/numpy/user/basics.types.html
typedef enum {
C2NUMPY_BOOL, // Boolean (True or False) stored as a byte
C2NUMPY_INT, // Default integer type (same as C long; normally either int64 or int32)
C2NUMPY_INTC, // Identical to C int (normally int32 or int64)
C2NUMPY_INTP, // Integer used for indexing (same as C ssize_t; normally either int32 or int64)
C2NUMPY_INT8, // Byte (-128 to 127)
C2NUMPY_INT16, // Integer (-32768 to 32767)
C2NUMPY_INT32, // Integer (-2147483648 to 2147483647)
C2NUMPY_INT64, // Integer (-9223372036854775808 to 9223372036854775807)
C2NUMPY_UINT8, // Unsigned integer (0 to 255)
C2NUMPY_UINT16, // Unsigned integer (0 to 65535)
C2NUMPY_UINT32, // Unsigned integer (0 to 4294967295)
C2NUMPY_UINT64, // Unsigned integer (0 to 18446744073709551615)
C2NUMPY_FLOAT, // Shorthand for float64.
C2NUMPY_FLOAT16, // Half precision float: sign bit, 5 bits exponent, 10 bits mantissa
C2NUMPY_FLOAT32, // Single precision float: sign bit, 8 bits exponent, 23 bits mantissa
C2NUMPY_FLOAT64, // Double precision float: sign bit, 11 bits exponent, 52 bits mantissa
C2NUMPY_COMPLEX, // Shorthand for complex128.
C2NUMPY_COMPLEX64, // Complex number, represented by two 32-bit floats (real and imaginary components)
C2NUMPY_COMPLEX128, // Complex number, represented by two 64-bit floats (real and imaginary components)
C2NUMPY_STRING = 100, // strings are C2NUMPY_STRING + their fixed size (up to 155)
C2NUMPY_END = 255 // ensure that c2numpy_type is at least a byte
} c2numpy_type;
// a Numpy writer object
typedef struct {
FILE *file; // output file handle
std::string outputFilePrefix; // output file name, not including the rotating number and .npy
int64_t sizeSeekPosition; // (internal) keep track of number of rows to modify before closing
int64_t sizeSeekSize; // (internal)
int32_t numColumns; // number of columns in the record array
std::vector<std::string> columnNames; // column names
std::vector<c2numpy_type> columnTypes; // column types
int32_t numRowsPerFile; // maximum number of rows per file
int32_t currentColumn; // current column number
int32_t currentRowInFile; // current row number in the current file
int32_t currentFileNumber; // current file number
} c2numpy_writer;
const char *c2numpy_descr(c2numpy_type type) {
// FIXME: all of the "<" signs should be system-dependent (they mean little endian)
static const char *c2numpy_bool = "|b1";
static const char *c2numpy_int = "<i8";
static const char *c2numpy_intc = "<i4"; // FIXME: should be system-dependent
static const char *c2numpy_intp = "<i8"; // FIXME: should be system-dependent
static const char *c2numpy_int8 = "|i1";
static const char *c2numpy_int16 = "<i2";
static const char *c2numpy_int32 = "<i4";
static const char *c2numpy_int64 = "<i8";
static const char *c2numpy_uint8 = "|u1";
static const char *c2numpy_uint16 = "<u2";
static const char *c2numpy_uint32 = "<u4";
static const char *c2numpy_uint64 = "<u8";
static const char *c2numpy_float = "<f8";
static const char *c2numpy_float16 = "<f2";
static const char *c2numpy_float32 = "<f4";
static const char *c2numpy_float64 = "<f8";
static const char *c2numpy_complex = "<c16";
static const char *c2numpy_complex64 = "<c8";
static const char *c2numpy_complex128 = "<c16";
static const char *c2numpy_str[155] = {"|S0", "|S1", "|S2", "|S3", "|S4", "|S5", "|S6", "|S7", "|S8", "|S9", "|S10", "|S11", "|S12", "|S13", "|S14", "|S15", "|S16", "|S17", "|S18", "|S19", "|S20", "|S21", "|S22", "|S23", "|S24", "|S25", "|S26", "|S27", "|S28", "|S29", "|S30", "|S31", "|S32", "|S33", "|S34", "|S35", "|S36", "|S37", "|S38", "|S39", "|S40", "|S41", "|S42", "|S43", "|S44", "|S45", "|S46", "|S47", "|S48", "|S49", "|S50", "|S51", "|S52", "|S53", "|S54", "|S55", "|S56", "|S57", "|S58", "|S59", "|S60", "|S61", "|S62", "|S63", "|S64", "|S65", "|S66", "|S67", "|S68", "|S69", "|S70", "|S71", "|S72", "|S73", "|S74", "|S75", "|S76", "|S77", "|S78", "|S79", "|S80", "|S81", "|S82", "|S83", "|S84", "|S85", "|S86", "|S87", "|S88", "|S89", "|S90", "|S91", "|S92", "|S93", "|S94", "|S95", "|S96", "|S97", "|S98", "|S99", "|S100", "|S101", "|S102", "|S103", "|S104", "|S105", "|S106", "|S107", "|S108", "|S109", "|S110", "|S111", "|S112", "|S113", "|S114", "|S115", "|S116", "|S117", "|S118", "|S119", "|S120", "|S121", "|S122", "|S123", "|S124", "|S125", "|S126", "|S127", "|S128", "|S129", "|S130", "|S131", "|S132", "|S133", "|S134", "|S135", "|S136", "|S137", "|S138", "|S139", "|S140", "|S141", "|S142", "|S143", "|S144", "|S145", "|S146", "|S147", "|S148", "|S149", "|S150", "|S151", "|S152", "|S153", "|S154"};
switch (type) {
case C2NUMPY_BOOL:
return c2numpy_bool;
case C2NUMPY_INT:
return c2numpy_int;
case C2NUMPY_INTC:
return c2numpy_intc;
case C2NUMPY_INTP:
return c2numpy_intp;
case C2NUMPY_INT8:
return c2numpy_int8;
case C2NUMPY_INT16:
return c2numpy_int16;
case C2NUMPY_INT32:
return c2numpy_int32;
case C2NUMPY_INT64:
return c2numpy_int64;
case C2NUMPY_UINT8:
return c2numpy_uint8;
case C2NUMPY_UINT16:
return c2numpy_uint16;
case C2NUMPY_UINT32:
return c2numpy_uint32;
case C2NUMPY_UINT64:
return c2numpy_uint64;
case C2NUMPY_FLOAT:
return c2numpy_float;
case C2NUMPY_FLOAT16:
return c2numpy_float16;
case C2NUMPY_FLOAT32:
return c2numpy_float32;
case C2NUMPY_FLOAT64:
return c2numpy_float64;
case C2NUMPY_COMPLEX:
return c2numpy_complex;
case C2NUMPY_COMPLEX64:
return c2numpy_complex64;
case C2NUMPY_COMPLEX128:
return c2numpy_complex128;
default:
if (0 < type - C2NUMPY_STRING && type - C2NUMPY_STRING < 155)
return c2numpy_str[type - C2NUMPY_STRING];
}
return NULL;
}
int c2numpy_init(c2numpy_writer *writer, const std::string outputFilePrefix, int32_t numRowsPerFile) {
writer->file = NULL;
writer->outputFilePrefix = outputFilePrefix;
writer->sizeSeekPosition = 0;
writer->sizeSeekSize = 0;
writer->numColumns = 0;
writer->numRowsPerFile = numRowsPerFile;
writer->currentColumn = 0;
writer->currentRowInFile = 0;
writer->currentFileNumber = 0;
return 0;
}
int c2numpy_addcolumn(c2numpy_writer *writer, const std::string name, c2numpy_type type) {
writer->numColumns += 1;
writer->columnNames.push_back(name);
writer->columnTypes.push_back(type);
return 0;
}
int c2numpy_open(c2numpy_writer *writer) {
std::stringstream fileNameStream;
fileNameStream << writer->outputFilePrefix;
fileNameStream << writer->currentFileNumber;
fileNameStream << ".npy";
std::string fileName = fileNameStream.str();
writer->file = fopen(fileName.c_str(), "wb");
std::stringstream headerStream;
headerStream << "{'descr': [";
int column;
for (column = 0; column < writer->numColumns; ++column) {
headerStream << "('" << writer->columnNames[column] << "', '" << c2numpy_descr(writer->columnTypes[column]) << "')";
if (column < writer->numColumns - 1)
headerStream << ", ";
}
headerStream << "], 'fortran_order': False, 'shape': (";
writer->sizeSeekPosition = headerStream.str().size();
headerStream << writer->numRowsPerFile;
writer->sizeSeekSize = headerStream.str().size() - writer->sizeSeekPosition;
headerStream << ",), }";
int headerSize = headerStream.str().size();
char version = 1;
if (headerSize > 65535) version = 2;
while ((6 + 2 + (version == 1 ? 2 : 4) + headerSize) % 16 != 0) {
headerSize += 1;
headerStream << " ";
if (headerSize > 65535) version = 2;
}
fwrite("\x93NUMPY", 1, 6, writer->file);
if (version == 1) {
fwrite("\x01\x00", 1, 2, writer->file);
fwrite(&headerSize, 1, 2, writer->file);
writer->sizeSeekPosition += 6 + 2 + 2;
}
else {
fwrite("\x02\x00", 1, 2, writer->file);
fwrite(&headerSize, 1, 4, writer->file);
writer->sizeSeekPosition += 6 + 2 + 4;
}
std::string header = headerStream.str();
fwrite(header.c_str(), 1, header.size(), writer->file);
return 0;
}
#define C2NUMPY_CHECK_ITEM { \
if (writer->file == NULL) { \
int status = c2numpy_open(writer); \
if (status != 0) \
return status; \
} \
}
#define C2NUMPY_INCREMENT_ITEM { \
if (writer->currentColumn == 0) { \
writer->currentRowInFile += 1; \
if (writer->currentRowInFile == writer->numRowsPerFile) { \
fclose(writer->file); \
writer->file = NULL; \
writer->currentRowInFile = 0; \
writer->currentFileNumber += 1; \
} \
} \
return 0; \
}
int c2numpy_bool(c2numpy_writer *writer, int8_t data) { // "bool" is just a byte
C2NUMPY_CHECK_ITEM
if (writer->columnTypes[writer->currentColumn] != C2NUMPY_BOOL) return -1;
fwrite(&data, sizeof(int8_t), 1, writer->file);
writer->currentColumn = (writer->currentColumn + 1) % writer->numColumns;
C2NUMPY_INCREMENT_ITEM
}
int c2numpy_int(c2numpy_writer *writer, int64_t data) { // Numpy's default int is 64-bit
C2NUMPY_CHECK_ITEM
if (writer->columnTypes[writer->currentColumn] != C2NUMPY_INT) return -1;
fwrite(&data, sizeof(int64_t), 1, writer->file);
writer->currentColumn = (writer->currentColumn + 1) % writer->numColumns;
C2NUMPY_INCREMENT_ITEM
}
int c2numpy_intc(c2numpy_writer *writer, int data) { // the built-in C int
C2NUMPY_CHECK_ITEM
if (writer->columnTypes[writer->currentColumn] != C2NUMPY_INTC) return -1;
fwrite(&data, sizeof(int), 1, writer->file);
writer->currentColumn = (writer->currentColumn + 1) % writer->numColumns;
C2NUMPY_INCREMENT_ITEM
}
int c2numpy_intp(c2numpy_writer *writer, size_t data) { // intp is Numpy's way of saying size_t
C2NUMPY_CHECK_ITEM
if (writer->columnTypes[writer->currentColumn] != C2NUMPY_INTP) return -1;
fwrite(&data, sizeof(size_t), 1, writer->file);
writer->currentColumn = (writer->currentColumn + 1) % writer->numColumns;
C2NUMPY_INCREMENT_ITEM
}
int c2numpy_int8(c2numpy_writer *writer, int8_t data) {
C2NUMPY_CHECK_ITEM
if (writer->columnTypes[writer->currentColumn] != C2NUMPY_INT8) return -1;
fwrite(&data, sizeof(int8_t), 1, writer->file);
writer->currentColumn = (writer->currentColumn + 1) % writer->numColumns;
C2NUMPY_INCREMENT_ITEM
}
int c2numpy_int16(c2numpy_writer *writer, int16_t data) {
C2NUMPY_CHECK_ITEM
if (writer->columnTypes[writer->currentColumn] != C2NUMPY_INT16) return -1;
fwrite(&data, sizeof(int16_t), 1, writer->file);
writer->currentColumn = (writer->currentColumn + 1) % writer->numColumns;
C2NUMPY_INCREMENT_ITEM
}
int c2numpy_int32(c2numpy_writer *writer, int32_t data) {
C2NUMPY_CHECK_ITEM
if (writer->columnTypes[writer->currentColumn] != C2NUMPY_INT32) return -1;
fwrite(&data, sizeof(int32_t), 1, writer->file);
writer->currentColumn = (writer->currentColumn + 1) % writer->numColumns;
C2NUMPY_INCREMENT_ITEM
}
int c2numpy_int64(c2numpy_writer *writer, int64_t data) {
C2NUMPY_CHECK_ITEM
if (writer->columnTypes[writer->currentColumn] != C2NUMPY_INT64) return -1;
fwrite(&data, sizeof(int64_t), 1, writer->file);
writer->currentColumn = (writer->currentColumn + 1) % writer->numColumns;
C2NUMPY_INCREMENT_ITEM
}
int c2numpy_uint8(c2numpy_writer *writer, uint8_t data) {
C2NUMPY_CHECK_ITEM
if (writer->columnTypes[writer->currentColumn] != C2NUMPY_UINT8) return -1;
fwrite(&data, sizeof(uint8_t), 1, writer->file);
writer->currentColumn = (writer->currentColumn + 1) % writer->numColumns;
C2NUMPY_INCREMENT_ITEM
}
int c2numpy_uint16(c2numpy_writer *writer, uint16_t data) {
C2NUMPY_CHECK_ITEM
if (writer->columnTypes[writer->currentColumn] != C2NUMPY_UINT16) return -1;
fwrite(&data, sizeof(uint16_t), 1, writer->file);
writer->currentColumn = (writer->currentColumn + 1) % writer->numColumns;
C2NUMPY_INCREMENT_ITEM
}
int c2numpy_uint32(c2numpy_writer *writer, uint32_t data) {
C2NUMPY_CHECK_ITEM
if (writer->columnTypes[writer->currentColumn] != C2NUMPY_UINT32) return -1;
fwrite(&data, sizeof(uint32_t), 1, writer->file);
writer->currentColumn = (writer->currentColumn + 1) % writer->numColumns;
C2NUMPY_INCREMENT_ITEM
}
int c2numpy_uint64(c2numpy_writer *writer, uint64_t data) {
C2NUMPY_CHECK_ITEM
if (writer->columnTypes[writer->currentColumn] != C2NUMPY_UINT64) return -1;
fwrite(&data, sizeof(uint64_t), 1, writer->file);
writer->currentColumn = (writer->currentColumn + 1) % writer->numColumns;
C2NUMPY_INCREMENT_ITEM
}
int c2numpy_float(c2numpy_writer *writer, double data) { // Numpy's "float" is a double
C2NUMPY_CHECK_ITEM
if (writer->columnTypes[writer->currentColumn] != C2NUMPY_FLOAT) return -1;
fwrite(&data, sizeof(double), 1, writer->file);
writer->currentColumn = (writer->currentColumn + 1) % writer->numColumns;
C2NUMPY_INCREMENT_ITEM
}
// int c2numpy_float16(c2numpy_writer *writer, ??? data) { // how to do float16 in C?
// C2NUMPY_CHECK_ITEM
// if (writer->columnTypes[writer->currentColumn] != C2NUMPY_FLOAT16) return -1;
// fwrite(&data, sizeof(???), 1, writer->file);
// writer->currentColumn = (writer->currentColumn + 1) % writer->numColumns;
// C2NUMPY_INCREMENT_ITEM
// }
int c2numpy_float32(c2numpy_writer *writer, float data) {
C2NUMPY_CHECK_ITEM
if (writer->columnTypes[writer->currentColumn] != C2NUMPY_FLOAT32) return -1;
fwrite(&data, sizeof(float), 1, writer->file);
writer->currentColumn = (writer->currentColumn + 1) % writer->numColumns;
C2NUMPY_INCREMENT_ITEM
}
int c2numpy_float64(c2numpy_writer *writer, double data) {
C2NUMPY_CHECK_ITEM
if (writer->columnTypes[writer->currentColumn] != C2NUMPY_FLOAT64) return -1;
fwrite(&data, sizeof(double), 1, writer->file);
writer->currentColumn = (writer->currentColumn + 1) % writer->numColumns;
C2NUMPY_INCREMENT_ITEM
}
// int c2numpy_complex(c2numpy_writer *writer, ??? data) { // how to do complex in C?
// C2NUMPY_CHECK_ITEM
// if (writer->columnTypes[writer->currentColumn] != C2NUMPY_COMPLEX) return -1;
// fwrite(&data, sizeof(???), 1, writer->file);
// writer->currentColumn = (writer->currentColumn + 1) % writer->numColumns;
// C2NUMPY_INCREMENT_ITEM
// }
// int c2numpy_complex64(c2numpy_writer *writer, ??? data) {
// C2NUMPY_CHECK_ITEM
// if (writer->columnTypes[writer->currentColumn] != C2NUMPY_COMPLEX64) return -1;
// fwrite(&data, sizeof(???), 1, writer->file);
// writer->currentColumn = (writer->currentColumn + 1) % writer->numColumns;
// C2NUMPY_INCREMENT_ITEM
// }
// int c2numpy_complex128(c2numpy_writer *writer, ??? data) {
// C2NUMPY_CHECK_ITEM
// if (writer->columnTypes[writer->currentColumn] != C2NUMPY_COMPLEX128) return -1;
// fwrite(&data, sizeof(???), 1, writer->file);
// writer->currentColumn = (writer->currentColumn + 1) % writer->numColumns;
// C2NUMPY_INCREMENT_ITEM
// }
int c2numpy_string(c2numpy_writer *writer, const char *data) {
C2NUMPY_CHECK_ITEM
int stringlength = writer->columnTypes[writer->currentColumn] - C2NUMPY_STRING;
if (0 < stringlength && stringlength < 155)
fwrite(data, 1, stringlength, writer->file);
else
return -1;
writer->currentColumn = (writer->currentColumn + 1) % writer->numColumns;
C2NUMPY_INCREMENT_ITEM
}
int c2numpy_close(c2numpy_writer *writer) {
if (writer->file != NULL) {
// we wrote fewer rows than we promised
if (writer->currentRowInFile < writer->numRowsPerFile) {
// so go back to the part of the header where that was written
fseek(writer->file, writer->sizeSeekPosition, SEEK_SET);
// overwrite it with spaces
int i;
for (i = 0; i < writer->sizeSeekSize; ++i)
fputc(' ', writer->file);
// now go back and write it again (it MUST be fewer or an equal number of digits)
fseek(writer->file, writer->sizeSeekPosition, SEEK_SET);
fprintf(writer->file, "%d", writer->currentRowInFile);
}
// now close it
fclose(writer->file);
}
return 0;
}
#endif // C2NUMPY
| [
"[email protected]"
] | |
44085c602487bd32a27f3b7b8020188cbef39582 | 7be62e9490ee69a3bb99ee10c630cf313b4a59b2 | /contrib/matrix/laspack_MmatrixM.h | 06dd63913a46f06489d6410d595e7a459116bfc1 | [] | no_license | FemusPlatform/femus | da6282857bafcbd1e8a225d580770af22561ab38 | cf368d58540d7b99fb492544208158fc23d36e16 | refs/heads/master | 2022-05-20T05:12:54.315613 | 2022-03-07T11:25:06 | 2022-03-07T11:25:06 | 159,841,346 | 7 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 9,139 | h | #ifndef __laspack_MmatrixM_h__
#define __laspack_MmatrixM_h__
#include "Solverlib_conf.h"
#ifdef HAVE_LASPACKM
#include "MGGraph.h"
#include "Typedefs_conf.h"
// C++ includes
#include <algorithm>
// Local includes
#include "dense_matrixM.h"
#include "sparse_MmatrixM.h"
#include <matrix.h>
// Forward declarations
class LaspackVectorM;
// template <typename T> class LaspackLinearSolver;
// ===========================================
// Generic laspack matrix. This class contains
// pure virtual members that must be overloaded
// in derived classes. Using a derived class
// allows for uniform access to laspack matrices
// from various different solver packages in
// different formats.
// ================================================
class LaspackMMatrixM : public SparseMMatrixM {
public:
/// The Laspack sparse matrix pointer.
Matrix _Mat;
int* _uncomp_row;
private:
bool _closed; /// Flag indicating if the matrix has been closed yet.
public:
// Constructor ---------------------------------------------------------
/// Constructor I; initialize the matrix before usage with \p init(...).
LaspackMMatrixM() : _closed(false){};
/// Constructor II.
LaspackMMatrixM(Matrix m);
void init(
const uint m, const uint n, const uint m_l, const uint n_l, /// Initialize a Petsc matrix
const unsigned int nnz = 0, const unsigned int noz = 0);
void init(); /// Initialize using sparsity structure
// Destructors ----------------------------
/// Destructor
~LaspackMMatrixM() { this->clear(); };
void clear(); /// Release all memory
// ==============================
// DATA RETURN
// ==============================
// matrix dimensions
unsigned int m() const; ///< row-dimension
unsigned int n() const; ///< column dimension
unsigned int row_start() const; ///< row-start
unsigned int row_stop() const; ///< row-stop
// flags
bool closed() const { return _closed; } ///< Return the closed flag value
bool need_full_sparsity_pattern() const { return true; } ///< Return the sparsity flag value
// values
int MatGetRowM(const unsigned int i_val, int* cols, double* vals){}; ///< Return the row values
Real operator()(const uint i, const uint j) const; ///< Return the value
// Setting -------------------------------------
// sparsity patter update
void update_sparsity_pattern(const Graph& sparsity_pattern); ///< Full sparsity update
void update_sparsity_pattern(
int m, int n, int m_l, int n_l, const uint ml_start, ///< Partial sparsity update
const std::vector<uint> n_oz, const std::vector<uint> n_nz){};
// values
void set(const unsigned int i, const unsigned int j, const Real value); ///< Set the value.
void add(const unsigned int i, const unsigned int j, const Real value); ///< add value
// zeroes
void zero_rows(std::vector<int>& rows, Real diag_value); ///< set a row to zero
void zero(); ///< set to zero
// add
/// Add the full matrix to the Laspack matrix.
void add_matrix(const DenseMatrixM& dm, const std::vector<uint>& rows, const std::vector<uint>& cols);
/// Add the full matrix to the Laspack matrix.
void add_matrix(const DenseMatrixM& dm, const std::vector<uint>& dof_indices);
/// Add a Sparse matrix
void add(const Real a, SparseMMatrixM& X);
// flags
void close() const {
const_cast<LaspackMMatrixM*>(this)->_closed = true;
;
} ///< close
// functions ------------------------------------
// norm
Real l1_norm() const; /// Return the l1-norm of the matrix
Real linfty_norm() const; /// Return the linfty-norm of the matrix
// print -----------------------------------------------------
void print_personal(std::ostream& os = std::cout) const {}; ///< print personal
void print_personal(const std::string name = "NULL") const {}; ///< print
void print_hdf5(const std::string name = "NULL") const {}; ///< print hdf5
friend std::ostream& operator<<(
std::ostream& os, const SparseMMatrixM& m); /// Same as the print method above
// function
/// Copies the diagonal part of the matrix
virtual void get_diagonal(NumericVectorM& dest) const;
/// Transpose Matrix.
virtual void get_transpose(SparseMMatrixM& dest) const;
/// Swaps the raw PETSc matrix context pointers.
void swap(LaspackMMatrixM&);
private:
/// This function returns the position in the compressed row. Very expensive
unsigned int pos(const uint i, const uint j) const;
/// Make other Laspack datatypes friends
friend class LaspackVectorM;
friend class LaspackLinearSolverM;
};
// ========================================
// LaspackMMatrixM class inline members
// ==========================================
inline void LaspackMMatrixM::clear() {
if (this->initialized()) M_Destr(&_Mat);
delete[] _uncomp_row;
_closed = false;
this->_is_initialized = false;
}
// ========================================
inline void LaspackMMatrixM::zero() {
for (unsigned int row = 0; row < this->m(); row++) {
const unsigned int len = M__GetLen(&_Mat, row + 1);
for (unsigned int l = 0; l < len; l++) M__SetEntry(&_Mat, row + 1, l, M__GetPos(&_Mat, row + 1, l), 0.);
}
return;
}
// ==============================================
inline unsigned int LaspackMMatrixM::m() const {
assert(this->initialized());
return static_cast<uint>(M_GetRowDim(const_cast<Matrix*>(&_Mat)));
}
// ========================================================
inline unsigned int LaspackMMatrixM::n() const {
assert(this->initialized());
return static_cast<unsigned int>(M_GetClmDim(const_cast<Matrix*>(&_Mat)));
}
// ========================================================
inline unsigned int LaspackMMatrixM::row_start() const { return 0; }
// =======================================================
inline unsigned int LaspackMMatrixM::row_stop() const { return this->m(); }
// ===================================================
inline void LaspackMMatrixM::set(const unsigned int i, const unsigned int j, const Real value) {
// very expensive
assert(this->initialized());
assert(i < this->m());
assert(j < this->n());
const unsigned int position = this->pos(i, j);
assert((j + 1) == M_GetPos(&_Mat, i + 1, position));
M_SetEntry(&_Mat, i + 1, position, j + 1, value);
}
// ================================================
inline void LaspackMMatrixM::add(const unsigned int i, const unsigned int j, const Real value) {
// very expensive
assert(this->initialized());
assert(i < this->m());
assert(j < this->n());
const unsigned int position = this->pos(i, j);
M_AddVal(&_Mat, i + 1, position, value);
}
// ===========================================
inline void LaspackMMatrixM::add_matrix(
const DenseMatrixM& dm, const std::vector<unsigned int>& dof_indices) {
this->add_matrix(dm, dof_indices, dof_indices);
}
// ===========================================
inline void LaspackMMatrixM::add_matrix(
const DenseMatrixM& dm, const std::vector<unsigned int>& rows, const std::vector<unsigned int>& cols)
{
assert(this->initialized());
assert(dm.m() == rows.size());
assert(dm.n() == cols.size());
for (unsigned int i = 0; i < rows.size(); i++) {
int irow = rows[i] + 1;
for (unsigned int k = 0; k < M__GetLen(&_Mat, irow); k++) _uncomp_row[M__GetPos(&_Mat, irow, k) - 1] = k;
for (unsigned int j = 0; j < cols.size(); j++) M__AddVal(&_Mat, irow, _uncomp_row[cols[j]], dm(i, j));
}
}
// ===========================================
inline void LaspackMMatrixM::add(const Real a_in, SparseMMatrixM& X_in) {
// the matrices must have the same structure
assert(this->initialized());
assert(this->m() == X_in.m());
assert(this->n() == X_in.n());
LaspackMMatrixM* X = static_cast<LaspackMMatrixM*>(&X_in);
assert(X != NULL);
_LPNumber a = static_cast<_LPNumber>(a_in);
// loops taken from LaspackMMatrixM::zero ()
const unsigned int n_rows = this->m();
for (unsigned int row = 0; row < n_rows; row++) {
const unsigned int len = M__GetLen(&_Mat, row + 1);
for (unsigned int l = 0; l < len; l++) {
const _LPNumber value = a * M__GetVal(const_cast<Matrix*>(&(X->_Mat)), row + 1, l);
M__AddVal(&_Mat, row + 1, l, value);
}
}
}
// ===========================================
inline Real LaspackMMatrixM::operator()(const uint i, const uint j) const {
// very expensive call
assert(this->initialized());
assert(i < this->m());
assert(j < this->n());
return M_GetEl(const_cast<Matrix*>(&_Mat), i + 1, j + 1);
}
// ===========================================
inline unsigned int LaspackMMatrixM::pos(const uint i, const uint j) const {
// very expensive call
assert(i < this->m());
assert(j < this->n());
const uint length = M__GetLen(&_Mat, i + 1);
for (uint k = 0; k < length; k++)
if (M__GetPos(&_Mat, i + 1, k) == j) return k;
std::cout << " LaspackMMatrixM::pos position not found \n";
abort();
return 0;
}
#endif // #ifdef LIBMESH_HAVE_LASPACK
#endif // #ifdef __laspack_matrix_h__
| [
"[email protected]"
] | |
8ba8cf3be68e349dd2da7e49d44440ffb08c7e56 | 9fe245c298b2b374fd706e1adc361e4451a03b2b | /CheezePizza/src/games/tetrisgame/tetrisblockl.cpp | 7ac1cdf5351281496adff87a23c8aac8c77e30b5 | [] | no_license | provokingastorm/FurryFace | c26e9344226bafeda2c7174dd7536d20f6ca4daf | 6a451bb830441174bc63616e43f85e8fae44f4fa | refs/heads/master | 2021-01-19T01:13:36.686258 | 2018-02-19T18:47:12 | 2018-02-19T18:47:12 | 33,712,673 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,106 | cpp | #include "tetrisblockl.h"
#include "tetrisblockproxy.h"
#include "block.h"
TetrisBlockL::TetrisBlockL( float TopLeftPositionX, float TopLeftPositionY )
{
// initializes all the x and y-coordinates
m_Blocks[0]->SetX( TopLeftPositionX );
m_Blocks[0]->SetY( TopLeftPositionY + 17 );
m_Blocks[1]->SetX( TopLeftPositionX );
m_Blocks[1]->SetY( TopLeftPositionY );
m_Blocks[2]->SetX( TopLeftPositionX - 17 );
m_Blocks[2]->SetY( TopLeftPositionY + 17 );
m_Blocks[3]->SetX( TopLeftPositionX - 34 );
m_Blocks[3]->SetY( TopLeftPositionY + 17 );
// initializes the line value
m_Blocks[0]->SetLine(18);
m_Blocks[1]->SetLine(19);
m_Blocks[2]->SetLine(18);
m_Blocks[3]->SetLine(18);
// initializes the line position
m_Blocks[0]->SetLinePosition(5);
m_Blocks[1]->SetLinePosition(5);
m_Blocks[2]->SetLinePosition(4);
m_Blocks[3]->SetLinePosition(3);
// sets the color of the blocks
for(int i = 0; i < TetrisBlockSize; i++)
{
m_Blocks[i]->SetColor(GREEN);
}
m_BlockType = BlockType_L;
}
TetrisBlockL::~TetrisBlockL()
{
}
int TetrisBlockL::GetBottomLine() const
{
int BottomLine = 0;
switch( m_Rotation % 4 )
{
case 0:
BottomLine = m_Blocks[3]->GetLine();
break;
case 1:
BottomLine = m_Blocks[0]->GetLine();
break;
case 2:
BottomLine = m_Blocks[0]->GetLine();
break;
case 3:
BottomLine = m_Blocks[1]->GetLine();
break;
default:
break;
}
return BottomLine;
}
void TetrisBlockL::SimulateRotation(int Rotation, TetrisBlockProxy& OutProxy)
{
switch( Rotation % 4 )
{
case 1:
{
OutProxy.Proxies[0].Position.X += 17;
OutProxy.Proxies[0].Position.Y += 17;
OutProxy.Proxies[0].Line -= 1;
const int BaseLine = OutProxy.Proxies[0].Line;
OutProxy.Proxies[1].Position.X += 17;
OutProxy.Proxies[1].Position.Y -= 17;
OutProxy.Proxies[1].Line = BaseLine + 1;
OutProxy.Proxies[2].Position.X += 17;
OutProxy.Proxies[2].Position.Y += 17;
OutProxy.Proxies[2].Line = BaseLine;
OutProxy.Proxies[3].Position.X -= 17;
OutProxy.Proxies[3].Position.Y -= 17;
OutProxy.Proxies[3].Line = BaseLine;
OutProxy.Proxies[0].LinePosition += 1;
const int BaseLinePosition = OutProxy.Proxies[0].LinePosition;
OutProxy.Proxies[1].LinePosition = BaseLinePosition;
OutProxy.Proxies[2].LinePosition = BaseLinePosition - 1;
OutProxy.Proxies[3].LinePosition = BaseLinePosition - 2;
break;
}
case 2:
{
const int BaseLine = OutProxy.Proxies[0].Line;
OutProxy.Proxies[2].Position.X += 34;
OutProxy.Proxies[2].Line = BaseLine;
OutProxy.Proxies[3].Position.X += 34;
OutProxy.Proxies[3].Position.Y -= 34;
OutProxy.Proxies[3].Line = BaseLine + 2;
const int BaseLinePosition = OutProxy.Proxies[0].LinePosition;
OutProxy.Proxies[2].LinePosition = BaseLinePosition + 1;
OutProxy.Proxies[3].LinePosition = BaseLinePosition;
break;
}
case 3:
{
const int BaseLine = OutProxy.Proxies[0].Line;
OutProxy.Proxies[1].Position.Y += 34;
OutProxy.Proxies[1].Line = BaseLine - 1;
OutProxy.Proxies[3].Position.X += 34;
OutProxy.Proxies[3].Position.Y += 34;
OutProxy.Proxies[3].Line = BaseLine;
OutProxy.Proxies[3].LinePosition += 2;
break;
}
case 0:
{
const int BaseLine = OutProxy.Proxies[0].Line;
OutProxy.Proxies[2].Position.X -= 34;
OutProxy.Proxies[2].Line = BaseLine;
OutProxy.Proxies[3].Position.X -= 34;
OutProxy.Proxies[3].Position.Y += 34;
OutProxy.Proxies[3].Line = BaseLine - 2;
const int BaseLinePosition = OutProxy.Proxies[0].LinePosition;
OutProxy.Proxies[2].LinePosition = BaseLinePosition - 1;
OutProxy.Proxies[3].LinePosition = BaseLinePosition;
break;
}
default:
break;
}
}
// EOF
| [
"[email protected]"
] | |
21426ab8eb0a2f703abcb34b00b252b2eae50245 | 60abe778e4d9005b1772a35313732cc7a93c14ee | /include/component/attribute/OUI_AttributeNames.h | 29cebb1f5dda37d8912d7b18d564b61168a0970b | [
"MIT"
] | permissive | nicole-mcg/OUI-engine | 57f933a127916c74f8bb9b5e9a73890c24947648 | 526ebf38831682111696f585727bd3e66d7228ff | refs/heads/master | 2022-04-12T07:29:30.955026 | 2020-03-14T21:50:55 | 2020-03-14T21:50:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,894 | h | #ifndef OUI_COMPONENT_ATTRIBUTE_NAMES_H
#define OUI_COMPONENT_ATTRIBUTE_NAMES_H
#include "OUI_Export.h"
namespace oui {
namespace AttributeNames {
// Component attributes
const static std::string VISIBLE = "visible";
const static std::string INTERACTABLE = "interactable";
const static std::string PERMANENT = "permanent";
const static std::string OPACITY = "opacity";
const static std::string BACKGROUND_COLOR = "bg-color";
const static std::string BACKGROUND_COLOR_1 = "bg-color1";
const static std::string BACKGROUND_COLOR_2 = "bg-color2";
const static std::string CURSOR = "cursor";
const static std::string BORDER_STYLE = "border-style";
const static std::string BORDER_WIDTH = "border-width";
const static std::string BORDER_COLOR = "border-color";
const static std::string CENTER_TEXT = "center-text";
const static std::string CENTERED_X = "centered-x";
const static std::string CENTERED_Y = "centered-y";
const static std::string CENTERED = "centered";
const static std::string X_PERCENT = "x-percent";
const static std::string Y_PERCENT = "y-percent";
const static std::string X_OFFSET = "x-offset";
const static std::string Y_OFFSET = "y-offset";
const static std::string Z_INDEX = "z";
const static std::string MIN_WIDTH = "min-width";
const static std::string MIN_HEIGHT = "min-height";
const static std::string WIDTH_PERCENT = "width-percent";
const static std::string HEIGHT_PERCENT = "height-percent";
const static std::string WIDTH_OFFSET = "width-offset";
const static std::string HEIGHT_OFFSET = "height-offset";
const static std::string NUM_OPTIONS = "num-options";
const static std::string RIGHT_CLICK_OPTIONS = "right-click-options";
const static std::string TEXT = "text";
const static std::string FONT = "font";
const static std::string FONT_FACE = "font-face";
const static std::string FONT_SIZE = "font-size";
const static std::string TEXT_COLOR = "text-color";
const static std::string AUTO_SIZE = "auto-size";
const static std::string HOVER_COLOR = "hover-color";
const static std::string PADDING = "padding";
const static std::string OPTION_HEIGHT = "option-height";
const static std::string OPTIONS = "options";
const static std::string SIZE = "size";
const static std::string LOCATION = "location";
const static std::string IMAGE = "image";
const static std::string CARAT_WIDTH = "carat-width";
const static std::string CARAT_COLOR = "carat-color";
const static std::string CARAT_H_OFFSET = "carat-h-offset";
const static std::string HIGHLIGHT_COLOR = "highlight-color";
}
}
#endif | [
"[email protected]"
] | |
f16938cb465ae7f8942ba917e7f127db5b01b78e | ceb378f286bf827bb8e0276aaf31658d16f87895 | /ros2/turtlebot2_demo/depthimage_to_pointcloud2/src/depthimage_to_pointcloud2_node.cpp | 47f109c993b676f34d8b3501e59ba6689cc20956 | [] | no_license | pantphot/turtlebot | 0d5505156b8ea0fb5ea00e0b3037d810dbe664b7 | 80d826a79ea03cc2e0987c13a1827b4d1e9b283d | refs/heads/master | 2020-05-10T00:06:48.216753 | 2019-05-03T12:20:38 | 2019-05-03T12:20:38 | 181,521,702 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,730 | cpp | // Copyright 2017 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <depthimage_to_pointcloud2/depth_conversions.hpp>
#include <image_geometry/pinhole_camera_model.h>
#include <rclcpp/rclcpp.hpp>
#include <rcutils/logging_macros.h>
#include <sensor_msgs/image_encodings.hpp>
#include <sensor_msgs/msg/camera_info.hpp>
#include <sensor_msgs/msg/image.hpp>
#include <sensor_msgs/msg/point_cloud2.hpp>
#include <sensor_msgs/point_cloud2_iterator.hpp>
#include <limits>
#include <memory>
#include <string>
#include <vector>
static rclcpp::Publisher<sensor_msgs::msg::PointCloud2>::SharedPtr g_pub_point_cloud;
static sensor_msgs::msg::CameraInfo::SharedPtr g_cam_info;
static void depthCb(const sensor_msgs::msg::Image::SharedPtr image)
{
// The meat of this function is a port of the code from:
// https://github.com/ros-perception/image_pipeline/blob/92d7f6b/depth_image_proc/src/nodelets/point_cloud_xyz.cpp
if (nullptr == g_cam_info) {
// we haven't gotten the camera info yet, so just drop until we do
RCUTILS_LOG_WARN("No camera info, skipping point cloud conversion")
return;
}
sensor_msgs::msg::PointCloud2::SharedPtr cloud_msg =
std::make_shared<sensor_msgs::msg::PointCloud2>();
cloud_msg->header = image->header;
cloud_msg->height = image->height;
cloud_msg->width = image->width;
cloud_msg->is_dense = false;
cloud_msg->is_bigendian = false;
cloud_msg->fields.clear();
cloud_msg->fields.reserve(1);
sensor_msgs::PointCloud2Modifier pcd_modifier(*cloud_msg);
pcd_modifier.setPointCloud2FieldsByString(1, "xyz");
// g_cam_info here is a sensor_msg::msg::CameraInfo::SharedPtr,
// which we get from the depth_camera_info topic.
image_geometry::PinholeCameraModel model;
model.fromCameraInfo(g_cam_info);
if (image->encoding == sensor_msgs::image_encodings::TYPE_16UC1) {
depthimage_to_pointcloud2::convert<uint16_t>(image, cloud_msg, model);
} else if (image->encoding == sensor_msgs::image_encodings::TYPE_32FC1) {
depthimage_to_pointcloud2::convert<float>(image, cloud_msg, model);
} else {
RCUTILS_LOG_WARN_THROTTLE(RCUTILS_STEADY_TIME, 5000,
"Depth image has unsupported encoding [%s]", image->encoding.c_str())
return;
}
g_pub_point_cloud->publish(cloud_msg);
}
static void infoCb(sensor_msgs::msg::CameraInfo::SharedPtr info)
{
g_cam_info = info;
}
int main(int argc, char ** argv)
{
rclcpp::init(argc, argv);
rclcpp::Node::SharedPtr node = rclcpp::Node::make_shared("depthimage_to_pointcloud2");
rmw_qos_profile_t custom_qos_profile = rmw_qos_profile_default;
custom_qos_profile.depth = 1;
custom_qos_profile.reliability = RMW_QOS_POLICY_RELIABILITY_BEST_EFFORT;
custom_qos_profile.history = RMW_QOS_POLICY_HISTORY_KEEP_LAST;
g_pub_point_cloud = node->create_publisher<sensor_msgs::msg::PointCloud2>(
"points2", custom_qos_profile);
auto image_sub = node->create_subscription<sensor_msgs::msg::Image>(
"depth", depthCb, custom_qos_profile);
auto cam_info_sub = node->create_subscription<sensor_msgs::msg::CameraInfo>(
"depth_camera_info", infoCb, custom_qos_profile);
rclcpp::spin(node);
rclcpp::shutdown();
return 0;
}
| [
"[email protected]"
] | |
cad2ec64c81c89244e0229e14dc04fd30f3e0369 | 04615e5a0f0c27e757d5e5114a67f6e8d5667f61 | /four/Main.cpp | c4b4474a9bf8878a315b1d9f9b771ba5aa4567bc | [] | no_license | itam94/IntermediateCplusplus | d895fd22c76a744061033c8fb8f083ee3b2f690c | 4125f4b351c854bece2dcb0321232952269f75c4 | refs/heads/master | 2020-04-07T21:51:59.961227 | 2018-11-22T22:04:21 | 2018-11-22T22:04:21 | 158,743,966 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 865 | cpp | #include <fstream>
#include<iostream>
#include <sstream>
using namespace std;
int main(int argc, char const *argv[])
{
/* code */
ifstream mainReadStream;
ofstream mainWriteStream;
int totalAmount;
string name;
string toAdd;
string lastAmount;
string line;
mainReadStream.open("/home/mateusz/VSC/c++c/four/donation_total.txt");
while(getline(mainReadStream,line)){
totalAmount = stoi(line);
}
mainReadStream.close();
stringstream userString;
cin >> name >>toAdd;
cout << toAdd;
totalAmount += stoi(toAdd);
mainWriteStream.open("/home/mateusz/VSC/c++c/four/donation_total.txt",ios_base::app);
mainWriteStream << endl << totalAmount;
mainWriteStream.close();
return 0;
}
| [
"[email protected]"
] | |
02a4e084535b67210c7661e4b183b382a618f4a6 | 000a7af455ed3f5f534b28b18be0b5997ddbdefa | /TClient/TChatTabButton.cpp | d025ad56c60a9ab08cb5f6c9d4e56ed739faf9f4 | [] | no_license | boyfromhell/4Ever | 6f58182c07182f9569201dbc0f9116cc6644d296 | 8bd1d638f9ae23c3b97a56bd04f00061f39fbe61 | refs/heads/master | 2020-04-15T14:21:14.071423 | 2018-07-22T17:07:17 | 2018-07-22T17:07:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,203 | cpp | #include "Stdafx.h"
#ifdef NEW_IF
// ===============================================================================
#define TAB_WINK_PERIOD 500
// ===============================================================================
const DWORD CTChatTabButton::FONT_COLOR_NORMAL = 0xFFB19D67;
const DWORD CTChatTabButton::FONT_COLOR_PUSH = 0xFFC1AD77;
const DWORD CTChatTabButton::FONT_COLOR_HOVER = 0xFFD1BD87;
// ===============================================================================
// ===============================================================================
CTChatTabButton::CTChatTabButton(CTChatFrame* pHost, LP_FRAMEDESC pDesc)
: TButton(pHost, pDesc), m_pHost(pHost), m_pList(NULL), m_iSlot(T_INVALID),
m_bSelect(FALSE), m_dwTotalTick(0), m_bNewMsg(FALSE), m_bHovering(FALSE),m_bHideBackground(FALSE)
{
m_style |= TBS_STATE_BUTTON;
ResetFontColor();
}
// ===============================================================================
// ===============================================================================
void CTChatTabButton::Init(INT iSlot, CTChatList* pList)
{
LinkWithList(pList);
SetSlot(iSlot);
m_dwTotalTick = 0;
m_bNewMsg = FALSE;
}
// -------------------------------------------------------------------------------
void CTChatTabButton::Update(DWORD dwTick)
{
m_dwTotalTick += dwTick;
if( IsVisible() && !m_bSelect && m_bNewMsg )
{
if( !m_bHovering )
{
INT tp = m_dwTotalTick % (TAB_WINK_PERIOD<<1);
if( tp < TAB_WINK_PERIOD )
m_bState |= TBUTTON_STATE_HOVER;
else
m_bState &= (~TBUTTON_STATE_HOVER);
ResetFontColor();
}
}
else
{
m_bNewMsg = FALSE;
}
}
// ===============================================================================
void CTChatTabButton::LinkWithList(CTChatList* pList)
{
m_pList = pList;
m_strText = pList->GetTitle();
}
// -------------------------------------------------------------------------------
void CTChatTabButton::SetSlot(INT iSlot)
{
m_iSlot = iSlot;
m_rc = m_pHost->GetTabSlotRect(iSlot);
}
// ===============================================================================
void CTChatTabButton::SetSelect(BOOL bSel)
{
if( m_bSelect == bSel )
return;
m_bSelect = bSel;
if( m_bSelect )
m_bState |= TBUTTON_STATE_DOWN;
else
{
m_bState &= (~TBUTTON_STATE_DOWN);
}
if( m_pList && IsVisible() )
m_pList->ShowComponent(m_bSelect);
m_bNewMsg = FALSE;
ResetFontColor();
}
// ===============================================================================
void CTChatTabButton::NotifyNewMsg()
{
m_bNewMsg = TRUE;
}
// ===============================================================================
// ===============================================================================
void CTChatTabButton::OnMouseMove(UINT nFlags, CPoint pt)
{
if(!CanProcess())
return;
if(!HitTest(pt))
{
m_bHovering = FALSE;
m_bState &= (~TBUTTON_STATE_HOVER);
if( !(m_style & TBS_STATE_BUTTON) )
m_bState &= (~TBUTTON_STATE_DOWN);
}
else if( !(m_bState & TBUTTON_STATE_DOWN) && !(m_bState & TBUTTON_STATE_HOVER) && m_pHover )
{
m_bHovering = TRUE;
m_bState |= TBUTTON_STATE_HOVER;
}
ResetFontColor();
}
// ===============================================================================
// ===============================================================================
void CTChatTabButton::ResetFontColor()
{
m_pFont->m_dwColor = FONT_COLOR_NORMAL;
}
// ===============================================================================
void CTChatTabButton::SetHideBackground(BOOL bHide)
{
ShowComponent(!bHide);
}
#else
// ===============================================================================
#define TAB_WINK_PERIOD 500
// ===============================================================================
const DWORD CTChatTabButton::FONT_COLOR_NORMAL = 0xFFB19D67;
const DWORD CTChatTabButton::FONT_COLOR_PUSH = 0xFFC1AD77;
const DWORD CTChatTabButton::FONT_COLOR_HOVER = 0xFFD1BD87;
// ===============================================================================
// ===============================================================================
CTChatTabButton::CTChatTabButton(CTChatFrame* pHost, LP_FRAMEDESC pDesc)
: TButton(pHost, pDesc), m_pHost(pHost), m_pList(NULL), m_iSlot(T_INVALID),
m_bSelect(FALSE), m_dwTotalTick(0), m_bNewMsg(FALSE), m_bHovering(FALSE)
{
m_style |= TBS_STATE_BUTTON;
ResetFontColor();
}
// ===============================================================================
// ===============================================================================
void CTChatTabButton::Init(INT iSlot, CTChatList* pList)
{
LinkWithList(pList);
SetSlot(iSlot);
m_dwTotalTick = 0;
m_bNewMsg = FALSE;
}
// -------------------------------------------------------------------------------
void CTChatTabButton::Update(DWORD dwTick)
{
m_dwTotalTick += dwTick;
if( IsVisible() && !m_bSelect && m_bNewMsg )
{
if( !m_bHovering )
{
INT tp = m_dwTotalTick % (TAB_WINK_PERIOD<<1);
if( tp < TAB_WINK_PERIOD )
m_bState |= TBUTTON_STATE_HOVER;
else
m_bState &= (~TBUTTON_STATE_HOVER);
ResetFontColor();
}
}
else
{
m_bNewMsg = FALSE;
}
}
// ===============================================================================
void CTChatTabButton::LinkWithList(CTChatList* pList)
{
m_pList = pList;
m_strText = pList->GetTitle();
}
// -------------------------------------------------------------------------------
void CTChatTabButton::SetSlot(INT iSlot)
{
m_iSlot = iSlot;
m_rc = m_pHost->GetTabSlotRect(iSlot);
}
// ===============================================================================
void CTChatTabButton::SetSelect(BOOL bSel)
{
if( m_bSelect == bSel )
return;
m_bSelect = bSel;
if( m_bSelect )
m_bState |= TBUTTON_STATE_DOWN;
else
{
m_bState &= (~TBUTTON_STATE_DOWN);
}
if( m_pList && IsVisible() )
m_pList->ShowComponent(m_bSelect);
m_bNewMsg = FALSE;
ResetFontColor();
}
// ===============================================================================
void CTChatTabButton::NotifyNewMsg()
{
m_bNewMsg = TRUE;
}
// ===============================================================================
// ===============================================================================
void CTChatTabButton::OnMouseMove(UINT nFlags, CPoint pt)
{
if(!CanProcess())
return;
if(!HitTest(pt))
{
m_bHovering = FALSE;
m_bState &= (~TBUTTON_STATE_HOVER);
if( !(m_style & TBS_STATE_BUTTON) )
m_bState &= (~TBUTTON_STATE_DOWN);
}
else if( !(m_bState & TBUTTON_STATE_DOWN) && !(m_bState & TBUTTON_STATE_HOVER) && m_pHover )
{
m_bHovering = TRUE;
m_bState |= TBUTTON_STATE_HOVER;
}
ResetFontColor();
}
// ===============================================================================
// ===============================================================================
void CTChatTabButton::ResetFontColor()
{
if( m_bState & TBUTTON_STATE_HOVER )
m_pFont->m_dwColor = FONT_COLOR_HOVER;
else if( m_bState & TBUTTON_STATE_DOWN )
m_pFont->m_dwColor = FONT_COLOR_PUSH;
else
m_pFont->m_dwColor = FONT_COLOR_NORMAL;
}
// ===============================================================================
#endif
| [
"[email protected]"
] | |
1f09313f90453e72b4e05f72e866b0d4f78e4a02 | 91c0029f9cfa8f2afb2306c8486c10e6cc74c382 | /Classes/WelcomeLayer.cpp | 710c729dae9db19e010892a1c396f9988b044cd1 | [] | no_license | fordream/AirPlane | 6f9e465edbf0642b1cba521e3b2773ffad7beb56 | b956b5af844643e2f84ccd139b4ba6bdd3eb88d1 | refs/heads/master | 2021-01-20T16:24:18.846749 | 2015-09-21T12:07:04 | 2015-09-21T12:07:04 | 44,259,114 | 1 | 0 | null | 2015-10-14T15:55:33 | 2015-10-14T15:55:33 | null | UTF-8 | C++ | false | false | 2,334 | cpp | #include "WelcomeLayer.h"
#include "GameScene.h"
#include "GameOverLayer.h"
USING_NS_CC;
WelcomeLayer::WelcomeLayer(){}
WelcomeLayer::~WelcomeLayer(){}
bool WelcomeLayer::init()
{
if (!Layer::init()){
return false;
}
SpriteFrameCache::getInstance()->addSpriteFramesWithFile("shoot_background.plist");
SpriteFrameCache::getInstance()->addSpriteFramesWithFile("shoot.plist");
auto visibleSize = Director::getInstance()->getVisibleSize();
auto background = Sprite::createWithSpriteFrameName("background.png");
background->setPosition(Point(visibleSize.width / 2, visibleSize.height / 2));
this->addChild(background);
auto loading = Sprite::createWithSpriteFrameName("game_loading1.png");
loading->setPosition(Point(visibleSize.width / 2, visibleSize.height / 2 - 40));
this->addChild(loading);
auto animation = Animation::create();
animation->setDelayPerUnit(0.2f);
animation->addSpriteFrame(SpriteFrameCache::getInstance()->getSpriteFrameByName("game_loading1.png"));
animation->addSpriteFrame(SpriteFrameCache::getInstance()->getSpriteFrameByName("game_loading2.png"));
animation->addSpriteFrame(SpriteFrameCache::getInstance()->getSpriteFrameByName("game_loading3.png"));
animation->addSpriteFrame(SpriteFrameCache::getInstance()->getSpriteFrameByName("game_loading4.png"));
auto animate = Animate::create(animation);
auto repeat = Repeat::create(animate, 2);
auto repeatdone = CallFuncN::create(CC_CALLBACK_1(WelcomeLayer::loadingDone, this));
auto sequence = Sequence::create(repeat, repeatdone, nullptr);
loading->runAction(sequence);
getHighestHistorySorce();
return true;
}
void WelcomeLayer::loadingDone(Node* pNode)
{
auto pScene = GameScene::create();
auto animateScene = TransitionMoveInB::create(0.5f, pScene);
Director::getInstance()->replaceScene(animateScene);
}
bool WelcomeLayer::isHaveSaveFile()
{
if (!UserDefault::getInstance()->getBoolForKey("isHaveSaveFileXml"))
{
UserDefault::getInstance()->setBoolForKey("isHaveSaveFileXml", true);
UserDefault::getInstance()->setIntegerForKey("HighestScore", 0);
UserDefault::getInstance()->flush();
return false;
}
else
{
return true;
}
}
void WelcomeLayer::getHighestHistorySorce()
{
if (isHaveSaveFile())
{
GameOverLayer::_highestHistoryScore = UserDefault::getInstance()->getIntegerForKey("HighestScore", 0);
}
} | [
"[email protected]"
] | |
c9686d4d710e6bd0999f6512e02186319aaa7190 | 27466e78d3cd1ed168d96fd4c2fb26add1ec7cc3 | /NVIS/NDYN/include/Physics/Physics/Spatial/ForceField/NEGravity.h | abfad906bed57e7a0260670fc01ab9bac90e1590 | [] | no_license | gpudev0517/Fire-Simulator | 37e1190d638a30c186ae1532975a56b23ffaac67 | 46581c19356e47a5c6fc8a9ee6f6478b96d02968 | refs/heads/master | 2023-04-26T02:54:53.458427 | 2021-05-14T10:16:10 | 2021-05-14T15:25:28 | 277,579,935 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 704 | h | #pragma once
#include "Physics/Spatial/NEForceField.h"
#include "Base/NENodeFactory.h"
class NEGravityPrivate;
class NECEXP_PHYSICS NEGravity : public NEForceField
{
Q_OBJECT
NE_CLASS("Gravity")
NE_PROP_3D_RW(vec3f, float, Gravity, "Gravitational Acceleration", "Acceleration caused by the gravity", true,)
public:
NEGravity(NENodeFactory* factory);
virtual ~NEGravity();
const vec3f& force(const vec3f* pos = 0, const vec3f* vel = 0) const;
protected:
NE_DERIVED(NESpatial, Protected)
private:
NE_DECL_PRIVATE(NEGravity)
};
class NEGravityFactory : public NENodeFactory
{
public:
NEGravityFactory(NEManager* m);
~NEGravityFactory();
NE_DERIVED(NENodeFactory, Public)
};
| [
"[email protected]"
] | |
9eb6240941bb68a2bb26d1ccdba9e3b7063d142c | cb80a8562d90eb969272a7ff2cf52c1fa7aeb084 | /inletTest2/0/T | 2411a84247b6ffe40518935f515bbc5073ff8791 | [] | no_license | mahoep/inletCFD | eb516145fad17408f018f51e32aa0604871eaa95 | 0df91e3fbfa60d5db9d52739e212ca6d3f0a28b2 | refs/heads/main | 2023-08-30T22:07:41.314690 | 2021-10-14T19:23:51 | 2021-10-14T19:23:51 | 314,657,843 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,292 | /*--------------------------------*- C++ -*----------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Version: 7
\\/ M anipulation |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
object T;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 0 0 1 0 0 0];
internalField uniform 290;
boundaryField
{
inlet
{
type totalTemperature;
T0 uniform 300;
value uniform 300;
gamma 1.4;
}
outlet
{
type inletOutlet;
inletValue uniform 300;
value uniform 300;
}
symmetryLine
{
type symmetryPlane;
}
walls
{
type zeroGradient;
}
defaultFaces
{
type empty;
}
}
// ************************************************************************* //
| [
"[email protected]"
] | ||
556e16268673bb0ec08f26c5c4aadda1d401b636 | 52767515c87f99525fdbe74a4b86e6b322bf38c0 | /Music_HPNY.cpp | 70355ee63e5786e0d6b98d75da8b7c46f5309e56 | [] | no_license | 6guojun/C_Datastructures_Algorithms | 3e73628c625b6f83ac94fe94823a00a8bb0fa952 | d123c8437ab806f9eb4eaac5a728c3ae33b3b881 | refs/heads/master | 2021-02-15T10:05:30.571195 | 2018-12-15T06:40:03 | 2018-12-15T06:40:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 849 | cpp | #include<windows.h>
#include<stdio.h>
#include<conio.h>
int main(int arg, char** args){
Sleep(1000);
system("color a1");
Sleep(300);
system("color b2");
Sleep(300);
system("color c3");
Sleep(300);
system("color d4");
Sleep(300);
system("color af");
Sleep(300);
system("color a0");
Sleep(300);
system("color f6");
Sleep(300);
system("color e5");
Sleep(300);
system("color a1");
Sleep(300);
system("color b2");
Sleep(300);
system("color c3");
Sleep(300);
system("color d4");
Sleep(300);
system("color e5");
Sleep(300);
system("color f6");
Sleep(300);
system("color a0");
Sleep(300);
system("color 30");
Sleep(300);
system("color a0");
Sleep(300);
system("color b0");
Sleep(300);
system("color d0");
Sleep(300);
system("color df");
Sleep(300);
printf("HAPPY NEW YEAR 2017!!!");
Sleep(1000);
system("cls");
}
| [
"[email protected]"
] | |
eb681e9b58b7cd67649d1834020157f3b01686b8 | 6aeccfb60568a360d2d143e0271f0def40747d73 | /sandbox/SOC/2007/signals/boost/dataflow/signals/component/filter_base.hpp | 6de86cd176a3ea983469098ecb98c12503224173 | [
"BSL-1.0"
] | permissive | ttyang/sandbox | 1066b324a13813cb1113beca75cdaf518e952276 | e1d6fde18ced644bb63e231829b2fe0664e51fac | refs/heads/trunk | 2021-01-19T17:17:47.452557 | 2013-06-07T14:19:55 | 2013-06-07T14:19:55 | 13,488,698 | 1 | 3 | null | 2023-03-20T11:52:19 | 2013-10-11T03:08:51 | C++ | UTF-8 | C++ | false | false | 4,550 | hpp | // Copyright Stjepan Rajko 2007. Use, modification and
// distribution is subject to 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)
#ifndef SIGNAL_NETWORK_FILTER_BASE_HPP
#define SIGNAL_NETWORK_FILTER_BASE_HPP
#include <boost/dataflow/signals/support.hpp>
#include <boost/dataflow/support/fusion_component.hpp>
#include <boost/dataflow/support/port/port_adapter.hpp>
#include <boost/signal.hpp>
#include <boost/mpl/vector.hpp>
namespace boost { namespace signals {
namespace detail {
template<typename Signals, typename InSignatures>
struct default_port_map
{
typedef
mpl::map<
mpl::pair<dataflow::default_port_selector
<dataflow::args::left, dataflow::signals::connect_mechanism>,
mpl::int_<0> >,
mpl::pair<dataflow::default_port_selector
<dataflow::args::right, dataflow::signals::connect_mechanism>,
mpl::int_<1> >
> type;
};
template<typename InSignatures>
struct default_port_map<void, InSignatures>
{
typedef
mpl::map<
mpl::pair<dataflow::default_port_selector
<dataflow::args::right, dataflow::signals::connect_mechanism>,
mpl::int_<0> >
> type;
};
}
template<typename T>
struct is_boost_signal
: public mpl::false_
{};
template<
typename Signature,
typename Combiner,
typename Group,
typename GroupCompare>
struct is_boost_signal<boost::signal<Signature, Combiner, Group, GroupCompare> >
: public mpl::true_
{};
template<typename T>
struct underlying_signal
{
typedef typename underlying_signal<typename T::signal_type>::type type;
};
template<
typename Signature,
typename Combiner,
typename Group,
typename GroupCompare>
struct underlying_signal<boost::signal<Signature, Combiner, Group, GroupCompare> >
{
typedef boost::signal<Signature, Combiner, Group, GroupCompare> type;
};
template<typename T, typename Enable=void>
struct get_underlying_signal
{
T &operator()(T &t) const
{
return t;
}
};
template<typename T>
struct get_underlying_signal<T, typename disable_if<is_boost_signal<T> >::type>
{
typename underlying_signal<T>::type & operator()(T &t) const
{
return get_underlying_signal<typename T::signal_type>()(t.default_signal());
}
};
/// ComponentTraits for a Dataflow.Signals filter.
/// \param[in] Filter Filter type (the class deriving filter)
/// \param[in] Signals A boost::signal type or void (will be: a fusion sequence of signals)
/// \param[in] InSignatures An mpl sequence of input signatures
template<typename Filter, typename Signals, typename InSignatures>
struct filter_component_traits
: public dataflow::fusion_component_traits<
fusion::vector<
typename underlying_signal<Signals>::type &,
dataflow::port_adapter<
Filter,
dataflow::signals::call_consumer<InSignatures>,
dataflow::signals::tag> >,
typename detail::default_port_map<Signals, InSignatures>::type,
dataflow::signals::tag>
{
template<typename Component>
static typename filter_component_traits::fusion_ports get_ports(Component &component)
{
return typename filter_component_traits::fusion_ports(
get_underlying_signal<Filter>()(component),
component);
};
};
template<typename Filter, typename InSignatures>
struct filter_component_traits<Filter, void, InSignatures>
: public dataflow::fusion_component_traits<
fusion::vector<
dataflow::port_adapter<
Filter,
dataflow::signals::call_consumer<InSignatures>,
dataflow::signals::tag> >,
typename detail::default_port_map<void, InSignatures>::type,
dataflow::signals::tag>
{
template<typename Component>
static typename filter_component_traits::fusion_ports get_ports(Component &component)
{
return typename filter_component_traits::fusion_ports(fusion::vector1<Component &>(component));
};
};
template<typename Filter, typename Signals, typename InSignatures = mpl::vector<> >
class filter_base : public dataflow::component<filter_component_traits<Filter, Signals, InSignatures> >
{
public:
typedef InSignatures in_signatures_type;
};
} }
#endif // SIGNAL_NETWORK_FILTER_BASE_HPP
| [
"[email protected]"
] | |
7c1f3936a4eadd5fddaa76586434031158eb9633 | a1a8b69b2a24fd86e4d260c8c5d4a039b7c06286 | /build/iOS/Release/include/Fuse.Layouts.ColumnLayout.h | 4f865881ac5d63cf76c0460d229b9518d4518537 | [] | no_license | epireve/hikr-tute | df0af11d1cfbdf6e874372b019d30ab0541c09b7 | 545501fba7044b4cc927baea2edec0674769e22c | refs/heads/master | 2021-09-02T13:54:05.359975 | 2018-01-03T01:21:31 | 2018-01-03T01:21:31 | 115,536,756 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,963 | h | // This file was generated based on /usr/local/share/uno/Packages/Fuse.Controls.Panels/1.4.2/Layouts/ColumnLayout.uno.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Fuse.Layouts.Layout.h>
namespace g{namespace Fuse{namespace Layouts{struct ColumnLayout;}}}
namespace g{namespace Fuse{struct LayoutParams;}}
namespace g{namespace Fuse{struct Visual;}}
namespace g{namespace Uno{struct Float2;}}
namespace g{namespace Uno{struct Float4;}}
namespace g{
namespace Fuse{
namespace Layouts{
// public sealed class ColumnLayout :28
// {
::g::Fuse::Layouts::Layout_type* ColumnLayout_typeof();
void ColumnLayout__Arrange_fn(ColumnLayout* __this, ::g::Fuse::Visual* container, ::g::Fuse::LayoutParams* lp, bool* doArrange, ::g::Uno::Float4* padding, ::g::Uno::Float2* __retval);
void ColumnLayout__ArrangePaddingBox_fn(ColumnLayout* __this, ::g::Fuse::Visual* container, ::g::Uno::Float4* padding, ::g::Fuse::LayoutParams* lp);
void ColumnLayout__get_ColumnCount_fn(ColumnLayout* __this, int* __retval);
void ColumnLayout__set_ColumnCount_fn(ColumnLayout* __this, int* value);
void ColumnLayout__get_ColumnSize_fn(ColumnLayout* __this, float* __retval);
void ColumnLayout__set_ColumnSize_fn(ColumnLayout* __this, float* value);
void ColumnLayout__get_ColumnSpacing_fn(ColumnLayout* __this, float* __retval);
void ColumnLayout__set_ColumnSpacing_fn(ColumnLayout* __this, float* value);
void ColumnLayout__GetContentSize_fn(ColumnLayout* __this, ::g::Fuse::Visual* container, ::g::Fuse::LayoutParams* lp, ::g::Uno::Float2* __retval);
void ColumnLayout__get_ItemSpacing_fn(ColumnLayout* __this, float* __retval);
void ColumnLayout__set_ItemSpacing_fn(ColumnLayout* __this, float* value);
void ColumnLayout__LeastAt_fn(ColumnLayout* __this, uArray* c, int* __retval);
void ColumnLayout__Max_fn(ColumnLayout* __this, uArray* c, float* __retval);
void ColumnLayout__get_Orientation_fn(ColumnLayout* __this, int* __retval);
void ColumnLayout__set_Orientation_fn(ColumnLayout* __this, int* value);
void ColumnLayout__get_Sizing_fn(ColumnLayout* __this, int* __retval);
void ColumnLayout__set_Sizing_fn(ColumnLayout* __this, int* value);
struct ColumnLayout : ::g::Fuse::Layouts::Layout
{
int _orientation;
bool _hasColumnCount;
int _columnCount;
bool _hasColumnSize;
float _columnSize;
float _columnSpacing;
float _itemSpacing;
int _sizing;
::g::Uno::Float2 Arrange(::g::Fuse::Visual* container, ::g::Fuse::LayoutParams lp, bool doArrange, ::g::Uno::Float4 padding);
int ColumnCount();
void ColumnCount(int value);
float ColumnSize();
void ColumnSize(float value);
float ColumnSpacing();
void ColumnSpacing(float value);
float ItemSpacing();
void ItemSpacing(float value);
int LeastAt(uArray* c);
float Max(uArray* c);
int Orientation();
void Orientation(int value);
int Sizing();
void Sizing(int value);
};
// }
}}} // ::g::Fuse::Layouts
| [
"[email protected]"
] | |
a93cd7e5baf96f8207d76a5127812a84bb4b6490 | 916ef1b31f0b683de4f043626d9df59f37edbbc4 | /atcoder/07_AtCoder-Grand-Contest/agc046/A/main.cpp | d11bf13db0c1741ece773b89805b113087312c13 | [] | no_license | solareenlo/cpp | 56cc33673d30dd4a4031e4b81cec16b08b3490e0 | f78f8a098849938153e6e3a282737e067dbe2c58 | refs/heads/master | 2021-03-31T04:31:39.420394 | 2020-11-29T22:22:25 | 2020-11-29T22:22:25 | 248,076,420 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 182 | cpp | #include <bits/stdc++.h>
using namespace std;
int main() {
cin.tie(0)->sync_with_stdio(false);
int x;
cin >> x;
cout << 360 / gcd(x, 360) << endl;
return 0;
}
| [
"[email protected]"
] | |
04c1246dcc1716ebc47e11bde96545137ced027f | b1040761ce5527824201742958328d9a8b6cf95b | /LeetCode/LC-69.cpp | 7f573ffbbfa1880857f4b98598a6ff7452a2e2d2 | [] | no_license | Ruhulcse/Problem-solving | 537011561ddfe2ceaeed7742c2829552d4f49977 | 4718b2d9b4eec56d2d1cc2a17214b040f1261105 | refs/heads/main | 2023-04-01T08:46:48.513058 | 2021-04-07T17:00:50 | 2021-04-07T17:00:50 | 305,057,079 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 430 | cpp | class Solution {
public:
int mySqrt(int x) {
long long left=0,right=x;
long long mid;
while(left<right){
mid=left+(right-left)/2;
if(mid*mid==x){
return mid;
}
else if(mid*mid>x){
right=mid-1;
}
else{
left=mid+1;
}
}
return left*left>x?left-1:left;
}
}; | [
"[email protected]"
] | |
b1dfa288cbc0dfe0e3c92838c50ec520c975b310 | c0dd78f7a0b303ebeb0f041320e632d9370edee0 | /launcher-widget.cpp | d3065bd60c4ac901a00cb9f8fff67f77cfe1e095 | [] | no_license | 289698/MazeGenerating2 | 03ec71203ec7673fb8a0f287c87383f8459ce6ff | c6fdc83199e9f8d032d4d1f673b1156a2268ec2f | refs/heads/master | 2020-03-23T01:04:09.374411 | 2018-11-05T22:40:25 | 2018-11-05T22:40:25 | 140,899,510 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,262 | cpp | #include "launcher-widget.h"
LauncherWidget::LauncherWidget (QWidget *parent) : QWidget (parent) {
this->setWindowFlags (Qt::FramelessWindowHint);
this->resize (200, 100);
QGridLayout *layout = new QGridLayout (this);
QPushButton *game = new QPushButton ("GAME", this);
game->setCursor (Qt::PointingHandCursor);
connect (game, SIGNAL(clicked ()), this, SLOT (newGame ()));
layout->addWidget (game, 0, 0);
QPushButton *quitb = new QPushButton ("QUIT", this);
quitb->setCursor (Qt::PointingHandCursor);
connect (quitb, SIGNAL (clicked ()), QApplication::instance (), SLOT (quit ()));
layout->addWidget (quitb, 1, 0);
this->setLayout (layout);
textures_ = new Textures ();
}
LauncherWidget::~LauncherWidget () {
if (textures_ != nullptr)
delete textures_;
}
void LauncherWidget::keyPressEvent (QKeyEvent *event) {
switch (event->key ()) {
case Qt::Key_1:
newGame ();
break;
case Qt::Key_Escape:
QApplication::instance ()->quit ();
}
}
void LauncherWidget::newGame () {
game_widget_ = new GameWidget (textures_);
connect (game_widget_, SIGNAL (closed ()), this, SLOT (QWidgetClosed ()));
game_widget_->show ();
this->hide ();
}
void LauncherWidget::QWidgetClosed () {
this->show ();
}
| [
"[email protected]"
] | |
8dd2aa83551e8878f3f1b63a88819107347c7f9a | 41517acc756eec850eead461263fce3520baa041 | /nvse/Hooks_Animation.cpp | 96176ef3a651f4317d8bffea7f4746ad01deebf6 | [] | no_license | lStewieAl/Geck-Extender | 10c45f1043ccb9575bee4d18a58be1c3c6688d55 | 693f3154964eb681f62c02ff5fc8c0bf2852a1bb | refs/heads/master | 2023-06-24T07:33:25.102898 | 2023-06-19T10:56:01 | 2023-06-19T10:56:01 | 183,600,605 | 27 | 9 | null | 2023-05-05T08:43:28 | 2019-04-26T09:32:16 | C++ | UTF-8 | C++ | false | false | 1,116 | cpp | #include "Hooks_Animation.h"
#include "SafeWrite.h"
#include <cstdarg>
#include "Utilities.h"
#include "GameForms.h"
#if RUNTIME
#if RUNTIME_VERSION == RUNTIME_VERSION_1_4_0_525
#define kHookGetGlobalModelPath 0x0104A1B8
static const UInt32 kOriginalGetGlobalModelPath = 0x00601C30;
#elif RUNTIME_VERSION == RUNTIME_VERSION_1_4_0_525ng
#define kHookGetGlobalModelPath 0x0104A1B8
static const UInt32 kOriginalGetGlobalModelPath = 0x00601BF0;
#else
#error
#endif
static bool __stdcall doAnimationHook(TESModel* model)
{
return (model && strrchr(model->nifPath.CStr(), '\\'));
}
static __declspec(naked) char* AnimationHook(void)
{
_asm {
pushad
push ecx
call doAnimationHook
test eax,eax
jz doCallOriginalGetGlobalModelPath
popad
mov eax, [ecx + 4]
retn
doCallOriginalGetGlobalModelPath:
popad
jmp kOriginalGetGlobalModelPath
}
}
void Hook_Animation_Init(void)
{
UInt32 enableAnimationHook = 0;
if(GetNVSEConfigOption_UInt32("Animation", "EnableAnimationHook", &enableAnimationHook) && enableAnimationHook)
{
SafeWrite32(kHookGetGlobalModelPath, (UInt32)AnimationHook);
}
}
#endif
| [
"[email protected]"
] | |
172de85cf5ba79934ac074441416a769516ccbe9 | 85e0f2f6b25a223d9eadd85a92550b6af3c6750e | /FireCube/Scripting/Bindings/ScriptingBindings.cpp | 061d30787a1dfe0eac491b5c604326227c788b66 | [
"MIT"
] | permissive | ashleygwinnell/firecube | 69cba6679615253d2bf895187e69bb202f605e05 | ea6bec6bab98d922dce76610a739beb5f7f88b61 | refs/heads/master | 2020-05-04T23:07:43.773207 | 2019-03-23T10:32:00 | 2019-03-23T10:32:00 | 179,533,589 | 2 | 0 | NOASSERTION | 2019-04-04T16:15:05 | 2019-04-04T16:15:05 | null | UTF-8 | C++ | false | false | 1,460 | cpp | #include "lua.hpp"
#include "sol.hpp"
#include "Scripting/LuaBindings.h"
#include "Scripting/LuaFile.h"
#include "Scripting/LuaScript.h"
using namespace FireCube;
void LuaBindings::InitScripting(sol::state &luaState)
{
luaState.new_usertype<LuaFile>("LuaFile",
sol::base_classes, sol::bases<Resource, Object, RefCounted>());
luaState.new_usertype<LuaScript>("LuaScript",
"SubscribeToEvent", &LuaScript::SubscribeToEventFromLua,
"CreateObject", sol::resolve<void(LuaFile *, const std::string &)>(&LuaScript::CreateObject),
"objectName", sol::property(&LuaScript::GetObjectName),
sol::base_classes, sol::bases<Component, Object, RefCounted>());
sol::table ScriptPropertyTypeTable = luaState.create_named_table("ScriptPropertyType");
ScriptPropertyTypeTable["STRING"] = static_cast<unsigned int>(ScriptPropertyType::STRING);
ScriptPropertyTypeTable["BOOL"] = static_cast<unsigned int>(ScriptPropertyType::BOOL);
ScriptPropertyTypeTable["FLOAT"] = static_cast<unsigned int>(ScriptPropertyType::FLOAT);
ScriptPropertyTypeTable["VEC2"] = static_cast<unsigned int>(ScriptPropertyType::VEC2);
ScriptPropertyTypeTable["VEC3"] = static_cast<unsigned int>(ScriptPropertyType::VEC3);
ScriptPropertyTypeTable["VEC4"] = static_cast<unsigned int>(ScriptPropertyType::VEC4);
ScriptPropertyTypeTable["RGB"] = static_cast<unsigned int>(ScriptPropertyType::RGB);
ScriptPropertyTypeTable["RGBA"] = static_cast<unsigned int>(ScriptPropertyType::RGBA);
}
| [
"[email protected]"
] | |
3677c6ce8f7514d492c0c024db24a7b7af161253 | c4b027a94e84870c4773e36d0b8227f3c9e1bf7f | /src/Plan/test/ByteCodeInterpreterTest.cpp | 88014ee7806f8ecc6a90180e7497d8a95cfe9a1a | [
"MIT"
] | permissive | nucflash/BitFunnel | 9f831fd3f01f6044b014bca749be164d3b31afbc | 42523cd6ce5ac99f8ab91c0a6383c3ecb50fdcd4 | refs/heads/master | 2020-05-23T08:06:54.498960 | 2016-10-05T20:59:55 | 2016-10-05T20:59:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,782 | cpp | // The MIT License (MIT)
// Copyright (c) 2016, Microsoft
// 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 <iomanip>
#include <iostream>
#include "gtest/gtest.h"
#include "Allocator.h"
#include "BitFunnel/Configuration/IFileSystem.h"
#include "BitFunnel/Configuration/Factories.h"
#include "BitFunnel/Index/Factories.h"
#include "BitFunnel/Index/IIngestor.h"
#include "BitFunnel/Index/IShard.h"
#include "BitFunnel/Index/ISimpleIndex.h"
#include "BitFunnel/Index/RowIdSequence.h"
#include "BitFunnel/Mocks/Factories.h"
#include "BitFunnel/Plan/IResultsProcessor.h"
#include "BitFunnel/Term.h"
#include "ByteCodeInterpreter.h"
#include "CompileNode.h"
#include "TextObjectParser.h"
namespace BitFunnel
{
class ResultsProcessor : public IResultsProcessor
{
public:
void AddResult(uint64_t accumulator,
size_t offset) override
{
std::cout
<< "AddResult("
<< std::hex << accumulator
<< ", " << offset
<< ")" << std::endl;
}
bool FinishIteration(void const * /*sliceBuffer*/) override
{
std::cout
<< "FinishIteration()" << std::endl;
return false;
}
bool TerminatedEarly() const override
{
std::cout
<< "TerminatedEarly()" << std::endl;
return false;
}
private:
};
size_t c_allocatorBufferSize = 1000000;
void GenerateCode(char const * rowPlanText,
ByteCodeGenerator& code)
{
std::stringstream rowPlan(rowPlanText);
Allocator allocator(c_allocatorBufferSize);
TextObjectParser parser(rowPlan, allocator, &CompileNode::GetType);
CompileNode const & node = CompileNode::Parse(parser);
node.Compile(code);
}
RowId GetFirstRow(ITermTable const & termTable,
Term term)
{
RowIdSequence rows(term, termTable);
auto it = rows.begin();
// TODO: Implement operator << for RowIdSequence::const_iterator.
//CHECK_NE(it, rows.end())
// << "Expected at least one row.";
RowId row = *it;
++it;
// TODO: Implement operator << for RowIdSequence::const_iterator.
//CHECK_EQ(it, rows.end())
// << "Expected no more than one row.";
return row;
}
ptrdiff_t GetRowOffset(char const * text,
Term::StreamId stream,
IConfiguration const & config,
ITermTable const & termTable,
IShard const & shard)
{
Term term(text, stream, config);
RowId row = GetFirstRow(termTable, term);
return shard.GetRowOffset(row);
}
void RunTest(ByteCodeGenerator const & code)
{
const DocId maxDocId = 800;
const Term::StreamId streamId = 0;
auto fileSystem = Factories::CreateRAMFileSystem();
auto index =
Factories::CreatePrimeFactorsIndex(*fileSystem,
maxDocId,
streamId);
const ShardId shardId = 0;
auto & shard = index->GetIngestor().GetShard(shardId);
std::vector<ptrdiff_t> rowOffsets;
rowOffsets.push_back(GetRowOffset(
"0",
streamId,
index->GetConfiguration(),
index->GetTermTable(),
shard));
rowOffsets.push_back(GetRowOffset(
"1",
streamId,
index->GetConfiguration(),
index->GetTermTable(),
shard));
rowOffsets.push_back(GetRowOffset(
"2",
streamId,
index->GetConfiguration(),
index->GetTermTable(),
shard));
Rank c_maxRank = 0;
auto & sliceBuffers = shard.GetSliceBuffers();
auto iterationsPerSlice = shard.GetSliceCapacity() / (64ull << c_maxRank);
ResultsProcessor resultsProcessor;
ByteCodeInterpreter interpreter(
code,
resultsProcessor,
sliceBuffers.size(),
reinterpret_cast<char* const *>(sliceBuffers.data()),
iterationsPerSlice,
rowOffsets.data());
interpreter.Run();
}
//class MockSlice
//{
//public:
// MockSlice(size_t sliceNumber,
// size_t quadwordsPerSlice,
// size_t rowCount);
// std::vector<ptrdiff_t>
// GetRowOffsets(std::vector<size_t> rowIndices) const;
//private:
// std::vector<std::vector<uint64_t>> m_rows;
//};
//MockSlice::MockSlice(size_t sliceNumber,
// size_t quadwordsPerSlice,
// size_t rowCount)
//{
//}
//class MockIndex
//{
//public:
// MockIndex(size_t sliceCount,
// size_t quadwordsPerSlice,
// size_t rowCount);
//private:
// std::vector<MockSlice> m_slices;
//};
//void RunTest2()
//{
// std::vector<uint64_t> rowOffsetsSlice1 =
//}
TEST(ByteCodeInterpreter, Placeholder)
{
char const * text =
"LoadRowJz {"
" Row: Row(0, 0, 0, false)," // Row(0) is 0, 1, 2, ...
" Child: AndRowJz {"
" Row: Row(2, 0, 0, false)," // Row(2) is AAAAAAA....
" Child: Report {"
" Child: "
" }"
" }"
"}";
ByteCodeGenerator code;
GenerateCode(text, code);
code.Seal();
RunTest(code);
}
}
| [
"[email protected]"
] | |
989ee5fe6fc0422109dd4d9c5581e2f8615786a5 | 641fa8341d8c436ad24945bcbf8e7d7d1dd7dbb2 | /components/sync/engine/attachments/fake_attachment_downloader.cc | 66f85fb7baadb19870e41fe9682fef76bf410976 | [
"BSD-3-Clause"
] | permissive | massnetwork/mass-browser | 7de0dfc541cbac00ffa7308541394bac1e945b76 | 67526da9358734698c067b7775be491423884339 | refs/heads/master | 2022-12-07T09:01:31.027715 | 2017-01-19T14:29:18 | 2017-01-19T14:29:18 | 73,799,690 | 4 | 4 | BSD-3-Clause | 2022-11-26T11:53:23 | 2016-11-15T09:49:29 | null | UTF-8 | C++ | false | false | 1,303 | 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.
#include "components/sync/engine/attachments/fake_attachment_downloader.h"
#include <memory>
#include "base/bind.h"
#include "base/location.h"
#include "base/memory/ptr_util.h"
#include "base/single_thread_task_runner.h"
#include "base/threading/thread_task_runner_handle.h"
#include "components/sync/engine/attachments/attachment_util.h"
namespace syncer {
FakeAttachmentDownloader::FakeAttachmentDownloader() {}
FakeAttachmentDownloader::~FakeAttachmentDownloader() {
DCHECK(CalledOnValidThread());
}
void FakeAttachmentDownloader::DownloadAttachment(
const AttachmentId& attachment_id,
const DownloadCallback& callback) {
DCHECK(CalledOnValidThread());
// This is happy fake downloader, it always successfully downloads empty
// attachment.
scoped_refptr<base::RefCountedMemory> data(new base::RefCountedBytes());
std::unique_ptr<Attachment> attachment = base::MakeUnique<Attachment>(
Attachment::CreateFromParts(attachment_id, data));
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::Bind(callback, DOWNLOAD_SUCCESS, base::Passed(&attachment)));
}
} // namespace syncer
| [
"[email protected]"
] | |
489fb27993d24ce65679fb2d71694043729444d3 | 88ae8695987ada722184307301e221e1ba3cc2fa | /chrome/browser/chromeos/app_mode/chrome_kiosk_app_installer.h | 670f054e3c6279e066ff2fe9be16870519e1801d | [
"BSD-3-Clause"
] | permissive | iridium-browser/iridium-browser | 71d9c5ff76e014e6900b825f67389ab0ccd01329 | 5ee297f53dc7f8e70183031cff62f37b0f19d25f | refs/heads/master | 2023-08-03T16:44:16.844552 | 2023-07-20T15:17:00 | 2023-07-23T16:09:30 | 220,016,632 | 341 | 40 | BSD-3-Clause | 2021-08-13T13:54:45 | 2019-11-06T14:32:31 | null | UTF-8 | C++ | false | false | 3,864 | h | // Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_CHROMEOS_APP_MODE_CHROME_KIOSK_APP_INSTALLER_H_
#define CHROME_BROWSER_CHROMEOS_APP_MODE_CHROME_KIOSK_APP_INSTALLER_H_
#include <string>
#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "base/scoped_observation.h"
#include "base/time/time.h"
#include "chrome/browser/chromeos/app_mode/startup_app_launcher_update_checker.h"
#include "chrome/browser/extensions/forced_extensions/install_stage_tracker.h"
#include "chrome/browser/extensions/install_observer.h"
#include "chrome/browser/extensions/install_tracker.h"
#include "chromeos/crosapi/mojom/chrome_app_kiosk_service.mojom.h"
class Profile;
namespace ash {
class ChromeKioskAppInstaller
: private extensions::InstallObserver,
public extensions::InstallStageTracker::Observer {
public:
using InstallResult = crosapi::mojom::ChromeKioskInstallResult;
using AppInstallParams = crosapi::mojom::AppInstallParams;
using InstallCallback =
crosapi::mojom::ChromeKioskLaunchController::InstallKioskAppCallback;
ChromeKioskAppInstaller(Profile* profile,
const AppInstallParams& install_data);
ChromeKioskAppInstaller(const ChromeKioskAppInstaller&) = delete;
ChromeKioskAppInstaller& operator=(const ChromeKioskAppInstaller&) = delete;
~ChromeKioskAppInstaller() override;
void BeginInstall(InstallCallback callback);
private:
void MaybeInstallSecondaryApps();
void MaybeCheckExtensionUpdate();
void OnExtensionUpdateCheckFinished(bool update_found);
void FinalizeAppInstall();
// extensions::InstallObserver overrides.
void OnFinishCrxInstall(content::BrowserContext* context,
const std::string& extension_id,
bool success) override;
// extensions::InstallStageTracker::Observer overrides.
void OnExtensionInstallationFailed(
const extensions::ExtensionId& id,
extensions::InstallStageTracker::FailureReason reason) override;
void ReportInstallSuccess();
void ReportInstallFailure(InstallResult result);
void ObserveActiveInstallations();
const extensions::Extension* GetPrimaryAppExtension() const;
// Returns true if all secondary apps have been installed.
bool AreSecondaryAppsInstalled() const;
// Returns true if the app with id |id| is pending an install.
bool IsAppInstallPending(const std::string& id) const;
// Returns true if any secondary app is pending.
bool IsAnySecondaryAppPending() const;
// Returns true if the primary app has a pending update.
bool PrimaryAppHasPendingUpdate() const;
// Returns true if the app with |id| failed, and it is the primary or one of
// the secondary apps.
bool DidPrimaryOrSecondaryAppFailedToInstall(bool success,
const std::string& id) const;
const raw_ptr<Profile> profile_;
AppInstallParams primary_app_install_data_;
InstallCallback on_ready_callback_;
bool install_complete_ = false;
bool secondary_apps_installing_ = false;
base::Time extension_update_start_time_;
// Used to run extension update checks for primary app's imports and
// secondary extensions.
std::unique_ptr<StartupAppLauncherUpdateChecker> update_checker_;
base::ScopedObservation<extensions::InstallTracker,
extensions::InstallObserver>
install_observation_{this};
base::ScopedObservation<extensions::InstallStageTracker,
extensions::InstallStageTracker::Observer>
install_stage_observation_{this};
base::WeakPtrFactory<ChromeKioskAppInstaller> weak_ptr_factory_{this};
};
} // namespace ash
#endif // CHROME_BROWSER_CHROMEOS_APP_MODE_CHROME_KIOSK_APP_INSTALLER_H_
| [
"[email protected]"
] | |
c0cdb9399be008bbb71c6ab2b7501bd0ddea1f8d | 5d83739af703fb400857cecc69aadaf02e07f8d1 | /Archive2/e5/5dbe1601508519/main.cpp | aa4c2256bc27e3491c297cb31374a1410d843151 | [] | no_license | WhiZTiM/coliru | 3a6c4c0bdac566d1aa1c21818118ba70479b0f40 | 2c72c048846c082f943e6c7f9fa8d94aee76979f | refs/heads/master | 2021-01-01T05:10:33.812560 | 2015-08-24T19:09:22 | 2015-08-24T19:09:22 | 56,789,706 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 977 | cpp | #include <boost/geometry.hpp>
#include <boost/geometry/geometries/box.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/index/predicates.hpp>
#include <boost/geometry/index/rtree.hpp>
#include <boost/geometry/io/io.hpp>
namespace bg = boost::geometry;
namespace bgi = boost::geometry::index;
using point = bg::model::d2::point_xy<int>;
using box = bg::model::box<point>;
static auto boxof = [] (point p) { return box { p, p }; };
int main() {
using Value = std::pair<box, int>;
using Tree = bgi::rtree<Value, bgi::rstar<32> >;
Tree idx;
std::vector<point> const points { point {1,10}, point {2,5}, point {5,8}, point {1,2}, point {8,10}, };
for (size_t i = 0; i < points.size(); ++i)
idx.insert(Value { boxof(points[i]), i });
for (auto& entry : boost::make_iterator_range(bgi::qbegin(idx, bgi::nearest(point{0,0}, 100)), bgi::qend(idx)))
std::cout << bg::dsv(points[entry.second]) << " ";
}
| [
"francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df"
] | francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df |
fac6ac30de4f683041dc2ce914b98fcd4220982d | 303e592c312459bf9eb3ce231b1357c4de91124b | /aoj/0087/0087.cpp | 66a31097436cebe021ac4f4bb287397a1183211d | [] | no_license | kohyatoh/contests | 866c60a1687f8a59d440da3356c6117f9596e8ce | b3dffeaf15564d57aec5c306f5f84bd448bc791f | refs/heads/master | 2021-01-17T15:06:23.216232 | 2016-07-18T14:06:05 | 2016-07-18T14:06:05 | 2,369,261 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 863 | cpp | #include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <sstream>
#include <vector>
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
using namespace std;
int main() {
string s;
while (getline(cin, s)) {
istringstream sin(s);
vector<double> v;
string w;
while (sin >> w) {
if (w.size() > 1 || isdigit(w[0])) v.push_back(atof(w.c_str()));
else {
const double a = v[v.size()-2];
const double b = v[v.size()-1];
v.pop_back();
v.pop_back();
if (w[0] == '+') v.push_back(a+b);
if (w[0] == '-') v.push_back(a-b);
if (w[0] == '*') v.push_back(a*b);
if (w[0] == '/') v.push_back(a/b);
}
}
printf("%.6f\n", v[0]);
}
return 0;
}
| [
"[email protected]"
] | |
239a57483d69380039046c06d6108d148ab5828f | ea6d9a14bb7a45ec6aa13a63caae184fa81d2da2 | /tools/clang/lib/CodeGen/CodeGenFunction.h | 34fc8b9b353479e85a31da0b65bd1ea550ab25ad | [
"NCSA"
] | permissive | xingjinglu/ParaFinder | 525d37c8948ad6ab305d67201251650fa8634b99 | 0bb4f44280b2a74035bf0df1015597cafb7b3149 | refs/heads/master | 2021-09-03T03:56:42.351027 | 2018-01-05T10:50:33 | 2018-01-05T10:50:33 | 105,554,349 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 113,928 | h | //===-- CodeGenFunction.h - Per-Function state for LLVM CodeGen -*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This is the internal per-function state used for llvm translation.
//
//===----------------------------------------------------------------------===//
#ifndef CLANG_CODEGEN_CODEGENFUNCTION_H
#define CLANG_CODEGEN_CODEGENFUNCTION_H
#include "clang/AST/Type.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/ExprObjC.h"
#include "clang/AST/CharUnits.h"
#include "clang/Frontend/CodeGenOptions.h"
#include "clang/Basic/ABI.h"
#include "clang/Basic/TargetInfo.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/ValueHandle.h"
#include "llvm/Support/Debug.h"
#include "CodeGenModule.h"
#include "CGBuilder.h"
#include "CGDebugInfo.h"
#include "CGValue.h"
namespace llvm {
class BasicBlock;
class LLVMContext;
class MDNode;
class Module;
class SwitchInst;
class Twine;
class Value;
class CallSite;
}
namespace clang {
class ASTContext;
class BlockDecl;
class CXXDestructorDecl;
class CXXForRangeStmt;
class CXXTryStmt;
class Decl;
class LabelDecl;
class EnumConstantDecl;
class FunctionDecl;
class FunctionProtoType;
class LabelStmt;
class ObjCContainerDecl;
class ObjCInterfaceDecl;
class ObjCIvarDecl;
class ObjCMethodDecl;
class ObjCImplementationDecl;
class ObjCPropertyImplDecl;
class TargetInfo;
class TargetCodeGenInfo;
class VarDecl;
class ObjCForCollectionStmt;
class ObjCAtTryStmt;
class ObjCAtThrowStmt;
class ObjCAtSynchronizedStmt;
class ObjCAutoreleasePoolStmt;
namespace CodeGen {
class CodeGenTypes;
class CGFunctionInfo;
class CGRecordLayout;
class CGBlockInfo;
class CGCXXABI;
class BlockFlags;
class BlockFieldFlags;
/// A branch fixup. These are required when emitting a goto to a
/// label which hasn't been emitted yet. The goto is optimistically
/// emitted as a branch to the basic block for the label, and (if it
/// occurs in a scope with non-trivial cleanups) a fixup is added to
/// the innermost cleanup. When a (normal) cleanup is popped, any
/// unresolved fixups in that scope are threaded through the cleanup.
struct BranchFixup {
/// The block containing the terminator which needs to be modified
/// into a switch if this fixup is resolved into the current scope.
/// If null, LatestBranch points directly to the destination.
llvm::BasicBlock *OptimisticBranchBlock;
/// The ultimate destination of the branch.
///
/// This can be set to null to indicate that this fixup was
/// successfully resolved.
llvm::BasicBlock *Destination;
/// The destination index value.
unsigned DestinationIndex;
/// The initial branch of the fixup.
llvm::BranchInst *InitialBranch;
};
template <class T> struct InvariantValue {
typedef T type;
typedef T saved_type;
static bool needsSaving(type value) { return false; }
static saved_type save(CodeGenFunction &CGF, type value) { return value; }
static type restore(CodeGenFunction &CGF, saved_type value) { return value; }
};
/// A metaprogramming class for ensuring that a value will dominate an
/// arbitrary position in a function.
template <class T> struct DominatingValue : InvariantValue<T> {};
template <class T, bool mightBeInstruction =
llvm::is_base_of<llvm::Value, T>::value &&
!llvm::is_base_of<llvm::Constant, T>::value &&
!llvm::is_base_of<llvm::BasicBlock, T>::value>
struct DominatingPointer;
template <class T> struct DominatingPointer<T,false> : InvariantValue<T*> {};
// template <class T> struct DominatingPointer<T,true> at end of file
template <class T> struct DominatingValue<T*> : DominatingPointer<T> {};
enum CleanupKind {
EHCleanup = 0x1,
NormalCleanup = 0x2,
NormalAndEHCleanup = EHCleanup | NormalCleanup,
InactiveCleanup = 0x4,
InactiveEHCleanup = EHCleanup | InactiveCleanup,
InactiveNormalCleanup = NormalCleanup | InactiveCleanup,
InactiveNormalAndEHCleanup = NormalAndEHCleanup | InactiveCleanup
};
/// A stack of scopes which respond to exceptions, including cleanups
/// and catch blocks.
class EHScopeStack {
public:
/// A saved depth on the scope stack. This is necessary because
/// pushing scopes onto the stack invalidates iterators.
class stable_iterator {
friend class EHScopeStack;
/// Offset from StartOfData to EndOfBuffer.
ptrdiff_t Size;
stable_iterator(ptrdiff_t Size) : Size(Size) {}
public:
static stable_iterator invalid() { return stable_iterator(-1); }
stable_iterator() : Size(-1) {}
bool isValid() const { return Size >= 0; }
/// Returns true if this scope encloses I.
/// Returns false if I is invalid.
/// This scope must be valid.
bool encloses(stable_iterator I) const { return Size <= I.Size; }
/// Returns true if this scope strictly encloses I: that is,
/// if it encloses I and is not I.
/// Returns false is I is invalid.
/// This scope must be valid.
bool strictlyEncloses(stable_iterator I) const { return Size < I.Size; }
friend bool operator==(stable_iterator A, stable_iterator B) {
return A.Size == B.Size;
}
friend bool operator!=(stable_iterator A, stable_iterator B) {
return A.Size != B.Size;
}
};
/// Information for lazily generating a cleanup. Subclasses must be
/// POD-like: cleanups will not be destructed, and they will be
/// allocated on the cleanup stack and freely copied and moved
/// around.
///
/// Cleanup implementations should generally be declared in an
/// anonymous namespace.
class Cleanup {
// Anchor the construction vtable.
virtual void anchor();
public:
/// Generation flags.
class Flags {
enum {
F_IsForEH = 0x1,
F_IsNormalCleanupKind = 0x2,
F_IsEHCleanupKind = 0x4
};
unsigned flags;
public:
Flags() : flags(0) {}
/// isForEH - true if the current emission is for an EH cleanup.
bool isForEHCleanup() const { return flags & F_IsForEH; }
bool isForNormalCleanup() const { return !isForEHCleanup(); }
void setIsForEHCleanup() { flags |= F_IsForEH; }
bool isNormalCleanupKind() const { return flags & F_IsNormalCleanupKind; }
void setIsNormalCleanupKind() { flags |= F_IsNormalCleanupKind; }
/// isEHCleanupKind - true if the cleanup was pushed as an EH
/// cleanup.
bool isEHCleanupKind() const { return flags & F_IsEHCleanupKind; }
void setIsEHCleanupKind() { flags |= F_IsEHCleanupKind; }
};
// Provide a virtual destructor to suppress a very common warning
// that unfortunately cannot be suppressed without this. Cleanups
// should not rely on this destructor ever being called.
virtual ~Cleanup() {}
/// Emit the cleanup. For normal cleanups, this is run in the
/// same EH context as when the cleanup was pushed, i.e. the
/// immediately-enclosing context of the cleanup scope. For
/// EH cleanups, this is run in a terminate context.
///
// \param flags cleanup kind.
virtual void Emit(CodeGenFunction &CGF, Flags flags) = 0;
};
/// ConditionalCleanupN stores the saved form of its N parameters,
/// then restores them and performs the cleanup.
template <class T, class A0>
class ConditionalCleanup1 : public Cleanup {
typedef typename DominatingValue<A0>::saved_type A0_saved;
A0_saved a0_saved;
void Emit(CodeGenFunction &CGF, Flags flags) {
A0 a0 = DominatingValue<A0>::restore(CGF, a0_saved);
T(a0).Emit(CGF, flags);
}
public:
ConditionalCleanup1(A0_saved a0)
: a0_saved(a0) {}
};
template <class T, class A0, class A1>
class ConditionalCleanup2 : public Cleanup {
typedef typename DominatingValue<A0>::saved_type A0_saved;
typedef typename DominatingValue<A1>::saved_type A1_saved;
A0_saved a0_saved;
A1_saved a1_saved;
void Emit(CodeGenFunction &CGF, Flags flags) {
A0 a0 = DominatingValue<A0>::restore(CGF, a0_saved);
A1 a1 = DominatingValue<A1>::restore(CGF, a1_saved);
T(a0, a1).Emit(CGF, flags);
}
public:
ConditionalCleanup2(A0_saved a0, A1_saved a1)
: a0_saved(a0), a1_saved(a1) {}
};
template <class T, class A0, class A1, class A2>
class ConditionalCleanup3 : public Cleanup {
typedef typename DominatingValue<A0>::saved_type A0_saved;
typedef typename DominatingValue<A1>::saved_type A1_saved;
typedef typename DominatingValue<A2>::saved_type A2_saved;
A0_saved a0_saved;
A1_saved a1_saved;
A2_saved a2_saved;
void Emit(CodeGenFunction &CGF, Flags flags) {
A0 a0 = DominatingValue<A0>::restore(CGF, a0_saved);
A1 a1 = DominatingValue<A1>::restore(CGF, a1_saved);
A2 a2 = DominatingValue<A2>::restore(CGF, a2_saved);
T(a0, a1, a2).Emit(CGF, flags);
}
public:
ConditionalCleanup3(A0_saved a0, A1_saved a1, A2_saved a2)
: a0_saved(a0), a1_saved(a1), a2_saved(a2) {}
};
template <class T, class A0, class A1, class A2, class A3>
class ConditionalCleanup4 : public Cleanup {
typedef typename DominatingValue<A0>::saved_type A0_saved;
typedef typename DominatingValue<A1>::saved_type A1_saved;
typedef typename DominatingValue<A2>::saved_type A2_saved;
typedef typename DominatingValue<A3>::saved_type A3_saved;
A0_saved a0_saved;
A1_saved a1_saved;
A2_saved a2_saved;
A3_saved a3_saved;
void Emit(CodeGenFunction &CGF, Flags flags) {
A0 a0 = DominatingValue<A0>::restore(CGF, a0_saved);
A1 a1 = DominatingValue<A1>::restore(CGF, a1_saved);
A2 a2 = DominatingValue<A2>::restore(CGF, a2_saved);
A3 a3 = DominatingValue<A3>::restore(CGF, a3_saved);
T(a0, a1, a2, a3).Emit(CGF, flags);
}
public:
ConditionalCleanup4(A0_saved a0, A1_saved a1, A2_saved a2, A3_saved a3)
: a0_saved(a0), a1_saved(a1), a2_saved(a2), a3_saved(a3) {}
};
private:
// The implementation for this class is in CGException.h and
// CGException.cpp; the definition is here because it's used as a
// member of CodeGenFunction.
/// The start of the scope-stack buffer, i.e. the allocated pointer
/// for the buffer. All of these pointers are either simultaneously
/// null or simultaneously valid.
char *StartOfBuffer;
/// The end of the buffer.
char *EndOfBuffer;
/// The first valid entry in the buffer.
char *StartOfData;
/// The innermost normal cleanup on the stack.
stable_iterator InnermostNormalCleanup;
/// The innermost EH scope on the stack.
stable_iterator InnermostEHScope;
/// The current set of branch fixups. A branch fixup is a jump to
/// an as-yet unemitted label, i.e. a label for which we don't yet
/// know the EH stack depth. Whenever we pop a cleanup, we have
/// to thread all the current branch fixups through it.
///
/// Fixups are recorded as the Use of the respective branch or
/// switch statement. The use points to the final destination.
/// When popping out of a cleanup, these uses are threaded through
/// the cleanup and adjusted to point to the new cleanup.
///
/// Note that branches are allowed to jump into protected scopes
/// in certain situations; e.g. the following code is legal:
/// struct A { ~A(); }; // trivial ctor, non-trivial dtor
/// goto foo;
/// A a;
/// foo:
/// bar();
SmallVector<BranchFixup, 8> BranchFixups;
char *allocate(size_t Size);
void *pushCleanup(CleanupKind K, size_t DataSize);
public:
EHScopeStack() : StartOfBuffer(0), EndOfBuffer(0), StartOfData(0),
InnermostNormalCleanup(stable_end()),
InnermostEHScope(stable_end()) {}
~EHScopeStack() { delete[] StartOfBuffer; }
// Variadic templates would make this not terrible.
/// Push a lazily-created cleanup on the stack.
template <class T>
void pushCleanup(CleanupKind Kind) {
void *Buffer = pushCleanup(Kind, sizeof(T));
Cleanup *Obj = new(Buffer) T();
(void) Obj;
}
/// Push a lazily-created cleanup on the stack.
template <class T, class A0>
void pushCleanup(CleanupKind Kind, A0 a0) {
void *Buffer = pushCleanup(Kind, sizeof(T));
Cleanup *Obj = new(Buffer) T(a0);
(void) Obj;
}
/// Push a lazily-created cleanup on the stack.
template <class T, class A0, class A1>
void pushCleanup(CleanupKind Kind, A0 a0, A1 a1) {
void *Buffer = pushCleanup(Kind, sizeof(T));
Cleanup *Obj = new(Buffer) T(a0, a1);
(void) Obj;
}
/// Push a lazily-created cleanup on the stack.
template <class T, class A0, class A1, class A2>
void pushCleanup(CleanupKind Kind, A0 a0, A1 a1, A2 a2) {
void *Buffer = pushCleanup(Kind, sizeof(T));
Cleanup *Obj = new(Buffer) T(a0, a1, a2);
(void) Obj;
}
/// Push a lazily-created cleanup on the stack.
template <class T, class A0, class A1, class A2, class A3>
void pushCleanup(CleanupKind Kind, A0 a0, A1 a1, A2 a2, A3 a3) {
void *Buffer = pushCleanup(Kind, sizeof(T));
Cleanup *Obj = new(Buffer) T(a0, a1, a2, a3);
(void) Obj;
}
/// Push a lazily-created cleanup on the stack.
template <class T, class A0, class A1, class A2, class A3, class A4>
void pushCleanup(CleanupKind Kind, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) {
void *Buffer = pushCleanup(Kind, sizeof(T));
Cleanup *Obj = new(Buffer) T(a0, a1, a2, a3, a4);
(void) Obj;
}
// Feel free to add more variants of the following:
/// Push a cleanup with non-constant storage requirements on the
/// stack. The cleanup type must provide an additional static method:
/// static size_t getExtraSize(size_t);
/// The argument to this method will be the value N, which will also
/// be passed as the first argument to the constructor.
///
/// The data stored in the extra storage must obey the same
/// restrictions as normal cleanup member data.
///
/// The pointer returned from this method is valid until the cleanup
/// stack is modified.
template <class T, class A0, class A1, class A2>
T *pushCleanupWithExtra(CleanupKind Kind, size_t N, A0 a0, A1 a1, A2 a2) {
void *Buffer = pushCleanup(Kind, sizeof(T) + T::getExtraSize(N));
return new (Buffer) T(N, a0, a1, a2);
}
/// Pops a cleanup scope off the stack. This is private to CGCleanup.cpp.
void popCleanup();
/// Push a set of catch handlers on the stack. The catch is
/// uninitialized and will need to have the given number of handlers
/// set on it.
class EHCatchScope *pushCatch(unsigned NumHandlers);
/// Pops a catch scope off the stack. This is private to CGException.cpp.
void popCatch();
/// Push an exceptions filter on the stack.
class EHFilterScope *pushFilter(unsigned NumFilters);
/// Pops an exceptions filter off the stack.
void popFilter();
/// Push a terminate handler on the stack.
void pushTerminate();
/// Pops a terminate handler off the stack.
void popTerminate();
/// Determines whether the exception-scopes stack is empty.
bool empty() const { return StartOfData == EndOfBuffer; }
bool requiresLandingPad() const {
return InnermostEHScope != stable_end();
}
/// Determines whether there are any normal cleanups on the stack.
bool hasNormalCleanups() const {
return InnermostNormalCleanup != stable_end();
}
/// Returns the innermost normal cleanup on the stack, or
/// stable_end() if there are no normal cleanups.
stable_iterator getInnermostNormalCleanup() const {
return InnermostNormalCleanup;
}
stable_iterator getInnermostActiveNormalCleanup() const;
stable_iterator getInnermostEHScope() const {
return InnermostEHScope;
}
stable_iterator getInnermostActiveEHScope() const;
/// An unstable reference to a scope-stack depth. Invalidated by
/// pushes but not pops.
class iterator;
/// Returns an iterator pointing to the innermost EH scope.
iterator begin() const;
/// Returns an iterator pointing to the outermost EH scope.
iterator end() const;
/// Create a stable reference to the top of the EH stack. The
/// returned reference is valid until that scope is popped off the
/// stack.
stable_iterator stable_begin() const {
return stable_iterator(EndOfBuffer - StartOfData);
}
/// Create a stable reference to the bottom of the EH stack.
static stable_iterator stable_end() {
return stable_iterator(0);
}
/// Translates an iterator into a stable_iterator.
stable_iterator stabilize(iterator it) const;
/// Turn a stable reference to a scope depth into a unstable pointer
/// to the EH stack.
iterator find(stable_iterator save) const;
/// Removes the cleanup pointed to by the given stable_iterator.
void removeCleanup(stable_iterator save);
/// Add a branch fixup to the current cleanup scope.
BranchFixup &addBranchFixup() {
assert(hasNormalCleanups() && "adding fixup in scope without cleanups");
BranchFixups.push_back(BranchFixup());
return BranchFixups.back();
}
unsigned getNumBranchFixups() const { return BranchFixups.size(); }
BranchFixup &getBranchFixup(unsigned I) {
assert(I < getNumBranchFixups());
return BranchFixups[I];
}
/// Pops lazily-removed fixups from the end of the list. This
/// should only be called by procedures which have just popped a
/// cleanup or resolved one or more fixups.
void popNullFixups();
/// Clears the branch-fixups list. This should only be called by
/// ResolveAllBranchFixups.
void clearFixups() { BranchFixups.clear(); }
};
/// CodeGenFunction - This class organizes the per-function state that is used
/// while generating LLVM code.
class CodeGenFunction : public CodeGenTypeCache {
CodeGenFunction(const CodeGenFunction &) LLVM_DELETED_FUNCTION;
void operator=(const CodeGenFunction &) LLVM_DELETED_FUNCTION;
friend class CGCXXABI;
public:
/// A jump destination is an abstract label, branching to which may
/// require a jump out through normal cleanups.
struct JumpDest {
JumpDest() : Block(0), ScopeDepth(), Index(0) {}
JumpDest(llvm::BasicBlock *Block,
EHScopeStack::stable_iterator Depth,
unsigned Index)
: Block(Block), ScopeDepth(Depth), Index(Index) {}
bool isValid() const { return Block != 0; }
llvm::BasicBlock *getBlock() const { return Block; }
EHScopeStack::stable_iterator getScopeDepth() const { return ScopeDepth; }
unsigned getDestIndex() const { return Index; }
private:
llvm::BasicBlock *Block;
EHScopeStack::stable_iterator ScopeDepth;
unsigned Index;
};
CodeGenModule &CGM; // Per-module state.
const TargetInfo &Target;
typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy;
CGBuilderTy Builder;
/// CurFuncDecl - Holds the Decl for the current function or ObjC method.
/// This excludes BlockDecls.
const Decl *CurFuncDecl;
/// CurCodeDecl - This is the inner-most code context, which includes blocks.
const Decl *CurCodeDecl;
const CGFunctionInfo *CurFnInfo;
QualType FnRetTy;
llvm::Function *CurFn;
/// CurGD - The GlobalDecl for the current function being compiled.
GlobalDecl CurGD;
/// PrologueCleanupDepth - The cleanup depth enclosing all the
/// cleanups associated with the parameters.
EHScopeStack::stable_iterator PrologueCleanupDepth;
/// ReturnBlock - Unified return block.
JumpDest ReturnBlock;
/// ReturnValue - The temporary alloca to hold the return value. This is null
/// iff the function has no return value.
llvm::Value *ReturnValue;
/// AllocaInsertPoint - This is an instruction in the entry block before which
/// we prefer to insert allocas.
llvm::AssertingVH<llvm::Instruction> AllocaInsertPt;
/// BoundsChecking - Emit run-time bounds checks. Higher values mean
/// potentially higher performance penalties.
unsigned char BoundsChecking;
/// CatchUndefined - Emit run-time checks to catch undefined behaviors.
bool CatchUndefined;
/// In ARC, whether we should autorelease the return value.
bool AutoreleaseResult;
const CodeGen::CGBlockInfo *BlockInfo;
llvm::Value *BlockPointer;
llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
FieldDecl *LambdaThisCaptureField;
/// \brief A mapping from NRVO variables to the flags used to indicate
/// when the NRVO has been applied to this variable.
llvm::DenseMap<const VarDecl *, llvm::Value *> NRVOFlags;
EHScopeStack EHStack;
/// i32s containing the indexes of the cleanup destinations.
llvm::AllocaInst *NormalCleanupDest;
unsigned NextCleanupDestIndex;
/// FirstBlockInfo - The head of a singly-linked-list of block layouts.
CGBlockInfo *FirstBlockInfo;
/// EHResumeBlock - Unified block containing a call to llvm.eh.resume.
llvm::BasicBlock *EHResumeBlock;
/// The exception slot. All landing pads write the current exception pointer
/// into this alloca.
llvm::Value *ExceptionSlot;
/// The selector slot. Under the MandatoryCleanup model, all landing pads
/// write the current selector value into this alloca.
llvm::AllocaInst *EHSelectorSlot;
/// Emits a landing pad for the current EH stack.
llvm::BasicBlock *EmitLandingPad();
llvm::BasicBlock *getInvokeDestImpl();
template <class T>
typename DominatingValue<T>::saved_type saveValueInCond(T value) {
return DominatingValue<T>::save(*this, value);
}
public:
/// ObjCEHValueStack - Stack of Objective-C exception values, used for
/// rethrows.
SmallVector<llvm::Value*, 8> ObjCEHValueStack;
/// A class controlling the emission of a finally block.
class FinallyInfo {
/// Where the catchall's edge through the cleanup should go.
JumpDest RethrowDest;
/// A function to call to enter the catch.
llvm::Constant *BeginCatchFn;
/// An i1 variable indicating whether or not the @finally is
/// running for an exception.
llvm::AllocaInst *ForEHVar;
/// An i8* variable into which the exception pointer to rethrow
/// has been saved.
llvm::AllocaInst *SavedExnVar;
public:
void enter(CodeGenFunction &CGF, const Stmt *Finally,
llvm::Constant *beginCatchFn, llvm::Constant *endCatchFn,
llvm::Constant *rethrowFn);
void exit(CodeGenFunction &CGF);
};
/// pushFullExprCleanup - Push a cleanup to be run at the end of the
/// current full-expression. Safe against the possibility that
/// we're currently inside a conditionally-evaluated expression.
template <class T, class A0>
void pushFullExprCleanup(CleanupKind kind, A0 a0) {
// If we're not in a conditional branch, or if none of the
// arguments requires saving, then use the unconditional cleanup.
if (!isInConditionalBranch())
return EHStack.pushCleanup<T>(kind, a0);
typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0);
typedef EHScopeStack::ConditionalCleanup1<T, A0> CleanupType;
EHStack.pushCleanup<CleanupType>(kind, a0_saved);
initFullExprCleanup();
}
/// pushFullExprCleanup - Push a cleanup to be run at the end of the
/// current full-expression. Safe against the possibility that
/// we're currently inside a conditionally-evaluated expression.
template <class T, class A0, class A1>
void pushFullExprCleanup(CleanupKind kind, A0 a0, A1 a1) {
// If we're not in a conditional branch, or if none of the
// arguments requires saving, then use the unconditional cleanup.
if (!isInConditionalBranch())
return EHStack.pushCleanup<T>(kind, a0, a1);
typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0);
typename DominatingValue<A1>::saved_type a1_saved = saveValueInCond(a1);
typedef EHScopeStack::ConditionalCleanup2<T, A0, A1> CleanupType;
EHStack.pushCleanup<CleanupType>(kind, a0_saved, a1_saved);
initFullExprCleanup();
}
/// pushFullExprCleanup - Push a cleanup to be run at the end of the
/// current full-expression. Safe against the possibility that
/// we're currently inside a conditionally-evaluated expression.
template <class T, class A0, class A1, class A2>
void pushFullExprCleanup(CleanupKind kind, A0 a0, A1 a1, A2 a2) {
// If we're not in a conditional branch, or if none of the
// arguments requires saving, then use the unconditional cleanup.
if (!isInConditionalBranch()) {
return EHStack.pushCleanup<T>(kind, a0, a1, a2);
}
typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0);
typename DominatingValue<A1>::saved_type a1_saved = saveValueInCond(a1);
typename DominatingValue<A2>::saved_type a2_saved = saveValueInCond(a2);
typedef EHScopeStack::ConditionalCleanup3<T, A0, A1, A2> CleanupType;
EHStack.pushCleanup<CleanupType>(kind, a0_saved, a1_saved, a2_saved);
initFullExprCleanup();
}
/// pushFullExprCleanup - Push a cleanup to be run at the end of the
/// current full-expression. Safe against the possibility that
/// we're currently inside a conditionally-evaluated expression.
template <class T, class A0, class A1, class A2, class A3>
void pushFullExprCleanup(CleanupKind kind, A0 a0, A1 a1, A2 a2, A3 a3) {
// If we're not in a conditional branch, or if none of the
// arguments requires saving, then use the unconditional cleanup.
if (!isInConditionalBranch()) {
return EHStack.pushCleanup<T>(kind, a0, a1, a2, a3);
}
typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0);
typename DominatingValue<A1>::saved_type a1_saved = saveValueInCond(a1);
typename DominatingValue<A2>::saved_type a2_saved = saveValueInCond(a2);
typename DominatingValue<A3>::saved_type a3_saved = saveValueInCond(a3);
typedef EHScopeStack::ConditionalCleanup4<T, A0, A1, A2, A3> CleanupType;
EHStack.pushCleanup<CleanupType>(kind, a0_saved, a1_saved,
a2_saved, a3_saved);
initFullExprCleanup();
}
/// Set up the last cleaup that was pushed as a conditional
/// full-expression cleanup.
void initFullExprCleanup();
/// PushDestructorCleanup - Push a cleanup to call the
/// complete-object destructor of an object of the given type at the
/// given address. Does nothing if T is not a C++ class type with a
/// non-trivial destructor.
void PushDestructorCleanup(QualType T, llvm::Value *Addr);
/// PushDestructorCleanup - Push a cleanup to call the
/// complete-object variant of the given destructor on the object at
/// the given address.
void PushDestructorCleanup(const CXXDestructorDecl *Dtor,
llvm::Value *Addr);
/// PopCleanupBlock - Will pop the cleanup entry on the stack and
/// process all branch fixups.
void PopCleanupBlock(bool FallThroughIsBranchThrough = false);
/// DeactivateCleanupBlock - Deactivates the given cleanup block.
/// The block cannot be reactivated. Pops it if it's the top of the
/// stack.
///
/// \param DominatingIP - An instruction which is known to
/// dominate the current IP (if set) and which lies along
/// all paths of execution between the current IP and the
/// the point at which the cleanup comes into scope.
void DeactivateCleanupBlock(EHScopeStack::stable_iterator Cleanup,
llvm::Instruction *DominatingIP);
/// ActivateCleanupBlock - Activates an initially-inactive cleanup.
/// Cannot be used to resurrect a deactivated cleanup.
///
/// \param DominatingIP - An instruction which is known to
/// dominate the current IP (if set) and which lies along
/// all paths of execution between the current IP and the
/// the point at which the cleanup comes into scope.
void ActivateCleanupBlock(EHScopeStack::stable_iterator Cleanup,
llvm::Instruction *DominatingIP);
/// \brief Enters a new scope for capturing cleanups, all of which
/// will be executed once the scope is exited.
class RunCleanupsScope {
EHScopeStack::stable_iterator CleanupStackDepth;
bool OldDidCallStackSave;
bool PerformCleanup;
RunCleanupsScope(const RunCleanupsScope &) LLVM_DELETED_FUNCTION;
void operator=(const RunCleanupsScope &) LLVM_DELETED_FUNCTION;
protected:
CodeGenFunction& CGF;
public:
/// \brief Enter a new cleanup scope.
explicit RunCleanupsScope(CodeGenFunction &CGF)
: PerformCleanup(true), CGF(CGF)
{
CleanupStackDepth = CGF.EHStack.stable_begin();
OldDidCallStackSave = CGF.DidCallStackSave;
CGF.DidCallStackSave = false;
}
/// \brief Exit this cleanup scope, emitting any accumulated
/// cleanups.
~RunCleanupsScope() {
if (PerformCleanup) {
CGF.DidCallStackSave = OldDidCallStackSave;
CGF.PopCleanupBlocks(CleanupStackDepth);
}
}
/// \brief Determine whether this scope requires any cleanups.
bool requiresCleanups() const {
return CGF.EHStack.stable_begin() != CleanupStackDepth;
}
/// \brief Force the emission of cleanups now, instead of waiting
/// until this object is destroyed.
void ForceCleanup() {
assert(PerformCleanup && "Already forced cleanup");
CGF.DidCallStackSave = OldDidCallStackSave;
CGF.PopCleanupBlocks(CleanupStackDepth);
PerformCleanup = false;
}
};
class LexicalScope: protected RunCleanupsScope {
SourceRange Range;
bool PopDebugStack;
LexicalScope(const LexicalScope &) LLVM_DELETED_FUNCTION;
void operator=(const LexicalScope &) LLVM_DELETED_FUNCTION;
public:
/// \brief Enter a new cleanup scope.
explicit LexicalScope(CodeGenFunction &CGF, SourceRange Range)
: RunCleanupsScope(CGF), Range(Range), PopDebugStack(true) {
if (CGDebugInfo *DI = CGF.getDebugInfo())
DI->EmitLexicalBlockStart(CGF.Builder, Range.getBegin());
}
/// \brief Exit this cleanup scope, emitting any accumulated
/// cleanups.
~LexicalScope() {
if (PopDebugStack) {
CGDebugInfo *DI = CGF.getDebugInfo();
if (DI) DI->EmitLexicalBlockEnd(CGF.Builder, Range.getEnd());
}
}
/// \brief Force the emission of cleanups now, instead of waiting
/// until this object is destroyed.
void ForceCleanup() {
RunCleanupsScope::ForceCleanup();
if (CGDebugInfo *DI = CGF.getDebugInfo()) {
DI->EmitLexicalBlockEnd(CGF.Builder, Range.getEnd());
PopDebugStack = false;
}
}
};
/// PopCleanupBlocks - Takes the old cleanup stack size and emits
/// the cleanup blocks that have been added.
void PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize);
void ResolveBranchFixups(llvm::BasicBlock *Target);
/// The given basic block lies in the current EH scope, but may be a
/// target of a potentially scope-crossing jump; get a stable handle
/// to which we can perform this jump later.
JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target) {
return JumpDest(Target,
EHStack.getInnermostNormalCleanup(),
NextCleanupDestIndex++);
}
/// The given basic block lies in the current EH scope, but may be a
/// target of a potentially scope-crossing jump; get a stable handle
/// to which we can perform this jump later.
JumpDest getJumpDestInCurrentScope(StringRef Name = StringRef()) {
return getJumpDestInCurrentScope(createBasicBlock(Name));
}
/// EmitBranchThroughCleanup - Emit a branch from the current insert
/// block through the normal cleanup handling code (if any) and then
/// on to \arg Dest.
void EmitBranchThroughCleanup(JumpDest Dest);
/// isObviouslyBranchWithoutCleanups - Return true if a branch to the
/// specified destination obviously has no cleanups to run. 'false' is always
/// a conservatively correct answer for this method.
bool isObviouslyBranchWithoutCleanups(JumpDest Dest) const;
/// popCatchScope - Pops the catch scope at the top of the EHScope
/// stack, emitting any required code (other than the catch handlers
/// themselves).
void popCatchScope();
llvm::BasicBlock *getEHResumeBlock();
llvm::BasicBlock *getEHDispatchBlock(EHScopeStack::stable_iterator scope);
/// An object to manage conditionally-evaluated expressions.
class ConditionalEvaluation {
llvm::BasicBlock *StartBB;
public:
ConditionalEvaluation(CodeGenFunction &CGF)
: StartBB(CGF.Builder.GetInsertBlock()) {}
void begin(CodeGenFunction &CGF) {
assert(CGF.OutermostConditional != this);
if (!CGF.OutermostConditional)
CGF.OutermostConditional = this;
}
void end(CodeGenFunction &CGF) {
assert(CGF.OutermostConditional != 0);
if (CGF.OutermostConditional == this)
CGF.OutermostConditional = 0;
}
/// Returns a block which will be executed prior to each
/// evaluation of the conditional code.
llvm::BasicBlock *getStartingBlock() const {
return StartBB;
}
};
/// isInConditionalBranch - Return true if we're currently emitting
/// one branch or the other of a conditional expression.
bool isInConditionalBranch() const { return OutermostConditional != 0; }
void setBeforeOutermostConditional(llvm::Value *value, llvm::Value *addr) {
assert(isInConditionalBranch());
llvm::BasicBlock *block = OutermostConditional->getStartingBlock();
new llvm::StoreInst(value, addr, &block->back());
}
/// An RAII object to record that we're evaluating a statement
/// expression.
class StmtExprEvaluation {
CodeGenFunction &CGF;
/// We have to save the outermost conditional: cleanups in a
/// statement expression aren't conditional just because the
/// StmtExpr is.
ConditionalEvaluation *SavedOutermostConditional;
public:
StmtExprEvaluation(CodeGenFunction &CGF)
: CGF(CGF), SavedOutermostConditional(CGF.OutermostConditional) {
CGF.OutermostConditional = 0;
}
~StmtExprEvaluation() {
CGF.OutermostConditional = SavedOutermostConditional;
CGF.EnsureInsertPoint();
}
};
/// An object which temporarily prevents a value from being
/// destroyed by aggressive peephole optimizations that assume that
/// all uses of a value have been realized in the IR.
class PeepholeProtection {
llvm::Instruction *Inst;
friend class CodeGenFunction;
public:
PeepholeProtection() : Inst(0) {}
};
/// A non-RAII class containing all the information about a bound
/// opaque value. OpaqueValueMapping, below, is a RAII wrapper for
/// this which makes individual mappings very simple; using this
/// class directly is useful when you have a variable number of
/// opaque values or don't want the RAII functionality for some
/// reason.
class OpaqueValueMappingData {
const OpaqueValueExpr *OpaqueValue;
bool BoundLValue;
CodeGenFunction::PeepholeProtection Protection;
OpaqueValueMappingData(const OpaqueValueExpr *ov,
bool boundLValue)
: OpaqueValue(ov), BoundLValue(boundLValue) {}
public:
OpaqueValueMappingData() : OpaqueValue(0) {}
static bool shouldBindAsLValue(const Expr *expr) {
// gl-values should be bound as l-values for obvious reasons.
// Records should be bound as l-values because IR generation
// always keeps them in memory. Expressions of function type
// act exactly like l-values but are formally required to be
// r-values in C.
return expr->isGLValue() ||
expr->getType()->isRecordType() ||
expr->getType()->isFunctionType();
}
static OpaqueValueMappingData bind(CodeGenFunction &CGF,
const OpaqueValueExpr *ov,
const Expr *e) {
if (shouldBindAsLValue(ov))
return bind(CGF, ov, CGF.EmitLValue(e));
return bind(CGF, ov, CGF.EmitAnyExpr(e));
}
static OpaqueValueMappingData bind(CodeGenFunction &CGF,
const OpaqueValueExpr *ov,
const LValue &lv) {
assert(shouldBindAsLValue(ov));
CGF.OpaqueLValues.insert(std::make_pair(ov, lv));
return OpaqueValueMappingData(ov, true);
}
static OpaqueValueMappingData bind(CodeGenFunction &CGF,
const OpaqueValueExpr *ov,
const RValue &rv) {
assert(!shouldBindAsLValue(ov));
CGF.OpaqueRValues.insert(std::make_pair(ov, rv));
OpaqueValueMappingData data(ov, false);
// Work around an extremely aggressive peephole optimization in
// EmitScalarConversion which assumes that all other uses of a
// value are extant.
data.Protection = CGF.protectFromPeepholes(rv);
return data;
}
bool isValid() const { return OpaqueValue != 0; }
void clear() { OpaqueValue = 0; }
void unbind(CodeGenFunction &CGF) {
assert(OpaqueValue && "no data to unbind!");
if (BoundLValue) {
CGF.OpaqueLValues.erase(OpaqueValue);
} else {
CGF.OpaqueRValues.erase(OpaqueValue);
CGF.unprotectFromPeepholes(Protection);
}
}
};
/// An RAII object to set (and then clear) a mapping for an OpaqueValueExpr.
class OpaqueValueMapping {
CodeGenFunction &CGF;
OpaqueValueMappingData Data;
public:
static bool shouldBindAsLValue(const Expr *expr) {
return OpaqueValueMappingData::shouldBindAsLValue(expr);
}
/// Build the opaque value mapping for the given conditional
/// operator if it's the GNU ?: extension. This is a common
/// enough pattern that the convenience operator is really
/// helpful.
///
OpaqueValueMapping(CodeGenFunction &CGF,
const AbstractConditionalOperator *op) : CGF(CGF) {
if (isa<ConditionalOperator>(op))
// Leave Data empty.
return;
const BinaryConditionalOperator *e = cast<BinaryConditionalOperator>(op);
Data = OpaqueValueMappingData::bind(CGF, e->getOpaqueValue(),
e->getCommon());
}
OpaqueValueMapping(CodeGenFunction &CGF,
const OpaqueValueExpr *opaqueValue,
LValue lvalue)
: CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, lvalue)) {
}
OpaqueValueMapping(CodeGenFunction &CGF,
const OpaqueValueExpr *opaqueValue,
RValue rvalue)
: CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, rvalue)) {
}
void pop() {
Data.unbind(CGF);
Data.clear();
}
~OpaqueValueMapping() {
if (Data.isValid()) Data.unbind(CGF);
}
};
/// getByrefValueFieldNumber - Given a declaration, returns the LLVM field
/// number that holds the value.
unsigned getByRefValueLLVMField(const ValueDecl *VD) const;
/// BuildBlockByrefAddress - Computes address location of the
/// variable which is declared as __block.
llvm::Value *BuildBlockByrefAddress(llvm::Value *BaseAddr,
const VarDecl *V);
private:
CGDebugInfo *DebugInfo;
bool DisableDebugInfo;
/// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid
/// calling llvm.stacksave for multiple VLAs in the same scope.
bool DidCallStackSave;
/// IndirectBranch - The first time an indirect goto is seen we create a block
/// with an indirect branch. Every time we see the address of a label taken,
/// we add the label to the indirect goto. Every subsequent indirect goto is
/// codegen'd as a jump to the IndirectBranch's basic block.
llvm::IndirectBrInst *IndirectBranch;
/// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C
/// decls.
typedef llvm::DenseMap<const Decl*, llvm::Value*> DeclMapTy;
DeclMapTy LocalDeclMap;
/// LabelMap - This keeps track of the LLVM basic block for each C label.
llvm::DenseMap<const LabelDecl*, JumpDest> LabelMap;
// BreakContinueStack - This keeps track of where break and continue
// statements should jump to.
struct BreakContinue {
BreakContinue(JumpDest Break, JumpDest Continue)
: BreakBlock(Break), ContinueBlock(Continue) {}
JumpDest BreakBlock;
JumpDest ContinueBlock;
};
SmallVector<BreakContinue, 8> BreakContinueStack;
/// SwitchInsn - This is nearest current switch instruction. It is null if
/// current context is not in a switch.
llvm::SwitchInst *SwitchInsn;
/// CaseRangeBlock - This block holds if condition check for last case
/// statement range in current switch instruction.
llvm::BasicBlock *CaseRangeBlock;
/// OpaqueLValues - Keeps track of the current set of opaque value
/// expressions.
llvm::DenseMap<const OpaqueValueExpr *, LValue> OpaqueLValues;
llvm::DenseMap<const OpaqueValueExpr *, RValue> OpaqueRValues;
// VLASizeMap - This keeps track of the associated size for each VLA type.
// We track this by the size expression rather than the type itself because
// in certain situations, like a const qualifier applied to an VLA typedef,
// multiple VLA types can share the same size expression.
// FIXME: Maybe this could be a stack of maps that is pushed/popped as we
// enter/leave scopes.
llvm::DenseMap<const Expr*, llvm::Value*> VLASizeMap;
/// A block containing a single 'unreachable' instruction. Created
/// lazily by getUnreachableBlock().
llvm::BasicBlock *UnreachableBlock;
/// CXXThisDecl - When generating code for a C++ member function,
/// this will hold the implicit 'this' declaration.
ImplicitParamDecl *CXXABIThisDecl;
llvm::Value *CXXABIThisValue;
llvm::Value *CXXThisValue;
/// CXXVTTDecl - When generating code for a base object constructor or
/// base object destructor with virtual bases, this will hold the implicit
/// VTT parameter.
ImplicitParamDecl *CXXVTTDecl;
llvm::Value *CXXVTTValue;
/// OutermostConditional - Points to the outermost active
/// conditional control. This is used so that we know if a
/// temporary should be destroyed conditionally.
ConditionalEvaluation *OutermostConditional;
/// ByrefValueInfoMap - For each __block variable, contains a pair of the LLVM
/// type as well as the field number that contains the actual data.
llvm::DenseMap<const ValueDecl *, std::pair<llvm::Type *,
unsigned> > ByRefValueInfo;
llvm::BasicBlock *TerminateLandingPad;
llvm::BasicBlock *TerminateHandler;
llvm::BasicBlock *TrapBB;
/// Add a kernel metadata node to the named metadata node 'opencl.kernels'.
/// In the kernel metadata node, reference the kernel function and metadata
/// nodes for its optional attribute qualifiers (OpenCL 1.1 6.7.2):
/// - A node for the work_group_size_hint(X,Y,Z) qualifier contains string
/// "work_group_size_hint", and three 32-bit integers X, Y and Z.
/// - A node for the reqd_work_group_size(X,Y,Z) qualifier contains string
/// "reqd_work_group_size", and three 32-bit integers X, Y and Z.
void EmitOpenCLKernelMetadata(const FunctionDecl *FD,
llvm::Function *Fn);
public:
CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext=false);
~CodeGenFunction();
CodeGenTypes &getTypes() const { return CGM.getTypes(); }
ASTContext &getContext() const { return CGM.getContext(); }
/// Returns true if DebugInfo is actually initialized.
bool maybeInitializeDebugInfo() {
if (CGM.getModuleDebugInfo()) {
DebugInfo = CGM.getModuleDebugInfo();
return true;
}
return false;
}
CGDebugInfo *getDebugInfo() {
if (DisableDebugInfo)
return NULL;
return DebugInfo;
}
void disableDebugInfo() { DisableDebugInfo = true; }
void enableDebugInfo() { DisableDebugInfo = false; }
bool shouldUseFusedARCCalls() {
return CGM.getCodeGenOpts().OptimizationLevel == 0;
}
const LangOptions &getLangOpts() const { return CGM.getLangOpts(); }
/// Returns a pointer to the function's exception object and selector slot,
/// which is assigned in every landing pad.
llvm::Value *getExceptionSlot();
llvm::Value *getEHSelectorSlot();
/// Returns the contents of the function's exception object and selector
/// slots.
llvm::Value *getExceptionFromSlot();
llvm::Value *getSelectorFromSlot();
llvm::Value *getNormalCleanupDestSlot();
llvm::BasicBlock *getUnreachableBlock() {
if (!UnreachableBlock) {
UnreachableBlock = createBasicBlock("unreachable");
new llvm::UnreachableInst(getLLVMContext(), UnreachableBlock);
}
return UnreachableBlock;
}
llvm::BasicBlock *getInvokeDest() {
if (!EHStack.requiresLandingPad()) return 0;
return getInvokeDestImpl();
}
llvm::LLVMContext &getLLVMContext() { return CGM.getLLVMContext(); }
//===--------------------------------------------------------------------===//
// Cleanups
//===--------------------------------------------------------------------===//
typedef void Destroyer(CodeGenFunction &CGF, llvm::Value *addr, QualType ty);
void pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
llvm::Value *arrayEndPointer,
QualType elementType,
Destroyer *destroyer);
void pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
llvm::Value *arrayEnd,
QualType elementType,
Destroyer *destroyer);
void pushDestroy(QualType::DestructionKind dtorKind,
llvm::Value *addr, QualType type);
void pushDestroy(CleanupKind kind, llvm::Value *addr, QualType type,
Destroyer *destroyer, bool useEHCleanupForArray);
void emitDestroy(llvm::Value *addr, QualType type, Destroyer *destroyer,
bool useEHCleanupForArray);
llvm::Function *generateDestroyHelper(llvm::Constant *addr,
QualType type,
Destroyer *destroyer,
bool useEHCleanupForArray);
void emitArrayDestroy(llvm::Value *begin, llvm::Value *end,
QualType type, Destroyer *destroyer,
bool checkZeroLength, bool useEHCleanup);
Destroyer *getDestroyer(QualType::DestructionKind destructionKind);
/// Determines whether an EH cleanup is required to destroy a type
/// with the given destruction kind.
bool needsEHCleanup(QualType::DestructionKind kind) {
switch (kind) {
case QualType::DK_none:
return false;
case QualType::DK_cxx_destructor:
case QualType::DK_objc_weak_lifetime:
return getLangOpts().Exceptions;
case QualType::DK_objc_strong_lifetime:
return getLangOpts().Exceptions &&
CGM.getCodeGenOpts().ObjCAutoRefCountExceptions;
}
llvm_unreachable("bad destruction kind");
}
CleanupKind getCleanupKind(QualType::DestructionKind kind) {
return (needsEHCleanup(kind) ? NormalAndEHCleanup : NormalCleanup);
}
//===--------------------------------------------------------------------===//
// Objective-C
//===--------------------------------------------------------------------===//
void GenerateObjCMethod(const ObjCMethodDecl *OMD);
void StartObjCMethod(const ObjCMethodDecl *MD,
const ObjCContainerDecl *CD,
SourceLocation StartLoc);
/// GenerateObjCGetter - Synthesize an Objective-C property getter function.
void GenerateObjCGetter(ObjCImplementationDecl *IMP,
const ObjCPropertyImplDecl *PID);
void generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
const ObjCPropertyImplDecl *propImpl,
const ObjCMethodDecl *GetterMothodDecl,
llvm::Constant *AtomicHelperFn);
void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
ObjCMethodDecl *MD, bool ctor);
/// GenerateObjCSetter - Synthesize an Objective-C property setter function
/// for the given property.
void GenerateObjCSetter(ObjCImplementationDecl *IMP,
const ObjCPropertyImplDecl *PID);
void generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
const ObjCPropertyImplDecl *propImpl,
llvm::Constant *AtomicHelperFn);
bool IndirectObjCSetterArg(const CGFunctionInfo &FI);
bool IvarTypeWithAggrGCObjects(QualType Ty);
//===--------------------------------------------------------------------===//
// Block Bits
//===--------------------------------------------------------------------===//
llvm::Value *EmitBlockLiteral(const BlockExpr *);
llvm::Value *EmitBlockLiteral(const CGBlockInfo &Info);
static void destroyBlockInfos(CGBlockInfo *info);
llvm::Constant *BuildDescriptorBlockDecl(const BlockExpr *,
const CGBlockInfo &Info,
llvm::StructType *,
llvm::Constant *BlockVarLayout);
llvm::Function *GenerateBlockFunction(GlobalDecl GD,
const CGBlockInfo &Info,
const Decl *OuterFuncDecl,
const DeclMapTy &ldm,
bool IsLambdaConversionToBlock);
llvm::Constant *GenerateCopyHelperFunction(const CGBlockInfo &blockInfo);
llvm::Constant *GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo);
llvm::Constant *GenerateObjCAtomicSetterCopyHelperFunction(
const ObjCPropertyImplDecl *PID);
llvm::Constant *GenerateObjCAtomicGetterCopyHelperFunction(
const ObjCPropertyImplDecl *PID);
llvm::Value *EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty);
void BuildBlockRelease(llvm::Value *DeclPtr, BlockFieldFlags flags);
class AutoVarEmission;
void emitByrefStructureInit(const AutoVarEmission &emission);
void enterByrefCleanup(const AutoVarEmission &emission);
llvm::Value *LoadBlockStruct() {
assert(BlockPointer && "no block pointer set!");
return BlockPointer;
}
void AllocateBlockCXXThisPointer(const CXXThisExpr *E);
void AllocateBlockDecl(const DeclRefExpr *E);
llvm::Value *GetAddrOfBlockDecl(const VarDecl *var, bool ByRef);
llvm::Type *BuildByRefType(const VarDecl *var);
void GenerateCode(GlobalDecl GD, llvm::Function *Fn,
const CGFunctionInfo &FnInfo);
void StartFunction(GlobalDecl GD, QualType RetTy,
llvm::Function *Fn,
const CGFunctionInfo &FnInfo,
const FunctionArgList &Args,
SourceLocation StartLoc);
void EmitConstructorBody(FunctionArgList &Args);
void EmitDestructorBody(FunctionArgList &Args);
void EmitFunctionBody(FunctionArgList &Args);
void EmitForwardingCallToLambda(const CXXRecordDecl *Lambda,
CallArgList &CallArgs);
void EmitLambdaToBlockPointerBody(FunctionArgList &Args);
void EmitLambdaBlockInvokeBody();
void EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD);
void EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD);
/// EmitReturnBlock - Emit the unified return block, trying to avoid its
/// emission when possible.
void EmitReturnBlock();
/// FinishFunction - Complete IR generation of the current function. It is
/// legal to call this function even if there is no current insertion point.
void FinishFunction(SourceLocation EndLoc=SourceLocation());
/// GenerateThunk - Generate a thunk for the given method.
void GenerateThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo,
GlobalDecl GD, const ThunkInfo &Thunk);
void GenerateVarArgsThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo,
GlobalDecl GD, const ThunkInfo &Thunk);
void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type,
FunctionArgList &Args);
void EmitInitializerForField(FieldDecl *Field, LValue LHS, Expr *Init,
ArrayRef<VarDecl *> ArrayIndexes);
/// InitializeVTablePointer - Initialize the vtable pointer of the given
/// subobject.
///
void InitializeVTablePointer(BaseSubobject Base,
const CXXRecordDecl *NearestVBase,
CharUnits OffsetFromNearestVBase,
llvm::Constant *VTable,
const CXXRecordDecl *VTableClass);
typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
void InitializeVTablePointers(BaseSubobject Base,
const CXXRecordDecl *NearestVBase,
CharUnits OffsetFromNearestVBase,
bool BaseIsNonVirtualPrimaryBase,
llvm::Constant *VTable,
const CXXRecordDecl *VTableClass,
VisitedVirtualBasesSetTy& VBases);
void InitializeVTablePointers(const CXXRecordDecl *ClassDecl);
/// GetVTablePtr - Return the Value of the vtable pointer member pointed
/// to by This.
llvm::Value *GetVTablePtr(llvm::Value *This, llvm::Type *Ty);
/// EnterDtorCleanups - Enter the cleanups necessary to complete the
/// given phase of destruction for a destructor. The end result
/// should call destructors on members and base classes in reverse
/// order of their construction.
void EnterDtorCleanups(const CXXDestructorDecl *Dtor, CXXDtorType Type);
/// ShouldInstrumentFunction - Return true if the current function should be
/// instrumented with __cyg_profile_func_* calls
bool ShouldInstrumentFunction();
/// EmitFunctionInstrumentation - Emit LLVM code to call the specified
/// instrumentation function with the current function and the call site, if
/// function instrumentation is enabled.
void EmitFunctionInstrumentation(const char *Fn);
/// EmitMCountInstrumentation - Emit call to .mcount.
void EmitMCountInstrumentation();
/// EmitFunctionProlog - Emit the target specific LLVM code to load the
/// arguments for the given function. This is also responsible for naming the
/// LLVM function arguments.
void EmitFunctionProlog(const CGFunctionInfo &FI,
llvm::Function *Fn,
const FunctionArgList &Args);
/// EmitFunctionEpilog - Emit the target specific LLVM code to return the
/// given temporary.
void EmitFunctionEpilog(const CGFunctionInfo &FI);
/// EmitStartEHSpec - Emit the start of the exception spec.
void EmitStartEHSpec(const Decl *D);
/// EmitEndEHSpec - Emit the end of the exception spec.
void EmitEndEHSpec(const Decl *D);
/// getTerminateLandingPad - Return a landing pad that just calls terminate.
llvm::BasicBlock *getTerminateLandingPad();
/// getTerminateHandler - Return a handler (not a landing pad, just
/// a catch handler) that just calls terminate. This is used when
/// a terminate scope encloses a try.
llvm::BasicBlock *getTerminateHandler();
llvm::Type *ConvertTypeForMem(QualType T);
llvm::Type *ConvertType(QualType T);
llvm::Type *ConvertType(const TypeDecl *T) {
return ConvertType(getContext().getTypeDeclType(T));
}
/// LoadObjCSelf - Load the value of self. This function is only valid while
/// generating code for an Objective-C method.
llvm::Value *LoadObjCSelf();
/// TypeOfSelfObject - Return type of object that this self represents.
QualType TypeOfSelfObject();
/// hasAggregateLLVMType - Return true if the specified AST type will map into
/// an aggregate LLVM type or is void.
static bool hasAggregateLLVMType(QualType T);
/// createBasicBlock - Create an LLVM basic block.
llvm::BasicBlock *createBasicBlock(const Twine &name = "",
llvm::Function *parent = 0,
llvm::BasicBlock *before = 0) {
#ifdef NDEBUG
return llvm::BasicBlock::Create(getLLVMContext(), "", parent, before);
#else
return llvm::BasicBlock::Create(getLLVMContext(), name, parent, before);
#endif
}
/// getBasicBlockForLabel - Return the LLVM basicblock that the specified
/// label maps to.
JumpDest getJumpDestForLabel(const LabelDecl *S);
/// SimplifyForwardingBlocks - If the given basic block is only a branch to
/// another basic block, simplify it. This assumes that no other code could
/// potentially reference the basic block.
void SimplifyForwardingBlocks(llvm::BasicBlock *BB);
/// EmitBlock - Emit the given block \arg BB and set it as the insert point,
/// adding a fall-through branch from the current insert block if
/// necessary. It is legal to call this function even if there is no current
/// insertion point.
///
/// IsFinished - If true, indicates that the caller has finished emitting
/// branches to the given block and does not expect to emit code into it. This
/// means the block can be ignored if it is unreachable.
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false);
/// EmitBlockAfterUses - Emit the given block somewhere hopefully
/// near its uses, and leave the insertion point in it.
void EmitBlockAfterUses(llvm::BasicBlock *BB);
/// EmitBranch - Emit a branch to the specified basic block from the current
/// insert block, taking care to avoid creation of branches from dummy
/// blocks. It is legal to call this function even if there is no current
/// insertion point.
///
/// This function clears the current insertion point. The caller should follow
/// calls to this function with calls to Emit*Block prior to generation new
/// code.
void EmitBranch(llvm::BasicBlock *Block);
/// HaveInsertPoint - True if an insertion point is defined. If not, this
/// indicates that the current code being emitted is unreachable.
bool HaveInsertPoint() const {
return Builder.GetInsertBlock() != 0;
}
/// EnsureInsertPoint - Ensure that an insertion point is defined so that
/// emitted IR has a place to go. Note that by definition, if this function
/// creates a block then that block is unreachable; callers may do better to
/// detect when no insertion point is defined and simply skip IR generation.
void EnsureInsertPoint() {
if (!HaveInsertPoint())
EmitBlock(createBasicBlock());
}
/// ErrorUnsupported - Print out an error that codegen doesn't support the
/// specified stmt yet.
void ErrorUnsupported(const Stmt *S, const char *Type,
bool OmitOnError=false);
//===--------------------------------------------------------------------===//
// Helpers
//===--------------------------------------------------------------------===//
LValue MakeAddrLValue(llvm::Value *V, QualType T,
CharUnits Alignment = CharUnits()) {
return LValue::MakeAddr(V, T, Alignment, getContext(),
CGM.getTBAAInfo(T));
}
LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T) {
CharUnits Alignment;
if (!T->isIncompleteType())
Alignment = getContext().getTypeAlignInChars(T);
return LValue::MakeAddr(V, T, Alignment, getContext(),
CGM.getTBAAInfo(T));
}
/// CreateTempAlloca - This creates a alloca and inserts it into the entry
/// block. The caller is responsible for setting an appropriate alignment on
/// the alloca.
llvm::AllocaInst *CreateTempAlloca(llvm::Type *Ty,
const Twine &Name = "tmp");
/// InitTempAlloca - Provide an initial value for the given alloca.
void InitTempAlloca(llvm::AllocaInst *Alloca, llvm::Value *Value);
/// CreateIRTemp - Create a temporary IR object of the given type, with
/// appropriate alignment. This routine should only be used when an temporary
/// value needs to be stored into an alloca (for example, to avoid explicit
/// PHI construction), but the type is the IR type, not the type appropriate
/// for storing in memory.
llvm::AllocaInst *CreateIRTemp(QualType T, const Twine &Name = "tmp");
/// CreateMemTemp - Create a temporary memory object of the given type, with
/// appropriate alignment.
llvm::AllocaInst *CreateMemTemp(QualType T, const Twine &Name = "tmp");
/// CreateAggTemp - Create a temporary memory object for the given
/// aggregate type.
AggValueSlot CreateAggTemp(QualType T, const Twine &Name = "tmp") {
CharUnits Alignment = getContext().getTypeAlignInChars(T);
return AggValueSlot::forAddr(CreateMemTemp(T, Name), Alignment,
T.getQualifiers(),
AggValueSlot::IsNotDestructed,
AggValueSlot::DoesNotNeedGCBarriers,
AggValueSlot::IsNotAliased);
}
/// Emit a cast to void* in the appropriate address space.
llvm::Value *EmitCastToVoidPtr(llvm::Value *value);
/// EvaluateExprAsBool - Perform the usual unary conversions on the specified
/// expression and compare the result against zero, returning an Int1Ty value.
llvm::Value *EvaluateExprAsBool(const Expr *E);
/// EmitIgnoredExpr - Emit an expression in a context which ignores the result.
void EmitIgnoredExpr(const Expr *E);
/// EmitAnyExpr - Emit code to compute the specified expression which can have
/// any type. The result is returned as an RValue struct. If this is an
/// aggregate expression, the aggloc/agglocvolatile arguments indicate where
/// the result should be returned.
///
/// \param ignoreResult True if the resulting value isn't used.
RValue EmitAnyExpr(const Expr *E,
AggValueSlot aggSlot = AggValueSlot::ignored(),
bool ignoreResult = false);
// EmitVAListRef - Emit a "reference" to a va_list; this is either the address
// or the value of the expression, depending on how va_list is defined.
llvm::Value *EmitVAListRef(const Expr *E);
/// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
/// always be accessible even if no aggregate location is provided.
RValue EmitAnyExprToTemp(const Expr *E);
/// EmitAnyExprToMem - Emits the code necessary to evaluate an
/// arbitrary expression into the given memory location.
void EmitAnyExprToMem(const Expr *E, llvm::Value *Location,
Qualifiers Quals, bool IsInitializer);
/// EmitExprAsInit - Emits the code necessary to initialize a
/// location in memory with the given initializer.
void EmitExprAsInit(const Expr *init, const ValueDecl *D,
LValue lvalue, bool capturedByInit);
/// EmitAggregateCopy - Emit an aggrate assignment.
///
/// The difference to EmitAggregateCopy is that tail padding is not copied.
/// This is required for correctness when assigning non-POD structures in C++.
void EmitAggregateAssign(llvm::Value *DestPtr, llvm::Value *SrcPtr,
QualType EltTy, bool isVolatile=false,
CharUnits Alignment = CharUnits::Zero()) {
EmitAggregateCopy(DestPtr, SrcPtr, EltTy, isVolatile, Alignment, true);
}
/// EmitAggregateCopy - Emit an aggrate copy.
///
/// \param isVolatile - True iff either the source or the destination is
/// volatile.
/// \param isAssignment - If false, allow padding to be copied. This often
/// yields more efficient.
void EmitAggregateCopy(llvm::Value *DestPtr, llvm::Value *SrcPtr,
QualType EltTy, bool isVolatile=false,
CharUnits Alignment = CharUnits::Zero(),
bool isAssignment = false);
/// StartBlock - Start new block named N. If insert block is a dummy block
/// then reuse it.
void StartBlock(const char *N);
/// GetAddrOfStaticLocalVar - Return the address of a static local variable.
llvm::Constant *GetAddrOfStaticLocalVar(const VarDecl *BVD) {
return cast<llvm::Constant>(GetAddrOfLocalVar(BVD));
}
/// GetAddrOfLocalVar - Return the address of a local variable.
llvm::Value *GetAddrOfLocalVar(const VarDecl *VD) {
llvm::Value *Res = LocalDeclMap[VD];
assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!");
return Res;
}
/// getOpaqueLValueMapping - Given an opaque value expression (which
/// must be mapped to an l-value), return its mapping.
const LValue &getOpaqueLValueMapping(const OpaqueValueExpr *e) {
assert(OpaqueValueMapping::shouldBindAsLValue(e));
llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator
it = OpaqueLValues.find(e);
assert(it != OpaqueLValues.end() && "no mapping for opaque value!");
return it->second;
}
/// getOpaqueRValueMapping - Given an opaque value expression (which
/// must be mapped to an r-value), return its mapping.
const RValue &getOpaqueRValueMapping(const OpaqueValueExpr *e) {
assert(!OpaqueValueMapping::shouldBindAsLValue(e));
llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator
it = OpaqueRValues.find(e);
assert(it != OpaqueRValues.end() && "no mapping for opaque value!");
return it->second;
}
/// getAccessedFieldNo - Given an encoded value and a result number, return
/// the input field number being accessed.
static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts);
llvm::BlockAddress *GetAddrOfLabel(const LabelDecl *L);
llvm::BasicBlock *GetIndirectGotoBlock();
/// EmitNullInitialization - Generate code to set a value of the given type to
/// null, If the type contains data member pointers, they will be initialized
/// to -1 in accordance with the Itanium C++ ABI.
void EmitNullInitialization(llvm::Value *DestPtr, QualType Ty);
// EmitVAArg - Generate code to get an argument from the passed in pointer
// and update it accordingly. The return value is a pointer to the argument.
// FIXME: We should be able to get rid of this method and use the va_arg
// instruction in LLVM instead once it works well enough.
llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty);
/// emitArrayLength - Compute the length of an array, even if it's a
/// VLA, and drill down to the base element type.
llvm::Value *emitArrayLength(const ArrayType *arrayType,
QualType &baseType,
llvm::Value *&addr);
/// EmitVLASize - Capture all the sizes for the VLA expressions in
/// the given variably-modified type and store them in the VLASizeMap.
///
/// This function can be called with a null (unreachable) insert point.
void EmitVariablyModifiedType(QualType Ty);
/// getVLASize - Returns an LLVM value that corresponds to the size,
/// in non-variably-sized elements, of a variable length array type,
/// plus that largest non-variably-sized element type. Assumes that
/// the type has already been emitted with EmitVariablyModifiedType.
std::pair<llvm::Value*,QualType> getVLASize(const VariableArrayType *vla);
std::pair<llvm::Value*,QualType> getVLASize(QualType vla);
/// LoadCXXThis - Load the value of 'this'. This function is only valid while
/// generating code for an C++ member function.
llvm::Value *LoadCXXThis() {
assert(CXXThisValue && "no 'this' value for this function");
return CXXThisValue;
}
/// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have
/// virtual bases.
llvm::Value *LoadCXXVTT() {
assert(CXXVTTValue && "no VTT value for this function");
return CXXVTTValue;
}
/// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a
/// complete class to the given direct base.
llvm::Value *
GetAddressOfDirectBaseInCompleteClass(llvm::Value *Value,
const CXXRecordDecl *Derived,
const CXXRecordDecl *Base,
bool BaseIsVirtual);
/// GetAddressOfBaseClass - This function will add the necessary delta to the
/// load of 'this' and returns address of the base class.
llvm::Value *GetAddressOfBaseClass(llvm::Value *Value,
const CXXRecordDecl *Derived,
CastExpr::path_const_iterator PathBegin,
CastExpr::path_const_iterator PathEnd,
bool NullCheckValue);
llvm::Value *GetAddressOfDerivedClass(llvm::Value *Value,
const CXXRecordDecl *Derived,
CastExpr::path_const_iterator PathBegin,
CastExpr::path_const_iterator PathEnd,
bool NullCheckValue);
llvm::Value *GetVirtualBaseClassOffset(llvm::Value *This,
const CXXRecordDecl *ClassDecl,
const CXXRecordDecl *BaseClassDecl);
void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
CXXCtorType CtorType,
const FunctionArgList &Args);
// It's important not to confuse this and the previous function. Delegating
// constructors are the C++0x feature. The constructor delegate optimization
// is used to reduce duplication in the base and complete consturctors where
// they are substantially the same.
void EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
const FunctionArgList &Args);
void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
bool ForVirtualBase, llvm::Value *This,
CallExpr::const_arg_iterator ArgBeg,
CallExpr::const_arg_iterator ArgEnd);
void EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
llvm::Value *This, llvm::Value *Src,
CallExpr::const_arg_iterator ArgBeg,
CallExpr::const_arg_iterator ArgEnd);
void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
const ConstantArrayType *ArrayTy,
llvm::Value *ArrayPtr,
CallExpr::const_arg_iterator ArgBeg,
CallExpr::const_arg_iterator ArgEnd,
bool ZeroInitialization = false);
void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
llvm::Value *NumElements,
llvm::Value *ArrayPtr,
CallExpr::const_arg_iterator ArgBeg,
CallExpr::const_arg_iterator ArgEnd,
bool ZeroInitialization = false);
static Destroyer destroyCXXObject;
void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type,
bool ForVirtualBase, llvm::Value *This);
void EmitNewArrayInitializer(const CXXNewExpr *E, QualType elementType,
llvm::Value *NewPtr, llvm::Value *NumElements);
void EmitCXXTemporary(const CXXTemporary *Temporary, QualType TempType,
llvm::Value *Ptr);
llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E);
void EmitCXXDeleteExpr(const CXXDeleteExpr *E);
void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr,
QualType DeleteTy);
llvm::Value* EmitCXXTypeidExpr(const CXXTypeidExpr *E);
llvm::Value *EmitDynamicCast(llvm::Value *V, const CXXDynamicCastExpr *DCE);
llvm::Value* EmitCXXUuidofExpr(const CXXUuidofExpr *E);
void MaybeEmitStdInitializerListCleanup(llvm::Value *loc, const Expr *init);
void EmitStdInitializerListCleanup(llvm::Value *loc,
const InitListExpr *init);
/// \brief Situations in which we might emit a check for the suitability of a
/// pointer or glvalue.
enum TypeCheckKind {
/// Checking the operand of a load. Must be suitably sized and aligned.
TCK_Load,
/// Checking the destination of a store. Must be suitably sized and aligned.
TCK_Store,
/// Checking the bound value in a reference binding. Must be suitably sized
/// and aligned, but is not required to refer to an object (until the
/// reference is used), per core issue 453.
TCK_ReferenceBinding,
/// Checking the object expression in a non-static data member access. Must
/// be an object within its lifetime.
TCK_MemberAccess,
/// Checking the 'this' pointer for a call to a non-static member function.
/// Must be an object within its lifetime.
TCK_MemberCall
};
/// \brief Emit a check that \p V is the address of storage of the
/// appropriate size and alignment for an object of type \p Type.
void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, llvm::Value *V,
QualType Type, CharUnits Alignment = CharUnits::Zero());
llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
bool isInc, bool isPre);
ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
bool isInc, bool isPre);
//===--------------------------------------------------------------------===//
// Declaration Emission
//===--------------------------------------------------------------------===//
/// EmitDecl - Emit a declaration.
///
/// This function can be called with a null (unreachable) insert point.
void EmitDecl(const Decl &D);
/// EmitVarDecl - Emit a local variable declaration.
///
/// This function can be called with a null (unreachable) insert point.
void EmitVarDecl(const VarDecl &D);
void EmitScalarInit(const Expr *init, const ValueDecl *D,
LValue lvalue, bool capturedByInit);
void EmitScalarInit(llvm::Value *init, LValue lvalue);
typedef void SpecialInitFn(CodeGenFunction &Init, const VarDecl &D,
llvm::Value *Address);
/// EmitAutoVarDecl - Emit an auto variable declaration.
///
/// This function can be called with a null (unreachable) insert point.
void EmitAutoVarDecl(const VarDecl &D);
class AutoVarEmission {
friend class CodeGenFunction;
const VarDecl *Variable;
/// The alignment of the variable.
CharUnits Alignment;
/// The address of the alloca. Null if the variable was emitted
/// as a global constant.
llvm::Value *Address;
llvm::Value *NRVOFlag;
/// True if the variable is a __block variable.
bool IsByRef;
/// True if the variable is of aggregate type and has a constant
/// initializer.
bool IsConstantAggregate;
struct Invalid {};
AutoVarEmission(Invalid) : Variable(0) {}
AutoVarEmission(const VarDecl &variable)
: Variable(&variable), Address(0), NRVOFlag(0),
IsByRef(false), IsConstantAggregate(false) {}
bool wasEmittedAsGlobal() const { return Address == 0; }
public:
static AutoVarEmission invalid() { return AutoVarEmission(Invalid()); }
/// Returns the address of the object within this declaration.
/// Note that this does not chase the forwarding pointer for
/// __block decls.
llvm::Value *getObjectAddress(CodeGenFunction &CGF) const {
if (!IsByRef) return Address;
return CGF.Builder.CreateStructGEP(Address,
CGF.getByRefValueLLVMField(Variable),
Variable->getNameAsString());
}
};
AutoVarEmission EmitAutoVarAlloca(const VarDecl &var);
void EmitAutoVarInit(const AutoVarEmission &emission);
void EmitAutoVarCleanups(const AutoVarEmission &emission);
void emitAutoVarTypeCleanup(const AutoVarEmission &emission,
QualType::DestructionKind dtorKind);
void EmitStaticVarDecl(const VarDecl &D,
llvm::GlobalValue::LinkageTypes Linkage);
/// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
void EmitParmDecl(const VarDecl &D, llvm::Value *Arg, unsigned ArgNo);
/// protectFromPeepholes - Protect a value that we're intending to
/// store to the side, but which will probably be used later, from
/// aggressive peepholing optimizations that might delete it.
///
/// Pass the result to unprotectFromPeepholes to declare that
/// protection is no longer required.
///
/// There's no particular reason why this shouldn't apply to
/// l-values, it's just that no existing peepholes work on pointers.
PeepholeProtection protectFromPeepholes(RValue rvalue);
void unprotectFromPeepholes(PeepholeProtection protection);
//===--------------------------------------------------------------------===//
// Statement Emission
//===--------------------------------------------------------------------===//
/// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info.
void EmitStopPoint(const Stmt *S);
/// EmitStmt - Emit the code for the statement \arg S. It is legal to call
/// this function even if there is no current insertion point.
///
/// This function may clear the current insertion point; callers should use
/// EnsureInsertPoint if they wish to subsequently generate code without first
/// calling EmitBlock, EmitBranch, or EmitStmt.
void EmitStmt(const Stmt *S);
/// EmitSimpleStmt - Try to emit a "simple" statement which does not
/// necessarily require an insertion point or debug information; typically
/// because the statement amounts to a jump or a container of other
/// statements.
///
/// \return True if the statement was handled.
bool EmitSimpleStmt(const Stmt *S);
RValue EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false,
AggValueSlot AVS = AggValueSlot::ignored());
/// EmitLabel - Emit the block for the given label. It is legal to call this
/// function even if there is no current insertion point.
void EmitLabel(const LabelDecl *D); // helper for EmitLabelStmt.
void EmitLabelStmt(const LabelStmt &S);
void EmitAttributedStmt(const AttributedStmt &S);
void EmitGotoStmt(const GotoStmt &S);
void EmitIndirectGotoStmt(const IndirectGotoStmt &S);
void EmitIfStmt(const IfStmt &S);
void EmitWhileStmt(const WhileStmt &S);
void EmitDoStmt(const DoStmt &S);
void EmitForStmt(const ForStmt &S);
void EmitReturnStmt(const ReturnStmt &S);
void EmitDeclStmt(const DeclStmt &S);
void EmitBreakStmt(const BreakStmt &S);
void EmitContinueStmt(const ContinueStmt &S);
void EmitSwitchStmt(const SwitchStmt &S);
void EmitDefaultStmt(const DefaultStmt &S);
void EmitCaseStmt(const CaseStmt &S);
void EmitCaseStmtRange(const CaseStmt &S);
void EmitAsmStmt(const AsmStmt &S);
void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S);
void EmitObjCAtTryStmt(const ObjCAtTryStmt &S);
void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S);
void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S);
void EmitObjCAutoreleasePoolStmt(const ObjCAutoreleasePoolStmt &S);
llvm::Constant *getUnwindResumeFn();
llvm::Constant *getUnwindResumeOrRethrowFn();
void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
void EmitCXXTryStmt(const CXXTryStmt &S);
void EmitCXXForRangeStmt(const CXXForRangeStmt &S);
//===--------------------------------------------------------------------===//
// LValue Expression Emission
//===--------------------------------------------------------------------===//
/// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
RValue GetUndefRValue(QualType Ty);
/// EmitUnsupportedRValue - Emit a dummy r-value using the type of E
/// and issue an ErrorUnsupported style diagnostic (using the
/// provided Name).
RValue EmitUnsupportedRValue(const Expr *E,
const char *Name);
/// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue
/// an ErrorUnsupported style diagnostic (using the provided Name).
LValue EmitUnsupportedLValue(const Expr *E,
const char *Name);
/// EmitLValue - Emit code to compute a designator that specifies the location
/// of the expression.
///
/// This can return one of two things: a simple address or a bitfield
/// reference. In either case, the LLVM Value* in the LValue structure is
/// guaranteed to be an LLVM pointer type.
///
/// If this returns a bitfield reference, nothing about the pointee type of
/// the LLVM value is known: For example, it may not be a pointer to an
/// integer.
///
/// If this returns a normal address, and if the lvalue's C type is fixed
/// size, this method guarantees that the returned pointer type will point to
/// an LLVM type of the same size of the lvalue's type. If the lvalue has a
/// variable length type, this is not possible.
///
LValue EmitLValue(const Expr *E);
/// \brief Same as EmitLValue but additionally we generate checking code to
/// guard against undefined behavior. This is only suitable when we know
/// that the address will be used to access the object.
LValue EmitCheckedLValue(const Expr *E, TypeCheckKind TCK);
/// EmitToMemory - Change a scalar value from its value
/// representation to its in-memory representation.
llvm::Value *EmitToMemory(llvm::Value *Value, QualType Ty);
/// EmitFromMemory - Change a scalar value from its memory
/// representation to its value representation.
llvm::Value *EmitFromMemory(llvm::Value *Value, QualType Ty);
/// EmitLoadOfScalar - Load a scalar value from an address, taking
/// care to appropriately convert from the memory representation to
/// the LLVM value representation.
llvm::Value *EmitLoadOfScalar(llvm::Value *Addr, bool Volatile,
unsigned Alignment, QualType Ty,
llvm::MDNode *TBAAInfo = 0);
/// EmitLoadOfScalar - Load a scalar value from an address, taking
/// care to appropriately convert from the memory representation to
/// the LLVM value representation. The l-value must be a simple
/// l-value.
llvm::Value *EmitLoadOfScalar(LValue lvalue);
/// EmitStoreOfScalar - Store a scalar value to an address, taking
/// care to appropriately convert from the memory representation to
/// the LLVM value representation.
void EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr,
bool Volatile, unsigned Alignment, QualType Ty,
llvm::MDNode *TBAAInfo = 0, bool isInit=false);
/// EmitStoreOfScalar - Store a scalar value to an address, taking
/// care to appropriately convert from the memory representation to
/// the LLVM value representation. The l-value must be a simple
/// l-value. The isInit flag indicates whether this is an initialization.
/// If so, atomic qualifiers are ignored and the store is always non-atomic.
void EmitStoreOfScalar(llvm::Value *value, LValue lvalue, bool isInit=false);
/// EmitLoadOfLValue - Given an expression that represents a value lvalue,
/// this method emits the address of the lvalue, then loads the result as an
/// rvalue, returning the rvalue.
RValue EmitLoadOfLValue(LValue V);
RValue EmitLoadOfExtVectorElementLValue(LValue V);
RValue EmitLoadOfBitfieldLValue(LValue LV);
/// EmitStoreThroughLValue - Store the specified rvalue into the specified
/// lvalue, where both are guaranteed to the have the same type, and that type
/// is 'Ty'.
void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit=false);
void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst);
/// EmitStoreThroughLValue - Store Src into Dst with same constraints as
/// EmitStoreThroughLValue.
///
/// \param Result [out] - If non-null, this will be set to a Value* for the
/// bit-field contents after the store, appropriate for use as the result of
/// an assignment to the bit-field.
void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
llvm::Value **Result=0);
/// Emit an l-value for an assignment (simple or compound) of complex type.
LValue EmitComplexAssignmentLValue(const BinaryOperator *E);
LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E);
// Note: only available for agg return types
LValue EmitBinaryOperatorLValue(const BinaryOperator *E);
LValue EmitCompoundAssignmentLValue(const CompoundAssignOperator *E);
// Note: only available for agg return types
LValue EmitCallExprLValue(const CallExpr *E);
// Note: only available for agg return types
LValue EmitVAArgExprLValue(const VAArgExpr *E);
LValue EmitDeclRefLValue(const DeclRefExpr *E);
LValue EmitStringLiteralLValue(const StringLiteral *E);
LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E);
LValue EmitPredefinedLValue(const PredefinedExpr *E);
LValue EmitUnaryOpLValue(const UnaryOperator *E);
LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E);
LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E);
LValue EmitMemberExpr(const MemberExpr *E);
LValue EmitObjCIsaExpr(const ObjCIsaExpr *E);
LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E);
LValue EmitInitListLValue(const InitListExpr *E);
LValue EmitConditionalOperatorLValue(const AbstractConditionalOperator *E);
LValue EmitCastLValue(const CastExpr *E);
LValue EmitNullInitializationLValue(const CXXScalarValueInitExpr *E);
LValue EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
LValue EmitOpaqueValueLValue(const OpaqueValueExpr *e);
RValue EmitRValueForField(LValue LV, const FieldDecl *FD);
class ConstantEmission {
llvm::PointerIntPair<llvm::Constant*, 1, bool> ValueAndIsReference;
ConstantEmission(llvm::Constant *C, bool isReference)
: ValueAndIsReference(C, isReference) {}
public:
ConstantEmission() {}
static ConstantEmission forReference(llvm::Constant *C) {
return ConstantEmission(C, true);
}
static ConstantEmission forValue(llvm::Constant *C) {
return ConstantEmission(C, false);
}
operator bool() const { return ValueAndIsReference.getOpaqueValue() != 0; }
bool isReference() const { return ValueAndIsReference.getInt(); }
LValue getReferenceLValue(CodeGenFunction &CGF, Expr *refExpr) const {
assert(isReference());
return CGF.MakeNaturalAlignAddrLValue(ValueAndIsReference.getPointer(),
refExpr->getType());
}
llvm::Constant *getValue() const {
assert(!isReference());
return ValueAndIsReference.getPointer();
}
};
ConstantEmission tryEmitAsConstant(DeclRefExpr *refExpr);
RValue EmitPseudoObjectRValue(const PseudoObjectExpr *e,
AggValueSlot slot = AggValueSlot::ignored());
LValue EmitPseudoObjectLValue(const PseudoObjectExpr *e);
llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface,
const ObjCIvarDecl *Ivar);
LValue EmitLValueForField(LValue Base, const FieldDecl* Field);
/// EmitLValueForFieldInitialization - Like EmitLValueForField, except that
/// if the Field is a reference, this will return the address of the reference
/// and not the address of the value stored in the reference.
LValue EmitLValueForFieldInitialization(LValue Base,
const FieldDecl* Field);
LValue EmitLValueForIvar(QualType ObjectTy,
llvm::Value* Base, const ObjCIvarDecl *Ivar,
unsigned CVRQualifiers);
LValue EmitCXXConstructLValue(const CXXConstructExpr *E);
LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E);
LValue EmitLambdaLValue(const LambdaExpr *E);
LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E);
LValue EmitCXXUuidofLValue(const CXXUuidofExpr *E);
LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E);
LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E);
LValue EmitStmtExprLValue(const StmtExpr *E);
LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E);
LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E);
void EmitDeclRefExprDbgValue(const DeclRefExpr *E, llvm::Constant *Init);
//===--------------------------------------------------------------------===//
// Scalar Expression Emission
//===--------------------------------------------------------------------===//
/// EmitCall - Generate a call of the given function, expecting the given
/// result type, and using the given argument list which specifies both the
/// LLVM arguments and the types they were derived from.
///
/// \param TargetDecl - If given, the decl of the function in a direct call;
/// used to set attributes on the call (noreturn, etc.).
RValue EmitCall(const CGFunctionInfo &FnInfo,
llvm::Value *Callee,
ReturnValueSlot ReturnValue,
const CallArgList &Args,
const Decl *TargetDecl = 0,
llvm::Instruction **callOrInvoke = 0);
RValue EmitCall(QualType FnType, llvm::Value *Callee,
ReturnValueSlot ReturnValue,
CallExpr::const_arg_iterator ArgBeg,
CallExpr::const_arg_iterator ArgEnd,
const Decl *TargetDecl = 0);
RValue EmitCallExpr(const CallExpr *E,
ReturnValueSlot ReturnValue = ReturnValueSlot());
llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee,
ArrayRef<llvm::Value *> Args,
const Twine &Name = "");
llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee,
const Twine &Name = "");
llvm::Value *BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *This,
llvm::Type *Ty);
llvm::Value *BuildVirtualCall(const CXXDestructorDecl *DD, CXXDtorType Type,
llvm::Value *This, llvm::Type *Ty);
llvm::Value *BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
NestedNameSpecifier *Qual,
llvm::Type *Ty);
llvm::Value *BuildAppleKextVirtualDestructorCall(const CXXDestructorDecl *DD,
CXXDtorType Type,
const CXXRecordDecl *RD);
RValue EmitCXXMemberCall(const CXXMethodDecl *MD,
SourceLocation CallLoc,
llvm::Value *Callee,
ReturnValueSlot ReturnValue,
llvm::Value *This,
llvm::Value *VTT,
CallExpr::const_arg_iterator ArgBeg,
CallExpr::const_arg_iterator ArgEnd);
RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E,
ReturnValueSlot ReturnValue);
RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
ReturnValueSlot ReturnValue);
llvm::Value *EmitCXXOperatorMemberCallee(const CXXOperatorCallExpr *E,
const CXXMethodDecl *MD,
llvm::Value *This);
RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
const CXXMethodDecl *MD,
ReturnValueSlot ReturnValue);
RValue EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
ReturnValueSlot ReturnValue);
RValue EmitBuiltinExpr(const FunctionDecl *FD,
unsigned BuiltinID, const CallExpr *E);
RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
/// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call
/// is unhandled by the current target.
llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
llvm::Value *EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
llvm::Value *EmitNeonCall(llvm::Function *F,
SmallVectorImpl<llvm::Value*> &O,
const char *name,
unsigned shift = 0, bool rightshift = false);
llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx);
llvm::Value *EmitNeonShiftVector(llvm::Value *V, llvm::Type *Ty,
bool negateForRightShift);
llvm::Value *BuildVector(ArrayRef<llvm::Value*> Ops);
llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E);
llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E);
llvm::Value *EmitObjCBoxedExpr(const ObjCBoxedExpr *E);
llvm::Value *EmitObjCArrayLiteral(const ObjCArrayLiteral *E);
llvm::Value *EmitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E);
llvm::Value *EmitObjCCollectionLiteral(const Expr *E,
const ObjCMethodDecl *MethodWithObjects);
llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E);
RValue EmitObjCMessageExpr(const ObjCMessageExpr *E,
ReturnValueSlot Return = ReturnValueSlot());
/// Retrieves the default cleanup kind for an ARC cleanup.
/// Except under -fobjc-arc-eh, ARC cleanups are normal-only.
CleanupKind getARCCleanupKind() {
return CGM.getCodeGenOpts().ObjCAutoRefCountExceptions
? NormalAndEHCleanup : NormalCleanup;
}
// ARC primitives.
void EmitARCInitWeak(llvm::Value *value, llvm::Value *addr);
void EmitARCDestroyWeak(llvm::Value *addr);
llvm::Value *EmitARCLoadWeak(llvm::Value *addr);
llvm::Value *EmitARCLoadWeakRetained(llvm::Value *addr);
llvm::Value *EmitARCStoreWeak(llvm::Value *value, llvm::Value *addr,
bool ignored);
void EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src);
void EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src);
llvm::Value *EmitARCRetainAutorelease(QualType type, llvm::Value *value);
llvm::Value *EmitARCRetainAutoreleaseNonBlock(llvm::Value *value);
llvm::Value *EmitARCStoreStrong(LValue lvalue, llvm::Value *value,
bool ignored);
llvm::Value *EmitARCStoreStrongCall(llvm::Value *addr, llvm::Value *value,
bool ignored);
llvm::Value *EmitARCRetain(QualType type, llvm::Value *value);
llvm::Value *EmitARCRetainNonBlock(llvm::Value *value);
llvm::Value *EmitARCRetainBlock(llvm::Value *value, bool mandatory);
void EmitARCDestroyStrong(llvm::Value *addr, bool precise);
void EmitARCRelease(llvm::Value *value, bool precise);
llvm::Value *EmitARCAutorelease(llvm::Value *value);
llvm::Value *EmitARCAutoreleaseReturnValue(llvm::Value *value);
llvm::Value *EmitARCRetainAutoreleaseReturnValue(llvm::Value *value);
llvm::Value *EmitARCRetainAutoreleasedReturnValue(llvm::Value *value);
std::pair<LValue,llvm::Value*>
EmitARCStoreAutoreleasing(const BinaryOperator *e);
std::pair<LValue,llvm::Value*>
EmitARCStoreStrong(const BinaryOperator *e, bool ignored);
llvm::Value *EmitObjCThrowOperand(const Expr *expr);
llvm::Value *EmitObjCProduceObject(QualType T, llvm::Value *Ptr);
llvm::Value *EmitObjCConsumeObject(QualType T, llvm::Value *Ptr);
llvm::Value *EmitObjCExtendObjectLifetime(QualType T, llvm::Value *Ptr);
llvm::Value *EmitARCExtendBlockObject(const Expr *expr);
llvm::Value *EmitARCRetainScalarExpr(const Expr *expr);
llvm::Value *EmitARCRetainAutoreleaseScalarExpr(const Expr *expr);
static Destroyer destroyARCStrongImprecise;
static Destroyer destroyARCStrongPrecise;
static Destroyer destroyARCWeak;
void EmitObjCAutoreleasePoolPop(llvm::Value *Ptr);
llvm::Value *EmitObjCAutoreleasePoolPush();
llvm::Value *EmitObjCMRRAutoreleasePoolPush();
void EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr);
void EmitObjCMRRAutoreleasePoolPop(llvm::Value *Ptr);
/// EmitReferenceBindingToExpr - Emits a reference binding to the passed in
/// expression. Will emit a temporary variable if E is not an LValue.
RValue EmitReferenceBindingToExpr(const Expr* E,
const NamedDecl *InitializedDecl);
//===--------------------------------------------------------------------===//
// Expression Emission
//===--------------------------------------------------------------------===//
// Expressions are broken into three classes: scalar, complex, aggregate.
/// EmitScalarExpr - Emit the computation of the specified expression of LLVM
/// scalar type, returning the result.
llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false);
/// EmitScalarConversion - Emit a conversion from the specified type to the
/// specified destination type, both of which are LLVM scalar types.
llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy,
QualType DstTy);
/// EmitComplexToScalarConversion - Emit a conversion from the specified
/// complex type to the specified destination type, where the destination type
/// is an LLVM scalar type.
llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy,
QualType DstTy);
/// EmitAggExpr - Emit the computation of the specified expression
/// of aggregate type. The result is computed into the given slot,
/// which may be null to indicate that the value is not needed.
void EmitAggExpr(const Expr *E, AggValueSlot AS);
/// EmitAggExprToLValue - Emit the computation of the specified expression of
/// aggregate type into a temporary LValue.
LValue EmitAggExprToLValue(const Expr *E);
/// EmitGCMemmoveCollectable - Emit special API for structs with object
/// pointers.
void EmitGCMemmoveCollectable(llvm::Value *DestPtr, llvm::Value *SrcPtr,
QualType Ty);
/// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
/// make sure it survives garbage collection until this point.
void EmitExtendGCLifetime(llvm::Value *object);
/// EmitComplexExpr - Emit the computation of the specified expression of
/// complex type, returning the result.
ComplexPairTy EmitComplexExpr(const Expr *E,
bool IgnoreReal = false,
bool IgnoreImag = false);
/// EmitComplexExprIntoAddr - Emit the computation of the specified expression
/// of complex type, storing into the specified Value*.
void EmitComplexExprIntoAddr(const Expr *E, llvm::Value *DestAddr,
bool DestIsVolatile);
/// StoreComplexToAddr - Store a complex number into the specified address.
void StoreComplexToAddr(ComplexPairTy V, llvm::Value *DestAddr,
bool DestIsVolatile);
/// LoadComplexFromAddr - Load a complex number from the specified address.
ComplexPairTy LoadComplexFromAddr(llvm::Value *SrcAddr, bool SrcIsVolatile);
/// CreateStaticVarDecl - Create a zero-initialized LLVM global for
/// a static local variable.
llvm::GlobalVariable *CreateStaticVarDecl(const VarDecl &D,
const char *Separator,
llvm::GlobalValue::LinkageTypes Linkage);
/// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
/// global variable that has already been created for it. If the initializer
/// has a different type than GV does, this may free GV and return a different
/// one. Otherwise it just returns GV.
llvm::GlobalVariable *
AddInitializerToStaticVarDecl(const VarDecl &D,
llvm::GlobalVariable *GV);
/// EmitCXXGlobalVarDeclInit - Create the initializer for a C++
/// variable with global storage.
void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr,
bool PerformInit);
/// Call atexit() with a function that passes the given argument to
/// the given function.
void registerGlobalDtorWithAtExit(llvm::Constant *fn, llvm::Constant *addr);
/// Emit code in this function to perform a guarded variable
/// initialization. Guarded initializations are used when it's not
/// possible to prove that an initialization will be done exactly
/// once, e.g. with a static local variable or a static data member
/// of a class template.
void EmitCXXGuardedInit(const VarDecl &D, llvm::GlobalVariable *DeclPtr,
bool PerformInit);
/// GenerateCXXGlobalInitFunc - Generates code for initializing global
/// variables.
void GenerateCXXGlobalInitFunc(llvm::Function *Fn,
llvm::Constant **Decls,
unsigned NumDecls);
/// GenerateCXXGlobalDtorsFunc - Generates code for destroying global
/// variables.
void GenerateCXXGlobalDtorsFunc(llvm::Function *Fn,
const std::vector<std::pair<llvm::WeakVH,
llvm::Constant*> > &DtorsAndObjects);
void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
const VarDecl *D,
llvm::GlobalVariable *Addr,
bool PerformInit);
void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest);
void EmitSynthesizedCXXCopyCtor(llvm::Value *Dest, llvm::Value *Src,
const Expr *Exp);
void enterFullExpression(const ExprWithCleanups *E) {
if (E->getNumObjects() == 0) return;
enterNonTrivialFullExpression(E);
}
void enterNonTrivialFullExpression(const ExprWithCleanups *E);
void EmitCXXThrowExpr(const CXXThrowExpr *E);
void EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Dest);
RValue EmitAtomicExpr(AtomicExpr *E, llvm::Value *Dest = 0);
//===--------------------------------------------------------------------===//
// Annotations Emission
//===--------------------------------------------------------------------===//
/// Emit an annotation call (intrinsic or builtin).
llvm::Value *EmitAnnotationCall(llvm::Value *AnnotationFn,
llvm::Value *AnnotatedVal,
llvm::StringRef AnnotationStr,
SourceLocation Location);
/// Emit local annotations for the local variable V, declared by D.
void EmitVarAnnotations(const VarDecl *D, llvm::Value *V);
/// Emit field annotations for the given field & value. Returns the
/// annotation result.
llvm::Value *EmitFieldAnnotations(const FieldDecl *D, llvm::Value *V);
//===--------------------------------------------------------------------===//
// Internal Helpers
//===--------------------------------------------------------------------===//
/// ContainsLabel - Return true if the statement contains a label in it. If
/// this statement is not executed normally, it not containing a label means
/// that we can just remove the code.
static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false);
/// containsBreak - Return true if the statement contains a break out of it.
/// If the statement (recursively) contains a switch or loop with a break
/// inside of it, this is fine.
static bool containsBreak(const Stmt *S);
/// ConstantFoldsToSimpleInteger - If the specified expression does not fold
/// to a constant, or if it does but contains a label, return false. If it
/// constant folds return true and set the boolean result in Result.
bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result);
/// ConstantFoldsToSimpleInteger - If the specified expression does not fold
/// to a constant, or if it does but contains a label, return false. If it
/// constant folds return true and set the folded value.
bool ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &Result);
/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an
/// if statement) to the specified blocks. Based on the condition, this might
/// try to simplify the codegen of the conditional based on the branch.
void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock,
llvm::BasicBlock *FalseBlock);
/// \brief Emit a description of a type in a format suitable for passing to
/// a runtime sanitizer handler.
llvm::Constant *EmitCheckTypeDescriptor(QualType T);
/// \brief Convert a value into a format suitable for passing to a runtime
/// sanitizer handler.
llvm::Value *EmitCheckValue(llvm::Value *V);
/// \brief Emit a description of a source location in a format suitable for
/// passing to a runtime sanitizer handler.
llvm::Constant *EmitCheckSourceLocation(SourceLocation Loc);
/// \brief Create a basic block that will call the trap intrinsic, and emit a
/// conditional branch to it.
void EmitCheck(llvm::Value *Checked, StringRef CheckName,
llvm::ArrayRef<llvm::Constant *> StaticArgs,
llvm::ArrayRef<llvm::Value *> DynamicArgs);
/// EmitCallArg - Emit a single call argument.
void EmitCallArg(CallArgList &args, const Expr *E, QualType ArgType);
/// EmitDelegateCallArg - We are performing a delegate call; that
/// is, the current function is delegating to another one. Produce
/// a r-value suitable for passing the given parameter.
void EmitDelegateCallArg(CallArgList &args, const VarDecl *param);
/// SetFPAccuracy - Set the minimum required accuracy of the given floating
/// point operation, expressed as the maximum relative error in ulp.
void SetFPAccuracy(llvm::Value *Val, float Accuracy);
private:
llvm::MDNode *getRangeForLoadFromType(QualType Ty);
void EmitReturnOfRValue(RValue RV, QualType Ty);
/// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty
/// from function arguments into \arg Dst. See ABIArgInfo::Expand.
///
/// \param AI - The first function argument of the expansion.
/// \return The argument following the last expanded function
/// argument.
llvm::Function::arg_iterator
ExpandTypeFromArgs(QualType Ty, LValue Dst,
llvm::Function::arg_iterator AI);
/// ExpandTypeToArgs - Expand an RValue \arg Src, with the LLVM type for \arg
/// Ty, into individual arguments on the provided vector \arg Args. See
/// ABIArgInfo::Expand.
void ExpandTypeToArgs(QualType Ty, RValue Src,
SmallVector<llvm::Value*, 16> &Args,
llvm::FunctionType *IRFuncTy);
llvm::Value* EmitAsmInput(const TargetInfo::ConstraintInfo &Info,
const Expr *InputExpr, std::string &ConstraintStr);
llvm::Value* EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info,
LValue InputValue, QualType InputType,
std::string &ConstraintStr);
/// EmitCallArgs - Emit call arguments for a function.
/// The CallArgTypeInfo parameter is used for iterating over the known
/// argument types of the function being called.
template<typename T>
void EmitCallArgs(CallArgList& Args, const T* CallArgTypeInfo,
CallExpr::const_arg_iterator ArgBeg,
CallExpr::const_arg_iterator ArgEnd) {
CallExpr::const_arg_iterator Arg = ArgBeg;
// First, use the argument types that the type info knows about
if (CallArgTypeInfo) {
for (typename T::arg_type_iterator I = CallArgTypeInfo->arg_type_begin(),
E = CallArgTypeInfo->arg_type_end(); I != E; ++I, ++Arg) {
assert(Arg != ArgEnd && "Running over edge of argument list!");
QualType ArgType = *I;
#ifndef NDEBUG
QualType ActualArgType = Arg->getType();
if (ArgType->isPointerType() && ActualArgType->isPointerType()) {
QualType ActualBaseType =
ActualArgType->getAs<PointerType>()->getPointeeType();
QualType ArgBaseType =
ArgType->getAs<PointerType>()->getPointeeType();
if (ArgBaseType->isVariableArrayType()) {
if (const VariableArrayType *VAT =
getContext().getAsVariableArrayType(ActualBaseType)) {
if (!VAT->getSizeExpr())
ActualArgType = ArgType;
}
}
}
assert(getContext().getCanonicalType(ArgType.getNonReferenceType()).
getTypePtr() ==
getContext().getCanonicalType(ActualArgType).getTypePtr() &&
"type mismatch in call argument!");
#endif
EmitCallArg(Args, *Arg, ArgType);
}
// Either we've emitted all the call args, or we have a call to a
// variadic function.
assert((Arg == ArgEnd || CallArgTypeInfo->isVariadic()) &&
"Extra arguments in non-variadic function!");
}
// If we still have any arguments, emit them using the type of the argument.
for (; Arg != ArgEnd; ++Arg)
EmitCallArg(Args, *Arg, Arg->getType());
}
const TargetCodeGenInfo &getTargetHooks() const {
return CGM.getTargetCodeGenInfo();
}
void EmitDeclMetadata();
CodeGenModule::ByrefHelpers *
buildByrefHelpers(llvm::StructType &byrefType,
const AutoVarEmission &emission);
void AddObjCARCExceptionMetadata(llvm::Instruction *Inst);
/// GetPointeeAlignment - Given an expression with a pointer type, emit the
/// value and compute our best estimate of the alignment of the pointee.
std::pair<llvm::Value*, unsigned> EmitPointerWithAlignment(const Expr *Addr);
};
/// Helper class with most of the code for saving a value for a
/// conditional expression cleanup.
struct DominatingLLVMValue {
typedef llvm::PointerIntPair<llvm::Value*, 1, bool> saved_type;
/// Answer whether the given value needs extra work to be saved.
static bool needsSaving(llvm::Value *value) {
// If it's not an instruction, we don't need to save.
if (!isa<llvm::Instruction>(value)) return false;
// If it's an instruction in the entry block, we don't need to save.
llvm::BasicBlock *block = cast<llvm::Instruction>(value)->getParent();
return (block != &block->getParent()->getEntryBlock());
}
/// Try to save the given value.
static saved_type save(CodeGenFunction &CGF, llvm::Value *value) {
if (!needsSaving(value)) return saved_type(value, false);
// Otherwise we need an alloca.
llvm::Value *alloca =
CGF.CreateTempAlloca(value->getType(), "cond-cleanup.save");
CGF.Builder.CreateStore(value, alloca);
return saved_type(alloca, true);
}
static llvm::Value *restore(CodeGenFunction &CGF, saved_type value) {
if (!value.getInt()) return value.getPointer();
return CGF.Builder.CreateLoad(value.getPointer());
}
};
/// A partial specialization of DominatingValue for llvm::Values that
/// might be llvm::Instructions.
template <class T> struct DominatingPointer<T,true> : DominatingLLVMValue {
typedef T *type;
static type restore(CodeGenFunction &CGF, saved_type value) {
return static_cast<T*>(DominatingLLVMValue::restore(CGF, value));
}
};
/// A specialization of DominatingValue for RValue.
template <> struct DominatingValue<RValue> {
typedef RValue type;
class saved_type {
enum Kind { ScalarLiteral, ScalarAddress, AggregateLiteral,
AggregateAddress, ComplexAddress };
llvm::Value *Value;
Kind K;
saved_type(llvm::Value *v, Kind k) : Value(v), K(k) {}
public:
static bool needsSaving(RValue value);
static saved_type save(CodeGenFunction &CGF, RValue value);
RValue restore(CodeGenFunction &CGF);
// implementations in CGExprCXX.cpp
};
static bool needsSaving(type value) {
return saved_type::needsSaving(value);
}
static saved_type save(CodeGenFunction &CGF, type value) {
return saved_type::save(CGF, value);
}
static type restore(CodeGenFunction &CGF, saved_type value) {
return value.restore(CGF);
}
};
} // end namespace CodeGen
} // end namespace clang
#endif
| [
"[email protected]"
] | |
b1683bf61447696310682d0061d76970656c2932 | 7db6ed1cc1a20fb7be4113c96fc6e242cc15338f | /src/Visualisation/renderThreadFunc.cpp | 411680df31b8739a84f824a51fdc75ebe44edccb | [] | no_license | PeterMaltby/VRPSolver | a576a77f63eba4c925cebff1f3466b334e9d328c | 97be813a6797b440cf24aa80786626a06d27a418 | refs/heads/master | 2023-06-24T21:02:49.446859 | 2021-07-25T19:23:06 | 2021-07-25T19:23:06 | 350,971,732 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,125 | cpp | #include "renderThreadFunc.h"
void renderThread(std::shared_ptr<RenderData>_renderData, Problem& problem, float windowScale, int moniter, float drawScale) {
std::shared_ptr<RenderData> renderData = _renderData;
Window window("hello World!", windowScale, moniter);
//how much points scale from default %
float pointsRange = 0.5f;
Color blue = { 1.0f,1.0f,1.0f,1.0f };
Color red = { 1.0f,1.0f,1.0f,1.0f };
/*---Create renderer and translate data from problem------*/
float minPointSize = drawScale - (drawScale * pointsRange);
//sends all points coords.
Renderer render = Renderer(problem.getCoords(), renderData, { 0.0f,0.0f,0.0f,1.0f });
//index 0 is distribution point.
render.pointsProperties(0, blue, drawScale + (drawScale * pointsRange));
std::vector<DeliveryPoint> p = problem.getPointsData();
//user index 1 as start to ignore distribution index.
double max = p[1].qauntitiy;
double min = p[1].qauntitiy;
for (std::vector<DeliveryPoint>::const_iterator it = p.begin()+2; it != p.end(); it++) {
max = (max < it->qauntitiy) ? it->qauntitiy : max;
min = (min > it->qauntitiy) ? it->qauntitiy : min;
}
//fix this!!!!!!!!!!!!!!!!!!!!!!!
//finds how many point size availible;
int bins = static_cast<int>(ceil((drawScale + (drawScale * pointsRange)) - (drawScale - (drawScale * pointsRange))));
int step = static_cast<int>(ceil((max - min) / bins));
int tmpMax = static_cast<int> (min + step);
std::vector<unsigned int> tmpBin;
for (int x = 0; x <= bins; x++) {
tmpBin.clear();
for (std::vector<DeliveryPoint>::const_iterator it = p.begin(); it != p.end(); it++) {
if (it->qauntitiy >= min && it->qauntitiy <= tmpMax) tmpBin.push_back(it->id);
}
if (!tmpBin.empty()) render.pointsProperties(tmpBin, red, minPointSize + x);
min += step;
tmpMax += step;
}
std::vector<unsigned int> bois = { 2,5,8,1,2 };
_renderData->AddLine(bois, { 0.0f, 0.0f, 0.0f, 1.0f }, minPointSize);
problem.printall();
window.Run(&render);
} | [
"[email protected]"
] | |
891c4472e75d7ebcabaf0c85f6ee0c7627265f42 | 45bc2f1e36e4ff30b4db42ca1aa0d3035e95f6fa | /EntityEditorQt/GeneratedFiles/ui_dialog.h | 11a73af6ad2a2414791b332f036efd85d4e60c99 | [] | no_license | Norcinu/EntityEditorQt | fce52204454dd738d1411f8edd9908ced0de348a | c0a3945f06617b6745ae23b06922d58661a44a69 | refs/heads/master | 2020-05-29T16:33:39.881716 | 2011-06-11T00:46:39 | 2011-06-11T00:46:39 | 1,878,679 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,226 | h | /********************************************************************************
** Form generated from reading UI file 'dialog.ui'
**
** Created: Mon 28. Mar 23:32:02 2011
** by: Qt User Interface Compiler version 4.7.1
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_DIALOG_H
#define UI_DIALOG_H
#include <QtCore/QVariant>
#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QButtonGroup>
#include <QtGui/QDialog>
#include <QtGui/QDialogButtonBox>
#include <QtGui/QGroupBox>
#include <QtGui/QHeaderView>
#include <QtGui/QLabel>
#include <QtGui/QRadioButton>
QT_BEGIN_NAMESPACE
class Ui_Dialog
{
public:
QDialogButtonBox *buttonBox;
QGroupBox *groupBox;
QLabel *label;
QRadioButton *rad2DEntity;
QRadioButton *rad3DEntity;
void setupUi(QDialog *Dialog)
{
if (Dialog->objectName().isEmpty())
Dialog->setObjectName(QString::fromUtf8("Dialog"));
Dialog->setWindowModality(Qt::ApplicationModal);
Dialog->resize(232, 124);
Dialog->setModal(true);
buttonBox = new QDialogButtonBox(Dialog);
buttonBox->setObjectName(QString::fromUtf8("buttonBox"));
buttonBox->setGeometry(QRect(-120, 90, 341, 32));
buttonBox->setOrientation(Qt::Horizontal);
buttonBox->setStandardButtons(QDialogButtonBox::Cancel|QDialogButtonBox::Ok);
groupBox = new QGroupBox(Dialog);
groupBox->setObjectName(QString::fromUtf8("groupBox"));
groupBox->setGeometry(QRect(10, 10, 211, 80));
label = new QLabel(groupBox);
label->setObjectName(QString::fromUtf8("label"));
label->setGeometry(QRect(10, 20, 111, 16));
rad2DEntity = new QRadioButton(groupBox);
rad2DEntity->setObjectName(QString::fromUtf8("rad2DEntity"));
rad2DEntity->setGeometry(QRect(10, 40, 82, 17));
rad3DEntity = new QRadioButton(groupBox);
rad3DEntity->setObjectName(QString::fromUtf8("rad3DEntity"));
rad3DEntity->setGeometry(QRect(110, 40, 82, 17));
retranslateUi(Dialog);
QObject::connect(buttonBox, SIGNAL(accepted()), Dialog, SLOT(accept()));
QObject::connect(buttonBox, SIGNAL(rejected()), Dialog, SLOT(reject()));
QMetaObject::connectSlotsByName(Dialog);
} // setupUi
void retranslateUi(QDialog *Dialog)
{
Dialog->setWindowTitle(QApplication::translate("Dialog", "New Entity Selection", 0, QApplication::UnicodeUTF8));
groupBox->setTitle(QApplication::translate("Dialog", "Selection", 0, QApplication::UnicodeUTF8));
label->setText(QApplication::translate("Dialog", "Please select 2D or 3D", 0, QApplication::UnicodeUTF8));
rad2DEntity->setText(QApplication::translate("Dialog", "2D", 0, QApplication::UnicodeUTF8));
rad3DEntity->setText(QApplication::translate("Dialog", "3D", 0, QApplication::UnicodeUTF8));
} // retranslateUi
};
namespace Ui {
class Dialog: public Ui_Dialog {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_DIALOG_H
| [
"[email protected]"
] | |
7e607563eff9bc76bb458210842f6e7e6ecaf051 | 75452de12ec9eea346e3b9c7789ac0abf3eb1d73 | /src/camera/bin/camera-gym/main.cc | b787dc66ff7ef918484cc2692ef76865aa8e8dbe | [
"BSD-3-Clause"
] | permissive | oshunter/fuchsia | c9285cc8c14be067b80246e701434bbef4d606d1 | 2196fc8c176d01969466b97bba3f31ec55f7767b | refs/heads/master | 2022-12-22T11:30:15.486382 | 2020-08-16T03:41:23 | 2020-08-16T03:41:23 | 287,920,017 | 2 | 2 | BSD-3-Clause | 2022-12-16T03:30:27 | 2020-08-16T10:18:30 | C++ | UTF-8 | C++ | false | false | 5,236 | cc | // Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <fuchsia/camera3/cpp/fidl.h>
#include <fuchsia/sysmem/cpp/fidl.h>
#include <fuchsia/ui/policy/cpp/fidl.h>
#include <fuchsia/ui/scenic/cpp/fidl.h>
#include <lib/async-loop/cpp/loop.h>
#include <lib/async-loop/default.h>
#include <lib/async/cpp/task.h>
#include <lib/fit/bridge.h>
#include <lib/fit/single_threaded_executor.h>
#include <lib/fzl/vmo-mapper.h>
#include <lib/sys/cpp/component_context.h>
#include <lib/syslog/cpp/log_settings.h>
#include <lib/syslog/cpp/macros.h>
#include <set>
#include "src/camera/bin/camera-gym/buffer_collage.h"
#include "src/camera/bin/camera-gym/lifecycle_impl.h"
#include "src/camera/bin/camera-gym/stream_cycler.h"
int main(int argc, char* argv[]) {
syslog::SetLogSettings({.min_log_level = CAMERA_MIN_LOG_LEVEL}, {"camera-gym"});
async::Loop loop(&kAsyncLoopConfigAttachToCurrentThread);
auto context = sys::ComponentContext::CreateAndServeOutgoingDirectory();
// Connect to required services for the collage.
fuchsia::sysmem::AllocatorHandle allocator;
zx_status_t status = context->svc()->Connect(allocator.NewRequest());
if (status != ZX_OK) {
FX_PLOGS(ERROR, status) << "Failed to request Allocator service.";
return EXIT_FAILURE;
}
fuchsia::ui::scenic::ScenicHandle scenic;
status = context->svc()->Connect(scenic.NewRequest());
if (status != ZX_OK) {
FX_PLOGS(ERROR, status) << "Failed to request Scenic service.";
return EXIT_FAILURE;
}
fuchsia::ui::policy::PresenterHandle presenter;
context->svc()->Connect(presenter.NewRequest());
if (status != ZX_OK) {
FX_PLOGS(ERROR, status) << "Failed to request Presenter service.";
return EXIT_FAILURE;
}
// Create the collage.
auto collage_result = camera::BufferCollage::Create(std::move(scenic), std::move(allocator),
std::move(presenter), [&] { loop.Quit(); });
if (collage_result.is_error()) {
FX_PLOGS(ERROR, collage_result.error()) << "Failed to create BufferCollage.";
return EXIT_FAILURE;
}
auto collage = collage_result.take_value();
// Connect to required services for the cycler.
fuchsia::camera3::DeviceWatcherHandle watcher;
status = context->svc()->Connect(watcher.NewRequest());
if (status != ZX_OK) {
FX_PLOGS(ERROR, status) << "Failed to request DeviceWatcher service.";
return EXIT_FAILURE;
}
allocator = nullptr;
status = context->svc()->Connect(allocator.NewRequest());
if (status != ZX_OK) {
FX_PLOGS(ERROR, status) << "Failed to request Allocator service.";
return EXIT_FAILURE;
}
// Create the cycler and attach it to the collage.
auto cycler_result = camera::StreamCycler::Create(std::move(watcher), std::move(allocator));
if (cycler_result.is_error()) {
FX_PLOGS(ERROR, cycler_result.error()) << "Failed to create StreamCycler.";
return EXIT_FAILURE;
}
auto cycler = cycler_result.take_value();
bool device_muted = false;
std::set<uint32_t> collection_ids;
camera::StreamCycler::AddCollectionHandler add_collection_handler =
[&](fuchsia::sysmem::BufferCollectionTokenHandle token,
fuchsia::sysmem::ImageFormat_2 image_format, std::string description) -> uint32_t {
auto result = fit::run_single_threaded(
collage->AddCollection(std::move(token), image_format, description));
if (result.is_error()) {
FX_LOGS(FATAL) << "Failed to add collection to collage.";
return 0;
}
collection_ids.insert(result.value());
return result.value();
};
camera::StreamCycler::RemoveCollectionHandler remove_collection_handler = [&](uint32_t id) {
collection_ids.erase(id);
collage->RemoveCollection(id);
};
camera::StreamCycler::ShowBufferHandler show_buffer_handler =
[&](uint32_t collection_id, uint32_t buffer_index, zx::eventpair release_fence,
std::optional<fuchsia::math::RectF> subregion) {
collage->PostShowBuffer(collection_id, buffer_index, std::move(release_fence),
std::move(subregion));
if (!device_muted) {
// Only make the collection visible after we have shown an unmuted frame.
collage->PostSetCollectionVisibility(collection_id, true);
}
};
camera::StreamCycler::MuteStateHandler mute_handler = [&](bool muted) {
collage->PostSetMuteIconVisibility(muted);
if (muted) {
// Immediately hide all collections on mute.
for (auto id : collection_ids) {
collage->PostSetCollectionVisibility(id, false);
}
}
device_muted = muted;
};
cycler->SetHandlers(std::move(add_collection_handler), std::move(remove_collection_handler),
std::move(show_buffer_handler), std::move(mute_handler));
// Publish the view service.
context->outgoing()->AddPublicService(collage->GetHandler());
// Publish a handler for the Lifecycle protocol that cleanly quits the component.
LifecycleImpl lifecycle([&] { loop.Quit(); });
context->outgoing()->AddPublicService(lifecycle.GetHandler());
loop.Run();
return EXIT_SUCCESS;
}
| [
"[email protected]"
] | |
a675aae497f97639557e1a27c03dda45d98c84eb | 9fdc1cbdda5fca9a916388e81dcaf7fe3c44c17b | /src/chrono_vehicle/wheeled_vehicle/vehicle/WheeledVehicle.cpp | 333d78cad0b908db643a5f7f545e51dc466a9c09 | [
"BSD-3-Clause"
] | permissive | StefanoZaghi1987/ChronoWheelDesigner | 473c7b4b7177532c6c0b6a7e04df03c85678c4ab | 48b0235565e6c1c08ce8b5a742bf92b0fcbd70f0 | refs/heads/master | 2021-01-22T00:29:12.900606 | 2018-01-26T15:20:01 | 2018-01-26T15:20:01 | 102,189,611 | 1 | 0 | BSD-3-Clause | 2018-01-26T15:20:02 | 2017-09-02T10:38:38 | C++ | UTF-8 | C++ | false | false | 18,500 | cpp | // =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban
// =============================================================================
//
// Wheeled vehicle model constructed from a JSON specification file
//
// =============================================================================
#include <cstdio>
#include "chrono/assets/ChSphereShape.h"
#include "chrono/assets/ChCylinderShape.h"
#include "chrono/assets/ChTriangleMeshShape.h"
#include "chrono/assets/ChTexture.h"
#include "chrono/assets/ChColorAsset.h"
#include "chrono/physics/ChGlobal.h"
#include "chrono_vehicle/wheeled_vehicle/vehicle/WheeledVehicle.h"
#include "chrono_vehicle/chassis/RigidChassis.h"
#include "chrono_vehicle/wheeled_vehicle/suspension/DoubleWishbone.h"
#include "chrono_vehicle/wheeled_vehicle/suspension/DoubleWishboneReduced.h"
#include "chrono_vehicle/wheeled_vehicle/suspension/SolidAxle.h"
#include "chrono_vehicle/wheeled_vehicle/suspension/MultiLink.h"
#include "chrono_vehicle/wheeled_vehicle/suspension/MacPhersonStrut.h"
#include "chrono_vehicle/wheeled_vehicle/suspension/SemiTrailingArm.h"
#include "chrono_vehicle/wheeled_vehicle/suspension/ThreeLinkIRS.h"
#include "chrono_vehicle/wheeled_vehicle/antirollbar/AntirollBarRSD.h"
#include "chrono_vehicle/wheeled_vehicle/steering/PitmanArm.h"
#include "chrono_vehicle/wheeled_vehicle/steering/RackPinion.h"
#include "chrono_vehicle/wheeled_vehicle/driveline/ShaftsDriveline2WD.h"
#include "chrono_vehicle/wheeled_vehicle/driveline/ShaftsDriveline4WD.h"
#include "chrono_vehicle/wheeled_vehicle/driveline/SimpleDriveline.h"
#include "chrono_vehicle/wheeled_vehicle/wheel/Wheel.h"
#include "chrono_vehicle/wheeled_vehicle/brake/BrakeSimple.h"
#include "chrono_vehicle/ChVehicleModelData.h"
#include "chrono_thirdparty/rapidjson/document.h"
#include "chrono_thirdparty/rapidjson/filereadstream.h"
using namespace rapidjson;
namespace chrono {
namespace vehicle {
// -----------------------------------------------------------------------------
// These utility functions return a ChVector and a ChQuaternion, respectively,
// from the specified JSON array.
// -----------------------------------------------------------------------------
static ChVector<> loadVector(const Value& a) {
assert(a.IsArray());
assert(a.Size() == 3);
return ChVector<>(a[0u].GetDouble(), a[1u].GetDouble(), a[2u].GetDouble());
}
static ChQuaternion<> loadQuaternion(const Value& a) {
assert(a.IsArray());
assert(a.Size() == 4);
return ChQuaternion<>(a[0u].GetDouble(), a[1u].GetDouble(), a[2u].GetDouble(), a[3u].GetDouble());
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
void WheeledVehicle::LoadChassis(const std::string& filename) {
FILE* fp = fopen(filename.c_str(), "r");
char readBuffer[65536];
FileReadStream is(fp, readBuffer, sizeof(readBuffer));
fclose(fp);
Document d;
d.ParseStream<ParseFlag::kParseCommentsFlag>(is);
// Check that the given file is a chassis specification file.
assert(d.HasMember("Type"));
std::string type = d["Type"].GetString();
assert(type.compare("Chassis") == 0);
// Extract the chassis type.
assert(d.HasMember("Template"));
std::string subtype = d["Template"].GetString();
// Create the steering using the appropriate template.
if (subtype.compare("RigidChassis") == 0) {
m_chassis = std::make_shared<RigidChassis>(d);
}
GetLog() << " Loaded JSON: " << filename.c_str() << "\n";
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
void WheeledVehicle::LoadSteering(const std::string& filename, int which) {
FILE* fp = fopen(filename.c_str(), "r");
char readBuffer[65536];
FileReadStream is(fp, readBuffer, sizeof(readBuffer));
fclose(fp);
Document d;
d.ParseStream<ParseFlag::kParseCommentsFlag>(is);
// Check that the given file is a steering specification file.
assert(d.HasMember("Type"));
std::string type = d["Type"].GetString();
assert(type.compare("Steering") == 0);
// Extract the steering type.
assert(d.HasMember("Template"));
std::string subtype = d["Template"].GetString();
// Create the steering using the appropriate template.
if (subtype.compare("PitmanArm") == 0) {
m_steerings[which] = std::make_shared<PitmanArm>(d);
} else if (subtype.compare("RackPinion") == 0) {
m_steerings[which] = std::make_shared<RackPinion>(d);
}
GetLog() << " Loaded JSON: " << filename.c_str() << "\n";
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
void WheeledVehicle::LoadDriveline(const std::string& filename) {
FILE* fp = fopen(filename.c_str(), "r");
char readBuffer[65536];
FileReadStream is(fp, readBuffer, sizeof(readBuffer));
fclose(fp);
Document d;
d.ParseStream<ParseFlag::kParseCommentsFlag>(is);
// Check that the given file is a driveline specification file.
assert(d.HasMember("Type"));
std::string type = d["Type"].GetString();
assert(type.compare("Driveline") == 0);
// Extract the driveline type.
assert(d.HasMember("Template"));
std::string subtype = d["Template"].GetString();
// Create the driveline using the appropriate template.
if (subtype.compare("ShaftsDriveline2WD") == 0) {
m_driveline = std::make_shared<ShaftsDriveline2WD>(d);
} else if (subtype.compare("ShaftsDriveline4WD") == 0) {
m_driveline = std::make_shared<ShaftsDriveline4WD>(d);
} else if (subtype.compare("SimpleDriveline") == 0) {
m_driveline = std::make_shared<SimpleDriveline>(d);
}
GetLog() << " Loaded JSON: " << filename.c_str() << "\n";
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
void WheeledVehicle::LoadSuspension(const std::string& filename, int axle) {
FILE* fp = fopen(filename.c_str(), "r");
char readBuffer[65536];
FileReadStream is(fp, readBuffer, sizeof(readBuffer));
fclose(fp);
Document d;
d.ParseStream<ParseFlag::kParseCommentsFlag>(is);
// Check that the given file is a suspension specification file.
assert(d.HasMember("Type"));
std::string type = d["Type"].GetString();
assert(type.compare("Suspension") == 0);
// Extract the suspension type.
assert(d.HasMember("Template"));
std::string subtype = d["Template"].GetString();
// Create the suspension using the appropriate template.
if (subtype.compare("DoubleWishbone") == 0) {
m_suspensions[axle] = std::make_shared<DoubleWishbone>(d);
} else if (subtype.compare("DoubleWishboneReduced") == 0) {
m_suspensions[axle] = std::make_shared<DoubleWishboneReduced>(d);
} else if (subtype.compare("SolidAxle") == 0) {
m_suspensions[axle] = std::make_shared<SolidAxle>(d);
} else if (subtype.compare("MultiLink") == 0) {
m_suspensions[axle] = std::make_shared<MultiLink>(d);
} else if (subtype.compare("MacPhersonStrut") == 0) {
m_suspensions[axle] = std::make_shared<MacPhersonStrut>(d);
} else if (subtype.compare("SemiTrailingArm") == 0) {
m_suspensions[axle] = std::make_shared<SemiTrailingArm>(d);
} else if (subtype.compare("ThreeLinkIRS") == 0) {
m_suspensions[axle] = std::make_shared<ThreeLinkIRS>(d);
}
GetLog() << " Loaded JSON: " << filename.c_str() << "\n";
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
void WheeledVehicle::LoadAntirollbar(const std::string& filename) {
FILE* fp = fopen(filename.c_str(), "r");
char readBuffer[65536];
FileReadStream is(fp, readBuffer, sizeof(readBuffer));
fclose(fp);
Document d;
d.ParseStream<ParseFlag::kParseCommentsFlag>(is);
// Check that the given file is an antirollbar specification file.
assert(d.HasMember("Type"));
std::string type = d["Type"].GetString();
assert(type.compare("Antirollbar") == 0);
// Extract the antirollbar type.
assert(d.HasMember("Template"));
std::string subtype = d["Template"].GetString();
if (subtype.compare("AntirollBarRSD") == 0) {
m_antirollbars.push_back(std::make_shared<AntirollBarRSD>(d));
}
GetLog() << " Loaded JSON: " << filename.c_str() << "\n";
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
void WheeledVehicle::LoadWheel(const std::string& filename, int axle, int side) {
FILE* fp = fopen(filename.c_str(), "r");
char readBuffer[65536];
FileReadStream is(fp, readBuffer, sizeof(readBuffer));
fclose(fp);
Document d;
d.ParseStream<ParseFlag::kParseCommentsFlag>(is);
// Check that the given file is a wheel specification file.
assert(d.HasMember("Type"));
std::string type = d["Type"].GetString();
assert(type.compare("Wheel") == 0);
// Extract the wheel type.
assert(d.HasMember("Template"));
std::string subtype = d["Template"].GetString();
// Create the wheel using the appropriate template.
if (subtype.compare("Wheel") == 0) {
m_wheels[2 * axle + side] = std::make_shared<Wheel>(d);
}
GetLog() << " Loaded JSON: " << filename.c_str() << "\n";
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
void WheeledVehicle::LoadBrake(const std::string& filename, int axle, int side) {
FILE* fp = fopen(filename.c_str(), "r");
char readBuffer[65536];
FileReadStream is(fp, readBuffer, sizeof(readBuffer));
fclose(fp);
Document d;
d.ParseStream<ParseFlag::kParseCommentsFlag>(is);
// Check that the given file is a brake specification file.
assert(d.HasMember("Type"));
std::string type = d["Type"].GetString();
assert(type.compare("Brake") == 0);
// Extract the brake type.
assert(d.HasMember("Template"));
std::string subtype = d["Template"].GetString();
// Create the brake using the appropriate template.
if (subtype.compare("BrakeSimple") == 0) {
m_brakes[2 * axle + side] = std::make_shared<BrakeSimple>(d);
}
GetLog() << " Loaded JSON: " << filename.c_str() << "\n";
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
WheeledVehicle::WheeledVehicle(const std::string& filename, ChMaterialSurface::ContactMethod contact_method)
: ChWheeledVehicle("", contact_method) {
Create(filename);
}
WheeledVehicle::WheeledVehicle(ChSystem* system, const std::string& filename) : ChWheeledVehicle("", system) {
Create(filename);
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
void WheeledVehicle::Create(const std::string& filename) {
// -------------------------------------------
// Open and parse the input file
// -------------------------------------------
FILE* fp = fopen(filename.c_str(), "r");
char readBuffer[65536];
FileReadStream is(fp, readBuffer, sizeof(readBuffer));
fclose(fp);
Document d;
d.ParseStream<ParseFlag::kParseCommentsFlag>(is);
// Read top-level data
assert(d.HasMember("Type"));
assert(d.HasMember("Template"));
assert(d.HasMember("Name"));
std::string name = d["Name"].GetString();
std::string type = d["Type"].GetString();
std::string subtype = d["Template"].GetString();
assert(type.compare("Vehicle") == 0);
assert(subtype.compare("WheeledVehicle") == 0);
SetName(name);
// ----------------------------
// Validations of the JSON file
// ----------------------------
assert(d.HasMember("Steering Subsystems"));
assert(d.HasMember("Driveline"));
assert(d.HasMember("Axles"));
assert(d["Axles"].IsArray());
assert(d["Steering Subsystems"].IsArray());
// Extract the number of axles.
m_num_axles = d["Axles"].Size();
// Extract the number of steering subsystems
m_num_strs = d["Steering Subsystems"].Size();
// Resize arrays
m_suspensions.resize(m_num_axles);
m_suspLocations.resize(m_num_axles);
m_suspSteering.resize(m_num_axles, -1);
m_wheels.resize(2 * m_num_axles);
m_brakes.resize(2 * m_num_axles);
m_steerings.resize(m_num_strs);
m_strLocations.resize(m_num_strs);
m_strRotations.resize(m_num_strs);
// -------------------------------------------
// Create the chassis system
// -------------------------------------------
assert(d.HasMember("Chassis"));
{
std::string file_name = d["Chassis"]["Input File"].GetString();
LoadChassis(vehicle::GetDataFile(file_name));
}
// ------------------------------
// Create the steering subsystems
// ------------------------------
for (int i = 0; i < m_num_strs; i++) {
std::string file_name = d["Steering Subsystems"][i]["Input File"].GetString();
LoadSteering(vehicle::GetDataFile(file_name), i);
m_strLocations[i] = loadVector(d["Steering Subsystems"][i]["Location"]);
m_strRotations[i] = loadQuaternion(d["Steering Subsystems"][i]["Orientation"]);
}
// --------------------
// Create the driveline
// --------------------
{
std::string file_name = d["Driveline"]["Input File"].GetString();
LoadDriveline(vehicle::GetDataFile(file_name));
SizeType num_driven_susp = d["Driveline"]["Suspension Indexes"].Size();
m_driven_susp.resize(num_driven_susp);
for (SizeType i = 0; i < num_driven_susp; i++) {
m_driven_susp[i] = d["Driveline"]["Suspension Indexes"][i].GetInt();
}
assert(num_driven_susp == GetDriveline()->GetNumDrivenAxles());
}
// ---------------------------------------------------
// Create the suspension, wheel, and brake subsystems.
// ---------------------------------------------------
for (int i = 0; i < m_num_axles; i++) {
// Suspension
std::string file_name = d["Axles"][i]["Suspension Input File"].GetString();
LoadSuspension(vehicle::GetDataFile(file_name), i);
m_suspLocations[i] = loadVector(d["Axles"][i]["Suspension Location"]);
// Index of steering subsystem (if applicable)
if (d["Axles"][i].HasMember("Steering Index")) {
m_suspSteering[i] = d["Axles"][i]["Steering Index"].GetInt();
}
// Antirollbar (if applicable)
if (d["Axles"][i].HasMember("Antirollbar Input File")) {
assert(m_suspensions[i]->IsIndependent());
assert(d["Axles"][i].HasMember("Antirollbar Location"));
file_name = d["Axles"][i]["Antirollbar Input File"].GetString();
LoadAntirollbar(vehicle::GetDataFile(file_name));
m_arbLocations.push_back(loadVector(d["Axles"][i]["Antirollbar Location"]));
m_arbSuspension.push_back(i);
}
// Left and right wheels
file_name = d["Axles"][i]["Left Wheel Input File"].GetString();
LoadWheel(vehicle::GetDataFile(file_name), i, 0);
file_name = d["Axles"][i]["Right Wheel Input File"].GetString();
LoadWheel(vehicle::GetDataFile(file_name), i, 1);
// Left and right brakes
file_name = d["Axles"][i]["Left Brake Input File"].GetString();
LoadBrake(vehicle::GetDataFile(file_name), i, 0);
file_name = d["Axles"][i]["Right Brake Input File"].GetString();
LoadBrake(vehicle::GetDataFile(file_name), i, 1);
}
GetLog() << "Loaded JSON: " << filename.c_str() << "\n";
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
void WheeledVehicle::Initialize(const ChCoordsys<>& chassisPos, double chassisFwdVel) {
// Invoke base class method to initialize the chassis.
ChWheeledVehicle::Initialize(chassisPos, chassisFwdVel);
// Initialize the steering subsystems.
for (int i = 0; i < m_num_strs; i++) {
m_steerings[i]->Initialize(m_chassis->GetBody(), m_strLocations[i], m_strRotations[i]);
}
// Initialize the suspension, wheel, and brake subsystems.
for (int i = 0; i < m_num_axles; i++) {
if (m_suspSteering[i] >= 0)
m_suspensions[i]->Initialize(m_chassis->GetBody(), m_suspLocations[i],
m_steerings[m_suspSteering[i]]->GetSteeringLink(), m_suspSteering[i]);
else
m_suspensions[i]->Initialize(m_chassis->GetBody(), m_suspLocations[i], m_chassis->GetBody(), -1);
m_wheels[2 * i]->Initialize(m_suspensions[i]->GetSpindle(LEFT));
m_wheels[2 * i + 1]->Initialize(m_suspensions[i]->GetSpindle(RIGHT));
m_brakes[2 * i]->Initialize(m_suspensions[i]->GetRevolute(LEFT));
m_brakes[2 * i + 1]->Initialize(m_suspensions[i]->GetRevolute(RIGHT));
}
// Initialize the antirollbar subsystems.
for (unsigned int i = 0; i < m_antirollbars.size(); i++) {
int j = m_arbSuspension[i];
m_antirollbars[i]->Initialize(m_chassis->GetBody(), m_arbLocations[i], m_suspensions[j]->GetLeftBody(),
m_suspensions[j]->GetRightBody());
}
// Initialize the driveline
m_driveline->Initialize(m_chassis->GetBody(), m_suspensions, m_driven_susp);
}
} // end namespace vehicle
} // end namespace chrono
| [
"[email protected]"
] | |
465e6bee30d74e5c8f8aeacb53bcd34a2e261b92 | be0204c1b95839adee1ad204be022be38e32e2d6 | /BOJ/11506.cpp | b1aac93340e6fe22244ab9c91945f126af70917b | [] | no_license | tlsdorye/Problem-Solving | 507bc8d3cf1865c10067ef2e8eb7cb2ee42e16dd | 5c112d2238bfb1fc092612a76f10c7785ba86c78 | refs/heads/master | 2021-06-12T19:19:19.337092 | 2021-04-23T06:39:43 | 2021-04-23T06:39:43 | 179,432,390 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 72 | cpp | #include <iostream>
using namespace std;
int main()
{
cout << "�";
} | [
"[email protected]"
] | |
c7b96c57b6775b68260636669b16bc72ee5d916c | 2ad6ba1fab44fe95fad95e434007b99f77e724a7 | /EXAM 2/L6/l6p2.cc | 3217e520b44f065b1115852729bb3333833dc659 | [] | no_license | AlexP97/PRO1 | c896dd67e125f1974dc04bbd51df746b57f71cd1 | 1c4b7e6e60fd04521026a206c980a386eb1da365 | refs/heads/master | 2020-03-23T13:29:54.684977 | 2018-07-19T19:28:05 | 2018-07-19T19:28:05 | 141,621,834 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 445 | cc | #include <iostream>
using namespace std;
int main() {
int nombre;
while(cin >> nombre) {
int seguent;
int sumain = 0;
int sumafin = 0;
bool acaba1 = false;
for (int i = 1; i <= nombre; i++) {
cin >> seguent;
if (seguent >= 0 and not acaba1) sumain = sumain + seguent;
else acaba1 = true;
if (sumafin + seguent >= 0) sumafin = sumafin + seguent;
else sumafin = 0;
}
cout << sumain << ' ' << sumafin << endl;
}
}
| [
"[email protected]"
] | |
1ed484eb6db569b06665c1d16e2b2096b94acddf | fc833788e798460d3fb153fbb150ea5263daf878 | /boj/1000~1999/1291.cpp | c9653b154077cc70634d86bacde5bdb74dcb582d | [] | no_license | ydk1104/PS | a50afdc4dd15ad1def892368591d4bd1f84e9658 | 2c791b267777252ff4bf48a8f54c98bcdcd64af9 | refs/heads/master | 2021-07-18T08:19:34.671535 | 2020-09-02T17:45:59 | 2020-09-02T17:45:59 | 208,404,564 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 776 | cpp | #include<stdio.h>
int p[3000];
int cnt;
int digit(int N){
int temp=0;
while(N){
temp+=N%10;
N/=10;
}
return temp%2;
}
int im(int N){
int count=0;
for(int i=0; i<cnt; i++){
if(N%p[i]) continue;
count++;
while(!(N%p[i])) N/=p[i];
}
return count%2;
}
int main(void){
int N;
scanf("%d", &N);
// N=1;
// while(N<2700){
int prime[3000] = {0,};
for(int i=4; i<=2700; i+=2) prime[i]=1;
p[cnt++]=2;
for(int i=3; i<=2700; i+=2){
if(prime[i]) continue;
for(int j=3; i*j<=2700; j+=2){
prime[i*j]++;
}
p[cnt++]=i;
}
if(N>5 && digit(N) && !im(N)){
printf("4");
}
else if(N==2 || N==4){
printf("2");
}
else if(N>5 && digit(N)){
printf("1");
}
else if(N!=1 && !im(N)){
printf("2");
}
else{
printf("3");
}
printf("\n");
// N++;
}
| [
"[email protected]"
] | |
432cc9f231bb854642d478745aa4b39828cb07f6 | 8407fb7e3005cfea576aab37175d5113eb783525 | /include/arma/armadillo_bits/fn_eigs_sym.hpp | 68cd7698e5e97966753f5d7f96746993d1f486a9 | [] | no_license | zhipeng93/simrank | 851e0c9be14aa87b871a85692824701b2c140602 | 71818e9e9b8a6da38e6226d72c8823fa13dc3706 | refs/heads/master | 2022-12-29T10:54:46.472963 | 2017-01-02T06:36:50 | 2017-01-02T06:36:50 | 64,645,280 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,953 | hpp | // Copyright (C) 2013-2016 National ICT Australia (NICTA)
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
// -------------------------------------------------------------------
//
// Written by Conrad Sanderson - http://conradsanderson.id.au
// Written by Ryan Curtin
//! \addtogroup fn_eigs_sym
//! @{
//! eigenvalues of symmetric real sparse matrix X
template<typename T1>
arma_warn_unused
inline
Col<typename T1::pod_type>
eigs_sym
(
const SpBase<typename T1::elem_type,T1>& X,
const uword n_eigvals,
const char* form = "lm",
const typename T1::elem_type tol = 0.0,
const typename arma_real_only<typename T1::elem_type>::result* junk = 0
)
{
arma_extra_debug_sigprint();
arma_ignore(junk);
Mat<typename T1::elem_type> eigvec;
Col<typename T1::pod_type > eigval;
const bool status = sp_auxlib::eigs_sym(eigval, eigvec, X, n_eigvals, form, tol);
if(status == false)
{
eigval.reset();
arma_stop_runtime_error("eigs_sym(): decomposition failed");
}
return eigval;
}
//! eigenvalues of symmetric real sparse matrix X
template<typename T1>
inline
bool
eigs_sym
(
Col<typename T1::pod_type >& eigval,
const SpBase<typename T1::elem_type,T1>& X,
const uword n_eigvals,
const char* form = "lm",
const typename T1::elem_type tol = 0.0,
const typename arma_real_only<typename T1::elem_type>::result* junk = 0
)
{
arma_extra_debug_sigprint();
arma_ignore(junk);
Mat<typename T1::elem_type> eigvec;
const bool status = sp_auxlib::eigs_sym(eigval, eigvec, X, n_eigvals, form, tol);
if(status == false)
{
eigval.reset();
arma_debug_warn("eigs_sym(): decomposition failed");
}
return status;
}
//! eigenvalues and eigenvectors of symmetric real sparse matrix X
template<typename T1>
inline
bool
eigs_sym
(
Col<typename T1::pod_type >& eigval,
Mat<typename T1::elem_type>& eigvec,
const SpBase<typename T1::elem_type,T1>& X,
const uword n_eigvals,
const char* form = "lm",
const typename T1::elem_type tol = 0.0,
const typename arma_real_only<typename T1::elem_type>::result* junk = 0
)
{
arma_extra_debug_sigprint();
arma_ignore(junk);
arma_debug_check( void_ptr(&eigval) == void_ptr(&eigvec), "eigs_sym(): paramater 'eigval' is an alias of parameter 'eigvec'" );
const bool status = sp_auxlib::eigs_sym(eigval, eigvec, X, n_eigvals, form, tol);
if(status == false)
{
eigval.reset();
arma_debug_warn("eigs_sym(): decomposition failed");
}
return status;
}
//! @}
| [
"user.name"
] | user.name |
ef00463510c6d1383a4ad4daa4d72c9420a0033c | 6b2acad97d2461a1e9260cb370f12e670473e415 | /tool/ROS/source code/a15_mission_crossmove/src/MissionHandler_CrossMove.h | 3aacefc29fc4f6063c0887f05f293cd918c31a35 | [] | no_license | Liemani/_deprecated_portfolio | 342c0d4e51176168cdbc80bf15478f125b15b120 | a0f91b76c7cc0072230d167d64b87da57246c135 | refs/heads/main | 2023-02-24T10:27:42.218565 | 2021-01-28T12:04:24 | 2021-01-28T12:04:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,088 | h | #ifndef MISSIONHANDLER_CROSSMOVE_H
#define MISSIONHANDLER_CROSSMOVE_H
#include <ros/ros.h>
#include <stdio.h> // getchar()
#include <Model/Drone.h>
#include <Model/GlobalPosition.h>
#include <Model/Mission.h>
#include <Model/Mission_CrossMove.h>
using std::vector;
class Drone;
class MissionPlanner {
// callback function
friend void callWhenPositionChanged(MissionPlanner& planner, Drone& drone);
friend void callWhenAltitudeChanged(MissionPlanner& planner, Drone& drone);
friend void callWhenBearingChanged(MissionPlanner& planner, Drone& drone);
private:
int* pCommand;
std::vector<Drone*> pDrone_vector;
ros::NodeHandle* pNodeHandle;
Mission* mission;
int missionState;
GlobalPosition targetGlobalPosition;
public:
MissionPlanner(int argc, char** argv, ros::NodeHandle* pNodeHandle, int* pCommand);
// get set function
double getTargetLatitude();
double getTargetLongitude();
double getTargetAltitude();
void processCommand();
void doMission();
void debugDescription();
void loop();
};
#endif | [
"[email protected]"
] | |
2a925e7f92ce24747594775416a08962091d38db | 19bb555f6c2c5af14636f03ec4da68c444fae7ad | /Arduino/RFSerialSender/RFSerialSender.ino | 16e5c47f943d752b525499374ba8c4a59eb5a02f | [] | no_license | ImanolGo/NormaLedDresses | 9d26b56cafe6d403e17eb53c9b0d151782900cf9 | 389a1e90d1d1b5f2bbfedfbecb2616453f4d074f | refs/heads/master | 2020-05-23T04:55:30.721703 | 2019-06-03T07:37:50 | 2019-06-03T07:37:50 | 186,641,324 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 627 | ino |
/*
RF Serial Sender
Description:
* Firmware sending Serial changes using the an RF module
Software:
* RFLite
Hardware:
* Arduino Nano
* NRF24L01+ module
created 19 May 2019
This code is under A Creative Commons Attribution/Share-Alike License http://creativecommons.org/licenses/by-sa/4.0/
(2019) by Imanol Gomez
*/
#include "RFManager.h"
#include "SerialManager.h"
RFManager rfManager;
SerialManager serialManager(&rfManager);
RadioPacket radioData;
void setup()
{
serialManager.setup();
rfManager.setup();
}
void loop()
{
rfManager.update();
serialManager.update();
}
| [
"[email protected]"
] | |
ab29ad8ce90aac2d8cd0d4518098117ea27203db | f7b28c627ee3cc49bea55025def618e9184eea56 | /sources/cb_abort.h | 098b0464e5a27998be6cc9abd42a723b3f4f6989 | [] | no_license | CamielBouchier/cb_find_duplicates | 0b0d638b63a1dace2fdda444ac7448664df595a7 | 0b036bec2979d506d06d0fae8721d45bc63427ae | refs/heads/main | 2023-03-13T02:27:55.382151 | 2021-02-28T14:23:48 | 2021-02-28T14:23:48 | 337,198,788 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,018 | h | //;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
//
// $BeginLicense$
//
// (C) 2015-2021 by Camiel Bouchier ([email protected])
//
// This file is part of cb_find_duplicates.
// All rights reserved.
// You are granted a non-exclusive and non-transferable license to use this
// software for personal or internal business purposes.
//
// THIS SOFTWARE IS PROVIDED "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL Camiel Bouchier BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// $EndLicense$
//
//;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#pragma once
#include <QDesktopServices>
#include <QMessageBox>
#include <QtCore>
#include "cb_log.h"
#define ABORT(msg) \
{ \
qCritical() << (msg) << Qt::endl; \
QMessageBox::critical(nullptr, QObject::tr("Aborting"), (msg)); \
QDesktopServices::openUrl(QUrl(cb_log::m_logfile_name, QUrl::TolerantMode)); \
abort(); \
}
//;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
// vim: syntax=cpp ts=4 sw=4 sts=4 sr et columns=100
| [
"[email protected]"
] | |
36f2b1ec50e9a8f6a2b5b37857a641d0127d60af | df8e99739d3519e01cd98b00810df08da14b3a55 | /PipelineComponent/ScreenSpaceReflection.h | 71c205d7c3f5d4a2255099138d248465eb1b9ce5 | [] | no_license | Yuanzan/Virtual-Engine | 21e1bf13fe973c3a57537a10e99831e365979fc8 | 0c06d26399dbe73b163c5a40d2e0aeb097246087 | refs/heads/master | 2022-09-10T21:18:47.073078 | 2020-05-24T08:37:08 | 2020-05-24T08:37:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 23,077 | h | #pragma once
#include "PipelineComponent.h"
#include "../Singleton/ShaderID.h"
#include "../Singleton/ShaderCompiler.h"
#include "../Singleton/PSOContainer.h"
#include "../RenderComponent/RenderComponentInclude.h"
#include "../RenderComponent/ReflectionProbe.h"
#include "../Singleton/ShaderCompiler.h"
#include "../Singleton/ShaderID.h"
#include "../Common/Camera.h"
#include "../Common/RingQueue.h"
#include "../ResourceManagement/AssetDatabase.h"
#include "../CJsonObject/CJsonObject.hpp"
using namespace Math;
struct SSRParameterDescriptor
{
int NumRays;
int NumSteps;
float BRDFBias;
float Fadeness;
float RoughnessDiscard;
};
struct SVGFParameterDescriptor
{
int NumSpatial;
float SpatialRadius;
float TemporalScale;
float TemporalWeight;
/*float BilateralRadius;
float BilateralColorWeight;
float BilateralDepthWeight;
float BilateralNormalWeight;*/
};
struct SVGFInputDescriptor
{
Vector4 Resolution;
Matrix4 Matrix_PrevViewProj;
Matrix4 Matrix_InvProj;
Matrix4 Matrix_ViewProj;
Matrix4 Matrix_InvViewProj;
Matrix4 Matrix_WorldToView;
int FrameIndex;
uint SRV_SceneDepth;
uint SRV_GBufferMotion;
uint SRV_GBufferNormal;
uint SRV_GBufferRoughness;
};
struct SSR_Params_Struct
{
float4 SSR_TraceResolution;
float4 SVGF_TemporalSize;
float4 SVGF_SpatialSize;
float4 SVGF_BilateralSize;
uint2 _RayTraceResolution;
uint2 _PostResolution;
float SVGF_SpatialRadius;
float SSR_BRDFBias;
float SSR_Thickness;
float SSR_Fadeness;
float SSR_RoughnessDiscard;
float ColorPyramidNumLOD;
float SVGF_TemporalScale;
float SVGF_TemporalWeight;
float SVGF_BilateralRadius;
float SVGF_ColorWeight;
float SVGF_NormalWeight;
float SVGF_DepthWeight;
int SSR_NumRays;
int SSR_NumSteps;
int SSR_FrameIndex;
int SVGF_FrameIndex;
};
struct SSRShaderID
{
/*
int NumRays;
int NumSteps;
int FrameIndex;
int BRDFBias;
int Fadeness;
int TraceResolution;
int RoughnessDiscard;
int Matrix_Proj;
int Matrix_InvProj;
int Matrix_InvViewProj;
int Matrix_WorldToView;*/
/* int SRV_Ranking_Tile = ShaderID::PropertyToID("SRV_Ranking_Tile");
int SRV_Scrambled_Tile = ShaderID::PropertyToID("SRV_Scrambled_Tile");
int SRV_Scrambled_Owen = ShaderID::PropertyToID("SRV_Scrambled_Owen");
int SRV_Scrambled_Noise = ShaderID::PropertyToID("SRV_Scrambled_Noise");*/
int SRV_PyramidColor = ShaderID::PropertyToID("SRV_PyramidColor");
int SRV_PyramidDepth = ShaderID::PropertyToID("SRV_PyramidDepth");
int SRV_SceneDepth = ShaderID::PropertyToID("SRV_SceneDepth");
int SRV_GBufferNormal = ShaderID::PropertyToID("SRV_GBufferNormal");
int SRV_GBufferRoughness = ShaderID::PropertyToID("SRV_GBufferRoughness");
int UAV_ReflectionUVWPDF = ShaderID::PropertyToID("UAV_ReflectionUWVPDF");
int UAV_ReflectionColorMask = ShaderID::PropertyToID("UAV_ReflectionColorMask");
int SSR_Params = ShaderID::PropertyToID("SSR_Params");
};
struct SVGF_SpatialShaderID
{
int FrameIndex = ShaderID::PropertyToID("SVGF_FrameIndex");
int SpatialRadius = ShaderID::PropertyToID("SVGF_SpatialRadius");
int SpatialSize = ShaderID::PropertyToID("SVGF_SpatialSize");
int Matrix_InvProj = ShaderID::PropertyToID("Matrix_InvProj");
int Matrix_InvViewProj = ShaderID::PropertyToID("Matrix_InvViewProj");
int Matrix_WorldToView = ShaderID::PropertyToID("Matrix_WorldToView");
int SRV_SceneDepth = ShaderID::PropertyToID("SRV_SceneDepth");
int SRV_GBufferNormal = ShaderID::PropertyToID("SRV_GBufferNormal");
int SRV_GBufferRoughness = ShaderID::PropertyToID("SRV_GBufferRoughness");
int SRV_UWVPDF = ShaderID::PropertyToID("SRV_UWVPDF");
int SRV_ColorMask = ShaderID::PropertyToID("SRV_ColorMask");
int UAV_SpatialColor = ShaderID::PropertyToID("UAV_SpatialColor");
};
struct SVGF_TemporalShaderID
{
int TemporalScale = ShaderID::PropertyToID("SVGF_TemporalScale");
int TemporalWeight = ShaderID::PropertyToID("SVGF_TemporalWeight");
int TemporalSize = ShaderID::PropertyToID("SVGF_TemporalSize");
int Matrix_PrevViewProj = ShaderID::PropertyToID("Matrix_PrevViewProj");
int Matrix_ViewProj = ShaderID::PropertyToID("Matrix_ViewProj");
int Matrix_InvViewProj = ShaderID::PropertyToID("Matrix_InvViewProj");
int SRV_CurrColor = ShaderID::PropertyToID("SRV_CurrColor");
int SRV_PrevColor = ShaderID::PropertyToID("SRV_PrevColor");
int SRV_GBufferMotion = ShaderID::PropertyToID("SRV_GBufferMotion");
int SRV_RayDepth = ShaderID::PropertyToID("SRV_RayDepth");
int SRV_GBufferNormal = ShaderID::PropertyToID("SRV_GBufferNormal");
int UAV_TemporalColor = ShaderID::PropertyToID("UAV_TemporalColor");
};
struct SVGF_BilateralShaderID
{
int BilateralRadius = ShaderID::PropertyToID("SVGF_BilateralRadius");
int ColorWeight = ShaderID::PropertyToID("SVGF_ColorWeight");
int NormalWeight = ShaderID::PropertyToID("SVGF_NormalWeight");
int DepthWeight = ShaderID::PropertyToID("SVGF_DepthWeight");
int BilateralSize = ShaderID::PropertyToID("SVGF_BilateralSize");
int SRV_InputColor = ShaderID::PropertyToID("SRV_InputColor");
int SRV_GBufferNormal = ShaderID::PropertyToID("SRV_GBufferNormal");
int SRV_SceneDepth = ShaderID::PropertyToID("SRV_SceneDepth");
int UAV_BilateralColor = ShaderID::PropertyToID("UAV_BilateralColor");
};
class SSRFrameData : public IPipelineResource
{
private:
CBufferPool* cbPool;
public:
DescriptorHeap hizDescHeap;
ConstBufferElement paramEle;
uint64_t frameIndex = 0;
SSRFrameData(ID3D12Device* device, CBufferPool* cbPool) :
hizDescHeap(device, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 11, true),
cbPool(cbPool)
{
paramEle = cbPool->Get(device);
}
~SSRFrameData()
{
cbPool->Return(paramEle);
}
};
class SSRCameraData : public IPipelineResource
{
public:
std::unique_ptr<RenderTexture> temporalPrev;
};
#define GET_SCREENDEPTH_KERNEL 2
#define FIRST_MIP_KERNEL 0
#define SECOND_MIP_KERNEL 1
#define RAYCAST_KERNEL 3
#define SPATIAL_KERNEL 4
#define TEMPORAL_KERNEL 5
#define BILATERAL_KERNEL 6
class ScreenSpaceReflection
{
private:
std::mutex mtx;
inline static const int2 HZBSize = { 1024, 1024 };
//////////// vars
const uint sampleRate = 2;
bool enabled = false;
////////////
uint _CameraDepthTexture;
uint _DepthTexture;
CBufferPool paramsCBPool;
StackObject<RenderTexture> RTV_PyramidDepth;
const ComputeShader* ssrCS;
const Shader* blitShader;
SSRShaderID ssrShaderID;
SVGF_SpatialShaderID svgf_SpatialShaderID;
SVGF_TemporalShaderID svgf_TemporalShaderID;
SVGF_BilateralShaderID svgf_BilateralShaderID;
struct RenderTextures
{
RenderTexture* UAV_ReflectionUVWPDF;
RenderTexture* UAV_ReflectionColorMask;
RenderTexture* UAV_SpatialColor;
RenderTexture* UAV_TemporalColor;
};
RingQueue<RenderTextures> rQueue;
std::vector<uint> tempRTIndices;
SSRParameterDescriptor ssrSettings; //TODO: read from json
SVGFParameterDescriptor svgfSettings;//TODO: read from json
neb::CJsonObject json;
public:
ScreenSpaceReflection(ID3D12Device* device, ID3D12GraphicsCommandList* commandList, std::vector<TemporalResourceCommand>& temps, const Shader* blitShader) :
paramsCBPool(sizeof(SSR_Params_Struct), 12),
blitShader(blitShader),
rQueue(3)
{
/*ssrSettings.NumRays = 8;
ssrSettings.NumSteps = 8;
ssrSettings.BRDFBias = 0.7;
ssrSettings.Fadeness = 0.1;
ssrSettings.RoughnessDiscard = 0.5;
svgfSettings.NumSpatial = 1;
svgfSettings.SpatialRadius = 2;
svgfSettings.TemporalScale = 1.25;
svgfSettings.TemporalWeight = 0.99;
svgfSettings.BilateralColorWeight = 1;
svgfSettings.BilateralDepthWeight = 1;
svgfSettings.BilateralNormalWeight = 0.1;
svgfSettings.BilateralRadius = 2;*/
AssetDatabase::GetInstance()->TryGetJson("SSR", &json);
int enabledData = 0;
json.Get("enabled", enabledData);
enabled = enabledData;
json.Get("NumRays", ssrSettings.NumRays);
json.Get("NumSteps", ssrSettings.NumSteps);
json.Get("BRDFBias", ssrSettings.BRDFBias);
json.Get("Fadeness", ssrSettings.Fadeness);
json.Get("RoughnessDiscard", ssrSettings.RoughnessDiscard);
json.Get("NumSpatial", svgfSettings.NumSpatial);
json.Get("SpatialRadius", svgfSettings.SpatialRadius);
json.Get("TemporalScale", svgfSettings.TemporalScale);
json.Get("TemporalWeight", svgfSettings.TemporalWeight);
tempRTIndices.reserve(10);
_CameraDepthTexture = ShaderID::PropertyToID("_CameraDepthTexture");
_DepthTexture = ShaderID::PropertyToID("_DepthTexture");
TemporalResourceCommand resCommand;
RenderTextureDescriptor& desc = resCommand.descriptor.rtDesc;
resCommand.type = TemporalResourceCommand::CommandType_Create_RenderTexture;
resCommand.uID = ssrShaderID.UAV_ReflectionUVWPDF;
resCommand.descriptor.type = ResourceDescriptor::ResourceType_RenderTexture;
desc.depthSlice = 1;
desc.type = TextureDimension::Tex2D;
desc.rtFormat = RenderTextureFormat::GetColorFormat(DXGI_FORMAT_R16G16B16A16_FLOAT);
tempRTIndices.push_back(temps.size());
temps.push_back(resCommand);
resCommand.uID = ssrShaderID.UAV_ReflectionColorMask;
tempRTIndices.push_back(temps.size());
temps.push_back(resCommand);
resCommand.uID = svgf_SpatialShaderID.UAV_SpatialColor;
tempRTIndices.push_back(temps.size());
temps.push_back(resCommand);
resCommand.uID = svgf_TemporalShaderID.UAV_TemporalColor;
tempRTIndices.push_back(temps.size());
temps.push_back(resCommand);
ssrCS = ShaderCompiler::GetComputeShader("SSR");
RTV_PyramidDepth.New(device, 1024, 1024, RenderTextureFormat::GetColorFormat(DXGI_FORMAT_R16_FLOAT), TextureDimension::Tex2D, 1, 10, RenderTextureState::Unordered_Access);
}
void PrepareRenderTexture(std::vector<MObject*>& objs)
{
RenderTextures rts;
rts.UAV_ReflectionUVWPDF = (RenderTexture*)objs[tempRTIndices[0]];
rts.UAV_ReflectionColorMask = (RenderTexture*)objs[tempRTIndices[1]];
rts.UAV_SpatialColor = (RenderTexture*)objs[tempRTIndices[2]];
rts.UAV_TemporalColor = (RenderTexture*)objs[tempRTIndices[3]];
std::lock_guard<std::mutex> lck(mtx);
rQueue.Push(rts);
}
void UpdateTempRT(const PipelineComponent::EventData& data, std::vector<TemporalResourceCommand>& temps)
{
uint2 screenSize = uint2(data.width, data.height) / uint2(sampleRate, sampleRate);
temps[tempRTIndices[0]].descriptor.rtDesc.width = screenSize.x;
temps[tempRTIndices[0]].descriptor.rtDesc.height = screenSize.y;
temps[tempRTIndices[1]].descriptor.rtDesc.width = screenSize.x;
temps[tempRTIndices[1]].descriptor.rtDesc.height = screenSize.y;
temps[tempRTIndices[2]].descriptor.rtDesc.width = data.width;
temps[tempRTIndices[2]].descriptor.rtDesc.height = data.height;
temps[tempRTIndices[3]].descriptor.rtDesc.width = data.width;
temps[tempRTIndices[3]].descriptor.rtDesc.height = data.height;
}
~ScreenSpaceReflection()
{
RTV_PyramidDepth.Delete();
}
void FrameUpdate(
ID3D12Device* device,
ID3D12GraphicsCommandList* commandList,
FrameResource* resource,
Camera* cam,
TransitionBarrierBuffer* barrierBuffer,
RenderTexture* depthTex,
RenderTexture* gbuffer1,
RenderTexture* gbuffer2,
RenderTexture* source,
RenderTexture* renderTarget,
RenderTexture* motionVector,
PSOContainer* toRenderTargetPSOContainer)
{
if (!enabled) return;
RenderTextures rt;
{
std::lock_guard<std::mutex> lck(mtx);
if (!rQueue.TryPop(&rt)) return;
}
uint2 screenSize = uint2(renderTarget->GetWidth() / sampleRate, renderTarget->GetHeight() / sampleRate);
uint2 originScreenSize = uint2(renderTarget->GetWidth(), renderTarget->GetHeight());
//Depth Pyramid
SSRFrameData* frameData = (SSRFrameData*)resource->GetPerCameraResource(this, cam, [&]()->SSRFrameData*
{
return new SSRFrameData(device, ¶msCBPool);
});
SSRCameraData* camData = (SSRCameraData*)cam->GetResource(this, []()->SSRCameraData*
{
return new SSRCameraData;
});
for (uint i = 0; i < 10; ++i)
{
RTV_PyramidDepth->BindUAVToHeap(&frameData->hizDescHeap, i, device, i);
}
frameData->frameIndex += 1;
depthTex->BindSRVToHeap(&frameData->hizDescHeap, 10, device);
////////////////Mark Barrier Buffer
barrierBuffer->RegistInitState(RenderTexture::RenderTargetState, renderTarget->GetResource());
barrierBuffer->RegistInitState(RenderTexture::ColorReadState, motionVector->GetResource());
barrierBuffer->RegistInitState(RenderTexture::RenderTargetState, rt.UAV_ReflectionUVWPDF->GetResource());
barrierBuffer->RegistInitState(RenderTexture::RenderTargetState, rt.UAV_ReflectionColorMask->GetResource());
barrierBuffer->RegistInitState(RenderTexture::RenderTargetState, rt.UAV_SpatialColor->GetResource());
barrierBuffer->RegistInitState(RenderTexture::RenderTargetState, rt.UAV_TemporalColor->GetResource());
barrierBuffer->RegistInitState(RenderTexture::UnorderedAccessState, RTV_PyramidDepth->GetResource());
////////////////
barrierBuffer->UpdateState(RenderTexture::UnorderedAccessState, rt.UAV_ReflectionUVWPDF->GetResource());
barrierBuffer->UpdateState(RenderTexture::UnorderedAccessState, rt.UAV_ReflectionColorMask->GetResource());
barrierBuffer->UpdateState(RenderTexture::UnorderedAccessState, rt.UAV_SpatialColor->GetResource());
barrierBuffer->UpdateState(RenderTexture::UnorderedAccessState, rt.UAV_TemporalColor->GetResource());
barrierBuffer->ExecuteCommand(commandList);
ssrCS->BindRootSignature(commandList, &frameData->hizDescHeap);
ssrCS->SetResource(commandList, _CameraDepthTexture, &frameData->hizDescHeap, 10);
ssrCS->SetResource(commandList, _DepthTexture, &frameData->hizDescHeap, 0);
ssrCS->Dispatch(commandList, GET_SCREENDEPTH_KERNEL, HZBSize.x / 8, HZBSize.y / 8, 1);
barrierBuffer->UAVBarrier(RTV_PyramidDepth->GetResource());
barrierBuffer->ExecuteCommand(commandList);
ssrCS->Dispatch(commandList, FIRST_MIP_KERNEL, HZBSize.x / 32 / 2, HZBSize.y / 32 / 2, 1);
barrierBuffer->UAVBarrier(RTV_PyramidDepth->GetResource());
barrierBuffer->ExecuteCommand(commandList);
ssrCS->Dispatch(commandList, SECOND_MIP_KERNEL, 1, 1, 1);
barrierBuffer->UpdateState(RenderTexture::ColorReadState, RTV_PyramidDepth->GetResource());
/////////////////////Ray Casting
float4 traceResolution;
traceResolution.x = screenSize.x;
traceResolution.y = screenSize.y;
traceResolution.z = 1.0 / traceResolution.x;
traceResolution.w = 1.0 / traceResolution.y;
float4 resolution;
resolution.x = originScreenSize.x;
resolution.y = originScreenSize.y;
resolution.z = 1.0 / resolution.x;
resolution.w = 1.0 / resolution.y;
SSR_Params_Struct ssrParams;
ssrParams.SSR_NumRays = ssrSettings.NumRays;
ssrParams.SSR_NumSteps = ssrSettings.NumSteps;
ssrParams.SSR_FrameIndex = frameData->frameIndex;
ssrParams.SSR_BRDFBias = ssrSettings.BRDFBias;
ssrParams.SSR_Fadeness = ssrSettings.Fadeness;
ssrParams.SSR_RoughnessDiscard = ssrSettings.RoughnessDiscard;
ssrParams.SSR_TraceResolution = traceResolution;
ssrParams._RayTraceResolution = screenSize;
ssrParams._PostResolution = originScreenSize;
const DescriptorHeap* globalHeap = Graphics::GetGlobalDescHeap();
Graphics::GetGlobalDescHeap()->SetDescriptorHeap(commandList);
ConstBufferElement ele = resource->cameraCBs[cam];
ssrCS->SetResource(commandList, ShaderID::GetPerCameraBufferID(), ele.buffer, ele.element);
ssrCS->SetResource(commandList, ssrShaderID.SSR_Params, frameData->paramEle.buffer, frameData->paramEle.element);
ssrCS->SetResource(commandList, ssrShaderID.SRV_PyramidColor, globalHeap, source->GetGlobalDescIndex());
ssrCS->SetResource(commandList, ssrShaderID.SRV_SceneDepth, globalHeap, depthTex->GetGlobalDescIndex());
ssrCS->SetResource(commandList, ssrShaderID.SRV_GBufferNormal, globalHeap, gbuffer2->GetGlobalDescIndex());
ssrCS->SetResource(commandList, ssrShaderID.SRV_GBufferRoughness, globalHeap, gbuffer1->GetGlobalDescIndex());
ssrCS->SetResource(commandList, ssrShaderID.SRV_PyramidDepth, globalHeap, RTV_PyramidDepth->GetGlobalDescIndex());
ssrCS->SetResource(commandList, ssrShaderID.UAV_ReflectionUVWPDF, globalHeap, rt.UAV_ReflectionUVWPDF->GetGlobalUAVDescIndex(0));
ssrCS->SetResource(commandList, ssrShaderID.UAV_ReflectionColorMask, globalHeap, rt.UAV_ReflectionColorMask->GetGlobalUAVDescIndex(0));
barrierBuffer->ExecuteCommand(commandList);
ssrCS->Dispatch(commandList, RAYCAST_KERNEL, (screenSize.x + 15) / 16, (screenSize.y + 15) / 16, 1);
barrierBuffer->UpdateState(RenderTexture::ColorReadState, rt.UAV_ReflectionUVWPDF->GetResource());
///////////////////Spatial Filter
ssrParams.SVGF_FrameIndex = frameData->frameIndex;
ssrParams.SVGF_SpatialRadius = svgfSettings.SpatialRadius;
ssrParams.SVGF_SpatialSize = resolution;
ssrCS->SetResource(commandList, svgf_SpatialShaderID.SRV_UWVPDF, globalHeap, rt.UAV_ReflectionUVWPDF->GetGlobalDescIndex());
/*for (uint i = 0; i < svgfSettings.NumSpatial; i++) {
uint CurrState = i & 1;
if (CurrState == 0)
{
barrierBuffer->UpdateState(RenderTexture::ColorReadState, rt.UAV_ReflectionColorMask->GetResource());
barrierBuffer->UpdateState(RenderTexture::UnorderedAccessState, rt.UAV_SpatialColor->GetResource());
ssrCS->SetResource(commandList, svgf_SpatialShaderID.SRV_ColorMask, globalHeap, rt.UAV_ReflectionColorMask->GetGlobalDescIndex());
ssrCS->SetResource(commandList, svgf_SpatialShaderID.UAV_SpatialColor, globalHeap, rt.UAV_SpatialColor->GetGlobalUAVDescIndex(0));
barrierBuffer->ExecuteCommand(commandList);
ssrCS->Dispatch(commandList, SPATIAL_KERNEL, (originScreenSize.x + 15) / 16, (originScreenSize.y + 15) / 16, 1);
if (i == svgfSettings.NumSpatial - 1)
{
Graphics::UAVBarriers(commandList, { rt.UAV_SpatialColor->GetResource() });
}
}
else
{
barrierBuffer->UpdateState(RenderTexture::ColorReadState, rt.UAV_SpatialColor->GetResource());
barrierBuffer->UpdateState(RenderTexture::UnorderedAccessState, rt.UAV_ReflectionColorMask->GetResource());
ssrCS->SetResource(commandList, svgf_SpatialShaderID.SRV_ColorMask, globalHeap, rt.UAV_SpatialColor->GetGlobalDescIndex());
ssrCS->SetResource(commandList, svgf_SpatialShaderID.UAV_SpatialColor, globalHeap, rt.UAV_ReflectionColorMask->GetGlobalUAVDescIndex(0));
barrierBuffer->ExecuteCommand(commandList);
ssrCS->Dispatch(commandList, SPATIAL_KERNEL, (originScreenSize.x + 15) / 16, (originScreenSize.y + 15) / 16, 1);
barrierBuffer->UpdateState(RenderTexture::ColorReadState, rt.UAV_ReflectionColorMask->GetResource());
barrierBuffer->UpdateState(RenderTexture::CopyDestState, rt.UAV_SpatialColor->GetResource());
barrierBuffer->ExecuteCommand(commandList);
Graphics::CopyTexture(commandList, rt.UAV_ReflectionColorMask, 0, 0, rt.UAV_SpatialColor, 0, 0);
}
}*/
barrierBuffer->UpdateState(RenderTexture::ColorReadState, rt.UAV_ReflectionColorMask->GetResource());
barrierBuffer->UpdateState(RenderTexture::UnorderedAccessState, rt.UAV_SpatialColor->GetResource());
ssrCS->SetResource(commandList, svgf_SpatialShaderID.SRV_ColorMask, globalHeap, rt.UAV_ReflectionColorMask->GetGlobalDescIndex());
ssrCS->SetResource(commandList, svgf_SpatialShaderID.UAV_SpatialColor, globalHeap, rt.UAV_SpatialColor->GetGlobalUAVDescIndex(0));
barrierBuffer->ExecuteCommand(commandList);
ssrCS->Dispatch(commandList, SPATIAL_KERNEL, (originScreenSize.x + 15) / 16, (originScreenSize.y + 15) / 16, 1);
barrierBuffer->UAVBarrier(rt.UAV_SpatialColor->GetResource());
////////////////////Temporal Filter
if (!camData->temporalPrev
|| (camData->temporalPrev->GetWidth() != originScreenSize.x)
|| (camData->temporalPrev->GetHeight() != originScreenSize.y))
{
camData->temporalPrev = std::unique_ptr<RenderTexture>(new RenderTexture(
device,
originScreenSize.x,
originScreenSize.y,
RenderTextureFormat::GetColorFormat(rt.UAV_TemporalColor->GetFormat()),
TextureDimension::Tex2D,
1, 1, RenderTextureState::Unordered_Access));
}
barrierBuffer->RegistInitState(RenderTexture::UnorderedAccessState, camData->temporalPrev->GetResource());
ssrParams.SVGF_TemporalScale = svgfSettings.TemporalScale;
ssrParams.SVGF_TemporalWeight = svgfSettings.TemporalWeight;
ssrParams.SVGF_TemporalSize = resolution;
barrierBuffer->UpdateState(RenderTexture::ColorReadState, rt.UAV_ReflectionUVWPDF->GetResource());
barrierBuffer->UpdateState(RenderTexture::ColorReadState, rt.UAV_SpatialColor->GetResource());
barrierBuffer->UpdateState(RenderTexture::ColorReadState, camData->temporalPrev->GetResource());
barrierBuffer->UpdateState(RenderTexture::UnorderedAccessState, rt.UAV_TemporalColor->GetResource());
ssrCS->SetResource(commandList, svgf_TemporalShaderID.SRV_GBufferMotion, globalHeap, motionVector->GetGlobalDescIndex());
ssrCS->SetResource(commandList, svgf_TemporalShaderID.SRV_RayDepth, globalHeap, rt.UAV_ReflectionUVWPDF->GetGlobalDescIndex());
ssrCS->SetResource(commandList, svgf_TemporalShaderID.SRV_CurrColor, globalHeap, rt.UAV_SpatialColor->GetGlobalDescIndex());
ssrCS->SetResource(commandList, svgf_TemporalShaderID.SRV_PrevColor, globalHeap, camData->temporalPrev->GetGlobalDescIndex());
ssrCS->SetResource(commandList, svgf_TemporalShaderID.UAV_TemporalColor, globalHeap, rt.UAV_TemporalColor->GetGlobalUAVDescIndex(0));
barrierBuffer->ExecuteCommand(commandList);
ssrCS->Dispatch(commandList, TEMPORAL_KERNEL, (15 + originScreenSize.x) / 16, (15 + originScreenSize.y) / 16, 1);
barrierBuffer->UpdateState(RenderTexture::ColorReadState, rt.UAV_TemporalColor->GetResource());
barrierBuffer->UpdateState(RenderTexture::CopyDestState, camData->temporalPrev->GetResource());
barrierBuffer->ExecuteCommand(commandList);
Graphics::CopyTexture(commandList, rt.UAV_TemporalColor, 0, 0, camData->temporalPrev.get(), 0, 0);
barrierBuffer->ExecuteCommand(commandList);//Delete
//////////////Blit
blitShader->BindRootSignature(commandList, globalHeap);
blitShader->SetResource(commandList, ShaderID::GetMainTex(), globalHeap, rt.UAV_TemporalColor->GetGlobalDescIndex());
blitShader->SetResource(commandList, ssrShaderID.SRV_GBufferRoughness, globalHeap, gbuffer1->GetGlobalDescIndex());
Graphics::Blit(commandList,
device,
&renderTarget->GetColorDescriptor(0, 0),
1,
nullptr,
toRenderTargetPSOContainer,
toRenderTargetPSOContainer->GetIndex( {renderTarget->GetFormat()} ),
renderTarget->GetWidth(),
renderTarget->GetHeight(),
blitShader,
0);
barrierBuffer->UpdateState(RenderTexture::RenderTargetState, rt.UAV_ReflectionUVWPDF->GetResource());
barrierBuffer->UpdateState(RenderTexture::RenderTargetState, rt.UAV_ReflectionColorMask->GetResource());
barrierBuffer->UpdateState(RenderTexture::RenderTargetState, rt.UAV_SpatialColor->GetResource());
barrierBuffer->UpdateState(RenderTexture::RenderTargetState, rt.UAV_TemporalColor->GetResource());
barrierBuffer->UpdateState(RenderTexture::UnorderedAccessState, RTV_PyramidDepth->GetResource());
barrierBuffer->UpdateState(RenderTexture::UnorderedAccessState, camData->temporalPrev->GetResource());
frameData->paramEle.buffer->CopyData(frameData->paramEle.element, &ssrParams);
}
};
#undef GET_SCREENDEPTH_KERNEL
#undef FIRST_MIP_KERNEL
#undef SECOND_MIP_KERNEL
#undef RAYCAST_KERNEL
#undef SPATIAL_KERNEL
#undef TEMPORAL_KERNEL
#undef BILATERAL_KERNEL | [
"[email protected]"
] | |
29b66b11278ff8cb74b223d3d560af37d0c7bf23 | d26954247e12248ad63f1089f85abe43a6faaa41 | /test/geomUtils/polylineTest.cpp | 7de2d38285fe20f083c541937e6a1c324644ca5b | [] | no_license | indivisibleatom/cppUtils | 773521bf74e6b6f1438ef155a7ff60b904497f77 | 06883e56550f6761bc97690fa8bdb0c4a8d6bd02 | refs/heads/master | 2021-01-10T09:47:19.769819 | 2016-04-12T22:39:07 | 2016-04-12T22:39:07 | 51,717,805 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 233 | cpp | #include <gtest/gtest.h>
#include "geomUtils/polyline.h"
class PolylineTest : public ::testing::Test {
protected:
virtual void SetUp() {}
virtual void TearDown() {}
};
TEST_F(PolylineTest, size) {
Polyline polyline;
}
| [
"[email protected]"
] | |
251b492c36d7367881320ddda1495da24fb4b5ba | b2005ae57ebdbf15fcf679a5b13c9626b0b07825 | /SuperBlinkPabloMario2/SuperBlinkPabloMario2.ino | 2381aff0b8b7f7b1c22afa0681febe59e02598f3 | [] | no_license | pablomario/ArduinoProjects | a2fdd00ef94dde6dd6124a950dba20cb8ea05ca1 | 033a6b7e19587018954cdcc4bcfb2b7644b5cd5a | refs/heads/master | 2021-01-23T06:25:54.983599 | 2017-08-12T20:27:40 | 2017-08-12T20:27:40 | 16,008,370 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 633 | ino |
int led1 = 11;
int led2 = 10;
int led3 = 6;
int led4 = 5;
int led5 = 3;
void setup() {
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
pinMode(led3, OUTPUT);
pinMode(led4, OUTPUT);
pinMode(led5, OUTPUT);
}
void loop() {
digitalWrite(led1, HIGH);
delay(100);
digitalWrite(led1, LOW);
digitalWrite(led2, HIGH);
delay(100);
digitalWrite(led2, LOW);
digitalWrite(led3, HIGH);
delay(100);
digitalWrite(led3, LOW);
digitalWrite(led4, HIGH);
delay(100);
digitalWrite(led4, LOW);
digitalWrite(led5, HIGH);
delay(100);
digitalWrite(led5, LOW);
}
| [
"[email protected]"
] | |
6af799ee9cdf39093e2837057a9111c2e161f159 | a9e308c81c27a80c53c899ce806d6d7b4a9bbbf3 | /engine/xray/maya_animation/sources/maya_animation_data.h | 4f145544511500498a0aa0d9733085188585448e | [] | no_license | NikitaNikson/xray-2_0 | 00d8e78112d7b3d5ec1cb790c90f614dc732f633 | 82b049d2d177aac15e1317cbe281e8c167b8f8d1 | refs/heads/master | 2023-06-25T16:51:26.243019 | 2020-09-29T15:49:23 | 2020-09-29T15:49:23 | 390,966,305 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 992 | h | ////////////////////////////////////////////////////////////////////////////
// Created : 24.12.2009
// Author : Konstantin Slipchenko
// Copyright (C) GSC Game World - 2009
////////////////////////////////////////////////////////////////////////////
#ifndef MAYA_ANIMATION_DATA_H_INCLUDED
#define MAYA_ANIMATION_DATA_H_INCLUDED
#include <xray/maya_animation/anim_track.h>
namespace xray {
namespace maya_animation {
class animation_data {
public:
bool load ( const char* fn );
void clear ( );
void bone_pose ( xray::float4x4 &pose, u32 id, float time );
u32 anim_bone_count ( ){ return m_bone_animations.size(); }
float min_time ();
float max_time ();
float evaluate_mean_time ();
inline anim_track &bone_animation ( u32 id ) { return m_bone_animations[id]; }
private:
vector <anim_track> m_bone_animations;
}; // class animation_data
} // namespace maya_animation
} // namespace xray
#endif // #ifndef MAYA_ANIMATION_DATA_H_INCLUDED | [
"[email protected]"
] | |
85f8cc444bfdcd59bb3474c4406a011ebea477e0 | 83aea5d899b7be4d59c91181f7e139481ab67e6d | /Engine/_Editor/_Headers/Gizmos/ZEditorGizmo.hpp | b4d9e6a1ec3cd69daa08951a22533410c7686b33 | [
"MIT"
] | permissive | gitbetter/Zenith | 7c2fce0278e80ff28f5c4bde276f197f46480aa6 | 5034f84d406d7de1cf653d16832650435cf41ea0 | refs/heads/master | 2023-02-06T07:20:30.260090 | 2023-01-31T21:47:37 | 2023-01-31T21:47:37 | 167,701,171 | 17 | 2 | MIT | 2021-03-19T05:58:06 | 2019-01-26T15:01:27 | C++ | UTF-8 | C++ | false | false | 1,788 | hpp | /*
______ ______ __ __ __ ______ __ __
/\___ \ /\ ___\ /\ "-.\ \ /\ \ /\__ _\ /\ \_\ \
\/_/ /__ \ \ __\ \ \ \-. \ \ \ \ \/_/\ \/ \ \ __ \
/\_____\ \ \_____\ \ \_\\"\_\ \ \_\ \ \_\ \ \_\ \_\
\/_____/ \/_____/ \/_/ \/_/ \/_/ \/_/ \/_/\/_/
ZEditorGizmo.hpp
Created by Adrian Sanchez on 02/20/21.
Copyright © 2019 Pervasive Sense. All rights reserved.
This file is part of Zenith.
Zenith 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.
Zenith 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 Zenith. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
// Includes
#include "ZEditorEntity.hpp"
// Forward Declarations
class ZGameObject;
class ZRay;
// Definitions
class ZEditorGizmo : public ZEditorEntity
{
public:
ZEditorGizmo() { }
virtual ~ZEditorGizmo() { }
virtual void Initialize(const std::shared_ptr<ZScene>& scene) override;
void Update() override { }
bool Showing();
void SetPosition(const glm::vec3& position);
void Hide();
void Show();
virtual bool TryActivate(const ZRect& viewportRect) = 0;
virtual void Manipulate(const ZRect& viewportRect, glm::mat4& transform) = 0;
virtual void Deactivate() = 0;
protected:
std::shared_ptr<ZGameObject> gizmo_;
bool active_ = false;
};
| [
"[email protected]"
] | |
fa9321e2070ca6f677797f43e3292480b96be81c | 1880ae99db197e976c87ba26eb23a20248e8ee51 | /iotvideo/include/tencentcloud/iotvideo/v20201215/model/CheckForwardAuthResponse.h | 429d16400594e39e73509d4f841f460fb5fc3318 | [
"Apache-2.0"
] | permissive | caogenwang/tencentcloud-sdk-cpp | 84869793b5eb9811bb1eb46ed03d4dfa7ce6d94d | 6e18ee6622697a1c60a20a509415b0ddb8bdeb75 | refs/heads/master | 2023-08-23T12:37:30.305972 | 2021-11-08T01:18:30 | 2021-11-08T01:18:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,597 | h | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef TENCENTCLOUD_IOTVIDEO_V20201215_MODEL_CHECKFORWARDAUTHRESPONSE_H_
#define TENCENTCLOUD_IOTVIDEO_V20201215_MODEL_CHECKFORWARDAUTHRESPONSE_H_
#include <string>
#include <vector>
#include <map>
#include <tencentcloud/core/AbstractModel.h>
namespace TencentCloud
{
namespace Iotvideo
{
namespace V20201215
{
namespace Model
{
/**
* CheckForwardAuth返回参数结构体
*/
class CheckForwardAuthResponse : public AbstractModel
{
public:
CheckForwardAuthResponse();
~CheckForwardAuthResponse() = default;
CoreInternalOutcome Deserialize(const std::string &payload);
std::string ToJsonString() const;
/**
* 获取腾讯云账号
* @return Endpoint 腾讯云账号
*/
std::string GetEndpoint() const;
/**
* 判断参数 Endpoint 是否已赋值
* @return Endpoint 是否已赋值
*/
bool EndpointHasBeenSet() const;
/**
* 获取结果
* @return Result 结果
*/
uint64_t GetResult() const;
/**
* 判断参数 Result 是否已赋值
* @return Result 是否已赋值
*/
bool ResultHasBeenSet() const;
/**
* 获取产品ID
* @return Productid 产品ID
*/
std::string GetProductid() const;
/**
* 判断参数 Productid 是否已赋值
* @return Productid 是否已赋值
*/
bool ProductidHasBeenSet() const;
/**
* 获取错误消息
* @return ErrMsg 错误消息
*/
std::string GetErrMsg() const;
/**
* 判断参数 ErrMsg 是否已赋值
* @return ErrMsg 是否已赋值
*/
bool ErrMsgHasBeenSet() const;
/**
* 获取队列类型 0.CMQ 1.Ckafka
* @return QueueType 队列类型 0.CMQ 1.Ckafka
*/
uint64_t GetQueueType() const;
/**
* 判断参数 QueueType 是否已赋值
* @return QueueType 是否已赋值
*/
bool QueueTypeHasBeenSet() const;
private:
/**
* 腾讯云账号
*/
std::string m_endpoint;
bool m_endpointHasBeenSet;
/**
* 结果
*/
uint64_t m_result;
bool m_resultHasBeenSet;
/**
* 产品ID
*/
std::string m_productid;
bool m_productidHasBeenSet;
/**
* 错误消息
*/
std::string m_errMsg;
bool m_errMsgHasBeenSet;
/**
* 队列类型 0.CMQ 1.Ckafka
*/
uint64_t m_queueType;
bool m_queueTypeHasBeenSet;
};
}
}
}
}
#endif // !TENCENTCLOUD_IOTVIDEO_V20201215_MODEL_CHECKFORWARDAUTHRESPONSE_H_
| [
"[email protected]"
] | |
ba8c57955b01457bff6ef687ba90ccc9c813d914 | 7a3518dad1eb04958d95e1e1c4332e5f8db321fa | /cpu/pv/ram/tests_ram.cpp | 763018f3cda3a2914bd67fff027679d3e7a1e8ab | [] | no_license | Diseno-sistemas-electronicos/project_1 | c07c708df699b4b5bd9b00e892337157b734b7c1 | acbe842b9c129ae5e40324ca699b957a642421b6 | refs/heads/master | 2022-11-19T15:38:30.266785 | 2020-07-14T23:45:52 | 2020-07-14T23:45:52 | 267,205,217 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 776 | cpp | #include "systemc.h"
#include "ram.h"
int sc_main(int argn, char * argv[]) {
//const char * inputFile = "in.text";
std::vector<sc_int<32> > initRam;
ram<sc_int<32>,256> memRam("MEMRAM", initRam);
sc_signal<bool> clock, enable, write;
sc_signal<int> address;
sc_signal<sc_int<32> > data;
memRam.clock(clock);
memRam.enable(enable);
memRam.write(write);
memRam.address(address);
memRam.data(data);
enable = 0;
write = 0;
address = 9;
data = 0;
cout << data.read() << endl;
sc_start(0, SC_PS);
clock = 1;
enable = 1;
write = 1;
data.write(0xF);
address.write(0x10);
sc_start(1, SC_PS);
clock = 0;
enable = 0;
sc_start(1, SC_PS);
enable = 1;
write = 0;
address.write(0x10);
sc_start(1, SC_PS);
cout << data.read() << endl;
return 0;
}
| [
"[email protected]"
] | |
dbe6f49b0e5d46d60b3339b102d7cbbb78cb66ef | 7598cc3495ca207f7086c9dd92752c6d76443362 | /2020 Year/경량 패턴/타일 맵 생성/2DClient/Player.cpp | ceb1da75b0c617a7d7d8b5f276f2caacb8629a0d | [] | no_license | SnowFleur/Design-Patterns | 6e45efa5cec256efdfc118328478e28bbc2392e8 | 237ae7239d955674ba81945e07eadfba1abb2275 | refs/heads/master | 2023-04-21T05:27:54.650807 | 2021-05-07T14:29:12 | 2021-05-07T14:29:12 | 258,778,833 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 291 | cpp | #include "stdafx.h"
#include "Player.h"
void Player::GetPlayerPosition(int& x, int& y) {
x = xpos_;
y = ypos_;
}
void Player::SetPlayerPosition(int x, int y) {
xpos_ = x;
ypos_ = y;
y = ypos_;
}
const Texture& Player::GetPlayerTexture()const {
return *texture_;
}
| [
"[email protected]"
] | |
72c52eeb82d88e557e04fcac5d69a08d076071ac | 27ebd7f3cf3bd1d483f8a1d27c3575c720f642e5 | /Think_in_C++/code/C10/Header2.h | 86344d6a80b2f6bf75d3cd50489505059dabafa9 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | walte/resourcerepo | a6ad55e907c72811b7aec82be7bfd5c58edecf5c | b8450232a098077965e76eb7134eca894b0a38c6 | refs/heads/master | 2016-09-06T05:35:18.599888 | 2013-11-22T06:43:35 | 2013-11-22T06:43:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 293 | h | //: C10:Header2.h
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 1999
// Copyright notice in Copyright.txt
// Add more names to MyLib
namespace MyLib { // NOT a redefinition!
extern int y;
void g();
// ...
} ///:~
| [
"[email protected]"
] | |
d8c22794800ebb532742b7fb3afdeaa5a1da5169 | 83cf354a71e8cf57d2a46ee0cc374038834f2e7a | /src/redispack/alias.h | 56ccf1412dbe3106956bc0b7c5e1a84e2382f8bf | [] | no_license | guangie88/redispack | ff5d12aa08b3f1b063a75066843ea86c3755b71e | ef07857e7ec02b669e6fa4cf273ea34be0e954fc | refs/heads/master | 2021-01-22T05:34:06.306872 | 2017-05-28T16:04:46 | 2017-05-28T16:04:46 | 92,479,880 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 464 | h | #pragma once
#include "cpp_redis/redis_client.hpp"
#include "cpp_redis/redis_error.hpp"
#include <memory>
namespace redispack {
/** Alias to cpp_redis::redis_error. */
using redis_error = ::cpp_redis::redis_error;
/** Alias to cpp_redis::redis_client. */
using redis_client = ::cpp_redis::redis_client;
/** Alias to the common form of redis_client shared ownership pointer. **/
using redis_client_ptr = std::shared_ptr<redis_client>;
} | [
"[email protected]"
] | |
ab880c56308402f4e3ec874925469ead9eeef39f | 092061a87bb130b5e14fafdc31c33fdb4146eefc | /project4/creature.cpp | 1f5a1193819567685036c5a248220fc65e623af1 | [] | no_license | bgpalmer/Computer-Science-II | 111d58e01586bdaf813c01a0054db986ed0852f3 | 1388b6998248454a9525e5a2a41923bf865f2581 | refs/heads/master | 2021-08-30T16:39:30.952392 | 2017-12-18T17:43:29 | 2017-12-18T17:43:29 | 114,670,083 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,474 | cpp | /*********************************************************************
** Program Filename: creature.cpp
** Author: brian palmer
** Date: 11.5.16
** Description: Creature function definitions
** Input: none
** Output: none
*********************************************************************/
#include "creature.hpp"
// returns type member
string Creature::get_type() const
{
return type;
}
// returns strength points
int Creature::get_str_pts() const
{
return str_pts;
}
/*********************************************************************
** Function: attack
** Description: basic attack function for all creatures
** Parameters: none
** Pre-Conditions: none
** Post-Conditions: none
** Return: none
*********************************************************************/
int Creature::attack()
{
int counter = 0;
int attack = 0;
cout << get_type() << " attacks!\n";
while (counter < num_atk_die)
{
int roll = atk_die->roll();
cout << "\t" << get_type() << " rolls a " << roll << "!\n";
attack += roll;
counter++;
}
cout << "\tTotal attack is " << attack << "!\n";
return attack;
}
/*********************************************************************
** Function: Destructor()
** Description: creature destructor
** Parameters: none
** Pre-Conditions: none
** Post-Conditions: die should be removed successfully
** Return: none
*********************************************************************/
Creature::~Creature()
{
delete atk_die;
delete def_die;
}
/*********************************************************************
** Function: Creature()
** Description: Creature constructor
** Parameters: string, int, int, int, int, int, int
** Pre-Conditions: none
** Post-Conditions: none
** Return: none
*********************************************************************/
Creature::Creature(string t, int arm, int strength_pts, int num_a_die, int num_d_die, int num_atk_sides, int num_def_sides)
{
type = t;
armor = arm;
str_pts = strength_pts;
num_atk_die = num_a_die;
num_def_die = num_d_die;
atk_die = new Dice(num_atk_sides);
def_die = new Dice(num_def_sides);
max_str_pts = str_pts;
}
/*********************************************************************
** Function: defend(int attack)
** Description: basic defense for all creatures
** Parameters: string, int, int, int, int, int, int
** Pre-Conditions: none
** Post-Conditions: none
** Return: none
*********************************************************************/
void Creature::defend(int attack)
{
// if true, the creature was Glared at by Medusa!
if (attack == -1)
{
// reduce health to zero by subtract strength points from itself
reduce_str_pts(str_pts);
}
else
{
cout << get_type() << " tries to defend itself/himself!\n";
int counter = 0;
int defense = 0;
while (counter < num_def_die)
{
int roll = def_die->roll();
defense += roll;
cout << "\t Rolls a " << roll << "!\n";
counter++;
}
cout << "\tTotal defense is " << defense << "!\n";
int true_diff = attack - defense;
int game_diff = true_diff;
if (game_diff < 0)
game_diff = 0;
cout << get_type() << " puts up a defense, reducing attack to " << game_diff << "(" << true_diff << ")" << endl;
game_diff = armor_effect(game_diff);
cout << get_type() << " loses " << game_diff << " strength points!" << endl;
reduce_str_pts(game_diff);
}
}
/*********************************************************************
** Function: armor_effect()
** Description: armor reduces some of the attack
** Parameters: int
** Pre-Conditions: none
** Post-Conditions: none
** Return: int
*********************************************************************/
int Creature::armor_effect(int attack)
{
int true_diff = attack - armor;
int game_diff = true_diff;
if (game_diff < 0)
game_diff = 0;
cout << get_type() << " is wearing armor (" << armor << "), which reduces the attack to " << game_diff << "(" << true_diff << ")"<< endl;
return game_diff;
}
/*********************************************************************
** Function: reduce_str_pts()
** Description: reduces creatures strength points by parameter.
** Parameters: string, int, int, int, int, int, int
** Pre-Conditions: none
** Post-Conditions: none
** Return: positive integer
*********************************************************************/
void Creature::reduce_str_pts(int damage)
{
str_pts -= damage;
cout << get_type() << " takes " << damage << " damage ";
if (str_pts < 0)
{
str_pts = 0;
}
cout << "and has " << str_pts << " left." << endl;
}
void Creature::heal()
{
str_pts += (max_str_pts/4);
if (str_pts > max_str_pts)
str_pts = max_str_pts;
cout << get_type() << "heals a little, and now has " << str_pts << " strength points" << endl;
}
| [
"[email protected]"
] | |
b6d8d848887b0471ba9d90e6fc5ca3d8dbc87ca7 | dab73429585b735c50a32d4987f084aba03fe26f | /cocos2d/cocos/2d/CCLabel.cpp | 0b6f9d132452123fc10605bb771bb9d35acd2724 | [
"MIT"
] | permissive | JoaoBaptMG/InfiniteSpaceExplorer | c59fe19f5099d699f39356f790b8f1c1b2d3bed9 | 841fbf57e8bcab279a7b252dad1f4ef411c5cc47 | refs/heads/master | 2020-04-06T07:53:23.992743 | 2018-01-23T22:00:11 | 2018-01-23T22:00:11 | 64,075,574 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 62,970 | cpp | /****************************************************************************
Copyright (c) 2013 Zynga Inc.
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "2d/CCLabel.h"
#include <algorithm>
#include "2d/CCFont.h"
#include "2d/CCFontAtlasCache.h"
#include "2d/CCFontAtlas.h"
#include "2d/CCSprite.h"
#include "2d/CCSpriteBatchNode.h"
#include "2d/CCDrawNode.h"
#include "2d/CCCamera.h"
#include "base/ccUTF8.h"
#include "platform/CCFileUtils.h"
#include "renderer/CCRenderer.h"
#include "renderer/ccGLStateCache.h"
#include "base/CCDirector.h"
#include "base/CCEventListenerCustom.h"
#include "base/CCEventDispatcher.h"
#include "base/CCEventCustom.h"
#include "2d/CCFontFNT.h"
NS_CC_BEGIN
/**
* LabelLetter used to update the quad in texture atlas without SpriteBatchNode.
*/
class LabelLetter : public Sprite
{
public:
LabelLetter()
{
_textureAtlas = nullptr;
_letterVisible = true;
}
static LabelLetter* createWithTexture(Texture2D *texture, const Rect& rect, bool rotated = false)
{
auto letter = new (std::nothrow) LabelLetter();
if (letter && letter->initWithTexture(texture, rect, rotated))
{
letter->Sprite::setVisible(false);
letter->autorelease();
return letter;
}
CC_SAFE_DELETE(letter);
return nullptr;
}
CREATE_FUNC(LabelLetter);
virtual void updateTransform() override
{
if (isDirty())
{
_transformToBatch = getNodeToParentTransform();
Size &size = _rect.size;
float x1 = _offsetPosition.x;
float y1 = _offsetPosition.y;
float x2 = x1 + size.width;
float y2 = y1 + size.height;
if (_flippedX)
{
std::swap(x1, x2);
}
if (_flippedY)
{
std::swap(y1, y2);
}
float x = _transformToBatch.m[12];
float y = _transformToBatch.m[13];
float cr = _transformToBatch.m[0];
float sr = _transformToBatch.m[1];
float cr2 = _transformToBatch.m[5];
float sr2 = -_transformToBatch.m[4];
float ax = x1 * cr - y1 * sr2 + x;
float ay = x1 * sr + y1 * cr2 + y;
float bx = x2 * cr - y1 * sr2 + x;
float by = x2 * sr + y1 * cr2 + y;
float cx = x2 * cr - y2 * sr2 + x;
float cy = x2 * sr + y2 * cr2 + y;
float dx = x1 * cr - y2 * sr2 + x;
float dy = x1 * sr + y2 * cr2 + y;
_quad.bl.vertices.set(SPRITE_RENDER_IN_SUBPIXEL(ax), SPRITE_RENDER_IN_SUBPIXEL(ay), _positionZ);
_quad.br.vertices.set(SPRITE_RENDER_IN_SUBPIXEL(bx), SPRITE_RENDER_IN_SUBPIXEL(by), _positionZ);
_quad.tl.vertices.set(SPRITE_RENDER_IN_SUBPIXEL(dx), SPRITE_RENDER_IN_SUBPIXEL(dy), _positionZ);
_quad.tr.vertices.set(SPRITE_RENDER_IN_SUBPIXEL(cx), SPRITE_RENDER_IN_SUBPIXEL(cy), _positionZ);
if (_textureAtlas)
{
_textureAtlas->updateQuad(&_quad, _atlasIndex);
}
_recursiveDirty = false;
setDirty(false);
}
Node::updateTransform();
}
virtual void updateColor() override
{
if (_textureAtlas == nullptr)
{
return;
}
auto displayedOpacity = _displayedOpacity;
if(!_letterVisible)
{
displayedOpacity = 0.0f;
}
Color4B color4(_displayedColor.r, _displayedColor.g, _displayedColor.b, displayedOpacity);
// special opacity for premultiplied textures
if (_opacityModifyRGB)
{
color4.r *= displayedOpacity / 255.0f;
color4.g *= displayedOpacity / 255.0f;
color4.b *= displayedOpacity / 255.0f;
}
_quad.bl.colors = color4;
_quad.br.colors = color4;
_quad.tl.colors = color4;
_quad.tr.colors = color4;
_textureAtlas->updateQuad(&_quad, _atlasIndex);
}
void setVisible(bool visible) override
{
_letterVisible = visible;
updateColor();
}
//LabelLetter doesn't need to draw directly.
void draw(Renderer *renderer, const Mat4 &transform, uint32_t flags) override
{
}
private:
bool _letterVisible;
};
Label* Label::create()
{
auto ret = new (std::nothrow) Label;
if (ret)
{
ret->autorelease();
}
return ret;
}
Label* Label::create(const std::string& text, const std::string& font, float fontSize, const Size& dimensions /* = Size::ZERO */, TextHAlignment hAlignment /* = TextHAlignment::LEFT */, TextVAlignment vAlignment /* = TextVAlignment::TOP */)
{
if (FileUtils::getInstance()->isFileExist(font))
{
return createWithTTF(text,font,fontSize,dimensions,hAlignment,vAlignment);
}
else
{
return createWithSystemFont(text,font,fontSize,dimensions,hAlignment,vAlignment);
}
}
Label* Label::createWithSystemFont(const std::string& text, const std::string& font, float fontSize, const Size& dimensions /* = Size::ZERO */, TextHAlignment hAlignment /* = TextHAlignment::LEFT */, TextVAlignment vAlignment /* = TextVAlignment::TOP */)
{
auto ret = new (std::nothrow) Label(hAlignment,vAlignment);
if (ret)
{
ret->setSystemFontName(font);
ret->setSystemFontSize(fontSize);
ret->setDimensions(dimensions.width, dimensions.height);
ret->setString(text);
ret->autorelease();
return ret;
}
return nullptr;
}
Label* Label::createWithTTF(const std::string& text, const std::string& fontFile, float fontSize, const Size& dimensions /* = Size::ZERO */, TextHAlignment hAlignment /* = TextHAlignment::LEFT */, TextVAlignment vAlignment /* = TextVAlignment::TOP */)
{
auto ret = new (std::nothrow) Label(hAlignment,vAlignment);
if (ret && ret->initWithTTF(text, fontFile, fontSize, dimensions, hAlignment, vAlignment))
{
ret->autorelease();
return ret;
}
CC_SAFE_DELETE(ret);
return nullptr;
}
Label* Label::createWithTTF(const TTFConfig& ttfConfig, const std::string& text, TextHAlignment hAlignment /* = TextHAlignment::CENTER */, int maxLineWidth /* = 0 */)
{
auto ret = new (std::nothrow) Label(hAlignment);
if (ret && ret->initWithTTF(ttfConfig, text, hAlignment, maxLineWidth))
{
ret->autorelease();
return ret;
}
CC_SAFE_DELETE(ret);
return nullptr;
}
Label* Label::createWithBMFont(const std::string& bmfontFilePath, const std::string& text,const TextHAlignment& hAlignment /* = TextHAlignment::LEFT */, int maxLineWidth /* = 0 */, const Vec2& imageOffset /* = Vec2::ZERO */)
{
auto ret = new (std::nothrow) Label(hAlignment);
if (ret && ret->setBMFontFilePath(bmfontFilePath,imageOffset))
{
ret->setMaxLineWidth(maxLineWidth);
ret->setString(text);
ret->autorelease();
return ret;
}
delete ret;
return nullptr;
}
Label* Label::createWithCharMap(const std::string& plistFile)
{
auto ret = new (std::nothrow) Label();
if (ret && ret->setCharMap(plistFile))
{
ret->autorelease();
return ret;
}
delete ret;
return nullptr;
}
Label* Label::createWithCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap)
{
auto ret = new (std::nothrow) Label();
if (ret && ret->setCharMap(texture,itemWidth,itemHeight,startCharMap))
{
ret->autorelease();
return ret;
}
delete ret;
return nullptr;
}
Label* Label::createWithCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap)
{
auto ret = new (std::nothrow) Label();
if (ret && ret->setCharMap(charMapFile,itemWidth,itemHeight,startCharMap))
{
ret->autorelease();
return ret;
}
delete ret;
return nullptr;
}
bool Label::setCharMap(const std::string& plistFile)
{
auto newAtlas = FontAtlasCache::getFontAtlasCharMap(plistFile);
if (!newAtlas)
{
reset();
return false;
}
_currentLabelType = LabelType::CHARMAP;
setFontAtlas(newAtlas);
return true;
}
bool Label::initWithTTF(const std::string& text, const std::string& fontFilePath, float fontSize,
const Size& dimensions, TextHAlignment hAlignment, TextVAlignment vAlignment)
{
if (FileUtils::getInstance()->isFileExist(fontFilePath))
{
TTFConfig ttfConfig(fontFilePath, fontSize, GlyphCollection::DYNAMIC);
if (setTTFConfig(ttfConfig))
{
setDimensions(dimensions.width, dimensions.height);
setString(text);
}
return true;
}
return false;
}
bool Label::initWithTTF(const TTFConfig& ttfConfig, const std::string& text, TextHAlignment hAlignment, int maxLineWidth)
{
if (FileUtils::getInstance()->isFileExist(ttfConfig.fontFilePath) && setTTFConfig(ttfConfig))
{
setMaxLineWidth(maxLineWidth);
setString(text);
return true;
}
return false;
}
bool Label::setCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap)
{
auto newAtlas = FontAtlasCache::getFontAtlasCharMap(texture,itemWidth,itemHeight,startCharMap);
if (!newAtlas)
{
reset();
return false;
}
_currentLabelType = LabelType::CHARMAP;
setFontAtlas(newAtlas);
return true;
}
bool Label::setCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap)
{
auto newAtlas = FontAtlasCache::getFontAtlasCharMap(charMapFile,itemWidth,itemHeight,startCharMap);
if (!newAtlas)
{
reset();
return false;
}
_currentLabelType = LabelType::CHARMAP;
setFontAtlas(newAtlas);
return true;
}
Label::Label(TextHAlignment hAlignment /* = TextHAlignment::LEFT */,
TextVAlignment vAlignment /* = TextVAlignment::TOP */)
: _textSprite(nullptr)
, _shadowNode(nullptr)
, _fontAtlas(nullptr)
, _reusedLetter(nullptr)
, _horizontalKernings(nullptr)
, _boldEnabled(false)
, _underlineNode(nullptr)
, _strikethroughEnabled(false)
{
setAnchorPoint(Vec2::ANCHOR_MIDDLE);
reset();
_hAlignment = hAlignment;
_vAlignment = vAlignment;
#if CC_LABEL_DEBUG_DRAW
_debugDrawNode = DrawNode::create();
addChild(_debugDrawNode);
#endif
_purgeTextureListener = EventListenerCustom::create(FontAtlas::CMD_PURGE_FONTATLAS, [this](EventCustom* event){
if (_fontAtlas && _currentLabelType == LabelType::TTF && event->getUserData() == _fontAtlas)
{
for (auto&& it : _letters)
{
it.second->setTexture(nullptr);
}
_batchNodes.clear();
if (_fontAtlas)
{
FontAtlasCache::releaseFontAtlas(_fontAtlas);
}
}
});
_eventDispatcher->addEventListenerWithFixedPriority(_purgeTextureListener, 1);
_resetTextureListener = EventListenerCustom::create(FontAtlas::CMD_RESET_FONTATLAS, [this](EventCustom* event){
if (_fontAtlas && _currentLabelType == LabelType::TTF && event->getUserData() == _fontAtlas)
{
_fontAtlas = nullptr;
this->setTTFConfig(_fontConfig);
for (auto&& it : _letters)
{
getLetter(it.first);
}
}
});
_eventDispatcher->addEventListenerWithFixedPriority(_resetTextureListener, 2);
}
Label::~Label()
{
delete [] _horizontalKernings;
if (_fontAtlas)
{
Node::removeAllChildrenWithCleanup(true);
CC_SAFE_RELEASE_NULL(_reusedLetter);
_batchNodes.clear();
FontAtlasCache::releaseFontAtlas(_fontAtlas);
}
_eventDispatcher->removeEventListener(_purgeTextureListener);
_eventDispatcher->removeEventListener(_resetTextureListener);
CC_SAFE_RELEASE_NULL(_textSprite);
CC_SAFE_RELEASE_NULL(_shadowNode);
}
void Label::reset()
{
CC_SAFE_RELEASE_NULL(_textSprite);
CC_SAFE_RELEASE_NULL(_shadowNode);
Node::removeAllChildrenWithCleanup(true);
CC_SAFE_RELEASE_NULL(_reusedLetter);
_letters.clear();
_batchNodes.clear();
_lettersInfo.clear();
if (_fontAtlas)
{
FontAtlasCache::releaseFontAtlas(_fontAtlas);
_fontAtlas = nullptr;
}
_currentLabelType = LabelType::STRING_TEXTURE;
_currLabelEffect = LabelEffect::NORMAL;
_contentDirty = false;
_numberOfLines = 0;
_lengthOfString = 0;
_utf16Text.clear();
_utf8Text.clear();
TTFConfig temp;
_fontConfig = temp;
_outlineSize = 0.f;
_bmFontPath = "";
_systemFontDirty = false;
_systemFont = "Helvetica";
_systemFontSize = 12;
if (_horizontalKernings)
{
delete[] _horizontalKernings;
_horizontalKernings = nullptr;
}
_additionalKerning = 0.f;
_lineHeight = 0.f;
_lineSpacing = 0.f;
_maxLineWidth = 0.f;
_labelDimensions.width = 0.f;
_labelDimensions.height = 0.f;
_labelWidth = 0.f;
_labelHeight = 0.f;
_lineBreakWithoutSpaces = false;
_hAlignment = TextHAlignment::LEFT;
_vAlignment = TextVAlignment::TOP;
_effectColorF = Color4F::BLACK;
_textColor = Color4B::WHITE;
_textColorF = Color4F::WHITE;
setColor(Color3B::WHITE);
_shadowDirty = false;
_shadowEnabled = false;
_shadowBlurRadius = 0.f;
_useDistanceField = false;
_useA8Shader = false;
_clipEnabled = false;
_blendFuncDirty = false;
_blendFunc = BlendFunc::ALPHA_PREMULTIPLIED;
_isOpacityModifyRGB = false;
_insideBounds = true;
_enableWrap = true;
_bmFontSize = -1;
_bmfontScale = 1.0f;
_overflow = Overflow::NONE;
_originalFontSize = 0.0f;
_boldEnabled = false;
if (_underlineNode)
{
removeChild(_underlineNode);
_underlineNode = nullptr;
}
_strikethroughEnabled = false;
setRotationSkewX(0); // reverse italics
}
void Label::updateShaderProgram()
{
switch (_currLabelEffect)
{
case cocos2d::LabelEffect::NORMAL:
if (_useDistanceField)
setGLProgramState(GLProgramState::getOrCreateWithGLProgramName(GLProgram::SHADER_NAME_LABEL_DISTANCEFIELD_NORMAL));
else if (_useA8Shader)
setGLProgramState(GLProgramState::getOrCreateWithGLProgramName(GLProgram::SHADER_NAME_LABEL_NORMAL));
else if (_shadowEnabled)
setGLProgramState(GLProgramState::getOrCreateWithGLProgramName(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR));
else
setGLProgramState(GLProgramState::getOrCreateWithGLProgramName(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP));
break;
case cocos2d::LabelEffect::OUTLINE:
setGLProgramState(GLProgramState::getOrCreateWithGLProgramName(GLProgram::SHADER_NAME_LABEL_OUTLINE));
_uniformEffectColor = glGetUniformLocation(getGLProgram()->getProgram(), "u_effectColor");
break;
case cocos2d::LabelEffect::GLOW:
if (_useDistanceField)
{
setGLProgramState(GLProgramState::getOrCreateWithGLProgramName(GLProgram::SHADER_NAME_LABEL_DISTANCEFIELD_GLOW));
_uniformEffectColor = glGetUniformLocation(getGLProgram()->getProgram(), "u_effectColor");
}
break;
default:
return;
}
_uniformTextColor = glGetUniformLocation(getGLProgram()->getProgram(), "u_textColor");
}
void Label::setFontAtlas(FontAtlas* atlas,bool distanceFieldEnabled /* = false */, bool useA8Shader /* = false */)
{
if(atlas)
{
_systemFontDirty = false;
}
if (atlas == _fontAtlas)
{
FontAtlasCache::releaseFontAtlas(atlas);
return;
}
if (_fontAtlas)
{
_batchNodes.clear();
FontAtlasCache::releaseFontAtlas(_fontAtlas);
_fontAtlas = nullptr;
}
_fontAtlas = atlas;
if (_reusedLetter == nullptr)
{
_reusedLetter = Sprite::create();
_reusedLetter->setOpacityModifyRGB(_isOpacityModifyRGB);
_reusedLetter->retain();
_reusedLetter->setAnchorPoint(Vec2::ANCHOR_TOP_LEFT);
}
if (_fontAtlas)
{
_lineHeight = _fontAtlas->getLineHeight();
_contentDirty = true;
_systemFontDirty = false;
}
_useDistanceField = distanceFieldEnabled;
_useA8Shader = useA8Shader;
if (_currentLabelType != LabelType::TTF)
{
_currLabelEffect = LabelEffect::NORMAL;
updateShaderProgram();
}
}
bool Label::setTTFConfig(const TTFConfig& ttfConfig)
{
_originalFontSize = ttfConfig.fontSize;
return setTTFConfigInternal(ttfConfig);
}
bool Label::setBMFontFilePath(const std::string& bmfontFilePath, const Vec2& imageOffset, float fontSize)
{
FontAtlas *newAtlas = FontAtlasCache::getFontAtlasFNT(bmfontFilePath,imageOffset);
if (!newAtlas)
{
reset();
return false;
}
//assign the default fontSize
if (fabs(fontSize) < FLT_EPSILON) {
FontFNT *bmFont = (FontFNT*)newAtlas->getFont();
if (bmFont) {
float originalFontSize = bmFont->getOriginalFontSize();
_bmFontSize = originalFontSize / CC_CONTENT_SCALE_FACTOR();
}
}
if(fontSize > 0.0f){
_bmFontSize = fontSize;
}
_bmFontPath = bmfontFilePath;
_currentLabelType = LabelType::BMFONT;
setFontAtlas(newAtlas);
return true;
}
void Label::setString(const std::string& text)
{
if (text.compare(_utf8Text))
{
_utf8Text = text;
_contentDirty = true;
std::u16string utf16String;
if (StringUtils::UTF8ToUTF16(_utf8Text, utf16String))
{
_utf16Text = utf16String;
}
}
}
void Label::setAlignment(TextHAlignment hAlignment,TextVAlignment vAlignment)
{
if (hAlignment != _hAlignment || vAlignment != _vAlignment)
{
_hAlignment = hAlignment;
_vAlignment = vAlignment;
_contentDirty = true;
}
}
void Label::setMaxLineWidth(float maxLineWidth)
{
if (_labelWidth == 0 && _maxLineWidth != maxLineWidth)
{
_maxLineWidth = maxLineWidth;
_contentDirty = true;
}
}
void Label::setDimensions(float width, float height)
{
if(_overflow == Overflow::RESIZE_HEIGHT){
height = 0;
}
if (height != _labelHeight || width != _labelWidth)
{
_labelWidth = width;
_labelHeight = height;
_labelDimensions.width = width;
_labelDimensions.height = height;
_maxLineWidth = width;
_contentDirty = true;
if(_overflow == Overflow::SHRINK){
if (_originalFontSize > 0) {
this->restoreFontSize();
}
}
}
}
void Label::restoreFontSize()
{
if(_currentLabelType == LabelType::TTF){
auto ttfConfig = this->getTTFConfig();
ttfConfig.fontSize = _originalFontSize;
this->setTTFConfigInternal(ttfConfig);
}else if(_currentLabelType == LabelType::BMFONT){
this->setBMFontSizeInternal(_originalFontSize);
}else if(_currentLabelType == LabelType::STRING_TEXTURE){
this->setSystemFontSize(_originalFontSize);
}
}
void Label::setLineBreakWithoutSpace(bool breakWithoutSpace)
{
if (breakWithoutSpace != _lineBreakWithoutSpaces)
{
_lineBreakWithoutSpaces = breakWithoutSpace;
_contentDirty = true;
}
}
void Label::updateLabelLetters()
{
if (!_letters.empty())
{
Rect uvRect;
LabelLetter* letterSprite;
int letterIndex;
for (auto it = _letters.begin(); it != _letters.end();)
{
letterIndex = it->first;
letterSprite = (LabelLetter*)it->second;
if (letterIndex >= _lengthOfString)
{
Node::removeChild(letterSprite, true);
it = _letters.erase(it);
}
else
{
auto& letterInfo = _lettersInfo[letterIndex];
auto& letterDef = _fontAtlas->_letterDefinitions[letterInfo.utf16Char];
uvRect.size.height = letterDef.height;
uvRect.size.width = letterDef.width;
uvRect.origin.x = letterDef.U;
uvRect.origin.y = letterDef.V;
auto batchNode = _batchNodes.at(letterDef.textureID);
letterSprite->setTextureAtlas(batchNode->getTextureAtlas());
letterSprite->setTexture(_fontAtlas->getTexture(letterDef.textureID));
if (letterDef.width <= 0.f || letterDef.height <= 0.f)
{
letterSprite->setTextureAtlas(nullptr);
}
else
{
letterSprite->setTextureRect(uvRect, false, uvRect.size);
letterSprite->setTextureAtlas(_batchNodes.at(letterDef.textureID)->getTextureAtlas());
letterSprite->setAtlasIndex(_lettersInfo[letterIndex].atlasIndex);
}
auto px = letterInfo.positionX + letterDef.width / 2 + _linesOffsetX[letterInfo.lineIndex];
auto py = letterInfo.positionY - letterDef.height / 2 + _letterOffsetY;
letterSprite->setPosition(px, py);
this->updateLetterSpriteScale(letterSprite);
++it;
}
}
}
}
bool Label::alignText()
{
if (_fontAtlas == nullptr || _utf16Text.empty())
{
setContentSize(Size::ZERO);
return true;
}
bool ret = true;
do {
_fontAtlas->prepareLetterDefinitions(_utf16Text);
auto& textures = _fontAtlas->getTextures();
if (textures.size() > static_cast<size_t>(_batchNodes.size()))
{
for (auto index = static_cast<size_t>(_batchNodes.size()); index < textures.size(); ++index)
{
auto batchNode = SpriteBatchNode::createWithTexture(textures.at(index));
if (batchNode)
{
_isOpacityModifyRGB = batchNode->getTexture()->hasPremultipliedAlpha();
_blendFunc = batchNode->getBlendFunc();
batchNode->setAnchorPoint(Vec2::ANCHOR_TOP_LEFT);
batchNode->setPosition(Vec2::ZERO);
_batchNodes.pushBack(batchNode);
}
}
}
if (_batchNodes.empty())
{
return true;
}
_reusedLetter->setBatchNode(_batchNodes.at(0));
_lengthOfString = 0;
_textDesiredHeight = 0.f;
_linesWidth.clear();
if (_maxLineWidth > 0.f && !_lineBreakWithoutSpaces)
{
multilineTextWrapByWord();
}
else
{
multilineTextWrapByChar();
}
computeAlignmentOffset();
if(_overflow == Overflow::SHRINK){
float fontSize = this->getRenderingFontSize();
if(fontSize > 0 && isVerticalClamp()){
this->shrinkLabelToContentSize(CC_CALLBACK_0(Label::isVerticalClamp, this));
}
}
if(!updateQuads()){
ret = false;
if(_overflow == Overflow::SHRINK){
this->shrinkLabelToContentSize(CC_CALLBACK_0(Label::isHorizontalClamp, this));
}
break;
}
updateLabelLetters();
updateColor();
}while (0);
return ret;
}
bool Label::computeHorizontalKernings(const std::u16string& stringToRender)
{
if (_horizontalKernings)
{
delete [] _horizontalKernings;
_horizontalKernings = nullptr;
}
int letterCount = 0;
_horizontalKernings = _fontAtlas->getFont()->getHorizontalKerningForTextUTF16(stringToRender, letterCount);
if(!_horizontalKernings)
return false;
else
return true;
}
bool Label::isHorizontalClamped(float letterPositionX, int lineIndex)
{
auto wordWidth = this->_linesWidth[lineIndex];
bool letterOverClamp = (letterPositionX > _contentSize.width || letterPositionX < 0);
if (!_enableWrap) {
return letterOverClamp;
}else{
return (wordWidth > this->_contentSize.width && letterOverClamp);
}
}
bool Label::updateQuads()
{
bool ret = true;
for (auto&& batchNode : _batchNodes)
{
batchNode->getTextureAtlas()->removeAllQuads();
}
bool letterClamp = false;
for (int ctr = 0; ctr < _lengthOfString; ++ctr)
{
if (_lettersInfo[ctr].valid)
{
auto& letterDef = _fontAtlas->_letterDefinitions[_lettersInfo[ctr].utf16Char];
_reusedRect.size.height = letterDef.height;
_reusedRect.size.width = letterDef.width;
_reusedRect.origin.x = letterDef.U;
_reusedRect.origin.y = letterDef.V;
auto py = _lettersInfo[ctr].positionY + _letterOffsetY;
if (_labelHeight > 0.f) {
if (py > _tailoredTopY)
{
auto clipTop = py - _tailoredTopY;
_reusedRect.origin.y += clipTop;
_reusedRect.size.height -= clipTop;
py -= clipTop;
}
if (py - letterDef.height * _bmfontScale < _tailoredBottomY)
{
_reusedRect.size.height = (py < _tailoredBottomY) ? 0.f : (py - _tailoredBottomY);
}
}
auto lineIndex = _lettersInfo[ctr].lineIndex;
auto px = _lettersInfo[ctr].positionX + letterDef.width/2 * _bmfontScale + _linesOffsetX[lineIndex];
if(_labelWidth > 0.f){
if (this->isHorizontalClamped(px, lineIndex)) {
if(_overflow == Overflow::CLAMP){
_reusedRect.size.width = 0;
}else if(_overflow == Overflow::SHRINK){
if (_contentSize.width > letterDef.width) {
letterClamp = true;
ret = false;
break;
}else{
_reusedRect.size.width = 0;
}
}
}
}
if (_reusedRect.size.height > 0.f && _reusedRect.size.width > 0.f)
{
_reusedLetter->setTextureRect(_reusedRect, false, _reusedRect.size);
float letterPositionX = _lettersInfo[ctr].positionX + _linesOffsetX[_lettersInfo[ctr].lineIndex];
_reusedLetter->setPosition(letterPositionX, py);
auto index = static_cast<int>(_batchNodes.at(letterDef.textureID)->getTextureAtlas()->getTotalQuads());
_lettersInfo[ctr].atlasIndex = index;
this->updateLetterSpriteScale(_reusedLetter);
_batchNodes.at(letterDef.textureID)->insertQuadFromSprite(_reusedLetter, index);
}
}
}
return ret;
}
bool Label::setTTFConfigInternal(const TTFConfig& ttfConfig)
{
FontAtlas *newAtlas = FontAtlasCache::getFontAtlasTTF(&ttfConfig);
if (!newAtlas)
{
reset();
return false;
}
_currentLabelType = LabelType::TTF;
setFontAtlas(newAtlas,ttfConfig.distanceFieldEnabled,true);
_fontConfig = ttfConfig;
if (_fontConfig.outlineSize > 0)
{
_fontConfig.distanceFieldEnabled = false;
_useDistanceField = false;
_useA8Shader = false;
_currLabelEffect = LabelEffect::OUTLINE;
updateShaderProgram();
}
else
{
_currLabelEffect = LabelEffect::NORMAL;
updateShaderProgram();
}
if (_fontConfig.italics)
this->enableItalics();
if (_fontConfig.bold)
this->enableBold();
if (_fontConfig.underline)
this->enableUnderline();
if (_fontConfig.strikethrough)
this->enableStrikethrough();
return true;
}
void Label::setBMFontSizeInternal(float fontSize)
{
if(_currentLabelType == LabelType::BMFONT){
this->setBMFontFilePath(_bmFontPath, Vec2::ZERO, fontSize);
_contentDirty = true;
}
}
void Label::scaleFontSizeDown(float fontSize)
{
bool shouldUpdateContent = true;
if(_currentLabelType == LabelType::TTF){
auto ttfConfig = this->getTTFConfig();
ttfConfig.fontSize = fontSize;
this->setTTFConfigInternal(ttfConfig);
}else if(_currentLabelType == LabelType::BMFONT){
if (fabs(fontSize) < FLT_EPSILON) {
fontSize = 0.1f;
shouldUpdateContent = false;
}
this->setBMFontSizeInternal(fontSize);
}else if (_currentLabelType == LabelType::STRING_TEXTURE){
this->setSystemFontSize(fontSize);
}
if (shouldUpdateContent) {
this->updateContent();
}
}
void Label::enableGlow(const Color4B& glowColor)
{
if (_currentLabelType == LabelType::TTF)
{
if (_fontConfig.distanceFieldEnabled == false)
{
auto config = _fontConfig;
config.outlineSize = 0;
config.distanceFieldEnabled = true;
setTTFConfig(config);
_contentDirty = true;
}
_currLabelEffect = LabelEffect::GLOW;
_effectColorF.r = glowColor.r / 255.0f;
_effectColorF.g = glowColor.g / 255.0f;
_effectColorF.b = glowColor.b / 255.0f;
_effectColorF.a = glowColor.a / 255.0f;
updateShaderProgram();
}
}
void Label::enableOutline(const Color4B& outlineColor,int outlineSize /* = -1 */)
{
CCASSERT(_currentLabelType == LabelType::STRING_TEXTURE || _currentLabelType == LabelType::TTF, "Only supported system font and TTF!");
if (outlineSize > 0 || _currLabelEffect == LabelEffect::OUTLINE)
{
if (_currentLabelType == LabelType::TTF)
{
_effectColorF.r = outlineColor.r / 255.0f;
_effectColorF.g = outlineColor.g / 255.0f;
_effectColorF.b = outlineColor.b / 255.0f;
_effectColorF.a = outlineColor.a / 255.0f;
if (outlineSize > 0 && _fontConfig.outlineSize != outlineSize)
{
_fontConfig.outlineSize = outlineSize;
setTTFConfig(_fontConfig);
}
}
else if (_effectColorF != outlineColor || _outlineSize != outlineSize)
{
_effectColorF.r = outlineColor.r / 255.f;
_effectColorF.g = outlineColor.g / 255.f;
_effectColorF.b = outlineColor.b / 255.f;
_effectColorF.a = outlineColor.a / 255.f;
_currLabelEffect = LabelEffect::OUTLINE;
_contentDirty = true;
}
_outlineSize = outlineSize;
}
}
void Label::enableShadow(const Color4B& shadowColor /* = Color4B::BLACK */,const Size &offset /* = Size(2 ,-2)*/, int blurRadius /* = 0 */)
{
_shadowEnabled = true;
_shadowDirty = true;
_shadowOffset.width = offset.width;
_shadowOffset.height = offset.height;
//TODO: support blur for shadow
_shadowColor3B.r = shadowColor.r;
_shadowColor3B.g = shadowColor.g;
_shadowColor3B.b = shadowColor.b;
_shadowOpacity = shadowColor.a;
if (!_systemFontDirty && !_contentDirty && _textSprite)
{
auto fontDef = _getFontDefinition();
if (_shadowNode)
{
if (shadowColor != _shadowColor4F)
{
_shadowNode->release();
_shadowNode = nullptr;
createShadowSpriteForSystemFont(fontDef);
}
else
{
_shadowNode->setPosition(_shadowOffset.width, _shadowOffset.height);
}
}
else
{
createShadowSpriteForSystemFont(fontDef);
}
}
_shadowColor4F.r = shadowColor.r / 255.0f;
_shadowColor4F.g = shadowColor.g / 255.0f;
_shadowColor4F.b = shadowColor.b / 255.0f;
_shadowColor4F.a = shadowColor.a / 255.0f;
if (_currentLabelType == LabelType::BMFONT || _currentLabelType == LabelType::CHARMAP)
{
if (_shadowEnabled)
{
setGLProgramState(GLProgramState::getOrCreateWithGLProgramName(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR));
}
else
{
setGLProgramState(GLProgramState::getOrCreateWithGLProgramName(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP));
}
}
}
void Label::enableItalics()
{
setRotationSkewX(12);
}
void Label::enableBold()
{
if (!_boldEnabled)
{
// bold is implemented with outline
enableShadow(Color4B::WHITE, Size(0.9f, 0), 0);
// add one to kerning
setAdditionalKerning(_additionalKerning+1);
_boldEnabled = true;
}
}
void Label::enableUnderline()
{
// remove it, just in case to prevent adding two or more
if (!_underlineNode)
{
_underlineNode = DrawNode::create();
addChild(_underlineNode, 100000);
_contentDirty = true;
}
}
void Label::enableStrikethrough()
{
if (!_strikethroughEnabled)
{
enableUnderline();
_strikethroughEnabled = true;
}
}
void Label::disableEffect()
{
disableEffect(LabelEffect::ALL);
}
void Label::disableEffect(LabelEffect effect)
{
switch (effect)
{
case cocos2d::LabelEffect::NORMAL:
break;
case cocos2d::LabelEffect::OUTLINE:
if (_currLabelEffect == LabelEffect::OUTLINE)
{
if (_currentLabelType == LabelType::TTF)
{
_fontConfig.outlineSize = 0;
setTTFConfig(_fontConfig);
}
_currLabelEffect = LabelEffect::NORMAL;
_contentDirty = true;
}
break;
case cocos2d::LabelEffect::SHADOW:
if (_shadowEnabled)
{
_shadowEnabled = false;
CC_SAFE_RELEASE_NULL(_shadowNode);
updateShaderProgram();
}
break;
case cocos2d::LabelEffect::GLOW:
if (_currLabelEffect == LabelEffect::GLOW)
{
_currLabelEffect = LabelEffect::NORMAL;
updateShaderProgram();
}
break;
case cocos2d::LabelEffect::ITALICS:
setRotationSkewX(0);
break;
case cocos2d::LabelEffect::BOLD:
_boldEnabled = false;
_additionalKerning -= 1;
disableEffect(LabelEffect::SHADOW);
break;
case cocos2d::LabelEffect::UNDERLINE:
if (_underlineNode) {
removeChild(_underlineNode);
_underlineNode = nullptr;
}
break;
case cocos2d::LabelEffect::STRIKETHROUGH:
_strikethroughEnabled = false;
// since it is based on underline, disable it as well
disableEffect(LabelEffect::UNDERLINE);
break;
case LabelEffect::ALL:
{
disableEffect(LabelEffect::SHADOW);
disableEffect(LabelEffect::GLOW);
disableEffect(LabelEffect::OUTLINE);
disableEffect(LabelEffect::ITALICS);
disableEffect(LabelEffect::BOLD);
disableEffect(LabelEffect::UNDERLINE);
disableEffect(LabelEffect::STRIKETHROUGH);
}
break;
default:
break;
}
}
void Label::createSpriteForSystemFont(const FontDefinition& fontDef)
{
_currentLabelType = LabelType::STRING_TEXTURE;
auto texture = new (std::nothrow) Texture2D;
texture->initWithString(_utf8Text.c_str(), fontDef);
_textSprite = Sprite::createWithTexture(texture);
//set camera mask using label's camera mask, because _textSprite may be null when setting camera mask to label
_textSprite->setCameraMask(getCameraMask());
_textSprite->setGlobalZOrder(getGlobalZOrder());
_textSprite->setAnchorPoint(Vec2::ANCHOR_BOTTOM_LEFT);
this->setContentSize(_textSprite->getContentSize());
texture->release();
if (_blendFuncDirty)
{
_textSprite->setBlendFunc(_blendFunc);
}
_textSprite->retain();
_textSprite->updateDisplayedColor(_displayedColor);
_textSprite->updateDisplayedOpacity(_displayedOpacity);
}
void Label::createShadowSpriteForSystemFont(const FontDefinition& fontDef)
{
if (!fontDef._stroke._strokeEnabled && fontDef._fontFillColor == _shadowColor3B
&& (fontDef._fontAlpha == _shadowOpacity))
{
_shadowNode = Sprite::createWithTexture(_textSprite->getTexture());
}
else
{
FontDefinition shadowFontDefinition = fontDef;
shadowFontDefinition._fontFillColor.r = _shadowColor3B.r;
shadowFontDefinition._fontFillColor.g = _shadowColor3B.g;
shadowFontDefinition._fontFillColor.b = _shadowColor3B.b;
shadowFontDefinition._fontAlpha = _shadowOpacity;
shadowFontDefinition._stroke._strokeColor = shadowFontDefinition._fontFillColor;
shadowFontDefinition._stroke._strokeAlpha = shadowFontDefinition._fontAlpha;
auto texture = new (std::nothrow) Texture2D;
texture->initWithString(_utf8Text.c_str(), shadowFontDefinition);
_shadowNode = Sprite::createWithTexture(texture);
texture->release();
}
if (_shadowNode)
{
if (_blendFuncDirty)
{
_shadowNode->setBlendFunc(_blendFunc);
}
_shadowNode->setCameraMask(getCameraMask());
_shadowNode->setGlobalZOrder(getGlobalZOrder());
_shadowNode->setAnchorPoint(Vec2::ANCHOR_BOTTOM_LEFT);
_shadowNode->setPosition(_shadowOffset.width, _shadowOffset.height);
_shadowNode->retain();
_shadowNode->updateDisplayedColor(_displayedColor);
_shadowNode->updateDisplayedOpacity(_displayedOpacity);
}
}
void Label::setCameraMask(unsigned short mask, bool applyChildren)
{
Node::setCameraMask(mask, applyChildren);
if (_textSprite)
{
_textSprite->setCameraMask(mask, applyChildren);
}
if (_shadowNode)
{
_shadowNode->setCameraMask(mask, applyChildren);
}
}
void Label::setFontDefinition(const FontDefinition& textDefinition)
{
_systemFont = textDefinition._fontName;
_systemFontSize = textDefinition._fontSize;
_hAlignment = textDefinition._alignment;
_vAlignment = textDefinition._vertAlignment;
setDimensions(textDefinition._dimensions.width, textDefinition._dimensions.height);
Color4B textColor = Color4B(textDefinition._fontFillColor);
textColor.a = textDefinition._fontAlpha;
setTextColor(textColor);
#if (CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID) && (CC_TARGET_PLATFORM != CC_PLATFORM_IOS)
if (textDefinition._stroke._strokeEnabled)
{
CCLOGERROR("Stroke Currently only supported on iOS and Android!");
}
_outlineSize = 0.f;
#else
if (textDefinition._stroke._strokeEnabled && textDefinition._stroke._strokeSize > 0.f)
{
Color4B outlineColor = Color4B(textDefinition._stroke._strokeColor);
outlineColor.a = textDefinition._stroke._strokeAlpha;
enableOutline(outlineColor, textDefinition._stroke._strokeSize);
}
#endif
if (textDefinition._shadow._shadowEnabled)
{
enableShadow(Color4B(0, 0, 0, 255 * textDefinition._shadow._shadowOpacity),
textDefinition._shadow._shadowOffset, textDefinition._shadow._shadowBlur);
}
}
void Label::updateContent()
{
if (_systemFontDirty)
{
if (_fontAtlas)
{
_batchNodes.clear();
FontAtlasCache::releaseFontAtlas(_fontAtlas);
_fontAtlas = nullptr;
}
_systemFontDirty = false;
}
CC_SAFE_RELEASE_NULL(_textSprite);
CC_SAFE_RELEASE_NULL(_shadowNode);
bool updateFinished = true;
if (_fontAtlas)
{
std::u16string utf16String;
if (StringUtils::UTF8ToUTF16(_utf8Text, utf16String))
{
_utf16Text = utf16String;
}
computeHorizontalKernings(_utf16Text);
updateFinished = alignText();
}
else
{
auto fontDef = _getFontDefinition();
createSpriteForSystemFont(fontDef);
if (_shadowEnabled)
{
createShadowSpriteForSystemFont(fontDef);
}
}
if (_underlineNode)
{
_underlineNode->clear();
if (_numberOfLines)
{
const float charheight = (_textDesiredHeight / _numberOfLines);
_underlineNode->setLineWidth(charheight/6);
// atlas font
for (int i=0; i<_numberOfLines; ++i)
{
float offsety = 0;
if (_strikethroughEnabled)
offsety += charheight / 2;
// FIXME: Might not work with different vertical alignments
float y = (_numberOfLines - i - 1) * charheight + offsety;
_underlineNode->drawLine(Vec2(_linesOffsetX[i],y), Vec2(_linesWidth[i] + _linesOffsetX[i],y), _textColorF);
}
}
else if (_textSprite)
{
// system font
float y = 0;
const auto spriteSize = _textSprite->getContentSize();
_underlineNode->setLineWidth(spriteSize.height/6);
if (_strikethroughEnabled)
// FIXME: system fonts don't report the height of the font correctly. only the size of the texture, which is POT
y += spriteSize.height / 2;
// FIXME: Might not work with different vertical alignments
_underlineNode->drawLine(Vec2(0,y), Vec2(spriteSize.width,y), Color4F(_textSprite->getDisplayedColor()));
}
}
if(updateFinished){
_contentDirty = false;
}
#if CC_LABEL_DEBUG_DRAW
_debugDrawNode->clear();
Vec2 vertices[4] =
{
Vec2::ZERO,
Vec2(_contentSize.width, 0),
Vec2(_contentSize.width, _contentSize.height),
Vec2(0, _contentSize.height)
};
_debugDrawNode->drawPoly(vertices, 4, true, Color4F::WHITE);
#endif
}
void Label::setBMFontSize(float fontSize)
{
this->setBMFontSizeInternal(fontSize);
_originalFontSize = fontSize;
}
float Label::getBMFontSize()const
{
return _bmFontSize;
}
void Label::onDrawShadow(GLProgram* glProgram, const Color4F& shadowColor)
{
if (_currentLabelType == LabelType::TTF)
{
glProgram->setUniformLocationWith4f(_uniformTextColor,
shadowColor.r, shadowColor.g, shadowColor.b, shadowColor.a);
if (_currLabelEffect == LabelEffect::OUTLINE || _currLabelEffect == LabelEffect::GLOW)
{
glProgram->setUniformLocationWith4f(_uniformEffectColor,
shadowColor.r, shadowColor.g, shadowColor.b, shadowColor.a);
}
glProgram->setUniformsForBuiltins(_shadowTransform);
for (auto&& it : _letters)
{
it.second->updateTransform();
}
for (auto&& batchNode : _batchNodes)
{
batchNode->getTextureAtlas()->drawQuads();
}
}
else
{
Color3B oldColor = _realColor;
GLubyte oldOPacity = _displayedOpacity;
_displayedOpacity = shadowColor.a * 255;
setColor(Color3B(shadowColor));
glProgram->setUniformsForBuiltins(_shadowTransform);
for (auto&& it : _letters)
{
it.second->updateTransform();
}
for (auto&& batchNode : _batchNodes)
{
batchNode->getTextureAtlas()->drawQuads();
}
_displayedOpacity = oldOPacity;
setColor(oldColor);
}
}
void Label::onDraw(const Mat4& transform, bool transformUpdated)
{
auto glprogram = getGLProgram();
glprogram->use();
GL::blendFunc(_blendFunc.src, _blendFunc.dst);
if (_shadowEnabled)
{
if (_boldEnabled)
onDrawShadow(glprogram, _textColorF);
else
onDrawShadow(glprogram, _shadowColor4F);
}
glprogram->setUniformsForBuiltins(transform);
for (auto&& it : _letters)
{
it.second->updateTransform();
}
if (_currentLabelType == LabelType::TTF)
{
switch (_currLabelEffect) {
case LabelEffect::OUTLINE:
//draw text with outline
glprogram->setUniformLocationWith4f(_uniformTextColor,
_textColorF.r, _textColorF.g, _textColorF.b, _textColorF.a);
glprogram->setUniformLocationWith4f(_uniformEffectColor,
_effectColorF.r, _effectColorF.g, _effectColorF.b, _effectColorF.a);
for (auto&& batchNode : _batchNodes)
{
batchNode->getTextureAtlas()->drawQuads();
}
//draw text without outline
glprogram->setUniformLocationWith4f(_uniformEffectColor,
_effectColorF.r, _effectColorF.g, _effectColorF.b, 0.f);
break;
case LabelEffect::GLOW:
glprogram->setUniformLocationWith4f(_uniformEffectColor,
_effectColorF.r, _effectColorF.g, _effectColorF.b, _effectColorF.a);
case LabelEffect::NORMAL:
glprogram->setUniformLocationWith4f(_uniformTextColor,
_textColorF.r, _textColorF.g, _textColorF.b, _textColorF.a);
break;
default:
break;
}
}
for (auto&& batchNode : _batchNodes)
{
batchNode->getTextureAtlas()->drawQuads();
}
}
void Label::draw(Renderer *renderer, const Mat4 &transform, uint32_t flags)
{
if (_batchNodes.empty() || _lengthOfString <= 0)
{
return;
}
// Don't do calculate the culling if the transform was not updated
bool transformUpdated = flags & FLAGS_TRANSFORM_DIRTY;
#if CC_USE_CULLING
auto visitingCamera = Camera::getVisitingCamera();
auto defaultCamera = Camera::getDefaultCamera();
if (visitingCamera == defaultCamera) {
_insideBounds = (transformUpdated || visitingCamera->isViewProjectionUpdated()) ? renderer->checkVisibility(transform, _contentSize) : _insideBounds;
}
else
{
_insideBounds = renderer->checkVisibility(transform, _contentSize);
}
if (_insideBounds)
#endif
{
if (!_shadowEnabled && (_currentLabelType == LabelType::BMFONT || _currentLabelType == LabelType::CHARMAP))
{
for (auto&& it : _letters)
{
it.second->updateTransform();
}
auto textureAtlas = _batchNodes.at(0)->getTextureAtlas();
_quadCommand.init(_globalZOrder, textureAtlas->getTexture()->getName(), getGLProgramState(),
_blendFunc, textureAtlas->getQuads(), textureAtlas->getTotalQuads(), transform, flags);
renderer->addCommand(&_quadCommand);
}
else
{
_customCommand.init(_globalZOrder, transform, flags);
_customCommand.func = CC_CALLBACK_0(Label::onDraw, this, transform, transformUpdated);
renderer->addCommand(&_customCommand);
}
}
}
void Label::visit(Renderer *renderer, const Mat4 &parentTransform, uint32_t parentFlags)
{
if (! _visible || (_utf8Text.empty() && _children.empty()) )
{
return;
}
if (_systemFontDirty || _contentDirty)
{
updateContent();
}
uint32_t flags = processParentFlags(parentTransform, parentFlags);
if (!_utf8Text.empty() && _shadowEnabled && (_shadowDirty || (flags & FLAGS_DIRTY_MASK)))
{
_position.x += _shadowOffset.width;
_position.y += _shadowOffset.height;
_transformDirty = _inverseDirty = true;
_shadowTransform = transform(parentTransform);
_position.x -= _shadowOffset.width;
_position.y -= _shadowOffset.height;
_transformDirty = _inverseDirty = true;
_shadowDirty = false;
}
bool visibleByCamera = isVisitableByVisitingCamera();
if (_children.empty() && !_textSprite && !visibleByCamera)
{
return;
}
// IMPORTANT:
// To ease the migration to v3.0, we still support the Mat4 stack,
// but it is deprecated and your code should not rely on it
_director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
_director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW, _modelViewTransform);
if (!_children.empty())
{
sortAllChildren();
int i = 0;
// draw children zOrder < 0
for (; i < _children.size(); i++)
{
auto node = _children.at(i);
if (node && node->getLocalZOrder() < 0)
node->visit(renderer, _modelViewTransform, flags);
else
break;
}
this->drawSelf(visibleByCamera, renderer, flags);
for (auto it = _children.cbegin() + i; it != _children.cend(); ++it)
{
(*it)->visit(renderer, _modelViewTransform, flags);
}
}
else
{
this->drawSelf(visibleByCamera, renderer, flags);
}
_director->popMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
}
void Label::drawSelf(bool visibleByCamera, Renderer* renderer, uint32_t flags)
{
if (_textSprite)
{
if (_shadowNode)
{
_shadowNode->visit(renderer, _modelViewTransform, flags);
}
_textSprite->visit(renderer, _modelViewTransform, flags);
}
else if (visibleByCamera && !_utf8Text.empty())
{
draw(renderer, _modelViewTransform, flags);
}
}
void Label::setSystemFontName(const std::string& systemFont)
{
if (systemFont != _systemFont)
{
_systemFont = systemFont;
_currentLabelType = LabelType::STRING_TEXTURE;
_systemFontDirty = true;
}
}
void Label::setSystemFontSize(float fontSize)
{
if (_systemFontSize != fontSize)
{
_systemFontSize = fontSize;
_originalFontSize = fontSize;
_currentLabelType = LabelType::STRING_TEXTURE;
_systemFontDirty = true;
}
}
///// PROTOCOL STUFF
Sprite* Label::getLetter(int letterIndex)
{
Sprite* letter = nullptr;
do
{
if (_systemFontDirty || _currentLabelType == LabelType::STRING_TEXTURE)
{
break;
}
auto contentDirty = _contentDirty;
if (contentDirty)
{
updateContent();
}
if (_textSprite == nullptr && letterIndex < _lengthOfString)
{
const auto &letterInfo = _lettersInfo[letterIndex];
if (!letterInfo.valid)
{
break;
}
if (_letters.find(letterIndex) != _letters.end())
{
letter = _letters[letterIndex];
}
if (letter == nullptr)
{
auto& letterDef = _fontAtlas->_letterDefinitions[letterInfo.utf16Char];
auto textureID = letterDef.textureID;
Rect uvRect;
uvRect.size.height = letterDef.height;
uvRect.size.width = letterDef.width;
uvRect.origin.x = letterDef.U;
uvRect.origin.y = letterDef.V;
if (letterDef.width <= 0.f || letterDef.height <= 0.f)
{
letter = LabelLetter::create();
}
else
{
letter = LabelLetter::createWithTexture(_fontAtlas->getTexture(textureID), uvRect);
letter->setTextureAtlas(_batchNodes.at(textureID)->getTextureAtlas());
letter->setAtlasIndex(letterInfo.atlasIndex);
auto px = letterInfo.positionX + uvRect.size.width / 2 + _linesOffsetX[letterInfo.lineIndex];
auto py = letterInfo.positionY - uvRect.size.height / 2 + _letterOffsetY;
letter->setPosition(px,py);
letter->setOpacity(_realOpacity);
}
addChild(letter);
_letters[letterIndex] = letter;
}
}
} while (false);
return letter;
}
void Label::setLineHeight(float height)
{
CCASSERT(_currentLabelType != LabelType::STRING_TEXTURE, "Not supported system font!");
if (_lineHeight != height)
{
_lineHeight = height;
_contentDirty = true;
}
}
float Label::getLineHeight() const
{
CCASSERT(_currentLabelType != LabelType::STRING_TEXTURE, "Not supported system font!");
return _textSprite ? 0.0f : _lineHeight * _bmfontScale;
}
void Label::setLineSpacing(float height)
{
if (_lineSpacing != height)
{
_lineSpacing = height;
_contentDirty = true;
}
}
float Label::getLineSpacing() const
{
return _lineSpacing;
}
void Label::setAdditionalKerning(float space)
{
if (_currentLabelType != LabelType::STRING_TEXTURE)
{
if (_additionalKerning != space)
{
_additionalKerning = space;
_contentDirty = true;
}
}
else
CCLOG("Label::setAdditionalKerning not supported on LabelType::STRING_TEXTURE");
}
float Label::getAdditionalKerning() const
{
CCASSERT(_currentLabelType != LabelType::STRING_TEXTURE, "Not supported system font!");
return _additionalKerning;
}
void Label::computeStringNumLines()
{
int quantityOfLines = 1;
if (_utf16Text.empty())
{
_numberOfLines = 0;
return;
}
// count number of lines
size_t stringLen = _utf16Text.length();
for (size_t i = 0; i < stringLen - 1; ++i)
{
if (_utf16Text[i] == (char16_t)TextFormatter::NewLine)
{
quantityOfLines++;
}
}
_numberOfLines = quantityOfLines;
}
int Label::getStringNumLines()
{
if (_contentDirty)
{
updateContent();
}
if (_currentLabelType == LabelType::STRING_TEXTURE)
{
computeStringNumLines();
}
return _numberOfLines;
}
int Label::getStringLength()
{
_lengthOfString = static_cast<int>(_utf16Text.length());
return _lengthOfString;
}
// RGBA protocol
void Label::setOpacityModifyRGB(bool isOpacityModifyRGB)
{
if (isOpacityModifyRGB != _isOpacityModifyRGB)
{
_isOpacityModifyRGB = isOpacityModifyRGB;
updateColor();
}
}
void Label::updateDisplayedColor(const Color3B& parentColor)
{
Node::updateDisplayedColor(parentColor);
if (_textSprite)
{
_textSprite->updateDisplayedColor(_displayedColor);
if (_shadowNode)
{
_shadowNode->updateDisplayedColor(_displayedColor);
}
if (_underlineNode)
_contentDirty = true;
}
for (auto&& it : _letters)
{
it.second->updateDisplayedColor(_displayedColor);;
}
}
void Label::updateDisplayedOpacity(GLubyte parentOpacity)
{
Node::updateDisplayedOpacity(parentOpacity);
if (_textSprite)
{
_textSprite->updateDisplayedOpacity(_displayedOpacity);
if (_shadowNode)
{
_shadowNode->updateDisplayedOpacity(_displayedOpacity);
}
}
for (auto&& it : _letters)
{
it.second->updateDisplayedOpacity(_displayedOpacity);;
}
}
void Label::setTextColor(const Color4B &color)
{
CCASSERT(_currentLabelType == LabelType::TTF || _currentLabelType == LabelType::STRING_TEXTURE, "Only supported system font and ttf!");
if (_currentLabelType == LabelType::STRING_TEXTURE && _textColor != color)
{
_contentDirty = true;
}
_textColor = color;
_textColorF.r = _textColor.r / 255.0f;
_textColorF.g = _textColor.g / 255.0f;
_textColorF.b = _textColor.b / 255.0f;
_textColorF.a = _textColor.a / 255.0f;
}
void Label::updateColor()
{
if (_batchNodes.empty())
{
return;
}
Color4B color4( _displayedColor.r, _displayedColor.g, _displayedColor.b, _displayedOpacity );
// special opacity for premultiplied textures
if (_isOpacityModifyRGB)
{
color4.r *= _displayedOpacity/255.0f;
color4.g *= _displayedOpacity/255.0f;
color4.b *= _displayedOpacity/255.0f;
}
cocos2d::TextureAtlas* textureAtlas;
V3F_C4B_T2F_Quad *quads;
for (auto&& batchNode:_batchNodes)
{
textureAtlas = batchNode->getTextureAtlas();
quads = textureAtlas->getQuads();
auto count = textureAtlas->getTotalQuads();
for (int index = 0; index < count; ++index)
{
quads[index].bl.colors = color4;
quads[index].br.colors = color4;
quads[index].tl.colors = color4;
quads[index].tr.colors = color4;
textureAtlas->updateQuad(&quads[index], index);
}
}
}
std::string Label::getDescription() const
{
char tmp[50];
sprintf(tmp, "<Label | Tag = %d, Label = >", _tag);
std::string ret = tmp;
ret += _utf8Text;
return ret;
}
const Size& Label::getContentSize() const
{
if (_systemFontDirty || _contentDirty)
{
const_cast<Label*>(this)->updateContent();
}
return _contentSize;
}
Rect Label::getBoundingBox() const
{
const_cast<Label*>(this)->getContentSize();
return Node::getBoundingBox();
}
void Label::setBlendFunc(const BlendFunc &blendFunc)
{
_blendFunc = blendFunc;
_blendFuncDirty = true;
if (_textSprite)
{
_textSprite->setBlendFunc(blendFunc);
if (_shadowNode)
{
_shadowNode->setBlendFunc(blendFunc);
}
}
}
void Label::removeAllChildrenWithCleanup(bool cleanup)
{
Node::removeAllChildrenWithCleanup(cleanup);
_letters.clear();
}
void Label::removeChild(Node* child, bool cleanup /* = true */)
{
Node::removeChild(child, cleanup);
for (auto&& it : _letters)
{
if (it.second == child)
{
_letters.erase(it.first);
break;
}
}
}
FontDefinition Label::_getFontDefinition() const
{
FontDefinition systemFontDef;
systemFontDef._fontName = _systemFont;
systemFontDef._fontSize = _systemFontSize;
systemFontDef._alignment = _hAlignment;
systemFontDef._vertAlignment = _vAlignment;
systemFontDef._dimensions.width = _labelWidth;
systemFontDef._dimensions.height = _labelHeight;
systemFontDef._fontFillColor.r = _textColor.r;
systemFontDef._fontFillColor.g = _textColor.g;
systemFontDef._fontFillColor.b = _textColor.b;
systemFontDef._fontAlpha = _textColor.a;
systemFontDef._shadow._shadowEnabled = false;
systemFontDef._enableWrap = _enableWrap;
systemFontDef._overflow = (int)_overflow;
if (_currLabelEffect == LabelEffect::OUTLINE && _outlineSize > 0.f)
{
systemFontDef._stroke._strokeEnabled = true;
systemFontDef._stroke._strokeSize = _outlineSize;
systemFontDef._stroke._strokeColor.r = _effectColorF.r * 255;
systemFontDef._stroke._strokeColor.g = _effectColorF.g * 255;
systemFontDef._stroke._strokeColor.b = _effectColorF.b * 255;
systemFontDef._stroke._strokeAlpha = _effectColorF.a * 255;
}
else
{
systemFontDef._stroke._strokeEnabled = false;
}
#if (CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID) && (CC_TARGET_PLATFORM != CC_PLATFORM_IOS)
if (systemFontDef._stroke._strokeEnabled)
{
CCLOGERROR("Stroke Currently only supported on iOS and Android!");
}
systemFontDef._stroke._strokeEnabled = false;
#endif
return systemFontDef;
}
void Label::setGlobalZOrder(float globalZOrder)
{
Node::setGlobalZOrder(globalZOrder);
if (_textSprite)
{
_textSprite->setGlobalZOrder(globalZOrder);
if (_shadowNode)
{
_shadowNode->setGlobalZOrder(globalZOrder);
}
}
}
float Label::getRenderingFontSize()const
{
float fontSize;
if (_currentLabelType == LabelType::BMFONT) {
fontSize = _bmFontSize;
}else if(_currentLabelType == LabelType::TTF){
fontSize = this->getTTFConfig().fontSize;
}else if(_currentLabelType == LabelType::STRING_TEXTURE){
fontSize = _systemFontSize;
}else{ //FIXME: find a way to calculate char map font size
fontSize = this->getLineHeight();
}
return fontSize;
}
void Label::enableWrap(bool enable)
{
if(enable == _enableWrap || _overflow == Overflow::RESIZE_HEIGHT){
return;
}
this->_enableWrap = enable;
this->rescaleWithOriginalFontSize();
_contentDirty = true;
}
bool Label::isWrapEnabled()const
{
return this->_enableWrap;
}
void Label::setOverflow(Overflow overflow)
{
if(_overflow == overflow){
return;
}
if (_currentLabelType == LabelType::CHARMAP) {
if (overflow == Overflow::SHRINK) {
return;
}
}
if(overflow == Overflow::RESIZE_HEIGHT){
this->setDimensions(_labelDimensions.width,0);
this->enableWrap(true);
}
_overflow = overflow;
this->rescaleWithOriginalFontSize();
_contentDirty = true;
}
void Label::rescaleWithOriginalFontSize()
{
auto renderingFontSize = this->getRenderingFontSize();
if (_originalFontSize - renderingFontSize >= 1) {
this->scaleFontSizeDown(_originalFontSize);
}
}
Label::Overflow Label::getOverflow()const
{
return _overflow;
}
void Label::updateLetterSpriteScale(Sprite* sprite)
{
if (_currentLabelType == LabelType::BMFONT && _bmFontSize > 0)
{
sprite->setScale(_bmfontScale);
}
else
{
if(fabs(_bmFontSize)<FLT_EPSILON)
{
sprite->setScale(0);
}
else
{
sprite->setScale(1.0);
}
}
}
NS_CC_END
| [
"[email protected]"
] | |
f97aedf4770244b0e1161e6c93ea4d3ea065c7fd | c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64 | /Engine/Source/Editor/SceneOutliner/Public/ISceneOutliner.h | 05a835b11f6b9d9572d42118c19b99024a5dfa7b | [
"MIT",
"LicenseRef-scancode-proprietary-license"
] | permissive | windystrife/UnrealEngine_NVIDIAGameWorks | c3c7863083653caf1bc67d3ef104fb4b9f302e2a | b50e6338a7c5b26374d66306ebc7807541ff815e | refs/heads/4.18-GameWorks | 2023-03-11T02:50:08.471040 | 2022-01-13T20:50:29 | 2022-01-13T20:50:29 | 124,100,479 | 262 | 179 | MIT | 2022-12-16T05:36:38 | 2018-03-06T15:44:09 | C++ | UTF-8 | C++ | false | false | 992 | h | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Misc/Attribute.h"
#include "SceneOutlinerFwd.h"
#include "Widgets/SCompoundWidget.h"
template<typename ItemType> class STreeView;
/**
* The public interface for the Scene Outliner widget
*/
class ISceneOutliner : public SCompoundWidget
{
public:
/** Sends a requests to the Scene Outliner to refresh itself the next chance it gets */
virtual void Refresh() = 0;
/** @return Returns a string to use for highlighting results in the outliner list */
virtual TAttribute<FText> GetFilterHighlightText() const = 0;
/** @return Returns the common data for this outliner */
virtual const SceneOutliner::FSharedOutlinerData& GetSharedData() const = 0;
/** Get a const reference to the actual tree hierarchy */
virtual const STreeView<SceneOutliner::FTreeItemPtr>& GetTree() const = 0;
/** Set the keyboard focus to the outliner */
virtual void SetKeyboardFocus() = 0;
};
| [
"[email protected]"
] | |
7c5068a31db36b62955ce66a31e7bf0fc217b224 | de33200cd65614455b30bacaa6a5b209cbabf114 | /baekjoon/2751.cpp | 5a17224ebeb764d83d26adea27a62e45ad444bb2 | [] | no_license | DongOnee/algorithm | 4b3367ea5e6346d44dbaa66328057654596b9ab2 | 662352f9fcfafdaa66b00af1806eeea2cf7ff0d1 | refs/heads/master | 2022-03-14T06:48:37.097846 | 2022-03-04T06:34:42 | 2022-03-04T06:34:42 | 138,333,071 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 310 | cpp | #include <iostream>
using namespace std;
int data[1000000];
int size;
int main(int argc, char const *argv[])
{
size = 0;
int N;
cin >> N;
for (int i=0; i<N; i++)
{
int tmp;
cin >> tmp;
data[size++] = tmp;
}
/* code */
return 0;
}
| [
"[email protected]"
] | |
a0be6ee417f57edf69ab9f6be94d10738c1c7667 | 139af846b3b4e4e02ee5c6c64994335a57eb276e | /src/localization/ndt_localization/include/ndt_localization/ndt_localization.h | 309ea953b7377efb1ab345f093585eb3bdb94aa6 | [] | no_license | strualo/elevation_mapping_with_localization | 5a4579cab2c482cabcc16115144c2d662e21a550 | 9efc25da6c014f54715dcf343746da92be9d19f5 | refs/heads/master | 2020-08-13T21:21:45.868053 | 2019-11-03T14:59:27 | 2019-11-03T14:59:27 | 215,039,829 | 7 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 6,435 | h | #ifndef __NDT_LOCALZATION__
#define __NDT_LOCALZATION__
#include <ros/duration.h>
#include <ros/ros.h>
#include <sensor_msgs/PointCloud2.h>
#include <tf/transform_broadcaster.h>
#include <tf/transform_listener.h>
// #include <sensor_msgs/Imu.h>
#include <geometry_msgs/PoseStamped.h>
#include <geometry_msgs/PoseWithCovarianceStamped.h>
#include <nav_msgs/Odometry.h>
#include <nav_msgs/Path.h>
#include <visualization_msgs/Marker.h>
#include <boost/thread/thread.hpp>
#include <chrono>
#include <iomanip>
#include <iostream>
#include <pcl/filters/approximate_voxel_grid.h>
#include <pcl/point_types.h>
#include <pcl/registration/ndt.h>
#include <pcl_conversions/pcl_conversions.h>
#include <pthread.h>
#include <sstream>
#include <string>
#include <std_msgs/Float32.h>
#include <std_msgs/Int16.h>
#include <ndt_cpu/NormalDistributionsTransform.h>
#include <ndt_gpu/NormalDistributionsTransform.h>
#include <pcl_omp_registration/ndt.h>
#ifndef USE_OMP
#define USE_OMP
#endif
#include "ground_filter.hpp"
#include "user_protocol.h"
#include "utils.hpp"
#define METHOD_PCL 0
#define METHOD_CUDA 1
#define METHOD_OMP 2
#define METHOD_CPU 3
typedef pcl::PointXYZ PointT;
typedef pcl::PointCloud<PointT> PointCloudT;
class NDTLocalization {
public:
NDTLocalization(ros::NodeHandle nh, ros::NodeHandle pnh)
: nh_(nh)
, pnh_(pnh)
, target_map_ptr(new PointCloudT())
{
}
~NDTLocalization();
/**
* @brief Initialize.
*
* @return true
* @return false
*/
bool init();
private:
ros::NodeHandle nh_;
ros::NodeHandle pnh_;
tf::TransformBroadcaster tf_broadcaster_;
tf::TransformListener tf_listener_;
tf::TransformBroadcaster odom_map_tf_broadcaster_;
ros::Publisher pub_current_pose_;
ros::Publisher pub_PoseWithCovarianceStamped;
ros::Publisher pub_ndt_odom;
ros::Publisher pub_marker_loc_conf_;
ros::Publisher pub_marker_trans_prob_;
// publish time-used of ndt
ros::Publisher pub_ndt_time;
ros::Publisher pub_ndt_iterations;
ros::Publisher pub_target_map;
ros::Publisher pub_global_map;
ros::Subscriber sub_odom_;
ros::Subscriber sub_odom_imu_pose;
nav_msgs::Odometry::ConstPtr msg_odom_; // under odom frame
ros::Subscriber sub_map_;
PointCloudT model_pc_;
ros::Subscriber sub_initial_pose_;
pose initial_pose_; // under map frame
ros::Subscriber sub_point_cloud_;
PointCloudT data_pc_; // 定义要加载的全局地图
PointCloudT::Ptr target_map_ptr;
PointCloudT target_map;
// publish debug_path
nav_msgs::Path debug_path;
ros::Publisher pub_path;
double length_update_path;
double param_min_scan_range;
double param_max_scan_range;
pose added_pose; // 更新局部target地图相关
bool use_local_target;
double lengh_update_target_map;
double target_map_radius;
double voxel_leaf_size;
pose current_pose_;
pose pre_pose_;
pose current_pose_odom_;
pose pre_pose_odom_;
pose predict_pose_odom_;
pose offset_odom_;
ros::Time pre_odom_time_;
// pose current_pose_imu_;
// pose pre_pose_imu_;
// pose predict_pose_imu_;
pose offset_imu_;
// ros::Time pre_imu_time_;
Eigen::Matrix4f tf_btol_;
tf::Transform current_map2odom_;
bool pose_init_;
bool odom_init_;
bool map_init_;
int model_pc_num_;
pthread_mutex_t mutex;
#ifdef CUDA_FOUND
std::shared_ptr<gpu::GNormalDistributionsTransform> anh_gpu_ndt_ptr;
#endif
#ifdef USE_OMP
pcl_omp::NormalDistributionsTransform<PointT, PointT> omp_ndt_;
#endif
cpu::NormalDistributionsTransform<PointT, PointT> cpu_ndt_;
pcl::NormalDistributionsTransform<PointT, PointT> ndt_;
bool has_converged_;
double fitness_score_;
double trans_probability_;
int iteration_;
double predict_pose_error_;
std::string param_odom_frame_;
std::string param_map_frame_;
std::string param_base_frame_;
std::string param_laser_frame_;
std::string param_map_topic_;
std::string param_lidar_topic_;
// std::string param_imu_topic_;
std::string param_odom_topic_;
double param_tf_timeout_;
double param_odom_timeout_;
bool param_use_odom_;
double param_predict_error_thresh_;
double param_ndt_resolution_;
int param_ndt_max_iterations_;
double param_ndt_step_size_;
double param_ndt_epsilon_;
int param_method_type_;
// debug use
bool param_debug_;
bool rawodom_init_;
ros::Publisher pub_rawodom_;
nav_msgs::Odometry msg_rawodom_;
nav_msgs::Odometry ndt_odometry;
std::string map_file;
bool is_filter_ground;
utils::RayGroundFilter filter;
ros::Publisher pub_localPC_handled;
bool load_map(std::string map_file);
/**
* @brief Save motion data to get a rough pose estimation to give NDT-matching a initial transformation matrix.
*
* @param msg
*/
void odomCB(const nav_msgs::Odometry::ConstPtr& msg);
void odom_imu_poseCB(const geometry_msgs::PoseStamped::ConstPtr& msg);
/**
* @brief Save model points(better to be filtered) for latter use.
*
* @param msg
*/
void mapCB(const sensor_msgs::PointCloud2::ConstPtr& msg);
/**
* @brief Set a rough pose estimation by manual.
*
* @param msg
*/
void initialPoseCB(const geometry_msgs::PoseWithCovarianceStamped::ConstPtr& msg);
// void initialPoseWithGNSS(const geometry_msgs::PoseStamped::ConstPtr& msg);
/**
* @brief Get measured data points, estimate current pose using 3D-NDT-matching.
*
* @param msg
*/
void pointCloudCB(const sensor_msgs::PointCloud2::ConstPtr& msg);
static bool pubMarkerText(const ros::Publisher pub, const geometry_msgs::Pose pose, const ros::Time stamp, const std::string frame, const std::string text);
static bool pubMarkerCylinder(const ros::Publisher pub, const geometry_msgs::Pose pose, const ros::Time stamp, const std::string frame, const geometry_msgs::Vector3 scale);
static bool pubMarkerCube(const ros::Publisher pub, const geometry_msgs::Pose pose, const ros::Time stamp, const std::string frame, const geometry_msgs::Vector3 scale);
void init_pose_with_param();
double init_x, init_y, init_z;
double init_roll, init_pitch, init_yaw;
bool param_init_pose_with_param;
void update_target_map();
void pub_debug_path();
};
#endif
| [
"[email protected]"
] | |
50f3d934a5d1114368ca0f1910d8edcc847539e5 | 30073e9bcf7976a49ef82da7584da8d6c63c623f | /custom_arduino_files/libraries/DashBot/DashBot.cpp | 1170c23b1eb490f8466b6e378a831163c880416f | [] | no_license | PolyPEDAL/DashboardTeleoperation | fbe736c53416d96d14452569b181b1b36509fc8f | 4e98406c221380650129a7e3eb5a7bb4041ffc46 | refs/heads/master | 2020-05-09T17:37:46.827798 | 2014-12-18T22:40:50 | 2014-12-18T22:40:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 30,053 | cpp | /*
DashBot.cpp - Library for using Dash.
Created by Nick Kohut, Dwight Springthorpe II, Paul Birkmeyer, and Kevin Peterson, August 14, 2014.
Property of Dash Robotics, Inc.
Released into the public domain.
*/
#include "Arduino.h"
#include "DashBot.h"
#include <VarSpeedServo.h>
//#include <SoftPWM.h>
VarSpeedServo servo1; // create servo object to control a servo
VarSpeedServo servo2;
VarSpeedServo servo3;
DashBot::DashBot(void)
{
// Gyro variables
gyro_init = 512;//gyro reading at rest (reset in setup)
// Controller variables
err_integral = 0;
// IR variales
baseline_IR_left = 800;
baseline_IR_right = 800;
// Initialize LED pins
pinMode(LED_RED, OUTPUT);
pinMode(LED_YELLOW, OUTPUT);
pinMode(LED_GREEN, OUTPUT);
// Initialize IR pins
pinMode(IR_ENABLE_LEFT, OUTPUT);
pinMode(IR_ENABLE_RIGHT, OUTPUT);
digitalWrite(IR_ENABLE_LEFT, HIGH);
digitalWrite(IR_ENABLE_RIGHT, HIGH);
// Default sensor emission delay
delay_between_sensor_emissions = 50;
}
////////////////////////////////////////////////////////////////////////////////
// Motor, Gyro, Control functions
////////////////////////////////////////////////////////////////////////////////
// reads the gyroscope, returns degrees/sec
float DashBot::readGyroDeg(void)
{
float gyro_current;
float gyro_init_fl;
float gyro_deg;
static const float GYRO_MAX_RANGE = 2000.0; // the LY3200ALH gyro reads plus or minus 2000 deg/sec
gyro_current = float(analogRead(GYRO_OUT));
gyro_init_fl = float (gyro_init);
gyro_deg = (gyro_current - gyro_init_fl)*(GYRO_MAX_RANGE/gyro_init_fl);
return gyro_deg;
}
// "zeroes" the gyro by taking an average measurement over 50 ms at startup
void DashBot::gyroSetup(void)
{
float val = 0;
int i;
//read the gyro 5 times in 50 ms
for (i = 0; i < 5; i++)
{
val += analogRead(GYRO_OUT);
delay(10);
}
gyro_init = val/5;
}
// drive the right motor, input should be between -100 and 100
void DashBot::motorDriveR(float motor_pwm)
{
motorDrive(motor_pwm, 'R');
}
// drive the left motor, input should be between -100 and 100
void DashBot::motorDriveL(float motor_pwm)
{
motorDrive(motor_pwm, 'L');
}
// takes in a number between -100 and 100, converts to bytes, drives motors. only called by motorDriveL and motorDriveR
void DashBot::motorDrive (float motor_pwm, char side) {
float pwm_scaled;
byte PWM_byte;
if (motor_pwm > 100.0) {
motor_pwm = 100.0;
}
if (motor_pwm < -100.0) {
motor_pwm = -100.0;
}
pwm_scaled = motor_pwm*255.0/100.0; // scale motor_pwm to a byte
if (side == 'R') {
if (pwm_scaled > 0.0) {
PWM_byte = byte(pwm_scaled);
//analogWrite(MOTOR_RIGHT_FORWARD, byte(20));
analogWrite(MOTOR_RIGHT_FORWARD, PWM_byte);
analogWrite(MOTOR_RIGHT_BACKWARD, 0);
motor_right_backward_value = 0;
motor_right_forward_value = PWM_byte;
}
else {
PWM_byte = byte(abs(pwm_scaled));
//analogWrite(MOTOR_RIGHT_BACKWARD, byte(20));
analogWrite(MOTOR_RIGHT_BACKWARD, PWM_byte);
analogWrite(MOTOR_RIGHT_FORWARD, 0);
motor_right_backward_value = PWM_byte;
motor_right_forward_value = 0;
}
}
if (side == 'L') {
if (pwm_scaled > 0.0) {
PWM_byte = byte(pwm_scaled);
//analogWrite(MOTOR_LEFT_FORWARD, byte(20));
analogWrite(MOTOR_LEFT_FORWARD, PWM_byte);
analogWrite(MOTOR_LEFT_BACKWARD, 0);
motor_left_backward_value = 0;
motor_left_forward_value = PWM_byte;
}
else {
PWM_byte = byte(abs(pwm_scaled));
//analogWrite(MOTOR_LEFT_BACKWARD, byte(20));
analogWrite(MOTOR_LEFT_BACKWARD, PWM_byte);
analogWrite(MOTOR_LEFT_FORWARD, 0);
motor_left_backward_value = PWM_byte;
motor_left_forward_value = 0;
}
}
}
void DashBot::driveForTime(float motorL_pwm, float motorR_pwm, long time_limit){
unsigned long init_time = millis();
unsigned long current_time = millis();
// auto_flag must be 1, if not, an all stop has been called and the auto mode should exit
while (current_time - init_time < time_limit) {
motorDriveR(motorR_pwm);
motorDriveL(motorL_pwm);
current_time = millis();
while (millis()-current_time < 50) {} // Give yourself time to run!
dashPacketHandler(); // listen for other commands
}
motorDriveR(0);
motorDriveL(0);
}
/*
float DashBot::dashRun (float ref_pwm, float ref_yaw)
{
static const float p_gain = 0.3;
static const float i_gain = 0.02;
static const int antiwindup = 7500;
float L_motor;
float R_motor;
float err;
float mix;
//PI controller with custom anti-windup
err = ref_yaw - readGyroDeg();
err_integral = err_integral + err;
if (abs(err_integral) > antiwindup)
{
err_integral = 0;
}
mix = p_gain*err+i_gain*err_integral;
L_motor = ref_pwm - mix;
R_motor = ref_pwm + mix;
motorDriveL(L_motor);
motorDriveR(R_motor);
return ref_yaw;
}
*/
/*
// gyro feedback steering for Dash. implements PI control law with "anti-windup" that resets integral error to zero
float DashBot::dashRun (float ref_pwm, float ref_yaw) {
float x;
float y;
static const float p_gain = .1;
static const float i_gain = .0005;
static const float antiwindup = 250/.0005; // 250/i_gain
float L_motor;
float R_motor;
float err;
float mix;
ref_yaw = 1.5*ref_yaw*abs(ref_pwm)/100; // Turn slowly if moving slowly
// Can do this next part more intelligently...
L_motor = ref_pwm;
R_motor = ref_pwm;
//PI controller with anti-windup
err = ref_yaw - readGyroDeg();
err_integral = err_integral + err;
if (err_integral > antiwindup) {
err_integral = antiwindup;
}
else if (err_integral < -antiwindup){
err_integral = -antiwindup;
}
mix = p_gain*err+i_gain*err_integral;
mix = mix*abs(ref_pwm)/100; // Cap mixing based on speed
L_motor = L_motor - mix;
R_motor = R_motor + mix;
// Send commands
motorDriveL(L_motor);
motorDriveR(R_motor);
return ref_yaw;
}
*/
float DashBot::dashRun (float ref_pwm, float ref_yaw) {
// yaw ranges from -400 to 400 (degrees per sec) from iPad
// pwm ranges from -100 to 100 (duty cycle) from iPad
// gyro feedback sttering for Dash. implements PI control law with anti-windup
static const float p_gain = .1;
static const float i_gain = .0005;
static const float antiwindup = 20/.0005; // 250/i_gain
static const int max_yaw = 400; // maximum from iPad
float L_motor;
float R_motor;
float err;
float mix;
// Baseline PWM values
L_motor = ref_pwm;
R_motor = ref_pwm;
// Scale PWM based on dirction (forward and backward) and target yaw rate
if (ref_pwm > 0) {
if (ref_yaw < 0) { // If right turn
L_motor = ref_pwm; // Left motor positive
R_motor = ref_pwm + (2 * ref_pwm) * (ref_yaw/max_yaw); // Right motor goes from 100 to -100
}
else if (ref_yaw > 0) { // If left turn
L_motor = ref_pwm - (2 * ref_pwm) * (ref_yaw/max_yaw); // Left motor goes from 100 to -100 (2 = (100 - (-100)) / max_pwm)
R_motor = ref_pwm; // Right motor positive
}
}
else {
if (ref_yaw > 0) { // If right turn
L_motor = ref_pwm; // Left motor positive
R_motor = ref_pwm + (2 * abs(ref_pwm)) * (ref_yaw/max_yaw); // Right motor goes from 100 to -100 (2 = (100 - (-100)) / max_pwm)
}
else if (ref_yaw < 0) { // If left turn
L_motor = ref_pwm - (2 * abs(ref_pwm)) * (ref_yaw/max_yaw); // Left motor goes from 100 to -100
R_motor = ref_pwm; // Right motor positive
}
}
// Translate yaw rate to a turning radius and amplify by 50%
ref_yaw = 1.5*ref_yaw*abs(ref_pwm)/100; // Turn slowly if moving slowly
//PI controller with anti-windup
err = ref_yaw - readGyroDeg();
err_integral = err_integral + err;
if (err_integral > antiwindup) {
err_integral = antiwindup;
}
else if (err_integral < -antiwindup){
err_integral = -antiwindup;
}
mix = p_gain*err+i_gain*err_integral;
mix = mix*abs(ref_pwm)/100; // Cap mixing based on speed
L_motor = L_motor - mix;
R_motor = R_motor + mix;
// Send commands
motorDriveL(L_motor);
motorDriveR(R_motor);
return ref_yaw;
}
// stop Dash's motors
void DashBot::allStop(void)
{
motorDriveL(0);
motorDriveR(0);
// analogWrite(MOTOR_RIGHT_BACKWARD, byte(0)); // right backward
// analogWrite(MOTOR_RIGHT_FORWARD, byte(0)); // right forward
// analogWrite(MOTOR_LEFT_BACKWARD, byte(0)); // left backward
// analogWrite(MOTOR_LEFT_FORWARD, byte(0)); // left forward
err_integral = 0;
}
// drive Dash's motors directly. used in app for joystick mode
void DashBot::directDrive(byte right_bckwd, byte right_fwd, byte left_bckwd, byte left_fwd)
{
analogWrite(MOTOR_RIGHT_BACKWARD, right_bckwd); // right backward
analogWrite(MOTOR_RIGHT_FORWARD, right_fwd); // right forward
analogWrite(MOTOR_LEFT_BACKWARD, left_bckwd); // left backward
analogWrite(MOTOR_LEFT_FORWARD, left_fwd); // left forward
motor_right_backward_value = right_bckwd;
motor_right_forward_value = right_fwd;
motor_left_backward_value = left_bckwd;
motor_left_forward_value = left_fwd;
}
////////////////////////////////////////////////////////////////////////////////
// Light functions
////////////////////////////////////////////////////////////////////////////////
// light up green LED to indicate robot is ready
void DashBot::startupBlink(void)
{
digitalWrite(LED_GREEN, HIGH);
}
// red LED high, used for debugging purposes
void DashBot::debugBlinkOn(void)
{
digitalWrite(LED_RED, HIGH);
}
// red LED low, used for debugging purposes
void DashBot::debugBlinkOff(void)
{
digitalWrite(LED_RED, LOW);
}
// set the color of Dash's eyes in 3 bytes (Red, Green, Blue)
void DashBot::setEyeColor(int eyeRedVal, int eyeGreenVal, int eyeBlueVal)
{
analogWrite(EYE_RED, eyeRedVal);
analogWrite(EYE_GREEN, eyeGreenVal);
analogWrite(EYE_BLUE, eyeBlueVal);
}
////////////////////////////////////////////////////////////////////////////////
// Sensor functions
////////////////////////////////////////////////////////////////////////////////
int DashBot::readAmbientLight(void)
{
return analogRead(AMBIENT_LIGHT);
}
int DashBot::readRightIRsensor(void)
{
return analogRead(PROXIMITY_RIGHT);
}
int DashBot::readLeftIRsensor(void)
{
return analogRead(PROXIMITY_LEFT);
}
// used to set a sensor baseline at startup
void DashBot::setupIRsensors(void)
{
baseline_IR_left = readLeftIRsensor();
baseline_IR_right = readRightIRsensor();
}
// detects a collision on the left side of the robot by comparing current IR reading to the baseline
// takes a threshold variable as an input to set sensitivity
boolean DashBot::detectCollisionLeft(int thresh)
{
if (readLeftIRsensor() < baseline_IR_left-thresh)
{
return true;
}
else
{
return false;
}
}
// detects a collision on the right side of the robot by comparing current IR reading to the baseline
// takes a threshold variable as an input to set sensitivity
boolean DashBot::detectCollisionRight(int thresh)
{
if(readRightIRsensor() < baseline_IR_right-thresh){
return true;
}
else
{
return false;
}
}
////////////////////////////////////////////////////////////////////////////////
// Radio functions
////////////////////////////////////////////////////////////////////////////////
void DashBot::clearRadioPacket(void)
{
for(byte i = 0; i< RADIO_PACKET_LENGTH; i++)
receivedRadioPacket[i] = 0;
}
boolean DashBot::readRadioPacket(void)
{
//if there's a full packet, read it and update the global packet variable.
//if there's not enoufgh data yet, do nothing and return a false
if(Serial1.available() >= RADIO_PACKET_LENGTH)
{
//digitalWrite(ledGreen, HIGH);
for (byte i = 0; i < RADIO_PACKET_LENGTH; i++)
{
receivedRadioPacket[i] = Serial1.read();
}
lastPacketTime = millis();
return true;
}
else
{
return false;
}
}
void DashBot::executeRadioCommand(void)
{
/*
switch (receivedRadioPacket[0]) {
case ALL_STOP:
mode = STOP_MODE;
allStop();
clearRadioPacket();
auto_flag = 0;
break;
case SET_NAME:
setName();
break;
case JOYSTICK_DRIVE:
// joystick drive
mode = JOYSTICK_MODE;
directDrive(receivedRadioPacket[1], receivedRadioPacket[2], receivedRadioPacket[3], receivedRadioPacket[4]);
clearRadioPacket();
break;
case GYRO_DRIVE:
// gyro-assisted driving
stabilizedDrive();
break;
case SET_EYE_COLOR:
setEyeColor(receivedRadioPacket[1], receivedRadioPacket[2], receivedRadioPacket[3]);
clearRadioPacket();
break;
case SEND_INFO_PACKET:
// send name and color to iOS device
sendInfoPacket();
break;
case SET_INFO_PACKET:
// set whether a name/color or sensor packet is being sent
setInfoPacketMode();
break;
case EXECUTE_AUTO_MODE:
executeAutoMode();
clearRadioPacket();
break;
default:
debugBlinkOn();
clearRadioPacket();
*/
switch (receivedRadioPacket[0]){
case 1:
setEyeColor(0,100,0); //green
clearRadioPacket();
break;
case 2:
setEyeColor(0,0,100); //blue
clearRadioPacket();
break;
case 3:
setEyeColor(100,0,0); //red
clearRadioPacket();
break;
case 4:
setEyeColor(0,0,0); //clear
clearRadioPacket();
break;
case 5:
setMessage();
break;
case 6:
setInfoPacketMode();
break;
case 7:
motorL_pwm = receivedRadioPacket[1];
motorR_pwm = receivedRadioPacket[2];
duration = (receivedRadioPacket[3] << 16) + (receivedRadioPacket[4] << 8) + receivedRadioPacket[5];
if (motorL_pwm > 100){
motorL_pwm = motorL_pwm - 100;
motorL_pwm = -1* motorL_pwm;
}
if (motorR_pwm > 100){
motorR_pwm = motorR_pwm - 100;
motorR_pwm = -1* motorR_pwm;
}
driveForTime(motorL_pwm, motorR_pwm, duration);
break;
case 8:
delay_between_sensor_emissions = receivedRadioPacket[1];
break;
case 9:
switch (receivedRadioPacket[3]){
case 1:
servo1.write(receivedRadioPacket[1], receivedRadioPacket[2], false);
break;
case 2:
servo2.write(receivedRadioPacket[1], receivedRadioPacket[2], false);
break;
case 3:
servo3.write(receivedRadioPacket[1], receivedRadioPacket[2], false);
break;
default:
setEyeColor(100,0,100); //purple
clearRadioPacket();
}
break;
/*case 10:
//servo1.write(180, 30, false);
servo2.write(receivedRadioPacket[1], receivedRadioPacket[2], false);
break;*/
case 11:
servo1port = receivedRadioPacket[1];
servo2port = receivedRadioPacket[2];
servo3port = receivedRadioPacket[3];
servo1.attach(servo1port); // attaches the servo on pin 9 to the servo object
servo2.attach(servo2port);
servo3.attach(servo3port);
break;
case 12:
motor_pwm = receivedRadioPacket[1];
if (motor_pwm > 100){
motor_pwm = motor_pwm - 100;
motor_pwm = -1*motor_pwm;
}
motorDriveR(motor_pwm);
break;
case 13:
motor_pwm = receivedRadioPacket[1];
if (motor_pwm > 100){
motor_pwm = motor_pwm - 100;
motor_pwm = -1*motor_pwm;
}
motorDriveL(motor_pwm);
break;
case 14:
servo3.write(receivedRadioPacket[1], receivedRadioPacket[2], false);
break;
default:
setEyeColor(100,0,100); //purple
clearRadioPacket();
}
}
// executes one of Dash's autonomous behaviors
void DashBot::executeAutoMode(void){
auto_flag = 1; // indicates an autonomous mode is on, if an all_stop is called, resets to zero to end auto behavior
switch (receivedRadioPacket[1]) {
case DASH_TEST:
dashTest();
Serial1.write('3');
case DASH_CIRCLE:
dashCircle();
Serial1.write('3');
break;
case DASH_FIG_8:
dashFig8();
Serial1.write('3');
break;
case DASH_DANCE:
dashDance();
Serial1.write('3');
break;
case DASH_BUMP:
dashBump();
Serial1.write('3');
break;
default:
setEyeColor(0,0,0);
}
}
//sends sensor data to mobile device
void DashBot::sendInfoPacket(void){
infoPacketTime = millis();
Serial1.write(INFO_PACKET); //2 means this is an info packet
Serial1.write(mode);
// send
int currentYaw = readGyroDeg();
// int sign = 1;
if (currentYaw < 0){
currentYaw = -currentYaw + 2000;
}
Serial1.write(highByte(currentYaw));
Serial1.write(lowByte(currentYaw));
int currentAmbientLight = readAmbientLight();
Serial1.write(highByte(currentAmbientLight));
Serial1.write(lowByte(currentAmbientLight));
int currentProxLeft = readLeftIRsensor();
Serial1.write(highByte(currentProxLeft));
Serial1.write(lowByte(currentProxLeft));
int currentProxRight = readRightIRsensor();
Serial1.write(highByte(currentProxRight));
Serial1.write(lowByte(currentProxRight));
Serial1.write(motor_right_backward_value);
Serial1.write(motor_right_forward_value);
Serial1.write(motor_left_backward_value);
Serial1.write(motor_left_forward_value);
}
// send robot name and color to iOS device
void DashBot::sendNamePacket(void){
Serial1.write(NAME_PACKET); //1 means this is a name packet
Serial1.write(robotType);
Serial1.write(robotColor);
Serial1.write(codeVersion);
for (byte i = 0; i < MAX_NAME_LENGTH; i++){
Serial1.write(robotName[i]);
}
}
//
void DashBot::sendMessagePacket(void){
Serial1.write(MESSAGE_PACKET); //1 means this is a name packet
//for (byte i = 0; i < MAX_MESSAGE_LENGTH; i++){
// Serial1.write(message[i]);
//}
Serial1.write(1);
Serial1.write(2);
Serial1.write(3);
Serial1.write(4);
Serial1.write(5);
Serial1.write(6);
Serial1.write(7);
Serial1.write(8);
Serial1.write(9);
Serial1.write(1);
Serial1.write(2);
Serial1.write(3);
Serial1.write(200);
}
// drives Dash via joystick with gyro-stabilized control
void DashBot::stabilizedDrive(void)
{
//enable stabilized drive mode:
mode = GYRO_MODE;
//note: I could send floats instead. need to find a good way to take 4-bytes and turn it into a float.
power = float(int(word(receivedRadioPacket[1],receivedRadioPacket[2]))); //convert the 2-byte value into signed value and cast as float.
heading = float(int(word(receivedRadioPacket[3],receivedRadioPacket[4])));
clearRadioPacket();
}
// sets Dash's name on the robot
void DashBot::setName(void)
{
//name packets should update variables store in program memory
robotType = receivedRadioPacket[1];
robotColor = receivedRadioPacket[2];
codeVersion = receivedRadioPacket[3]; //i don't think I really want the ability to update this value but I'll leave this in for now
robotName[0] = receivedRadioPacket[4];
robotName[1] = receivedRadioPacket[5];
robotName[2] = receivedRadioPacket[6];
robotName[3] = receivedRadioPacket[7];
robotName[4] = receivedRadioPacket[8];
robotName[5] = receivedRadioPacket[9];
robotName[6] = receivedRadioPacket[10];
robotName[7] = receivedRadioPacket[11];
robotName[8] = receivedRadioPacket[12];
robotName[9] = 0x00; //receivedRadioPacket[13]; //this should always be a null character
clearRadioPacket();
writeNameToEEPROM();
}
void DashBot::setMessage(void)
{
message[0] = receivedRadioPacket[1];
message[1] = receivedRadioPacket[2];
message[2] = receivedRadioPacket[3];
message[3] = receivedRadioPacket[4];
message[4] = receivedRadioPacket[5];
message[5] = receivedRadioPacket[6];
message[6] = receivedRadioPacket[7];
message[7] = receivedRadioPacket[8];
message[8] = receivedRadioPacket[9];
message[9] = receivedRadioPacket[10];
message[10] = receivedRadioPacket[11];
message[11] = receivedRadioPacket[12];
message[12] = 0x00; //receivedRadioPacket[13]; //this should always be a null character
clearRadioPacket();
writeMessageToEEPROM();
}
//toggles a mode variable which will enable automatic transmission of info packets
void DashBot::setInfoPacketMode(void){
switch (receivedRadioPacket[1]) {
case 0:
infoPacketTransmissionMode = 0; // send info packet (sensor readings)
break;
case 1:
infoPacketTransmissionMode = 1; // send name packet
break;
case 2:
infoPacketTransmissionMode = 2; // send message
break;
}
}
////////////////////////////////////////////////////////////////////////////////
// System functions
////////////////////////////////////////////////////////////////////////////////
// creates serial channels for radio and USB
void DashBot::setupSystemFunctions(void){
Serial1.begin(RADIO_BAUD_RATE); //radio channel
//Serial.begin(USB_BAUD_RATE); //USB channel
//read name from eeprom and update global name variable:
readNameFromEEPROM();
readMessageFromEEPROM();
}
//reads EEPROM to get name/info and loads results into global variables
void DashBot::readNameFromEEPROM(void){
robotType = EEPROM.read(0);
robotColor = EEPROM.read(1);
for (byte i = 0; i < MAX_NAME_LENGTH; i++){
robotName[i] = EEPROM.read(2 + i);
}
}
//writes Dash's name to memory
void DashBot::writeNameToEEPROM(void){
//puts robot name/info into eeprom
EEPROM.write(0, robotType);
EEPROM.write(1, robotColor);
for (byte i = 0; i < MAX_NAME_LENGTH; i++){
EEPROM.write(2+i, robotName[i]);
}
}
//reads a message from memory (beta)
void DashBot::readMessageFromEEPROM(void){
for (byte i = 0; i<MAX_MESSAGE_LENGTH; i++){
message[i] = EEPROM.read(MAX_NAME_LENGTH + 2 + i);
}
}
//writes a message to memory (beta)
void DashBot::writeMessageToEEPROM(void){
for (byte i = 0; i<MAX_MESSAGE_LENGTH; i++){
EEPROM.write(MAX_NAME_LENGTH + 2 + i, message[i]);
}
}
// If there is a radio packet, read and execute it. send info packets if appropriate
void DashBot::dashPacketHandler(void){
if(readRadioPacket()) {
executeRadioCommand();
}
debugBlinkOff();
//if in gyro-assisted mode, update controller and allow it to change the motor settings
if(mode == GYRO_MODE) {
dashRun(power, -heading);
}
//if in automatic info packet transmission mode is enabled, send an info packet
if(millis() - infoPacketTime > delay_between_sensor_emissions)
{
infoPacketTime = millis();
//if (infoPacketTransmissionMode == 1)
sendInfoPacket();
//else if (infoPacketTransmissionMode == 2)
// sendNamePacket();
//else if (infoPacketTransmissionMode == 3)
//sendMessagePacket();
}
//if there's not been a packet for the last 1/2 second, call an all-stop
if(millis() > lastPacketTime + 500)
{
allStop();
}
}
// setup Dash for iOS app
void DashBot::dashRadioSetup(void){
//servo1.attach(MISO); // attaches the servo on pin 9 to the servo object
//servo2.attach(MOSI);
startupBlink(); // green LED high
setupSystemFunctions(); //sets up serial radio and USB
setupIRsensors(); // baseline for IR sensors
gyroSetup(); // baseline for gyro
}
////////////////////////////////////////////////////////////////////////////////
// Autonomous functions
////////////////////////////////////////////////////////////////////////////////
// make Dash run in a circle!
/*void DashBot::dashCircle(void){
unsigned long init_time = millis();
unsigned long current_time = millis();
// auto_flag must be 1, if not, an all stop has been called and the auto mode should exit
while (current_time - init_time < 5000 && auto_flag == 1) {
setEyeColor(0, 100, 0);
dashRun(60, 150);
current_time = millis();
while (millis()-current_time < 50) {} // Give yourself time to run!
setEyeColor(0, 0, 100);
dashPacketHandler(); // listen for other commands
}
setEyeColor(0,0,0);
}*/
// make Dash run in a figure 8!
/*void DashBot::dashFig8(void){
unsigned long init_time = millis();
unsigned long current_time = millis();
// Turn left
// auto_flag must be 1, if not, an all stop has been called and the auto mode should exit
while (current_time- init_time < 2000 && auto_flag == 1) {
dashRun(60,150);
current_time = millis();
while (millis()-current_time < 50) {} // Give yourself time to run!
setEyeColor(0, 100, 0);
dashPacketHandler(); // listen for other commands
}
// Turn right
while (current_time- init_time < 4000 && auto_flag == 1) {
dashRun(60,-150);
current_time = millis();
while (millis()-current_time < 50) {} // Give yourself time to run!
setEyeColor(0, 0, 100);
dashPacketHandler();
}
setEyeColor(0,0,0);
}*/
// make Dash dance!
/*void DashBot::dashDance(void){
unsigned long init_time = millis();
// auto_flag must be 1, if not, an all stop has been called and the auto mode should exit
while (millis() - init_time < 2000 && auto_flag == 1) {
motorDriveL(-80);
motorDriveR(80);
setEyeColor(0, 0, 100);
dashPacketHandler(); // listen for other commands
}
while (millis() - init_time < 4000 && auto_flag == 1) {
motorDriveL(-80);
motorDriveR(80);
setEyeColor(0, 100, 0);
dashPacketHandler();
}
while (millis() - init_time < 6000 && auto_flag == 1) {
motorDriveL(80);
motorDriveR(-80);
setEyeColor(100, 0, 0);
dashPacketHandler();
}
while (millis() - init_time < 8000 && auto_flag == 1) {
motorDriveL(80);
motorDriveR(-80);
setEyeColor(100, 100, 100);
dashPacketHandler();
}
allStop();
setEyeColor(0,0,0);
}*/
// Dash will run forward until a collision is detected with the IR sensors, at which point Dash stops, backs up, turns, and again starts running
/*void DashBot::dashBump(void) {
unsigned long init_time = millis();
unsigned long current_time = millis();
// auto_flag must be 1, if not, an all stop has been called and the auto mode should exit
while (millis() - init_time < 20000 && auto_flag == 1){
// run around
dashRun(40,0);
current_time = millis();
while (millis()-current_time < 50) {} // Give yourself time to run!
setEyeColor(100, 0, 0);
dashPacketHandler(); // listen for other commands
//if collision, back up, turn around, try again
if (detectCollisionLeft(25) || detectCollisionRight(25)) {
unsigned long bump_time = millis();
// Stop the robot
while (millis() - bump_time < 500 && auto_flag == 1) {
setEyeColor(0, 100, 0);
allStop();
//dashPacketHandler();
}
// Back up
while (millis() - bump_time < 1500 && auto_flag == 1) {
dashRun(-40,0);
//dashPacketHandler();
}
// Turn around
while (millis() - bump_time < 2500 && auto_flag == 1) {
dashRun(40,150);
//dashPacketHandler();
}
}
}
allStop();
setEyeColor(0,0,0);
}*/
// make Dash dance!
/*
void DashBot::dashTest(void){
digitalWrite(LED_RED, HIGH);
delay(100);
digitalWrite(LED_YELLOW, HIGH);
delay(100);
digitalWrite(LED_GREEN, HIGH);
delay(100);
digitalWrite(LED_RED, LOW);
digitalWrite(LED_YELLOW, LOW);
digitalWrite(LED_GREEN, LOW);
unsigned long init_time = millis();
// auto_flag must be 1, if not, an all stop has been called and the auto mode should exit
while (millis() - init_time < 500 && auto_flag == 1) {
motorDriveL(80);
motorDriveR(0);
dashPacketHandler(); // listen for other commands
}
init_time = millis();
while (millis() - init_time < 500 && auto_flag == 1) {
motorDriveL(0);
motorDriveR(80);
dashPacketHandler();
}
init_time = millis();
while (millis() - init_time < 500 && auto_flag == 1) {
motorDriveL(-80);
motorDriveR(0);
dashPacketHandler();
}
init_time = millis();
while (millis() - init_time < 500 && auto_flag == 1) {
motorDriveL(0);
motorDriveR(-80);
dashPacketHandler();
}
init_time = millis();
while (millis() - init_time < 500 && auto_flag == 1) {
motorDriveL(0);
motorDriveR(0);
setEyeColor(100,0,0);
dashPacketHandler();
}
init_time = millis();
while (millis() - init_time < 500 && auto_flag == 1) {
motorDriveL(0);
motorDriveR(0);
setEyeColor(0,100,0);
dashPacketHandler();
}
init_time = millis();
while (millis() - init_time < 500 && auto_flag == 1) {
motorDriveL(0);
motorDriveR(0);
setEyeColor(0,0,100);
dashPacketHandler();
}
init_time = millis();
while (millis() - init_time < 10000 && auto_flag == 1) {
motorDriveL(0);
motorDriveR(0);
setEyeColor(50,50,50);
dashPacketHandler();
}
allStop();
setEyeColor(0,0,0);
}*/
| [
"[email protected]"
] | |
094471de3ce704e6d55e99a9838cead971cb1462 | a72d01c6c8dfdd687e9cc9b9bf4f4959e9d74f5d | /PRINCIPLE/plato/source/application.cpp | 1b04512e96ab78eb0ce4d9cf32a6fdd868f7a623 | [] | no_license | erinmaus/autonomaus | 8a3619f8380eae451dc40ba507b46661c5bc8247 | 9653f27f6ef0bbe14371a7077744a1fd8b97ae8d | refs/heads/master | 2022-10-01T01:24:23.028210 | 2018-05-09T21:59:26 | 2020-06-10T21:08:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 32,383 | cpp | // This file is a part of PRINCIPLE.
//
// Look, but don't touch.
//
// Copyright 2017 [bk]door.maus
#include <fstream>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/color_space.hpp>
#include <boost/filesystem.hpp>
#include "kommon/graphics/image.hpp"
#include "plato/application.hpp"
#include "plato/tools/tool.hpp"
#include "plato/tools/complexShapeTool.hpp"
#include "plato/tools/previewTool.hpp"
#include "principle/common/keyboardEvent.hpp"
#include "principle/common/mouseEvent.hpp"
#include "principle/graphics/guiManager.hpp"
#include "principle/graphics/imageStore.hpp"
#include "principle/deps/imgui/imgui.h"
#include "thoreau/thoreau.hpp"
void make_quad(kvncer::Mesh& mesh, kvncer::MeshBuffer& vertex_buffer)
{
struct Vertex
{
glm::vec2 position;
glm::vec2 texture;
};
Vertex vertices[] =
{
{ glm::vec2(0.0f, 0.0f), glm::vec2(0.0f, 0.0f) },
{ glm::vec2(1.0f, 0.0f), glm::vec2(1.0f, 0.0f) },
{ glm::vec2(1.0f, 1.0f), glm::vec2(1.0f, 1.0f) },
{ glm::vec2(1.0f, 1.0f), glm::vec2(1.0f, 1.0f) },
{ glm::vec2(0.0f, 1.0f), glm::vec2(0.0f, 1.0f) },
{ glm::vec2(0.0f, 0.0f), glm::vec2(0.0f, 0.0f) },
};
kompvter::Buffer vertex_buffer_data;
vertex_buffer_data.allocate(sizeof(vertices));
vertex_buffer_data.update(0, (const std::uint8_t*)vertices, vertex_buffer_data.get_data_size());
vertex_buffer.set_buffer(vertex_buffer_data);
mesh.enable_vertex_attrib(
kvncer::Shader::vertex_input_position,
&vertex_buffer,
2, GL_FLOAT, GL_FALSE,
offsetof(Vertex, position), sizeof(Vertex));
mesh.enable_vertex_attrib(
kvncer::Shader::vertex_input_texture_coordinate,
&vertex_buffer,
2, GL_FLOAT, GL_FALSE,
offsetof(Vertex, texture), sizeof(Vertex));
mesh.set_indices(nullptr, GL_NONE, 0, 6);
}
plato::Application::Application() :
principle::Application("plato"),
main_window(this),
import_dat_window(this),
resources_window(this),
edit_tile_window(this),
find_location_window(this),
find_resource_window(this),
export_window(this),
tool_renderer(this),
tool_factory(this),
visible_tile_pass(&get_game_manager().get_transform_state(), &get_game_manager().get_terrain_elevation_state(), &this->visible_tile_state)
{
this->quad_shader = principle::Material::load_shader_from_file(
"sprite.vert.glsl", "sprite.frag.glsl");
this->quad_shader->bind_input("vert_Position", kvncer::Shader::vertex_input_position);
this->quad_shader->bind_input("vert_Texture", kvncer::Shader::vertex_input_texture_coordinate);
make_quad(this->quad, this->quad_vertex_buffer);
get_game_manager().get_world_update_manager().add_pass(&visible_tile_pass);
auto data_path = std::getenv("NECRONOMICON_DATA_PATH");
if (data_path != nullptr)
{
std::string map_path = std::string(data_path) + "/map";
std::string brochure_path = std::string(data_path) + "/database";
try
{
load_map(map_path);
load_brochure(brochure_path);
}
catch (const std::exception& e)
{
std::cout << e.what() << std::endl;
}
}
}
plato::Application::~Application()
{
delete this->quad_shader;
clear_tiles();
}
void plato::Application::update(float delta)
{
ALLEGRO_MOUSE_STATE mouse_state;
al_get_mouse_state(&mouse_state);
this->current_mouse_x = mouse_state.x;
this->current_mouse_y = mouse_state.y;
}
void plato::Application::draw()
{
principle::Application::draw();
glDisable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
auto view = get_view_matrix();
auto projection = get_projection_matrix();
for (auto sector_coordinate: this->visible_sectors)
{
if (sector_coordinate.layer != this->current_layer)
{
continue;
}
auto position = glm::translate(glm::mat4(1.0f), glm::vec3(sector_coordinate.x, sector_coordinate.y, 0));
auto scale = glm::scale(glm::mat4(1.0f), glm::vec3(thoreau::SECTOR_SIZE, thoreau::SECTOR_SIZE, 1));
auto transformed_view = view * scale * position;
draw_sector(sector_coordinate, transformed_view, projection);
}
if (this->draw_elevations)
{
for (auto& i: this->sector_elevation_textures)
{
if (i.first.layer != this->current_layer)
{
continue;
}
auto sector_coordinate = i.first;
auto position = glm::translate(glm::mat4(1.0f), glm::vec3(sector_coordinate.x, sector_coordinate.y, 0));
auto scale = glm::scale(glm::mat4(1.0f), glm::vec3(thoreau::SECTOR_SIZE, thoreau::SECTOR_SIZE, 1));
auto transformed_view = view * scale * position;
draw_sector_elevations(i.first, transformed_view, projection);
}
}
if (this->draw_walls)
{
for (auto& i: this->sector_wall_textures)
{
if (i.first.layer != this->current_layer)
{
continue;
}
auto sector_coordinate = i.first;
auto position = glm::translate(glm::mat4(1.0f), glm::vec3(sector_coordinate.x, sector_coordinate.y, 0));
auto scale = glm::scale(glm::mat4(1.0f), glm::vec3(thoreau::SECTOR_SIZE, thoreau::SECTOR_SIZE, 1));
auto transformed_view = view * scale * position;
draw_sector_walls(i.first, transformed_view, projection);
}
}
if (this->preview_tool && this->draw_atlas)
{
this->preview_tool->draw(this->tool_renderer);
}
if (this->toolbox)
{
this->toolbox->draw(this->tool_renderer);
}
this->tool_renderer.draw();
}
void plato::Application::update_gui()
{
auto& imgui = ImGui::GetIO();
if (!this->menu.empty())
{
static const int WINDOW_FLAGS = ImGuiWindowFlags_NoTitleBar
| ImGuiWindowFlags_NoScrollbar
| ImGuiWindowFlags_NoResize
| ImGuiWindowFlags_NoSavedSettings;
ImGui::PushStyleColor(ImGuiCol_WindowBg, ImVec4(0, 0, 0, 0));
ImGui::SetNextWindowPos(ImVec2(current_mouse_x, current_mouse_y));
ImGui::Begin("plato_menu_window", nullptr, WINDOW_FLAGS);
{
ImGui::SetWindowSize(ImVec2(1, 1));
if (ImGui::BeginPopup("plato_tool_selector"))
{
this->menu_open = true;
if (this->menu.empty())
{
ImGui::CloseCurrentPopup();
}
int id = 0;
for (auto& item: this->menu)
{
ImGui::PushID(id);
if (ImGui::MenuItem(item.first.c_str()))
{
item.second();
}
ImGui::PopID();
}
if (ImGui::MenuItem("Cancel"))
{
clear_menu();
}
ImGui::EndPopup();
}
else
{
if (this->menu_open)
{
this->menu_open = false;
clear_menu();
}
else if (!this->menu.empty())
{
ImGui::OpenPopup("plato_tool_selector");
}
}
}
ImGui::End();
ImGui::PopStyleColor();
}
if (this->show_current_tile_info && !imgui.WantCaptureMouse)
{
auto& map = get_game_manager().get_map();
auto& minimap = get_game_manager().get_minimap();
auto tile_coordinate = thoreau::tile_from_world(this->mouse_world_position);
tile_coordinate.layer = this->current_layer;
auto sector_coordinate = thoreau::sector_from_tile(tile_coordinate);
ImGui::BeginTooltip();
ImGui::Text(
"Tile (%d, %d; %d)",
tile_coordinate.x,
tile_coordinate.y,
tile_coordinate.layer);
ImGui::Text(
"Sector (%d, %d; %d)",
sector_coordinate.x,
sector_coordinate.y,
sector_coordinate.layer);
if (this->visible_tile_state.has(tile_coordinate))
{
ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(0, 1, 0, 1));
ImGui::BulletText("visible");
ImGui::PopStyleColor();
}
else
{
ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1, 1, 0, 1));
ImGui::BulletText("not visible");
ImGui::PopStyleColor();
}
if (map.has_tile(tile_coordinate))
{
auto& tile = map.get_tile(tile_coordinate);
if (tile.has_elevation())
{
ImGui::BulletText("elevation: %.0f", tile.get_elevation());
}
else
{
ImGui::BulletText("elevation: (none)");
}
ImGui::BulletText("height: %.0f", tile.get_height());
ImGui::BulletText("flags: 0x%08x", tile.get_flags());
if (tile.is_wall())
{
ImGui::BulletText("is wall");
}
if (tile.is_door())
{
ImGui::BulletText("is door");
}
if (tile.is_portal())
{
ImGui::BulletText("is portal");
}
if (tile.is_impassable())
{
ImGui::BulletText("is impassable");
}
else
{
ImGui::BulletText("is passable");
}
if (minimap.get_is_visible())
{
std::set<std::string> features;
for (auto i = minimap.features_begin(); i != minimap.features_end(); ++i)
{
auto feature_coordinate = minimap.minimap_to_tile(i->second);
if (feature_coordinate == tile_coordinate)
{
features.insert(i->first);
}
}
if (!features.empty())
{
ImGui::Text("features:");
for (auto& i: features)
{
ImGui::BulletText("%s", i.c_str());
}
}
}
}
ImGui::EndTooltip();
}
principle::Application::update_gui();
for (auto window: this->pending_windows)
{
this->windows.erase(window);
delete window;
}
this->pending_windows.clear();
}
void plato::Application::on_mouse_move(const principle::MouseEvent& event)
{
if (this->is_camera_dragging)
{
this->camera_offset.x += event.get_difference().x / this->camera_scale;
this->camera_offset.y -= event.get_difference().y / this->camera_scale;
}
if (this->is_camera_zooming)
{
this->camera_scale += event.get_difference().y / 16.0f;
this->camera_scale = std::max(this->camera_scale, 1.0f);
}
auto position = event.get_position();
position.y = get_display()->get_height() - position.y;
auto view_matrix = glm::inverse(get_view_matrix());
auto transformed_position = view_matrix * glm::vec4(position, 0.0f, 1.0f);
transformed_position *= (float)thoreau::TILE_SIZE;
this->mouse_world_position.x = transformed_position.x;
this->mouse_world_position.y = transformed_position.y;
this->mouse_world_position.layer = this->current_layer;
this->current_mouse_tile_position = thoreau::tile_from_world(this->mouse_world_position);
if (this->toolbox)
{
this->toolbox->set_mouse_tile_coordinate(this->current_mouse_tile_position);
this->toolbox->on_mouse_move(event);
}
}
void plato::Application::on_mouse_button_down(
const principle::MouseEvent& event)
{
if (event.get_button() == 1)
{
if (!this->toolbox || !this->toolbox->active())
{
clear_menu();
add_menu_option("Edit Tile", [this]()
{
if (this->is_multiselection)
{
this->edit_tile_window.add_tile(this->current_mouse_tile_position);
}
else
{
this->edit_tile_window.set_tile(this->current_mouse_tile_position);
}
});
if (this->atlas)
{
add_menu_option("New Location", [this]()
{
this->tool_factory.add_new_location();
});
add_menu_option("New Child Location", [this]()
{
this->tool_factory.add_new_child_location();
});
mapp::Location hover;
if (this->atlas->find(this->current_mouse_tile_position, hover))
{
auto tile_coordinate = this->current_mouse_tile_position;
int count = 0;
while (hover.resource.get_id() &&
hover.resource.get_id() != this->atlas->root().resource.get_id() &&
count < 2)
{
std::string label = "New Child Location (";
label += hover.resource.get_name();
label += ")";
add_menu_option(label, [this, hover]()
{
this->tool_factory.add_new_child_location(hover);
});
label = "Add Waypoint (";
label += hover.resource.get_name();
label += ")";
add_menu_option(label, [this, hover, tile_coordinate]()
{
this->tool_factory.add_new_waypoint(hover, tile_coordinate);
});
label = "Set Anchor (";
label += hover.resource.get_name();
label += ")";
add_menu_option(label, [this, hover, tile_coordinate]
{
if (this->atlas)
{
mapp::LocationDefinition definition = hover;
definition.has_anchor = true;
definition.anchor = tile_coordinate;
this->atlas->update(hover, definition);
}
});
label = "Edit (";
label += hover.resource.get_name();
label += ")";
add_menu_option(label, [this, hover]()
{
this->tool_factory.edit(hover.resource);
});
hover = this->atlas->parent(hover);
++count;
}
}
}
add_menu_option("Remove Sector", [this]()
{
this->remove_sector(thoreau::sector_from_tile(this->current_mouse_tile_position));
});
}
}
else if (event.get_button() == 2)
{
this->is_camera_dragging = true;
}
else if (event.get_button() == 3)
{
this->is_camera_zooming = true;
}
if (this->toolbox)
{
this->toolbox->on_mouse_button_down(event);
}
}
void plato::Application::on_mouse_button_up(const principle::MouseEvent& event)
{
if (event.get_button() == 2)
{
this->is_camera_dragging = false;
}
else if (event.get_button() == 3)
{
this->is_camera_zooming = false;
}
if (this->toolbox)
{
this->toolbox->on_mouse_button_up(event);
}
}
void plato::Application::on_key_down(const principle::KeyboardEvent& event)
{
if (event.get_key_code() == ALLEGRO_KEY_LSHIFT ||
event.get_key_code() == ALLEGRO_KEY_RSHIFT)
{
++this->is_multiselection;
}
if (event.get_key_code() == ALLEGRO_KEY_LCTRL ||
event.get_key_code() == ALLEGRO_KEY_RCTRL)
{
this->show_current_tile_info = !this->show_current_tile_info;
}
if (event.get_key_code() == ALLEGRO_KEY_F)
{
auto current_tile_coordinate = thoreau::tile_from_world(this->mouse_world_position);
auto& map = get_game_manager().get_map();
if (!map.has_tile(current_tile_coordinate))
{
map.add_tile(current_tile_coordinate);
}
if (this->is_multiselection)
{
this->edit_tile_window.add_tile(current_tile_coordinate);
}
else
{
this->edit_tile_window.set_tile(current_tile_coordinate);
}
}
if (this->toolbox)
{
this->toolbox->on_key_down(event);
}
}
void plato::Application::on_key_up(const principle::KeyboardEvent& event)
{
if (event.get_key_code() == ALLEGRO_KEY_LSHIFT ||
event.get_key_code() == ALLEGRO_KEY_RSHIFT)
{
--this->is_multiselection;
}
if (this->toolbox)
{
this->toolbox->on_key_up(event);
}
}
void plato::Application::on_start_trace()
{
this->visible_tile_state.clear();
clear_tiles();
}
void plato::Application::on_finish_trace()
{
load_tiles();
}
void plato::Application::remove_sector(const thoreau::SectorCoordinate& sector_coordinate)
{
auto& map = get_game_manager().get_map();
auto tile_coordinate = thoreau::tile_from_sector(sector_coordinate);
std::map<thoreau::TileCoordinate, thoreau::Tile> tiles;
for (auto i = 0; i < thoreau::SECTOR_SIZE; ++i)
{
for (auto j = 0; j < thoreau::SECTOR_SIZE; ++j)
{
auto t = tile_coordinate;
t.x += i;
t.y += j;
if (!map.has_tile(t.x, t.y))
{
continue;
}
int num_layers = map.get_num_layers(t.x, t.y);
for (int k = 0; k < num_layers; ++k)
{
if (k == sector_coordinate.layer)
{
continue;
}
auto s = t;
if (k > sector_coordinate.layer)
{
s.layer = k - 1;
}
else
{
s.layer = k;
}
auto r = t;
r.layer = k;
if (map.has_tile(r))
{
tiles.emplace(s, map.get_tile(r));
}
}
map.remove_tile(t.x, t.y);
}
}
this->sector_textures.erase(sector_coordinate);
this->sector_wall_textures.erase(sector_coordinate);
this->dirty_sectors.erase(sector_coordinate);
for (auto& i: tiles)
{
this->modified_tiles.insert(i.first);
map.add_tile(i.first) = i.second;
this->dirty_sectors.insert(thoreau::sector_from_tile(i.first));
}
notify_map_update();
}
void plato::Application::add_window(principle::Window* window)
{
this->windows.insert(window);
}
void plato::Application::remove_window(principle::Window* window)
{
this->pending_windows.insert(window);
}
void plato::Application::change_layer(int layer)
{
this->current_layer = layer;
if (this->toolbox)
{
this->toolbox->set_current_layer(this->current_layer);
}
}
glm::mat4 plato::Application::get_projection_matrix()
{
return glm::ortho(
0.0f, (float)get_display()->get_width(),
0.0f, (float)get_display()->get_height(),
-1.0f, 1.0f);
}
glm::mat4 plato::Application::get_view_matrix()
{
auto translation = glm::translate(
glm::mat4(1.0f),
glm::vec3(glm::floor(this->camera_offset), 0.0f));
auto scale = glm::scale(
glm::mat4(1.0f),
glm::vec3(glm::floor(this->camera_scale), glm::floor(this->camera_scale), 1.0f));
auto from_origin = glm::translate(
glm::mat4(1.0f),
glm::vec3(get_display()->get_width() / 2.0f, get_display()->get_height() / 2.0f, 0.0f));
auto to_origin = glm::translate(
glm::mat4(1.0f),
-glm::vec3(get_display()->get_width() / 2.0f, get_display()->get_height() / 2.0f, 0.0f));
return from_origin * scale * to_origin * translation;
}
void plato::Application::load_tiles()
{
auto& map = get_game_manager().get_map();
this->bounds = kvlc::Bounds(glm::vec3(HUGE_VALF), glm::vec3(-HUGE_VALF));
for (auto& i: this->visible_tile_state)
{
auto tile_coordinate = i.first;
this->dirty_sectors.insert(thoreau::sector_from_tile(tile_coordinate));
if (!map.has_tile(tile_coordinate))
{
continue;
}
auto& tile = map.get_tile(tile_coordinate);
if (!tile.has_elevation())
{
continue;
}
glm::vec3 position;
position.x = i.first.x * thoreau::TILE_SIZE;
position.y = tile.get_elevation();
position.z = i.first.y * thoreau::TILE_SIZE;
this->bounds.expand(position);
}
auto center = this->bounds.compute_center();
this->camera_offset.x = -(center.x / thoreau::TILE_SIZE);
this->camera_offset.x += get_display()->get_width() / 2.0f;
this->camera_offset.y = -(center.z / thoreau::TILE_SIZE);
this->camera_offset.y += get_display()->get_height() / 2.0f;
for (auto& i: this->visible_tile_state)
{
load_tile(i.first);
this->visible_sectors.insert(thoreau::sector_from_tile(i.first));
}
notify_map_update();
}
void plato::Application::load_tile(const thoreau::TileCoordinate& tile_coordinate)
{
auto sector_coordinate = thoreau::sector_from_tile(tile_coordinate);
if (this->sector_textures.count(sector_coordinate) != 0)
{
return;
}
std::string path;
{
const char* root = std::getenv("NECRONOMICON_DATA_PATH");
if (root == nullptr)
{
path = "./";
}
else
{
path = root;
path += "/../samples/map/";
}
char filename[128];
std::snprintf(
filename, sizeof(filename), "%03dx%03dx%02d",
sector_coordinate.x, sector_coordinate.y, sector_coordinate.layer);
path += filename;
}
const std::size_t TILE_LENGTH = 64;
const std::size_t SECTOR_LENGTH = thoreau::SECTOR_SIZE * thoreau::SECTOR_SIZE;
const std::size_t IMAGE_LENGTH = TILE_LENGTH * thoreau::SECTOR_SIZE;
principle::ImageStore<glm::u8vec4, SECTOR_LENGTH, TILE_LENGTH, TILE_LENGTH> image_store;
if (boost::filesystem::exists(path + "-color.bin"))
{
image_store.read(path + "-color.bin");
}
else
{
image_store.clear(glm::u8vec4(0));
}
auto texture = std::make_unique<kvncer::Texture>(
kvncer::Texture::component_format_rgba, false,
IMAGE_LENGTH, IMAGE_LENGTH);
std::size_t index = 0;
for (int j = 0; j < thoreau::SECTOR_SIZE; ++j)
{
for (int i = 0; i < thoreau::SECTOR_SIZE; ++i)
{
texture->update(
i * TILE_LENGTH, j * TILE_LENGTH,
(int)TILE_LENGTH, (int)TILE_LENGTH,
kvncer::Texture::component_format_rgba,
kvncer::Texture::component_type_unsigned_byte,
&image_store.get(index)->x);
++index;
}
}
this->sector_textures[thoreau::sector_from_tile(tile_coordinate)] = std::move(texture);
}
void plato::Application::clear_tiles()
{
this->sector_textures.clear();
}
void plato::Application::notify_map_update()
{
for (auto sector: this->dirty_sectors)
{
update_sector_elevations_texture(sector);
update_sector_walls_texture(sector);
}
this->dirty_sectors.clear();
}
void plato::Application::update_sector_elevations_texture(
const thoreau::SectorCoordinate& sector_coordinate)
{
auto& map = get_game_manager().get_map();
auto begin = map.sector_begin(sector_coordinate);
auto end = map.sector_end(sector_coordinate);
std::map<thoreau::TileCoordinate, thoreau::Tile> tiles;
for (auto i = begin; i != end; ++i)
{
auto tile_coordinate = *i;
if (tile_coordinate.layer != sector_coordinate.layer)
{
continue;
}
auto& tile = map.get_tile(tile_coordinate);
if (!tile.has_elevation())
{
continue;
}
tiles[tile_coordinate] = tile;
}
float min_elevation = this->bounds.min.y;
float max_elevation = this->bounds.max.y;
const int TILE_SIZE = 16;
int width = TILE_SIZE * thoreau::SECTOR_SIZE;
int height = TILE_SIZE * thoreau::SECTOR_SIZE;
kommon::Image image(width, height);
int min_tile_x = sector_coordinate.x * thoreau::SECTOR_SIZE;
int min_tile_y = sector_coordinate.y * thoreau::SECTOR_SIZE;
for (auto& i: tiles)
{
auto elevation = i.second.get_elevation();
float relative_elevation = (elevation - min_elevation) / (max_elevation - min_elevation);
float hue = relative_elevation * 360.0f;
auto color = glm::rgbColor(glm::vec3(hue, 0.5f, 0.75f));
int left = (i.first.x - min_tile_x) * TILE_SIZE;
int bottom = (i.first.y - min_tile_y) * TILE_SIZE;
for (int y = 0; y < TILE_SIZE; ++y)
{
image.draw_line(
left, bottom + y,
left + TILE_SIZE, bottom + y,
glm::vec4(color, 1.0f));
}
}
auto texture = std::make_unique<kvncer::Texture>(
kvncer::Texture::component_format_rgba, false,
width, height);
texture->update(
0, 0, width, height,
kvncer::Texture::component_format_rgba,
kvncer::Texture::component_type_unsigned_byte,
image.get_pixels());
this->sector_elevation_textures[sector_coordinate] = std::move(texture);
}
void plato::Application::update_sector_walls_texture(
const thoreau::SectorCoordinate& sector_coordinate)
{
auto& map = get_game_manager().get_map();
auto begin = map.sector_begin(sector_coordinate);
auto end = map.sector_end(sector_coordinate);
std::map<thoreau::TileCoordinate, thoreau::Tile> tiles;
for (auto i = begin; i != end; ++i)
{
auto tile_coordinate = *i;
if (tile_coordinate.layer != sector_coordinate.layer)
{
continue;
}
auto& tile = map.get_tile(tile_coordinate);
tiles[tile_coordinate] = tile;
}
const int TILE_SIZE = 4;
int width = TILE_SIZE * thoreau::SECTOR_SIZE;
int height = TILE_SIZE * thoreau::SECTOR_SIZE;
kommon::Image image(width, height);
int min_tile_x = sector_coordinate.x * thoreau::SECTOR_SIZE;
int min_tile_y = sector_coordinate.y * thoreau::SECTOR_SIZE;
for (auto& i: tiles)
{
auto& tile = i.second;
int left = (i.first.x - min_tile_x) * TILE_SIZE;
int right = left + TILE_SIZE;
int bottom = (i.first.y - min_tile_y) * TILE_SIZE;
int top = bottom + TILE_SIZE;
if (tile.is_impassable() && tile.has_elevation())
{
if (tile.get_flags() & thoreau::Tile::flag_wall_diagonal_right)
{
image.draw_line(right, bottom, left, top, glm::vec4(1.0f));
}
else if (tile.get_flags() & thoreau::Tile::flag_wall_diagonal_left)
{
image.draw_line(left, bottom, right, top, glm::vec4(1.0f));
}
else
{
glm::vec4 color;
if (tile.get_flags() & thoreau::Tile::flag_water)
{
color = glm::vec4(0.0f, 0.0f, 1.0f, 0.5f);
}
else
{
color = glm::vec4(1.0f, 0.0f, 0.0f, 0.5f);
}
for (int y = bottom; y <= top; ++y)
{
for (int x = left; x <= right; ++x)
{
image.set_pixel(x, y, color);
}
}
}
}
if (tile.is_portal())
{
for (int y = bottom; y <= top; ++y)
{
for (int x = left; x <= right; ++x)
{
image.set_pixel(x, y, glm::vec4(0.0f, 1.0f, 0.0f, 1.0f));
}
}
continue;
}
if (!tile.is_wall() && !tile.is_door())
{
continue;
}
const auto wall_color = glm::vec4(1.0f, 1.0f, 1.0f, 1.0f);
const auto door_color = glm::vec4(1.0f, 0.0f, 0.0f, 1.0f);
int flags = tile.get_flags();
if (flags & thoreau::Tile::flag_door_left)
{
image.draw_line(left, top, left, bottom, door_color);
}
else if (flags & thoreau::Tile::flag_wall_left)
{
image.draw_line(left, top, left, bottom, wall_color);
}
if (flags & thoreau::Tile::flag_door_right)
{
image.draw_line(right, top, right, bottom, door_color);
}
else if (flags & thoreau::Tile::flag_wall_right)
{
image.draw_line(right, top, right, bottom, wall_color);
}
if (flags & thoreau::Tile::flag_door_top)
{
image.draw_line(left, top, right, top, door_color);
}
else if (flags & thoreau::Tile::flag_wall_top)
{
image.draw_line(left, top, right, top, wall_color);
}
if (flags & thoreau::Tile::flag_door_bottom)
{
image.draw_line(left, bottom, right, bottom, door_color);
}
else if (flags & thoreau::Tile::flag_wall_bottom)
{
image.draw_line(left, bottom, right, bottom, wall_color);
}
}
auto texture = std::make_unique<kvncer::Texture>(
kvncer::Texture::component_format_rgba, false,
width, height);
texture->update(
0, 0, width, height,
kvncer::Texture::component_format_rgba,
kvncer::Texture::component_type_unsigned_byte,
image.get_pixels());
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
this->sector_wall_textures[sector_coordinate] = std::move(texture);
}
void plato::Application::draw_sector(
const thoreau::SectorCoordinate& sector_coordinate,
const glm::mat4& view, const glm::mat4& projection)
{
auto sector = this->sector_textures.find(sector_coordinate);
if (sector == this->sector_textures.end())
{
return;
}
sector->second->bind(0);
this->quad_shader->use();
this->quad_shader->set("principle_Texture", 1);
this->quad_shader->set("principle_View", view);
this->quad_shader->set("principle_Projection", projection);
this->quad.draw();
}
void plato::Application::draw_sector_elevations(
const thoreau::SectorCoordinate& sector_coordinate,
const glm::mat4& view, const glm::mat4& projection)
{
auto texture = this->sector_elevation_textures.find(sector_coordinate);
if (texture == this->sector_elevation_textures.end())
{
return;
}
texture->second->bind(0);
this->quad_shader->use();
this->quad_shader->set("principle_Texture", 1);
this->quad_shader->set("principle_View", view);
this->quad_shader->set("principle_Projection", projection);
this->quad.draw();
}
void plato::Application::draw_sector_walls(
const thoreau::SectorCoordinate& sector_coordinate,
const glm::mat4& view, const glm::mat4& projection)
{
auto texture = this->sector_wall_textures.find(sector_coordinate);
if (texture == this->sector_wall_textures.end())
{
return;
}
texture->second->bind(0);
this->quad_shader->use();
this->quad_shader->set("principle_Texture", 1);
this->quad_shader->set("principle_View", view);
this->quad_shader->set("principle_Projection", projection);
this->quad.draw();
}
void plato::Application::load_map(const std::string& filename)
{
auto& map = get_game_manager().get_map();
map.clear();
std::ifstream stream(filename);
std::size_t count = map.load(stream);
if (stream.bad())
{
std::fprintf(stderr, "couldn't load map '%s'\n", filename.c_str());
}
else
{
std::fprintf(stderr, "loaded %lu tiles from map '%s'\n", count, filename.c_str());
get_game_manager().get_runtime_map().merge(map);
}
}
#include "plato/gui/itemResource.hpp"
#include "plato/gui/locationResource.hpp"
#include "plato/gui/shopResource.hpp"
void plato::Application::load_brochure(const std::string& filename)
{
this->brochure = std::make_unique<twoflower::Brochure>(filename);
this->atlas = std::make_unique<mapp::Atlas>(*this->brochure);
this->game = std::make_unique<mapp::Game>(*this->brochure);
this->toolbox = std::make_unique<Toolbox>(
this->tool_factory,
get_game_manager().get_map(),
*this->brochure,
*this->atlas);
this->preview_tool = std::make_unique<PreviewTool>(*this->toolbox);
this->brochure_widget_manager = std::make_unique<BrochureWidgetManager>(*this->brochure, *this->atlas, *this->game, *this->toolbox);
this->brochure_widget_manager->add("location", new LocationResourceView());
this->brochure_widget_manager->add("location", new LocationResourceEditor());
this->brochure_widget_manager->add("item", new ItemResourceView());
this->brochure_widget_manager->add("item", new ItemResourceEditor());
this->brochure_widget_manager->add("shop", new ShopResourceView());
this->brochure_widget_manager->add("shop", new ShopResourceEditor());
}
void plato::Application::add_menu_option(
const std::string& label, const std::function<void()>& callback)
{
this->menu.emplace_back(label, callback);
}
void plato::Application::clear_menu()
{
this->menu.clear();
}
plato::Application::ApplicationToolRenderer::ApplicationToolRenderer(Application* application)
{
this->application = application;
}
glm::vec2 plato::Application::ApplicationToolRenderer::get_camera_offset() const
{
return this->application->camera_offset;
}
float plato::Application::ApplicationToolRenderer::get_camera_scale() const
{
return this->application->camera_scale;
}
int plato::Application::ApplicationToolRenderer::get_viewport_width() const
{
return this->application->get_display()->get_width();
}
int plato::Application::ApplicationToolRenderer::get_viewport_height() const
{
return this->application->get_display()->get_height();
}
glm::mat4 plato::Application::ApplicationToolRenderer::get_view_matrix() const
{
return this->application->get_view_matrix();
}
glm::mat4 plato::Application::ApplicationToolRenderer::get_projection_matrix() const
{
return this->application->get_projection_matrix();
}
void plato::Application::ApplicationToolRenderer::render(ImDrawList& draw_list)
{
this->application->get_gui_manager().render(draw_list);
}
plato::Application::ApplicationToolFactory::ApplicationToolFactory(Application* application)
{
this->application = application;
}
void plato::Application::ApplicationToolFactory::add_new_location()
{
auto tool = new ComplexShapeTool(
*this->application->toolbox,
[this](auto shape)
{
mapp::LocationDefinition definition;
definition.name = "New Location";
definition.shape = shape;
auto result = this->application->atlas->add(definition);
this->edit(result.resource);
});
this->application->toolbox->use(tool);
}
void plato::Application::ApplicationToolFactory::add_new_child_location(
const mapp::Location& parent)
{
auto tool = new ComplexShapeTool(
*this->application->toolbox,
[this, parent](auto shape)
{
mapp::LocationDefinition definition;
definition.name = "New Location";
definition.shape = shape;
auto result = this->application->atlas->add(definition, parent);
this->edit(result.resource);
});
this->application->toolbox->use(tool);
}
void plato::Application::ApplicationToolFactory::add_new_child_location()
{
this->application->find_location_window.open(
[this](auto parent)
{
this->add_new_child_location(parent);
});
}
void plato::Application::ApplicationToolFactory::add_new_waypoint(
const mapp::Location& parent,
const thoreau::TileCoordinate& tile_coordinate)
{
mapp::LocationDefinition definition;
definition.name = "New Waypoint";
definition.shape.add_point(tile_coordinate);
auto location = this->application->atlas->add(definition, parent);
this->application->brochure->builder().add_tag(location.resource, "mapp-waypoint");
edit(location.resource);
}
void plato::Application::ApplicationToolFactory::add_new_link(const mapp::Location& from)
{
// TODO
}
void plato::Application::ApplicationToolFactory::find_location(const std::function<void(mapp::Location)>& callback)
{
this->application->find_location_window.open(
[this, callback](auto parent)
{
callback(parent);
});
}
void plato::Application::ApplicationToolFactory::find_resource(
const std::string& type,
const std::function<void(twoflower::Resource)>& callback)
{
this->application->find_resource_window.open(
type,
[this, callback](auto parent)
{
callback(parent);
});
}
void plato::Application::ApplicationToolFactory::view(const twoflower::Resource& resource)
{
this->application->add_window(new ViewResourceWindow(resource, this->application));
}
void plato::Application::ApplicationToolFactory::edit(const twoflower::Resource& resource)
{
this->application->add_window(new EditResourceWindow(resource, this->application));
}
void plato::Application::ApplicationToolFactory::view(const twoflower::Action& action)
{
this->application->add_window(new ViewActionWindow(action, this->application));
}
void plato::Application::ApplicationToolFactory::edit(const twoflower::Action& action)
{
this->application->add_window(new EditActionWindow(action, this->application));
}
| [
"[email protected]"
] | |
0c74c5fbc31849b2c915e833347a7eb130d66e69 | 1275d01222f4bf1f0764115c4492bff4bdd37ca1 | /engine/public/vox/model_data_reader.h | 108b77381abec4021ebd8d5dce9019de3ed45cc2 | [
"MIT"
] | permissive | biomorphs/SDLEngine | f37568a7f63eed4873a0825a46ec2e77894497a2 | e919c571f914e7e0d8ef1a85f184c86e04e8bf14 | refs/heads/master | 2021-01-22T13:47:29.529042 | 2015-08-21T17:32:47 | 2015-08-21T17:32:47 | 14,442,605 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,020 | h | /*
SDLEngine
Matt Hoyle
*/
#pragma once
#include <glm/glm.hpp>
namespace Vox
{
template<class ModelType>
class ModelDataReader
{
public:
ModelDataReader(const ModelType& model);
~ModelDataReader();
typedef typename ModelType::VoxelDataType VoxelDataType;
bool HasBlockData(const glm::ivec3& blockIndex) const;
VoxelDataType VoxelAt(const glm::ivec3& blockIndex, const glm::ivec3& voxelIndex);
VoxelDataType VoxelNeighbour(const glm::ivec3& blockIndex, const glm::ivec3& voxelIndex, const glm::ivec3& offset);
void MooreNeighbours(const glm::ivec3& blockIndex, const glm::ivec3& voxelIndex, VoxelDataType(&data)[3][3][3]);
private:
const typename ModelType::BlockType* GetBlockAndCache(const glm::ivec3& blockIndex);
void FixupNeighbourIndex(int32_t voxelIndex, int32_t blockIndex, int32_t& blockIndexOut, int32_t& voxelIndexOut) const;
const ModelType& m_target;
glm::ivec3 m_cachedBlockIndex;
const typename ModelType::BlockType* m_cachedBlock;
};
}
#include "model_data_reader.inl" | [
"[email protected]"
] | |
7b37f5713cccc467581ca17e6cb5b78faed9d4aa | 424d9d65e27cd204cc22e39da3a13710b163f4e7 | /components/sync/trusted_vault/trusted_vault_connection_impl.cc | 68fa73cc7bbe1e22120ee21ab7fa493ab7d446d2 | [
"BSD-3-Clause"
] | permissive | bigben0123/chromium | 7c5f4624ef2dacfaf010203b60f307d4b8e8e76d | 83d9cd5e98b65686d06368f18b4835adbab76d89 | refs/heads/master | 2023-01-10T11:02:26.202776 | 2020-10-30T09:47:16 | 2020-10-30T09:47:16 | 275,543,782 | 0 | 0 | BSD-3-Clause | 2020-10-30T09:47:18 | 2020-06-28T08:45:11 | null | UTF-8 | C++ | false | false | 1,552 | cc | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/sync/trusted_vault/trusted_vault_connection_impl.h"
#include <utility>
#include "components/sync/trusted_vault/securebox.h"
#include "components/sync/trusted_vault/trusted_vault_access_token_fetcher.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
namespace syncer {
TrustedVaultConnectionImpl::TrustedVaultConnectionImpl(
std::unique_ptr<network::PendingSharedURLLoaderFactory> url_loader_factory,
std::unique_ptr<TrustedVaultAccessTokenFetcher> access_token_fetcher)
: pending_url_loader_factory_(std::move(url_loader_factory)),
access_token_fetcher_(std::move(access_token_fetcher)) {}
TrustedVaultConnectionImpl::~TrustedVaultConnectionImpl() = default;
void TrustedVaultConnectionImpl::RegisterAuthenticationFactor(
const CoreAccountInfo& account_info,
const std::vector<uint8_t>& last_trusted_vault_key,
int last_trusted_vault_key_version,
const SecureBoxPublicKey& authentication_factor_public_key,
RegisterAuthenticationFactorCallback callback) {
NOTIMPLEMENTED();
}
void TrustedVaultConnectionImpl::DownloadKeys(
const CoreAccountInfo& account_info,
const std::vector<uint8_t>& last_trusted_vault_key,
int last_trusted_vault_key_version,
std::unique_ptr<SecureBoxKeyPair> device_key_pair,
DownloadKeysCallback callback) {
NOTIMPLEMENTED();
}
} // namespace syncer
| [
"[email protected]"
] | |
aabc69de4e44591d2c80c101c9b0bcd2bbcf8c23 | 600df3590cce1fe49b9a96e9ca5b5242884a2a70 | /net/cert/test_root_certs.cc | c5f777ed619ba086f16ece4a4280183d95692739 | [
"BSD-3-Clause"
] | permissive | metux/chromium-suckless | efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a | 72a05af97787001756bae2511b7985e61498c965 | refs/heads/orig | 2022-12-04T23:53:58.681218 | 2017-04-30T10:59:06 | 2017-04-30T23:35:58 | 89,884,931 | 5 | 3 | BSD-3-Clause | 2022-11-23T20:52:53 | 2017-05-01T00:09:08 | null | UTF-8 | C++ | false | false | 1,871 | cc | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/cert/test_root_certs.h"
#include <string>
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/logging.h"
#include "base/threading/thread_restrictions.h"
#include "net/cert/x509_certificate.h"
namespace net {
namespace {
bool g_has_instance = false;
base::LazyInstance<TestRootCerts>::Leaky
g_test_root_certs = LAZY_INSTANCE_INITIALIZER;
CertificateList LoadCertificates(const base::FilePath& filename) {
std::string raw_cert;
if (!base::ReadFileToString(filename, &raw_cert)) {
LOG(ERROR) << "Can't load certificate " << filename.value();
return CertificateList();
}
return X509Certificate::CreateCertificateListFromBytes(
raw_cert.data(), raw_cert.length(), X509Certificate::FORMAT_AUTO);
}
} // namespace
// static
TestRootCerts* TestRootCerts::GetInstance() {
return g_test_root_certs.Pointer();
}
bool TestRootCerts::HasInstance() {
return g_has_instance;
}
bool TestRootCerts::AddFromFile(const base::FilePath& file) {
base::ThreadRestrictions::ScopedAllowIO allow_io_for_loading_test_certs;
CertificateList root_certs = LoadCertificates(file);
if (root_certs.empty() || root_certs.size() > 1)
return false;
return Add(root_certs.front().get());
}
TestRootCerts::TestRootCerts() {
Init();
g_has_instance = true;
}
ScopedTestRoot::ScopedTestRoot() {}
ScopedTestRoot::ScopedTestRoot(X509Certificate* cert) {
Reset(cert);
}
ScopedTestRoot::~ScopedTestRoot() {
Reset(NULL);
}
void ScopedTestRoot::Reset(X509Certificate* cert) {
if (cert_.get())
TestRootCerts::GetInstance()->Clear();
if (cert)
TestRootCerts::GetInstance()->Add(cert);
cert_ = cert;
}
} // namespace net
| [
"[email protected]"
] | |
ef4587fb9f80aafe22a5bca666f16897ba2a7cb9 | 7cf6e8a304805e924c4f523ac6a801bf791860ef | /examples/C_barcodes/C_barcodes.ino | 7407340a692118e8a64948ab6d6578c1b4e359c1 | [
"MIT"
] | permissive | adafruit/Adafruit-Thermal-Printer-Library | 1fd14929fcb2cc689bee98e51e319f982fe2b5a1 | 54786351af1d84580c4ae555d439756679b0dc44 | refs/heads/master | 2023-08-29T08:18:04.322369 | 2023-05-16T14:47:23 | 2023-05-16T14:47:23 | 2,907,600 | 220 | 119 | null | 2021-04-14T17:59:05 | 2011-12-03T23:06:14 | C++ | UTF-8 | C++ | false | false | 3,494 | ino | /*------------------------------------------------------------------------
Example sketch for Adafruit Thermal Printer library for Arduino.
Demonstrates the available gamut of barcodes.
See 'A_printertest' sketch for a more generalized printing example.
BARCODE AVAILABILITY VARIES WITH FIRMWARE. Not all barcodes may be
displayed, this is normal. Sketch may need changes for older firmware.
------------------------------------------------------------------------*/
#include "Adafruit_Thermal.h"
// Here's the syntax when using SoftwareSerial (e.g. Arduino Uno) --------
// If using hardware serial instead, comment out or remove these lines:
#include "SoftwareSerial.h"
#define TX_PIN 6 // Arduino transmit YELLOW WIRE labeled RX on printer
#define RX_PIN 5 // Arduino receive GREEN WIRE labeled TX on printer
SoftwareSerial mySerial(RX_PIN, TX_PIN); // Declare SoftwareSerial obj first
Adafruit_Thermal printer(&mySerial); // Pass addr to printer constructor
// Then see setup() function regarding serial & printer begin() calls.
// Here's the syntax for hardware serial (e.g. Arduino Due) --------------
// Un-comment the following line if using hardware serial:
//Adafruit_Thermal printer(&Serial1); // Or Serial2, Serial3, etc.
// -----------------------------------------------------------------------
void setup() {
// This line is for compatibility with the Adafruit IotP project pack,
// which uses pin 7 as a spare grounding point. You only need this if
// wired up the same way (w/3-pin header into pins 5/6/7):
pinMode(7, OUTPUT); digitalWrite(7, LOW);
mySerial.begin(19200); // Initialize SoftwareSerial
//Serial1.begin(19200); // Use this instead if using hardware serial
printer.begin(); // Init printer (same regardless of serial type)
printer.justify('C');
printer.boldOn();
printer.println(F("BARCODE EXAMPLES\n"));
printer.boldOff();
printer.justify('L');
// There seems to be some conflict between datasheet descriptions
// of barcode formats and reality. Try Wikipedia and/or:
// http://www.barcodeisland.com/symbolgy.phtml
// Also note that strings passed to printBarcode() are always normal
// RAM-resident strings; PROGMEM strings (e.g. F("123")) are NOT used.
// UPC-A: 12 digits
printer.print(F("UPC-A:"));
printer.printBarcode("123456789012", UPC_A);
// UPC-E: 6 digits ???
/* Commented out because I can't get this one working yet
printer.print(F("UPC-E:"));
printer.printBarcode("123456", UPC_E);
*/
// EAN-13: 13 digits (same as JAN-13)
printer.print(F("EAN-13:"));
printer.printBarcode("1234567890123", EAN13);
// EAN-8: 8 digits (same as JAN-8)
printer.print(F("EAN-8:"));
printer.printBarcode("12345678", EAN8);
// CODE 39: variable length w/checksum?, 0-9,A-Z,space,$%+-./:
printer.print(F("CODE 39:"));
printer.printBarcode("ADAFRUT", CODE39);
// ITF: 2-254 digits (# digits always multiple of 2)
printer.print(F("ITF:"));
printer.printBarcode("1234567890", ITF);
// CODABAR: variable length 0-9,A-D,%+-./:
printer.print(F("CODABAR:"));
printer.printBarcode("1234567890", CODABAR);
// CODE 93: compressed version of Code 39?
printer.print(F("CODE 93:"));
printer.printBarcode("ADAFRUIT", CODE93);
// CODE 128: 2-255 characters (ASCII 0-127)
printer.print(F("CODE128:"));
printer.printBarcode("Adafruit", CODE128);
printer.feed(2);
printer.setDefault(); // Restore printer to defaults
}
void loop() {
}
| [
"[email protected]"
] | |
d9a87469a7f6e6accb4882bd948fb41f700953fd | 49822c3b5fa2b8216cad7158dd6d1a07f0e7c9ac | /kizunano/rpc/rpc.cpp | 916401aea32a0e9629fa7c41a72237e1b1cd272b | [
"BSD-3-Clause"
] | permissive | cool-japan/kiznode | 2653c4d67e1d3eb7b6e3c8ce25b5402ba84a59f2 | c6013e7e992ab75432db58da05054b381f821566 | refs/heads/master | 2023-05-03T10:58:58.195419 | 2020-12-24T16:13:22 | 2020-12-24T16:13:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,808 | cpp | #include <kizunano/boost/asio/bind_executor.hpp>
#include <kizunano/lib/rpc_handler_interface.hpp>
#include <kizunano/rpc/rpc.hpp>
#include <kizunano/rpc/rpc_connection.hpp>
#include <boost/format.hpp>
#include <iostream>
#ifdef NANO_SECURE_RPC
#include <kizunano/rpc/rpc_secure.hpp>
#endif
nano::rpc::rpc (boost::asio::io_context & io_ctx_a, nano::rpc_config const & config_a, nano::rpc_handler_interface & rpc_handler_interface_a) :
config (config_a),
acceptor (io_ctx_a),
logger (std::chrono::milliseconds (0)),
io_ctx (io_ctx_a),
rpc_handler_interface (rpc_handler_interface_a)
{
rpc_handler_interface.rpc_instance (*this);
}
nano::rpc::~rpc ()
{
if (!stopped)
{
stop ();
}
}
void nano::rpc::start ()
{
auto endpoint (boost::asio::ip::tcp::endpoint (boost::asio::ip::make_address_v6 (config.address), config.port));
if (!endpoint.address ().is_loopback () && config.enable_control)
{
auto warning = boost::str (boost::format ("WARNING: control-level RPCs are enabled on non-local address %1%, potentially allowing wallet access outside local computer") % endpoint.address ().to_string ());
std::cout << warning << std::endl;
logger.always_log (warning);
}
acceptor.open (endpoint.protocol ());
acceptor.set_option (boost::asio::ip::tcp::acceptor::reuse_address (true));
boost::system::error_code ec;
acceptor.bind (endpoint, ec);
if (ec)
{
logger.always_log (boost::str (boost::format ("Error while binding for RPC on port %1%: %2%") % endpoint.port () % ec.message ()));
throw std::runtime_error (ec.message ());
}
acceptor.listen ();
accept ();
}
void nano::rpc::accept ()
{
auto connection (std::make_shared<nano::rpc_connection> (config, io_ctx, logger, rpc_handler_interface));
acceptor.async_accept (connection->socket, boost::asio::bind_executor (connection->strand, [this, connection](boost::system::error_code const & ec) {
if (ec != boost::asio::error::operation_aborted && acceptor.is_open ())
{
accept ();
}
if (!ec)
{
connection->parse_connection ();
}
else
{
logger.always_log (boost::str (boost::format ("Error accepting RPC connections: %1% (%2%)") % ec.message () % ec.value ()));
}
}));
}
void nano::rpc::stop ()
{
stopped = true;
acceptor.close ();
}
std::unique_ptr<nano::rpc> nano::get_rpc (boost::asio::io_context & io_ctx_a, nano::rpc_config const & config_a, nano::rpc_handler_interface & rpc_handler_interface_a)
{
std::unique_ptr<rpc> impl;
if (config_a.secure.enable)
{
#ifdef NANO_SECURE_RPC
impl = std::make_unique<rpc_secure> (io_ctx_a, config_a, rpc_handler_interface_a);
#else
std::cerr << "RPC configured for TLS, but the node is not compiled with TLS support" << std::endl;
#endif
}
else
{
impl = std::make_unique<rpc> (io_ctx_a, config_a, rpc_handler_interface_a);
}
return impl;
}
| [
"[email protected]"
] | |
d2edf4ba9987729f2bc4d0e86ef833c96a36b687 | 7beff965d7b0e6155d6d52b27d71c557421d5ada | /APG4b/ex11/a.cpp | e5f7c9675164f1efba610caf4053d46b186a1b68 | [] | no_license | uk-ar/competitive_programming | 82a53a1007798843ac006b9c7d313826e6cb45c3 | d2523cf303f47644cada3b03e9eed2349bdbe394 | refs/heads/master | 2023-03-28T13:20:07.728861 | 2021-03-30T20:25:55 | 2021-03-30T20:25:55 | 249,638,234 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 454 | cpp | //#include <bits/stdc++.h>
#include <iostream>
using namespace std;
int main() {
long long N,A;
cin >> N >> A;
for(int i=0; i<N; i++){
string op;
int B;
cin >> op >> B;
if(op=="+"){
A = A + B;
}else if(op=="-"){
A = A - B;
}else if(op=="*"){
A = A * B;
}else if(op=="/" && B!=0){
A = A / B;
}else{
cout << "error" << endl;
break;
}
cout << i+1 << ":" << A << endl;
}
}
| [
"[email protected]"
] | |
79ed4a345d9cbcc01db245e95794d627502e2023 | 091dc0ac8cd98d704ff40654051c8e0c146e3b0b | /숫자골라내기.cpp | 424501d9e3bf8abcde65382be334412df9448942 | [] | no_license | jangsohee/Algorithm | e2ff80fe49c8acd566c221e857b264df8948dffd | e57eebafc9169e7c0493b666a16b94da3e1f788e | refs/heads/master | 2020-06-28T20:37:25.264200 | 2016-11-22T13:21:46 | 2016-11-22T13:21:46 | 74,246,997 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 582 | cpp | #include <cstdio>
#include <iostream>
using namespace std;
int main() {
//int argc, char** argv ----------------------------------------------------------------1
//setbuf(stdout, NULL); ----------------------------------------------------------------2
int TC;
int test_case;
scanf("%d", &TC);
for (test_case = 1; test_case <= TC; test_case++) {
unsigned int res = 0;
int N;
scanf("%d", &N);
for (int i = 0; i < N; i++) {
unsigned int temp = 0;
scanf("%d", &temp);
res ^= temp;
}
printf("Case #%d\n", test_case);
cout << res << endl;
}
return 0;
} | [
"[email protected]"
] | |
2ad973534a3d3118330647065f709e4b1dc1a43d | 045e9fc1dee6242ac3e7c5efeb0ab6d5269ec8ae | /analysis/compareYield_all_combination.cpp | a70b04fed27dee1cd9821d73549e9e5bbcc23426 | [] | no_license | MT2Analysis/MT2Analysis2015 | 84dd1109d80d531a76a29279e2ca36167fa17975 | ea735c552f3d7c74cdb93747f95921652957ee44 | refs/heads/MT2Analysis2015_RandD | 2021-04-12T05:24:43.473832 | 2018-08-29T14:05:09 | 2018-08-29T14:05:09 | 24,103,357 | 0 | 2 | null | 2018-11-02T13:31:55 | 2014-09-16T14:38:48 | C++ | UTF-8 | C++ | false | false | 17,818 | cpp | #include "interface/MT2Analysis.h"
#include "interface/MT2EstimateSyst.h"
#include "interface/MT2EstimateTree.h"
#include "interface/MT2Estimate.h"
#include "interface/MT2DrawTools.h"
#include "interface/MT2Config.h"
#include <iostream>
#include <sstream>
#include <fstream>
#include <iomanip>
#include <string>
#include "TMath.h"
#include "TRandom3.h"
#include "TTreeFormula.h"
#include "TF1.h"
#include "TH1D.h"
#include "TH2D.h"
#include "THStack.h"
#include "TCanvas.h"
#include "TLegend.h"
#include "TPaveText.h"
#include "TLatex.h"
#include "TGraphAsymmErrors.h"
#include "RooHistError.h"
float lumi2015; //fb-1
float lumi2016; //fb-1
void drawYields( const std::string& outputdir, std::string dir2015, std::string dir2016 );
int main( int argc, char* argv[] ) {
std::cout << std::endl << std::endl;
std::cout << "------------------------------------------------------" << std::endl;
std::cout << "| |" << std::endl;
std::cout << "| |" << std::endl;
std::cout << "| Running computeLostLepton |" << std::endl;
std::cout << "| |" << std::endl;
std::cout << "| |" << std::endl;
std::cout << "------------------------------------------------------" << std::endl;
std::cout << std::endl << std::endl;
if( argc!=3 ) {
std::cout << "USAGE: ./computeLostLepton [configFileName]" << std::endl;
std::cout << "Exiting." << std::endl;
exit(11);
}
std::string configFileName2015(argv[1]);
MT2Config cfg2015(configFileName2015);
std::string configFileName2016(argv[2]);
MT2Config cfg2016(configFileName2016);
lumi2015 = cfg2015.lumi();
lumi2016 = cfg2016.lumi();
TH1::AddDirectory(kTRUE);
std::string dir2015 = cfg2015.getEventYieldDir();
std::string dir2016 = cfg2016.getEventYieldDir();
std::string outputdir = "./YieldComparison_dataMC_combination2015plus2016/";
drawYields( outputdir.c_str(), dir2015, dir2016 );
return 0;
}
void drawYields( const std::string& outputdir, std::string dir2015, std::string dir2016 ) {
MT2DrawTools::setStyle();
system(Form("mkdir -p %s", outputdir.c_str()));
std::vector<int> colors;
// colors.push_back( 402 );
// colors.push_back( 430 );
// colors.push_back( 418 );
colors.push_back( kYellow+1 );
colors.push_back( kAzure+4 );
colors.push_back( kGreen+2 );
unsigned int bgSize = 3;
TFile* file2015 = TFile::Open(Form("%s/YieldComparison_dataMC/histograms_ALL.root", dir2015.c_str()));
TFile* file2016 = TFile::Open(Form("%s/YieldComparison_dataMC/histograms_ALL.root", dir2016.c_str()));
TH1D* hdata2015 = (TH1D*) file2015->Get("hdata");
TH1D* hdata2016 = (TH1D*) file2016->Get("hdata");
TH1D* hdata = (TH1D*) hdata2015->Clone();
hdata->Add(hdata2016);
hdata->GetYaxis()->SetTitle("Entries");
hdata->SetMarkerStyle(20);
hdata->SetMarkerSize(1.6);
hdata->SetLineColor( 1 );
hdata->SetMarkerColor( 1 );
TH1D* hestimate_all2015 = (TH1D*) file2015->Get("hestimate_all");
TH1D* hestimate_all2016 = (TH1D*) file2016->Get("hestimate_all");
TH1D* hestimate_all = (TH1D*) hestimate_all2015->Clone();
hestimate_all->Add(hestimate_all2016);
TH1D* hestimate_all_forRatio2015 = (TH1D*) file2015->Get("hestimate_all_forRatio");
TH1D* hestimate_all_forRatio2016 = (TH1D*) file2016->Get("hestimate_all_forRatio");
TH1D* hestimate_all_forRatio = (TH1D*) hestimate_all_forRatio2015->Clone();
hestimate_all_forRatio->Add(hestimate_all_forRatio2016);
TH1D* hestimate[bgSize];
TH1D* hestimate2015[bgSize];
TH1D* hestimate2016[bgSize];
for(unsigned int b=0; b<bgSize; ++b){
hestimate2015[b] = (TH1D*) file2015->Get(Form("hestimate_%d", b));
hestimate2016[b] = (TH1D*) file2016->Get(Form("hestimate_%d", b));
hestimate[b] = (TH1D*) hestimate2015[b]->Clone();
hestimate[b]->Add(hestimate2016[b]);
hestimate[b]->GetYaxis()->SetTitle("Entries");
hestimate[b]->SetFillColor(colors[b]);
hestimate[b]->SetLineColor(1);
}
THStack bgStack("bgStack", "");
TH1D* hPull = new TH1D("hPull", "", 21, -5.25, 5.25);
hPull->Sumw2();
hPull->GetXaxis()->SetTitle("(Est._{H_{T}, N_{j}, N_{b}}^{pre-fit} - Data) / #sqrt{#sigma_{Est.}^{ 2} + #sigma_{Data}^{ 2}}");
hPull->GetYaxis()->SetTitle("Entries");
TH1D* hPvalue = new TH1D("hPvalue", "", 14, 0, 1.05);
hPvalue->Sumw2();
hPvalue->GetXaxis()->SetTitle("p-value");
hPvalue->GetYaxis()->SetTitle("Entries");
std::string fullPath = outputdir;
std::string labelsMono[12]={"[200,250]","[250,350]","[350,450]","[450,575]","[575,700]","[700,1000]",">1000", "[200,250]","[250,350]","[350,450]","[450,575]",">575"};
for(unsigned int b=0; b<bgSize; ++b){
bgStack.Add(hestimate[b]);
//bgStack.Add(hestimate_forRatio[b]);
}
for(int iBin=1; iBin<=hestimate_all->GetNbinsX(); ++iBin){
float thisData = hdata->GetBinContent(iBin);
float thisEst = hestimate_all->GetBinContent(iBin);
float thisEstErr = hestimate_all->GetBinError(iBin);
int obs = thisData;
float meanExp = thisEst;
float meanUnc = thisEstErr;
int N=100000;
TRandom3 randGen;
unsigned int counterN(0);
unsigned int counterD(0);
bool doLeft = obs<=meanExp;
for(int i=0; i<N; i++){
double meanShift = randGen.Gaus(0.,(double)meanUnc);
//cout << "meanShift: " << meanShift << endl;
double rand = randGen.Poisson(double(meanExp)+meanShift); counterD++;
if(doLeft)
{
if(rand<=obs) counterN++;
}
else{
if(rand>=obs) counterN++;
}
//cout << "rand " << i << " : " << rand.Poisson(meanExp) << endl;
}
double prob=1.0*counterN/counterD;
double significance = TMath::NormQuantile(1-prob);
// std::cout << "probability: " << prob << std::endl;
// std::cout << "significance: " << significance << std::endl;
//
// std::cout << "Bin: " << iBin << std::endl;
// std::cout << "Obs: " << obs << std::endl;
// std::cout << "exp: " << meanExp << "\t" << meanUnc << std::endl;
hPvalue->Fill(prob);
}
TGraphAsymmErrors* g_Ratio = MT2DrawTools::getRatioGraph(hdata, hestimate_all_forRatio, "binWidth");
g_Ratio->SetMarkerStyle(20);
g_Ratio->SetMarkerSize(1.6);
g_Ratio->SetMarkerColor( 1 );
g_Ratio->SetLineColor(1);
g_Ratio->GetXaxis()->SetLabelSize(0.00);
g_Ratio->GetXaxis()->SetTickLength(0.09);
g_Ratio->GetYaxis()->SetNdivisions(5,5,0);
g_Ratio->GetYaxis()->SetRangeUser(0.0,2.0);
g_Ratio->GetYaxis()->SetTitleSize(0.17);
g_Ratio->GetYaxis()->SetTitleOffset(0.4);
g_Ratio->GetYaxis()->SetLabelSize(0.17);
g_Ratio->GetYaxis()->SetTitle("Ratio");
TGraphAsymmErrors* g_Ratio_zero = new TGraphAsymmErrors(*(g_Ratio));
g_Ratio_zero->SetMarkerSize(0);
g_Ratio_zero->SetLineColor( 1 );
g_Ratio_zero->SetMarkerColor( 1 );
TGraphAsymmErrors* gdata = MT2DrawTools::getPoissonGraph(hdata, true, "binWidth");
gdata->GetYaxis()->SetTitle("Entries");
gdata->SetMarkerStyle(20);
gdata->SetMarkerSize(1.6);
gdata->SetLineColor( 1 );
gdata->SetMarkerColor( 1 );
TGraphAsymmErrors* gdata_zero = new TGraphAsymmErrors(*(gdata));
gdata_zero->SetMarkerSize(0);
gdata_zero->SetLineColor( 1 );
gdata_zero->SetMarkerColor( 1 );
for(int iBin=1; iBin<=hestimate_all->GetNbinsX(); ++iBin){
float thisData = hdata->GetBinContent(iBin);
float thisDataErr = gdata->GetErrorY(iBin-1);
std::cout << "TEST!" << std::endl;
std::cout << thisData << "\t" << gdata->GetY()[iBin-1] << "\t" << thisDataErr << std::endl;
float thisEst = hestimate_all->GetBinContent(iBin);
float thisEstErr = hestimate_all->GetBinError(iBin);
hPull->Fill( (thisEst-thisData)/( TMath::Sqrt( thisDataErr*thisDataErr + thisEstErr*thisEstErr ) ) );
}
TCanvas* c2 = new TCanvas("c2", "", 1100, 600);
c2->cd();
// c2->SetLeftMargin(0.);
std::string thisName = Form("%s_ratio", hdata->GetName());
TH1D* h_Ratio = (TH1D*) hdata->Clone(thisName.c_str());
h_Ratio->Divide(hestimate_all_forRatio);
//h_Ratio->Divide(hestimate_all);
h_Ratio->SetStats(0);
h_Ratio->SetMarkerStyle(20);
h_Ratio->SetLineColor(1);
h_Ratio->GetXaxis()->SetLabelSize(0.00);
h_Ratio->GetXaxis()->SetTickLength(0.09);
h_Ratio->GetYaxis()->SetNdivisions(5,5,0);
h_Ratio->GetYaxis()->SetRangeUser(0.0,2.0);
h_Ratio->GetYaxis()->SetTitleSize(0.17);
h_Ratio->GetYaxis()->SetTitleOffset(0.4);
h_Ratio->GetYaxis()->SetLabelSize(0.17);
h_Ratio->GetYaxis()->SetTitle("Ratio");
TPad *pad1 = new TPad("pad1","pad1",0,0.3-0.1,1,1);
pad1->SetBottomMargin(0.15);
pad1->Draw();
pad1->cd();
pad1->SetLogy();
float yMax_1 = hdata->GetMaximum()*1.5;
float yMax_2 = 1.2*(hdata->GetMaximum() + hdata->GetBinError(hestimate_all->GetMaximumBin()));
float yMax1 = (yMax_1>yMax_2) ? yMax_1 : yMax_2;
float yMax_3 = hestimate_all->GetMaximum()*1.5;
float yMax_4 = 1.2*(hestimate_all->GetMaximum() + hestimate_all->GetBinError(hestimate_all->GetMaximumBin()));
float yMax2 = (yMax_3>yMax_4) ? yMax_3 : yMax_4;
float yMax = (yMax1>yMax2) ? yMax1 : yMax2;
float yMin = 1e-3;
// yMin=0;
yMax*=20.;
int thisBin=67;
hestimate_all->GetXaxis()->SetRangeUser(0, thisBin);
hdata->GetXaxis()->SetRangeUser(0, thisBin);
gdata->GetXaxis()->SetRangeUser(0, thisBin);
hestimate_all->GetYaxis()->SetRangeUser(yMin, yMax);
hdata->GetYaxis()->SetRangeUser(yMin, yMax);
// hestimate_all->GetXaxis()->LabelsOption("v");
// hestimate_all->GetXaxis()->SetLabelSize(0.035);
hestimate_all->GetXaxis()->SetLabelSize(0.043);
hestimate_all->GetXaxis()->SetLabelFont(62);
hestimate_all->SetFillStyle(3244);
hestimate_all->SetFillColor(kGray+2);
// TGraphAsymmErrors* g_data = new TGraphAsymmErrors(0);
// for( int iBin=1; iBin<(hdata->GetXaxis()->GetNbins()+1); ++iBin ) {
//
// double y;
// double x, xerr;
//
// x = hdata->GetBinCenter(iBin);
// xerr = hdata->GetBinWidth(iBin)/2.;
//
// y = hdata->GetBinContent(iBin);
// double yerr = hdata->GetBinError(iBin);
//
// int thisPoint = g_data->GetN();
// g_data->SetPoint( thisPoint, x, y );
// g_data->SetPointError( thisPoint, xerr, xerr, yerr, yerr );
//
// }
hestimate_all->GetYaxis()->SetTitleOffset(0.95);
hestimate_all->GetYaxis()->SetLabelSize(0.042);
hestimate_all->Draw("");
bgStack.Draw("histo, same");
hestimate_all->Draw("E2,same");
// hdata->Draw("pe,same");
gdata_zero->Draw("pe,same");
gdata->Draw("pe,same");
TH1D* prefit=new TH1D("prefit", "", 1, 0, 1);
prefit->SetFillColor(0);
prefit->SetLineColor(0);
TLegend* legend = new TLegend( 0.8, 0.9-(bgSize+1-1)*0.06-0.06, 0.93, 0.9-0.06 );
legend->SetTextSize(0.038);
legend->SetTextFont(42);
legend->SetFillColor(0);
legend->AddEntry( hdata, "Data", "PL" );
// legend->AddEntry( prefit, "A-priori background", "F" );
legend->AddEntry( hestimate[0], "Multijet", "F");
legend->AddEntry( hestimate[1], "Lost lepton", "F");
legend->AddEntry( hestimate[2], "Z #rightarrow #nu#bar{#nu}", "F");
// TPaveText* labelTop = MT2DrawTools::getLabelTopSimulation(lumi);
TPaveText* labelTop = MT2DrawTools::getLabelTop(lumi2015,lumi2016);
labelTop->Draw("same");
TPaveText* labelCMS = MT2DrawTools::getLabelCMS();
labelCMS->Draw("same");
// TLine* lHT[5];
// for( int iHT=0; iHT < 5; iHT++ ){
// lHT[iHT-1] = new TLine(12+11*iHT, 0.0, 12+11*iHT, yMax );
// lHT[iHT-1]->SetLineColor(kBlack);
// lHT[iHT-1]->SetLineStyle(3);
// lHT[iHT-1]->SetLineWidth(2);
//
// lHT[iHT-1]->Draw("same");
// }
int nHTRegions = 6;
std::vector< std::string > htRegions;
htRegions.push_back("1 Jet");
//// htRegions.push_back("very low H_{T}");
//// htRegions.push_back("low H_{T}");
//// htRegions.push_back("medium H_{T}");
//// htRegions.push_back("high H_{T}");
//// htRegions.push_back("extreme H_{T}");
// htRegions.push_back("#it{H}_{T} [200,450] GeV");
// htRegions.push_back("#it{H}_{T} [450,575] GeV");
// htRegions.push_back("#it{H}_{T} [575,1000] GeV");
// htRegions.push_back("#it{H}_{T} [1000,1500] GeV");
// htRegions.push_back("#it{H}_{T} >1500 GeV");
htRegions.push_back("H_{T} [200,450] GeV");
htRegions.push_back("H_{T} [450,575] GeV");
htRegions.push_back("H_{T} [575,1000] GeV");
htRegions.push_back("H_{T} [1000,1500] GeV");
htRegions.push_back("H_{T} > 1500 GeV");
TPaveText* htBox[5];
for( int iHT = 0; iHT < nHTRegions; ++iHT){
if (iHT==0) htBox[iHT] = new TPaveText(0.12+0.15*iHT, 0.9-0.06+0.02, 0.34+0.15*iHT, 0.85+0.02, "brNDC");
else htBox[iHT] = new TPaveText(0.13+0.13*iHT, 0.9-0.06+0.02, 0.34+0.13*iHT, 0.85+0.02, "brNDC");
htBox[iHT]->AddText( htRegions[iHT].c_str() );
htBox[iHT]->SetBorderSize(0);
htBox[iHT]->SetFillColor(kWhite);
htBox[iHT]->SetTextSize(0.035);
htBox[iHT]->SetTextAlign(21); // align centered
htBox[iHT]->SetTextFont(62);
htBox[iHT]->Draw("same");
}
TLine* lHT[5];
for( int iHT=0; iHT < 5; iHT++ ){
lHT[iHT-1] = new TLine(12+11*iHT, 0.0, 12+11*iHT, yMax );
lHT[iHT-1]->SetLineColor(kBlack);
lHT[iHT-1]->SetLineStyle(3);
lHT[iHT-1]->SetLineWidth(2);
lHT[iHT-1]->Draw("same");
}
legend->Draw("same");
gPad->RedrawAxis();
c2->cd();
TPad *pad2 = new TPad("pad2","pad2",0,0,1,0.21);
pad2->SetTopMargin(0.05);
pad2->SetBottomMargin(0.1);
pad2->Draw();
pad2->cd();
bool doLogRatio = true;
TH2D* h2_axes_ratio;
if(doLogRatio){
gPad->SetLogy();
h2_axes_ratio = new TH2D("axes_ratio", "", 10, 0, thisBin, 10, 0.1, 10.0 );
h_Ratio->GetYaxis()->SetRangeUser(0.1, 10.0);
g_Ratio->GetYaxis()->SetRangeUser(0.1, 10.0);
}
else
h2_axes_ratio = new TH2D("axes_ratio", "", 10, 0, thisBin, 10, 0., 2.0 );
// TH2D* h2_axes_ratio = new TH2D("axes_ratio", "", 10, 0, thisBin, 10, 0., 3.0 );
h2_axes_ratio->SetStats(0);
h2_axes_ratio->GetXaxis()->SetLabelSize(0.00);
h2_axes_ratio->GetXaxis()->SetTickLength(0.09);
h2_axes_ratio->GetYaxis()->SetNdivisions(5,5,0);
h2_axes_ratio->GetYaxis()->SetTitleSize(0.18);
// h2_axes_ratio->GetYaxis()->SetTitleOffset(0.4);
h2_axes_ratio->GetYaxis()->SetTitleOffset(0.26);
h2_axes_ratio->GetYaxis()->SetLabelSize(0.17);
h2_axes_ratio->GetYaxis()->SetTitle("Data/Est.");
TLine* LineCentral = new TLine(0, 1.0, thisBin, 1.0);
LineCentral->SetLineColor(1);
std::string thisName_Band = Form("%s_band", hestimate_all->GetName());
TH1D* h_band = (TH1D*)hestimate_all->Clone(thisName_Band.c_str());
h_band->SetMarkerSize(0);
h_band->SetFillColor (kGray+2);
h_band->SetFillStyle (3244);
for ( int iBin=1; iBin <= hestimate_all->GetNbinsX(); iBin++){
h_band->SetBinContent(iBin,1);
double error=0;
if(hestimate_all->GetBinContent(iBin)>0)
error = hestimate_all->GetBinError(iBin)/hestimate_all->GetBinContent(iBin);
else error = hestimate_all->GetBinError(iBin);
h_band->SetBinError(iBin, error);
}
h2_axes_ratio->Draw("");
h_band->Draw("E2same");
LineCentral->Draw("same");
// h_Ratio->Draw("pe,same");
g_Ratio->Draw("pe,same");
TLine* lHT_b[6];
for( int iHT=1; iHT < 6; iHT++ ){
// lHT_b[iHT-1] = new TLine(12+11*(iHT-1), 0, 12+11*(iHT-1), 3.0 );
if(doLogRatio)
lHT_b[iHT-1] = new TLine(12+11*(iHT-1), 0.1, 12+11*(iHT-1), 10.0 );
else
lHT_b[iHT-1] = new TLine(12+11*(iHT-1), 0, 12+11*(iHT-1), 2.0 );
lHT_b[iHT-1]->SetLineColor(kBlack);
lHT_b[iHT-1]->SetLineStyle(3);
lHT_b[iHT-1]->SetLineWidth(2);
lHT_b[iHT-1]->Draw("same");
}
gPad->RedrawAxis();
c2->cd();
c2->SaveAs( Form("%s/mt2_ALL_fullEstimate.pdf", fullPath.c_str()) );
c2->SaveAs( Form("%s/mt2_ALL_fullEstimate.C", fullPath.c_str()) );
c2->SaveAs( Form("%s/mt2_ALL_fullEstimate.png", fullPath.c_str()) );
c2->SaveAs( Form("%s/mt2_ALL_fullEstimate.eps", fullPath.c_str()) );
// gStyle->SetOptStat(0110);
gStyle->SetOptFit(0011);
TF1* fgauss= new TF1("fgauss", "gaus", -5, 5);
fgauss->SetLineColor(2);
TCanvas* c3 = new TCanvas("c3", "", 600, 600);
c3->cd();
hPull->SetStats(1100);
// hPull->GetYaxis()->SetRangeUser(0, 15);
hPull->Draw("hist");
hPull->Fit("fgauss");
fgauss->Draw("same");
labelTop = MT2DrawTools::getLabelTop(lumi2015,lumi2016);
labelTop->Draw("same");
labelCMS = MT2DrawTools::getLabelCMS("CMS Supplementary");
labelCMS->Draw("same");
TPaveText *arxiv = new TPaveText(0.2, 0.9-0.05, 0.35, 0.9, "brNDC");
arxiv->AddText( "arXiv:1603.04053" );
arxiv->SetBorderSize(0);
arxiv->SetFillColor(kWhite);
// arxiv->SetTextSize(0.035);
arxiv->SetTextAlign(11); // align centered
arxiv->SetTextFont(42);
arxiv->Draw("same");
c3->SaveAs( Form("%s/PullDistribution.pdf", fullPath.c_str()) );
c3->SaveAs( Form("%s/PullDistribution.png", fullPath.c_str()) );
c3->SaveAs( Form("%s/PullDistribution.root", fullPath.c_str()) );
TCanvas* c4 = new TCanvas("c4", "", 600, 600);
c4->cd();
hPvalue->SetStats(1110);
hPvalue->Draw("hist");
c4->SaveAs( Form("%s/PvalueDistribution.pdf", fullPath.c_str()) );
c4->SaveAs( Form("%s/PvalueDistribution.png", fullPath.c_str()) );
}
| [
"[email protected]"
] |
Subsets and Splits