blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
71cfccb641c9c4184c568afd4002efe4821f81fa | 009ccffec019a4d28de22fc4d43c55861218e40b | /src/QTSmartsIntPickDialog.H | 74e121f7af1302755619f3f16729adb841789958 | [
"BSD-3-Clause"
] | permissive | OpenEye-Contrib/SmiV | 8a9728b62919f5993a8cfb35b57922451a21c459 | 784f2a66a8dfb6e986cbb21af23504ecdd4b975e | refs/heads/master | 2021-01-10T15:55:47.180398 | 2017-01-25T17:45:52 | 2017-01-25T17:45:52 | 51,924,908 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,138 | h | //
// file QTSmartsIntPickDialog.H
// Dave Cosgrove
// AstraZeneca
// 12th January 2010
//
// This class derives from QTSmartsEditDialog, and takes adds a QTMolDisplay2D
// from which the user can pick atoms to define the SMARTS.
#ifndef DAC_QT_SMARTS_INT_PICK_DIALOG
#define DAC_QT_SMARTS_INT_PICK_DIALOG
#include "QTSmartsEditDialog.H"
#include <string>
#include <boost/scoped_ptr.hpp>
#include <oechem.h>
class QString;
// ****************************************************************************
class QTSmartsIntPickDialog : public QTSmartsEditDialog {
Q_OBJECT
public :
QTSmartsIntPickDialog( const std::string &smi , bool with_name_input = true ,
QWidget *parent = 0 , Qt::WindowFlags f = 0 );
public slots :
void slot_int_pick_atom_selected();
void slot_select_mol_disp_atoms();
private :
DACLIB::QTMolDisplay2D *int_pick_disp_;
boost::scoped_ptr<OEChem::OEMolBase> disp_mol_;
void add_int_pick_display( const std::string &smi );
QString build_smarts_from_disp_mol_sel_atoms( std::vector<OEChem::OEAtomBase *> &sel_atoms );
};
#endif // DAC_QT_SMARTS_INT_PICK_DIALOG
| [
"davidacosgroveaz@gmail.com"
] | davidacosgroveaz@gmail.com |
4cccf2014a975b743be7504b914e438e48fbe1ab | 818df5a6b667055f9c472e72ee0fc823f86de819 | /11483.cpp | 9da9fd5d45164c921e575638a68cdfa2598600bc | [] | no_license | kalex1994/UVA | 0a495e971fdcf92a785421a5c741bda915c21fca | cf45c6174cd299df14e8b52637c29ea7c3ec0f20 | refs/heads/master | 2021-01-01T19:47:13.630295 | 2016-10-15T19:14:46 | 2016-10-15T19:14:46 | 12,342,624 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,120 | cpp | #include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
#include <limits>
#include <climits>
#include <cctype>
#include <stack>
#include <cstdio>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <set>
#include <queue>
#include <numeric>
#include <deque>
#include <map>
#include <iterator>
#include <cassert>
#include <list>
#include <functional>
#include <bitset>
#include <array>
#include <regex>
using namespace std;
int main()
{
#ifndef ONLINE_JUDGE
freopen("E:\\IN.txt", "r", stdin);
freopen("E:\\OUT.txt", "w", stdout);
#endif
int n, ch, c = 1;
string line;
while(cin >> n && n)
{
cin.ignore(100, '\n');
cout << "Case " << c++ << ":" << endl;
cout << "#include<string.h>" << endl << "#include<stdio.h>" << endl << "int main()" << endl << "{" << endl;
while(n--)
{
cout << "printf(\"";
getline(cin, line);
for(char ch : line)
{
if (ch == '\\' || ch == '"')
cout << '\\';
cout << ch;
}
cout << "\\n\");\n";
}
cout << "printf(\"\\n\");" << endl << "return 0;" << endl << "}" << endl;
}
} | [
"kiralaleks@gmail.com"
] | kiralaleks@gmail.com |
e66999ad0f28b4f57962d5212566eee600a7f8df | 02e07149af0dff9796c2cc8af56a0730d5f4861f | /src/Workspace/include/Workspace/EventFilter.h | 9166e168cc06aa1aba0a8c0b251a997027edb31a | [
"BSD-3-Clause"
] | permissive | loganek/gstcreator | b5817acc271b00d52aaed491f96ab1b03a03ea92 | 619f1a6f1ee39c7c5b883c0a676cd490f59ac81b | refs/heads/master | 2021-01-10T22:14:08.257537 | 2014-07-31T18:14:40 | 2014-07-31T18:14:45 | 15,843,428 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,016 | h | /*
* gstcreator
* EventFilter.h
*
* Created on: 28 sty 2014
* Author: Marcin Kolny <marcin.kolny@gmail.com>
*/
#ifndef EVENTFILTER_H_
#define EVENTFILTER_H_
#include "qnelibrary.h"
#include <QObject>
#include <QEvent>
#include <QMimeData>
#include <QPointF>
#include <gstreamermm.h>
class WorkspaceWidget;
class EventFilter : public QObject
{
Q_OBJECT
private:
Glib::RefPtr<Gst::Element> model;
QNEConnection* current_connection;
QPointF previous_pos;
WorkspaceWidget* workspace;
static bool check_mime_data(const QMimeData* mime_data);
bool drop_block(QEvent* e);
bool mouse_press_handler(QEvent* e);
QString get_new_name(const QString& name) const;
QGraphicsScene* get_scene() const;
QGraphicsItem* item_at_position(const QPointF &pos) const;
public:
EventFilter(QGraphicsScene* parent, WorkspaceWidget* workspace);
bool eventFilter(QObject *o, QEvent *e);
void set_model(const Glib::RefPtr<Gst::Bin>& model);
QPointF get_previous_pos() const;
};
#endif /* EVENTFILTER_H_ */
| [
"marcin.kolny@gmail.com"
] | marcin.kolny@gmail.com |
e38a653991cd241b6ae15e8f8dc3707b6e932a22 | f1e44c6028890e2403c74bfd891d971100b864c8 | /week_02_22-Sep-2019/lab_assessment_–_object_manipulation/2/Sale.h | 1ff7e9468d3731123e5100025e294d238e439fa0 | [
"MIT"
] | permissive | tengkuaon/UTMSPACE_2019-2020-sem1_SCSJ1023_Programming_Techniques_II | d0124a9899de1bb9ca1c63f766f54993b34bba78 | b884f47ff714ddc297d2236235f1deb34be5dd53 | refs/heads/master | 2020-08-06T22:34:12.157242 | 2019-10-06T09:33:13 | 2019-10-06T09:33:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 624 | h | #ifndef SALE_H
#define SALE_H
class Sale
{
private:
double itemCost;
double disRate;
public:
Sale (double cost, double discount = 0.05)
{
itemCost = cost;
disRate = discount;
}
double getItemCost () const
{
return itemCost;
}
double getDisRate () const
{
return disRate;
}
double getDis () const
{
return (itemCost * disRate);
}
double getTotal () const
{
return (itemCost - getDis());
}
};
#endif | [
"oneseedfruit@gmail.com"
] | oneseedfruit@gmail.com |
74ec8863699d3607aa9dbdaa3258bda3f75ac420 | e72a48ffff811f4a73b12ead24dfebc961b9e13e | /plugins/viennagrid/uniform_refine.cpp | b0b6baed519cc9c24fb8fb1861c0b6326926e62a | [] | no_license | In-Ki-Kim/viennamesh-dev | 354f5fb49a36e43d9ca441c06c929db1ca80d7ff | 6fe645b36557275dc23ac83256dbe6c283a9e312 | refs/heads/master | 2022-04-08T12:46:59.654293 | 2020-03-10T11:41:31 | 2020-03-10T11:41:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,286 | cpp | /* ============================================================================
Copyright (c) 2011-2014, Institute for Microelectronics,
Institute for Analysis and Scientific Computing,
TU Wien.
-----------------
ViennaMesh - The Vienna Meshing Framework
-----------------
http://viennamesh.sourceforge.net/
License: MIT (X11), see file LICENSE in the base directory
=============================================================================== */
#include "uniform_refine.hpp"
#include "viennagrid/viennagrid.hpp"
#include "viennagrid/algorithm/refine.hpp"
namespace viennamesh
{
uniform_refine::uniform_refine() {}
std::string uniform_refine::name() { return "uniform_refine"; }
bool uniform_refine::run(viennamesh::algorithm_handle &)
{
mesh_handle input_mesh = get_required_input<mesh_handle>("mesh");
if (!input_mesh.valid())
return false;
mesh_handle output_mesh = make_data<mesh_handle>();
if (output_mesh == input_mesh)
return false;
viennagrid::cell_refine_uniformly(input_mesh(), output_mesh());
set_output( "mesh", output_mesh );
return true;
}
}
| [
"rudolf@iue.tuwien.ac.at"
] | rudolf@iue.tuwien.ac.at |
05c8934d46147ab14e2756b501b28871e0e85f3d | 2d1f82fe5c4818ef1da82d911d0ed81a0b41ec85 | /codeforces/gym/NEERC 2017/CF101630J.cpp | eb07460cb869abedabfc374d8a1387876cfdeedf | [] | no_license | OrigenesZhang/-1s | d12bad12dee37d4bb168647d7b888e2e198e8e56 | 08a88e4bb84b67a44eead1b034a42f5338aad592 | refs/heads/master | 2020-12-31T00:43:17.972520 | 2020-12-23T14:56:38 | 2020-12-23T14:56:38 | 80,637,191 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,647 | cpp | #include <iostream>
#include <cstring>
#include <vector>
#include <queue>
#define pb push_back
using namespace std;
typedef long long LL;
typedef pair<int, int> pii;
const int N = 3000 + 10;
const LL INF = LL(1e15);
vector<pii> G[N], G2[N];
vector<int> val;
int n, m, k;
LL d[N];
struct Node {
int u;
LL d;
bool operator < (const Node& rhs) const {
return d > rhs.d;
}
};
LL Dijkstra() {
for (int i = 2; i <= n; i++) d[i] = INF;
priority_queue<Node> pq;
pq.push({ 1, 0 });
while (!pq.empty()) {
Node u = pq.top(); pq.pop();
if (d[u.u] < u.d) continue;
for (int i = 0; i < G[u.u].size(); i++) {
int v = G[u.u][i].first, w = G[u.u][i].second;
if (u.d + w < d[v]) {
d[v] = u.d + w;
pq.push({ v, d[v] });
}
}
}
return d[n];
}
LL deal(int val) {
for (int i = 1; i <= n; i++)
for (int j = 0; j < G[i].size(); j++) G[i][j].second = max(0, G[i][j].second - val);
LL ret = Dijkstra() + (LL)val * k;
for (int i = 1; i <= n; i++) G[i] = G2[i];
return ret;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cin >> n >> m >> k;
for (int i = 0; i < m; i++) {
int u, v, w;
cin >> u >> v >> w;
G[u].pb({ v, w });
G[v].pb({ u, w });
G2[u].pb({ v, w });
G2[v].pb({ u, w });
val.pb(w);
}
LL minm = Dijkstra();
for (int i = 0; i < m; i++) minm = min(minm, deal(val[i]));
cout << minm << '\n';
return 0;
} | [
"noreply@github.com"
] | noreply@github.com |
a7511b30fbb395606c734d4039870b70e3b70ff0 | 9c73501c5a8413753ed5776299fe1f62a0a2659e | /include/DREAM/Equations/Kinetic/SynchrotronTerm.hpp | 43886c05798f9e164b99617b8f879f2852983ad6 | [
"MIT"
] | permissive | anymodel/DREAM-1 | 5d1ac63ffc48157f110ef672036d801442a2c917 | eba9fabddfa4ef439737807ef30978a52ab55afb | refs/heads/master | 2023-08-23T05:01:13.867792 | 2021-10-28T19:45:33 | 2021-10-28T19:45:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,062 | hpp | #ifndef _DREAM_EQUATIONS_KINETIC_SYNCHROTRON_TERM_HPP
#define _DREAM_EQUATIONS_KINETIC_SYNCHROTRON_TERM_HPP
#include "DREAM/EquationSystem.hpp"
#include "DREAM/Settings/OptionConstants.hpp"
#include "DREAM/Equations/CollisionQuantityHandler.hpp"
#include "FVM/config.h"
#include "FVM/Equation/AdvectionTerm.hpp"
#include "FVM/Grid/Grid.hpp"
#include "FVM/UnknownQuantityHandler.hpp"
namespace DREAM {
class SynchrotronTerm
: public FVM::AdvectionTerm {
private:
enum OptionConstants::momentumgrid_type gridtype;
const real_t constPrefactor = Constants::ec * Constants::ec * Constants::ec * Constants::ec / (
6*M_PI * Constants::eps0 * Constants::me * Constants::me * Constants::me *
Constants::c * Constants::c * Constants::c);
public:
SynchrotronTerm(FVM::Grid*, enum OptionConstants::momentumgrid_type);
virtual void Rebuild(const real_t, const real_t, FVM::UnknownQuantityHandler*) override;
};
}
#endif/*_DREAM_EQUATIONS_KINETIC_SYNCHROTRON_TERM_HPP*/
| [
"embreus@chalmers.se"
] | embreus@chalmers.se |
1e946941fb546cac7d35588f7739557c3e8acedb | 5f61021d5d46053ce7770e69f4d178769f7fa58a | /DboClient/Lib/NtlPresentation/NtlPLCharacter.cpp | 6465c56c712aac25030700849d71525863522186 | [] | no_license | Guardian820/DragonBallOnline | ce2f64a2b88d98f25e747191fde75d7e8a6c12f7 | 201c28d8067fe0ddfde9da49c76516de82c394bf | refs/heads/master | 2020-03-10T01:13:50.855049 | 2017-07-31T08:54:08 | 2017-07-31T08:54:08 | null | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 80,999 | cpp | #include "precomp_ntlpresentation.h"
#include "NtlAtomic.h"
#include "NtlTimer.h"
#include "NtlPLEntityFreeList.h"
#include "NtlPLResourceManager.h"
#include "NtlPLProperty.h"
#include "NtlWorldInterface.h"
#include "NtlPLCharacterParser.h"
#include "NtlPLPropertyContainer.h"
#include "NtlPLEventGenerator.h"
#include "NtlPLSceneManager.h"
#include "NtlInstanceEffect.h"
#include "NtlPLMaterialExtWrapper.h"
#include "NtlSoundMessage.h"
#include "NtlSoundManager.h"
#include "NtlPLEntityBlend.h"
#include "NtlPLRenderState.h"
#include "NtlPLHelpers.h"
#include "NtlPLCharMeshRenderPipe.h"
#include "NtlPLCharMeshRenderPipe00.h"
#include "NtlPLCharMeshRenderPipe01.h"
#include "NtlPLCharMeshRenderPipeFarAway.h"
#include "ntlworlddi.h"
#include "NtlProfiler.h"
#include "NtlPLOccluder_Base.h"
#include "NtlPLCullingScheduling.h"
#include "NtlPLCharacter.h"
RwBool CNtlPLCharacter::m_SkipAnimUpdate = TRUE;
RwBool CNtlPLCharacter::m_SkipSimpleMaterial = TRUE;
RwBool CNtlPLCharacter::m_SkipAdge = FALSE;
void* CNtlPLCharacter::operator new(size_t size)
{
NTL_FUNCTION("CNtlPLCharacter::operator new");
NTL_RETURN(CNtlPLEntityFreeList::Alloc(PLENTITY_CHARACTER));
}
void CNtlPLCharacter::operator delete(void *pObj)
{
CNtlPLEntityFreeList::Free(PLENTITY_CHARACTER, pObj);
}
CNtlPLCharacter::CNtlPLCharacter() : m_pProperty(NULL),
m_pResourceClump(NULL),
m_bAnimUpdate(FALSE),
m_pBaseHierarchy(NULL),
m_fAnimSpeed(1.f),
m_pEquipItem(NULL),
m_bRunTimeAlpha(FALSE),
m_SkipAnimUpdateTime(0.0f),
m_SkipAnimUpdateElapsedTime(0.0f),
m_SimpleMaterial(FALSE),
m_PetrifySkillActivated(FALSE)
{
SetLayer(PLENTITY_LAYER_RWWORLD);
SetClassType(PLENTITY_CHARACTER);
SetFlags(NTL_PLEFLAG_ATTACH | NTL_PLEFLAG_PICKING);
m_vCurPos.x = 0.f;
m_vCurPos.y = 0.f;
m_vCurPos.z = 0.f;
m_vScale.x = 1.f;
m_vScale.y = 1.f;
m_vScale.z = 1.f;
m_vAngle.x = 0.f;
m_vAngle.y = 0.f;
m_vAngle.z = 0.f;
m_sSkinColor.red = 255;
m_sSkinColor.green = 255;
m_sSkinColor.blue = 255;
m_sSkinColor.alpha = 255;
m_sHeadColor.red = 255;
m_sHeadColor.green = 255;
m_sHeadColor.blue = 255;
m_sHeadColor.alpha = 255;
m_sColor.red = 255;
m_sColor.green = 255;
m_sColor.blue = 255;
m_sColor.alpha = 255;
m_sAddColor.red = 0;
m_sAddColor.green = 0;
m_sAddColor.blue = 0;
m_sAddColor.alpha = 255;
m_sInkColor.red = 0;
m_sInkColor.green = 0;
m_sInkColor.blue = 0;
m_sInkColor.alpha = 255;
m_fFastMaxExtent = 1.0f;
m_vBoneStretchTargetPos = ZeroAxis;
ZeroMemory(m_szBoneStretchAxisBone, sizeof(m_szBoneStretchAxisBone));
m_vecAtomicList.reserve(10);
m_ToonEdgeVisibility = TRUE;
m_pSEMTex = NULL;
#ifndef dNTL_WORLD_CULLING_NEW
GetNtlPLCullingScheduler()->AddCulling(this);
#endif
}
CNtlPLCharacter::~CNtlPLCharacter()
{
#ifndef dNTL_WORLD_CULLING_NEW
GetNtlPLCullingScheduler()->RemoveCulling(GetClassType(), this);
#endif
if(m_sScheduleResInfo.bPCFlag && (m_sScheduleResInfo.uiRace == RACE_NAMEK || m_sScheduleResInfo.uiRace == RACE_MAJIN))
{
NTL_DELETE(m_pTypeBoneData);
}
}
RwBool CNtlPLCharacter::SetProperty(const CNtlPLProperty *pData)
{
return SetThreadSafeProperty(pData);
}
/**
* Character 생성시 호출이 된다.
* \param pParam Character 생성시 필요한(Head, Hair, SkinColor, HairColor값을 받아야 한다. Pc, Mob, Npc에 대한 구분도)
* \return 실패 유무
*/
RwBool CNtlPLCharacter::Create(const SPLEntityCreateParam *pParam)
{
NTL_ASSERTE(CNtlPLGlobal::m_pRpWorld);
if(CNtlPLGlobal::m_pRpWorld == NULL)
return TRUE;
m_pEquipItem = NTL_NEW CNtlPLEquipItem;
m_pEquipItem->SetOwner(this);
if(pParam)
{
SPLCharacterCreateParam *pCharParam = (SPLCharacterCreateParam *)pParam;
SetSerialID(pCharParam->uiSerialId);
m_sScheduleResInfo.bPCFlag = pCharParam->bPcFlag;
m_sScheduleResInfo.uiClass = pCharParam->uiClass;
m_sScheduleResInfo.uiRace = pCharParam->uiRace;
m_sScheduleResInfo.uiGender = pCharParam->uiGender;
m_sScheduleResInfo.uiHeadType = pCharParam->uiHeadType;
m_sScheduleResInfo.uiFaceType = pCharParam->uiFaceType;
m_sScheduleResInfo.uiSkinColorType = pCharParam->uiSkinColorType;
m_sScheduleResInfo.uiHeadColorType = pCharParam->uiHeadColorType;
m_sScheduleResInfo.uiSerialId = pCharParam->uiSerialId;
m_sScheduleResInfo.bNotShadingFlag = pCharParam->bNotShadingFlag;
m_sScheduleResInfo.bIsAdult = pCharParam->bIsAdult;
if( GetCharScheduleResInfo()->bPCFlag )
{
m_pEquipItem->Create( m_sScheduleResInfo.uiClass,
m_sScheduleResInfo.uiRace,
m_sScheduleResInfo.uiGender,
m_sScheduleResInfo.uiHeadType,
m_sScheduleResInfo.uiFaceType,
m_sScheduleResInfo.uiSkinColorType,
m_sScheduleResInfo.uiHeadColorType,
m_sScheduleResInfo.bIsAdult);
}
}
// 나메크는 본이 늘어나는 스킬이 있다. Bone의 정보를 공유해버리면 다른 나메크들도 본이 늘어나 버린다.
// 그래서 나메크만은 Bone을 공유하지 않고, 따로 복사해서 가지고 있는다. (by agebreak 2008.10.21)
if(pParam && m_sScheduleResInfo.bPCFlag && (m_sScheduleResInfo.uiRace == RACE_NAMEK || m_sScheduleResInfo.uiRace == RACE_MAJIN))
{
m_pTypeBoneData = NTL_NEW STypeBoneData();
memcpy(m_pTypeBoneData, m_pProperty->GetBoneScaleData(), sizeof(STypeBoneData));
}
else
{
m_pTypeBoneData = m_pProperty->GetBoneScaleData();
}
if(!CreateScheduling(pParam))
return FALSE;
return TRUE;
}
void CNtlPLCharacter::CallSchedulingResource(CNtlPLResource *pResource)
{
m_pResourceClump = pResource;
NTL_ASSERTE(m_pResourceClump);
if( m_pResourceClump == NULL )
return;
CreateThreadSafe();
}
RwBool CNtlPLCharacter::CreateThreadSafe(void)
{
NTL_ASSERTE( m_pResourceClump );
m_pBaseHierarchy = Helper_GetHierarchyClump(m_pResourceClump->GetClump());
NTL_ASSERTE(m_pBaseHierarchy);
if(m_pBaseHierarchy == NULL)
return FALSE;
// PC일 경우는 Atomic을 모두 제거 한다.
if( GetCharScheduleResInfo()->bPCFlag )
{
Helper_DestroyAllAtomics(&m_vecAtomicList);
Helper_RemoveClumpAllAtomics(m_pResourceClump->GetClump());
}
NTL_ASSERTE(m_pProperty);
m_InstanceAnimTable.Create(m_pProperty->GetAnimTable());
if( m_sScheduleResInfo.uiAnimKey == NML_IDLE_LOOP )
m_sScheduleResInfo.bAnimLoop = TRUE;
if(!CreateAnim(m_sScheduleResInfo.uiAnimKey, m_sScheduleResInfo.fAnimElapsedTime, m_sScheduleResInfo.bAnimLoop))
return FALSE;
if(GetCharScheduleResInfo()->bNotShadingFlag)
//CreateToonData("smooth_white.png", "texture/toon/");
CreateToonData("smooth.png", "texture/toon/");
else
CreateToonData("smooth.png", "texture/toon/");
Helper_SetToonClump(m_pResourceClump->GetClump(), &m_ToonData);
Helper_GetBoneList(m_pResourceClump->GetClump(), &m_mapFrame);
m_AnimLayer[CHARACTER_ANIM_LAYER_BASE].SetCallBack(this, &CNtlPLCharacter::CallBackBaseAnim);
m_nBoneCount = m_pBaseHierarchy->numNodes;
if( GetCharScheduleResInfo()->bPCFlag)
RpNtlClumpSetData( m_pResourceClump->GetClump(), this);
else
{
Helper_SetClumpAllAtomics( m_pResourceClump->GetClump(), &m_vecAtomicList);
for(RwUInt32 i = 0; i < m_vecAtomicList.size(); i++)
{
RpAtomic *pAtomic = m_vecAtomicList[i]->pData;
RpNtlAtomicSetRenderCallBack( pAtomic, RpAtomicGetRenderCallBack(pAtomic) );
RpAtomicSetRenderCallBack(pAtomic, CNtlPLCharacter::RenderCallBack);
RpNtlAtomicSetData(pAtomic, this);
}
// NPC, MOB, VEHICLE spherical enviroment mapping
RwUInt16 EnvTexName = 0;
for(RwUInt32 i = 0; i < m_vecAtomicList.size(); i++)
{
EnvTexName = RpNtlAtomicGetEnvTexName(m_vecAtomicList[i]->pData);
if(EnvTexName)
break;
}
if(EnvTexName)
{
char szTmp[32] = {0,};
_itoa_s(EnvTexName, szTmp, 10);
m_pSEMTex = GetNtlResourceManager()->LoadTexture(szTmp, ".\\Texture\\EnvMap\\");
}
}
m_sScheduleResInfo.bLoadComplete = TRUE;
// Link Effect를 설정한다.(loadComplete가 설정된 후여야 한다.)
for(UINT i = 0; i < m_pProperty->m_vLinkEffect.size(); ++i)
{
SEventLinkEffect* pEventLinkEffect = m_pProperty->m_vLinkEffect[i];
m_LinkEffectInstance.AttachLinkEffect(this, pEventLinkEffect);
}
SetAnimUpdate(TRUE);
SetPosition(&m_vCurPos);
SetAngleY(m_vAngle.y);
SetScale(m_vScale.x);
SetColor(m_sColor.red, m_sColor.green, m_sColor.blue);
SetAlpha(m_sColor.alpha);
SetWeightAlpha( GetWeightAlpha() );
SetSerialID( GetCharScheduleResInfo()->uiSerialId);
SetVisible( GetCharScheduleResInfo()->bVisible );
SetBaseAnimation( m_sScheduleResInfo.uiAnimKey, m_sScheduleResInfo.fAnimElapsedTime, m_sScheduleResInfo.bAnimLoop );
CreateOccluderProxy();
AddWorld();
return TRUE;
}
RwBool CNtlPLCharacter::CreateOccluderProxy()
{
#ifdef dNTL_WORLD_CULLING_NEW
return COccluderProxy::CreateOccluderProxy(0.5f, m_vecAtomicList.size() + 1);
#else
return COccluderProxy::CreateOccluderProxy(0.5f, m_vecAtomicList.size());
#endif
}
RwBool CNtlPLCharacter::SetThreadSafeProperty(const CNtlPLProperty *pData)
{
NTL_ASSERTE( pData );
if(pData == NULL)
return FALSE;
m_pProperty = (CNtlPLCharacterProperty *)pData;
return TRUE;
}
RwBool CNtlPLCharacter::CreateScheduling(const SPLEntityCreateParam * pParam)
{
NTL_ASSERT( pParam != NULL, RWSTRING( "NULL Param" ) );
if( pParam == NULL)
return FALSE;
std::string strClumpFileName = m_pProperty->GetBaseMeshFilePath();
strClumpFileName += m_pProperty->GetBaseMeshFileName();
std::string strTexPath = "Texture\\character\\;";
strTexPath += "Texture\\item\\";
CNtlPLResourceManager::GetInstance()->LoadSchedulingClump( strClumpFileName.c_str(), strTexPath.c_str(), this );
return TRUE;
}
RwReal CNtlPLCharacter::GetMaxExtent()
{
RwReal fWidth = GetWidth();
RwReal fHeight = GetHeight();
RwReal fDepth = GetDepth();
if(fWidth > fHeight && fWidth > fDepth)
{
return GetWidth();
}
if(fHeight > fWidth && fHeight > fDepth)
{
return GetHeight();
}
if(fDepth > fHeight && fDepth > fWidth)
{
return fDepth;
}
return fWidth;
}
RwReal CNtlPLCharacter::GetFastMaxExtent()
{
return m_fFastMaxExtent;
}
void CNtlPLCharacter::SetSkipAnimUpdate(RwBool _Skip/* = TRUE*/)
{
m_SkipAnimUpdate = _Skip;
}
void CNtlPLCharacter::SetSkipSimpleMaterial(RwBool _Skip/* = TRUE*/)
{
m_SkipSimpleMaterial = _Skip;
}
RwBool CNtlPLCharacter::GetSkipSimpleMaterial(void)
{
return m_SkipSimpleMaterial;
}
void CNtlPLCharacter::SetSkipEdge(RwBool _Skip /*= FALSE*/)
{
m_SkipAdge = _Skip;
}
RwBool CNtlPLCharacter::GetSkipEdge(void)
{
return m_SkipAdge;
}
RwBool CNtlPLCharacter::Update(float fElapsed)
{
if ( 0.f == fElapsed )
{
return TRUE;
}
/*
static RwBool woody = FALSE;
if(dOKEY(DIK_I))
{
woody = !woody;
SetPetrifyMaterial(woody);
SetAnimUpdate(!woody);
}
*/
m_fFastMaxExtent = GetMaxExtent();
RwBool bVisible = IsVisible();
// 보이지 않으면 업데이트 하지 않는다. (맵툴 전용)
if( !bVisible && CNtlPLGlobal::m_bCharacterUpdateVisible)
return TRUE;
if( GetCharScheduleResInfo()->bLoadComplete)
{
if(!bVisible)
{
m_SkipAnimUpdateElapsedTime += fElapsed;
m_SkipAnimUpdateTime = CNtlTimer::AdjustBestFpsToSec();
if(m_SkipAnimUpdateElapsedTime < m_SkipAnimUpdateTime)
return TRUE;
fElapsed = m_SkipAnimUpdateElapsedTime;
}
if(m_pEquipItem)
{
m_pEquipItem->Update(fElapsed);
}
// get the distance from a camera to me
RwV3d vPos = GetPosition();
RwMatrix* pMatrix = RwFrameGetMatrix(RwCameraGetFrame(CNtlPLGlobal::m_RwCamera));
RwV3d vDelta;
RwV3dSub(&vDelta, RwMatrixGetPos(pMatrix), &vPos);
RwReal fLen = RwV3dLength(&vDelta);
RwReal MaxExtent = GetFastMaxExtent();
RwBool CharException = GetFlags() & NTL_PLEFLAG_DUMMY;
// simplify material when the distance is far enough away
if(fLen > 70.0f && MaxExtent < 4.0f && !CharException)
{
SetSimpleMaterial(TRUE);
}
else
{
SetSimpleMaterial(FALSE);
}
if(m_SkipAnimUpdate)
{
// Guard band clip test
/*
RwSphere sphere;
sphere.center = vPos;
sphere.radius = GetFastMaxExtent() * 0.5f;
sphere.center.y += (GetHeight() * 0.5f);
// Big entities exceptions; dinosaurs
RwFrustumTestResult ret = RwCameraFrustumTestSphere(CNtlPLGlobal::m_RwCamera, &sphere);
*/
if(/*ret == rwSPHEREOUTSIDE ||*/m_uiCullFlags)
{
// one second delay 4 invisible chars
m_SkipAnimUpdateTime = 1.0f;
}
else
{
// 4 meters diameter 4 the big entities
if(MaxExtent > 4.0f)
{
// 200 meters 4 distance visibility
// 0.1 sec 4 big entities
m_SkipAnimUpdateTime = fLen * 0.1f / 200.0f;
}
else
{
// 0.2 sec 4 the entities smaller than the big ones
m_SkipAnimUpdateTime = fLen * 0.2f / 200.0f;
}
}
// GUI characters exceptions
if(CharException)
{
m_SkipAnimUpdateTime = 0.001f;
}
}
else
{
m_SkipAnimUpdateTime = 0.001f;
}
m_SkipAnimUpdateElapsedTime += fElapsed;
if(m_SkipAnimUpdateElapsedTime > m_SkipAnimUpdateTime)
{
if(m_bAnimUpdate)
{
float fFinalAnimSpeed = 0.f;
if(m_pProperty != NULL)
{
if(m_sBaseAnimPlayInfo.m_uiAnimKey == RUN_FRONT )
fFinalAnimSpeed = m_fAnimSpeed * m_pProperty->GetInitRunFrontAnimSpeed();
else if(m_sBaseAnimPlayInfo.m_uiAnimKey == WALK_FRONT )
fFinalAnimSpeed = m_fAnimSpeed * m_pProperty->GetInitWalkFrontAnimSpeed();
else
fFinalAnimSpeed = m_fAnimSpeed;
}
else
fFinalAnimSpeed = m_fAnimSpeed;
m_AnimLayer[CHARACTER_ANIM_LAYER_BASE].Update(m_SkipAnimUpdateElapsedTime * fFinalAnimSpeed);
//m_AnimLayer[CHARACTER_ANIM_LAYER_BASE].Update(fElapsed * fFinalAnimSpeed);
if( m_pTypeBoneData && m_pTypeBoneData->bBoneScale)
UpdatePreBoneScale();
RpHAnimHierarchyUpdateMatrices(m_pBaseHierarchy);
if( m_pTypeBoneData && m_pTypeBoneData->bBoneScale)
UpdatePostBoneScale();
}
else
{
RwReal fCurTime = m_AnimLayer[CHARACTER_ANIM_LAYER_BASE].GetCurrentAnimTime();
m_AnimLayer[CHARACTER_ANIM_LAYER_BASE].SetCurrentAnimTime(fCurTime);
if( m_pTypeBoneData && m_pTypeBoneData->bBoneScale)
UpdatePreBoneScale();
RpHAnimHierarchyUpdateMatrices(m_pBaseHierarchy);
if( m_pTypeBoneData && m_pTypeBoneData->bBoneScale)
UpdatePostBoneScale();
}
//CNtlPLAttach::Update(fElapsed);
//CNtlPLAttach::Update(m_SkipAnimUpdateElapsedTime);
m_SkipAnimUpdateElapsedTime = 0;
}
else
{
if(GetCharScheduleResInfo()->bPCFlag)
{
RwReal fCurTime = m_AnimLayer[CHARACTER_ANIM_LAYER_BASE].GetCurrentAnimTime();
m_AnimLayer[CHARACTER_ANIM_LAYER_BASE].SetCurrentAnimTime(fCurTime);
if( m_pTypeBoneData && m_pTypeBoneData->bBoneScale)
UpdatePreBoneScale();
RpHAnimHierarchyUpdateMatrices(m_pBaseHierarchy);
if( m_pTypeBoneData && m_pTypeBoneData->bBoneScale)
UpdatePostBoneScale();
}
else
{
RpHAnimHierarchyUpdateMatrices(m_pBaseHierarchy);
}
}
CNtlPLAttach::Update(fElapsed);
/*
if(m_pEquipItem)
{
m_pEquipItem->Update(fElapsed);
}
// Guard band clip test
RwSphere sphere;
sphere.center = vPos;
sphere.radius = GetFastMaxExtent() * 0.5f;
sphere.center.y += (GetHeight() * 0.5f);
// Big entities exceptions; dinosaurs
RwFrustumTestResult ret = RwCameraFrustumTestSphere(CNtlPLGlobal::m_RwCamera, &sphere);
if(m_bAnimUpdate)
{
float fFinalAnimSpeed = 0.f;
if(m_pProperty != NULL)
{
if(m_sBaseAnimPlayInfo.m_uiAnimKey == RUN_FRONT )
fFinalAnimSpeed = m_fAnimSpeed * m_pProperty->GetInitRunFrontAnimSpeed();
else if(m_sBaseAnimPlayInfo.m_uiAnimKey == WALK_FRONT )
fFinalAnimSpeed = m_fAnimSpeed * m_pProperty->GetInitWalkFrontAnimSpeed();
else
fFinalAnimSpeed = m_fAnimSpeed;
}
else
fFinalAnimSpeed = m_fAnimSpeed;
m_AnimLayer[CHARACTER_ANIM_LAYER_BASE].Update(fElapsed * fFinalAnimSpeed);
if( m_pTypeBoneData && m_pTypeBoneData->bBoneScale)
UpdatePreBoneScale();
RpHAnimHierarchyUpdateMatrices(m_pBaseHierarchy);
if( m_pTypeBoneData && m_pTypeBoneData->bBoneScale)
UpdatePostBoneScale();
}
else
{
RwReal fCurTime = m_AnimLayer[CHARACTER_ANIM_LAYER_BASE].GetCurrentAnimTime();
m_AnimLayer[CHARACTER_ANIM_LAYER_BASE].SetCurrentAnimTime(fCurTime);
if( m_pTypeBoneData && m_pTypeBoneData->bBoneScale)
UpdatePreBoneScale();
RpHAnimHierarchyUpdateMatrices(m_pBaseHierarchy);
if( m_pTypeBoneData && m_pTypeBoneData->bBoneScale)
UpdatePostBoneScale();
}
CNtlPLAttach::Update(fElapsed); */
}
else
{
m_sScheduleResInfo.fAnimElapsedTime += fElapsed;
}
return TRUE;
}
/**
* Visula Manager에서 Render를 강제로 호출하게 했다.
* CallBack 형식으로 변경을 해야 할듯 하다.
* \return 실패 유무
*/
RwBool CNtlPLCharacter::Render(void)
{
return TRUE;
}
static RpAtomic *RenderToTextureAtomic(RpAtomic *pAtomic, void *pData)
{
RwUInt32 uiRenderFlags = RpNtlAtomicGetFlag(pAtomic);
if(uiRenderFlags & NTL_ALPHATEST)
BeginNtlAotmicAlphaTestState();
if(uiRenderFlags & NTL_TWOSIDE)
BeginNtlAtomicTwoSideState();
if ( uiRenderFlags & NTL_ALPHA) UpdateAlphaState(TRUE);
pAtomic->renderCallBack(pAtomic);
if ( uiRenderFlags & NTL_ALPHA) UpdateAlphaState(FALSE);
if(uiRenderFlags & NTL_TWOSIDE)
EndNtlAtomicTwoSideState();
if(uiRenderFlags & NTL_ALPHATEST)
EndNtlAtomicAlphaTestState();
return pAtomic;
}
/**
* Texture에 Rendering을 할 경우 쓰는 함수
* \return 실패 유무
*/
RwBool CNtlPLCharacter::RenderToTexture()
{
if( !GetCharScheduleResInfo()->bLoadComplete ||
m_pResourceClump == NULL)
return FALSE;
if(m_pResourceClump->GetClump())
{
RpClumpForAllAtomics(m_pResourceClump->GetClump(), RenderToTextureAtomic, NULL);
//RpClumpRender(m_pResourceClump->GetClump());
}
if(m_pEquipItem)
{
m_pEquipItem->RenderToTexture();
}
return TRUE;
}
void CNtlPLCharacter::UpdatePreBoneScale()
{
int nTotalBone = m_pBaseHierarchy->numNodes;
RwUInt32 stack[MAX_NUM_SCALE_BONE>>1];
RwUInt32 nStack = 0;
RwUInt32 parentIndex = 0;
RwUInt32 currentIndex;
RwBool bTargetPosApply = FALSE;
RwUInt32 uiBone1 = 0;
RwMatrix* pMatClavicle = NULL;
if(strlen(m_szBoneStretchAxisBone) > 0)
{
uiBone1 = GetBoneIndex(m_szBoneStretchAxisBone);
bTargetPosApply = RwV3dLength(&m_vBoneStretchTargetPos) > 0.0f ? TRUE : FALSE;
pMatClavicle = GetBoneMatrix(m_szBoneStretchAxisBone);
}
for (currentIndex=1; currentIndex < (RwUInt32)nTotalBone; currentIndex++)
{
RwUInt32 flags;
RpHAnimInterpFrame *iFrame = (RpHAnimInterpFrame *)
rtANIMGETINTERPFRAME(m_pBaseHierarchy->currentAnim, currentIndex);
iFrame->t.x *= m_pTypeBoneData->BoneScale[parentIndex].fLength;
iFrame->t.y *= m_pTypeBoneData->BoneScale[parentIndex].fWidth;
iFrame->t.z *= m_pTypeBoneData->BoneScale[parentIndex].fWidth;
if(bTargetPosApply && parentIndex == uiBone1)
{
// 어깨 본으로부터 타겟의 각도를 계산해서 변형한다.
// 타겟 방향으로 본을 늘리기 위해서다. 나메크 팔늘리기 스킬용 (by agebreak 08-10-23)
RwV3d vBonePos = pMatClavicle->pos;
vBonePos.x = GetPosition().x;
vBonePos.z = GetPosition().z;
RwV3d vDir = m_vBoneStretchTargetPos - GetPosition();
vDir.y = 0.0f;
RwV3dNormalize(&vDir, &vDir);
RwV3d vTargetDir = m_vBoneStretchTargetPos - vBonePos;
RwV3dNormalize(&vTargetDir, &vTargetDir);
RwReal fAngle = acos(RwV3dDotProduct(&vDir, &vTargetDir));
// 왼쪽, 오른쪽 어깨에 따라서 휘어지는 각도가 다르다.
if(strstr(m_szBoneStretchAxisBone, " L ") > 0)
{
fAngle = vBonePos.y <= m_vBoneStretchTargetPos.y ? fAngle : -fAngle;
}
else if(strstr(m_szBoneStretchAxisBone, " R ") > 0)
{
fAngle = vBonePos.y <= m_vBoneStretchTargetPos.y ? -fAngle : fAngle;
}
else
{
fAngle = 0.0f;
}
RwMatrix matRot, matAnim;
RwMatrixSetIdentity(&matRot);
RwMatrixSetIdentity(&matAnim);
RtQuatConvertToMatrix(&iFrame->q, &matAnim);
RwMatrixRotate(&matRot, &ZAxis, NTL_RAD2DEG(fAngle), rwCOMBINEPOSTCONCAT);
RwMatrixMultiply(&matAnim, &matRot, &matAnim);
RtQuatConvertFromMatrix(&iFrame->q, &matAnim);
}
flags = m_pBaseHierarchy->pNodeInfo[currentIndex].flags;
if (flags & rpHANIMPUSHPARENTMATRIX)
{
stack[++nStack] = parentIndex;
}
if (flags & rpHANIMPOPPARENTMATRIX)
{
parentIndex = stack[nStack--];
nStack = max(nStack, 0);
}
else
{
parentIndex = currentIndex;
}
}
}
void CNtlPLCharacter::UpdatePostBoneScale()
{
int nTotalBone = m_pBaseHierarchy->numNodes;
RwUInt32 uiBone1 = GetBoneIndex("Bip01 L UpperArm");
RwMatrix *matrix;
matrix = RpHAnimHierarchyGetMatrixArray(m_pBaseHierarchy);
for (int i=0; i < nTotalBone ; i++)
{
RwV3d vScale;
vScale.x = m_pTypeBoneData->BoneScale[i].fLength;
vScale.y = vScale.z = m_pTypeBoneData->BoneScale[i].fWidth;
RwMatrixScale(matrix, &vScale, rwCOMBINEPRECONCAT);
//if(uiBone1 == i)
//{
// RwMatrixRotate(matrix, &XAxis, -45.0f, rwCOMBINEPOSTCONCAT);
//}
matrix++;
}
}
/**
* Toon Data를 생성을 한다.
*/
void CNtlPLCharacter::CreateToonData(const RwChar *szTexName, const RwChar *szTexPath)
{
NTL_FUNCTION("CNtlPLCharacter::CreateToonData()");
m_ToonData.pTexture = CNtlPLResourceManager::GetInstance()->LoadTexture(szTexName, szTexPath);
m_ToonData.pToonInk = RpToonInkCreate();
//RwTextureSetFilterMode(m_ToonData.pTexture, rwFILTERLINEARMIPLINEAR);
SetInkThickness(DEFAULT_INK_THICKNESS);
RpToonInkSetColor(m_ToonData.pToonInk, m_sInkColor);
RpToonInkSetName(m_ToonData.pToonInk, "silhouette" );
m_ToonData.pToonPaint = RpToonPaintCreate();
RpToonPaintSetGradientTexture(m_ToonData.pToonPaint, m_ToonData.pTexture);
NTL_RETURNVOID();
}
/**
* Animation에 필요한 세팅을 한다.
* \param pAnim RtAnimAnimation Data
* \return 실패 유무
*/
RwBool CNtlPLCharacter::CreateAnim(RwUInt32 uiAnimKey, RwReal fStartTime, RwBool bLoop )
{
NTL_ASSERTE(m_pResourceClump != NULL);
SInstanceAnimData *pInstanceAnimData = m_InstanceAnimTable.Get(uiAnimKey);
if(pInstanceAnimData == NULL)
{
std::string *pStrAnimName = CNtlPLCharacterParser::GetInstance().GetPCMatchTable()->GetString(uiAnimKey);
if(pStrAnimName == NULL)
pStrAnimName = CNtlPLCharacterParser::GetInstance().GetMobMatchTable()->GetString(uiAnimKey);
if(pStrAnimName == NULL)
pStrAnimName = CNtlPLCharacterParser::GetInstance().GetNPCMatchTable()->GetString(uiAnimKey);
if(pStrAnimName != NULL)
NTL_ASSERT(pInstanceAnimData, "Find not animation: " << "ModelName: " << GetName() << "AnimName: " << pStrAnimName->c_str() << "AnimID: " << uiAnimKey );
if(pStrAnimName == NULL)
NTL_ASSERT(pInstanceAnimData, "Find not animation: " << "ModelName: " << GetName() << "AnimID: " << uiAnimKey );
}
if((pInstanceAnimData == NULL) || (pInstanceAnimData->pResource == NULL) )
return FALSE;
RpHAnimHierarchySetCurrentAnim(m_pBaseHierarchy, pInstanceAnimData->pResource->GetAnimation());
Helper_SetHierarchyClumpSkin(m_pResourceClump->GetClump(), m_pBaseHierarchy);
RpHAnimHierarchySetFlags( m_pBaseHierarchy,
(RpHAnimHierarchyFlag)(RpHAnimHierarchyGetFlags(m_pBaseHierarchy) |
rpHANIMHIERARCHYUPDATELTMS |
rpHANIMHIERARCHYUPDATEMODELLINGMATRICES));
RpHAnimHierarchyAttach(m_pBaseHierarchy);
RpHAnimUpdateHierarchyMatrices(m_pBaseHierarchy);
if(!m_AnimLayer[CHARACTER_ANIM_LAYER_BASE].Create(m_pBaseHierarchy))
return FALSE;
m_AnimLayer[CHARACTER_ANIM_LAYER_BASE].SetAllAnimation(pInstanceAnimData, fStartTime, bLoop);
m_sBaseAnimPlayInfo.m_uiAnimKey = uiAnimKey;
return TRUE;
}
RwBool CNtlPLCharacter::IsExistAnim(RwUInt32 uiAnimKey)
{
STypeAnimData *pTypeAnimData = m_pProperty->GetAnimTable()->Get(uiAnimKey);
if(pTypeAnimData == NULL)
{
return FALSE;
}
return TRUE;
}
/**
* Animation Change를 한다. RUN_FRONT, RUN_BACK, ROTATE는 현재 Animation이 있을 경우 변경하지 않는다.
* \param uiAnimKey AnimationKey
* \param fStartTime Animation 시작시간
* \param bLoop Loop 유무
* \return 실패 유무
*/
RwBool CNtlPLCharacter::SetBaseAnimation(RwUInt32 uiAnimKey, RwReal fStartTime, RwBool bLoop)
{
if( !GetCharScheduleResInfo()->bLoadComplete )
{
m_sScheduleResInfo.uiAnimKey = uiAnimKey;
m_sScheduleResInfo.fAnimElapsedTime = 0.f;
m_sScheduleResInfo.bAnimLoop = bLoop;
return FALSE;
}
// 애니메이션이 변경되면, LoopEffect를 모두 소멸시킨다.
if(m_sBaseAnimPlayInfo.m_uiAnimKey != uiAnimKey)
{
ClearLoopEffect();
ClearLoopSound();
}
SInstanceAnimData *pInstanceAnimData = m_InstanceAnimTable.Get(uiAnimKey);
if(pInstanceAnimData == NULL)
{
std::string *pStrAnimName = CNtlPLCharacterParser::GetInstance().GetPCMatchTable()->GetString(uiAnimKey);
if(pStrAnimName == NULL)
pStrAnimName = CNtlPLCharacterParser::GetInstance().GetMobMatchTable()->GetString(uiAnimKey);
if(pStrAnimName == NULL)
pStrAnimName = CNtlPLCharacterParser::GetInstance().GetNPCMatchTable()->GetString(uiAnimKey);
if(pStrAnimName != NULL)
NtlLogFilePrintArgs("Find not animation : ModelName(%s), AnimID(%s)", GetName(), pStrAnimName->c_str());
if(pStrAnimName == NULL)
NtlLogFilePrintArgs("Find not animation : ModelName(%s), AnimID(%d)", GetName(), uiAnimKey);
pInstanceAnimData = m_InstanceAnimTable.Get(NML_IDLE_LOOP);
}
if( (pInstanceAnimData == NULL) ||
(pInstanceAnimData->pResource == NULL) )
return TRUE;
m_sBaseAnimPlayInfo.m_uiAnimKey = uiAnimKey;
m_AnimLayer[CHARACTER_ANIM_LAYER_BASE].SetAnimation(pInstanceAnimData, fStartTime, bLoop);
return TRUE;
}
/**
* Animation Blend를 하지 않고 Pre, Next 모두 Animation를 바꾼다.
* \param uiAnimKey AnimationKey
* \param fStartTime Animation 시작시간
* \param bLoop Loop 유무
* \return 실패 유무
*/
RwBool CNtlPLCharacter::SetAllAnimation(RwUInt32 uiAnimKey, RwReal fStartTime, RwBool bLoop)
{
SInstanceAnimData *pInstanceAnimData = m_InstanceAnimTable.Get(uiAnimKey);
NTL_ASSERTE(pInstanceAnimData);
NTL_ASSERTE(pInstanceAnimData->pResource);
if((pInstanceAnimData == NULL) || (pInstanceAnimData->pResource == NULL) )
NTL_RETURN(FALSE);
m_sBaseAnimPlayInfo.m_uiAnimKey = uiAnimKey;
m_AnimLayer[CHARACTER_ANIM_LAYER_BASE].SetAllAnimation(pInstanceAnimData, fStartTime, bLoop);
return TRUE;
}
RwBool CNtlPLCharacter::SetBlend(EBlendType eBlendType, RwReal fBlendAlpha, RwReal fBlendInterval)
{
NTL_FUNCTION("CNtlPLCharacter::SetBlend()");
m_AnimLayer[CHARACTER_ANIM_LAYER_BASE].SetBlend(eBlendType, fBlendAlpha, fBlendInterval);
NTL_RETURN(TRUE);
}
/**
* Animation에서의 AnimHit
* \return SAnimHitParam
*/
SAnimPlayInfo *CNtlPLCharacter::GetBaseAnimPlayInfo()
{
NTL_FUNCTION("CNtlPLCharacter::GetBaseAnimPlayInfo()");
if( !GetCharScheduleResInfo()->bLoadComplete )
return NULL;
m_sBaseAnimPlayInfo.vecAnimHit.clear();
SInstanceAnimData *pInstanceAnimData = m_InstanceAnimTable.Get(m_sBaseAnimPlayInfo.m_uiAnimKey);
NTL_ASSERTE(pInstanceAnimData);
RwUInt32 uiCount = pInstanceAnimData->pTypeAnimData->vecAnimEvent.size();
for(RwUInt32 i = 0; i < uiCount; i++)
{
if(pInstanceAnimData->pTypeAnimData->vecAnimEvent[i]->eEventID == EVENT_ANIM_HIT)
{
m_sBaseAnimPlayInfo.vecAnimHit.push_back( (SEventAnimHit *)pInstanceAnimData->pTypeAnimData->vecAnimEvent[i] );
}
}
NTL_RETURN(&m_sBaseAnimPlayInfo);
}
RwReal CNtlPLCharacter::GetDurationAnimTime(RwUInt32 uiAnimKey)
{
if( !GetCharScheduleResInfo()->bLoadComplete )
return 0.f;
SInstanceAnimData *pInstanceAnimData = m_InstanceAnimTable.Get(uiAnimKey);
NTL_ASSERTE(pInstanceAnimData);
NTL_ASSERTE(pInstanceAnimData->pResource);
return pInstanceAnimData->pResource->GetAnimation()->duration;
}
RwReal CNtlPLCharacter::GetWidth()
{
RwBBox *pbbBoxAnim = m_pProperty->GetAnimBBox();
RwReal fWidth = pbbBoxAnim->sup.x - pbbBoxAnim->inf.x;
fWidth *= m_vScale.x;
return fWidth;
}
RwReal CNtlPLCharacter::GetHeight()
{
RwBBox *pbbBoxAnim = m_pProperty->GetAnimBBox();
RwReal fHeight = pbbBoxAnim->sup.y - pbbBoxAnim->inf.y;
fHeight *= m_vScale.y;
return fHeight;
}
RwReal CNtlPLCharacter::GetDepth()
{
RwBBox *pbbBoxAnim = m_pProperty->GetAnimBBox();
RwReal fDepth = pbbBoxAnim->sup.z - pbbBoxAnim->inf.z;
fDepth *= m_vScale.z;
return fDepth;
}
void CNtlPLCharacter::Destroy()
{
RemoveWorld();
for each(SPLAttachAttr* pPLAttachAttr in m_listAttachAttr)
{
if(!pPLAttachAttr->pPLEntity)
continue;
if(strcmp(pPLAttachAttr->pPLEntity->GetName(), EFFECT_NAME_TRACE) == 0)
{
pPLAttachAttr->pPLEntity->SetAttachParent(NULL);
GetSceneManager()->DeleteEntity(pPLAttachAttr->pPLEntity);
pPLAttachAttr->pPLEntity = NULL;
}
}
if(m_pEquipItem)
{
m_pEquipItem->Destroy();
NTL_DELETE(m_pEquipItem);
m_pEquipItem = NULL;
}
ClearLoopEffect();
ClearLoopSound();
if(m_ToonData.pToonPaint)
RpToonPaintDestroy(m_ToonData.pToonPaint);
if(m_ToonData.pToonInk)
RpToonInkDestroy(m_ToonData.pToonInk);
if(m_ToonData.pTexture)
CNtlPLResourceManager::GetInstance()->UnLoadTexture(m_ToonData.pTexture);
if(m_pBaseHierarchy != NULL)
RpHAnimHierarchyDestroy(m_pBaseHierarchy);
CNtlPLResourceManager::GetInstance()->UnLoadScheduling(this, m_pResourceClump );
m_pResourceClump = NULL;
m_mapFrame.clear();
m_InstanceAnimTable.Destroy();
m_AnimLayer[CHARACTER_ANIM_LAYER_BASE].Destroy();
m_AnimLayer[CHARACTER_ANIM_LAYER_UPPER].Destroy();
Helper_DestroyAllAtomics(&m_vecAtomicList);
DestroyOccluderProxy();
}
void CNtlPLCharacter::AddWorld(void)
{
if( m_pResourceClump == NULL ||
CNtlPLGlobal::m_pRpWorld == NULL)
return;
if(RpClumpGetWorld( m_pResourceClump->GetClump() ) == NULL)
RpWorldAddClump(CNtlPLGlobal::m_pRpWorld, m_pResourceClump->GetClump());
}
void CNtlPLCharacter::RemoveWorld(void)
{
if( m_pResourceClump == NULL ||
CNtlPLGlobal::m_pRpWorld == NULL)
return;
if(RpClumpGetWorld( m_pResourceClump->GetClump() ) != NULL)
RpWorldRemoveClump(CNtlPLGlobal::m_pRpWorld, m_pResourceClump->GetClump());
}
RwBool CNtlPLCharacter::IsExistWorld()
{
if( m_pResourceClump == NULL )
return FALSE;
if( RpClumpGetWorld( m_pResourceClump->GetClump() ) != NULL)
return TRUE;
return FALSE;
}
RpClump *CNtlPLCharacter::GetClump()
{
if( m_pResourceClump == NULL)
return NULL;
return m_pResourceClump->GetClump();
}
RpHAnimHierarchy *CNtlPLCharacter::GetBaseHierarchy()
{
return m_pBaseHierarchy;
}
RpAtomic* CNtlPLCharacter::GetAtomic( const std::string& strName )
{
std::string strAtomicName;
for each(SEntityAtomicData* pAtomicData in m_vecAtomicList)
{
strAtomicName = Helper_AtomicName(pAtomicData->pData);
if(strName == strAtomicName)
return pAtomicData->pData;
}
return NULL;
}
/**
* pPos위치에 Character를 위치 시킨다.
* \param pPos World에서의 위치
*/
void CNtlPLCharacter::SetPosition(const RwV3d *pPos)
{
memcpy(&m_vCurPos, pPos, sizeof(RwV3d));
if( !GetCharScheduleResInfo()->bLoadComplete )
return;
NTL_ASSERTE(m_pResourceClump);
if(m_pResourceClump == NULL)
return;
RwFrame* pFrame;
pFrame = RpClumpGetFrame(m_pResourceClump->GetClump());
RwFrameRotate(pFrame, &CNtlPLGlobal::m_vXAxisV3, m_vAngle.x,rwCOMBINEREPLACE);
RwFrameRotate(pFrame, &CNtlPLGlobal::m_vYAxisV3, m_vAngle.y,rwCOMBINEPOSTCONCAT);
if(m_pTypeBoneData)
{
if(m_pTypeBoneData->bBaseScale)
RwFrameScale(pFrame, &m_pTypeBoneData->vBaseScale, rwCOMBINEPOSTCONCAT);
RwFrameScale(pFrame, &m_vScale, rwCOMBINEPOSTCONCAT);
if(m_pTypeBoneData->bBoneScale)
RwFrameTranslate(pFrame, &m_pTypeBoneData->vPosOffset, rwCOMBINEPOSTCONCAT);
}
RwFrameTranslate(pFrame, &m_vCurPos, rwCOMBINEPOSTCONCAT);
RwFrameUpdateObjects( pFrame );
// Sound의 위치도 변경한다.
ListSoundHandle::iterator it = m_listLoopSound.begin();
for(; it != m_listLoopSound.end(); ++it)
{
SOUND_HANDLE hSound = *it;
GetSoundManager()->SetSoundPosition(hSound, m_vCurPos.x, m_vCurPos.y, m_vCurPos.z);
}
// Position이 변경이 될 경우에 위치는 변경이 되지 않는다.(이거 Test를 좀 해봐야 할 듯 하다 by HoDong)
//CNtlPLAttach::Update(0.f);
}
/**
* Base Scale를 조정을 한다.
* \param fScale Default값은 1.f 이다.
*/
void CNtlPLCharacter::SetScale(RwReal fScale)
{
m_vScale.x = fScale;
m_vScale.y = fScale;
m_vScale.z = fScale;
if( !GetCharScheduleResInfo()->bLoadComplete )
return;
NTL_ASSERTE(m_pResourceClump);
if(m_pResourceClump == NULL)
return;
RwFrame* pFrame;
pFrame = RpClumpGetFrame(m_pResourceClump->GetClump());
RwFrameRotate(pFrame, &CNtlPLGlobal::m_vXAxisV3, m_vAngle.x,rwCOMBINEREPLACE);
RwFrameRotate(pFrame, &CNtlPLGlobal::m_vYAxisV3, m_vAngle.y,rwCOMBINEPOSTCONCAT);
if(m_pTypeBoneData)
{
if(m_pTypeBoneData->bBaseScale)
RwFrameScale(pFrame, &m_pTypeBoneData->vBaseScale, rwCOMBINEPOSTCONCAT);
RwFrameScale(pFrame, &m_vScale, rwCOMBINEPOSTCONCAT);
if(m_pTypeBoneData->bBoneScale)
RwFrameTranslate(pFrame, &m_pTypeBoneData->vPosOffset, rwCOMBINEPOSTCONCAT);
}
RwFrameTranslate(pFrame, &m_vCurPos, rwCOMBINEPOSTCONCAT);
}
RwReal CNtlPLCharacter::GetScale()
{
return m_vScale.x;
}
/**
* Base Scale를 조정을 한다.
* \param fScale Default값은 1.f 이다.
*/
void CNtlPLCharacter::SetBaseScale(RwReal fBaseScale)
{
if(m_pTypeBoneData)
{
m_pTypeBoneData->vBaseScale.x = fBaseScale;
m_pTypeBoneData->vBaseScale.y = fBaseScale;
m_pTypeBoneData->vBaseScale.z = fBaseScale;
}
if( !GetCharScheduleResInfo()->bLoadComplete )
return;
NTL_ASSERTE(m_pResourceClump);
if( m_pResourceClump == NULL)
return;
RwFrame* pFrame;
pFrame = RpClumpGetFrame(m_pResourceClump->GetClump());
RwFrameRotate(pFrame, &CNtlPLGlobal::m_vXAxisV3, m_vAngle.x,rwCOMBINEREPLACE);
RwFrameRotate(pFrame, &CNtlPLGlobal::m_vYAxisV3, m_vAngle.y,rwCOMBINEPOSTCONCAT);
if(m_pTypeBoneData)
{
if(m_pTypeBoneData->bBaseScale)
RwFrameScale(pFrame, &m_pTypeBoneData->vBaseScale, rwCOMBINEPOSTCONCAT);
RwFrameScale(pFrame, &m_vScale, rwCOMBINEPOSTCONCAT);
if(m_pTypeBoneData->bBoneScale)
RwFrameTranslate(pFrame, &m_pTypeBoneData->vPosOffset, rwCOMBINEPOSTCONCAT);
}
RwFrameTranslate(pFrame, &m_vCurPos, rwCOMBINEPOSTCONCAT);
}
/**
* 프로퍼티에 설정된 BaseScale을 반환한다.
*/
RwReal CNtlPLCharacter::GetBaseScale()
{
if(m_pTypeBoneData)
{
return m_pTypeBoneData->vBaseScale.x;
}
else
{
return 1.0f;
}
}
/**
* 발이 땅에서 떨어질 경우 위치값이다.
* \param pPos 이동시킬 위치이다.
*/
void CNtlPLCharacter::SetPosOffset(RwV3d *pPos)
{
NTL_ASSERTE(pPos);
NTL_ASSERTE(m_pTypeBoneData);
m_pTypeBoneData->vPosOffset.x = pPos->x;
m_pTypeBoneData->vPosOffset.y = pPos->y;
m_pTypeBoneData->vPosOffset.z = pPos->z;
RwFrame* pFrame;
pFrame = RpClumpGetFrame(m_pResourceClump->GetClump());
RwFrameRotate(pFrame, &CNtlPLGlobal::m_vXAxisV3, m_vAngle.x,rwCOMBINEREPLACE);
RwFrameRotate(pFrame, &CNtlPLGlobal::m_vYAxisV3, m_vAngle.y,rwCOMBINEPOSTCONCAT);
if(m_pTypeBoneData)
{
if(m_pTypeBoneData->bBaseScale)
RwFrameScale(pFrame, &m_pTypeBoneData->vBaseScale, rwCOMBINEPOSTCONCAT);
RwFrameScale(pFrame, &m_vScale, rwCOMBINEPOSTCONCAT);
if(m_pTypeBoneData->bBoneScale)
RwFrameTranslate(pFrame, &m_pTypeBoneData->vPosOffset, rwCOMBINEPOSTCONCAT);
}
RwFrameTranslate(pFrame, &m_vCurPos, rwCOMBINEPOSTCONCAT);
int test = 0;
}
/**
* Character의 회전
* \param fAngleY 회전값
*/
void CNtlPLCharacter::SetAngleY(const RwReal fAngleY)
{
m_vAngle.y = fAngleY;
if( !GetCharScheduleResInfo()->bLoadComplete )
return;
NTL_ASSERTE(m_pResourceClump);
if(m_pResourceClump == NULL)
return;
RwFrame* pFrame;
pFrame = RpClumpGetFrame(m_pResourceClump->GetClump());
RwFrameRotate(pFrame, &CNtlPLGlobal::m_vXAxisV3, m_vAngle.x,rwCOMBINEREPLACE);
RwFrameRotate(pFrame, &CNtlPLGlobal::m_vYAxisV3, m_vAngle.y,rwCOMBINEPOSTCONCAT);
if(m_pTypeBoneData)
{
if(m_pTypeBoneData->bBaseScale)
RwFrameScale(pFrame, &m_pTypeBoneData->vBaseScale, rwCOMBINEPOSTCONCAT);
RwFrameScale(pFrame, &m_vScale, rwCOMBINEPOSTCONCAT);
if(m_pTypeBoneData->bBoneScale)
RwFrameTranslate(pFrame, &m_pTypeBoneData->vPosOffset, rwCOMBINEPOSTCONCAT);
}
RwFrameTranslate(pFrame, &m_vCurPos, rwCOMBINEPOSTCONCAT);
}
void CNtlPLCharacter::SetAngleX(const RwReal fAngleX)
{
m_vAngle.x = fAngleX;
if( !GetCharScheduleResInfo()->bLoadComplete )
return;
NTL_ASSERTE(m_pResourceClump);
if(m_pResourceClump == NULL)
return;
RwFrame* pFrame;
pFrame = RpClumpGetFrame(m_pResourceClump->GetClump());
RwFrameRotate(pFrame, &CNtlPLGlobal::m_vXAxisV3, m_vAngle.x,rwCOMBINEREPLACE);
RwFrameRotate(pFrame, &CNtlPLGlobal::m_vYAxisV3, m_vAngle.y,rwCOMBINEPOSTCONCAT);
if(m_pTypeBoneData)
{
if(m_pTypeBoneData->bBaseScale)
RwFrameScale(pFrame, &m_pTypeBoneData->vBaseScale, rwCOMBINEPOSTCONCAT);
RwFrameScale(pFrame, &m_vScale, rwCOMBINEPOSTCONCAT);
if(m_pTypeBoneData->bBoneScale)
RwFrameTranslate(pFrame, &m_pTypeBoneData->vPosOffset, rwCOMBINEPOSTCONCAT);
}
RwFrameTranslate(pFrame, &m_vCurPos, rwCOMBINEPOSTCONCAT);
}
/**
* 현재 Angle에서 fAngleDeltaY값 만큼을 더한다.
* \param fAngleDeltaY Delta 회전값
*/
void CNtlPLCharacter::SetAngleDelta(const RwReal fAngleDeltaY)
{
m_vAngle.y = m_vAngle.y + fAngleDeltaY;
if( !GetCharScheduleResInfo()->bLoadComplete )
return;
SetAngleY(m_vAngle.y);
}
/**
* 특정 Bone의 Matrix 값을 얻는다.
* \param pBoneName Bone의 이름
*/
RwMatrix* CNtlPLCharacter::GetBoneMatrix(const RwChar *pBoneName)
{
if( !GetCharScheduleResInfo()->bLoadComplete )
return NULL;
RwFrame *pFrame = GetBoneByName(pBoneName);
if(pFrame != NULL)
return &pFrame->ltm;
return NULL;
}
RwFrame *CNtlPLCharacter::GetBoneByName(const RwChar *pBoneName)
{
if( !GetCharScheduleResInfo()->bLoadComplete )
return NULL;
if(m_mapFrame.find( pBoneName ) == m_mapFrame.end())
return NULL;
RwFrame *pFrame = m_mapFrame[pBoneName];
if(pFrame != NULL)
return pFrame;
return NULL;
}
RwUInt32 CNtlPLCharacter::GetBoneIndex( const RwChar* pBoneName )
{
std::string strBoneName = pBoneName;
std::string strMapBoneName;
for(int i = 0; i < m_nBoneCount; ++i)
{
strMapBoneName = GetBoneName(i);
if(strMapBoneName == strBoneName)
return i;
}
return 0;
}
RwV3d CNtlPLCharacter::GetPosition()
{
if( !GetCharScheduleResInfo()->bLoadComplete )
{
return m_vCurPos;
}
RwFrame *pFrame = RpClumpGetFrame(m_pResourceClump->GetClump());
NTL_ASSERTE(pFrame);
return pFrame->modelling.pos;
}
void CNtlPLCharacter::SetDirection(const RwV3d *pDir)
{
if( !GetCharScheduleResInfo()->bLoadComplete )
return;
RwReal fAxisAngleX, fAxisAngleY;
CNtlMath::LineToAngleXY(pDir, fAxisAngleX, fAxisAngleY);
m_vAngle.x = fAxisAngleX + m_vAngle.x;
m_vAngle.y = fAxisAngleY + m_vAngle.y;
SetAngleX(m_vAngle.x);
SetAngleY(m_vAngle.y);
}
RwV3d CNtlPLCharacter::GetDirection()
{
if( !GetCharScheduleResInfo()->bLoadComplete )
{
return m_vCurPos;
}
RwFrame *pFrame = RpClumpGetFrame(m_pResourceClump->GetClump());
NTL_ASSERTE(pFrame);
return pFrame->modelling.at;
}
RwV3d CNtlPLCharacter::GetRight()
{
if( !GetCharScheduleResInfo()->bLoadComplete )
{
return m_vCurPos;
}
RwFrame *pFrame = RpClumpGetFrame(m_pResourceClump->GetClump());
NTL_ASSERTE(pFrame);
return pFrame->modelling.right;
}
RwV3d CNtlPLCharacter::GetUp()
{
if( !GetCharScheduleResInfo()->bLoadComplete )
{
return YAxis;
}
RwFrame *pFrame = RpClumpGetFrame(m_pResourceClump->GetClump());
NTL_ASSERTE(pFrame);
return pFrame->modelling.up;
}
RwFrame *CNtlPLCharacter::GetFrame()
{
//NTL_ASSERTE(m_pResourceClump);
if(m_pResourceClump == NULL)
return NULL;
return RpClumpGetFrame(m_pResourceClump->GetClump());
}
RwMatrix& CNtlPLCharacter::GetMatrix()
{
RwFrame *pFrame = GetFrame();
if(pFrame == NULL)
{
return CNtlPLEntity::GetMatrix();
}
return *RwFrameGetMatrix(pFrame);
}
void CNtlPLCharacter::SetMatrix( RwMatrix& matWorld)
{
RwFrame *pFrame = GetFrame();
if(!pFrame)
return;
RwMatrix* pMatChar = RwFrameGetMatrix(pFrame);
if(!pMatChar)
return;
RwMatrixCopy(pMatChar, &matWorld);
pMatChar->pos = ZeroAxis;
// Base Scale을 적용해줘야만 한다.
RwFrameScale(pFrame, &m_pTypeBoneData->vBaseScale, rwCOMBINEPOSTCONCAT);
RwFrameTranslate(pFrame, RwMatrixGetPos(&matWorld), rwCOMBINEPOSTCONCAT);
RwFrameUpdateObjects(pFrame);
}
void CNtlPLCharacter::SetAnimSpeed(RwReal fSpeed)
{
m_fAnimSpeed = fSpeed;
}
RwReal CNtlPLCharacter::GetAnimSpeed()
{
return m_fAnimSpeed;
}
void CNtlPLCharacter::SetAnimUpdate(RwBool bAnimUpdate)
{
m_bAnimUpdate = bAnimUpdate;
}
RwBool CNtlPLCharacter::GetAnimUpdate()
{
return m_bAnimUpdate;
}
RwReal CNtlPLCharacter::GetBaseCurrentAnimTime()
{
return m_AnimLayer[CHARACTER_ANIM_LAYER_BASE].GetCurrentAnimTime();
}
RwReal CNtlPLCharacter::GetBaseDurationAnimTime()
{
return m_AnimLayer[CHARACTER_ANIM_LAYER_BASE].GetDurationAnimTime();
}
void CNtlPLCharacter::SetBaseCurrentAnimTime(RwReal fCurrTime)
{
m_AnimLayer[CHARACTER_ANIM_LAYER_BASE].SetCurrentAnimTime(fCurrTime);
}
RwBool CNtlPLCharacter::GetBaseCurrentAnimEnd()
{
return m_AnimLayer[CHARACTER_ANIM_LAYER_BASE].GetCurrentAnimEnd();
}
RwBool CNtlPLCharacter::SetChangeEquipCItem(CNtlPLItem* _pItem, RwBool _bAttach, RwUInt32 _CBitSet)
{
if(m_pEquipItem)
{
m_pEquipItem->AddCItem(_pItem, _bAttach, _CBitSet);
// Cz : Character Atomic List
// DestroyOccluderProxy();
//
// if(m_pResourceClump)
// {
// Helper_DestroyAllAtomics(&m_vecAtomicList);
// Helper_SetClumpAllAtomics(m_pResourceClump->GetClump(), &m_vecAtomicList);
// }
// CreateOccluderProxy();
return TRUE;
}
return FALSE;
}
RwBool CNtlPLCharacter::SetRemoveEquipCItem(CNtlPLItem* _pItem, RwUInt32 _CBitSet)
{
if(m_pEquipItem)
{
m_pEquipItem->RemoveCItem(_pItem, _CBitSet);
// Cz : Character Atomic List
// DestroyOccluderProxy();
// if(m_pResourceClump)
// {
// Helper_DestroyAllAtomics( &m_vecAtomicList );
// Helper_SetClumpAllAtomics( m_pResourceClump->GetClump(), &m_vecAtomicList);
// }
// CreateOccluderProxy();
return TRUE;
}
return FALSE;
}
RwBool CNtlPLCharacter::SetChangeEquipItem(CNtlPLItem *pItem, RwBool bAttach, RwUInt32 _CBitSet/* = dCOSTUME_BITSET_INVALID*/)
{
if(_CBitSet != dCOSTUME_BITSET_INVALID)
{
SetChangeEquipCItem(pItem, bAttach, _CBitSet);
return TRUE;
}
if(m_pEquipItem != NULL)
{
m_pEquipItem->AddItem(pItem, bAttach);
// Cz : Character Atomic List
// DestroyOccluderProxy();
// if(m_pResourceClump)
// {
// Helper_DestroyAllAtomics( &m_vecAtomicList );
// Helper_SetClumpAllAtomics( m_pResourceClump->GetClump(), &m_vecAtomicList);
// }
// CreateOccluderProxy();
return TRUE;
}
return FALSE;
}
RwBool CNtlPLCharacter::SetRemoveEquipItem(CNtlPLItem *pItem, RwUInt32 _CBitSet/* = dCOSTUME_BITSET_INVALID*/)
{
if(_CBitSet != dCOSTUME_BITSET_INVALID)
{
SetRemoveEquipCItem(pItem, _CBitSet);
return TRUE;
}
if(m_pEquipItem != NULL)
{
m_pEquipItem->RemoveItem(pItem);
// Cz : Character Atomic List
// DestroyOccluderProxy();
// if(m_pResourceClump)
// {
// Helper_DestroyAllAtomics( &m_vecAtomicList );
// Helper_SetClumpAllAtomics( m_pResourceClump->GetClump(), &m_vecAtomicList);
// }
// CreateOccluderProxy();
return TRUE;
}
return FALSE;
}
void CNtlPLCharacter::UpdateCharacterAtomicList()
{
DestroyOccluderProxy();
if(m_pResourceClump)
{
Helper_DestroyAllAtomics( &m_vecAtomicList );
Helper_SetClumpAllAtomics( m_pResourceClump->GetClump(), &m_vecAtomicList);
}
CreateOccluderProxy();
}
VOID CNtlPLCharacter::SetToonEdgeVisibility4CurEquipItem(RwBool _Visibility)
{
if(m_pEquipItem)
{
m_pEquipItem->SetToonEdgeVisibility4CurEquipItem(_Visibility);
}
}
/**
* Character를 Rendering시 호출이 되는 CallBack 함수
* Equip Item도 이함수가 호출이 된다.
* \param pAtomic:
*/
RpAtomic *CNtlPLCharacter::RenderCallBack(RpAtomic *pAtomic)
{
CNtlPLEntity *pEntity = (CNtlPLEntity*)RpNtlAtomicGetData(pAtomic);
if(pEntity)
{
if(pEntity->GetClassType() == PLENTITY_ITEM)
{
CNtlPLItem* pItemEntity = (CNtlPLItem*)pEntity;
// 스카우터 안보이기 옵션
if(CNtlPLGlobal::m_bRenderScouter == FALSE && pItemEntity->GetEquipSlotType() == ITEM_EQUIP_R_EYE)
{
return pAtomic;
}
RwTexture* pTexture = pItemEntity->GetBaseTexture();
RwTexture* pUVTexture = pItemEntity->GetUVTexture();
pItemEntity->SetEMUVController(TRUE);
pItemEntity->CreateSimpleMaterial();
pItemEntity->CreatePetrifyMaterial();
RpGeometry *pGeom = RpAtomicGetGeometry(pAtomic);
if(pGeom)
{
RwInt32 nMatCount = RpGeometryGetNumMaterials(pGeom);
for(int i = 0; i < nMatCount; i++)
{
RpMaterial *pMaterial = RpGeometryGetMaterial(pGeom, i);
if(pMaterial)
{
CNtlPLCharacter *pCharEntity = pItemEntity->GetOwner();
// get through the proper renderpipe
RpNtlMaterialSetRenderCB(pMaterial, CNtlPLCharacter::fpRenderCB);
if(pTexture)
RpMaterialSetTexture(pMaterial, pTexture);
if(pUVTexture)
{
RpNtlMaterialExtSetUVTransform(pMaterial, pItemEntity->GetUVMatrix() );
RpNtlMaterialExtSetUVTexture(pMaterial, pUVTexture);
}
// DOGI emblem
if((NtlMatExtGetFlag(pMaterial) & rpNTL_MATERIAL_EMBLEM) && !pCharEntity->GetPetrifyMaterial())
{
RpNtlMaterialExtSetEmblemTex(pMaterial, pItemEntity->GetDogiEmblem());
RpNtlMaterialExtSetDogiColor(pMaterial, pItemEntity->GetDogiEditedColor());
}
// DOGI pants
if((NtlMatExtGetFlag(pMaterial) & rpNTL_MATERIAL_DOGI_PANTS) && !pCharEntity->GetPetrifyMaterial())
{
RpNtlMaterialExtSetDogiColor(pMaterial, pItemEntity->GetDogiEditedColor());
}
// DOGI skirt
if((NtlMatExtGetFlag(pMaterial) & rpNTL_MATERIAL_DOGI_SKIRT) && !pCharEntity->GetPetrifyMaterial())
{
RpNtlMaterialExtSetDogiColor(pMaterial, pItemEntity->GetDogiEditedColor());
}
// color
RwRGBAReal sColorReal;
RwRGBARealFromRwRGBA(&sColorReal, pItemEntity->GetColor());
const D3DCAPS9* pD3DCaps = (const D3DCAPS9*)RwD3D9GetCaps();
if(pD3DCaps->MaxSimultaneousTextures <= 4)
{
sColorReal.red = 1.0f;
sColorReal.green = 1.0f;
sColorReal.blue = 1.0f;
}
if(pCharEntity != NULL)
{
if(NtlMatExtGetFlag(pMaterial) & rpNTL_MATERIAL_SKIN_COLOR)
{
RwRGBAReal sSkinColorReal;
RwRGBARealFromRwRGBA(&sSkinColorReal, pCharEntity->GetSkinColor());
RwRGBA sColor;
sColor.red = RwUInt8((sSkinColorReal.red) * 255.f);
sColor.green = RwUInt8((sSkinColorReal.green) * 255.f);
sColor.blue = RwUInt8((sSkinColorReal.blue) * 255.f);
sColor.alpha = pCharEntity->GetColor()->alpha;
RpNtlMaterialExtSetSkinColor(pMaterial, &sColor);
sColorReal.alpha = pCharEntity->GetColor()->alpha / 255.0f;
}
else if((NtlMatExtGetFlag(pMaterial) & rpNTL_MATERIAL_HEAD_COLOR) && !pCharEntity->GetPetrifyMaterial())
{
RwRGBAReal sHeadColorReal;
RwRGBARealFromRwRGBA(&sHeadColorReal, pCharEntity->GetHeadColor());
sColorReal.red = sColorReal.red * sHeadColorReal.red;
sColorReal.green = sColorReal.green * sHeadColorReal.green;
sColorReal.blue = sColorReal.blue * sHeadColorReal.blue;
}
else if((NtlMatExtGetFlag(pMaterial) & rpNTL_MATERIAL_BELT_COLOR) && !pCharEntity->GetPetrifyMaterial())
{
RwRGBAReal DogiClrReal;
RwRGBARealFromRwRGBA(&DogiClrReal, pItemEntity->GetDogiBeltColor());
sColorReal.red = sColorReal.red * DogiClrReal.red;
sColorReal.green = sColorReal.green * DogiClrReal.green;
sColorReal.blue = sColorReal.blue * DogiClrReal.blue;
}
else
{
sColorReal.alpha = static_cast<RwReal>(pCharEntity->GetColor()->alpha / 255.0f);
}
// to highlight a character while selecting
RpNtlMaterialExtSetAddColor(pMaterial, pCharEntity->GetAddColor());
}
else
{
// to highlight a character while selecting
RpNtlMaterialExtSetAddColor(pMaterial, pItemEntity->GetAddColor());
}
RwRGBA sColor;
sColor.red = RwUInt8((sColorReal.red) * 255.f);
sColor.green = RwUInt8((sColorReal.green) * 255.f);
sColor.blue = RwUInt8((sColorReal.blue) * 255.f);
sColor.alpha = RwUInt8((sColorReal.alpha) * pItemEntity->GetWeightAlpha() * 255.f);
RpMaterialSetColor(pMaterial, &sColor);
}
}
}
pTexture = pItemEntity->GetMultiTexture();
if(pTexture)
{
if(pGeom)
{
RpMaterial *pMaterial = RpGeometryGetMaterial(pGeom, 0);
if(pMaterial)
NtlMatExtSetMultiTexture(pMaterial, pTexture);
}
}
// 형석 coding
if(m_SkipAdge)
{
AtomicDefaultRenderCallBack(pAtomic);
}
else
{
SToonData *pToonData = pItemEntity->GetToonData();
if(pToonData->pToonInk)
{
Helper_SetToonAtomicRender( pAtomic, pToonData);
}
if(RpNtlAtomicGetFlag(pAtomic) & NTL_TOON_EDGE_OFF)
{
AtomicDefaultRenderCallBack(pAtomic);
}
else
{
RpNtlAtomicGetRenderCallBack(pAtomic)(pAtomic);
}
}
pItemEntity->SetEMUVController(FALSE);
pItemEntity->RestoreSimpleMaterial();
pItemEntity->RestorePetrifyMaterial();
}
// render MOB, NPC; CNtlPLCharacter::m_pResourceClump
else if(pEntity->GetClassType() == PLENTITY_CHARACTER)
{
CNtlPLCharacter* pCharEntity = (CNtlPLCharacter *)pEntity;
RpGeometry* pGeom = RpAtomicGetGeometry(pAtomic);
RwBool SEMActFlag = RpNtlAtomicGetEnvTexName(pAtomic);
if(pGeom)
{
RwInt32 nMatCount = RpGeometryGetNumMaterials(pGeom);
for(int i = 0; i < nMatCount; i++)
{
RpMaterial *pMaterial = RpGeometryGetMaterial(pGeom, i);
if(pMaterial)
{
// For MOB, NPC, VEHECLE spherical enviroment mapping
if(SEMActFlag)
RpNtlMaterialExtSetEnvMapTexture(pMaterial, pCharEntity->GetSEM());
// simple material
if(pCharEntity->GetSimpleMaterial())
RpNtlMaterialExtSetFlag(pMaterial, RpNtlMaterialExtGetFlag(pMaterial) | rpNTL_MATERIAL_SIMPLEMATERIAL);
else
RpNtlMaterialExtSetFlag(pMaterial, RpNtlMaterialExtGetFlag(pMaterial) & ~rpNTL_MATERIAL_SIMPLEMATERIAL);
// petrify
if(pCharEntity->GetPetrifyMaterial())
RpNtlMaterialExtSetFlag(pMaterial, RpNtlMaterialExtGetFlag(pMaterial) | rpNTL_MATERIAL_PETRIFY);
else
RpNtlMaterialExtSetFlag(pMaterial, RpNtlMaterialExtGetFlag(pMaterial) & ~rpNTL_MATERIAL_PETRIFY);
// get through the proper renderpipe
RpNtlMaterialSetRenderCB(pMaterial, CNtlPLCharacter::fpRenderCB);
RwRGBAReal sColorReal;
RwRGBARealFromRwRGBA(&sColorReal, pCharEntity->GetColor());
// Atomic에 설정된 Alpha 값
RwReal fAtomicAlpha = RpNtlAtomicGetAlpha(pAtomic) / 255.0f;
RwRGBA sColor;
sColor.red = RwUInt8((sColorReal.red)*255.f);
sColor.green = RwUInt8((sColorReal.green)*255.f);
sColor.blue = RwUInt8((sColorReal.blue)*255.f);
sColor.alpha = RwUInt8((sColorReal.alpha)*255.f*fAtomicAlpha);
RpMaterialSetColor(pMaterial, &sColor);
RpNtlMaterialExtSetAddColor(pMaterial, pCharEntity->GetAddColor());
pMaterial->color.alpha = sColor.alpha;
if(NtlMatExtGetFlag(pMaterial) & rpNTL_MATERIAL_SKIN_COLOR)
{
RwRGBAReal sSkinColorReal;
RwRGBARealFromRwRGBA(&sSkinColorReal, pCharEntity->GetSkinColor());
sColor.red = RwUInt8((sSkinColorReal.red) * 255.f);
sColor.green = RwUInt8((sSkinColorReal.green) * 255.f);
sColor.blue = RwUInt8((sSkinColorReal.blue) * 255.f);
sColor.alpha = pCharEntity->GetColor()->alpha;
RpNtlMaterialExtSetSkinColor(pMaterial, &sColor);
}
}
}
}
// 형석 coding
if(m_SkipAdge)
{
AtomicDefaultRenderCallBack(pAtomic);
}
else
{
SToonData *pToonData = pCharEntity->GetToonData();
if(pToonData->pToonInk)
{
Helper_SetToonAtomicRender( pAtomic, pToonData);
}
if(RpNtlAtomicGetFlag(pAtomic) & NTL_TOON_EDGE_OFF)
{
AtomicDefaultRenderCallBack(pAtomic);
}
else
{
RpNtlAtomicGetRenderCallBack(pAtomic)(pAtomic);
}
}
// For MOB, NPC, VEHECLE spherical enviroment mapping
if(SEMActFlag)
{
RwInt32 nMatCount = RpGeometryGetNumMaterials(pGeom);
for(int i = 0; i < nMatCount; i++)
{
RpMaterial *pMaterial = RpGeometryGetMaterial(pGeom, i);
if(pMaterial)
{
RpNtlMaterialExtSetEnvMapTexture(pMaterial, NULL);
}
}
}
}
}
return pAtomic;
}
int CNtlPLCharacter::CallBackBaseAnim(RwUInt32 uiEventData)
{
SEventAnim *pEventAnim = (SEventAnim *)uiEventData;
switch(pEventAnim->eEventID)
{
case EVENT_ANIM_END:
OnEventAnimEnd((SEventAnimEnd*)pEventAnim);
break;
case EVENT_ANIM_HIT:
OnEventHit((SEventAnimHit*)pEventAnim);
break;
case EVENT_ANIM_WEIGHT_TIME:
OnEventWeightTime((SEventWeightTime*)pEventAnim);
break;
case EVENT_ANIM_FOOT_STEP:
OnEventFootStep((SEventFootStep*)pEventAnim);
break;
case EVENT_ANIM_VISUAL_EFFECT:
OnEventVisualEffect((SEventVisualEffect*)pEventAnim);
break;
case EVENT_ANIM_VISUAL_SOUND:
OnEventVisualSound((SEventSound*)pEventAnim);
break;
case EVENT_ANIM_TRACE_EFFECT:
OnEventTraceEffect((SEventTrace*)pEventAnim);
break;
case EVENT_ANIM_SUB_WEAPON:
OnEventSubWeapon((SEventSubWeapon*)pEventAnim);
break;
case EVENT_ANIM_POST_EFFECT:
OnEventPostEffect((SEventPostEffect*)pEventAnim);
break;
case EVENT_ANIM_SUMMON_PET:
OnEventSummonPet((SEventSummonPet*)pEventAnim);
break;
case EVENT_ANIM_ALPHA:
OnEventAlphaFade((SEventAlpha*)pEventAnim);
break;
case EVENT_ANIM_DIRECT:
OnEventDirect((SEventDirect*)pEventAnim);
break;
case EVENT_ANIM_COLOR_CHANGE:
OnEventColorChange((SEventColorChange*)pEventAnim);
break;
case EVENT_ANIM_STRETCH:
OnEventStretch((SEventStretch*)pEventAnim);
break;
case EVENT_ANIM_TRIGGER:
OnEventTrigger((SEventTrigger*)pEventAnim);
break;
case EVENT_ANIM_SKILL_CANCEL:
OnEventSkillCancel((SEventSkillCancel*)pEventAnim);
break;
default:
NTL_ASSERT(TRUE, "Not EventID");
break;
}
return TRUE;
}
void CNtlPLCharacter::OnEventTraceEffect( SEventTrace* pEventTrace )
{
if(!pEventTrace)
return;
if(pEventTrace->eAttachType == SEventTrace::CHARACTER_BONE)
{
CNtlInstanceTraceSystem* pTraceSystem = NTL_NEW CNtlInstanceTraceSystem();
pTraceSystem->Create(pEventTrace, this);
CNtlInstanceEffect* pEffect = NTL_NEW CNtlInstanceEffect();
pEffect->SetName(EFFECT_NAME_TRACE);
pEffect->SetFlags(NTL_PLEFLAG_NOT_PROPERTY_USED);
pEffect->AddComponentSystem(pTraceSystem);
Attach(pEffect);
GetSceneManager()->AddPLEntity(pEffect);
}
else
{
for each(CNtlPLItem* pItem in *(m_pEquipItem->GetEquipItemList()))
{
if(!pItem)
continue;
pItem->ActiveTraceEffect(pEventTrace);
}
}
}
void CNtlPLCharacter::OnEventVisualEffect( SEventVisualEffect* pEventVisualEffect )
{
//Effect Name이 없는 경우는 무조건 Return을 한다.
if( strlen(pEventVisualEffect->chEffectName) <= 0)
return;
if( strlen(pEventVisualEffect->chBoneName) <= 0 &&
pEventVisualEffect->bAttachBone)
return;
if(!pEventVisualEffect->bAttach || pEventVisualEffect->eBoneType == BONE_CHARACTER)
{
// 만약 LoopEffect 리스트에 같은 이름,Bone이 있으면 새로 생성하지 않는다.
if(IsExistLoopEffect(pEventVisualEffect->chEffectName, pEventVisualEffect->chBoneName))
return;
CNtlPLEntity *pPLEntity = GetSceneManager()->CreateEntity(PLENTITY_EFFECT, pEventVisualEffect->chEffectName);
NTL_ASSERT(pPLEntity, __FUNCTION__ << "pPLEntity == NULL");
if(pPLEntity == NULL)
return;
CNtlInstanceEffect *pInstanceEffect = (CNtlInstanceEffect *)pPLEntity;
// 이펙트의 Scale 적용 유무 플래그를 설정한다.
pInstanceEffect->SetApplyScale(pEventVisualEffect->bApplyScale);
pPLEntity->SetScale(GetBaseScale() * m_vScale.x);
//Effect에 Character의 Serial ID를 넣는다.(Client에서 사용을 하기 위해서)
pPLEntity->SetSerialID(GetSerialID());
pInstanceEffect->SetPlayAnimSpeed(m_fAnimSpeed);
// AutoDelete가 아니면 LoopEffect라고 간주하고 리스트에 추가한다
if(!pPLEntity->IsAutoDelete())
{
SLoopEffect* pLoopEffect = NTL_NEW SLoopEffect();
pLoopEffect->pLoopEffectIntance = pInstanceEffect;
pLoopEffect->szBoneName = pEventVisualEffect->chBoneName;
AddLoopEffect(pLoopEffect);
}
if(!pEventVisualEffect->bAttach)
{
RwV3d vPos = GetPosition() + pEventVisualEffect->vOffSetPos;
pInstanceEffect->SetPosition(&vPos);
pInstanceEffect->SetVisible(IsVisible());
}
else if( pEventVisualEffect->bAttachBone)
{
if(pEventVisualEffect->bProjectileType)
{
// 발사체 타입인경우에는 Attach 하지 않는다.
RwMatrix* pMatBone = GetBoneMatrix(pEventVisualEffect->chBoneName);
RwMatrix matEffect;
RwMatrixSetIdentity(&matEffect);
*RwMatrixGetPos(&matEffect) = *RwMatrixGetPos(pMatBone);
*RwMatrixGetAt(&matEffect) = GetDirection();
*RwMatrixGetUp(&matEffect) = GetUp();
*RwMatrixGetRight(&matEffect) = GetRight();
RwMatrixUpdate(&matEffect);
pInstanceEffect->SetMatrix(matEffect);
}
else
{
SPLAttachAttr attachAttr;
attachAttr.vOffsetPos = pEventVisualEffect->vOffSetPos;
AttachBone((CNtlPLAttach *)pPLEntity, pEventVisualEffect->chBoneName, &attachAttr);
}
}
else
{
AttachWorldPosAndRotate((CNtlPLAttach *)pPLEntity, pEventVisualEffect->vOffSetPos);
}
}
else if(pEventVisualEffect->eBoneType == BONE_WEAPON)
{
if(m_pEquipItem)
{
for each(CNtlPLItem* pItem in *(m_pEquipItem->GetEquipItemList()))
{
if(!pItem || pItem->GetProperty()->GetResType() != ITEM_RES_EQUIP_MAIN)
continue;
RwFrame* pFrame = pItem->GetBoneByName(pEventVisualEffect->chBoneName);
if(pFrame)
{
CNtlInstanceEffect* pInstanceEffect = (CNtlInstanceEffect*)GetSceneManager()->CreateEntity(PLENTITY_EFFECT, pEventVisualEffect->chEffectName);
if(!pInstanceEffect)
return;
pItem->AttachVisualEffect(pInstanceEffect, pEventVisualEffect);
break;
}
}
}
}
else if(pEventVisualEffect->eBoneType == BONE_SUB_WEAPON)
{
if(m_pEquipItem)
{
for each(CNtlPLItem* pItem in *(m_pEquipItem->GetEquipItemList()))
{
if(!pItem || pItem->GetProperty()->GetResType() != ITEM_RES_EQUIP_SUB)
continue;
RwFrame* pFrame = pItem->GetBoneByName(pEventVisualEffect->chBoneName);
if(pFrame)
{
CNtlInstanceEffect* pInstanceEffect = (CNtlInstanceEffect*)GetSceneManager()->CreateEntity(PLENTITY_EFFECT, pEventVisualEffect->chEffectName);
if(!pInstanceEffect)
return;
pItem->AttachVisualEffect(pInstanceEffect, pEventVisualEffect);
break;
}
}
}
}
}
void CNtlPLCharacter::OnEventSubWeapon( SEventSubWeapon* pEventSubWeapon )
{
switch(pEventSubWeapon->eSubWeaponActiveFlag)
{
case SUB_WEAPON_ACTIVE:
{
CNtlPLEventGenerator::AnimEventSubWeaponActive(GetSerialID());
break;
}
case SUB_WEAPON_DEACTIVE:
{
CNtlPLEventGenerator::AnimEventSubWeaponDeActive(GetSerialID());
break;
}
}
}
void CNtlPLCharacter::OnEventVisualSound( SEventSound* pEventSound )
{
// Sound를 Play한다.
if(strlen(pEventSound->chSoundName) <= 1)
return ;
// LoopSound이고 이미 기존에 Play되고 있다면 Play하지 않는다.
if(pEventSound->bLoop && IsExistLoopSound(pEventSound->chSoundName))
return ;
// 파일이 여러개 세팅되어 있는경우에는 랜덤으로 플레이된다.
std::string soundFileName;
int nMax = 1;
if(strlen(pEventSound->chSoundName4) > 0)
nMax = 4;
else if(strlen(pEventSound->chSoundName3) > 0)
nMax = 3;
else if(strlen(pEventSound->chSoundName2) > 0)
nMax = 2;
if(nMax > 1)
{
int nRand = NtlRandomNumber(1, nMax);
switch(nRand)
{
case 1:
soundFileName = pEventSound->chSoundName;
break;
case 2:
soundFileName = pEventSound->chSoundName2;
break;
case 3:
soundFileName = pEventSound->chSoundName3;
break;
case 4:
soundFileName = pEventSound->chSoundName4;
break;
}
}
else
{
soundFileName = pEventSound->chSoundName;
}
// 피치를 랜덤으로 선택한다
RwReal fSoundPitch = NtlRandomNumber(pEventSound->fSoundPitchMin, pEventSound->fSoundPitchMax);
sNtlSoundPlayParameta tSoundParam;
tSoundParam.iChannelGroup = pEventSound->eSoundType;
tSoundParam.pcFileName = (char*)soundFileName.c_str();
tSoundParam.bLoop = pEventSound->bLoop;
tSoundParam.fVolume = pEventSound->fSoundVolume * 0.01f;
tSoundParam.fPitch = fSoundPitch;
tSoundParam.fXPos = m_vCurPos.x;
tSoundParam.fYPos = m_vCurPos.y;
tSoundParam.fZPos = m_vCurPos.z;
tSoundParam.fMinDistance = pEventSound->fSoundDist;
tSoundParam.fMaxDistance = pEventSound->fSoundDecayDist;
int iRet = GetSoundManager()->Play(&tSoundParam);
// Loop Sound면 리스트에 추가한다.
if(iRet == SOUNDRESULT_OK && pEventSound->bLoop && tSoundParam.hHandle != INVALID_SOUND_HANDLE)
{
AddLoopSound(tSoundParam.hHandle);
}
}
void CNtlPLCharacter::OnEventWeightTime( SEventWeightTime* pEventTime )
{
CNtlPLEventGenerator::AnimWeightTime(GetSerialID(), pEventTime);
}
void CNtlPLCharacter::OnEventAnimEnd( SEventAnimEnd* pEventAnimEnd )
{
if(m_sBaseAnimPlayInfo.m_uiAnimKey == NML_SPAWN)
{
SetBaseAnimation(NML_IDLE_LOOP);
}
CNtlPLEventGenerator::AnimEnd(GetSerialID(), pEventAnimEnd->uiAnimKey, INVALID_GRAPHIC_ANIMATION_ID);
}
void CNtlPLCharacter::OnEventHit( SEventAnimHit* pEventHit )
{
CNtlPLEventGenerator::AnimHit(GetSerialID(), pEventHit);
}
void CNtlPLCharacter::OnEventPostEffect( SEventPostEffect* pEventPostEffect )
{
// 포스트 이펙트는 타겟을 판별하고, 자신 이외의 다른 캐릭터의 이펙트를 보지 않기 위해서 Simul 레이어에서 처리한다.
CNtlPLEventGenerator::AnimEventPostEffect(GetSerialID(), pEventPostEffect);
}
void CNtlPLCharacter::OnEventSummonPet( SEventSummonPet* pEventSummonPet )
{
CNtlPLEventGenerator::AnimEventSummonActive(GetSerialID());
}
void CNtlPLCharacter::OnEventAlphaFade( SEventAlpha* pEventAlpha )
{
// Atomic Alpha에 관해서만 PL단에서 처리한다.
if(pEventAlpha->eAlphaEventType != SEventAlpha::E_ALPHA_EVENT_ATOMIC)
{
CNtlPLEventGenerator::AnimEventAlpha(GetSerialID(), (void*)pEventAlpha);
return;
}
for(RwUInt32 i = 0; i < m_vecAtomicList.size(); i++)
{
if(Helper_GetBitFlag(pEventAlpha->bfAtomicList, i))
{
RwUInt32 uiRenderFlag = RpNtlAtomicGetFlag(m_vecAtomicList[i]->pData);
RpNtlAtomicSetFlag(m_vecAtomicList[i]->pData, uiRenderFlag | NTL_RUNTIME_ALPHA);
std::string strAtomicName = Helper_AtomicName(m_vecAtomicList[i]->pData);
GetAlphaBlendController()->AddAtomicAlpha(strAtomicName.c_str(),
pEventAlpha->nStartAlpha / 255.0f,
pEventAlpha->nDestAlpha / 255.0f,
pEventAlpha->fFadeTime,
pEventAlpha->fLifeTime, FALSE);
}
}
}
void CNtlPLCharacter::OnEventFootStep( SEventFootStep* pEventFootStep )
{
CNtlPLEventGenerator::AnimFootStep(GetSerialID(), pEventFootStep);
}
void CNtlPLCharacter::OnEventDirect( SEventDirect* pEventDirect )
{
CNtlPLEventGenerator::AnimEventDirect(GetSerialID(), pEventDirect);
}
void CNtlPLCharacter::OnEventColorChange( SEventColorChange* pEventColorChange )
{
CNtlPLEventGenerator::AnimEventColorChange(GetSerialID(), pEventColorChange);
}
void CNtlPLCharacter::OnEventStretch( SEventStretch* pEventStretch )
{
CNtlPLEventGenerator::AnimEventStretch(GetSerialID(), pEventStretch);
}
void CNtlPLCharacter::OnEventTrigger( SEventTrigger* pEventTrigger )
{
CNtlPLEventGenerator::AnimEventTrigger(GetSerialID(), pEventTrigger);
}
void CNtlPLCharacter::OnEventSkillCancel( SEventSkillCancel* pEventSkillCancel )
{
CNtlPLEventGenerator::AnimEventSkillCancel(GetSerialID());
}
void CNtlPLCharacter::SetSkinColor(RwUInt8 byRed, RwUInt8 byGreen, RwUInt8 byBlue)
{
m_sSkinColor.red = byRed;
m_sSkinColor.green = byGreen;
m_sSkinColor.blue = byBlue;
}
void CNtlPLCharacter::SetHeadColor(RwUInt8 byRed, RwUInt8 byGreen, RwUInt8 byBlue)
{
m_sHeadColor.red = byRed;
m_sHeadColor.green = byGreen;
m_sHeadColor.blue = byBlue;
}
void CNtlPLCharacter::SetInkColor(RwUInt8 byRed, RwUInt8 byGreen, RwUInt8 byBlue)
{
if(m_ToonData.pToonInk)
{
m_sInkColor.red = byRed;
m_sInkColor.green = byGreen;
m_sInkColor.blue = byBlue;
}
if( !GetCharScheduleResInfo()->bLoadComplete )
return;
RpToonInkSetColor(m_ToonData.pToonInk, m_sInkColor);
}
void CNtlPLCharacter::SetInkThickness(RwReal fThickness)
{
if( !GetCharScheduleResInfo()->bLoadComplete )
return;
RpToonInkSetOverallThickness(m_ToonData.pToonInk, fThickness);
}
void CNtlPLCharacter::ClearLoopEffect()
{
for each(SLoopEffect* pLoopEffect in m_listLoopEffect)
{
if(pLoopEffect && pLoopEffect->pLoopEffectIntance)
{
// 삭제가 아니라 종료를 시킨다.
pLoopEffect->pLoopEffectIntance->Finish();
}
NTL_DELETE(pLoopEffect);
}
m_listLoopEffect.clear();
}
RwBool CNtlPLCharacter::IsExistLoopEffect(const RwChar* szEffectName, const RwChar* szBoneName)
{
if(!szEffectName || !szBoneName)
return FALSE;
ListLoopEffect::iterator it = m_listLoopEffect.begin();
for(;it != m_listLoopEffect.end(); ++it)
{
SLoopEffect* pLoopEffect = *it;
if(pLoopEffect && pLoopEffect->pLoopEffectIntance)
{
if(strcmp(pLoopEffect->pLoopEffectIntance->GetName(), szEffectName) == 0 &&
strcmp(pLoopEffect->szBoneName, szBoneName) == 0)
{
return TRUE;
}
}
}
return FALSE;
}
void CNtlPLCharacter::ClearLoopSound()
{
ListSoundHandle::iterator it = m_listLoopSound.begin();
for(; it != m_listLoopSound.end(); ++it)
{
SOUND_HANDLE hSound = *it;
GetSoundManager()->Stop(hSound);
}
m_listLoopSound.clear();
}
RwBool CNtlPLCharacter::IsExistLoopSound(RwChar* szSoundName)
{
ListSoundHandle::iterator it = m_listLoopSound.begin();
for(; it != m_listLoopSound.end(); ++it)
{
SOUND_HANDLE hListSound = *it;
if(hListSound == INVALID_SOUND_HANDLE)
continue;
if(_strcmpi(GetSoundManager()->GetSoundName(hListSound),szSoundName) == 0)
{
return TRUE;
}
}
return FALSE;
}
CNtlInstanceEffect* CNtlPLCharacter::AttachLinkEffect(SEventLinkEffect* pEventLinkEffect)
{
if(!pEventLinkEffect)
return FALSE;
return m_LinkEffectInstance.AttachLinkEffect(this, pEventLinkEffect);
}
RwBool CNtlPLCharacter::DetachLinkEffect(CNtlInstanceEffect* pLinkEffect)
{
if(!pLinkEffect)
return FALSE;
return m_LinkEffectInstance.DetachLinkEffect(this, pLinkEffect);
}
void CNtlPLCharacter::SetColor(RwUInt8 byRed, RwUInt8 byGreen, RwUInt8 byBlue)
{
m_sColor.red = byRed;
m_sColor.green = byGreen;
m_sColor.blue = byBlue;
if( !GetCharScheduleResInfo()->bLoadComplete )
return;
if(m_pEquipItem)
m_pEquipItem->SetDefItemColor( byRed, byGreen, byBlue );
}
void CNtlPLCharacter::SetAddColor(RwUInt8 byRed, RwUInt8 byGreen, RwUInt8 byBlue)
{
m_sAddColor.red = byRed;
m_sAddColor.green = byGreen;
m_sAddColor.blue = byBlue;
if( !GetCharScheduleResInfo()->bLoadComplete )
return;
if( m_pEquipItem )
m_pEquipItem->SetDefItemAddColor( byRed, byGreen, byBlue );
}
void CNtlPLCharacter::SetAlpha(RwUInt8 byValue)
{
m_sColor.alpha = byValue;
if( !GetCharScheduleResInfo()->bLoadComplete )
return;
if(m_pEquipItem)
m_pEquipItem->SetDefItemAlpha(byValue);
if( !m_sScheduleResInfo.bPCFlag )
{
if( m_sColor.alpha >= 255 && GetWeightAlpha() >= 1.f)
{
if( !m_bRunTimeAlpha )
return;
m_bRunTimeAlpha = FALSE;
}
else
{
if( m_bRunTimeAlpha )
return;
m_bRunTimeAlpha = TRUE;
}
SetApplyRunTimeAlpha( m_bRunTimeAlpha );
// RW's DXT1 Alpha Attr check
SetDXT1AlphaCheck(m_sColor.alpha);
}
}
void CNtlPLCharacter::SetWeightAlpha(RwReal fWeightValue)
{
CNtlPLAttach::SetWeightAlpha(fWeightValue);
if(m_pEquipItem)
m_pEquipItem->SetDefItemWeightAlpha(fWeightValue);
if( !m_sScheduleResInfo.bPCFlag )
{
if( m_sColor.alpha >= 255 && GetWeightAlpha() >= 1.f)
{
if( !m_bRunTimeAlpha )
return;
m_bRunTimeAlpha = FALSE;
}
else
{
if( m_bRunTimeAlpha )
return;
m_bRunTimeAlpha = TRUE;
}
SetApplyRunTimeAlpha( m_bRunTimeAlpha );
}
}
void CNtlPLCharacter::SetAtomicWeightAlpha( const RwChar *pAtomicName, RwReal fWeightValue )
{
for(RwUInt32 i = 0; i < m_vecAtomicList.size(); i++)
{
if(strcmp(Helper_AtomicName(m_vecAtomicList[i]->pData), pAtomicName) == 0)
{
RwUInt8 byAlpha = (RwUInt8)(fWeightValue * 255.0f);
RpNtlAtomicSetAlpha(m_vecAtomicList[i]->pData, byAlpha);
break;
}
}
}
void CNtlPLCharacter::SetApplyRunTimeAlpha(RwBool bFlag)
{
for(RwUInt32 i = 0; i < m_vecAtomicList.size(); i++)
{
RwUInt32 uiRenderFlag = RpNtlAtomicGetFlag(m_vecAtomicList[i]->pData);
if(bFlag)
RpNtlAtomicSetFlag(m_vecAtomicList[i]->pData, uiRenderFlag | NTL_RUNTIME_ALPHA);
else
RpNtlAtomicSetFlag(m_vecAtomicList[i]->pData, uiRenderFlag & (~NTL_RUNTIME_ALPHA));
}
}
void CNtlPLCharacter::SetVisible(RwBool bVisible)
{
if( !GetCharScheduleResInfo()->bLoadComplete )
{
m_sScheduleResInfo.bVisible = bVisible;
return;
}
if( m_pEquipItem )
{
m_pEquipItem->SetDefItemVisible( bVisible );
}
m_LinkEffectInstance.SetVisible(bVisible);
for each(SLoopEffect* pEffect in m_listLoopEffect)
{
if(pEffect && pEffect->pLoopEffectIntance)
{
pEffect->pLoopEffectIntance->SetVisible(bVisible);
}
}
CNtlPLAttach::SetVisible(bVisible);
}
void CNtlPLCharacter::SetPicking(RwBool bPicking)
{
if(m_pEquipItem)
{
DEFAULT_ITEM_MAP *pmapDefItem = m_pEquipItem->GetDefaultItemList();
DEFAULT_ITEM_MAP_ITER it;
for(it = pmapDefItem->begin(); it != pmapDefItem->end(); it++)
{
(*it).second->SetPicking(bPicking);
}
for each(CNtlPLItem* pItem in *(m_pEquipItem->GetEquipItemList()))
{
if(!pItem)
continue;
pItem->SetPicking(bPicking);
}
}
CNtlPLEntity::SetPicking(bPicking);
}
RwBool CNtlPLCharacter::SetItemGradeEffect( ENtlPLItemGrade eGrade )
{
if(m_pEquipItem)
{
for each(CNtlPLItem* pItem in *(m_pEquipItem->GetEquipItemList()))
{
if(!pItem)
continue;
pItem->SetUpgradeEffect(eGrade);
}
}
return TRUE;
}
RwBool CNtlPLCharacter::IsApplyGroundPitchAngle(void)
{
if(m_pProperty == NULL)
return FALSE;
return m_pProperty->IsApplyNormal();
}
// RwSphere* CNtlPLCharacter::GetBoundingSphere()
// {
// m_BSphereCur.center = GetPosition() + m_BSphere.center;
// m_BSphereCur.radius = m_BSphere.radius;
//
// return &m_BSphereCur;
// }
//
// void CNtlPLCharacter::CalcBoundingSphere()
// {
// m_BSphere.center = GetPosition();
// m_BSphere.radius = 0.0f;
//
// for (RwInt32 iAtomicCnt = 0; iAtomicCnt < (RwInt32)m_vecAtomicList.size(); ++iAtomicCnt)
// {
// RpAtomic* pAtomic = m_vecAtomicList.at(iAtomicCnt)->pData;
// RwSphere* pCurSphere = const_cast<RwSphere*>(RpAtomicGetWorldBoundingSphere(pAtomic));
//
// m_BSphere.center = (m_BSphere.center + pCurSphere->center) * 0.5f;
// m_BSphere.radius = RwV3dLength(&((m_BSphere.center - pCurSphere->center) * 0.5f)) + (m_BSphere.radius < pCurSphere->radius ? pCurSphere->radius : m_BSphere.radius);
// }
//
// m_BSphere.center = m_BSphere.center - GetPosition();
// }
RwSphere* CNtlPLCharacter::GetBoundingSphere()
{
m_BSphereCur.center = GetPosition();
m_BSphereCur.radius = GetMaxExtent() * 0.5f;
m_BSphereCur.center.y += m_BSphereCur.radius;
return &m_BSphereCur;
}
#ifdef dNTL_WORLD_CULLING_NEW
//#include "NtlPLRenderGeometry.h"
RwBool CNtlPLCharacter::CullingTest(RwCamera* pRwCamera, RwUInt16 uiRenderFrame)
{
if (m_uiRenderFrame != uiRenderFrame)
{
if (!CNtlPLEntity::CullingTest(pRwCamera, uiRenderFrame))
{
RwInt32 iNumAtomic = static_cast<RwInt32>(m_vecAtomicList.size());
RwInt32 iFrustumCheck = 0;
RwInt32 iOccluderCheck = 0;
if (GetCharScheduleResInfo()->bLoadComplete && iNumAtomic > 0)
{
if (IsCullingTestAllAtomic())
{
// [m_vecAtomicList.size()]번 Occluder Proxy는 Bounding Sphere다.
for (RwInt32 i = 0; i < iNumAtomic; ++i)
{
#ifdef _DEBUG
++CNtlPLGlobal::m_uiCullTestAtomicCnt;
#endif
RpAtomic* pAtomic = static_cast<RpAtomic*>(m_vecAtomicList.at(i)->pData);
const RwSphere* pSphere = RpAtomicGetWorldBoundingSphere(pAtomic);
if (!CNtlPLGlobal::m_bCollObjVisible && (RpNtlAtomicGetFlag(pAtomic) & NTL_NOT_VISIBLE))
{
++iFrustumCheck;
}
else if (RwCameraFrustumTestSphere(pRwCamera, pSphere) == rwSPHEREOUTSIDE)
{
++iFrustumCheck;
}
else if (OccluderQuery(EOCCLUDER_SPHERE, EPLOCCLUDER_FUNC_CHARACTER, (void*)pSphere, i))
{
++iOccluderCheck;
}
else
{
break;
}
}
}
else
{
RwSphere* pSphere = GetBoundingSphere();
// static RwRGBA clr = { 255, 255, 255 ,255 };
// static RwMatrix mat;
//
// RwMatrixTranslate(&mat, &pSphere->center, rwCOMBINEREPLACE);
// RenderGeometryBillboardSphere(&mat, &clr, pSphere->radius, pRwCamera, TRUE);
#ifdef _DEBUG
++CNtlPLGlobal::m_uiCullTestAtomicCnt;
#endif
if (RwCameraFrustumTestSphere(pRwCamera, pSphere) == rwSPHEREOUTSIDE)
{
iFrustumCheck = iNumAtomic;
}
else if (OccluderQuery(EOCCLUDER_SPHERE, EPLOCCLUDER_FUNC_CHARACTER, (void*)pSphere, iNumAtomic))
{
iOccluderCheck = iNumAtomic;
}
}
}
if (iFrustumCheck >= iNumAtomic)
{
m_uiCullFlags |= NTL_PLEFLAG_CULLED_CAMERA_FRUSTUM_OUT;
}
else if (iFrustumCheck + iOccluderCheck >= iNumAtomic)
{
// Frustum + Occluder 갯수가 Atomic 갯수보다 많다면
// OCCLUDER Flag를 셋팅 한다. 단 OccluderCheck 갯수가 존재해야 하므로, iFrustumCheck >= iNumAtomic를 통과해야만 가능하다.
m_uiCullFlags |= NTL_PLEFLAG_CULLED_OCCLUDER;
}
}
SetCullFlags(m_uiCullFlags);
}
return !IsVisible();
}
#else
RwBool CNtlPLCharacter::CullingTest(RwCamera* pRwCamera)
{
if (!CNtlPLEntity::CullingTest(pRwCamera))
{
RwInt32 iNumAtomic = static_cast<RwInt32>(m_vecAtomicList.size());
if (GetCharScheduleResInfo()->bLoadComplete && iNumAtomic > 0)
{
RwInt32 iFrustumCheck = 0;
RwInt32 iOccluderCheck = 0;
for (RwInt32 i = 0; i < iNumAtomic; ++i)
{
#ifdef _DEBUG
++CNtlPLGlobal::m_uiCullTestAtomicCnt;
#endif
CNtlPLCullingScheduling *pCullScheduling = GetNtlPLCullingScheduler();
if(pCullScheduling)
{
pCullScheduling->IncAtomicOperator(PLENTITY_CHARACTER);
}
RpAtomic* pAtomic = static_cast<RpAtomic*>(m_vecAtomicList.at(i)->pData);
RwSphere* pSphere = &pAtomic->worldBoundingSphere;
#ifdef dNTL_WORLD_TOOL_MODE
if (!CNtlWorldObjVisionAnalyzer::GetInstance()->GetCheck(eNWOVA_VISIBILTITY_DIST))
{
rwObjectSetFlags(pAtomic, rwObjectGetFlags(pAtomic) | rpATOMICRENDER);
continue;
}
#endif
if (RwCameraFrustumTestSphere(pRwCamera, pSphere) == rwSPHEREOUTSIDE)
{
rwObjectSetFlags(pAtomic, rwObjectGetFlags(pAtomic) & (~rpATOMICRENDER));
++iFrustumCheck;
}
else if (OccluderQuery(EOCCLUDER_SPHERE, EPLOCCLUDER_FUNC_CHARACTER, (void*)pSphere, i))
{
rwObjectSetFlags(pAtomic, rwObjectGetFlags(pAtomic) & (~rpATOMICRENDER));
++iOccluderCheck;
}
else
{
rwObjectSetFlags(pAtomic, rwObjectGetFlags(pAtomic) | rpATOMICRENDER);
}
}
if (iFrustumCheck >= iNumAtomic)
{
m_uiCullFlags |= NTL_PLEFLAG_CULLED_CAMERA_FRUSTUM_OUT;
}
else if (iFrustumCheck + iOccluderCheck >= iNumAtomic)
{
// Frustum + Occluder 갯수가 Atomic 갯수보다 많다면
// OCCLUDER Flag를 셋팅 한다. 단 OccluderCheck 갯수가 존재해야 하므로, iFrustumCheck >= iNumAtomic를 통과해야만 가능하다.
m_uiCullFlags |= NTL_PLEFLAG_CULLED_OCCLUDER;
}
}
}
SetCullFlags(m_uiCullFlags);
return static_cast<RwBool>(m_uiCullFlags);
}
#endif
void CNtlPLCharacter::SetCullFlags(RwUInt32 uiFlag, RwBool bCulled)
{
CNtlPLAttach::SetCullFlags(uiFlag, bCulled);
if (m_pEquipItem)
{
m_pEquipItem->SetCullFlags(uiFlag, bCulled);
}
}
void CNtlPLCharacter::SetCullFlags(RwUInt32 uiFlag)
{
CNtlPLAttach::SetCullFlags(uiFlag);
if(m_pEquipItem)
{
m_pEquipItem->SetCullFlags(uiFlag);
}
}
RwReal CNtlPLCharacter::GetAlphaDistance()
{
// 설정이 안되어 있으면 높이의 1.5배를 반환한다.
return m_pProperty->GetAlphaDistance() == 0.0f ? GetHeight() * 1.5f : m_pProperty->GetAlphaDistance();
}
void CNtlPLCharacter::SetDXT1AlphaCheck(RwBool _DXT1AlphaCheck)
{
for(RwUInt32 i = 0; i < m_vecAtomicList.size(); i++)
{
RpGeometry *pGeom = RpAtomicGetGeometry(m_vecAtomicList[i]->pData);
if(pGeom)
{
RwInt32 nMatCount = RpGeometryGetNumMaterials(pGeom);
for(RwInt32 m = 0; m < nMatCount; m++)
{
RpMaterial *pMaterial = RpGeometryGetMaterial(pGeom, m);
if(pMaterial)
{
if(_DXT1AlphaCheck)
RpNtlMaterialExtSetFlag(pMaterial, RpNtlMaterialExtGetFlag(pMaterial) | rpNTL_MATERIAL_DXT1_ALPHA_CHECK);
else
RpNtlMaterialExtSetFlag(pMaterial, RpNtlMaterialExtGetFlag(pMaterial) & ~rpNTL_MATERIAL_DXT1_ALPHA_CHECK);
}
}
}
}
}
VOID CNtlPLCharacter::SetPetrifyMaterial(RwBool _PetrifyFlag)
{
// NPC, MOB
m_PetrifySkillActivated = _PetrifyFlag;
// Avatars
if(m_pEquipItem)
m_pEquipItem->SetPetrifyMaterial(_PetrifyFlag);
// Link Effects
m_LinkEffectInstance.SetVisible(!_PetrifyFlag);
}
void CNtlPLCharacter::SetSimpleMaterial(RwBool _SimpleMaterial)
{
// NPC, MOB
m_SimpleMaterial = _SimpleMaterial;
// Avatars
if(m_pEquipItem)
m_pEquipItem->SetSimpleMaterial(_SimpleMaterial);
}
void CNtlPLCharacter::fpRenderCB(void* _pParam)
{
MatExtInfoTag* pParam = static_cast<MatExtInfoTag*>(_pParam);
if(!m_SkipSimpleMaterial && (RpNtlMaterialExtGetFlag(pParam->pMaterial) & rpNTL_MATERIAL_SIMPLEMATERIAL))
{
CNtlPLCharMeshRenderPipeFarAway::GetInstance()->Execute(_pParam);
}
else
{
const D3DCAPS9* pD3DCaps = (const D3DCAPS9*)RwD3D9GetCaps();
if(pD3DCaps->MaxSimultaneousTextures > 4)
{
CNtlPLCharMeshRenderPipe01::GetInstance()->Execute(_pParam);
}
else
{
CNtlPLCharMeshRenderPipe00::GetInstance()->Execute(_pParam);
}
}
}
RwChar* CNtlPLCharacter::GetBoneName( int nBoneIndex )
{
if(nBoneIndex < 0)
return NULL;
RwFrame* pFrame = m_pBaseHierarchy->pNodeInfo[nBoneIndex].pFrame;
if(!pFrame)
return NULL;
RwChar* sBoneName = Helper_BoneName(pFrame);
return sBoneName;
}
void CNtlPLCharacter::SetSBoneStretchTargetPos( const RwV3d& vTargetPos, const RwChar* szAxisBone )
{
m_vBoneStretchTargetPos = vTargetPos;
sprintf_s(m_szBoneStretchAxisBone, "%s", szAxisBone);
}
void CNtlPLCharacter::UpdateMaterialSkinInfo()
{
for(RwUInt32 i = 0; i < m_vecAtomicList.size(); i++)
{
RpAtomic *pAtomic = m_vecAtomicList[i]->pData;
Helper_SetAtomicAllMaterialSkinInfo(pAtomic);
}
}
void CNtlPLCharacter::OnAfterAnimEventRun()
{
m_AnimLayer[CHARACTER_ANIM_LAYER_BASE].OnAfterAnimEventRun();
}
VOID CNtlPLCharacter::ToggleEMUVAni(RwBool _Visibility)
{
CNtlPLCharMeshRenderPipe::ToggleEMUVAni(_Visibility);
}
RwBool CNtlPLCharacter::IsCullingTestAllAtomic()
{
STypeAnimData *pTypeAnimData = m_pProperty->GetAnimTable()->Get(GetCurBaseAnimKey());
if(!pTypeAnimData)
return TRUE;
return pTypeAnimData->IsCullTestAllAtomic();
} | [
"sahino1996@hotmail.de"
] | sahino1996@hotmail.de |
36657b75d4f4a65ecd20c93e1d1eac131de6c48a | 3701a92adf71dcb239da026e9dbb97c0978156d3 | /rtmp/rtmp_ffmpeg/app/src/main/cpp/ffmpeg_rtmp.cpp | 7964475fa00a968d2f1091910e5c602ae1d2bd5a | [] | no_license | ColonelDarcy2018/excelsior | b1398e7ac690aacf4c75b5607a8693d3a7062a86 | 77a14e4ebcb616d987ae2c3bd13d6beceda56619 | refs/heads/master | 2023-08-08T03:26:21.395974 | 2023-07-28T09:12:04 | 2023-07-28T09:12:04 | 239,725,108 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,532 | cpp | #include "ffmpeg_common.h"
///摄像头Rtmp推流开始
AVFormatContext *ofmt_ctx;
AVCodecContext *codec_ctx;
AVStream *av_stm;
int yuv_width;
int yuv_height;
int y_length;
int uv_length;
int fps = 15;
/**
* 初始化
* @param env
* @param thiz
* @param url 输出路径/rtmp推流地址
* @param width
* @param height
* @return
*/
extern "C"
JNIEXPORT jint JNICALL
Java_com_itexcelsior_as_x_rtmp_camera_FFmpegRtmpCameraNative_initVideo(JNIEnv *env, jobject thiz,
jstring _url, jint _width,
jint _height) {
const char *out_path = env->GetStringUTFChars(_url, 0);
logd(out_path);
int width = _width;
int height = _height;
//计算yuv数据的长度
yuv_width = width;
yuv_height = height;
y_length = width * height;
uv_length = width * height / 4;
int ret;
//注册全部设备
av_register_all();
//Do global initialization of network components
// avformat_network_init();
//初始化编解码器
AVCodec *codec = avcodec_find_encoder(AV_CODEC_ID_H264);
if (!codec) {
loge("Can not find encoder!\n");
return -1;
}
//为输出格式分配AVFormatContext 初始化输出编码上下文
avformat_alloc_output_context2(&ofmt_ctx, NULL, "flv", out_path);
//获取编码器上下文
codec_ctx = avcodec_alloc_context3(codec);
//编码器的ID号,这里为264编码器,可以根据video_st里的codecID 参数赋值
codec_ctx->codec_id = codec->id;
//像素的格式,也就是说采用什么样的色彩空间来表明一个像素点
codec_ctx->pix_fmt = AV_PIX_FMT_YUV420P;
// codec_ctx->pix_fmt = AV_PIX_FMT_NV21;
//编码器编码的数据类型
codec_ctx->codec_type = AVMEDIA_TYPE_VIDEO;
//编码目标的视频帧大小,以像素为单位
codec_ctx->width = width;
codec_ctx->height = height;
codec_ctx->framerate = (AVRational) {fps, 1};
//帧率的基本单位
codec_ctx->time_base = (AVRational) {1, fps};
//目标的码率,即采样的码率;
codec_ctx->bit_rate = 400000;
//50
codec_ctx->gop_size = 50;
/* Some formats want stream headers to be separate. */
if (ofmt_ctx->oformat->flags & AVFMT_GLOBALHEADER)
codec_ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
codec_ctx->qcompress = 0.6; ///< amount of qscale change between easy & hard scenes (0.0-1.0)
//最大和最小量化系数
codec_ctx->qmin = 10;
codec_ctx->qmax = 51;
//B帧
codec_ctx->max_b_frames = 0;
// Set H264 preset and tune
AVDictionary *param = 0;
/**
* 这个非常重要,如果不设置延时非常的大
* ultrafast,superfast, veryfast, faster, fast, medium
* slow, slower, veryslow, placebo. 这是x264编码速度的选项
*/
av_dict_set(¶m, "preset", "superfast", 0);
av_dict_set(¶m, "tune", "zerolatency", 0);
///Initialize the AVCodecContext to use the given AVCodec
ret=avcodec_open2(codec_ctx,codec,¶m);
if (ret<0){
loge("Failed to open encoder!\n");
avError(ret);
return -1;
}
//Add a new stream to output
av_stm=avformat_new_stream(ofmt_ctx,codec);
if (av_stm == NULL){
loge("添加流失败,返回NULL");
return -1;
}
av_stm->time_base.num=1;
av_stm->time_base.den=fps;
av_stm->codecpar->codec_tag=0;
avcodec_parameters_from_context(av_stm->codecpar,codec_ctx);
ret=avio_open(&ofmt_ctx->pb,out_path,AVIO_FLAG_READ_WRITE);
if (ret<0){
loge("Failed to open output file! \n");
avError(ret);
return -1;
}
avformat_write_header(ofmt_ctx,NULL);
return 0;
}
//This structure describes decoded (raw) audio or video data
AVFrame *av_frm;
int count=0;
AVPacket av_pkt;
/**
* H264编码视频流并输出
*/
extern "C"
JNIEXPORT jint JNICALL
Java_com_itexcelsior_as_x_rtmp_camera_FFmpegRtmpCameraNative_encodeFrame(JNIEnv *env, jobject thiz,
jbyteArray _buffer) {
// int64_t start_time=av_gettime();
jbyte *in=env->GetByteArrayElements(_buffer,NULL);
int ret=0;
///Allocate an AVFrame and set its fields to default values.
av_frm=av_frame_alloc();
///Return the size in bytes of the amount of data required to store an image with the given parameters.
int picture_size=av_image_get_buffer_size(codec_ctx->pix_fmt,codec_ctx->width,codec_ctx->height,1);
///Allocate a memory block with alignment suitable for all memory accesses (including vectors if available on the CPU).
uint8_t *buffers= (uint8_t *)av_malloc(picture_size);
av_image_fill_arrays(av_frm->data,av_frm->linesize,buffers,codec_ctx->pix_fmt,codec_ctx->width,codec_ctx->height,1);
//安卓摄像头数据为NV21格式,此处将其转换为YUV420P格式
//复制Y分量的数据
memcpy(av_frm->data[0],in,y_length);
///Presentation timestamp in time_base units (time when frame should be shown to user).
av_frm->pts=count;
for (int i = 0; i < uv_length; i++) {
//将v数据存到第三个平面
*(av_frm->data[2] + i) = *(in + y_length + i * 2);
//将U数据存到第二个平面
*(av_frm->data[1] + i) = *(in + y_length + i * 2 + 1);
}
av_frm->format=AV_PIX_FMT_YUV420P;
av_frm->width=yuv_width;
av_frm->height=yuv_height;
//例如对于H.264来说。1个AVPacket的data通常对应一个NAL
//初始化AVPacket
av_init_packet(&av_pkt);
//开始编码YUV数据
ret=avcodec_send_frame(codec_ctx,av_frm);
if (ret!=0){
logw("avcodec_send_frame error");
avError(ret);
return -1;
}
//获取编码后的数据
ret=avcodec_receive_packet(codec_ctx,&av_pkt);
//释放编码前的YUV数据
av_frame_free(&av_frm);
if (ret != 0 || av_pkt.size<= 0){
loge("avcodec_receive_packet error");
avError(ret);
return -2;
}
av_pkt.stream_index=av_stm->index; /**< stream index in AVFormatContext */
AVRational time_base= ofmt_ctx->streams[0]->time_base;
av_pkt.pts=count*(av_stm->time_base.den)/((av_stm->time_base.num)*fps);
av_pkt.dts=av_pkt.pts;
av_pkt.duration = (av_stm->time_base.den)/((av_stm->time_base.num)*fps);
__android_log_print(ANDROID_LOG_WARN, "zxw",
"index:%d,pts:%lld,dts:%lld,duration:%lld,time_base:%d,%d",
count,
(long long) av_pkt.pts,
(long long) av_pkt.dts,
(long long) av_pkt.duration,
time_base.num, time_base.den);
av_pkt.pos=-1;
ret=av_interleaved_write_frame(ofmt_ctx,&av_pkt);///Write a packet to an output media file ensuring correct interleaving.
if (ret != 0) {
loge("av_interleaved_write_frame failed");
avError(ret);
}
// av_packet_unref(&av_pkt);
count++;
env->ReleaseByteArrayElements(_buffer,in,0);
return 0;
}
///摄像头Rtmp推流结束
extern "C"
JNIEXPORT jint JNICALL
Java_com_itexcelsior_as_x_rtmp_camera_FFmpegRtmpCameraNative_close(JNIEnv *env, jobject thiz) {
if (av_stm)
avcodec_close(av_stm->codec);
if (ofmt_ctx) {
avio_close(ofmt_ctx->pb);
avformat_free_context(ofmt_ctx);
ofmt_ctx = NULL;
}
return 0;
}
| [
"excelsior2018@163.com"
] | excelsior2018@163.com |
744bf4476bfef1b9bc84ef6447306265909a498c | a218f97bf76618932df94dd3df1f25b4ac820cc4 | /DXEngine06_WVP/DXUtil.cpp | ce554779db66940ba577c76d976dba6a7e70563b | [] | no_license | Oboon2/Graphics | efb398a57a8284b70b23dfab0d76e363003d3b3a | 85be600e911205732044933a41a987ee70f43a8d | refs/heads/master | 2020-08-27T17:52:38.668193 | 2019-10-25T04:24:20 | 2019-10-25T04:24:20 | 194,786,716 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 238 | cpp | #include "DXUtil.h"
bool IsError(HRESULT hr, LPCTSTR msg)
{
// 오류가 있으면 오류 메시지 보여주는 메시지 창 띄우기
if (hr < 0)
{
MessageBox(NULL, msg, TEXT("오류"), MB_OK);
return true;
}
return false;
}
| [
"42952414+Oboon2@users.noreply.github.com"
] | 42952414+Oboon2@users.noreply.github.com |
9da7859fefa1833ef103c9d8ce0827bd8e70b540 | 1880ae99db197e976c87ba26eb23a20248e8ee51 | /iai/include/tencentcloud/iai/v20200303/model/SearchFacesRequest.h | 13912121f631e67efb382c4d10437a4f32fb24c1 | [
"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 | 23,541 | 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_IAI_V20200303_MODEL_SEARCHFACESREQUEST_H_
#define TENCENTCLOUD_IAI_V20200303_MODEL_SEARCHFACESREQUEST_H_
#include <string>
#include <vector>
#include <map>
#include <tencentcloud/core/AbstractModel.h>
namespace TencentCloud
{
namespace Iai
{
namespace V20200303
{
namespace Model
{
/**
* SearchFaces请求参数结构体
*/
class SearchFacesRequest : public AbstractModel
{
public:
SearchFacesRequest();
~SearchFacesRequest() = default;
std::string ToJsonString() const;
/**
* 获取希望搜索的人员库列表,上限100个。数组元素取值为创建人员库接口中的GroupId。
不可同时搜索不同算法模型版本(FaceModelVersion)的人员库。
* @return GroupIds 希望搜索的人员库列表,上限100个。数组元素取值为创建人员库接口中的GroupId。
不可同时搜索不同算法模型版本(FaceModelVersion)的人员库。
*/
std::vector<std::string> GetGroupIds() const;
/**
* 设置希望搜索的人员库列表,上限100个。数组元素取值为创建人员库接口中的GroupId。
不可同时搜索不同算法模型版本(FaceModelVersion)的人员库。
* @param GroupIds 希望搜索的人员库列表,上限100个。数组元素取值为创建人员库接口中的GroupId。
不可同时搜索不同算法模型版本(FaceModelVersion)的人员库。
*/
void SetGroupIds(const std::vector<std::string>& _groupIds);
/**
* 判断参数 GroupIds 是否已赋值
* @return GroupIds 是否已赋值
*/
bool GroupIdsHasBeenSet() const;
/**
* 获取图片 base64 数据,base64 编码后大小不可超过5M。
jpg格式长边像素不可超过4000,其他格式图片长边像素不可超2000。
支持PNG、JPG、JPEG、BMP,不支持 GIF 图片。
* @return Image 图片 base64 数据,base64 编码后大小不可超过5M。
jpg格式长边像素不可超过4000,其他格式图片长边像素不可超2000。
支持PNG、JPG、JPEG、BMP,不支持 GIF 图片。
*/
std::string GetImage() const;
/**
* 设置图片 base64 数据,base64 编码后大小不可超过5M。
jpg格式长边像素不可超过4000,其他格式图片长边像素不可超2000。
支持PNG、JPG、JPEG、BMP,不支持 GIF 图片。
* @param Image 图片 base64 数据,base64 编码后大小不可超过5M。
jpg格式长边像素不可超过4000,其他格式图片长边像素不可超2000。
支持PNG、JPG、JPEG、BMP,不支持 GIF 图片。
*/
void SetImage(const std::string& _image);
/**
* 判断参数 Image 是否已赋值
* @return Image 是否已赋值
*/
bool ImageHasBeenSet() const;
/**
* 获取图片的 Url 。对应图片 base64 编码后大小不可超过5M。
jpg格式长边像素不可超过4000,其他格式图片长边像素不可超2000。
Url、Image必须提供一个,如果都提供,只使用 Url。
图片存储于腾讯云的Url可保障更高下载速度和稳定性,建议图片存储于腾讯云。
非腾讯云存储的Url速度和稳定性可能受一定影响。
支持PNG、JPG、JPEG、BMP,不支持 GIF 图片。
* @return Url 图片的 Url 。对应图片 base64 编码后大小不可超过5M。
jpg格式长边像素不可超过4000,其他格式图片长边像素不可超2000。
Url、Image必须提供一个,如果都提供,只使用 Url。
图片存储于腾讯云的Url可保障更高下载速度和稳定性,建议图片存储于腾讯云。
非腾讯云存储的Url速度和稳定性可能受一定影响。
支持PNG、JPG、JPEG、BMP,不支持 GIF 图片。
*/
std::string GetUrl() const;
/**
* 设置图片的 Url 。对应图片 base64 编码后大小不可超过5M。
jpg格式长边像素不可超过4000,其他格式图片长边像素不可超2000。
Url、Image必须提供一个,如果都提供,只使用 Url。
图片存储于腾讯云的Url可保障更高下载速度和稳定性,建议图片存储于腾讯云。
非腾讯云存储的Url速度和稳定性可能受一定影响。
支持PNG、JPG、JPEG、BMP,不支持 GIF 图片。
* @param Url 图片的 Url 。对应图片 base64 编码后大小不可超过5M。
jpg格式长边像素不可超过4000,其他格式图片长边像素不可超2000。
Url、Image必须提供一个,如果都提供,只使用 Url。
图片存储于腾讯云的Url可保障更高下载速度和稳定性,建议图片存储于腾讯云。
非腾讯云存储的Url速度和稳定性可能受一定影响。
支持PNG、JPG、JPEG、BMP,不支持 GIF 图片。
*/
void SetUrl(const std::string& _url);
/**
* 判断参数 Url 是否已赋值
* @return Url 是否已赋值
*/
bool UrlHasBeenSet() const;
/**
* 获取最多识别的人脸数目。默认值为1(仅检测图片中面积最大的那张人脸),最大值为10。
MaxFaceNum用于,当输入的待识别图片包含多张人脸时,设定要搜索的人脸的数量。
例:输入的Image或Url中的图片包含多张人脸,设MaxFaceNum=5,则会识别图片中面积最大的5张人脸。
* @return MaxFaceNum 最多识别的人脸数目。默认值为1(仅检测图片中面积最大的那张人脸),最大值为10。
MaxFaceNum用于,当输入的待识别图片包含多张人脸时,设定要搜索的人脸的数量。
例:输入的Image或Url中的图片包含多张人脸,设MaxFaceNum=5,则会识别图片中面积最大的5张人脸。
*/
uint64_t GetMaxFaceNum() const;
/**
* 设置最多识别的人脸数目。默认值为1(仅检测图片中面积最大的那张人脸),最大值为10。
MaxFaceNum用于,当输入的待识别图片包含多张人脸时,设定要搜索的人脸的数量。
例:输入的Image或Url中的图片包含多张人脸,设MaxFaceNum=5,则会识别图片中面积最大的5张人脸。
* @param MaxFaceNum 最多识别的人脸数目。默认值为1(仅检测图片中面积最大的那张人脸),最大值为10。
MaxFaceNum用于,当输入的待识别图片包含多张人脸时,设定要搜索的人脸的数量。
例:输入的Image或Url中的图片包含多张人脸,设MaxFaceNum=5,则会识别图片中面积最大的5张人脸。
*/
void SetMaxFaceNum(const uint64_t& _maxFaceNum);
/**
* 判断参数 MaxFaceNum 是否已赋值
* @return MaxFaceNum 是否已赋值
*/
bool MaxFaceNumHasBeenSet() const;
/**
* 获取人脸长和宽的最小尺寸,单位为像素。默认为34。低于34的人脸图片无法被识别。建议设置为80。
* @return MinFaceSize 人脸长和宽的最小尺寸,单位为像素。默认为34。低于34的人脸图片无法被识别。建议设置为80。
*/
uint64_t GetMinFaceSize() const;
/**
* 设置人脸长和宽的最小尺寸,单位为像素。默认为34。低于34的人脸图片无法被识别。建议设置为80。
* @param MinFaceSize 人脸长和宽的最小尺寸,单位为像素。默认为34。低于34的人脸图片无法被识别。建议设置为80。
*/
void SetMinFaceSize(const uint64_t& _minFaceSize);
/**
* 判断参数 MinFaceSize 是否已赋值
* @return MinFaceSize 是否已赋值
*/
bool MinFaceSizeHasBeenSet() const;
/**
* 获取单张被识别的人脸返回的最相似人员数量。默认值为5,最大值为100。
例,设MaxFaceNum为1,MaxPersonNum为8,则返回Top8相似的人员信息。
值越大,需要处理的时间越长。建议不要超过10。
* @return MaxPersonNum 单张被识别的人脸返回的最相似人员数量。默认值为5,最大值为100。
例,设MaxFaceNum为1,MaxPersonNum为8,则返回Top8相似的人员信息。
值越大,需要处理的时间越长。建议不要超过10。
*/
uint64_t GetMaxPersonNum() const;
/**
* 设置单张被识别的人脸返回的最相似人员数量。默认值为5,最大值为100。
例,设MaxFaceNum为1,MaxPersonNum为8,则返回Top8相似的人员信息。
值越大,需要处理的时间越长。建议不要超过10。
* @param MaxPersonNum 单张被识别的人脸返回的最相似人员数量。默认值为5,最大值为100。
例,设MaxFaceNum为1,MaxPersonNum为8,则返回Top8相似的人员信息。
值越大,需要处理的时间越长。建议不要超过10。
*/
void SetMaxPersonNum(const uint64_t& _maxPersonNum);
/**
* 判断参数 MaxPersonNum 是否已赋值
* @return MaxPersonNum 是否已赋值
*/
bool MaxPersonNumHasBeenSet() const;
/**
* 获取是否返回人员具体信息。0 为关闭,1 为开启。默认为 0。其他非0非1值默认为0
* @return NeedPersonInfo 是否返回人员具体信息。0 为关闭,1 为开启。默认为 0。其他非0非1值默认为0
*/
int64_t GetNeedPersonInfo() const;
/**
* 设置是否返回人员具体信息。0 为关闭,1 为开启。默认为 0。其他非0非1值默认为0
* @param NeedPersonInfo 是否返回人员具体信息。0 为关闭,1 为开启。默认为 0。其他非0非1值默认为0
*/
void SetNeedPersonInfo(const int64_t& _needPersonInfo);
/**
* 判断参数 NeedPersonInfo 是否已赋值
* @return NeedPersonInfo 是否已赋值
*/
bool NeedPersonInfoHasBeenSet() const;
/**
* 获取图片质量控制。
0: 不进行控制;
1:较低的质量要求,图像存在非常模糊,眼睛鼻子嘴巴遮挡至少其中一种或多种的情况;
2: 一般的质量要求,图像存在偏亮,偏暗,模糊或一般模糊,眉毛遮挡,脸颊遮挡,下巴遮挡,至少其中三种的情况;
3: 较高的质量要求,图像存在偏亮,偏暗,一般模糊,眉毛遮挡,脸颊遮挡,下巴遮挡,其中一到两种的情况;
4: 很高的质量要求,各个维度均为最好或最多在某一维度上存在轻微问题;
默认 0。
若图片质量不满足要求,则返回结果中会提示图片质量检测不符要求。
* @return QualityControl 图片质量控制。
0: 不进行控制;
1:较低的质量要求,图像存在非常模糊,眼睛鼻子嘴巴遮挡至少其中一种或多种的情况;
2: 一般的质量要求,图像存在偏亮,偏暗,模糊或一般模糊,眉毛遮挡,脸颊遮挡,下巴遮挡,至少其中三种的情况;
3: 较高的质量要求,图像存在偏亮,偏暗,一般模糊,眉毛遮挡,脸颊遮挡,下巴遮挡,其中一到两种的情况;
4: 很高的质量要求,各个维度均为最好或最多在某一维度上存在轻微问题;
默认 0。
若图片质量不满足要求,则返回结果中会提示图片质量检测不符要求。
*/
uint64_t GetQualityControl() const;
/**
* 设置图片质量控制。
0: 不进行控制;
1:较低的质量要求,图像存在非常模糊,眼睛鼻子嘴巴遮挡至少其中一种或多种的情况;
2: 一般的质量要求,图像存在偏亮,偏暗,模糊或一般模糊,眉毛遮挡,脸颊遮挡,下巴遮挡,至少其中三种的情况;
3: 较高的质量要求,图像存在偏亮,偏暗,一般模糊,眉毛遮挡,脸颊遮挡,下巴遮挡,其中一到两种的情况;
4: 很高的质量要求,各个维度均为最好或最多在某一维度上存在轻微问题;
默认 0。
若图片质量不满足要求,则返回结果中会提示图片质量检测不符要求。
* @param QualityControl 图片质量控制。
0: 不进行控制;
1:较低的质量要求,图像存在非常模糊,眼睛鼻子嘴巴遮挡至少其中一种或多种的情况;
2: 一般的质量要求,图像存在偏亮,偏暗,模糊或一般模糊,眉毛遮挡,脸颊遮挡,下巴遮挡,至少其中三种的情况;
3: 较高的质量要求,图像存在偏亮,偏暗,一般模糊,眉毛遮挡,脸颊遮挡,下巴遮挡,其中一到两种的情况;
4: 很高的质量要求,各个维度均为最好或最多在某一维度上存在轻微问题;
默认 0。
若图片质量不满足要求,则返回结果中会提示图片质量检测不符要求。
*/
void SetQualityControl(const uint64_t& _qualityControl);
/**
* 判断参数 QualityControl 是否已赋值
* @return QualityControl 是否已赋值
*/
bool QualityControlHasBeenSet() const;
/**
* 获取出参Score中,只有超过FaceMatchThreshold值的结果才会返回。默认为0。
* @return FaceMatchThreshold 出参Score中,只有超过FaceMatchThreshold值的结果才会返回。默认为0。
*/
double GetFaceMatchThreshold() const;
/**
* 设置出参Score中,只有超过FaceMatchThreshold值的结果才会返回。默认为0。
* @param FaceMatchThreshold 出参Score中,只有超过FaceMatchThreshold值的结果才会返回。默认为0。
*/
void SetFaceMatchThreshold(const double& _faceMatchThreshold);
/**
* 判断参数 FaceMatchThreshold 是否已赋值
* @return FaceMatchThreshold 是否已赋值
*/
bool FaceMatchThresholdHasBeenSet() const;
/**
* 获取是否开启图片旋转识别支持。0为不开启,1为开启。默认为0。本参数的作用为,当图片中的人脸被旋转且图片没有exif信息时,如果不开启图片旋转识别支持则无法正确检测、识别图片中的人脸。若您确认图片包含exif信息或者您确认输入图中人脸不会出现被旋转情况,请不要开启本参数。开启后,整体耗时将可能增加数百毫秒。
* @return NeedRotateDetection 是否开启图片旋转识别支持。0为不开启,1为开启。默认为0。本参数的作用为,当图片中的人脸被旋转且图片没有exif信息时,如果不开启图片旋转识别支持则无法正确检测、识别图片中的人脸。若您确认图片包含exif信息或者您确认输入图中人脸不会出现被旋转情况,请不要开启本参数。开启后,整体耗时将可能增加数百毫秒。
*/
uint64_t GetNeedRotateDetection() const;
/**
* 设置是否开启图片旋转识别支持。0为不开启,1为开启。默认为0。本参数的作用为,当图片中的人脸被旋转且图片没有exif信息时,如果不开启图片旋转识别支持则无法正确检测、识别图片中的人脸。若您确认图片包含exif信息或者您确认输入图中人脸不会出现被旋转情况,请不要开启本参数。开启后,整体耗时将可能增加数百毫秒。
* @param NeedRotateDetection 是否开启图片旋转识别支持。0为不开启,1为开启。默认为0。本参数的作用为,当图片中的人脸被旋转且图片没有exif信息时,如果不开启图片旋转识别支持则无法正确检测、识别图片中的人脸。若您确认图片包含exif信息或者您确认输入图中人脸不会出现被旋转情况,请不要开启本参数。开启后,整体耗时将可能增加数百毫秒。
*/
void SetNeedRotateDetection(const uint64_t& _needRotateDetection);
/**
* 判断参数 NeedRotateDetection 是否已赋值
* @return NeedRotateDetection 是否已赋值
*/
bool NeedRotateDetectionHasBeenSet() const;
private:
/**
* 希望搜索的人员库列表,上限100个。数组元素取值为创建人员库接口中的GroupId。
不可同时搜索不同算法模型版本(FaceModelVersion)的人员库。
*/
std::vector<std::string> m_groupIds;
bool m_groupIdsHasBeenSet;
/**
* 图片 base64 数据,base64 编码后大小不可超过5M。
jpg格式长边像素不可超过4000,其他格式图片长边像素不可超2000。
支持PNG、JPG、JPEG、BMP,不支持 GIF 图片。
*/
std::string m_image;
bool m_imageHasBeenSet;
/**
* 图片的 Url 。对应图片 base64 编码后大小不可超过5M。
jpg格式长边像素不可超过4000,其他格式图片长边像素不可超2000。
Url、Image必须提供一个,如果都提供,只使用 Url。
图片存储于腾讯云的Url可保障更高下载速度和稳定性,建议图片存储于腾讯云。
非腾讯云存储的Url速度和稳定性可能受一定影响。
支持PNG、JPG、JPEG、BMP,不支持 GIF 图片。
*/
std::string m_url;
bool m_urlHasBeenSet;
/**
* 最多识别的人脸数目。默认值为1(仅检测图片中面积最大的那张人脸),最大值为10。
MaxFaceNum用于,当输入的待识别图片包含多张人脸时,设定要搜索的人脸的数量。
例:输入的Image或Url中的图片包含多张人脸,设MaxFaceNum=5,则会识别图片中面积最大的5张人脸。
*/
uint64_t m_maxFaceNum;
bool m_maxFaceNumHasBeenSet;
/**
* 人脸长和宽的最小尺寸,单位为像素。默认为34。低于34的人脸图片无法被识别。建议设置为80。
*/
uint64_t m_minFaceSize;
bool m_minFaceSizeHasBeenSet;
/**
* 单张被识别的人脸返回的最相似人员数量。默认值为5,最大值为100。
例,设MaxFaceNum为1,MaxPersonNum为8,则返回Top8相似的人员信息。
值越大,需要处理的时间越长。建议不要超过10。
*/
uint64_t m_maxPersonNum;
bool m_maxPersonNumHasBeenSet;
/**
* 是否返回人员具体信息。0 为关闭,1 为开启。默认为 0。其他非0非1值默认为0
*/
int64_t m_needPersonInfo;
bool m_needPersonInfoHasBeenSet;
/**
* 图片质量控制。
0: 不进行控制;
1:较低的质量要求,图像存在非常模糊,眼睛鼻子嘴巴遮挡至少其中一种或多种的情况;
2: 一般的质量要求,图像存在偏亮,偏暗,模糊或一般模糊,眉毛遮挡,脸颊遮挡,下巴遮挡,至少其中三种的情况;
3: 较高的质量要求,图像存在偏亮,偏暗,一般模糊,眉毛遮挡,脸颊遮挡,下巴遮挡,其中一到两种的情况;
4: 很高的质量要求,各个维度均为最好或最多在某一维度上存在轻微问题;
默认 0。
若图片质量不满足要求,则返回结果中会提示图片质量检测不符要求。
*/
uint64_t m_qualityControl;
bool m_qualityControlHasBeenSet;
/**
* 出参Score中,只有超过FaceMatchThreshold值的结果才会返回。默认为0。
*/
double m_faceMatchThreshold;
bool m_faceMatchThresholdHasBeenSet;
/**
* 是否开启图片旋转识别支持。0为不开启,1为开启。默认为0。本参数的作用为,当图片中的人脸被旋转且图片没有exif信息时,如果不开启图片旋转识别支持则无法正确检测、识别图片中的人脸。若您确认图片包含exif信息或者您确认输入图中人脸不会出现被旋转情况,请不要开启本参数。开启后,整体耗时将可能增加数百毫秒。
*/
uint64_t m_needRotateDetection;
bool m_needRotateDetectionHasBeenSet;
};
}
}
}
}
#endif // !TENCENTCLOUD_IAI_V20200303_MODEL_SEARCHFACESREQUEST_H_
| [
"tencentcloudapi@tenent.com"
] | tencentcloudapi@tenent.com |
c6451117e9c73226991fa10a073851a7ef3977dd | 84b066b24d4ce9910b5eb2f77a7c6bc712475227 | /Buclle_for.ino.ino | 2bbb6b03f37ad38dacc917a0948697a65d21e162 | [
"CC0-1.0"
] | permissive | Wesley3455/Arduino- | 8599161ff13c4997cee2bc7270a5a39ec00fb4ec | fb91e35e422ef994069f5e0241bed99a10533a48 | refs/heads/main | 2023-03-16T22:15:12.935473 | 2021-03-22T12:40:50 | 2021-03-22T12:40:50 | 334,881,532 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,021 | ino | //Variables globales
int switchState = 0;
//Variables de los pines
const int redPin = 4;
const int bluePin = 2;
const int buttonPin = 3;
void setup() {
// put your setup code here, to run once:
//Iniciando leds
pinMode(redPin, OUTPUT);
pinMode(bluePin, OUTPUT);
//iniciando botón
pinMode(buttonPin, INPUT);
}
void loop() {
//leer el estado del botón
switchState = digitalRead(buttonPin);
if (switchState == LOW){
//el botón no esta pulsado
digitalWrite(redPin,HIGH); //se enciende el rojo
digitalWrite(bluePin,LOW); //se apaga el azul
}
else {
//elsa let it go
//el botón está pulsado
digitalWrite(redPin,LOW); //se apaga el rojo
for (int blinks = 0; blinks <5; blinks ++) {
digitalWrite(bluePin,HIGH); //se enciende el azul
delay(500); //espera un segundo antes de apagar
digitalWrite(bluePin,LOW); //se enciende el azul
delay(500); //espera un segundo antes de apagar
} //llave del for
} //llave del else
}//vuelve al inicio del bucle(llave del loop() )
| [
"noreply@github.com"
] | noreply@github.com |
d112f01f9a7b370a2acd019a245086269a8cffc7 | 14248aaedfa5f77c7fc5dd8c3741604fb987de5c | /luogu/P3188.cpp | b47758eb24473b2054687d31ad5bd5c67022a785 | [] | no_license | atubo/online-judge | fc51012465a1bd07561b921f5c7d064e336a4cd2 | 8774f6c608bb209a1ebbb721d6bbfdb5c1d1ce9b | refs/heads/master | 2021-11-22T19:48:14.279016 | 2021-08-29T23:16:16 | 2021-08-29T23:16:16 | 13,290,232 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,694 | cpp | // https://www.luogu.org/problemnew/show/P3188
// [HNOI2007]梦幻岛宝珠
#include <bits/stdc++.h>
using namespace std;
struct Item {
int w, v;
};
const int MASK = 1023;
int N, W;
int dp[32][1024];
vector<vector<Item>> items(32);
int main() {
while (scanf("%d%d", &N, &W) > 0 && N != -1) {
memset(dp, 0, sizeof(dp));
for (int i = 0; i < 32; i++) items[i].clear();
for (int i = 0; i < N; i++) {
int w, v;
scanf("%d%d", &w, &v);
int b = 0;
while (!(w&1)) {
w >>= 1;
b++;
}
items[b].push_back({w, v});
}
for (const auto &item: items[0]) {
for (int k = MASK; k >= item.w; k--) {
dp[0][k] = max(dp[0][k], dp[0][k-item.w] + item.v);
}
}
for (int k = 1; k <= MASK; k++) {
dp[0][k] = max(dp[0][k], dp[0][k-1]);
}
int ans = 0;
for (int i = 0; i <= min(W, MASK); i++) {
ans = max(ans, dp[0][i]);
}
for (int i = 1; i < 32; i++) {
int u = (W >> (i-1)) & 1;
for (int j = 0; j <= min(MASK, W>>i); j++) {
dp[i][j] = dp[i-1][((j<<1)&MASK)|u];
}
for (const auto &item: items[i]) {
for (int j = min(MASK, W>>i); j >= item.w; j--) {
dp[i][j] = max(dp[i][j], dp[i][j-item.w] + item.v);
}
}
for (int j = 1; j <= MASK; j++) {
dp[i][j] = max(dp[i][j], dp[i][j-1]);
}
ans = max(ans, dp[i][MASK]);
}
printf("%d\n", ans);
}
return 0;
}
| [
"err722@yahoo.com"
] | err722@yahoo.com |
832e4a54766487080971db412ddd351e1a6c12b4 | b4b4e324cbc6159a02597aa66f52cb8e1bc43bc1 | /C++ code/Uva Online Judge/Q517.cpp | 38bc02d6704d887d5e51f7d78c850b6f2fc5e3a0 | [] | no_license | fsps60312/old-C-code | 5d0ffa0796dde5ab04c839e1dc786267b67de902 | b4be562c873afe9eacb45ab14f61c15b7115fc07 | refs/heads/master | 2022-11-30T10:55:25.587197 | 2017-06-03T16:23:03 | 2017-06-03T16:23:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 681 | cpp | #include<cstdio>
int N,T;
char S[4][17],C[8][4];
void Transform(char* &a,char* &b,const int &r)
{
for(int i=0;i<N;i++)
{
if(a[i]==C[r][0]&&a[(i+2)%N]==C[r][1]&&a[(i+3)%N]==C[r][2])b[(i+2)%N]=C[r][3];
else b[(i+2)%N]=a[(i+2)%N];
}
char *c=a;a=b,b=c;
}
void Solve()
{
char *a=S[0],*b=S[1];
for(int i1=0,i2=0;;)
{
}
}
int main()
{
while(scanf("%d",&N)==1)
{
scanf("%s",S[0]);
for(int i=0;i<N;i++)S[2][i]=S[0][i];
for(int i=0;i<8;i++)for(int j=0;j<4;j++)
{
char &c=C[i][j];
do{scanf("%c",&c);}while(c!='a'&&c!='b');
}
scanf("%d",&T);
char *ans=Solve();
printf("%c",ans[0]);
for(int i=1;i<N;i++)printf(" %c",ans[i]);
puts("");
}
return 0;
}
| [
"fsps60312@yahoo.com.tw"
] | fsps60312@yahoo.com.tw |
822ddb36cee352453a9f0134b5887f6908e30a38 | 03fc8bbfb2632d98a8c5a6078361e3c377ad84ee | /App/DeepObjectTracker/RecurrentNeuralNetworkCUDA_Wrapper/RecurrentNeuralNetworkCUDA_Wrapper.h | d82aa18327a7d17830a6872ebef2c24dfea56d36 | [] | no_license | andu04/DeepObjectTracker | 157c488672ee78e90dbd5ef6a92a551f687b7738 | 078ad6fda1a837b1a0819cfa965e41bb6065c547 | refs/heads/master | 2021-01-21T17:28:28.823752 | 2017-04-05T20:30:44 | 2017-04-05T20:30:44 | 85,471,456 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 349 | h | // RecurrentNeuralNetworkCUDA_Wrapper.h
#pragma once
#include "RecurrentNeuralNetwork.h"
using namespace System;
namespace RecurrentNeuralNetworkCUDA_Wrapper {
public ref class RecurrentNeuralNetworkWrapper
{
public:
RecurrentNeuralNetworkWrapper();
bool CheckCUDA();
bool CheckCUDNN();
private:
RecurrentNeuralNetwork* rnn;
};
}
| [
"popandi04@gmail.com"
] | popandi04@gmail.com |
8d4828d677871da15cddd6ff3b99c9cc0258aa28 | 3224a2791c71895235e33c3e4c4319ab6139d0f6 | /04-visitors/expressions/IdentExpression.h | 2c41a13f5341932d23cf00c17f015fbd67a1117e | [] | no_license | akhtyamovpavel/CompilersCourse | de681e0734a33d0f95d1094b9a39b95d2b2943ee | 8475bcb9c49e25996758f04524a11c5800163170 | refs/heads/master | 2023-04-13T07:03:11.191364 | 2022-11-19T17:04:09 | 2022-11-19T17:04:09 | 241,050,653 | 45 | 32 | null | 2021-04-17T22:20:09 | 2020-02-17T08:00:14 | C++ | UTF-8 | C++ | false | false | 258 | h | #pragma once
#include "Expression.h"
#include <string>
class IdentExpression: public Expression {
public:
IdentExpression(const std::string& ident);
int eval() const override;
void Accept(Visitor* visitor) override;
std::string ident_;
}; | [
"akhtyamovpavel@gmail.com"
] | akhtyamovpavel@gmail.com |
32d8c4c8180b3e1b97cdcdd3a6ad1cbc4700329c | 689bfb48068feaf5c148d1a2f2099346b35e07e1 | /FunnyHunny/GameProcess.cpp | b4a939d64da34e03320538ffb9a387a8ca6ad3f2 | [] | no_license | TsentsevitskyDmitry/FunnyHunny | 5be5f9ed078ae2fef7d9ef2f42e319fef7d8093a | 300c24e1a0d0e7050ba483df5e65b25d188633cd | refs/heads/master | 2021-04-19T03:12:09.637749 | 2020-03-24T00:31:53 | 2020-03-24T00:31:53 | 249,574,484 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,088 | cpp | #include "GameProcess.h"
GameProcess* GameProcess::instance = nullptr;
GameProcess *GameProcess::getInstance()
{
if(instance == nullptr)
instance = new GameProcess;
return instance;
}
void GameProcess::setWH(int W, int H)
{
_W = W;
_H = H;
}
void GameProcess::check(int x, int y, int index, int group)
{
for(int i = 0; i < HOME_COUNT; ++i){
if(backgroundItems[i].group != group)
continue;
int dx = backgroundItems[i].x * _W - x;
int dy = backgroundItems[i].y * _H - y;
if(abs(dx) < HOME_SIZE && abs(dy) < HOME_SIZE)
mark(index);
else
unmark(index);
}
}
void GameProcess::mark(int index)
{
playerGood->play();
aims[index] = true;
if(all())
emit GameOver();
}
void GameProcess::unmark(int index)
{
playerBad->play();
aims[index] = false;
}
bool GameProcess::all()
{
for(int i = 0; i < ANIM_COUNT; ++i){
if(aims[i] == false)
return false;
}
return true;
}
| [
"noreply@github.com"
] | noreply@github.com |
39a7f0218d7c108fed9b792712bf9885a775da44 | 9dc335630cb97246a7d67ddf652b404701cece61 | /CAD/CAD_Verano/Actividad2/Actividad2.cpp | cd89cbfc40bb37c08776f51de361502fa242a856 | [] | no_license | getmiranda/sistemas_itver | 1e952e97a1a82891646c7df257c60870445fcae2 | f768d5783a9f570f5debe6a7d18d175f0503e8da | refs/heads/master | 2020-07-10T02:39:15.715234 | 2019-08-24T11:12:56 | 2019-08-24T11:12:56 | 204,145,537 | 1 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 1,217 | cpp | //Actividad 2: Implemente un algoritmo paralelo en el que los procesos pares envíen un mensaje de saludo a los procesos impares.
#include <stdio.h>
#include "mpi.h"
#include <string.h>
int main(int argc, char* argv[]) {
int total_procesos, nombre_proceso, origen, destino, flag = 0;
//mensaje de longitud 100
char mensaje[100];
MPI_Status status;
MPI_Init(NULL, NULL);
MPI_Comm_size(MPI_COMM_WORLD, &total_procesos);
MPI_Comm_rank(MPI_COMM_WORLD, &nombre_proceso);
//Si soy un proceso par envio un mensaje a los impares
if ( (nombre_proceso % 2) == 0)
{
printf("Send. Proceso %d de un total de %d\n", nombre_proceso, total_procesos);
sprintf_s(mensaje, "Saludos desde el proceso %d!", nombre_proceso);
for (destino = 1; destino < total_procesos; destino+=2)
{
MPI_Send(mensaje, strlen(mensaje) + 1, MPI_CHAR, destino, flag, MPI_COMM_WORLD);
}
}
//Pero si soy proceso impar recibo mensaje
else
{
printf("Recv. Proceso %d, Total de procesos = %d \n", nombre_proceso, total_procesos);
for (origen = 0; origen < total_procesos; origen+=2) {
MPI_Recv(mensaje, 100, MPI_CHAR, origen, flag, MPI_COMM_WORLD, &status);
printf("%s\n", mensaje);
}
}
MPI_Finalize();
return 0;
} | [
"androidgalaxys42@gmail.com"
] | androidgalaxys42@gmail.com |
9f516c363979effbdccb31a4343c5119e8078fb9 | bcb1fdd350b7b904cf5fa9d71fff131066c5069d | /test/string.cpp | 5b2472ac3a127f14e0d89d582402b21c5f1ec892 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | Cr4shOv3rrid3/scnlib | 97679caa63dbcb73e47da55080a4f649310f5323 | 72a4bab9e32f2b44593137fba40c54710e20a623 | refs/heads/master | 2022-08-13T07:15:35.474495 | 2022-04-26T18:31:41 | 2022-04-26T18:31:41 | 281,186,906 | 0 | 0 | Apache-2.0 | 2020-07-20T17:46:15 | 2020-07-20T17:46:14 | null | UTF-8 | C++ | false | false | 4,558 | cpp | // Copyright 2017 Elias Kosunen
//
// 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
//
// https://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.
//
// This file is a part of scnlib:
// https://github.com/eliaskosunen/scnlib
#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
#include "test.h"
TEST_CASE_TEMPLATE("string test", CharT, char, wchar_t)
{
using string_type = std::basic_string<CharT>;
{
string_type s{}, s2{};
auto e = do_scan<CharT>("thisisaword nextword", "{} {}", s, s2);
CHECK(s == widen<CharT>("thisisaword"));
CHECK(s2 == widen<CharT>("nextword"));
CHECK(e);
}
{
string_type s{};
auto e = do_scan<CharT>("WoRdW1th_Special<>Charact3rs!?", "{}", s);
CHECK(s == widen<CharT>("WoRdW1th_Special<>Charact3rs!?"));
CHECK(e);
}
{
string_type s{};
auto e = do_scan<CharT>("foo", "{:s}", s);
CHECK(s == widen<CharT>("foo"));
CHECK(e);
}
{
string_type s{};
auto e = do_scan<CharT>("foo", "{:a}", s);
CHECK(s.empty());
CHECK(!e);
CHECK(e.error() == scn::error::invalid_format_string);
}
{
string_type s{};
auto e = do_scan<CharT>(" space", "{}", s);
CHECK(e);
CHECK(s == widen<CharT>("space"));
s.clear();
e = do_scan<CharT>(" space", " {}", s);
CHECK(e);
CHECK(s == widen<CharT>("space"));
}
}
TEST_CASE_TEMPLATE("getline", CharT, char, wchar_t)
{
using string_type = std::basic_string<CharT>;
string_type data = widen<CharT>(
"firstline\n"
"Second line with spaces");
using string_view_type = scn::basic_string_view<CharT>;
SUBCASE("string")
{
string_type s{};
auto ret = scn::getline(data, s, scn::detail::ascii_widen<CharT>('\n'));
CHECK(ret);
CHECK(s == widen<CharT>("firstline"));
ret = scn::getline(ret.range(), s);
CHECK(ret);
CHECK(ret.empty());
CHECK(s == widen<CharT>("Second line with spaces"));
}
SUBCASE("string_view")
{
string_view_type s{};
auto ret = scn::getline(data, s, scn::detail::ascii_widen<CharT>('\n'));
CHECK(ret);
CHECK(string_type{s.data(), s.size()} == widen<CharT>("firstline"));
CHECK(!ret.empty());
ret = scn::getline(ret.range(), s);
CHECK(ret);
CHECK(string_type{s.data(), s.size()} ==
widen<CharT>("Second line with spaces"));
CHECK(ret.empty());
}
SUBCASE("non-contiguous")
{
string_type s{};
auto source = get_deque<CharT>(data);
auto ret =
scn::getline(source, s, scn::detail::ascii_widen<CharT>('\n'));
CHECK(ret);
CHECK(s == widen<CharT>("firstline"));
ret = scn::getline(ret.range(), s);
CHECK(ret);
CHECK(ret.empty());
CHECK(s == widen<CharT>("Second line with spaces"));
}
}
TEST_CASE_TEMPLATE("ignore", CharT, char, wchar_t)
{
using string_type = std::basic_string<CharT>;
string_type data = widen<CharT>("line1\nline2");
SUBCASE("ignore_until")
{
string_type s{};
{
auto ret = scn::ignore_until(data, CharT{0x0a}); // '\n'
CHECK(ret);
data.assign(ret.range_as_string());
}
{
auto ret = scn::scan_default(data, s);
CHECK(s == widen<CharT>("line2"));
CHECK(ret);
}
}
SUBCASE("not found")
{
auto ret = scn::ignore_until(data, CharT{0x33}); // '3'
CHECK(ret);
CHECK(ret.range().size() == 0);
}
SUBCASE("empty range")
{
string_type s{};
auto ret = scn::ignore_until(s, CharT{0x0a});
CHECK(!ret);
CHECK(ret.error().code() == scn::error::end_of_range);
scn::basic_string_view<CharT> sv{};
auto result = scn::make_result(sv);
ret = scn::ignore_until(result.range(), CharT{0x00});
CHECK(!ret);
CHECK(ret.error().code() == scn::error::end_of_range);
}
}
| [
"elias.kosunen@gmail.com"
] | elias.kosunen@gmail.com |
9361a0cfac9379ca3e04d04b0386ea2fb791e72a | 1dbb60db92072801e3e7eaf6645ef776e2a26b29 | /server/src/common/proto/singlearena/PQSingleArenaLogLoad.h | dc551c7197b74d55f0385e58ef5a21e889b19f00 | [] | no_license | atom-chen/phone-code | 5a05472fcf2852d1943ad869b37603a4901749d5 | c0c0f112c9a2570cc0390703b1bff56d67508e89 | refs/heads/master | 2020-07-05T01:15:00.585018 | 2015-06-17T08:52:21 | 2015-06-17T08:52:21 | 202,480,234 | 0 | 1 | null | 2019-08-15T05:36:11 | 2019-08-15T05:36:09 | null | UTF-8 | C++ | false | false | 1,063 | h | #ifndef _PQSingleArenaLogLoad_H_
#define _PQSingleArenaLogLoad_H_
#include <weedong/core/seq/seq.h>
#include <proto/common/SMsgHead.h>
class PQSingleArenaLogLoad : public SMsgHead
{
public:
PQSingleArenaLogLoad()
{
msg_cmd = 862327907;
}
virtual ~PQSingleArenaLogLoad()
{
}
virtual wd::CSeq* clone(void)
{
return ( new PQSingleArenaLogLoad(*this) );
}
virtual bool write( wd::CStream &stream )
{
uint32 uiSize = 0;
return loop( stream, wd::CSeq::eWrite, uiSize );
}
virtual bool read( wd::CStream &stream )
{
uint32 uiSize = 0;
return loop( stream, wd::CSeq::eRead, uiSize );
}
bool loop( wd::CStream &stream, wd::CSeq::ELoopType eType, uint32& uiSize )
{
uint32 _uiSize = 0;
return SMsgHead::loop( stream, eType, _uiSize )
&& wd::CSeq::loop( stream, eType, uiSize )
&& loopend( stream, eType, uiSize );
}
operator const char* ()
{
return "PQSingleArenaLogLoad";
}
};
#endif
| [
"757690733@qq.com"
] | 757690733@qq.com |
5a011af666f056ef4552c66f4fe2051a08940859 | dbc5ce4afcab5def2fcb3d8987721b6d11ba79cb | /Star Rain/Star Rain/ED/SceneED3.h | b2bf3e25c8ae4bb7b46d4e257b741161ed166ba3 | [] | no_license | Erin0428/team-Paella | 56cb5c0279bc9b673f00d1a7f3d94391de443372 | 83299444bc0dac12bf5c8167e7eee7466d85717e | refs/heads/master | 2020-04-27T15:43:11.377736 | 2019-05-20T03:08:04 | 2019-05-20T03:08:04 | 174,457,365 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 403 | h | #pragma once
//使用するヘッダーファイル
#include "../GameL\SceneManager.h"
//使用するネームスペース
using namespace GameL;
//シーン:ゲームエンディング3
class CSceneED3 :public CScene
{
public:
CSceneED3();
~CSceneED3();
void InitScene();//ゲームタイトルの初期化メソッド
void Scene(); //ゲームタイトルの実行中メソッド
private:
}; | [
"GA1@DEV1-19"
] | GA1@DEV1-19 |
8ca52e59aa9bc3c656045ce2c66a2d8f4bde52e9 | 4d7ae3ca4674267c72385fa1ba67496e3abd55ff | /libRayTracing/src/random.cpp | 26e57a8d60d9caf10ff03e20db646bce79dcf5ec | [
"MIT"
] | permissive | tanganke/RayTracing | 1e5c1e066b74f26ef215f1075e43cd8db8eb7259 | 876180439cbc2a6241735d18de6e0eb9e2f11e96 | refs/heads/master | 2023-08-25T02:56:58.126412 | 2021-10-13T11:52:07 | 2021-10-13T11:52:07 | 404,777,544 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 440 | cpp | #include "random.h"
namespace ray_tracing
{
vec2 random_vec2_in_unit_disk()
{
vec2 ans;
TRY:
ans = vec2{random<float>(-1, 1), random<float>(-1, 1)};
if (length(ans) >= 1)
goto TRY;
return ans;
}
vec3 random_vec3_in_unit_sphere()
{
vec3 ans;
TRY:
ans = random_vec3(-1, 1);
if (length(ans) >= 1)
goto TRY;
return ans;
}
} | [
"tang.anke@foxmail.com"
] | tang.anke@foxmail.com |
3ecd05f0f3568d5a23e14e1822287789c49550c5 | 62b1b74118497046645b3159ea27c15cbbc4765c | /WickedEngine/Utility/dxcapi.h | b226cf9dfce002e5e7b6b0d40518e9423a007efc | [
"MIT"
] | permissive | turanszkij/WickedEngine | ec9d9cde27553d9ff3bc1987bc13a5b9d0de3e52 | 003584863003a963718926c4e93ffe97ac00a6ff | refs/heads/master | 2023-09-01T07:03:25.947714 | 2023-08-31T05:40:42 | 2023-08-31T05:40:42 | 37,770,961 | 5,031 | 691 | MIT | 2023-09-13T01:09:46 | 2015-06-20T13:35:19 | C++ | UTF-8 | C++ | false | false | 36,885 | h |
///////////////////////////////////////////////////////////////////////////////
// //
// dxcapi.h //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// Provides declarations for the DirectX Compiler API entry point. //
// //
///////////////////////////////////////////////////////////////////////////////
#ifndef __DXC_API__
#define __DXC_API__
#ifdef _WIN32
#ifndef DXC_API_IMPORT
#define DXC_API_IMPORT __declspec(dllimport)
#endif
#else
#ifndef DXC_API_IMPORT
#define DXC_API_IMPORT __attribute__ ((visibility ("default")))
#endif
#endif
#ifdef _WIN32
#ifndef CROSS_PLATFORM_UUIDOF
// Warning: This macro exists in WinAdapter.h as well
#define CROSS_PLATFORM_UUIDOF(interface, spec) \
struct __declspec(uuid(spec)) interface;
#endif
#else
#include <dlfcn.h>
#include "dxc/Support/WinAdapter.h"
#endif
struct IMalloc;
struct IDxcIncludeHandler;
typedef HRESULT (__stdcall *DxcCreateInstanceProc)(
_In_ REFCLSID rclsid,
_In_ REFIID riid,
_Out_ LPVOID* ppv
);
typedef HRESULT(__stdcall *DxcCreateInstance2Proc)(
_In_ IMalloc *pMalloc,
_In_ REFCLSID rclsid,
_In_ REFIID riid,
_Out_ LPVOID* ppv
);
/// <summary>
/// Creates a single uninitialized object of the class associated with a specified CLSID.
/// </summary>
/// <param name="rclsid">
/// The CLSID associated with the data and code that will be used to create the object.
/// </param>
/// <param name="riid">
/// A reference to the identifier of the interface to be used to communicate
/// with the object.
/// </param>
/// <param name="ppv">
/// Address of pointer variable that receives the interface pointer requested
/// in riid. Upon successful return, *ppv contains the requested interface
/// pointer. Upon failure, *ppv contains NULL.</param>
/// <remarks>
/// While this function is similar to CoCreateInstance, there is no COM involvement.
/// </remarks>
extern "C"
DXC_API_IMPORT HRESULT __stdcall DxcCreateInstance(
_In_ REFCLSID rclsid,
_In_ REFIID riid,
_Out_ LPVOID* ppv
);
extern "C"
DXC_API_IMPORT HRESULT __stdcall DxcCreateInstance2(
_In_ IMalloc *pMalloc,
_In_ REFCLSID rclsid,
_In_ REFIID riid,
_Out_ LPVOID* ppv
);
// For convenience, equivalent definitions to CP_UTF8 and CP_UTF16.
#define DXC_CP_UTF8 65001
#define DXC_CP_UTF16 1200
#define DXC_CP_UTF32 12000
// Use DXC_CP_ACP for: Binary; ANSI Text; Autodetect UTF with BOM
#define DXC_CP_ACP 0
#ifdef _WIN32
#define DXC_CP_WIDE DXC_CP_UTF16
#else
#define DXC_CP_WIDE DXC_CP_UTF32
#endif
// This flag indicates that the shader hash was computed taking into account source information (-Zss)
#define DXC_HASHFLAG_INCLUDES_SOURCE 1
// Hash digest type for ShaderHash
typedef struct DxcShaderHash {
UINT32 Flags; // DXC_HASHFLAG_*
BYTE HashDigest[16];
} DxcShaderHash;
#define DXC_FOURCC(ch0, ch1, ch2, ch3) ( \
(UINT32)(UINT8)(ch0) | (UINT32)(UINT8)(ch1) << 8 | \
(UINT32)(UINT8)(ch2) << 16 | (UINT32)(UINT8)(ch3) << 24 \
)
#define DXC_PART_PDB DXC_FOURCC('I', 'L', 'D', 'B')
#define DXC_PART_PDB_NAME DXC_FOURCC('I', 'L', 'D', 'N')
#define DXC_PART_PRIVATE_DATA DXC_FOURCC('P', 'R', 'I', 'V')
#define DXC_PART_ROOT_SIGNATURE DXC_FOURCC('R', 'T', 'S', '0')
#define DXC_PART_DXIL DXC_FOURCC('D', 'X', 'I', 'L')
#define DXC_PART_REFLECTION_DATA DXC_FOURCC('S', 'T', 'A', 'T')
#define DXC_PART_SHADER_HASH DXC_FOURCC('H', 'A', 'S', 'H')
#define DXC_PART_INPUT_SIGNATURE DXC_FOURCC('I', 'S', 'G', '1')
#define DXC_PART_OUTPUT_SIGNATURE DXC_FOURCC('O', 'S', 'G', '1')
#define DXC_PART_PATCH_CONSTANT_SIGNATURE DXC_FOURCC('P', 'S', 'G', '1')
// Some option arguments are defined here for continuity with D3DCompile interface
#define DXC_ARG_DEBUG L"-Zi"
#define DXC_ARG_SKIP_VALIDATION L"-Vd"
#define DXC_ARG_SKIP_OPTIMIZATIONS L"-Od"
#define DXC_ARG_PACK_MATRIX_ROW_MAJOR L"-Zpr"
#define DXC_ARG_PACK_MATRIX_COLUMN_MAJOR L"-Zpc"
#define DXC_ARG_AVOID_FLOW_CONTROL L"-Gfa"
#define DXC_ARG_PREFER_FLOW_CONTROL L"-Gfp"
#define DXC_ARG_ENABLE_STRICTNESS L"-Ges"
#define DXC_ARG_ENABLE_BACKWARDS_COMPATIBILITY L"-Gec"
#define DXC_ARG_IEEE_STRICTNESS L"-Gis"
#define DXC_ARG_OPTIMIZATION_LEVEL0 L"-O0"
#define DXC_ARG_OPTIMIZATION_LEVEL1 L"-O1"
#define DXC_ARG_OPTIMIZATION_LEVEL2 L"-O2"
#define DXC_ARG_OPTIMIZATION_LEVEL3 L"-O3"
#define DXC_ARG_WARNINGS_ARE_ERRORS L"-WX"
#define DXC_ARG_RESOURCES_MAY_ALIAS L"-res_may_alias"
#define DXC_ARG_ALL_RESOURCES_BOUND L"-all_resources_bound"
#define DXC_ARG_DEBUG_NAME_FOR_SOURCE L"-Zss"
#define DXC_ARG_DEBUG_NAME_FOR_BINARY L"-Zsb"
// IDxcBlob is an alias of ID3D10Blob and ID3DBlob
CROSS_PLATFORM_UUIDOF(IDxcBlob, "8BA5FB08-5195-40e2-AC58-0D989C3A0102")
struct IDxcBlob : public IUnknown {
public:
virtual LPVOID STDMETHODCALLTYPE GetBufferPointer(void) = 0;
virtual SIZE_T STDMETHODCALLTYPE GetBufferSize(void) = 0;
};
CROSS_PLATFORM_UUIDOF(IDxcBlobEncoding, "7241d424-2646-4191-97c0-98e96e42fc68")
struct IDxcBlobEncoding : public IDxcBlob {
public:
virtual HRESULT STDMETHODCALLTYPE GetEncoding(_Out_ BOOL *pKnown,
_Out_ UINT32 *pCodePage) = 0;
};
// Notes on IDxcBlobWide and IDxcBlobUtf8
// These guarantee null-terminated text and eithre utf8 or the native wide char encoding.
// GetBufferSize() will return the size in bytes, including null-terminator
// GetStringLength() will return the length in characters, excluding the null-terminator
// Name strings will use IDxcBlobWide, while other string output blobs,
// such as errors/warnings, preprocessed HLSL, or other text will be based
// on the -encoding option.
// The API will use this interface for output name strings
CROSS_PLATFORM_UUIDOF(IDxcBlobWide, "A3F84EAB-0FAA-497E-A39C-EE6ED60B2D84")
struct IDxcBlobWide : public IDxcBlobEncoding {
public:
virtual LPCWSTR STDMETHODCALLTYPE GetStringPointer(void) = 0;
virtual SIZE_T STDMETHODCALLTYPE GetStringLength(void) = 0;
};
CROSS_PLATFORM_UUIDOF(IDxcBlobUtf8, "3DA636C9-BA71-4024-A301-30CBF125305B")
struct IDxcBlobUtf8 : public IDxcBlobEncoding {
public:
virtual LPCSTR STDMETHODCALLTYPE GetStringPointer(void) = 0;
virtual SIZE_T STDMETHODCALLTYPE GetStringLength(void) = 0;
};
// Define legacy name IDxcBlobUtf16 as IDxcBlobWide for Win32
#ifdef _WIN32
typedef IDxcBlobWide IDxcBlobUtf16;
#endif
CROSS_PLATFORM_UUIDOF(IDxcIncludeHandler, "7f61fc7d-950d-467f-b3e3-3c02fb49187c")
struct IDxcIncludeHandler : public IUnknown {
virtual HRESULT STDMETHODCALLTYPE LoadSource(
_In_z_ LPCWSTR pFilename, // Candidate filename.
_COM_Outptr_result_maybenull_ IDxcBlob **ppIncludeSource // Resultant source object for included file, nullptr if not found.
) = 0;
};
// Structure for supplying bytes or text input to Dxc APIs.
// Use Encoding = 0 for non-text bytes, ANSI text, or unknown with BOM.
typedef struct DxcBuffer {
LPCVOID Ptr;
SIZE_T Size;
UINT Encoding;
} DxcText;
struct DxcDefine {
LPCWSTR Name;
_Maybenull_ LPCWSTR Value;
};
CROSS_PLATFORM_UUIDOF(IDxcCompilerArgs, "73EFFE2A-70DC-45F8-9690-EFF64C02429D")
struct IDxcCompilerArgs : public IUnknown {
// Pass GetArguments() and GetCount() to Compile
virtual LPCWSTR* STDMETHODCALLTYPE GetArguments() = 0;
virtual UINT32 STDMETHODCALLTYPE GetCount() = 0;
// Add additional arguments or defines here, if desired.
virtual HRESULT STDMETHODCALLTYPE AddArguments(
_In_opt_count_(argCount) LPCWSTR *pArguments, // Array of pointers to arguments to add
_In_ UINT32 argCount // Number of arguments to add
) = 0;
virtual HRESULT STDMETHODCALLTYPE AddArgumentsUTF8(
_In_opt_count_(argCount)LPCSTR *pArguments, // Array of pointers to UTF-8 arguments to add
_In_ UINT32 argCount // Number of arguments to add
) = 0;
virtual HRESULT STDMETHODCALLTYPE AddDefines(
_In_count_(defineCount) const DxcDefine *pDefines, // Array of defines
_In_ UINT32 defineCount // Number of defines
) = 0;
};
//////////////////////////
// Legacy Interfaces
/////////////////////////
// NOTE: IDxcUtils replaces IDxcLibrary
CROSS_PLATFORM_UUIDOF(IDxcLibrary, "e5204dc7-d18c-4c3c-bdfb-851673980fe7")
struct IDxcLibrary : public IUnknown {
virtual HRESULT STDMETHODCALLTYPE SetMalloc(_In_opt_ IMalloc *pMalloc) = 0;
virtual HRESULT STDMETHODCALLTYPE CreateBlobFromBlob(
_In_ IDxcBlob *pBlob, UINT32 offset, UINT32 length, _COM_Outptr_ IDxcBlob **ppResult) = 0;
virtual HRESULT STDMETHODCALLTYPE CreateBlobFromFile(
_In_z_ LPCWSTR pFileName, _In_opt_ UINT32* codePage,
_COM_Outptr_ IDxcBlobEncoding **pBlobEncoding) = 0;
virtual HRESULT STDMETHODCALLTYPE CreateBlobWithEncodingFromPinned(
_In_bytecount_(size) LPCVOID pText, UINT32 size, UINT32 codePage,
_COM_Outptr_ IDxcBlobEncoding **pBlobEncoding) = 0;
virtual HRESULT STDMETHODCALLTYPE CreateBlobWithEncodingOnHeapCopy(
_In_bytecount_(size) LPCVOID pText, UINT32 size, UINT32 codePage,
_COM_Outptr_ IDxcBlobEncoding **pBlobEncoding) = 0;
virtual HRESULT STDMETHODCALLTYPE CreateBlobWithEncodingOnMalloc(
_In_bytecount_(size) LPCVOID pText, IMalloc *pIMalloc, UINT32 size, UINT32 codePage,
_COM_Outptr_ IDxcBlobEncoding **pBlobEncoding) = 0;
virtual HRESULT STDMETHODCALLTYPE CreateIncludeHandler(
_COM_Outptr_ IDxcIncludeHandler **ppResult) = 0;
virtual HRESULT STDMETHODCALLTYPE CreateStreamFromBlobReadOnly(
_In_ IDxcBlob *pBlob, _COM_Outptr_ IStream **ppStream) = 0;
virtual HRESULT STDMETHODCALLTYPE GetBlobAsUtf8(
_In_ IDxcBlob *pBlob, _COM_Outptr_ IDxcBlobEncoding **pBlobEncoding) = 0;
// Renamed from GetBlobAsUtf16 to GetBlobAsWide
virtual HRESULT STDMETHODCALLTYPE GetBlobAsWide(
_In_ IDxcBlob *pBlob, _COM_Outptr_ IDxcBlobEncoding **pBlobEncoding) = 0;
#ifdef _WIN32
// Alias to GetBlobAsWide on Win32
inline HRESULT GetBlobAsUtf16(
_In_ IDxcBlob *pBlob, _COM_Outptr_ IDxcBlobEncoding **pBlobEncoding) {
return this->GetBlobAsWide(pBlob, pBlobEncoding);
}
#endif
};
// NOTE: IDxcResult replaces IDxcOperationResult
CROSS_PLATFORM_UUIDOF(IDxcOperationResult, "CEDB484A-D4E9-445A-B991-CA21CA157DC2")
struct IDxcOperationResult : public IUnknown {
virtual HRESULT STDMETHODCALLTYPE GetStatus(_Out_ HRESULT *pStatus) = 0;
// GetResult returns the main result of the operation.
// This corresponds to:
// DXC_OUT_OBJECT - Compile() with shader or library target
// DXC_OUT_DISASSEMBLY - Disassemble()
// DXC_OUT_HLSL - Compile() with -P
// DXC_OUT_ROOT_SIGNATURE - Compile() with rootsig_* target
virtual HRESULT STDMETHODCALLTYPE GetResult(_COM_Outptr_result_maybenull_ IDxcBlob **ppResult) = 0;
// GetErrorBuffer Corresponds to DXC_OUT_ERRORS.
virtual HRESULT STDMETHODCALLTYPE GetErrorBuffer(_COM_Outptr_result_maybenull_ IDxcBlobEncoding **ppErrors) = 0;
};
// NOTE: IDxcCompiler3 replaces IDxcCompiler and IDxcCompiler2
CROSS_PLATFORM_UUIDOF(IDxcCompiler, "8c210bf3-011f-4422-8d70-6f9acb8db617")
struct IDxcCompiler : public IUnknown {
// Compile a single entry point to the target shader model
virtual HRESULT STDMETHODCALLTYPE Compile(
_In_ IDxcBlob *pSource, // Source text to compile
_In_opt_z_ LPCWSTR pSourceName, // Optional file name for pSource. Used in errors and include handlers.
_In_opt_z_ LPCWSTR pEntryPoint, // entry point name
_In_z_ LPCWSTR pTargetProfile, // shader profile to compile
_In_opt_count_(argCount) LPCWSTR *pArguments, // Array of pointers to arguments
_In_ UINT32 argCount, // Number of arguments
_In_count_(defineCount)
const DxcDefine *pDefines, // Array of defines
_In_ UINT32 defineCount, // Number of defines
_In_opt_ IDxcIncludeHandler *pIncludeHandler, // user-provided interface to handle #include directives (optional)
_COM_Outptr_ IDxcOperationResult **ppResult // Compiler output status, buffer, and errors
) = 0;
// Preprocess source text
virtual HRESULT STDMETHODCALLTYPE Preprocess(
_In_ IDxcBlob *pSource, // Source text to preprocess
_In_opt_z_ LPCWSTR pSourceName, // Optional file name for pSource. Used in errors and include handlers.
_In_opt_count_(argCount) LPCWSTR *pArguments, // Array of pointers to arguments
_In_ UINT32 argCount, // Number of arguments
_In_count_(defineCount)
const DxcDefine *pDefines, // Array of defines
_In_ UINT32 defineCount, // Number of defines
_In_opt_ IDxcIncludeHandler *pIncludeHandler, // user-provided interface to handle #include directives (optional)
_COM_Outptr_ IDxcOperationResult **ppResult // Preprocessor output status, buffer, and errors
) = 0;
// Disassemble a program.
virtual HRESULT STDMETHODCALLTYPE Disassemble(
_In_ IDxcBlob *pSource, // Program to disassemble.
_COM_Outptr_ IDxcBlobEncoding **ppDisassembly // Disassembly text.
) = 0;
};
// NOTE: IDxcCompiler3 replaces IDxcCompiler and IDxcCompiler2
CROSS_PLATFORM_UUIDOF(IDxcCompiler2, "A005A9D9-B8BB-4594-B5C9-0E633BEC4D37")
struct IDxcCompiler2 : public IDxcCompiler {
// Compile a single entry point to the target shader model with debug information.
virtual HRESULT STDMETHODCALLTYPE CompileWithDebug(
_In_ IDxcBlob *pSource, // Source text to compile
_In_opt_z_ LPCWSTR pSourceName, // Optional file name for pSource. Used in errors and include handlers.
_In_opt_z_ LPCWSTR pEntryPoint, // Entry point name
_In_z_ LPCWSTR pTargetProfile, // Shader profile to compile
_In_opt_count_(argCount) LPCWSTR *pArguments, // Array of pointers to arguments
_In_ UINT32 argCount, // Number of arguments
_In_count_(defineCount)
const DxcDefine *pDefines, // Array of defines
_In_ UINT32 defineCount, // Number of defines
_In_opt_ IDxcIncludeHandler *pIncludeHandler, // user-provided interface to handle #include directives (optional)
_COM_Outptr_ IDxcOperationResult **ppResult, // Compiler output status, buffer, and errors
_Outptr_opt_result_z_ LPWSTR *ppDebugBlobName,// Suggested file name for debug blob. (Must be CoTaskMemFree()'d!)
_COM_Outptr_opt_ IDxcBlob **ppDebugBlob // Debug blob
) = 0;
};
CROSS_PLATFORM_UUIDOF(IDxcLinker, "F1B5BE2A-62DD-4327-A1C2-42AC1E1E78E6")
struct IDxcLinker : public IUnknown {
public:
// Register a library with name to ref it later.
virtual HRESULT RegisterLibrary(
_In_opt_ LPCWSTR pLibName, // Name of the library.
_In_ IDxcBlob *pLib // Library blob.
) = 0;
// Links the shader and produces a shader blob that the Direct3D runtime can
// use.
virtual HRESULT STDMETHODCALLTYPE Link(
_In_opt_ LPCWSTR pEntryName, // Entry point name
_In_ LPCWSTR pTargetProfile, // shader profile to link
_In_count_(libCount)
const LPCWSTR *pLibNames, // Array of library names to link
_In_ UINT32 libCount, // Number of libraries to link
_In_opt_count_(argCount) const LPCWSTR *pArguments, // Array of pointers to arguments
_In_ UINT32 argCount, // Number of arguments
_COM_Outptr_
IDxcOperationResult **ppResult // Linker output status, buffer, and errors
) = 0;
};
/////////////////////////
// Latest interfaces. Please use these
////////////////////////
// NOTE: IDxcUtils replaces IDxcLibrary
CROSS_PLATFORM_UUIDOF(IDxcUtils, "4605C4CB-2019-492A-ADA4-65F20BB7D67F")
struct IDxcUtils : public IUnknown {
// Create a sub-blob that holds a reference to the outer blob and points to its memory.
virtual HRESULT STDMETHODCALLTYPE CreateBlobFromBlob(
_In_ IDxcBlob *pBlob, UINT32 offset, UINT32 length, _COM_Outptr_ IDxcBlob **ppResult) = 0;
// For codePage, use 0 (or DXC_CP_ACP) for raw binary or ANSI code page
// Creates a blob referencing existing memory, with no copy.
// User must manage the memory lifetime separately.
// (was: CreateBlobWithEncodingFromPinned)
virtual HRESULT STDMETHODCALLTYPE CreateBlobFromPinned(
_In_bytecount_(size) LPCVOID pData, UINT32 size, UINT32 codePage,
_COM_Outptr_ IDxcBlobEncoding **pBlobEncoding) = 0;
// Create blob, taking ownership of memory allocated with supplied allocator.
// (was: CreateBlobWithEncodingOnMalloc)
virtual HRESULT STDMETHODCALLTYPE MoveToBlob(
_In_bytecount_(size) LPCVOID pData, IMalloc *pIMalloc, UINT32 size, UINT32 codePage,
_COM_Outptr_ IDxcBlobEncoding **pBlobEncoding) = 0;
////
// New blobs and copied contents are allocated with the current allocator
// Copy blob contents to memory owned by the new blob.
// (was: CreateBlobWithEncodingOnHeapCopy)
virtual HRESULT STDMETHODCALLTYPE CreateBlob(
_In_bytecount_(size) LPCVOID pData, UINT32 size, UINT32 codePage,
_COM_Outptr_ IDxcBlobEncoding **pBlobEncoding) = 0;
// (was: CreateBlobFromFile)
virtual HRESULT STDMETHODCALLTYPE LoadFile(
_In_z_ LPCWSTR pFileName, _In_opt_ UINT32* pCodePage,
_COM_Outptr_ IDxcBlobEncoding **pBlobEncoding) = 0;
virtual HRESULT STDMETHODCALLTYPE CreateReadOnlyStreamFromBlob(
_In_ IDxcBlob *pBlob, _COM_Outptr_ IStream **ppStream) = 0;
// Create default file-based include handler
virtual HRESULT STDMETHODCALLTYPE CreateDefaultIncludeHandler(
_COM_Outptr_ IDxcIncludeHandler **ppResult) = 0;
// Convert or return matching encoded text blobs
virtual HRESULT STDMETHODCALLTYPE GetBlobAsUtf8(
_In_ IDxcBlob *pBlob, _COM_Outptr_ IDxcBlobUtf8 **pBlobEncoding) = 0;
// Renamed from GetBlobAsUtf16 to GetBlobAsWide
virtual HRESULT STDMETHODCALLTYPE GetBlobAsWide(
_In_ IDxcBlob *pBlob, _COM_Outptr_ IDxcBlobWide **pBlobEncoding) = 0;
#ifdef _WIN32
// Alias to GetBlobAsWide on Win32
inline HRESULT GetBlobAsUtf16(
_In_ IDxcBlob *pBlob, _COM_Outptr_ IDxcBlobWide **pBlobEncoding) {
return this->GetBlobAsWide(pBlob, pBlobEncoding);
}
#endif
virtual HRESULT STDMETHODCALLTYPE GetDxilContainerPart(
_In_ const DxcBuffer *pShader,
_In_ UINT32 DxcPart,
_Outptr_result_nullonfailure_ void **ppPartData,
_Out_ UINT32 *pPartSizeInBytes) = 0;
// Create reflection interface from serialized Dxil container, or DXC_PART_REFLECTION_DATA.
// TBD: Require part header for RDAT? (leaning towards yes)
virtual HRESULT STDMETHODCALLTYPE CreateReflection(
_In_ const DxcBuffer *pData, REFIID iid, void **ppvReflection) = 0;
virtual HRESULT STDMETHODCALLTYPE BuildArguments(
_In_opt_z_ LPCWSTR pSourceName, // Optional file name for pSource. Used in errors and include handlers.
_In_opt_z_ LPCWSTR pEntryPoint, // Entry point name. (-E)
_In_z_ LPCWSTR pTargetProfile, // Shader profile to compile. (-T)
_In_opt_count_(argCount) LPCWSTR *pArguments, // Array of pointers to arguments
_In_ UINT32 argCount, // Number of arguments
_In_count_(defineCount)
const DxcDefine *pDefines, // Array of defines
_In_ UINT32 defineCount, // Number of defines
_COM_Outptr_ IDxcCompilerArgs **ppArgs // Arguments you can use with Compile() method
) = 0;
// Takes the shader PDB and returns the hash and the container inside it
virtual HRESULT STDMETHODCALLTYPE GetPDBContents(
_In_ IDxcBlob *pPDBBlob, _COM_Outptr_ IDxcBlob **ppHash, _COM_Outptr_ IDxcBlob **ppContainer) = 0;
};
// For use with IDxcResult::[Has|Get]Output dxcOutKind argument
// Note: text outputs returned from version 2 APIs are UTF-8 or UTF-16 based on -encoding option
typedef enum DXC_OUT_KIND {
DXC_OUT_NONE = 0,
DXC_OUT_OBJECT = 1, // IDxcBlob - Shader or library object
DXC_OUT_ERRORS = 2, // IDxcBlobUtf8 or IDxcBlobWide
DXC_OUT_PDB = 3, // IDxcBlob
DXC_OUT_SHADER_HASH = 4, // IDxcBlob - DxcShaderHash of shader or shader with source info (-Zsb/-Zss)
DXC_OUT_DISASSEMBLY = 5, // IDxcBlobUtf8 or IDxcBlobWide - from Disassemble
DXC_OUT_HLSL = 6, // IDxcBlobUtf8 or IDxcBlobWide - from Preprocessor or Rewriter
DXC_OUT_TEXT = 7, // IDxcBlobUtf8 or IDxcBlobWide - other text, such as -ast-dump or -Odump
DXC_OUT_REFLECTION = 8, // IDxcBlob - RDAT part with reflection data
DXC_OUT_ROOT_SIGNATURE = 9, // IDxcBlob - Serialized root signature output
DXC_OUT_EXTRA_OUTPUTS = 10,// IDxcExtraResults - Extra outputs
DXC_OUT_REMARKS = 11, // IDxcBlobUtf8 or IDxcBlobWide - text directed at stdout
DXC_OUT_TIME_REPORT = 12, // IDxcBlobUtf8 or IDxcBlobWide - text directed at stdout
DXC_OUT_LAST = DXC_OUT_TIME_REPORT, // Last value for a counter
DXC_OUT_NUM_ENUMS,
DXC_OUT_FORCE_DWORD = 0xFFFFFFFF
} DXC_OUT_KIND;
static_assert(DXC_OUT_NUM_ENUMS == DXC_OUT_LAST + 1,
"DXC_OUT_* Enum added and last value not updated.");
CROSS_PLATFORM_UUIDOF(IDxcResult, "58346CDA-DDE7-4497-9461-6F87AF5E0659")
struct IDxcResult : public IDxcOperationResult {
virtual BOOL STDMETHODCALLTYPE HasOutput(_In_ DXC_OUT_KIND dxcOutKind) = 0;
virtual HRESULT STDMETHODCALLTYPE GetOutput(_In_ DXC_OUT_KIND dxcOutKind,
_In_ REFIID iid, _COM_Outptr_opt_result_maybenull_ void **ppvObject,
_COM_Outptr_ IDxcBlobWide **ppOutputName) = 0;
virtual UINT32 GetNumOutputs() = 0;
virtual DXC_OUT_KIND GetOutputByIndex(UINT32 Index) = 0;
virtual DXC_OUT_KIND PrimaryOutput() = 0;
};
// Special names for extra output that should get written to specific streams
#define DXC_EXTRA_OUTPUT_NAME_STDOUT L"*stdout*"
#define DXC_EXTRA_OUTPUT_NAME_STDERR L"*stderr*"
CROSS_PLATFORM_UUIDOF(IDxcExtraOutputs, "319b37a2-a5c2-494a-a5de-4801b2faf989")
struct IDxcExtraOutputs : public IUnknown {
virtual UINT32 STDMETHODCALLTYPE GetOutputCount() = 0;
virtual HRESULT STDMETHODCALLTYPE GetOutput(_In_ UINT32 uIndex,
_In_ REFIID iid, _COM_Outptr_opt_result_maybenull_ void **ppvObject,
_COM_Outptr_opt_result_maybenull_ IDxcBlobWide **ppOutputType,
_COM_Outptr_opt_result_maybenull_ IDxcBlobWide **ppOutputName) = 0;
};
CROSS_PLATFORM_UUIDOF(IDxcCompiler3, "228B4687-5A6A-4730-900C-9702B2203F54")
struct IDxcCompiler3 : public IUnknown {
// Compile a single entry point to the target shader model,
// Compile a library to a library target (-T lib_*),
// Compile a root signature (-T rootsig_*), or
// Preprocess HLSL source (-P)
virtual HRESULT STDMETHODCALLTYPE Compile(
_In_ const DxcBuffer *pSource, // Source text to compile
_In_opt_count_(argCount) LPCWSTR *pArguments, // Array of pointers to arguments
_In_ UINT32 argCount, // Number of arguments
_In_opt_ IDxcIncludeHandler *pIncludeHandler, // user-provided interface to handle #include directives (optional)
_In_ REFIID riid, _Out_ LPVOID *ppResult // IDxcResult: status, buffer, and errors
) = 0;
// Disassemble a program.
virtual HRESULT STDMETHODCALLTYPE Disassemble(
_In_ const DxcBuffer *pObject, // Program to disassemble: dxil container or bitcode.
_In_ REFIID riid, _Out_ LPVOID *ppResult // IDxcResult: status, disassembly text, and errors
) = 0;
};
static const UINT32 DxcValidatorFlags_Default = 0;
static const UINT32 DxcValidatorFlags_InPlaceEdit = 1; // Validator is allowed to update shader blob in-place.
static const UINT32 DxcValidatorFlags_RootSignatureOnly = 2;
static const UINT32 DxcValidatorFlags_ModuleOnly = 4;
static const UINT32 DxcValidatorFlags_ValidMask = 0x7;
CROSS_PLATFORM_UUIDOF(IDxcValidator, "A6E82BD2-1FD7-4826-9811-2857E797F49A")
struct IDxcValidator : public IUnknown {
// Validate a shader.
virtual HRESULT STDMETHODCALLTYPE Validate(
_In_ IDxcBlob *pShader, // Shader to validate.
_In_ UINT32 Flags, // Validation flags.
_COM_Outptr_ IDxcOperationResult **ppResult // Validation output status, buffer, and errors
) = 0;
};
CROSS_PLATFORM_UUIDOF(IDxcValidator2, "458e1fd1-b1b2-4750-a6e1-9c10f03bed92")
struct IDxcValidator2 : public IDxcValidator {
// Validate a shader.
virtual HRESULT STDMETHODCALLTYPE ValidateWithDebug(
_In_ IDxcBlob *pShader, // Shader to validate.
_In_ UINT32 Flags, // Validation flags.
_In_opt_ DxcBuffer *pOptDebugBitcode, // Optional debug module bitcode to provide line numbers
_COM_Outptr_ IDxcOperationResult **ppResult // Validation output status, buffer, and errors
) = 0;
};
CROSS_PLATFORM_UUIDOF(IDxcContainerBuilder, "334b1f50-2292-4b35-99a1-25588d8c17fe")
struct IDxcContainerBuilder : public IUnknown {
virtual HRESULT STDMETHODCALLTYPE Load(_In_ IDxcBlob *pDxilContainerHeader) = 0; // Loads DxilContainer to the builder
virtual HRESULT STDMETHODCALLTYPE AddPart(_In_ UINT32 fourCC, _In_ IDxcBlob *pSource) = 0; // Part to add to the container
virtual HRESULT STDMETHODCALLTYPE RemovePart(_In_ UINT32 fourCC) = 0; // Remove the part with fourCC
virtual HRESULT STDMETHODCALLTYPE SerializeContainer(_Out_ IDxcOperationResult **ppResult) = 0; // Builds a container of the given container builder state
};
CROSS_PLATFORM_UUIDOF(IDxcAssembler, "091f7a26-1c1f-4948-904b-e6e3a8a771d5")
struct IDxcAssembler : public IUnknown {
// Assemble dxil in ll or llvm bitcode to DXIL container.
virtual HRESULT STDMETHODCALLTYPE AssembleToContainer(
_In_ IDxcBlob *pShader, // Shader to assemble.
_COM_Outptr_ IDxcOperationResult **ppResult // Assembly output status, buffer, and errors
) = 0;
};
CROSS_PLATFORM_UUIDOF(IDxcContainerReflection, "d2c21b26-8350-4bdc-976a-331ce6f4c54c")
struct IDxcContainerReflection : public IUnknown {
virtual HRESULT STDMETHODCALLTYPE Load(_In_ IDxcBlob *pContainer) = 0; // Container to load.
virtual HRESULT STDMETHODCALLTYPE GetPartCount(_Out_ UINT32 *pResult) = 0;
virtual HRESULT STDMETHODCALLTYPE GetPartKind(UINT32 idx, _Out_ UINT32 *pResult) = 0;
virtual HRESULT STDMETHODCALLTYPE GetPartContent(UINT32 idx, _COM_Outptr_ IDxcBlob **ppResult) = 0;
virtual HRESULT STDMETHODCALLTYPE FindFirstPartKind(UINT32 kind, _Out_ UINT32 *pResult) = 0;
virtual HRESULT STDMETHODCALLTYPE GetPartReflection(UINT32 idx, REFIID iid, void **ppvObject) = 0;
};
CROSS_PLATFORM_UUIDOF(IDxcOptimizerPass, "AE2CD79F-CC22-453F-9B6B-B124E7A5204C")
struct IDxcOptimizerPass : public IUnknown {
virtual HRESULT STDMETHODCALLTYPE GetOptionName(_COM_Outptr_ LPWSTR *ppResult) = 0;
virtual HRESULT STDMETHODCALLTYPE GetDescription(_COM_Outptr_ LPWSTR *ppResult) = 0;
virtual HRESULT STDMETHODCALLTYPE GetOptionArgCount(_Out_ UINT32 *pCount) = 0;
virtual HRESULT STDMETHODCALLTYPE GetOptionArgName(UINT32 argIndex, _COM_Outptr_ LPWSTR *ppResult) = 0;
virtual HRESULT STDMETHODCALLTYPE GetOptionArgDescription(UINT32 argIndex, _COM_Outptr_ LPWSTR *ppResult) = 0;
};
CROSS_PLATFORM_UUIDOF(IDxcOptimizer, "25740E2E-9CBA-401B-9119-4FB42F39F270")
struct IDxcOptimizer : public IUnknown {
virtual HRESULT STDMETHODCALLTYPE GetAvailablePassCount(_Out_ UINT32 *pCount) = 0;
virtual HRESULT STDMETHODCALLTYPE GetAvailablePass(UINT32 index, _COM_Outptr_ IDxcOptimizerPass** ppResult) = 0;
virtual HRESULT STDMETHODCALLTYPE RunOptimizer(IDxcBlob *pBlob,
_In_count_(optionCount) LPCWSTR *ppOptions, UINT32 optionCount,
_COM_Outptr_ IDxcBlob **pOutputModule,
_COM_Outptr_opt_ IDxcBlobEncoding **ppOutputText) = 0;
};
static const UINT32 DxcVersionInfoFlags_None = 0;
static const UINT32 DxcVersionInfoFlags_Debug = 1; // Matches VS_FF_DEBUG
static const UINT32 DxcVersionInfoFlags_Internal = 2; // Internal Validator (non-signing)
CROSS_PLATFORM_UUIDOF(IDxcVersionInfo, "b04f5b50-2059-4f12-a8ff-a1e0cde1cc7e")
struct IDxcVersionInfo : public IUnknown {
virtual HRESULT STDMETHODCALLTYPE GetVersion(_Out_ UINT32 *pMajor, _Out_ UINT32 *pMinor) = 0;
virtual HRESULT STDMETHODCALLTYPE GetFlags(_Out_ UINT32 *pFlags) = 0;
};
CROSS_PLATFORM_UUIDOF(IDxcVersionInfo2, "fb6904c4-42f0-4b62-9c46-983af7da7c83")
struct IDxcVersionInfo2 : public IDxcVersionInfo {
virtual HRESULT STDMETHODCALLTYPE GetCommitInfo(
_Out_ UINT32 *pCommitCount, // The total number commits.
_Outptr_result_z_ char **pCommitHash // The SHA of the latest commit. (Must be CoTaskMemFree()'d!)
) = 0;
};
CROSS_PLATFORM_UUIDOF(IDxcVersionInfo3, "5e13e843-9d25-473c-9ad2-03b2d0b44b1e")
struct IDxcVersionInfo3 : public IUnknown {
virtual HRESULT STDMETHODCALLTYPE GetCustomVersionString(
_Outptr_result_z_ char **pVersionString // Custom version string for compiler. (Must be CoTaskMemFree()'d!)
) = 0;
};
struct DxcArgPair {
const WCHAR *pName;
const WCHAR *pValue;
};
CROSS_PLATFORM_UUIDOF(IDxcPdbUtils, "E6C9647E-9D6A-4C3B-B94C-524B5A6C343D")
struct IDxcPdbUtils : public IUnknown {
virtual HRESULT STDMETHODCALLTYPE Load(_In_ IDxcBlob *pPdbOrDxil) = 0;
virtual HRESULT STDMETHODCALLTYPE GetSourceCount(_Out_ UINT32 *pCount) = 0;
virtual HRESULT STDMETHODCALLTYPE GetSource(_In_ UINT32 uIndex, _COM_Outptr_ IDxcBlobEncoding **ppResult) = 0;
virtual HRESULT STDMETHODCALLTYPE GetSourceName(_In_ UINT32 uIndex, _Outptr_result_z_ BSTR *pResult) = 0;
virtual HRESULT STDMETHODCALLTYPE GetFlagCount(_Out_ UINT32 *pCount) = 0;
virtual HRESULT STDMETHODCALLTYPE GetFlag(_In_ UINT32 uIndex, _Outptr_result_z_ BSTR *pResult) = 0;
virtual HRESULT STDMETHODCALLTYPE GetArgCount(_Out_ UINT32 *pCount) = 0;
virtual HRESULT STDMETHODCALLTYPE GetArg(_In_ UINT32 uIndex, _Outptr_result_z_ BSTR *pResult) = 0;
virtual HRESULT STDMETHODCALLTYPE GetArgPairCount(_Out_ UINT32 *pCount) = 0;
virtual HRESULT STDMETHODCALLTYPE GetArgPair(_In_ UINT32 uIndex, _Outptr_result_z_ BSTR *pName, _Outptr_result_z_ BSTR *pValue) = 0;
virtual HRESULT STDMETHODCALLTYPE GetDefineCount(_Out_ UINT32 *pCount) = 0;
virtual HRESULT STDMETHODCALLTYPE GetDefine(_In_ UINT32 uIndex, _Outptr_result_z_ BSTR *pResult) = 0;
virtual HRESULT STDMETHODCALLTYPE GetTargetProfile(_Outptr_result_z_ BSTR *pResult) = 0;
virtual HRESULT STDMETHODCALLTYPE GetEntryPoint(_Outptr_result_z_ BSTR *pResult) = 0;
virtual HRESULT STDMETHODCALLTYPE GetMainFileName(_Outptr_result_z_ BSTR *pResult) = 0;
virtual HRESULT STDMETHODCALLTYPE GetHash(_COM_Outptr_ IDxcBlob **ppResult) = 0;
virtual HRESULT STDMETHODCALLTYPE GetName(_Outptr_result_z_ BSTR *pResult) = 0;
virtual BOOL STDMETHODCALLTYPE IsFullPDB() = 0;
virtual HRESULT STDMETHODCALLTYPE GetFullPDB(_COM_Outptr_ IDxcBlob **ppFullPDB) = 0;
virtual HRESULT STDMETHODCALLTYPE GetVersionInfo(_COM_Outptr_ IDxcVersionInfo **ppVersionInfo) = 0;
virtual HRESULT STDMETHODCALLTYPE SetCompiler(_In_ IDxcCompiler3 *pCompiler) = 0;
virtual HRESULT STDMETHODCALLTYPE CompileForFullPDB(_COM_Outptr_ IDxcResult **ppResult) = 0;
virtual HRESULT STDMETHODCALLTYPE OverrideArgs(_In_ DxcArgPair *pArgPairs, UINT32 uNumArgPairs) = 0;
virtual HRESULT STDMETHODCALLTYPE OverrideRootSignature(_In_ const WCHAR *pRootSignature) = 0;
};
CROSS_PLATFORM_UUIDOF(IDxcPdbUtils2, "4315D938-F369-4F93-95A2-252017CC3807")
struct IDxcPdbUtils2 : public IUnknown {
virtual HRESULT STDMETHODCALLTYPE Load(_In_ IDxcBlob *pPdbOrDxil) = 0;
virtual HRESULT STDMETHODCALLTYPE GetSourceCount(_Out_ UINT32 *pCount) = 0;
virtual HRESULT STDMETHODCALLTYPE GetSource(_In_ UINT32 uIndex, _COM_Outptr_ IDxcBlobEncoding **ppResult) = 0;
virtual HRESULT STDMETHODCALLTYPE GetSourceName(_In_ UINT32 uIndex, _COM_Outptr_ IDxcBlobWide **ppResult) = 0;
virtual HRESULT STDMETHODCALLTYPE GetLibraryPDBCount(UINT32 *pCount) = 0;
virtual HRESULT STDMETHODCALLTYPE GetLibraryPDB(_In_ UINT32 uIndex, _COM_Outptr_ IDxcPdbUtils2 **ppOutPdbUtils, _COM_Outptr_opt_result_maybenull_ IDxcBlobWide **ppLibraryName) = 0;
virtual HRESULT STDMETHODCALLTYPE GetFlagCount(_Out_ UINT32 *pCount) = 0;
virtual HRESULT STDMETHODCALLTYPE GetFlag(_In_ UINT32 uIndex, _COM_Outptr_ IDxcBlobWide **ppResult) = 0;
virtual HRESULT STDMETHODCALLTYPE GetArgCount(_Out_ UINT32 *pCount) = 0;
virtual HRESULT STDMETHODCALLTYPE GetArg(_In_ UINT32 uIndex, _COM_Outptr_ IDxcBlobWide **ppResult) = 0;
virtual HRESULT STDMETHODCALLTYPE GetArgPairCount(_Out_ UINT32 *pCount) = 0;
virtual HRESULT STDMETHODCALLTYPE GetArgPair(_In_ UINT32 uIndex, _COM_Outptr_result_maybenull_ IDxcBlobWide **ppName, _COM_Outptr_result_maybenull_ IDxcBlobWide **ppValue) = 0;
virtual HRESULT STDMETHODCALLTYPE GetDefineCount(_Out_ UINT32 *pCount) = 0;
virtual HRESULT STDMETHODCALLTYPE GetDefine(_In_ UINT32 uIndex, _COM_Outptr_ IDxcBlobWide **ppResult) = 0;
virtual HRESULT STDMETHODCALLTYPE GetTargetProfile(_COM_Outptr_result_maybenull_ IDxcBlobWide **ppResult) = 0;
virtual HRESULT STDMETHODCALLTYPE GetEntryPoint(_COM_Outptr_result_maybenull_ IDxcBlobWide **ppResult) = 0;
virtual HRESULT STDMETHODCALLTYPE GetMainFileName(_COM_Outptr_result_maybenull_ IDxcBlobWide **ppResult) = 0;
virtual HRESULT STDMETHODCALLTYPE GetHash(_COM_Outptr_result_maybenull_ IDxcBlob **ppResult) = 0;
virtual HRESULT STDMETHODCALLTYPE GetName(_COM_Outptr_result_maybenull_ IDxcBlobWide **ppResult) = 0;
virtual HRESULT STDMETHODCALLTYPE GetVersionInfo(_COM_Outptr_result_maybenull_ IDxcVersionInfo **ppVersionInfo) = 0;
virtual HRESULT STDMETHODCALLTYPE GetCustomToolchainID(_Out_ UINT32 *pID) = 0;
virtual HRESULT STDMETHODCALLTYPE GetCustomToolchainData(_COM_Outptr_result_maybenull_ IDxcBlob **ppBlob) = 0;
virtual HRESULT STDMETHODCALLTYPE GetWholeDxil(_COM_Outptr_result_maybenull_ IDxcBlob **ppResult) = 0;
virtual BOOL STDMETHODCALLTYPE IsFullPDB() = 0;
virtual BOOL STDMETHODCALLTYPE IsPDBRef() = 0;
};
// Note: __declspec(selectany) requires 'extern'
// On Linux __declspec(selectany) is removed and using 'extern' results in link error.
#ifdef _MSC_VER
#define CLSID_SCOPE __declspec(selectany) extern
#else
#define CLSID_SCOPE
#endif
CLSID_SCOPE const CLSID CLSID_DxcCompiler = {
0x73e22d93,
0xe6ce,
0x47f3,
{0xb5, 0xbf, 0xf0, 0x66, 0x4f, 0x39, 0xc1, 0xb0}};
// {EF6A8087-B0EA-4D56-9E45-D07E1A8B7806}
CLSID_SCOPE const GUID CLSID_DxcLinker = {
0xef6a8087,
0xb0ea,
0x4d56,
{0x9e, 0x45, 0xd0, 0x7e, 0x1a, 0x8b, 0x78, 0x6}};
// {CD1F6B73-2AB0-484D-8EDC-EBE7A43CA09F}
CLSID_SCOPE const CLSID CLSID_DxcDiaDataSource = {
0xcd1f6b73,
0x2ab0,
0x484d,
{0x8e, 0xdc, 0xeb, 0xe7, 0xa4, 0x3c, 0xa0, 0x9f}};
// {3E56AE82-224D-470F-A1A1-FE3016EE9F9D}
CLSID_SCOPE const CLSID CLSID_DxcCompilerArgs = {
0x3e56ae82,
0x224d,
0x470f,
{0xa1, 0xa1, 0xfe, 0x30, 0x16, 0xee, 0x9f, 0x9d}};
// {6245D6AF-66E0-48FD-80B4-4D271796748C}
CLSID_SCOPE const GUID CLSID_DxcLibrary = {
0x6245d6af,
0x66e0,
0x48fd,
{0x80, 0xb4, 0x4d, 0x27, 0x17, 0x96, 0x74, 0x8c}};
CLSID_SCOPE const GUID CLSID_DxcUtils = CLSID_DxcLibrary;
// {8CA3E215-F728-4CF3-8CDD-88AF917587A1}
CLSID_SCOPE const GUID CLSID_DxcValidator = {
0x8ca3e215,
0xf728,
0x4cf3,
{0x8c, 0xdd, 0x88, 0xaf, 0x91, 0x75, 0x87, 0xa1}};
// {D728DB68-F903-4F80-94CD-DCCF76EC7151}
CLSID_SCOPE const GUID CLSID_DxcAssembler = {
0xd728db68,
0xf903,
0x4f80,
{0x94, 0xcd, 0xdc, 0xcf, 0x76, 0xec, 0x71, 0x51}};
// {b9f54489-55b8-400c-ba3a-1675e4728b91}
CLSID_SCOPE const GUID CLSID_DxcContainerReflection = {
0xb9f54489,
0x55b8,
0x400c,
{0xba, 0x3a, 0x16, 0x75, 0xe4, 0x72, 0x8b, 0x91}};
// {AE2CD79F-CC22-453F-9B6B-B124E7A5204C}
CLSID_SCOPE const GUID CLSID_DxcOptimizer = {
0xae2cd79f,
0xcc22,
0x453f,
{0x9b, 0x6b, 0xb1, 0x24, 0xe7, 0xa5, 0x20, 0x4c}};
// {94134294-411f-4574-b4d0-8741e25240d2}
CLSID_SCOPE const GUID CLSID_DxcContainerBuilder = {
0x94134294,
0x411f,
0x4574,
{0xb4, 0xd0, 0x87, 0x41, 0xe2, 0x52, 0x40, 0xd2}};
// {54621dfb-f2ce-457e-ae8c-ec355faeec7c}
CLSID_SCOPE const GUID CLSID_DxcPdbUtils = {
0x54621dfb,
0xf2ce,
0x457e,
{0xae, 0x8c, 0xec, 0x35, 0x5f, 0xae, 0xec, 0x7c}};
#endif
| [
"noreply@github.com"
] | noreply@github.com |
fc9456abc133167f598c9ad8ee9f4be4375d407e | 9182ce864aba7bde45dda6a361532bf08cecf7f8 | /src/orbital/physical/Body.h | 359e97615197fb12194917d0ab91f2f1be9ebd43 | [
"MIT"
] | permissive | JohannesMP/orbital | f7850b54a0a4b563e9663c6f333d54b59327afa4 | 9dca53deb6989fbe4c5171c4e9517c2e548ea3fa | refs/heads/master | 2020-03-23T12:10:49.189587 | 2018-02-14T22:27:25 | 2018-02-14T22:27:25 | 141,541,943 | 0 | 1 | null | 2018-07-19T07:35:37 | 2018-07-19T07:35:37 | null | UTF-8 | C++ | false | false | 1,067 | h | //
// Created by jim on 23.01.18.
//
#pragma once
#include <orbital/common/common.h>
#include <orbital/math/Ellipse.h>
class Body
{
public:
/**
* Create a new body.
* @param name Planet name
* @param mass Planet mass
* @param radius Planet radius
* @param a Major semi axis (a > 0)
* @param e Elliptic eccentricity (0 <= e < 1)
*/
Body(
std::string_view name,
Decimal mass,
Decimal radius,
Decimal a,
Decimal e
);
std::string_view
getName() const;
Decimal
getMass() const;
const vec &
getPosition() const;
const Ellipse<Decimal> &
getTrajectory() const;
void
step(
Decimal M,
Decimal dt
);
private:
std::string mName;
Decimal mMass{}; ///< [kg] Planet mass (m > 0)
Decimal mRadius{}; ///< [m] Planet radius (r > 0)
vec mPosition{}; ///< [m] Position of body mass center
Ellipse<Decimal> mTrajectory;
vec mTrajectoryCenter{};
};
| [
"jim.eckerlein@gmail.com"
] | jim.eckerlein@gmail.com |
eba9d1af5f9655e8717e2c5a3a75b4f227fb98b8 | 1f54982576a90111d0edece2d2520d65ae21daad | /Vector.cpp | 77f137c487ce4c4af88af8193e39188ea6ddfbfd | [] | no_license | maryhmatthews/C-Second-year-Project | fd901cea79f7a94b0f26675a3130069f53bb0f13 | 92ae7095151f3f5e22b2928eaec0cb1ec31302dd | refs/heads/master | 2020-12-30T23:37:04.592269 | 2017-03-29T18:30:56 | 2017-03-29T18:30:56 | 86,614,432 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,533 | cpp | //
// Created by ap15015 on 28/02/2017.
//
#include "Vector.h"
#include <cmath>
double Vector::modSqr (Vector &v) const
{
double V = (v.getx()*v.getx()) + (v.gety()*v.gety()) + (v.getz()*v.getz());
return V;
}//function to calculate the Modulus Squared of a vector using |v|^2=x^2+y^2+z^2
double Vector:: mod (Vector &v)const
{
double U = modSqr(v);
double u = abs(sqrt(U));
return u;
}//function to return the Modulus of vector i.e. |v|
double Vector:: dot ( Vector &v) const
{
double W = (v.getx()*x + v.gety()*y + v.getz()*z);
return W;
}//function to calculate the Dot Product of two vectors (v and u) which is =(v(x).u(x))+(v(y).u(y))+(v(z).u(z))
double Vector:: distance ( Vector &v) const
{
Vector D;
D.setx((v.getx()- x)); D.sety((v.gety()-y)); D.setz((v.getz()-z));
double d=mod(D);
return d;
}/*function to calculate the Distance between two vectors (u and v) which is
=sqrt[((v(x)-u(x))^2)+((v(y)-u(y))^2)+((v(z)-u(z))^2)] */
void Vector::scale(double f)
{
setx(getx()*f);
sety(gety()*f);
setz(getz()*f);
}
Vector Vector::unit ()
{
Vector v;
v.setx(x);
v.sety(y);
v.setz(z);
double m=(1/(v.mod(v)));
v.scale(m);
return v;
}
Vector Vector::cross ( Vector &v )
{
double wx= (gety()*(v.getz()))-(getz()*(v.gety()));
double wy= (getz()*(v.getx()))-(getx()*(v.getz()));
double wz= (getx()*(v.gety()))-(gety()*(v.getx()));
Vector v1;
v1.setx(wx);
v1.sety(wy);
v1.setz(wz);
return v1;
} | [
"noreply@github.com"
] | noreply@github.com |
28a4cc1a5b46a593e013bfef3d01be73c9264555 | c760312ce602b8e16d0f6e026aa93d038eb156a6 | /src/modules/core/tests/OctreeTest.cpp | 7b5f4931ea4e4dd91d5b0428f3d8245f2f6f8cb4 | [] | no_license | cmaughan/engine | 8518befe4a5dba97b8e1db59696ed538fe5d7a76 | ad6edadcdc7a97e30faab785baff00856a35fe6a | refs/heads/master | 2021-04-12T12:10:08.234176 | 2017-05-30T17:48:37 | 2017-05-30T18:28:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,972 | cpp | /**
* @file
*/
#include <gtest/gtest.h>
#include "core/Octree.h"
namespace core {
class Item {
private:
AABB<int> _bounds;
int _id;
public:
Item(const AABB<int>& bounds, int id) :
_bounds(bounds), _id(id) {
}
const AABB<int>& aabb() const {
return _bounds;
}
bool operator==(const Item& rhs) const {
return rhs._id == _id;
}
};
TEST(OctreeTest, testAdd) {
Octree<Item, int> octree({0, 0, 0, 100, 100, 100});
EXPECT_EQ(0, octree.count())<< "Expected to have no entries in the octree";
EXPECT_TRUE(octree.insert({{51, 51, 51, 53, 53, 53}, 1}));
EXPECT_EQ(1, octree.count())<< "Expected to have 1 entry in the octree";
EXPECT_TRUE(octree.insert({{15, 15, 15, 18, 18, 18}, 2}));
EXPECT_EQ(2, octree.count())<< "Expected to have 2 entries in the octree";
}
TEST(OctreeTest, testAddAABBTooBig) {
Octree<Item, int> octree({0, 0, 0, 100, 100, 100});
EXPECT_EQ(0, octree.count())<< "Expected to have no entries in the octree";
EXPECT_FALSE(octree.insert({{-100, -100, -100, 200, 200, 200}, 1}));
}
TEST(OctreeTest, testRemove) {
Octree<Item, int> octree({0, 0, 0, 100, 100, 100});
EXPECT_EQ(0, octree.count())<< "Expected to have no entries in the octree";
const Item item({51, 51, 51, 53, 53, 53}, 1);
EXPECT_TRUE(octree.insert(item));
const Item item2({52, 52, 52, 54, 55, 55}, 2);
EXPECT_TRUE(octree.insert(item2));
EXPECT_EQ(2, octree.count())<< "Expected to have 2 entries in the octree";
EXPECT_TRUE(octree.remove(item));
EXPECT_EQ(1, octree.count())<<"Expected to have 0 entries in the octree";
}
TEST(OctreeTest, testQuery) {
// TODO: not using Item* but Item here results in valgrind errors...
Octree<Item*, int> octree({0, 0, 0, 100, 100, 100}, 3);
{
Octree<Item*, int>::Contents contents;
octree.query({50, 50, 50, 60, 60, 60}, contents);
EXPECT_EQ(0u, contents.size())<<"Expected to find nothing in an empty tree";
}
{
Octree<Item*, int>::Contents contents;
octree.query({52, 52, 52, 54, 54, 54}, contents);
EXPECT_EQ(0u, contents.size())<<"Expected to find nothing in an empty tree";
}
Item* item1 = new Item({51, 51, 51, 53, 53, 53}, 1);
EXPECT_TRUE(octree.insert(item1));
{
Octree<Item*, int>::Contents contents;
octree.query(item1->aabb(), contents);
EXPECT_EQ(1u, contents.size())<<"Expected to find one entry for the item aabb";
}
{
Octree<Item*, int>::Contents contents;
octree.query({52, 52, 52, 54, 54, 54}, contents);
EXPECT_EQ(1u, contents.size())<<"Expected to find one entry for the overlapping aabb";
}
{
Octree<Item*, int>::Contents contents;
octree.query({50, 50, 50, 52, 52, 52}, contents);
EXPECT_TRUE(intersects(item1->aabb(), {50, 50, 50, 52, 52, 52}));
EXPECT_EQ(1u, contents.size())<<"Expected to find one entry for the overlapping aabb";
}
}
TEST(OctreeTest, testOctreeCache) {
Octree<Item*, int> octree({0, 0, 0, 100, 100, 100});
OctreeCache<Item*, int> cache(octree);
{
Octree<Item*, int>::Contents contents;
octree.query({50, 50, 50, 60, 60, 60}, contents);
EXPECT_EQ(0u, contents.size())<<"Expected to find nothing in an empty tree";
contents.clear();
EXPECT_FALSE(cache.query({50, 50, 50, 60, 60, 60}, contents));
contents.clear();
EXPECT_TRUE(cache.query({50, 50, 50, 60, 60, 60}, contents));
}
Item* item = new Item({51, 51, 51, 53, 53, 53}, 1);
EXPECT_TRUE(octree.insert(item));
{
Octree<Item*, int>::Contents contents;
EXPECT_FALSE(cache.query({50, 50, 50, 60, 60, 60}, contents)) << "Expected to have the cache cleared, the octree was in a dirty state";
EXPECT_EQ(1u, contents.size())<<"Expected to find one entry for the enclosing aabb";
}
{
Octree<Item*, int>::Contents contents;
octree.query({50, 50, 50, 52, 52, 52}, contents);
EXPECT_EQ(1u, contents.size())<<"Expected to find one entry for the overlapping aabb";
contents.clear();
EXPECT_FALSE(cache.query({50, 50, 50, 52, 52, 52}, contents));
contents.clear();
EXPECT_TRUE(cache.query({50, 50, 50, 52, 52, 52}, contents));
}
delete item;
}
}
| [
"martin.gerhardy@gmail.com"
] | martin.gerhardy@gmail.com |
4440eaf5642bfcb409caf1d1234d64aa7a466b95 | 9cb565cfe571ca25c090de55b200eba5d99d5f28 | /session_02/order_of_summation1a.cpp | aa9423372f5fb3aa99af941d789a8e82ab33ecb7 | [] | no_license | psharma117/PHY480-Computational-Physics | 26ecf5335d77b8cbcc68433fc61994f21a24a1b3 | a93328952d966291a7c6167b104de537d105ee5c | refs/heads/main | 2023-04-18T13:30:03.337285 | 2021-05-04T16:17:46 | 2021-05-04T16:17:46 | 331,646,936 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,607 | cpp | //************************************************************************
// file: order_of_summation1a.cpp (order_of_summation1.cpp with errors
// and unformatted)
//
// Program to demonstrate that the order of summation of even positive
// numbers matters
//
// Programmer: Dick Furnstahl furnstahl.1@osu.edu
//
// Revision history:
// 01/02/11 new version from demo1a.cpp
//
// Notes:
// * An example to try to understand summing upward vs. summing
// downward. Add a small number eps (slightly below single-precision
// machine precision) many times to 1. It makes a big difference
// (in single precision) whether you do 1 + eps + eps + ... or
// eps + eps + ... + 1.
//
//
// * First pass: no subroutine
// * Use single precision AND double precision at the same time
// * Here is the output with eps=5e-8 added 10^7 time:
//
// 1+eps+eps+... eps+eps+...+1
// single precision: 1.0000000000 1.5323836803
// double precision: 1.4999999992 1.4999999999
//
// To do:
//
//*************************************************************************
// include files
#include <iostream> // note that .h is omitted
#include <iomanip>
using namespace std; // we need this when .h is omitted
//********************** begin main ******************************
int
main ()
{
int num_eps = 1e8; // number of times to add eps to 1
float eps_sp = 5.e-8; // single precision small increment
double eps_dp = 5.e-8; // double precision small increment
float sum_first_sp = 1.; // adding 1 first (single precision)
float sum_last_sp = 0.; // adding 1 at the end (single precision)
double sum_first_dp = 1.; // adding 1 first (double precision)
double sum_last_dp = 0.; // adding 1 at the end (double precision)
cout << endl << "Adding small numbers many times to a big number:"
<< endl << endl;
// add small numbers (in single or double precision) num_eps times
for (int i = 0; i < num_eps; i++)
{
sum_first_sp += eps_sp;
sum_last_sp += eps_sp;
sum_first_dp += eps_dp;
sum_last_dp += eps_dp;
}
sum_last_sp += 1.; // add 1 at the end
sum_last_dp += 1.; // add 1 at the end
cout << " 1+eps+eps+... eps+eps+...+1 \n";
cout << "single precision: " << fixed << setprecision (10) << setw (12)
<< sum_first_sp << " " << setw (12) << sum_last_sp << endl;
cout << "double precision: " << fixed << setprecision (10) << setw (12)
<< sum_first_dp << " " << setw (12) << sum_last_dp << endl;
return (0);
}
| [
"psharmacgk@gmail.com"
] | psharmacgk@gmail.com |
ff1b1fb420ace508adea9ac39730c1e03747cf78 | b73ae552d01725c21f29c2e84205e1aea9ec722a | /original_code/Graph.cc | 519b8875828e27b5012d277a0e99827c0a30a733 | [] | no_license | fiji-flo/preach2014 | 23ff27e05b98626c64b29536bf665101b15216bb | 1bfafad6f1df37224e3c4f8777eaccbd1249f5ef | refs/heads/master | 2020-05-18T04:10:31.000268 | 2014-10-31T08:21:54 | 2014-10-31T08:21:54 | 32,138,387 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 10,221 | cc | /*
* Copyright (c) Florian Merz 2013.
*
* The software is provided on an as is basis for research purposes.
* There is no additional support offered, nor are the author(s)
* or their institutions liable under any circumstances.
*
*/
#include "Graph.hh"
#include "util.hh"
#include <tuple>
#include <stdlib.h>
namespace preach {
typedef std::tuple<int, int> Pair_t;
bool PairLess(const Pair_t& l, const Pair_t& r) {
return std::get<0>(l) < std::get<0>(r);
}
bool LexLess(const int& i, const int& j) {
return std::to_string(i) < std::to_string(j);
}
void Graph::addNode(const int id) {
Node_t v;
v.order_fwd = -1;
v.till_fwd = -1;
v.peek_fwd = -1;
v.peek_till_fwd = -1;
v.peek_min_fwd = -1;
v.peek_max_fwd = -1;
v.order_bwd = -1;
v.till_bwd = -1;
v.peek_bwd = -1;
v.peek_till_bwd = -1;
v.peek_min_bwd = -1;
v.peek_max_bwd = -1;
v.level = 0;
v.level_back = 0;
nl[id] = v;
}
void Graph::addNodeBuild(const int id) {
NodeBuild_t v;
v.in = 0;
v.out = 0;
v.lvl_in = 0;
v.lvl_out = 0;
v.tail_edge_list_fwd = 0;
v.tail_edge_list_bwd = 0;
nbl[id] = v;
}
void Graph::strTrimRight(std::string& str) {
std::string whitespaces(" \t");
int index = str.find_last_not_of(whitespaces);
if (index != std::string::npos)
str.erase(index+1);
else
str.clear();
}
int Graph::addEdgeLine(std::string& buf, const int sid) {
int deg;
int idx;
int tid;
std::string sub;
strTrimRight(buf);
idx = buf.find(":");
buf.erase(0, idx+2);
deg = std::count(buf.begin(), buf.end(), ' ');
std::vector<int> tmp_nl = std::vector<int>(deg);
// check if unsorted edges break something TODO
idx = 0;
while (buf.find(" ") != std::string::npos) {
sub = buf.substr(0, buf.find(" "));
std::istringstream(sub) >> tid;
buf.erase(0, buf.find(" ")+1);
tmp_nl[idx] = tid;
idx++;
}
// for (std::vector<int>::iterator it = tmp_nl.begin(); it != tmp_nl.end(); it++) {
for (int& it: tmp_nl) {
if (nbl[sid].out == 0) {
num_sinks--;
}
nbl[sid].out++;
ncl[sid].out++;
if (nbl[it].in == 0) {
num_sources--;
}
nbl[it].in++;
ncl[it].in++;
addEdge(sid, it);
}
return tmp_nl.size();
}
void Graph::addEdge(const int sid, const int tid) {
int back_fwd = nbl[tid].tail_edge_list_bwd++;
int back_bwd = nbl[sid].tail_edge_list_fwd++;
ebl_fwd[sid].push_back((EdgeBuild_t){tid, back_fwd, E_E});
ebl_bwd[tid].push_back((EdgeBuild_t){sid, back_bwd, E_E_});
}
void Graph::readGraph(std::istream& in) {
std::string line;
int n, m;
std::stringstream ss;
std::getline(in, line);
std::getline(in, line);
ss << line;
ss >> n;
num_sinks = n;
num_sources = n;
nl = (NodeList)malloc(n * sizeof(Node_t));
for (int i = 0; i < n; i++) {
addNode(i);
}
nbl = NodeBuildList(n);
for (int i = 0; i < n; i++) {
addNodeBuild(i);
}
ncl = NodeContractList(n);
for (int i = 0; i < n; i++) {
ncl[i] = NodeContract_t{0,0,0,0};
}
ebl_fwd = EdgeBuildList(n);
ebl_bwd = EdgeBuildList(n);
for (std::vector<EdgeBuild_t>& ebv: ebl_fwd) {
ebv = std::vector<EdgeBuild_t>();
}
for (std::vector<EdgeBuild_t>& ebv: ebl_bwd) {
ebv = std::vector<EdgeBuild_t>();
}
m = 0;
for (int i = 0; i < n; i++) {
std::stringstream ss;
int sid, tid;
char c;
std::getline(in, line);
ss << line;
ss >> sid;
sid = i; // stupid bug in go-uniprot
ss >> c;
while(ss >> tid) {
if (nbl[sid].out == 0) {
num_sinks--;
}
nbl[sid].out++;
ncl[sid].out++;
if (nbl[tid].in == 0) {
num_sources--;
}
nbl[tid].in++;
ncl[tid].in++;
addEdge(sid, tid);
m++;
}
}
num_edges = m;
num_nodes = n;
}
void Graph::writeGraph(std::ostream& out) {
std::cout << "Nodes: " << num_nodes << " Edges: " << num_edges << std::endl;
out << "graph_for_greach" << std::endl;
out << num_nodes << std::endl;
EdgeBuildList::iterator ebl_fwd_it;
std::vector<EdgeBuild_t>::iterator eb_it;
int i = 0;
for (ebl_fwd_it = ebl_fwd.begin(); ebl_fwd_it != ebl_fwd.end(); ebl_fwd_it++) {
out << i << ": ";
for (eb_it = (*ebl_fwd_it).begin(); eb_it != (*ebl_fwd_it).end(); eb_it++) {
if ((*eb_it).subs & E_E) {
out << (*eb_it).to << " ";
}
}
out << "#" << std::endl;
i++;
}
}
/* Refinemnet */
int Graph::LevelBackDfs(const int vid, int tree_size) {
int level_back = nl[vid].level_back;
NodeBuild_t *tb;
for (EdgeBuild_t& e: ebl_bwd[vid]) {
if (nl[e.to].level_back <= level_back) {
nl[e.to].level_back = level_back + 1;
}
}
for (EdgeBuild_t& e: ebl_bwd[vid]) {
tb = &nbl[e.to];
tb->lvl_out++;
if (tb->out == tb->lvl_out) {
tree_size = LevelBackDfs(e.to, tree_size + 1);
}
}
return tree_size;
}
int Graph::LevelDfs(const int vid, int tree_size) {
int level = nl[vid].level;
NodeBuild_t *tb;
for (EdgeBuild_t& e: ebl_fwd[vid]) {
if (nl[e.to].level <= level) {
nl[e.to].level = level + 1;
}
}
for (EdgeBuild_t& e: ebl_fwd[vid]) {
tb = &nbl[e.to];
tb->lvl_in++;
if (tb->in == tb->lvl_in) {
tree_size = LevelDfs(e.to, tree_size + 1);
}
}
return tree_size;
}
int Graph::OrderBackDfs(const int vid, int order) {
Node_t *v = &nl[vid];
int max_peek = 1;
v->order_bwd = order;
order++;
v->peek_bwd = v->order_bwd;
v->peek_min_bwd = v->order_bwd;
v->peek_till_bwd = -2;
Node_t *t;
for (EdgeBuild_t& e: ebl_bwd[vid]) {
t = &nl[e.to];
if (t->peek_till_bwd == -1) {
order = OrderBackDfs(e.to, order);
}
if (t->order_bwd < v->order_bwd) {
if ((t->till_bwd - t->order_bwd) > max_peek) {
max_peek = t->till_bwd - t->order_bwd;
v->peek_bwd = t->order_bwd;
v->peek_till_bwd = t->till_bwd;
}
if (t->till_bwd > v->peek_max_bwd) {
v->peek_max_bwd = t->till_bwd;
}
}
if (t->peek_bwd < v->order_bwd) {
if ((t->peek_till_bwd - t->peek_bwd) > max_peek) {
max_peek = t->peek_till_bwd - t->peek_bwd;
v->peek_bwd = t->peek_bwd;
v->peek_till_bwd = t->peek_till_bwd;
}
}
if (t->peek_max_bwd > v->peek_max_bwd) {
v->peek_max_bwd = t->peek_max_bwd;
}
if ((t->peek_min_bwd > -1) && (t->peek_min_bwd < v-> peek_min_bwd)) {
v->peek_min_bwd = t->peek_min_bwd;
}
}
if (v->peek_till_bwd == -2) {
v->peek_till_bwd = order;
}
v->till_bwd = order;
return order;
}
int Graph::OrderDfs(const int vid, int order) {
Node_t *v = &nl[vid];
int max_peek = 1;
v->order_fwd = order;
order++;
v->peek_fwd = v->order_fwd;
v->peek_min_fwd = v->order_fwd;
v->peek_till_fwd = -2;
Node_t *t;
for (EdgeBuild_t& e: ebl_fwd[vid]) {
t = &nl[e.to];
if (t->peek_till_fwd == -1) {
order = OrderDfs(e.to, order);
}
if (t->order_fwd < v->order_fwd) {
if ((t->till_fwd - t->order_fwd) > max_peek) {
max_peek = t->till_fwd - t->order_fwd;
v->peek_fwd = t->order_fwd;
v->peek_till_fwd = t->till_fwd;
}
if (t->till_fwd > v->peek_max_fwd) {
v->peek_max_fwd = t->till_fwd;
}
}
if (t->peek_fwd < v->order_fwd) {
if ((t->peek_till_fwd - t->peek_fwd) > max_peek) {
max_peek = t->peek_till_fwd - t->peek_fwd;
v->peek_fwd = t->peek_fwd;
v->peek_till_fwd = t->peek_till_fwd;
}
}
if (t->peek_max_fwd > v->peek_max_fwd) {
v->peek_max_fwd = t->peek_max_fwd;
}
if ((t->peek_min_fwd > -1) && (t->peek_min_fwd < v-> peek_min_fwd)) {
v->peek_min_fwd = t->peek_min_fwd;
}
}
if (v->peek_till_fwd == -2) {
v->peek_till_fwd = order;
}
v->till_fwd = order;
return order;
}
void Graph::SetLevels() {
std::vector<Pair_t> l_fwd = std::vector<Pair_t>();
std::vector<Pair_t> l_bwd = std::vector<Pair_t>();
int tree_size = 0;
int id = 0;
TPRECALL();
for (NodeBuild_t& nb: nbl) {
if (nb.in == 0) {
tree_size = LevelDfs(id, 0);
l_fwd.push_back(std::make_tuple(num_nodes - tree_size, id));
}
if (nb.out == 0) {
tree_size = LevelBackDfs(id, 0);
l_bwd.push_back(std::make_tuple(num_nodes - tree_size, id));
}
id++;
}
TPOSTCALL("MakeLevels");
std::sort(l_fwd.begin(), l_fwd.end(), PairLess);
std::sort(l_bwd.begin(), l_bwd.end(), PairLess);
TPOSTCALL("SortTrees");
std::cout << "sinks: " << num_sinks << " source: " << num_sources << std::endl;
int order_fwd = 0;
int order_bwd = 0;
TPRECALL();
for (Pair_t& p: l_fwd) {
order_fwd = OrderDfs(std::get<1>(p), order_fwd);
}
TPOSTCALL("OrderDFS");
for (Pair_t& p: l_bwd) {
order_bwd = OrderBackDfs(std::get<1>(p), order_bwd);
}
TPOSTCALL("OrderBackDFS");
}
// fill edges array used for queries
void Graph::MakeEdgeList(uint8_t filter, EdgeList el, int *edges) {
int offset = 0;
EdgeBuildList::iterator ebl_it;
EdgeBuildList::iterator ebl_end;
std::vector<EdgeBuild_t>::iterator ebv_it;
int i = 0;
if (filter == E_ECHFWD) {
ebl_it = ebl_fwd.begin();
ebl_end = ebl_fwd.end();
} else {
ebl_it = ebl_bwd.begin();
ebl_end = ebl_bwd.end();
}
for (; ebl_it != ebl_end; ebl_it++) {
int m = 0;
for (ebv_it = ebl_it->begin(); ebv_it != ebl_it->end(); ebv_it++) {
if (((*ebv_it).subs & filter) > 0) {
m++;
}
}
el[i].a = edges + offset;
el[i].len = m;
offset += m;
ebv_it = ebl_it->begin();
int j = 0;
while (j < m) {
if (((*ebv_it).subs & filter) > 0) {
el[i].a[j] = (*ebv_it).to;
j++;
}
ebv_it++;
}
i++;
}
}
void Graph::CleanUp() {
for (std::vector<EdgeBuild_t>& ebl: ebl_fwd) {
std::vector<EdgeBuild_t>().swap(ebl);
}
EdgeBuildList().swap(ebl_fwd);
for (std::vector<EdgeBuild_t>& ebl: ebl_bwd) {
std::vector<EdgeBuild_t>().swap(ebl);
}
EdgeBuildList().swap(ebl_bwd);
NodeBuildList().swap(nbl);
NodeContractList().swap(ncl);
}
Graph::Graph() {
}
Graph::~Graph() {
if (nl) {
free(nl);
nl = nullptr;
}
if (el_fwd) {
free(el_fwd);
el_fwd = nullptr;
}
if (el_bwd) {
free(el_bwd);
el_bwd = nullptr;
}
}
} // namespace p2reach
| [
"flome.rz@gmail.com"
] | flome.rz@gmail.com |
dc78c7054550b57e4bbf152fb2c057d9d81c78f4 | 0013eb743eff741ae2087f91f895b582b01f0b7a | /src/software/ai/hl/stp/tactic/crease_defender_tactic.h | e7eef28ecb429559c75f323d239741826e1cfce2 | [
"MIT"
] | permissive | scveloso/Software | d8e1089e4819e865c7c179b4ddd59b9b58a6d796 | ac882d3df0aa0d108e5157c076c82c030d023e12 | refs/heads/master | 2020-08-03T00:00:02.184582 | 2019-09-28T19:26:46 | 2019-09-28T19:26:46 | 211,554,906 | 0 | 0 | MIT | 2019-09-28T19:59:29 | 2019-09-28T19:59:29 | null | UTF-8 | C++ | false | false | 3,372 | h | #pragma once
#include "software/ai/hl/stp/evaluation/enemy_threat.h"
#include "software/ai/hl/stp/tactic/tactic.h"
#include "software/geom/segment.h"
/**
* A crease defender moves around the exterior of our defense box to help shadow
* shots against the enemy
*
* XX <-- Enemy
* XX
* O <-- Ball
*
*
*
* ++ ++ <--- Two crease defenders
* ++ ++
*
* +--------------------+
* | |
* | |
* | ++ <-- Goalie
*+----------------------+---------++---------+------------------+
*/
class CreaseDefenderTactic : public Tactic
{
public:
enum LeftOrRight
{
LEFT,
RIGHT
};
/**
* Creates a new CreaseDefenderTactic
*/
explicit CreaseDefenderTactic(const Field &field, const Ball &ball,
const Team &friendly_team, const Team &enemy_team,
LeftOrRight left_or_right);
std::string getName() const override;
/**
* Updates the parameters for this CreaseDefenderTactic.
*
// TODO: comment
*/
void updateParams(const Ball &ball, const Field &field, const Team &friendly_team,
const Team &enemy_team);
/**
* Calculates the cost of assigning the given robot to this Tactic. Prefers robots
* closer to the destination
*
* @return A cost in the range [0,1] indicating the cost of assigning the given robot
* to this tactic. Lower cost values indicate a more preferred robot.
*/
double calculateRobotCost(const Robot &robot, const World &world) override;
private:
void calculateNextIntent(IntentCoroutine::push_type &yield) override;
/**
* Calculate the position and orientation we would like the defender to be in
*
* @return The position and orientation we would like the defender to be in, or
* std::nullopt if we could not compute one
*/
std::optional<std::pair<Point, Angle>> calculateDesiredState(const Robot &robot);
/**
* Gets the segments that make up the path the Crease Defender should follow
* @param field
* @return The segments that make up the path the Crease Defender should follow
*/
static std::vector<Segment> getPathSegments(Field field);
/**
* Gets a point on the defender crease path where a ray from the goalie at the given
* angle will intersect
*
* @param field The field the path is onAngle angle
* @param goalie The goalie the defenders are working with
* @param ball The ball
* @param offset The angle to offset ray formed from the goalie to the ball by
*
* @return The point on the path the ray from the goalie intersects, if
*/
static std::optional<Point> getPointOnCreasePath(Field field, Robot goalie, Ball ball,
Angle offset);
// Tactic parameters
Ball ball;
Field field;
Team friendly_team;
Team enemy_team;
LeftOrRight left_or_right;
// How slow the ball must be moving for us to clear it from the defense area
double BALL_SLOW_SPEED_THRESHOLD = 0.2;
};
| [
"noreply@github.com"
] | noreply@github.com |
3a6cc97d7d417d7453bb8d7f7e6a5df62a7b8ab0 | 21389b05856626c997e8dec4f5100aa8534feab7 | /enlace.c++ | 5d3a6c97598e1027e7dc88e487f1bfb8c1b632af | [] | no_license | Israel-GR/good | 80f7329dcef769db2039bf9af98be9e579d1fe6a | b5ab63283945460419e99d344c11c29b07d77dfd | refs/heads/master | 2023-02-10T02:57:02.907293 | 2021-01-07T18:41:12 | 2021-01-07T18:41:12 | 327,693,620 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 51 | /* este es un comentario pero voy a aprender c++*/
| [
"Israel@Garcia.com"
] | Israel@Garcia.com | |
efe21dfc01c546d7cf9fd8ead2f68e77785cf954 | b980f63564dc2c3a86047a69c9b9e224b4281c9b | /laser_filters/include/laser_filters/box_filter.h | 82cd74e395ded3f5d3816541065e912525341fb4 | [
"BSD-3-Clause"
] | permissive | BolaDeArroz/burger_war_dev | a3a7982e527d69234c7f0ccdf513f1960884205a | d924d9e70d661ed6a3a8bd83591104f7694083c5 | refs/heads/main | 2023-03-22T21:22:59.679868 | 2021-03-14T15:28:05 | 2021-03-14T15:28:05 | 343,038,127 | 0 | 0 | BSD-3-Clause | 2021-02-28T06:35:17 | 2021-02-28T06:35:16 | null | UTF-8 | C++ | false | false | 2,880 | h | /*
* Software License Agreement (BSD License)
*
* Robot Operating System code by the University of Osnabrück
* Copyright (c) 2015, University of Osnabrück
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* 2. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*
*
* box_filter.h
*
* author: Sebastian Pütz <spuetz@uni-osnabrueck.de>
*/
#ifndef BOXFILTER_H
#define BOXFILTER_H
#include <filters/filter_base.h>
#include <sensor_msgs/LaserScan.h>
#include <sensor_msgs/point_cloud_conversion.h>
#include <laser_geometry/laser_geometry.h>
#include <tf/transform_datatypes.h>
#include <tf/transform_listener.h>
namespace laser_filters
{
/**
* @brief This is a filter that removes points in a laser scan inside of a cartesian box.
*/
class LaserScanBoxFilter : public filters::FilterBase<sensor_msgs::LaserScan>
{
public:
LaserScanBoxFilter();
bool configure();
bool update(
const sensor_msgs::LaserScan& input_scan,
sensor_msgs::LaserScan& filtered_scan);
private:
bool inBox(tf::Point &point);
std::string box_frame_;
laser_geometry::LaserProjection projector_;
// tf listener to transform scans into the box_frame
tf::TransformListener tf_;
// defines two opposite corners of the box
tf::Point min_, max_;
bool invert_filter;
bool up_and_running_;
};
}
#endif /* box_filter.h */
| [
"kawai.takayasu@jp.panasonic.com"
] | kawai.takayasu@jp.panasonic.com |
4e7eab63857e78ec30af9b145237402f39003f30 | 44a4071698b7987f96833879dc334250dba6ac1a | /src/pool.cpp | 856d4b61d6bf0af353e2324f6dde152addf5c0ed | [] | no_license | boulware/color-c | 69febefb03ec7de3bd4ee849f11ecf9301af87e5 | 80a590ae41fc8b6028e7c712a8e6547a8fcf3a58 | refs/heads/master | 2023-01-23T06:30:53.799569 | 2020-12-04T17:22:15 | 2020-12-04T17:22:15 | 296,464,217 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,736 | cpp | #include "pool.h"
template<typename Type>
bool
operator==(PoolId<Type> a, PoolId<Type> b)
{
return(a.value == b.value);
}
template<typename Type>
Pool<Type>
AllocPool(int max_entry_count)
{
Pool<Type> pool = {};
pool.entries = (PoolEntry<Type>*)platform->AllocateMemory(max_entry_count*sizeof(PoolEntry<Type>));
pool.entry_count = 0;
pool.max_entry_count = max_entry_count;
pool.id_counter = 1; // 0 is reserved for invalid entries
return pool;
}
/*
template<typename Type>
PoolId<Type>
CreateEntry(Pool<Type> *pool)
{
if(pool->entry_count >= pool->max_entry_count)
{
// @unsure: does the mStringify macro happen before or after templatization?
Log("[%s] Pool couldn't create a requested entry because it was full.", mStringify(Type));
Assert(false);
return PoolId<Type>{.value = 0};
}
PoolEntry<Type> &entry = pool->entries[pool->entry_count];
entry.id.value = pool->id_counter++;
++pool->entry_count;
return entry.id;
}
*/
template<typename Type>
PoolId<Type>
CreateEntry(Pool<Type> volatile *pool)
{
if(pool->entry_count >= pool->max_entry_count)
{
// @unsure: does the mStringify macro happen before or after templatization?
//Log("[%s] Pool couldn't create a requested entry because it was full.", mStringify(Type));
Assert(false);
return PoolId<Type>{.value = 0};
}
PoolEntry<Type> &entry = pool->entries[pool->entry_count];
entry.id.value = pool->id_counter++;
++pool->entry_count;
return entry.id;
}
/*
template<typename Type>
void
DeleteEntry(Pool<Type> *pool, PoolId<Type> id)
{
if(id.value == 0) return; // invalid index. Do nothing.
int pool_index = -1;
for(int i=0; i<pool->entry_count; ++i)
{
PoolEntry<Type> &entry_to_be_deleted = pool->entries[i]; // alias
if(id == entry_to_be_deleted.id)
{ // Found the entry to delete
PoolEntry<Type> &last_entry_in_pool = pool->entries[pool->entry_count-1]; // alias
entry_to_be_deleted = last_entry_in_pool; // Move last entry in pool to the deleted entry slot.
--pool->entry_count;
return;
// Note: this should work even if the deleted entry was the last entry. It's redundant,
// because deleted_entry will be the same as last_entry_in_pool, but it should
// function logically. The alternative is to do a conditional beforehand, but
// I think we're better off without that. The redundant copy is probably faster.
}
}
// Tried to delete an entry that was not in the pool.
//Log(__FUNCTION__ "() tried to delete an entry that was not in the pool.");
Assert(false);
}
*/
template<typename Type>
void
DeleteEntry(Pool<Type> volatile *pool, PoolId<Type> id)
{
if(id.value == 0) return; // invalid index. Do nothing.
int pool_index = -1;
for(int i=0; i<pool->entry_count; ++i)
{
PoolEntry<Type> &entry_to_be_deleted = pool->entries[i]; // alias
if(id == entry_to_be_deleted.id)
{ // Found the entry to delete
PoolEntry<Type> &last_entry_in_pool = pool->entries[pool->entry_count-1]; // alias
entry_to_be_deleted = last_entry_in_pool; // Move last entry in pool to the deleted entry slot.
--pool->entry_count;
return;
// Note: this should work even if the deleted entry was the last entry. It's redundant,
// because deleted_entry will be the same as last_entry_in_pool, but it should
// function logically. The alternative is to do a conditional beforehand, but
// I think we're better off without that. The redundant copy is probably faster.
}
}
// Tried to delete an entry that was not in the pool.
//Log(__FUNCTION__ "() tried to delete an entry that was not in the pool.");
Assert(false);
}
/*
template<typename Type>
Type *
GetEntryFromId(Pool<Type> pool, PoolId<Type> id)
{
if(id.value == 0) return nullptr;
for(int i=0; i<pool.entry_count; ++i)
{
PoolEntry<Type> &entry = pool.entries[i]; // alias
if(id == entry.id) return &entry.data;
}
// An entry with the supplied id does not exist in the pool.
return nullptr;
}
*/
#if 1
template<typename Type>
Type *
GetEntryFromId(Pool<Type> volatile *pool, PoolId<Type> id)
{
if(id.value == 0) return nullptr;
for(int i=0; i<pool->entry_count; ++i)
{
PoolEntry<Type> &entry = pool->entries[i]; // alias
if(id == entry.id) return &entry.data;
}
// An entry with the supplied id does not exist in the pool.
return nullptr;
}
#endif | [
"tyler.boulware@gmail.com"
] | tyler.boulware@gmail.com |
8761e4ae64cac8a87b4815202e70fd3beadad876 | 02ce8a5d3386aa639ef1c2c2fdd6da8d0de158f9 | /ACE-5.6.1/ACE_wrappers/apps/JAWS2/JAWS/Server.h | a82eb97cf3380a9a963e7a9e14bd0844484ffa47 | [] | no_license | azraelly/knetwork | 932e27a22b1ee621742acf57618083ecab23bca1 | 69e30ee08d0c8e66c1cfb00d7ae3ba6983ff935c | refs/heads/master | 2021-01-20T13:48:24.909756 | 2010-07-03T13:59:39 | 2010-07-03T13:59:39 | 39,634,314 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 962 | h | /* -*- c++ -*- */
// $Id: Server.h 32270 2000-04-27 23:43:23Z jxh $
#ifndef JAWS_SERVER_H
#define JAWS_SERVER_H
#include "JAWS/Export.h"
#include "JAWS/Data_Block.h"
#include "JAWS/Policy.h"
class JAWS_IO_Handler_Factory;
class JAWS_Export JAWS_Server
{
public:
JAWS_Server (void);
JAWS_Server (int argc, char *argv[]);
void init (int argc, char *argv[]);
int open (JAWS_Pipeline_Handler *ph, JAWS_Dispatch_Policy *dp = 0);
private:
void parse_args (int argc, char *argv[]);
// Parse arguments
private:
int ratio_; // ratio of asynch ops to threads
int port_; // port to listen on
int concurrency_; // 0 => pool, 1 => per request
int dispatch_; // 0 => synch, 1 => asynch
int nthreads_; // number of threads
int maxthreads_; // maximum number of threads
long flags_; // thread creation flags
JAWS_Default_Dispatch_Policy policy_;
};
#endif /* !defined (JAWS_SERVER_H) */
| [
"yuwuxiong2010@gmail.com"
] | yuwuxiong2010@gmail.com |
ddcc8dec9847b57c4f8e1bf1aa36cf6c11bf9e8e | cb90ac80113d1fa46c74a88e18da6ba4935a7165 | /neural_network.h | dca6eef02854a13ba73dd8a339bb32ad935997c7 | [] | no_license | son-vo-cs/handwritten-digit | fa981659aaeeeb30e5e6700407dbf305c70e20d6 | da4c0e611c15ec4fcbfea715dece57a6a5d65d98 | refs/heads/master | 2020-05-30T09:51:39.609991 | 2020-05-05T02:27:12 | 2020-05-05T02:27:12 | 189,656,862 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,795 | h | #ifndef NEURAL_NETWORK_H_INCLUDED
#define NEURAL_NETWORK_H_INCLUDED
#include <vector>
#include <string>
#include <fstream>
//Alias
using Vec = std::vector<double>;
using Matrx = std::vector<Vec>;
using Layer = std::vector<Matrx>;
class neuralNetwork
{
private:
// Variables of the class
unsigned int in_nodes, hid_nodes, out_nodes, layers, epoch;
double learn_rate;
Layer weight_layer;
// Private methods
// Takes an input(Matrix of 28x28), and feed forward
Layer feed_forward(Matrx input);
// Calculates error and return error layer
Layer update_error(Vec target, Layer output_layer);
// Backpropagate, return the delta weight matrix
Matrx backpropagate(Matrx E, Matrx S, Matrx O, double learn_rate);
// Calculates backward and refine weight
void backward(Vec target, Matrx a_train_set, Layer output, Layer error);
// Signmoid function
double sigmoid(double x);
// Given a matrix, apply sigmoid function for all of its elements
void update_sigmoid(Matrx& m);
// After reading the MINIST file line by line as string, pass it in and begin learning
void learning(std::vector<std::string> train_sets);
public:
// Constructor
neuralNetwork(int in_nodes, int hid_nodes, int out_nodes, int layer, int epochs, double lr);
// Initialize all the variables
void initialize(int in_nodes, int hid_nodes, int out_nodes, int layer, int epochs, double lr);
// Takes the name of a train set and begin to train
void train(std::string train_set_file_name);
// Takes the name of a test_set and begin to predict
void query(std::string test_set_file_name);
// Destructor
~neuralNetwork();
};
#endif // NEURAL_NETWORK_H_INCLUDED
| [
"sonvo.cs@gmail.com"
] | sonvo.cs@gmail.com |
59a00947ea8834411accc645fa684113a5f67c44 | 54ce01d038792f708aab2d6750fc8f29047233d4 | /基本输入输出/2.cpp | 1d5f611e4ffdd141bc22c7550d631e267c969890 | [
"BSD-3-Clause"
] | permissive | handsomebsn/data-structure | bdb07e3ccb13f8518ff0a56d914180965b16bfb7 | 56efed88d3d96ee5851e3af277248e1d2e17736b | refs/heads/master | 2020-12-30T16:46:42.407631 | 2017-09-27T03:43:27 | 2017-09-27T03:43:27 | 91,030,908 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 292 | cpp | #include<iostream>
using namespace std;
/*cin 忽略前导空白 遇到空白结束 并将空白保留在输入队列中(输入缓存中)*/
int main(int argc, char const *argv[])
{
/* code */
char name[100];
char sex[100];
cin>>name>>sex;
cout<<name<<endl;
cout<<sex<<endl;
return 0;
} | [
"1903935168@qq.com"
] | 1903935168@qq.com |
2d4ada617b81d159927e42587f1242742333842b | 341ef329544215c4eeaf92416ef358a943b7db7f | /src/Config.h | b1adddca6d1d006657ad29092fb66e179ada390a | [] | no_license | adamk33n3r/chumspeak-server | fabbb287365ab19bb9ede22dae5f63fbea40d441 | 557b8e523dccf817683ae0339bad911f3c31a3a7 | refs/heads/master | 2021-07-04T20:58:54.569342 | 2020-08-19T23:34:49 | 2020-08-19T23:34:49 | 150,354,201 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 446 | h | #ifndef CONFIG_H
#define CONFIG_H
#include <string>
#include <memory>
#include "json.hpp"
class Config {
public:
Config(const std::string &configPath);
bool save() const;
std::string dump() const;
std::string value(const char* key, const char* defaultValue) const;
nlohmann::json& operator[](const char* key);
const nlohmann::json& operator[](const char* key) const;
private:
nlohmann::json json;
};
#endif
| [
"adam.g.keenan@gmail.com"
] | adam.g.keenan@gmail.com |
7866e064a414f5ddb72b8ffa1103bea2718609df | 309044c891f881b8e65ab3054ac31aa82d97bc50 | /src/network/Branch.h | 3515c2779417b2f45f52c6d2d19127f497caad89 | [
"MIT"
] | permissive | aboelmakarem/casena | 98c87435d0cabd91e727d44b4fd8946ab78af89d | 387c83a1bc6a5150684f5d54f8eba4712b81f827 | refs/heads/main | 2023-04-18T05:06:05.670701 | 2021-05-02T19:44:03 | 2021-05-02T19:44:03 | 347,510,506 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,304 | h | // Branch.h
// Ahmed M. Hussein (amhussein4@gmail.com)
// 03/13/2021
#ifndef BRANCH_H_
#define BRANCH_H_
#include "Component.h"
namespace CASENA
{
class Branch : public Component
{
public:
Branch();
Branch(const Branch& branch);
virtual ~Branch();
virtual Branch& operator=(const Branch& branch);
void Reset();
static bool IsBranchComponent(const char* line);
static unsigned int ReadMaxNodeID(const char* line);
bool Read(const char* line);
static Component* Create(const char* line);
double Current() const;
double PreviousCurrent() const;
void Current(const double& value);
void StartNodeID(const unsigned int& target_id);
unsigned int StartNodeID() const;
void EndNodeID(const unsigned int& target_id);
unsigned int EndNodeID() const;
void Equation(EZ::Math::Matrix& f) const;
void Gradients(EZ::Math::Matrix& A) const;
void Update(const EZ::Math::Matrix& x,const unsigned int& id_offset);
private:
void Initialize();
double currents[HistoryCount];
protected:
virtual bool ReadProperties(const EZ::List<EZ::String*>* line_tokens);
virtual void BranchEquation(EZ::Math::Matrix& f) const = 0;
virtual void BranchGradients(EZ::Math::Matrix& A) const = 0;
unsigned int start_node_id;
unsigned int end_node_id;
};
class IndSource : public Branch
{
public:
IndSource();
IndSource(const IndSource& source);
virtual ~IndSource();
virtual IndSource& operator=(const IndSource& source);
void Reset();
void Form(const double& value);
double Form() const;
private:
void Initialize();
bool ReadProperties(const EZ::List<EZ::String*>* line_tokens);
double form;
};
class IndVolSource : public IndSource
{
public:
IndVolSource();
IndVolSource(const IndVolSource& source);
~IndVolSource();
IndVolSource& operator=(const IndVolSource& source);
void Reset();
void Print() const;
private:
void Initialize();
void BranchEquation(EZ::Math::Matrix& f) const;
void BranchGradients(EZ::Math::Matrix& A) const;
};
class IndCurrSource : public IndSource
{
public:
IndCurrSource();
IndCurrSource(const IndCurrSource& resistor);
~IndCurrSource();
IndCurrSource& operator=(const IndCurrSource& resistor);
void Reset();
void Print() const;
private:
void Initialize();
void BranchEquation(EZ::Math::Matrix& f) const;
void BranchGradients(EZ::Math::Matrix& A) const;
};
class VCSource : public Branch
{
public:
VCSource();
VCSource(const VCSource& source);
virtual ~VCSource();
virtual VCSource& operator=(const VCSource& source);
void Reset();
void Coefficient(const double& value);
double Coefficient() const;
void SourceStartNodeID(const unsigned int& id);
unsigned int SourceStartNodeID() const;
void SourceEndNodeID(const unsigned int& id);
unsigned int SourceEndNodeID() const;
double SourceVoltage() const;
private:
void Initialize();
bool ReadProperties(const EZ::List<EZ::String*>* line_tokens);
double coefficient;
protected:
unsigned int source_start_node_id;
unsigned int source_end_node_id;
};
class VCVolSource : public VCSource
{
public:
VCVolSource();
VCVolSource(const VCVolSource& source);
~VCVolSource();
VCVolSource& operator=(const VCVolSource& source);
void Reset();
void Print() const;
private:
void Initialize();
void BranchEquation(EZ::Math::Matrix& f) const;
void BranchGradients(EZ::Math::Matrix& A) const;
};
class VCCurrSource : public VCSource
{
public:
VCCurrSource();
VCCurrSource(const VCCurrSource& source);
~VCCurrSource();
VCCurrSource& operator=(const VCCurrSource& source);
void Reset();
void Print() const;
private:
void Initialize();
void BranchEquation(EZ::Math::Matrix& f) const;
void BranchGradients(EZ::Math::Matrix& A) const;
};
class CCSource : public Branch
{
public:
CCSource();
CCSource(const CCSource& source);
virtual ~CCSource();
virtual CCSource& operator=(const CCSource& source);
void Reset();
void Coefficient(const double& value);
double Coefficient() const;
void SourceBranchName(const EZ::String& target_name);
const EZ::String& SourceBranchName() const;
double SourceCurrent() const;
private:
void Initialize();
bool ReadProperties(const EZ::List<EZ::String*>* line_tokens);
double coefficient;
protected:
EZ::String source_branch_name;
};
class CCVolSource : public CCSource
{
public:
CCVolSource();
CCVolSource(const CCVolSource& source);
~CCVolSource();
CCVolSource& operator=(const CCVolSource& source);
void Reset();
void Print() const;
private:
void Initialize();
void BranchEquation(EZ::Math::Matrix& f) const;
void BranchGradients(EZ::Math::Matrix& A) const;
};
class CCCurrSource : public CCSource
{
public:
CCCurrSource();
CCCurrSource(const CCCurrSource& source);
~CCCurrSource();
CCCurrSource& operator=(const CCCurrSource& source);
void Reset();
void Print() const;
private:
void Initialize();
void BranchEquation(EZ::Math::Matrix& f) const;
void BranchGradients(EZ::Math::Matrix& A) const;
};
class ShortBranch : public Branch
{
public:
ShortBranch();
ShortBranch(const ShortBranch& branch);
~ShortBranch();
ShortBranch& operator=(const ShortBranch& branch);
void Reset();
void Print() const;
private:
void Initialize();
void BranchEquation(EZ::Math::Matrix& f) const;
void BranchGradients(EZ::Math::Matrix& A) const;
};
class OpenBranch : public Branch
{
public:
OpenBranch();
OpenBranch(const OpenBranch& branch);
~OpenBranch();
OpenBranch& operator=(const OpenBranch& branch);
void Reset();
void Print() const;
private:
void Initialize();
void BranchEquation(EZ::Math::Matrix& f) const;
void BranchGradients(EZ::Math::Matrix& A) const;
};
class Resistor : public Branch
{
public:
Resistor();
Resistor(const Resistor& resistor);
~Resistor();
Resistor& operator=(const Resistor& resistor);
void Reset();
void Resistance(const double& value);
double Resistance() const;
void Print() const;
private:
void Initialize();
bool ReadProperties(const EZ::List<EZ::String*>* line_tokens);
void BranchEquation(EZ::Math::Matrix& f) const;
void BranchGradients(EZ::Math::Matrix& A) const;
double resistance;
};
class Capacitor : public Branch
{
public:
Capacitor();
Capacitor(const Capacitor& capacitor);
~Capacitor();
Capacitor& operator=(const Capacitor& capacitor);
void Reset();
void Capacitance(const double& value);
double Capacitance() const;
void Print() const;
private:
void Initialize();
bool ReadProperties(const EZ::List<EZ::String*>* line_tokens);
void BranchEquation(EZ::Math::Matrix& f) const;
void BranchGradients(EZ::Math::Matrix& A) const;
double capacitance;
};
class Inductor : public Branch
{
public:
Inductor();
Inductor(const Inductor& inductor);
~Inductor();
Inductor& operator=(const Inductor& inductor);
void Reset();
void Inductance(const double& value);
double Inductance() const;
void Print() const;
private:
void Initialize();
bool ReadProperties(const EZ::List<EZ::String*>* line_tokens);
void BranchEquation(EZ::Math::Matrix& f) const;
void BranchGradients(EZ::Math::Matrix& A) const;
double inductance;
};
}
#endif
| [
"amhussein4@gmail.com"
] | amhussein4@gmail.com |
7619277f51e389d09abc85706a130aed78edf763 | a8d25fd624be9debeb43b4f47232cf9d5c01aff1 | /IMathLib_develop/utility/singleton.hpp | 4e0201c099926a35e4489153a71adbd60704ee9c | [
"MIT"
] | permissive | waka-lab/IMathLib | fc2d0905ead770c7fc382040c3ce9d2907b3c15f | 87623ba931f74324a02698c05b44d59af3041eb4 | refs/heads/master | 2020-06-21T04:03:02.875026 | 2019-07-07T12:41:24 | 2019-07-07T12:41:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,054 | hpp | #ifndef IMATHLIB_UTILITY_SINGLETON_HPP
#define IMATHLIB_UTILITY_SINGLETON_HPP
#include "IMathLib/utility/utility.hpp"
#include "IMathLib/container/allocator.hpp"
namespace iml {
// シングルトンを実装するための基底クラス
template <class T>
class singleton {
static inline T* inst_m = nullptr;
singleton(const singleton &) = delete;
singleton(singleton &&) = delete;
singleton& operator=(const singleton &) = delete;
singleton& operator=(singleton &&) = delete;
protected:
constexpr singleton() {}
public:
virtual ~singleton() = 0 {}
// インスタンスの生成
template <class... Types>
static T* construct(Types... args) {
return inst_m = new T(forward<Types>(args)...);
}
// インスタンスの破棄
static void destroy() {
delete inst_m;
inst_m = nullptr;
}
// インスタンスの取得
static T* inst() {
return (inst_m == nullptr) ? construct() : inst_m;
}
// インスタンスの有無
static bool is_exists_inst() { return inst_m != nullptr; }
};
}
#endif | [
"168iroha@168iroha.net"
] | 168iroha@168iroha.net |
2550307805541a0ef93d7f7437354b3bb0f72aa2 | b8bc365f96bf72b4706d03db181f79946e5ca234 | /DirectX11/Mouse.cpp | b7564267a6118646f816a5698d56abfea392861c | [] | no_license | minkipro/myDirectX11 | 4d37801914b083d27b5c22c0b3d8c8132112b1cb | d072df515e8c0cba1199c27b21c3b5f099337c50 | refs/heads/master | 2020-08-12T11:28:34.814623 | 2019-11-11T08:56:58 | 2019-11-11T08:56:58 | 214,759,152 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,377 | cpp | #include "MinkiWin.h"
#include "Mouse.h"
std::pair<int, int> Mouse::GetPos() const noexcept
{
return { x,y };
}
int Mouse::GetPosX() const noexcept
{
return x;
}
int Mouse::GetPosY() const noexcept
{
return y;
}
bool Mouse::IsInWindow() const noexcept
{
return isInWindow;
}
bool Mouse::LeftIsPressed() const noexcept
{
return leftIsPressed;
}
bool Mouse::RightIsPressed() const noexcept
{
return rightIsPressed;
}
std::optional<Mouse::Event> Mouse::Read() noexcept
{
if (buffer.size() > 0u)
{
Mouse::Event e = buffer.front();
buffer.pop();
return e;
}
return {};
}
void Mouse::Flush() noexcept
{
buffer = std::queue<Event>();
}
void Mouse::OnMouseMove(int newx, int newy) noexcept
{
x = newx;
y = newy;
buffer.push(Mouse::Event(Mouse::Event::Type::Move, *this));
TrimBuffer();
}
void Mouse::OnMouseLeave() noexcept
{
isInWindow = false;
buffer.push(Mouse::Event(Mouse::Event::Type::Leave, *this));
TrimBuffer();
}
void Mouse::OnMouseEnter() noexcept
{
isInWindow = true;
buffer.push(Mouse::Event(Mouse::Event::Type::Enter, *this));
TrimBuffer();
}
void Mouse::OnLeftPressed(int x, int y) noexcept
{
leftIsPressed = true;
buffer.push(Mouse::Event(Mouse::Event::Type::LPress, *this));
TrimBuffer();
}
void Mouse::OnLeftReleased(int x, int y) noexcept
{
leftIsPressed = false;
buffer.push(Mouse::Event(Mouse::Event::Type::LRelease, *this));
TrimBuffer();
}
void Mouse::OnRightPressed(int x, int y) noexcept
{
rightIsPressed = true;
buffer.push(Mouse::Event(Mouse::Event::Type::RPress, *this));
TrimBuffer();
}
void Mouse::OnRightReleased(int x, int y) noexcept
{
rightIsPressed = false;
buffer.push(Mouse::Event(Mouse::Event::Type::RRelease, *this));
TrimBuffer();
}
void Mouse::OnWheelUp(int x, int y) noexcept
{
buffer.push(Mouse::Event(Mouse::Event::Type::WheelUp, *this));
TrimBuffer();
}
void Mouse::OnWheelDown(int x, int y) noexcept
{
buffer.push(Mouse::Event(Mouse::Event::Type::WheelDown, *this));
TrimBuffer();
}
void Mouse::TrimBuffer() noexcept
{
while (buffer.size() > bufferSize)
{
buffer.pop();
}
}
void Mouse::OnWheelDelta(int x, int y, int delta) noexcept
{
wheelDeltaCarry += delta;
while (wheelDeltaCarry >= WHEEL_DELTA)
{
wheelDeltaCarry -= WHEEL_DELTA;
OnWheelUp(x, y);
}
while (wheelDeltaCarry <= -WHEEL_DELTA)
{
wheelDeltaCarry += WHEEL_DELTA;
OnWheelDown(x, y);
}
}
| [
"ghkdalsrl222@gmail.com"
] | ghkdalsrl222@gmail.com |
ef64243bd93f6975e6facb0def89ec568a2f2884 | 525d7f39d177b0bdc8377fd129b0cec222d4c381 | /Classes/Contact/MyContact.cpp | 73337f624f1e40c2e13f0e1e743f22294070fac5 | [] | no_license | jpollo/ShootGame | 4d2e3d032087f0600636c4dc1bc93677b6c24dca | ee9dd7c6c1f7fbc5fb195b1c88c7a1d40a6e36fd | refs/heads/master | 2016-09-05T17:26:49.094896 | 2013-01-20T12:26:56 | 2013-01-20T12:26:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 108 | cpp | /*
* MyContactA.cpp
*
* Created on: 2012-9-28
* Author: arch
*/
#include "Contact/MyContact.h"
| [
"jasonllinux@gmail.com"
] | jasonllinux@gmail.com |
0d32856ef905c8e23c5cb315b0d56084e9a9f9b2 | b34e75714baec2b521e05b6835e8c2c8bd325827 | /chip8-lib/src/CKeyboard.cpp | f064fc07a2d5797e2cb88ebeb123575f5cff88c4 | [] | no_license | captainkent/chip8 | 20483850adc9a3edc22ccfcec4672fb18bb1ea78 | 9166a82e612af0a7e1419d47ed926cf2e2b10d65 | refs/heads/master | 2021-04-21T15:41:25.795730 | 2020-04-02T15:26:09 | 2020-04-02T15:26:09 | 249,792,867 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 302 | cpp | #include "CKeyboard.h"
CKeyboard::CKeyboard()
{
the_keyboard = {};
}
void
CKeyboard::set_key_state(int a_key, int a_state)
{
the_keyboard[a_key] = a_state;
}
uint8_t
CKeyboard::get_key_state(int a_key)
{
return the_keyboard[a_key];
}
size_t
CKeyboard::get_size()
{
return the_keyboard.size();
} | [
"jamesrkent@outlook.com"
] | jamesrkent@outlook.com |
113c21d328c3e59ea5d36164b9906b52295371b5 | 6eff174b79a8cc92127ee0653895a85786eab971 | /src/Object/Component/SkinnedMeshRenderer.cpp | 942babcdd8c6b05c3a41a57489e96707a4784c37 | [
"MIT"
] | permissive | lqq1985/Theodore | 5e2a6d8a7c5de5038ea7024f000af5e544dc94c9 | b9d4e228ba7cc90f5838eaf03db81e91c82543d3 | refs/heads/master | 2020-08-28T18:59:40.409194 | 2019-01-24T15:33:31 | 2019-01-24T15:33:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 430 | cpp | #include "SkinnedMeshRenderer.h"
namespace Theodore {
SkinnedMeshRenderer::SkinnedMeshRenderer() : Renderer("SkinnedMeshRenderer") {}
SkinnedMeshRenderer::~SkinnedMeshRenderer() {}
void SkinnedMeshRenderer::Update(float deltaTime) {}
void SkinnedMeshRenderer::Render() {}
bool SkinnedMeshRenderer::CompareEquality(const Object& rhs) const { return false; }
bool SkinnedMeshRenderer::Destroy() { return false; }
} | [
"alsrudgns99@gmail.com"
] | alsrudgns99@gmail.com |
5636a0caa8cb2cc5707d23ddef5ace1b3287ff88 | 73978bf14650a1ff02b010f820a535fd12998be8 | /Roe Semester Project v2/slime.h | e7aa6c13ef698897b2e9263d23db5a3f2781aef5 | [] | no_license | ExecutiveElf/Roe-Semester-Project | ad3e3e4e91326d986e2d192afd51d117d90d78f4 | 308726e6732aeb879760d515573dec970c7ef45a | refs/heads/master | 2021-03-09T19:47:42.843767 | 2020-05-06T22:45:43 | 2020-05-06T22:45:43 | 246,373,979 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 135 | h | #ifndef slime_h
#define slime_h
#include "monsters.h"
class slime : public monster
{
public:
slime();
~slime();
private:
};
#endif
| [
"benroe650@yahoo.com"
] | benroe650@yahoo.com |
be21dbef01ab6364d8b5b03c6e76f90b28d54d4a | 41f637206721d2007ee32d90bdf9cefce7231b94 | /C/CaveEscape/src/cave_escape_10.cpp | b0134e888796b6e4f0cd470dcd6642570c998466 | [] | no_license | sylvietrewhella/cave-escape | e51f5fad3b86eec50c9025f4b1f701ebf7e63eb4 | 4db2560efeab980a71ccfa66d7c51870a9037601 | refs/heads/master | 2020-12-27T09:30:59.622456 | 2016-09-02T20:44:22 | 2016-09-02T20:44:22 | 67,190,675 | 0 | 0 | null | 2016-09-02T04:47:46 | 2016-09-02T04:47:46 | null | UTF-8 | C++ | false | false | 7,188 | cpp | #include <stdio.h>
#include <stdlib.h>
#include "SwinGame.h"
#define GRAVITY 0.08
#define MAX_SPEED 5
#define JUMP_RECOVERY_BOOST 2
#define FOREGROUND_FOREROOF_POLE_SCROLL_SPEED -2
#define BACKGROUND_SCROLL_SPEED -1
#define NUM_POLES 4
typedef struct pole_data
{
bool score_limiter;
sprite up_pole, down_pole;
} pole_data;
typedef struct pole_data poles[NUM_POLES];
typedef struct background_data
{
sprite foreroof, foreground, background;
} background_data;
enum player_state{MENU, PLAY};
typedef struct player
{
sprite sprite;
int score;
bool is_dead;
player_state state;
} player;
typedef struct game_data
{
player player;
background_data scene;
poles poles;
} game_data;
player get_new_player()
{
player result;
result.sprite = create_sprite(bitmap_named("Player"), animation_script_named("PlayerAnimations"));
sprite_set_x(result.sprite, screen_width() / 2 - sprite_width(result.sprite));
sprite_set_y(result.sprite, screen_height() / 2);
sprite_start_animation(result.sprite, "Fly");
result.score = 0;
result.is_dead = false;
result.state = MENU;
return result;
}
pole_data get_random_poles()
{
pole_data result;
result.up_pole = create_sprite(bitmap_named("UpPole"));
result.down_pole = create_sprite(bitmap_named("DownPole"));
sprite_set_x(result.up_pole, screen_width() + rnd(1200));
sprite_set_y(result.up_pole, screen_height() - sprite_height(result.up_pole) - rnd(bitmap_height(bitmap_named("Foreground"))));
sprite_set_x(result.down_pole, sprite_x(result.up_pole));
sprite_set_y(result.down_pole, rnd(bitmap_height(bitmap_named("Foreroof"))));
sprite_set_dx(result.up_pole, FOREGROUND_FOREROOF_POLE_SCROLL_SPEED);
sprite_set_dx(result.down_pole, FOREGROUND_FOREROOF_POLE_SCROLL_SPEED);
result.score_limiter = true;
return result;
}
background_data get_new_background()
{
background_data result;
result.background = create_sprite(bitmap_named("Background"));
sprite_set_x(result.background, 0);
sprite_set_y(result.background, 0);
sprite_set_dx(result.background, BACKGROUND_SCROLL_SPEED);
result.foreground = create_sprite(bitmap_named("Foreground"), animation_script_named("ForegroundAminations"));
sprite_set_x(result.foreground, 0);
sprite_set_y(result.foreground, screen_height() - sprite_height(result.foreground));
sprite_set_dx(result.foreground, FOREGROUND_FOREROOF_POLE_SCROLL_SPEED);
sprite_start_animation(result.foreground, "Fire");
result.foreroof = create_sprite(bitmap_named("Foreroof"));
sprite_set_x(result.foreroof, 0);
sprite_set_y(result.foreroof, 0);
sprite_set_dx(result.foreroof, FOREGROUND_FOREROOF_POLE_SCROLL_SPEED);
return result;
}
void handle_input(player *player)
{
if (key_typed(SPACE_KEY) && (player->state = PLAY))
{
sprite_set_dy(player->sprite, sprite_dy(player->sprite) - JUMP_RECOVERY_BOOST);
}
else if (key_typed(SPACE_KEY))
{
player->state = PLAY;
}
}
void check_for_collisions(game_data *game)
{
int i;
if (sprite_collision(game->player.sprite, game->scene.foreground) || sprite_collision(game->player.sprite, game->scene.foreroof))
{
game->player.is_dead = true;
return;
}
for (i = 0; i < NUM_POLES; i++)
{
if (sprite_collision(game->player.sprite, game->poles[i].up_pole) || sprite_collision(game->player.sprite, game->poles[i].down_pole))
{
game->player.is_dead = true;
return;
}
}
}
void reset_pole_data(pole_data *poles)
{
free_sprite(poles->up_pole);
free_sprite(poles->down_pole);
*poles = get_random_poles();
}
void reset_player(player *player)
{
free_sprite(player->sprite);
*player = get_new_player();
}
void reset_game(game_data *game)
{
int i;
reset_player(&game->player);
for (i = 0; i < NUM_POLES; i++)
{
reset_pole_data(&game->poles[i]);
}
}
void update_velocity(sprite player)
{
sprite_set_dy(player, sprite_dy(player) + GRAVITY);
if (sprite_dy(player) > MAX_SPEED)
{
sprite_set_dy(player, MAX_SPEED);
}
else if (sprite_dy(player) < -(MAX_SPEED))
{
sprite_set_dy(player, -(MAX_SPEED));
}
}
void update_poles(pole_data *poles, player *player)
{
update_sprite(poles->up_pole);
update_sprite(poles->down_pole);
if ((sprite_x(poles->up_pole) < sprite_x(player->sprite)) && (poles->score_limiter == true))
{
poles->score_limiter = false;
player->score++;
}
if ((sprite_x(poles->up_pole) + sprite_width(poles->up_pole) < 0) && (sprite_x(poles->down_pole) + sprite_width(poles->down_pole) < 0))
{
reset_pole_data(poles);
}
}
void update_poles_array(poles poles_array, player *player)
{
int i;
for (i = 0; i < NUM_POLES; i++)
{
update_poles(&poles_array[i], player);
}
}
void update_background(background_data scene)
{
update_sprite(scene.foreground);
update_sprite(scene.foreroof);
update_sprite(scene.background);
if (sprite_x(scene.foreground) <= -(sprite_width(scene.foreground) / 2))
{
sprite_set_x(scene.foreground, 0);
sprite_set_x(scene.foreroof, 0);
}
if (sprite_x(scene.background) <= -(sprite_width(scene.background) / 2))
{
sprite_set_x(scene.background, 0);
}
}
void update_player(player player)
{
if (player.state == PLAY)
{
update_velocity(player.sprite);
}
update_sprite(player.sprite);
}
void update_game(game_data *game)
{
if (!game->player.is_dead)
{
check_for_collisions(game);
handle_input(&game->player);
update_background(game->scene);
update_player(game->player);
if (game->player.state == PLAY)
{
update_poles_array(game->poles, &game->player);
}
}
else
{
reset_game(game);
}
}
void draw_poles(pole_data poles)
{
draw_sprite(poles.up_pole);
draw_sprite(poles.down_pole);
}
void draw_poles_array(poles poles_array)
{
int i;
for (i = 0; i < NUM_POLES; i++)
{
draw_poles(poles_array[i]);
}
}
void draw_game(game_data *game)
{
char str[15];
sprintf(str, "%d", game->player.score);
draw_sprite(game->scene.background);
draw_poles_array(game->poles);
draw_sprite(game->scene.foreroof);
draw_sprite(game->scene.foreground);
draw_sprite(game->player.sprite);
if (game->player.state == PLAY)
{
draw_text(str, COLOR_WHITE, "GameFont", 10, 0);
}
else if (game->player.state == MENU)
{
draw_bitmap(bitmap_named("Logo"), 0, 40);
draw_text("PRESS SPACE!",
COLOR_WHITE,
"GameFont",
screen_width() / 2 - text_width(font_named("GameFont"), "PRESS SOACE!") / 2,
sprite_y(game->player.sprite) + text_height(font_named("GameFont"), " ") * 2);
}
}
void set_up_game(game_data *game)
{
int i;
load_resource_bundle_named("CaveEscape", "CaveEscape.txt", false);
for (i = 0; i < NUM_POLES; i++)
{
game->poles[i] = get_random_poles();
}
game->player = get_new_player();
game->scene = get_new_background();
fade_music_in("GameMusic", -1, 15000);
}
int main()
{
game_data game;
open_graphics_window("Cave Escape", 432, 768);
set_up_game(&game);
do
{
process_events();
clear_screen(ColorWhite);
update_game(&game);
draw_game(&game);
refresh_screen();
} while(!window_close_requested());
return 0;
}
| [
"rwilson@swin.edu.au"
] | rwilson@swin.edu.au |
f948109352dcc4b9d5410b882440a5e413bcc354 | 7e11249f955dd694e8993d07701eb50ca89991c0 | /pro7-b.cpp | 2f873e2b2478333114e3bcf7ac0440801872650f | [] | no_license | priyanka-cse/ada_programs | a111b1f24eee0f98fbc8d588115efb0091a94d58 | 1fb9788c2c987194765fdbaa273015eacea23338 | refs/heads/master | 2020-06-30T23:41:11.953468 | 2019-11-20T07:08:35 | 2019-11-20T07:08:35 | 200,985,256 | 0 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,284 | cpp | #include<bits/stdc++.h>
using namespace std;
int max(int a, int b)
{
return (a > b) ? a : b;
}
int knapsack_dp(int n, int M, int w[], int p[])
{
int i,j;
int knapsack[n+1][M+1];
for(i=0;i<=n;i++)
knapsack[i][0]=0;
for(j=0;j<=M;j++)
knapsack[0][j]=0;
for(i=1;i<=n;i++)
{
for(j=1;j<=M;j++)
{
if(w[i-1]<=j)
{
knapsack[i][j]=max(knapsack[i-1][j],p[i-1]+knapsack[i-1][j-w[i-1]]);
}
else
{
knapsack[i][j]=knapsack[i-1][j];
}
}
}
return knapsack[n][M];
}
int main()
{
int i;
int n;
int M;
cout<<"Enter the no. of items ";
cin>>n;
int w[n];
int p[n];
cout<<"Enter the weight and price of all items"<<endl;
for(i=0;i<n;i++)
{
cin>>w[i]>>p[i];
}
cout<<"enter the capacity of knapsack ";
cin>>M;
int result=knapsack_dp(n,M,w,p);
cout<<"The maximum value of items that can be put into knapsack is :"<<result<<endl;
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
a33277c18a42edf32b203a4bbd516fc60515fc78 | 9a526e15a844d444fb1e3503efb67c8cc01c94d4 | /StructProgrammingLab2/lab3/lab3.cpp | 34daa59e91ea75c6e82fde50ffb4856c0eebbafc | [] | no_license | Pavkazzz/MephiStructProgramming | a6ab5082e39b048e3b2b1f34eed15d0259984f6d | b9c9add70fbfb5ad58478ff4a7809908e277d16d | refs/heads/master | 2020-06-30T17:14:28.881219 | 2017-05-03T04:46:10 | 2017-05-03T04:46:10 | 67,521,484 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 9,192 | cpp | #include <limits>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include "lab3.h"
OrderedTable::OrderedTable(const char *filename)
{
for (size_t i=0; i<MAX_SIZE; i++) {
node[i] = new Node;
}
this->filename = filename;
current_size = 0;
closest_after_search = 0;
}
OrderedTable::~OrderedTable()
{
for (size_t i=0; i<MAX_SIZE; i++) {
if (node[i]->info != NULL) {
Item *item = node[i]->info;
while(item != NULL) {
Item *next_item = item->next;
delete item;
item = next_item;
}
}
delete node[i];
}
}
bool OrderedTable::addItem(int key, const char str[STRING_SIZE])
{
Node *foundNode = findPlaceForNewNode(key);
if (foundNode == NULL) {
return false;
}
size_t string_length = strlen(str) + 1;
if (foundNode->info == NULL) {
Item *item = new Item;
item->next = NULL;
item->release = 0;
item->string = (char *)malloc(string_length * sizeof(char));
strncpy(item->string, str, string_length);
foundNode->info = item;
foundNode->key = key;
current_size++;
} else {
/// Add another item
// Item *item = foundNode->info;
// int last_relase = item->release;
// last_relase++;
Item *item = new Item;
item->release = foundNode->info->release+1;
item->next = foundNode->info;
item->string = (char *)malloc(string_length * sizeof(char));
strncpy(item->string, str, string_length);
foundNode->info = item;
}
/// TODO: return status if fail
return true;
}
//Item *OrderedTable::findItem(int key, int rel)
//{
// Node *node = findNode(key);
// /// found node
// if (node->key == key && node->info != NULL) {
// Item *item = node->info;
// while(item != NULL) {
// if(item->release == rel) {
// return item;
// }
// item = item->next;
// }
// }
// return NULL;
//}
//Node *OrderedTable::findNode(int key)
//{
// /// search in added
// for (int i=0; i<current_size; i++) {
// if (node[i]->info != NULL) {
// if (node[i]->key == key) {
// return node[i];
// }
// }
// }
// /// find the first empty
// for (int i=0; i<MAX_SIZE; i++) {
// if (node[i]->info == NULL) {
// return node[i];
// }
// }
// /// All field's are filled
// /// What to do?
// return NULL;
//}
Node *OrderedTable::findPlaceForNewNode(int key)
{
if (current_size == 0 ) {
return node[0];
}
if (current_size == MAX_SIZE) {
return NULL;
}
/// Если нашли с таким ключом
Node *node_b = binarySearch(key, current_size);
if (node_b != NULL) {
return node_b;
}
for (size_t j=current_size; j>closest_after_search; j--) {
// node[j] = node[j-1];
memcpy(node[j], node[j-1], sizeof(Node));
}
node[closest_after_search]->info = NULL;
node[closest_after_search]->key = -1;
return node[closest_after_search];
}
Item *OrderedTable::findBinaryItem(int key, int rel)
{
Node *node = findBinaryNode(key);
/// found node
if (node != NULL) {
Item *item = node->info;
while(item != NULL) {
if(item->release == rel) {
return item;
}
item = item->next;
}
}
return NULL;
}
Node *OrderedTable::findBinaryNode(int key)
{
return binarySearch(key, current_size);
}
Node *OrderedTable::binarySearch(int key, size_t last_size)
{
size_t first = 0;
size_t last = last_size;
if (first == last) {
closest_after_search = 0;
return NULL;
}
if (key < node[first]->key) {
closest_after_search = 0;
return NULL;
}
if (key > node[last-1]->key) {
closest_after_search = last;
return NULL;
}
while (first < last) {
size_t mid = first + (last - first) / 2;
if (key <= node[mid]->key) {
last = mid;
} else {
first = mid + 1;
}
}
if (node[last] != NULL && node[last]->key == key) {
closest_after_search = last;
return node[last];
}
closest_after_search = last;
return NULL;
}
bool OrderedTable::removeItem(int key, int rel)
{
Node *node = findBinaryNode(key);
if (node != NULL) {
Item *item = node->info;
Item *prev_item = NULL;
while (item != NULL) {
if (item->release == rel) {
if (prev_item == NULL) {
node->info = item->next;
if (node->info == NULL) {
current_size--;
node->key = -1;
}
} else {
prev_item->next = item->next;
}
// prev_item = item;
delete item;
return true;
}
item->release--;
prev_item = item;
item = item->next;
}
}
return false;
}
bool OrderedTable::removeNode(int key)
{
Node *node = findBinaryNode(key);
if (node != NULL) {
Item *item = node->info;
Item *next_item = NULL;
while(item != NULL) {
next_item = item->next;
delete item;
item = next_item;
}
for (size_t j=current_size-1; j>closest_after_search; j--) {
memcpy(this->node[j-1], this->node[j], sizeof(Node));
}
this->node[current_size-1]->info = NULL;
this->node[current_size-1]->key = -1;
current_size--;
} else {
/// No item with this key
return false;
}
return true;
}
Node **OrderedTable::getAllNode()
{
return node;
}
int OrderedTable::getCurrentSize()
{
return current_size;
}
void OrderedTable::clearTable()
{
for (size_t i=0; i<MAX_SIZE; i++) {
if (node[i]->info != NULL) {
Item *item = node[i]->info;
while(item != NULL) {
Item *next_item = item->next;
delete item;
item = next_item;
}
}
delete node[i];
}
for (size_t i=0; i<MAX_SIZE; i++) {
node[i] = new Node;
node[i]->key = 0;
node[i]->info = NULL;
}
current_size = 0;
}
bool OrderedTable::serialize()
{
FILE *ptr_to_file;
ptr_to_file = fopen(filename, "wb");
if (!ptr_to_file) {
return false;
}
for (size_t i=0; i<MAX_SIZE; i++) {
fwrite(&node[i]->key, sizeof(node[i]->key), 1, ptr_to_file);
size_t pr_node;
if (node[i]->info == NULL) {
pr_node = 0;
} else {
pr_node = 1;
}
fwrite(&pr_node, sizeof(pr_node), 1, ptr_to_file);
Item *item = node[i]->info;
while(item != NULL) {
size_t len = strlen(item->string) + 1;
fwrite(&len, sizeof(size_t), 1, ptr_to_file);
fwrite(item->string, len, 1, ptr_to_file);
fwrite(&item->release, sizeof(item->release), 1, ptr_to_file);
size_t pr_end_item = 0;
if (item->next == NULL) {
pr_end_item = 1;
}
fwrite(&pr_end_item, sizeof(size_t), 1, ptr_to_file);
item = item->next;
}
}
pclose(ptr_to_file);
return true;
}
bool OrderedTable::desirialize()
{
FILE *ptr_to_file;
ptr_to_file = fopen(filename, "rb");
if (!ptr_to_file) {
return false;
}
clearTable();
for (size_t i=0; i<MAX_SIZE; i++) {
fread(&node[i]->key, sizeof(node[i]->key), 1, ptr_to_file);
node[i]->info = NULL;
size_t pr_node;
fread(&pr_node, sizeof(pr_node), 1, ptr_to_file);
if (pr_node == 1) {
Item *last_item = NULL;
size_t str_len;
for (;;) {
Item *item = new Item;
if (node[i]->info == NULL) {
node[i]->info = item;
} else {
last_item->next = item;
}
fread(&str_len, sizeof(str_len), 1, ptr_to_file);
item->string = new char[str_len];
fread(item->string, str_len, 1, ptr_to_file);
fread(&item->release, sizeof(item->release), 1, ptr_to_file);
size_t pr_end_item;
fread(&pr_end_item, sizeof(pr_end_item), 1, ptr_to_file);
if (pr_end_item > 0) {
break;
} else {
last_item = item;
}
}
}
}
calculateCurrentSize();
pclose(ptr_to_file);
return true;
}
const char *OrderedTable::getFilename()
{
return filename;
}
void OrderedTable::calculateCurrentSize()
{
current_size = 0;
for (size_t i=0; i<MAX_SIZE; i++) {
if (node[i]->info != NULL) {
current_size++;
}
}
}
| [
"pavel-mosein@yandex.ru"
] | pavel-mosein@yandex.ru |
51d5f58cbb49b7a05a80783753f18155149e3304 | bdf536c4e5b51ade2ddbbb5deb03f39e6ba2e38c | /SFML/Enemy.cpp | 9aa4966f9730476175499549cee77edd9e0d7261 | [] | no_license | zemin-xu/adventure-of-lolo | 0b12a8048e1fb944f9b8e9ecb4f8b25f7cfa9259 | b9d1cf3a65a1c73b75b9e73f3f42a7f24ba088f0 | refs/heads/master | 2023-04-09T19:14:45.885912 | 2021-04-10T09:38:24 | 2021-04-10T09:38:24 | 214,372,547 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,033 | cpp | //
// Enemy.cpp
// SFML
//
// Created by ZEMIN on 17/10/2019.
// Copyright © 2019 ZEMIN. All rights reserved.
//
#include "LIB.hpp"
using namespace std;
Enemy::Enemy()
{
}
Enemy::Enemy(int x, int y, int length, int height, sf::Texture *texture, int numHorizontal, int numVertical, int kind) : Creature(x, y, length, height, texture, numHorizontal, numVertical, kind)
{
speed = 70.0f;
dirHorizontal = 1;
dirVertical = 1;
canMove = true;
isUpDownBlocked = 0;
isLeftRightBlocked = 0;
timer = 0;
}
void Enemy::ScanAround(vector<Element> &obstacles, vector<Movable> &movables, vector<Collectable> &collectables, vector<Trigger> &triggers ,vector<MovableEnemy> &eggs, vector<Enemy> &enemies, const float deltaTime, Level & level)
{
Creature::ScanAround(obstacles, movables, collectables, triggers, eggs, enemies, deltaTime, level);
if (!canMove)
{
if (state == Forward_M && isUpDownBlocked == 0)
isUpDownBlocked = 1;
if (state == Backward_M && isUpDownBlocked == 0)
isUpDownBlocked = 2;
if (state == Backward_M && isUpDownBlocked == 1)
isUpDownBlocked = 3;
if (state == Forward_M && isUpDownBlocked == 2)
isUpDownBlocked = 3;
if (state == Leftward_M && isLeftRightBlocked == 0)
isLeftRightBlocked = 1;
if (state == Rightward_M && isLeftRightBlocked == 0)
isLeftRightBlocked = 2;
if (state == Rightward_M && isLeftRightBlocked == 1)
isLeftRightBlocked = 3;
if (state == Leftward_M && isLeftRightBlocked == 2)
isLeftRightBlocked = 3;
}
}
void Enemy::ChangeDirection()
{
if (isUpDownBlocked ==3 && isLeftRightBlocked == 3)
state = Forward_M;
else if (isUpDownBlocked == 3 && isLeftRightBlocked == 1)
state = Rightward_M;
else if (isUpDownBlocked == 3 && isLeftRightBlocked == 2)
state = Leftward_M;
else if (isLeftRightBlocked == 3 && isUpDownBlocked == 1)
state = Backward_M;
else if (isLeftRightBlocked == 3 && isUpDownBlocked == 2)
state = Forward_M;
else if (isUpDownBlocked == 2 && isLeftRightBlocked == 1)
state = Forward_M;
else if (isUpDownBlocked == 1 && isLeftRightBlocked == 1)
state = Backward_M;
else if (isUpDownBlocked == 2 && isLeftRightBlocked == 2)
state = Forward_M;
else if (isUpDownBlocked == 1 && isLeftRightBlocked == 2)
state = Backward_M;
else if (isUpDownBlocked == 3 && isLeftRightBlocked == 0)
state = Leftward_M;
else if (isUpDownBlocked == 0 && isLeftRightBlocked == 3)
state = Forward_M;
else if (isUpDownBlocked == 0 && isLeftRightBlocked == 1)
state = Forward_M;
else if (isUpDownBlocked == 0 && isLeftRightBlocked == 2)
state = Forward_M;
else if (isUpDownBlocked == 1 && isLeftRightBlocked == 0)
state = Leftward_M;
else if (isUpDownBlocked == 2 && isLeftRightBlocked == 0)
state = Leftward_M;
}
/* be executed each 1 sec to redirect */
void Enemy::FollowDirection(Element* player)
{
float a = abs(player->centerX - centerX);
float b = abs(player->centerY - centerY);
if ((player->centerX - centerX < -4) && a > b)
state = Leftward_M;
else if (player->centerX - centerX > 4)
state = Rightward_M;
else if (player->centerY - centerY < 0)
state = Backward_M;
else if (player->centerY - centerY > 0)
state = Forward_M;
}
void Enemy::UpdateVariable()
{
switch (state) {
case Forward_M:
{
dirHorizontal = 0;
dirVertical = 1;
}
break;
case Backward_M:
{
dirHorizontal = 0;
dirVertical = -1;
}
break;
case Leftward_M:
{
dirHorizontal = -1;
dirVertical = 0;
}
break;
case Rightward_M:
{
dirHorizontal = 1;
dirVertical = 0;
}
break;
default:
break;
}
}
void Enemy::Update(const float deltaTime, vector<Element> &obstacles, vector<Collectable> &collectables, vector<Movable> &movables, vector<Trigger> &triggers, vector<MovableEnemy> &eggs, vector<Enemy> &enemies, Element* player, Level & level)
{
timer += deltaTime;
if (timer > 0.2f)
{
FollowDirection(player);
isLeftRightBlocked = 0;
isUpDownBlocked = 0;
timer = 0.0f;
}
canMove = true;
ScanAround(obstacles, movables, collectables, triggers, eggs, enemies, deltaTime, level);
UpdateVariable();
UpdateMoveAnimation(1, 4, 4, 4, 2, 4, 3, 4);
ChangeDirection();
Move(deltaTime);
}
void Enemy::Render(sf::RenderWindow &window)
{
UpdateIdleAnimation(1, 4, 4, 4, 2, 4, 3, 4);
Element::Render(window);
}
void Enemy::Fire(Level& level, Projectile& projectile)
{
cout << " enemy fire";
}
| [
"zemin.xu@yahoo.com"
] | zemin.xu@yahoo.com |
d2099c5cebc28abd71df3955203a18ecb48aced7 | c6ce94e25e27870210d91fd9cfb1076d74696ad8 | /FlyEngine/src/Managers/CollisionManager.h | 77efaeb713f88106e1ae40e564623a63175eb13c | [] | no_license | fenilshingala/Robotest | 6e3dba4d1688f5b445b90fbcbb6011f9b7a8f1d9 | 72429fc86d003030669bb00ca2ae9f84b2665d39 | refs/heads/master | 2020-06-01T22:10:14.959145 | 2019-06-09T00:58:54 | 2019-06-09T00:58:54 | 190,945,529 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,168 | h | /* Start Header -------------------------------------------------------
Copyright (C) 2019 DigiPen Institute of Technology.
Reproduction or disclosure of this file or its contents without the prior
written consent of DigiPen Institute of Technology is prohibited.
Author: Shashwat Pandey, shashwat.pandey, 60003718
- End Header --------------------------------------------------------*/
#pragma once
#include <list>
#include "../Components/Collider.h"
#include "../Components/Body.h"
#include "../Components/Shape.h"
class Contact
{
public:
Contact(Collider*, Collider*);
Collider* mpCollider[2];
glm::vec2 colNormal;
float penetrationDepth;
glm::vec3 colPoint;
float e;
float cSF;
float cDF;
//private:
Body* A;
Body* B;
public:
void ApplyImpulse() {
glm::vec2 relativeVel = B->mVel - A->mVel;
float velNormal = glm::dot(relativeVel, colNormal);
if (velNormal > 0) return; // means the objects are separating
// linear impulse
// TODO upgrade to angular impulse
float impulseMagnitude = -(1.0f + e) * velNormal / (A->mInvMass + B->mInvMass);
glm::vec2 impulseVec = impulseMagnitude * colNormal;
A->mVel -= impulseVec * A->mInvMass;
B->mVel += impulseVec * B->mInvMass;
// TODO implement friction with more contact points
// having one contact point makes it unstable and unusable
if(A->applyFriction && B->applyFriction)
ApplyFrictionImpulse(impulseMagnitude);
}
void ApplyFrictionImpulse(float impulse) {
glm::vec2 relativeVel = B->mVel - A->mVel;
float relativeVelNormal = glm::dot(relativeVel, colNormal);
glm::vec2 tangent = relativeVel - (colNormal * relativeVelNormal);
tangent = glm::normalize(tangent);
// check if tangent is nan
if (isnan(tangent.x) || (isnan(tangent.y))) {
return;
}
//std::cout << "tangent : x " << tangent.x << "tangent : y " << tangent.y << std::endl;
float fricImpulseMagnitude = -glm::dot(relativeVel, tangent) / (A->mInvMass + B->mInvMass);
// not applying zero impulse
if (fricImpulseMagnitude == 0.0f) return;
glm::vec2 frictionImpulse;
// Coulomb's law of friction
if(abs(fricImpulseMagnitude) < impulse * cSF)
frictionImpulse = fricImpulseMagnitude * tangent;
else
frictionImpulse = -impulse * tangent * cDF;
A->mVel -= frictionImpulse * A->mInvMass;
B->mVel += frictionImpulse * B->mInvMass;
}
void CorrectPenetration() {
float slop = 0.01f; // if penetration is greater than this only then correct it
float percent = 0.4f; // resolving 40% of the actual penetration depth
glm::vec2 correction = (std::max(penetrationDepth - slop, 0.0f) / (A->mInvMass + B->mInvMass)) * percent * colNormal;
A->mPos -= correction * A->mInvMass;
B->mPos += correction * B->mInvMass;
}
};
class CollisionManager
{
public:
CollisionManager();
~CollisionManager();
void Reset();
bool CheckCollisionAndGenerateContact(Shape *pShape1, glm::vec2 Pos1,
Shape *pShape2, glm::vec2 Pos2);
public:
std::list<Contact*> mContacts;
private:
bool (*CollisionFunctions[ShapeType::SHAPESNUM][ShapeType::SHAPESNUM])(Shape *pShape1, glm::vec2 Pos1,
Shape *pShape2, glm::vec2 Pos2, std::list<Contact*> &mContacts);
};
| [
"fenil.shingala@digipen.edu"
] | fenil.shingala@digipen.edu |
8d895671fe6d3cede433955a4e391f2e924be784 | 08267d01cf96c7d2f22014ecb826b336ec141d2c | /prefix.cpp | bd77f746872347932569b56bef6c88837178e426 | [] | no_license | OldTraveller/RandomCodingProblems | 364ff0ed79df57a9ad813eb38766b3215be5f8c5 | 1ad836ade2e0e17c5ff5cfe4552faaf9f88193c9 | refs/heads/master | 2020-08-22T23:52:22.261650 | 2019-10-21T14:53:56 | 2019-10-21T14:53:56 | 216,500,570 | 0 | 1 | null | 2019-10-21T14:53:58 | 2019-10-21T07:08:52 | C++ | UTF-8 | C++ | false | false | 3,257 | cpp | #include <bits/stdc++.h>
using namespace std ;
using ll = long long ;
int main() {
ios :: sync_with_stdio(false) ;
cin.tie( nullptr ) ;
cout.tie( nullptr ) ;
int t ;
cin >> t ;
while( t-- ) {
string name ;
cin >> name ;
ll n ;
cin >> n ;
ll countA = 0 ;
ll countB = 0 ;
ll number_of_times = 0 ;
vector< pair<ll,ll> > p ;
bool AgB = false ;
for( int i = 0 ; i < name.length() ; i++ ) {
if( name.at(i) == 'a' ) {
p.push_back( pair<ll,ll>( ++countA , countB ) ) ;
}
else {
p.push_back( pair<ll,ll>( countA , ++countB ) ) ;
}
if( countA > countB ) {
number_of_times++ ;
}
}
if( countA == countB ) {
number_of_times *= n ;
}
else if( countA > countB ) {
set<ll> positions ;
for( ll i = 0 ; i < p.size() ; i++ ) {
if( p[i].first <= p[i].second ) {
positions.insert(i) ;
}
}
while( positions.size() ) {
for( ll i = 0 ; i < p.size() ; i++ ) {
p[i].first += countA ;
p[i].second += countB ;
if( p[i].first > p[i].second ) {
number_of_times++ ;
}
}
for( set<ll> :: iterator it = positions.begin() ; it != positions.end() ; it++ ) {
if( p[*it].first > p[*it].second ) {
positions.erase(*it) ;
}
}
--n ;
}
AgB = true ;
}
else {
set<ll> positions ;
for( ll i = 0 ; i < p.size() ; i++ ) {
if( p[i].first > p[i].second ) {
positions.insert(i) ;
}
}
while( positions.size() ) {
for( ll i = 0 ; i < p.size() ; i++ ) {
p[i].first += countA ;
p[i].first += countB ;
if( p[i].first > p[i].second ) {
number_of_times++ ;
}
}
for( set<ll> :: iterator it = positions.begin() ; it != positions.end() ; it++ ) {
if( p[*it].first <= p[*it].second ) {
positions.erase(*it) ;
}
}
}
}
if( AgB ) {
number_of_times += (n-1)*name.length() ;
}
cout << number_of_times << endl ;
}
} | [
"noreply@github.com"
] | noreply@github.com |
858c8e3ad83ebfb58e9cba9ce589444306ac4aef | 40a3a2c715cb41e3d36888de28e1c386e4d98cf0 | /framework/Input/Headers/KeyToAscii.h | 54b8a2f0686f7faae7d60c4ca447d5101588858c | [
"MIT"
] | permissive | n0vasys/kigs | 4da3ee23b0f88a5c8d753e7782216a2e6cb88991 | a229516547f0de08b685ec78e40de5e5d03259e3 | refs/heads/master | 2022-10-23T10:11:50.953888 | 2020-06-17T15:07:14 | 2020-06-17T15:07:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,037 | h | #ifndef _KEY_TO_ASCII_H_
#define _KEY_TO_ASCII_H_
#include "CoreModifiable.h"
class KeyboardDevice;
// ****************************************
// * KeyToAscii class
// * --------------------------------------
/**
* \file KeyToAscii.h
* \class KeyToAscii
* \ingroup Input
* \brief abstract base class for key to ascii classes
* \author ukn
* \version ukn
* \date ukn
*/
// ****************************************
class KeyToAscii : public CoreModifiable
{
public:
DECLARE_ABSTRACT_CLASS_INFO(KeyToAscii,CoreModifiable,Input)
/**
* \brief constructor
* \fn KeyToAscii(const kstl::string& name,DECLARE_CLASS_NAME_TREE_ARG);
* \param name : instance name
* \param DECLARE_CLASS_NAME_TREE_ARG : list of arguments
*/
KeyToAscii(const kstl::string& name,DECLARE_CLASS_NAME_TREE_ARG);
/**
* \brief convert a keyCode to ascii code
* \fn virtual int Convert(unsigned Code) = 0;
* \param Code : key code to convert
* \return ascii code of the key
*/
virtual int Convert(unsigned Code) = 0;
};
#endif
| [
"antoine.fresse@assoria.com"
] | antoine.fresse@assoria.com |
0f8649601b37e342fa49e0b33ea1f882080e664f | 69c066e183cd3281dc1f9846d1c897d1b753bb78 | /Server/Source.cpp | 3892c18ade87644ae25a05633243b4dc01ee8379 | [] | no_license | Ernyoke/TCP-Chat-Server | 740294911e3c38a5c122280edb81a515048508d5 | 2f2f91669328925ca6cc41ee41df8f53ab5c4366 | refs/heads/master | 2020-06-05T12:27:07.545627 | 2014-05-08T05:34:20 | 2014-05-08T05:34:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,581 | cpp | #include "winsock2.h"
#include <map>
#include <iostream>
#include "User.h"
#include "ChatRoom.h"
#include "Data.h"
#include "Message.h"
using namespace std;
char RecvBuf[1024], SendBuf[1024];
int BufLen;
int main() {
map<int, User*> users;
map<int, ChatRoom*> rooms;
Data data;
// Initialize Winsock.
WSACleanup();
WSADATA wsaData;
int iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != NO_ERROR) {
printf("Error at WSAStartup()\n");
}
//----------------------
// Create a SOCKET for listening for
// incoming connection requests.
BufLen = strlen(RecvBuf);
SOCKET ListenSocket, SendSocket;
ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
SendSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (ListenSocket == INVALID_SOCKET) {
cout << "Error at socket(): %ld\n" << WSAGetLastError() << endl;
WSACleanup();
return 1;
}
//----------------------
// The sockaddr_in structure specifies the address family,
// IP address, and port for the socket that is being bound.
sockaddr_in service;
service.sin_family = AF_INET;
service.sin_addr.s_addr = INADDR_ANY;
service.sin_port = htons(12000);
ChatRoom room(0);
rooms.insert(pair<int, ChatRoom*>(0, &room));
if (bind( ListenSocket, (SOCKADDR*) &service, sizeof(service)) == SOCKET_ERROR) {
printf("bind() failed.\n");
closesocket(ListenSocket);
WSACleanup();
return 1;
}
//----------------------
// Listen for incoming connection requests.
// on the created socket
if (listen( ListenSocket, 1 ) == SOCKET_ERROR) {
cout << "Error listening on socket.\n";
closesocket(ListenSocket);
WSACleanup();
return 1;
}
//----------------------
// Create a SOCKET for accepting incoming requests.
SOCKET AcceptSocket;
char recBuf[4];
int recSize;
bool exists = false;
cout << "Waiting for client to connect...\n";
//----------------------
// Accept the connection.
while(true) {
AcceptSocket = accept( ListenSocket, NULL, NULL );
if (AcceptSocket == INVALID_SOCKET) {
cout << "accept failed: %d\n" << WSAGetLastError() << endl;
closesocket(ListenSocket);
WSACleanup();
return 1;
} else
cout << "Client connected.\n";
iResult = recv(AcceptSocket, recBuf, sizeof(int), MSG_WAITALL);
memcpy(&recSize, recBuf, sizeof(int));
char* rec = new char[recSize];
int x = recv(AcceptSocket, rec, recSize, MSG_WAITALL);
Message message;
message.createMessage(rec, recSize);
string uname = message.getBuffer();
User *u;
CRITICAL_SECTION critical;
InitializeCriticalSection(&critical);
EnterCriticalSection(&critical);
exists = false;
for(map<int, User*>::iterator it = users.begin(); it != users.end(); ++it) {
User* user = (*it).second;
if(user->getUserName().compare(uname) == 0) {
exists = true;
break;
}
}
if(!exists) {
int userID = data.getUserId();
u = new User(AcceptSocket, userID);
users.insert(pair<int, User*>(userID, u));
data.setUserId(userID);
u->setUserId(userID);
room.addUser(u);
u->assigneToRoom(&room);
u->setRoomList(&rooms);
u->setUserList(&users);
u->setData(&data);
string uname = message.getBuffer();
u->setUserName(uname);
}
LeaveCriticalSection(&critical);
if(!exists) {
Message m(1, 0, u->getUserId(), 1, "OK");
m.sendTo(u->getSocket());
u->start();
}
else {
Message m(1, 0, 0, 1, "ERROR");
m.sendTo(&AcceptSocket);
}
}
//---------------------------------------------
// Clean up and quit.
printf("Exiting.\n");
WSACleanup();
return 0;
} | [
"ervin509@yahoo.com"
] | ervin509@yahoo.com |
8846eebf325f3231079802563dece433008336fd | d27fb219084a4cfa82bbee4073a63e5f0d1ecd5f | /Qlay/Core.cpp | ab642e6f9ddff74d40f1950f8dfb056a29998a5a | [
"MIT"
] | permissive | sjgriffiths/Qlay | 14e2a8c36fe4e2e2a5bc82742409de022c01feed | 7504399f4f862125727e5744d1439d0fb525f38c | refs/heads/master | 2020-03-30T14:21:25.579572 | 2019-01-16T00:21:43 | 2019-01-16T00:21:43 | 151,313,869 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 821 | cpp | /**
* @file Core.cpp
*
* Implements basic and global library functionality.
*
* @author Sam Griffiths
*/
#include "Core.h"
namespace qlay
{
std::default_random_engine rng;
void init()
{
rng.seed(static_cast<unsigned>(
std::chrono::high_resolution_clock::now().time_since_epoch().count()
));
}
void init(unsigned seed)
{
rng.seed(seed);
}
bool chance(double p)
{
std::bernoulli_distribution dist(p);
return dist(rng);
}
double deg_to_rad(double angle)
{
return angle * PI / 180.0;
}
Mat kronecker_product(const Mat &a, const Mat &b)
{
Mat k(a.rows() * b.rows(), a.cols() * b.cols());
for (Eigen::Index i = 0; i < a.rows(); i++)
for (Eigen::Index j = 0; j < a.cols(); j++)
k.block(i * b.rows(), j * b.cols(), b.rows(), b.cols())
= a(i, j) * b;
return k;
}
}
| [
"13700330+sjgriffiths@users.noreply.github.com"
] | 13700330+sjgriffiths@users.noreply.github.com |
1d5aa07457687775143d2d3b2ced30e02df477b2 | da646f3e5daa38e140ae0d83906489b34727ddb4 | /detector_ultrasonic_sensors/ultrasonicSensorInterface/libraries/ros_lib/droneMsgsROS/UltrasonicRangeArduino.h | 547e874c159d1df266b84ac45b1074960d55f7a5 | [
"MIT"
] | permissive | sarthak268/Obstacle_Avoidance_for_Drone_Delivery | 2b1e671bbb651ba68aef48eca8fe4e43e3b10f77 | 7ca58e47a6d318b69af3a3daa55051fb16893493 | refs/heads/master | 2023-01-23T14:55:18.239476 | 2023-01-11T22:04:45 | 2023-01-11T22:04:45 | 134,289,715 | 32 | 18 | null | null | null | null | UTF-8 | C++ | false | false | 1,803 | h | #ifndef _ROS_droneMsgsROS_UltrasonicRangeArduino_h
#define _ROS_droneMsgsROS_UltrasonicRangeArduino_h
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include "ros/msg.h"
#include "std_msgs/Header.h"
#include "std_msgs/UInt8.h"
namespace droneMsgsROS
{
class UltrasonicRangeArduino : public ros::Msg
{
public:
std_msgs::Header header;
uint8_t id;
std_msgs::UInt8 range;
std_msgs::UInt8 freq;
bool ok;
virtual int serialize(unsigned char *outbuffer) const
{
int offset = 0;
offset += this->header.serialize(outbuffer + offset);
*(outbuffer + offset + 0) = (this->id >> (8 * 0)) & 0xFF;
offset += sizeof(this->id);
offset += this->range.serialize(outbuffer + offset);
offset += this->freq.serialize(outbuffer + offset);
union {
bool real;
uint8_t base;
} u_ok;
u_ok.real = this->ok;
*(outbuffer + offset + 0) = (u_ok.base >> (8 * 0)) & 0xFF;
offset += sizeof(this->ok);
return offset;
}
virtual int deserialize(unsigned char *inbuffer)
{
int offset = 0;
offset += this->header.deserialize(inbuffer + offset);
this->id = ((uint8_t) (*(inbuffer + offset)));
offset += sizeof(this->id);
offset += this->range.deserialize(inbuffer + offset);
offset += this->freq.deserialize(inbuffer + offset);
union {
bool real;
uint8_t base;
} u_ok;
u_ok.base = 0;
u_ok.base |= ((uint8_t) (*(inbuffer + offset + 0))) << (8 * 0);
this->ok = u_ok.real;
offset += sizeof(this->ok);
return offset;
}
const char * getType(){ return "droneMsgsROS/UltrasonicRangeArduino"; };
const char * getMD5(){ return "4ef4f38100122c42e7816667ccbcc205"; };
};
}
#endif | [
"sarthak16189@iiitd.ac.in"
] | sarthak16189@iiitd.ac.in |
d0aad383c0f978d2214d0556398f063cbb208421 | c80a6a3bfd29e1cfff7d8b55e8d66c19445641d8 | /quicksort.cpp | 631fb3cefa3e0a138291caf0ee6508f13a34fc7d | [] | no_license | sharababy/labexam2 | aa5b724f142f4a62401cd6c583626ea95d72e3e3 | f133cc7c7ddbbee8752350cdbfab6a176af8c3af | refs/heads/master | 2021-01-22T20:59:31.094941 | 2017-03-18T12:27:51 | 2017-03-18T12:27:51 | 85,381,485 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 897 | cpp | #include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
void quicksort(int array[],long long int start,long long int end);
long long int partition(int array[],long long int start,long long int end);
void quicksort(int array[],long long int start,long long int end){
int midplace;
if (start<end)
{
midplace = partition(array,start,end);
quicksort(array,start,midplace-1);
quicksort(array,midplace+1,end);
}
}
long long int partition(int array[],long long int start,long long int end){
int pivot,temp;
long long int pointer;
pointer = start-1;
pivot = array[end];
for (int i = start; i < end; ++i)
{
if (array[i]<=pivot)
{
pointer=pointer+1;
temp = array[pointer];
array[pointer] = array[i];
array[i] = temp;
}
}
temp = array[pointer+1];
array[pointer+1] = array[end];
array[end] = temp;
return (pointer+1);
}
| [
"shikhabassi@shikhabassis-MacBook-Air.local"
] | shikhabassi@shikhabassis-MacBook-Air.local |
8ee83b5fa8d120633ad74dd959618a642de2de98 | 04ac16c95f7b54c644e06020b68f1d1fb02ab7bb | /h/SEMAPHOR.H | 08657f293af5b0b949964132447785458cb35782 | [
"MIT"
] | permissive | ivanrakonjac/OS-kernel | 1cbdc00dc667a267f5728ba81b55f1462862ded2 | 94c64910dc900adc330455e61535443356c6ab5f | refs/heads/master | 2022-12-08T20:29:49.832106 | 2020-09-07T12:30:02 | 2020-09-07T12:30:02 | 204,068,074 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 415 | h | // File: semaphor.h
#ifndef _semaphor_h_
#define _semaphor_h_
typedef unsigned int Time;
class KernelSem;
class Semaphore {
public:
Semaphore (int init=1);
virtual ~Semaphore ();
virtual int wait (Time maxTimeToWait);
virtual int signal(int n=0);
int val () const; // Returns the current value of the semaphore
KernelSem* getKernelSem(){
return myImpl;
}
private:
KernelSem* myImpl;
};
#endif
| [
"rakonjacivan98@gmail.com"
] | rakonjacivan98@gmail.com |
bed4f460a8afc464b8d056b850dbb173f21ff10e | 6afe2968e68f7e678a196b7335eb6e95d37aa378 | /generalized_packrat_parser.cc | bcd4b466b256adddd6661c53e7eaee239e1f4412 | [
"MIT"
] | permissive | NariyoshiChida/GPEG | 98aadf603ed566abf967ac50d18956bb51cc128b | 0c43fb40514e02fa6edf5636b41a885034f53d90 | refs/heads/master | 2020-05-21T21:00:46.013711 | 2017-02-09T17:06:17 | 2017-02-09T17:06:17 | 63,883,712 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 32,194 | cc | #include"generalized_packrat_parser.h"
#include"grammar.h"
#include"slash.h"
#include"char.h"
#include"alternation.h"
#include"node.h"
#include"sequence.h"
#include"gpeg_string.h"
#include<iostream>
#include<string>
#include<vector>
#include<cassert>
#include<deque>
#include<sstream>
#include<cmath>
#include<map>
#include<set>
#include<functional>
using generalized_packrat_parser::GeneralizedPackratParser;
//bool show_trace = false; // duplicateになる
std::ostream& operator << (std::ostream& os, const GeneralizedPackratParser& gpp) {
os << "[[Generalized Packrat Parser]]";
return os;
}
inline std::string itos(int i) { std::stringstream ss; ss << i; return ss.str(); }
void GeneralizedPackratParser::set(Grammar *tmp) { grammar = tmp; }
// <--- encode --->
// replaced by dispatch_macro
void GeneralizedPackratParser::writeln(std::string s,int ID=-1,int indent=0) {
if( ID == -1 ) {
std::cout << std::string(indent*2,' ') << s << std::endl;
} else {
assert( ID < (int)buffer.size() );
buffer[ID] += ( std::string(indent*2,' ') + s + "\n" );
}
}
void GeneralizedPackratParser::write(std::string s,int ID=-1,int indent=0) {
if( ID == -1 ) {
std::cout << std::string(indent*2,' ') << s;
} else {
assert( ID < (int)buffer.size() );
buffer[ID] += ( std::string(indent*2,' ') + s );
}
}
void GeneralizedPackratParser::dump() {
std::cout << buffer[first_ID];
std::cout << std::endl;
for(int i=0;i<(int)prot.size();++i) {
std::cout << "deque<int> " << prot[i] << "();" << std::endl;
}
std::cout << std::endl;
for(int i=0;i<(int)buffer.size();++i) {
if( i == first_ID || i == last_ID ) continue;
std::cout << buffer[i];
std::cout << std::endl;
}
std::cout << buffer[last_ID];
}
void GeneralizedPackratParser::write_packrat_return(int ID) {
// -1 is for adjustment by first_ID
writeln("if(memo.count(key("+itos(ID-1)+","+ptr_name+"))) {",ID,1);
writeln("return memo[key("+itos(ID-1)+","+ptr_name+")];",ID,2);
writeln("}",ID,1);
writeln("int " + backtracking_ptr_for_packrat + itos(ID-1) +"=" + ptr_name + ";",ID,1);
}
void GeneralizedPackratParser::write_packrat_assign(int ID,int indent) {
writeln("return memo[key("+itos(ID-1)+","+backtracking_ptr_for_packrat+itos(ID-1)+")] = result;",ID,indent);
}
void GeneralizedPackratParser::write_hash_function(int ID,int indent,int base_size) {
long long base = 1;
for(int i=0;i<base_size;++i) {
base *= 10LL;
}
writeln("const long long base = " + itos(base) + "; // for hash",ID,indent);
writeln("",ID,indent);
writeln("namespace std {",ID,indent++);
writeln("template <>",ID,indent);
writeln("class hash<std::pair<int, int>> {",ID,indent++);
writeln("public:",ID,indent);
writeln("size_t operator()(const std::pair<int, int>& x) const {",ID,indent++);
writeln("return base * x.second + x.first;",ID,indent);
writeln("}",ID,--indent);
writeln("};",ID,--indent);
writeln("}",ID,--indent);
}
void GeneralizedPackratParser::encode() {
buffer.clear();
first_ID = buffer.size();
buffer.push_back("");
//writeln("#include<bits/stdc++.h>",first_ID);
writeln("#include<iostream>",first_ID);
writeln("#include<chrono>",first_ID);
writeln("#include<deque>",first_ID);
writeln("#include<cassert>",first_ID);
writeln("#include<climits>",first_ID);
if( packrat ) {
if( hash_map ) {
writeln("#include<unordered_map>",first_ID);
} else {
writeln("#include<map>",first_ID);
}
}
writeln("#include<algorithm>",first_ID);
writeln("",first_ID);
writeln("#define FAIL -1",first_ID);
writeln("",first_ID);
writeln("using namespace std;",first_ID);
writeln("",first_ID);
writeln("int m;",first_ID);
writeln("int "+ptr_name+";",first_ID);
writeln("string I;",first_ID);
if( packrat ) {
writeln("typedef pair<int,int> key;",first_ID);
}
std::vector<Nonterminal*> nonterminals = grammar->getNonterminals();
assert( nonterminals.size() );
for(int i=0;i<(int)nonterminals.size();++i) {
encode(nonterminals[i],-1,0);
}
if( hash_map ) {
int base_size = (int)log10(suffix) + 1;
write_hash_function(first_ID,0,base_size);
}
if(packrat) {
if( hash_map ) {
writeln("unordered_map<key,deque<int>> memo;",first_ID);
} else {
writeln("map<key,deque<int>> memo;",first_ID);
}
}
last_ID = buffer.size();
buffer.push_back("");
writeln("",last_ID);
writeln("int main() {",last_ID);
writeln("getline(cin,I);",last_ID,1);
writeln("m = (int)I.size();",last_ID,1);
writeln(ptr_name+"=0;",last_ID,1);
// 完全マッチにしたければ parse_XXX(0) == true && ptr_name == (int)I.size()
if( matching_time ) {
writeln("auto st = chrono::system_clock::now();",last_ID,1);
}
writeln("deque<int> result = parse_"+nonterminals[0]->getName()+"();",last_ID,1);
if( matching_time ) {
writeln("auto ed = chrono::system_clock::now();",last_ID,1);
}
writeln("sort(result.begin(),result.end());",last_ID,1);
writeln("result.erase(unique(result.begin(),result.end()),result.end());",last_ID,1);
writeln("for(int i=0;i<(int)result.size();++i) {",last_ID,1);
writeln("if(result[i] == -1) {",last_ID,2);
writeln("cout << \"fail\" << endl;",last_ID,3);
writeln("} else {",last_ID,2);
writeln("cout << \"consumed :: [\" << result[i] << \"/\" << m << \"]\" << endl;",last_ID,3);
writeln("}",last_ID,2);
writeln("}",last_ID,1);
if( matching_time ) {
writeln("cout << \"matching time :: \" << chrono::duration_cast<chrono::milliseconds>(ed-st).count() << \"msec\" << endl;",last_ID,1);
}
//writeln("cout << (parse_"+nonterminals[0]->getName()+"()?\"success\":\"fail\") << endl;",last_ID,1);
writeln("return 0;",last_ID,1);
writeln("}",last_ID); // main
dump();
}
void GeneralizedPackratParser::encode(Node *node,int ID,int indent) {
int type = node->type;
if( type == NONTERMINAL ) {
Nonterminal* tmp = (Nonterminal*)node->values[NONTERMINAL];
encode(tmp,ID,indent);
} else if( type == SLASH ) {
Slash* tmp = (Slash*)node->values[SLASH];
encode(tmp,ID,indent);
} else if( type == ALTERNATION ) {
Alternation* tmp = (Alternation*)node->values[ALTERNATION];
encode(tmp,ID,indent);
} else if( type == CHAR ) {
Char* tmp = (Char*)node->values[CHAR];
encode(tmp,ID,indent);
} else if( type == AND ) {
And* tmp = (And*)node->values[AND];
encode(tmp,ID,indent);
} else if( type == NOT ) {
Not* tmp = (Not*)node->values[NOT];
encode(tmp,ID,indent);
} else if( type == SEQUENCE ) {
Sequence* tmp = (Sequence*)node->values[SEQUENCE];
encode(tmp,ID,indent);
} else if( type == QUESTION ) {
Question* tmp = (Question*)node->values[QUESTION];
encode(tmp,ID,indent);
} else if( type == STAR ) {
Star* tmp = (Star*)node->values[STAR];
encode(tmp,ID,indent);
} else if( type == PLUS ) {
Plus* tmp = (Plus*)node->values[PLUS];
encode(tmp,ID,indent);
} else if( type == ANY ) {
Any* tmp = (Any*)node->values[ANY];
encode(tmp,ID,indent);
} else if( type == RANGE ) {
Range* tmp = (Range*)node->values[RANGE];
encode(tmp,ID,indent);
} else if( type == GPEG_STRING ) {
Gpeg_string *tmp = (Gpeg_string*)node->values[GPEG_STRING];
encode(tmp,ID,indent);
} else if( type == GROUPING ) {
Grouping *tmp = (Grouping*)node->values[GROUPING];
encode(tmp,ID,indent);
} else {
std::cerr << "what is [[" << type << "]]?" << std::endl;
assert(false);
}
}
void GeneralizedPackratParser::encode(Nonterminal *cur,int ID=-1,int indent=0){
if( cur->getExpression() == nullptr ) { // in a parsing expression ( e.g A <- 'a' [[A]]
writeln("/* Nonterminal ("+cur->getName()+") */",ID,indent);
std::string i = "i" + itos(suffix++);
std::string next_prev = "next_prev" + itos(suffix++);
writeln("deque<int> "+next_prev+";",ID,indent);
writeln("for(int "+i+"=0;"+i+"<(int)prev.size();++"+i+") {",ID,indent), ++indent;
writeln("if( prev["+i+"] == FAIL ) {",ID,indent), ++indent;
writeln("if(!(!"+next_prev+".empty() && "+next_prev+".front() == FAIL )) {",ID,indent), ++indent;
writeln(next_prev+".push_front(FAIL);",ID,indent);
--indent, writeln("}",ID,indent); // if(!(!
writeln("continue;",ID,indent);
--indent, writeln("}",ID,indent);//(if( prev[
writeln(ptr_name+" = prev["+i+"];",ID,indent);
writeln("tmp = parse_"+cur->getName()+"();",ID,indent);
writeln("",ID,indent);
writeln("for(int "+i+"=0;"+i+"<(int)tmp.size();++"+i+") {",ID,indent), ++indent;
writeln("if( tmp["+i+"] == FAIL ) {",ID,indent), ++indent;
assert(ID>=1);
writeln("if(!( !"+next_prev+".empty() && "+next_prev+"[0] == FAIL )) {",ID,indent), ++indent;
writeln(next_prev+".push_front(FAIL);",ID,indent);
--indent, writeln("}",ID,indent); // !( !next_prev
--indent, writeln("} else {",ID,indent), ++indent; // !( !tmp[i] == FAIL
writeln(next_prev+".push_back(tmp["+i+"]);",ID,indent);
--indent, writeln("}",ID,indent); // } else {
--indent, writeln("}",ID,indent); // for
--indent, writeln("}",ID,indent); // for
writeln("prev = "+next_prev+";",ID,indent);
} else { // definition ( e.g. [[A <- 'a' A]]
assert( ID == -1 );
ID = buffer.size();
buffer.push_back("");
prot.push_back("parse_"+cur->getName());
writeln("deque<int> parse_"+cur->getName()+"(){",ID,indent), ++indent;
if( packrat ){
write_packrat_return(ID);
}
writeln("deque<int> "+succ_buffer+"; // we use -1 to denote failure",ID,indent);
writeln("deque<int> tmp;",ID,indent);
std::string i = "i" + itos(suffix++);
writeln("deque<int> prev; //ちょうど今失敗せずに残っているポインタ",ID,indent);
writeln("prev.push_back("+ptr_name+");",ID,indent);
encode(cur->getExpression(),ID,indent);
//i = "i" + itos(suffix++);
writeln("for(int "+i+"=0;"+i+"<(int)prev.size();++"+i+") {",ID,indent), ++indent;
writeln("if( prev["+i+"] == FAIL ) {",ID,indent), ++indent;
writeln("if(!( !"+succ_buffer+".empty() && "+succ_buffer+"[0] == FAIL )) {",ID,indent), ++indent;
writeln(succ_buffer+".push_front(FAIL);",ID,indent);
--indent, writeln("}",ID,indent);
--indent, writeln("} else {",ID,indent), ++indent;
writeln(succ_buffer+".push_back(prev["+i+"]);",ID,indent);
--indent, writeln("}",ID,indent);
--indent,writeln("}",ID,indent);
if( packrat ) {
write_packrat_assign(ID,indent);
} else {
writeln("return "+succ_buffer+";",ID,indent);
}
--indent, writeln("}",ID,indent);
}
}
void GeneralizedPackratParser::encode(Slash *tmp,int ID=-1,int indent=0) { // MODIFIED
std::deque<Node*> alternates = tmp->getAlternates();
writeln("/* Prioritized Choice */",ID,indent);
std::string i = "i" + itos(suffix++);
std::string next_prev = "next_prev" + itos(suffix++);
std::string final_prev = "prioritized_choice_final_prev" + itos(suffix++);
writeln("deque<int> "+next_prev+";",ID,indent);
writeln("deque<int> "+final_prev+";",ID,indent);
for(int j=0;j<(int)alternates.size();++j) {
writeln(next_prev+".clear();",ID,indent);
writeln("for(int "+i+"=0;"+i+"<(int)prev.size();++"+i+") {",ID,indent), ++indent;
writeln(ptr_name+" = prev["+i+"];",ID,indent);
// parse_slash -- BEGIN
std::string name_of_slash = "parse_slash" + itos(suffix++);
int slash_ID = buffer.size();
buffer.push_back("");
prot.push_back(name_of_slash);
writeln("inline deque<int> " + name_of_slash + "() { ",slash_ID);
if( packrat ) {
write_packrat_return(slash_ID);
}
writeln("deque<int> "+succ_buffer+"; // we use -1 to denote failure",slash_ID,1);
writeln("deque<int> tmp;",slash_ID,1);
std::string k = "i" + itos(suffix++);
writeln("deque<int> prev; //ちょうど今失敗せずに残っているポインタ",slash_ID,1);
writeln("prev.push_back("+ptr_name+");",slash_ID,1);
encode(alternates[j],slash_ID,1);
writeln("for(int "+k+"=0;"+k+"<(int)prev.size();++"+k+") {",slash_ID,1);
writeln("if( prev["+k+"] == FAIL ) {",slash_ID,2);
writeln("if(!( !"+succ_buffer+".empty() && "+succ_buffer+"[0] == FAIL )) {",slash_ID,3);
writeln(succ_buffer+".push_front(FAIL);",slash_ID,4);
writeln("}",slash_ID,3); // if(!(
writeln("} else {",slash_ID,2); // if( prev
writeln(succ_buffer+".push_back(prev["+k+"]);",slash_ID,3);
writeln("}",slash_ID,2); // else
writeln("}",slash_ID,1); // for prev
if( packrat ) {
write_packrat_assign(slash_ID,1);
} else {
writeln("return "+succ_buffer+";",slash_ID,1);
}
writeln("}",slash_ID,0); // parse_slash
// parse_slash -- END
writeln("tmp = "+name_of_slash+"();",ID,indent);
writeln("if(!tmp.empty()&&tmp[0]==FAIL) { " + next_prev +".push_back(prev["+i+"]); }",ID,indent);
std::string l = "i"+itos(suffix++);
writeln("for(int "+l+"=0;"+l+"<(int)tmp.size();++"+l+") {",ID,indent), ++indent;
writeln("if( tmp["+l+"] != FAIL ) {",ID,indent), ++indent;
writeln(final_prev+".push_back(tmp["+l+"]);",ID,indent);
--indent, writeln("}",ID,indent); // if
--indent, writeln("}",ID,indent); // for
--indent, writeln("}",ID,indent); // for
writeln("prev = "+next_prev+";",ID,indent);
}
writeln("if(!prev.empty()) {",ID,indent), ++indent;
writeln("if(!(!"+final_prev+".empty() && "+final_prev+".front() == FAIL )) {",ID,indent), ++indent;
writeln(final_prev + ".push_front(FAIL);",ID,indent);
--indent, writeln("}",ID,indent); // if ! final_prev
--indent, writeln("}",ID,indent); // if ! prev.empty()
writeln("prev = " + final_prev + ";",ID,indent);
}
/*
* A <- 'a' ( 'b' | 'c' ) 'd'
*/
void GeneralizedPackratParser::encode(Alternation *tmp,int ID=-1,int indent=0) { // MODIFIED
std::deque<Node*> alternates = tmp->getAlternates();
writeln("/* Alternation */",ID,indent);
std::string next_prev = "next_prev" + itos(suffix++);
std::string tmp_prev = "tmp" + itos(suffix++);
writeln("deque<int> " + next_prev + ";",ID,indent);
writeln("deque<int> " + tmp_prev + ";",ID,indent);
std::string index2 = "i" + itos(suffix++);
writeln("for(int "+index2+"=0;"+index2+"<(int)prev.size();++"+index2+") {",ID,indent), ++indent;
for(int i=0;i<(int)alternates.size();++i) {
writeln(ptr_name + " = prev["+index2+"];",ID,indent);
// parse_alternation -- BEGIN
std::string name_of_alternate = "parse_alternation" + itos(suffix++);
int alternation_ID = buffer.size();
buffer.push_back("");
prot.push_back(name_of_alternate);
writeln("inline deque<int> " + name_of_alternate + "() { ",alternation_ID);
if( packrat ) {
write_packrat_return(alternation_ID);
}
writeln("deque<int> "+succ_buffer+"; // we use -1 to denote failure",alternation_ID,1);
writeln("deque<int> tmp;",alternation_ID,1);
std::string k = "i" + itos(suffix++);
writeln("deque<int> prev; //ちょうど今失敗せずに残っているポインタ",alternation_ID,1);
writeln("prev.push_back("+ptr_name+");",alternation_ID,1);
encode(alternates[i],alternation_ID,1);
writeln("for(int "+k+"=0;"+k+"<(int)prev.size();++"+k+") {",alternation_ID,1);
writeln("if( prev["+k+"] == FAIL ) {",alternation_ID,2);
writeln("if(!( !"+succ_buffer+".empty() && "+succ_buffer+"[0] == FAIL )) {",alternation_ID,3);
writeln(succ_buffer+".push_front(FAIL);",alternation_ID,4);
writeln("}",alternation_ID,3); // if(!(
writeln("} else {",alternation_ID,2); // if( prev
writeln(succ_buffer+".push_back(prev["+k+"]);",alternation_ID,3);
writeln("}",alternation_ID,2); // else
writeln("}",alternation_ID,1); // for prev
if( packrat ) {
write_packrat_assign(alternation_ID,1);
} else {
writeln("return "+succ_buffer+";",alternation_ID,1);
}
writeln("}",alternation_ID,0); // parse_slash
// parse_alternation -- END
writeln(tmp_prev+"="+name_of_alternate+"();",ID,indent);
std::string index = "i" + itos(suffix++);
writeln("for(int "+index+"=0;"+index+"<(int)"+tmp_prev+".size();++"+index+") {",ID,indent), ++indent;
//writeln("if( "+tmp_prev+"["+index+"] == FAIL ) {",ID,indent), ++indent;
//writeln("if(!(!"+next_prev+".empty()&&"+next_prev+".front()==FAIL)) {",ID,indent), ++indent;
//writeln(next_prev+".push_front(FAIL);",ID,indent);
//--indent, writeln("}",ID,indent); // if(!(!next_prev
//--indent, writeln("} else {",ID,indent), ++indent; // if ( tmp_prev[index] == FAIL
writeln("if( " + tmp_prev + "[" + index + "] != FAIL ) {",ID,indent), ++indent; // after
writeln(next_prev+".push_back("+tmp_prev+"["+index+"]);",ID,indent);
--indent, writeln("}",ID,indent); // } else {
--indent, writeln("}",ID,indent); // for
}
--indent, writeln("}",ID,indent); // for(int index2=0;index2<(int)prev.size();++index2) {
writeln("if( " + next_prev + ".empty() ) {",ID,indent), ++indent; //after
writeln(next_prev + ".push_back(FAIL);",ID,indent);//after
--indent, writeln("}",ID,indent);//after
writeln("prev = " + next_prev + ";",ID,indent);
}
void GeneralizedPackratParser::encode(Char *tmp,int ID=-1,int indent=0) { // MODIFIED
writeln("tmp.clear();",ID,indent);
std::string i = "i" + itos(suffix++);
writeln("for(int "+i+"=0;"+i+"<(int)prev.size();++"+i+") {",ID,indent), ++indent;
writeln("if( prev["+i+"] == FAIL ) {",ID,indent), ++indent;
writeln("if(!(!tmp.empty()&&tmp.front()==FAIL)) {",ID,indent), ++indent;
writeln("tmp.push_front(FAIL);",ID,indent);
--indent, writeln("}",ID,indent); // if(!(!tmp.empty()
writeln("continue;",ID,indent);
--indent, writeln("}",ID,indent); // if ( prev[j]
char value = tmp->getValue();
if( !( value == '\\' || value == '\'' ) && ( isgraph(value) || value == ' ' ) ) {
writeln("if(prev["+i+"]<m&&I[prev["+i+"]]=='"+std::string(1,value)+"') {",ID,indent), ++indent;
} else {
writeln("if(prev["+i+"]<m&&I[prev["+i+"]]==(char)"+itos((int)value)+") {",ID,indent), ++indent;
}
writeln("tmp.push_back(prev["+i+"]+1);",ID,indent);
--indent, writeln("} else {",ID,indent), ++indent;
writeln("if(!( !tmp.empty() && tmp[0] == FAIL )){",ID,indent), ++indent;
writeln("tmp.push_front(FAIL);",ID,indent);
--indent, writeln("}",ID,indent);
--indent, writeln("}",ID,indent); // else
--indent, writeln("}",ID,indent); // for
writeln("prev = tmp;",ID,indent);
}
void GeneralizedPackratParser::encode(And *cur,int ID=-1,int indent=0) {
Node *next = cur->get();
// parse_and -- BEGIN
std::string name_of_and = "parse_and" + itos(suffix++);
int and_ID = buffer.size();
buffer.push_back("");
prot.push_back(name_of_and);
writeln("inline deque<int> " + name_of_and + "() { ",and_ID);
if( packrat ) {
write_packrat_return(and_ID);
}
writeln("deque<int> "+succ_buffer+"; // we use -1 to denote failure",and_ID,1);
writeln("deque<int> tmp;",and_ID,1);
std::string k = "i" + itos(suffix++);
writeln("deque<int> prev; //ちょうど今失敗せずに残っているポインタ",and_ID,1);
writeln("prev.push_back("+ptr_name+");",and_ID,1);
encode(next,and_ID,1);
writeln("for(int "+k+"=0;"+k+"<(int)prev.size();++"+k+") {",and_ID,1);
writeln("if( prev["+k+"] == FAIL ) {",and_ID,2);
writeln("if(!( !"+succ_buffer+".empty() && "+succ_buffer+"[0] == FAIL )) {",and_ID,3);
writeln(succ_buffer+".push_front(FAIL);",and_ID,4);
writeln("}",and_ID,3); // if(!(
writeln("} else {",and_ID,2); // if( prev
writeln(succ_buffer+".push_back(prev["+k+"]);",and_ID,3);
writeln("}",and_ID,2); // else
writeln("}",and_ID,1); // for prev
if( packrat ) {
write_packrat_assign(and_ID,1);
} else {
writeln("return "+succ_buffer+";",and_ID,1);
}
writeln("}",and_ID,0); // parse_slash
// parse_and -- END
writeln("/* And */",ID,indent);
std::string index = "i" + itos(suffix++);
std::string next_prev = "next_prev" + itos(suffix++);
writeln("deque<int> "+next_prev+";",ID,indent);
writeln("for(int "+index+"=0;"+index+"<(int)prev.size();++"+index+") {",ID,indent), ++indent;
writeln(ptr_name + " = prev["+index+"];",ID,indent);
writeln("tmp = " + name_of_and + "();",ID,indent);
writeln("if(!tmp.empty() && tmp[(int)tmp.size()-1] != FAIL) {",ID,indent), ++indent;
writeln("if(!(!"+next_prev+".empty()&&"+next_prev+".front()==FAIL)) {",ID,indent), ++indent;
writeln(next_prev + ".push_back(prev["+index+"]);",ID,indent);
--indent, writeln("}",ID,indent);
// --indent, writeln("}",ID,indent);
--indent, writeln("} else if(!tmp.empty() && tmp[0] == FAIL) {",ID,indent), ++indent;
writeln(next_prev+".push_front(FAIL);",ID,indent);
--indent,writeln("}",ID,indent);
--indent, writeln("}",ID,indent); // for int index=0;
writeln("prev = " + next_prev+";",ID,indent);
}
void GeneralizedPackratParser::encode(Not *cur,int ID=-1,int indent=0) {
Node *next = cur->get();
// parse_not -- BEGIN
std::string name_of_not = "parse_not" + itos(suffix++);
int not_ID = buffer.size();
buffer.push_back("");
prot.push_back(name_of_not);
writeln("inline deque<int> " + name_of_not + "() { ",not_ID);
if( packrat ) {
write_packrat_return(not_ID);
}
writeln("deque<int> "+succ_buffer+"; // we use -1 to denote failure",not_ID,1);
writeln("deque<int> tmp;",not_ID,1);
std::string k = "i" + itos(suffix++);
writeln("deque<int> prev; //ちょうど今失敗せずに残っているポインタ",not_ID,1);
writeln("prev.push_back("+ptr_name+");",not_ID,1);
encode(next,not_ID,1);
writeln("for(int "+k+"=0;"+k+"<(int)prev.size();++"+k+") {",not_ID,1);
writeln("if( prev["+k+"] == FAIL ) {",not_ID,2);
writeln("if(!( !"+succ_buffer+".empty() && "+succ_buffer+"[0] == FAIL )) {",not_ID,3);
writeln(succ_buffer+".push_front(FAIL);",not_ID,4);
writeln("}",not_ID,3); // if(!(
writeln("} else {",not_ID,2); // if( prev
writeln(succ_buffer+".push_back(prev["+k+"]);",not_ID,3);
writeln("}",not_ID,2); // else
writeln("}",not_ID,1); // for prev
if( packrat ) {
write_packrat_assign(not_ID,1);
} else {
writeln("return "+succ_buffer+";",not_ID,1);
}
writeln("}",not_ID,0); // parse_slash
// parse_not -- END
writeln("/* Not */",ID,indent);
std::string index = "i" + itos(suffix++);
std::string next_prev = "next_prev" + itos(suffix++);
writeln("deque<int> "+next_prev+";",ID,indent);
writeln("for(int "+index+"=0;"+index+"<(int)prev.size();++"+index+") {",ID,indent), ++indent;
writeln(ptr_name + " = prev["+index+"];",ID,indent);
writeln("tmp = " + name_of_not + "();",ID,indent);
writeln("if(!tmp.empty() && tmp[(int)tmp.size()-1] != FAIL) {",ID,indent), ++indent;
writeln("if(!(!"+next_prev+".empty()&&"+next_prev+".front()==FAIL)) {",ID,indent), ++indent;
writeln(next_prev+".push_front(FAIL);",ID,indent);
--indent, writeln("}",ID,indent);
//--indent, writeln("}",ID,indent);
--indent, writeln("} else if(!tmp.empty() && tmp[0] == FAIL) {",ID,indent), ++indent;
writeln(next_prev + ".push_back(prev["+index+"]);",ID,indent);
--indent,writeln("}",ID,indent);
--indent, writeln("}",ID,indent); // for int index=0;
writeln("prev = " + next_prev+";",ID,indent);
}
void GeneralizedPackratParser::encode(Sequence *tmp,int ID=-1,int indent=0) {
std::deque<Node*> sequence = tmp->getSequence();
assert( sequence.size() );
for(int i=0;i<(int)sequence.size();++i) {
writeln("if(!((int)prev.size()==1&&prev.front()==FAIL)) {",ID,indent), ++indent; // CHECK
encode(sequence[i],ID,indent);
writeln("sort(prev.begin(),prev.end());",ID,indent); // proto type
writeln("prev.erase(unique(prev.begin(),prev.end()),prev.end());",ID,indent); // proto type
--indent, writeln("}",ID,indent); // CHECK
}
}
void GeneralizedPackratParser::encode(Question *cur,int ID=-1,int indent=0) {
Node* question = new Node;
question->setType(1); // SLASH
question->add(cur->get());
{
Node* node = new Node;
Gpeg_string* tmp = new Gpeg_string;
tmp->set("");
node->setValue(tmp);
question->add(node);
}
encode(question,ID,indent);
}
void GeneralizedPackratParser::encode(Star *cur,int ID=-1,int indent=0) { // MODIFIED
Node *next = cur->get();
// parse_while -- BEGIN
std::string name_of_while = "parse_while" + itos(suffix++);
int while_ID = buffer.size();
buffer.push_back("");
prot.push_back(name_of_while);
writeln("inline deque<int> " + name_of_while + "() { ",while_ID);
if( packrat ) {
write_packrat_return(while_ID);
}
writeln("deque<int> "+succ_buffer+"; // we use -1 to denote failure",while_ID,1);
writeln("deque<int> tmp;",while_ID,1);
std::string k = "i" + itos(suffix++);
writeln("deque<int> prev; //ちょうど今失敗せずに残っているポインタ",while_ID,1);
writeln("prev.push_back("+ptr_name+");",while_ID,1);
encode(next,while_ID,1);
writeln("for(int "+k+"=0;"+k+"<(int)prev.size();++"+k+") {",while_ID,1);
writeln("if( prev["+k+"] == FAIL ) {",while_ID,2);
writeln("if(!( !"+succ_buffer+".empty() && "+succ_buffer+"[0] == FAIL )) {",while_ID,3);
writeln(succ_buffer+".push_front(FAIL);",while_ID,4);
writeln("}",while_ID,3); // if(!(
writeln("} else {",while_ID,2); // if( prev
writeln(succ_buffer+".push_back(prev["+k+"]);",while_ID,3);
writeln("}",while_ID,2); // else
writeln("}",while_ID,1); // for prev
if( packrat ) {
write_packrat_assign(while_ID,1);
} else {
writeln("return "+succ_buffer+";",while_ID,1);
}
writeln("}",while_ID,0); // parse_slash
// parse_while -- END
writeln("/* Star */",ID,indent);
std::string next_prev = "next_prev" + itos(suffix++);
std::string final_prev = "star_final_prev" + itos(suffix++);
writeln("deque<int> "+next_prev+";",ID,indent);
writeln("deque<int> "+final_prev+";",ID,indent);
writeln("while(!((int)prev.size()==1&&prev.front()==FAIL)) {",ID,indent), ++indent;
writeln(next_prev+".clear();",ID,indent);
std::string index = "i" + itos(suffix++);
writeln("for(int "+index+"=0;"+index+"<(int)prev.size();++"+index+") {",ID,indent), ++indent;
writeln(ptr_name + " = prev["+index+"];",ID,indent);
writeln("tmp = " + name_of_while + "();",ID,indent);
writeln("if( (int)tmp.size() == 1 && tmp.front() == FAIL ) {",ID,indent), ++indent;
writeln(final_prev+".push_back(prev["+index+"]);",ID,indent);
--indent, writeln("}",ID,indent);
std::string index2 = "i" + itos(suffix++);
writeln("for(int "+index2+"=0;"+index2+"<(int)tmp.size();++"+index2+") {",ID,indent), ++indent;
writeln("if(tmp["+index2+"]==FAIL) {",ID,indent), ++indent;
//writeln(final_prev+".push_back(prev["+index+"]);",ID,indent);
writeln("if(!( !"+next_prev+".empty() && "+next_prev+".front() == FAIL )) {",ID,indent), ++indent;
writeln(next_prev+".push_front(FAIL);",ID,indent);
--indent, writeln("}",ID,indent); // if(!(!
--indent, writeln("} else {",ID,indent), ++indent; // if(tmp[index2]
writeln(next_prev+".push_back(tmp["+index2+"]);",ID,indent);
--indent, writeln("}",ID,indent); // } else {
--indent, writeln("}",ID,indent); // for int index2 = 0;
--indent, writeln("}",ID,indent); // for int index = 0;
writeln("prev = " + next_prev + ";",ID,indent);
--indent, writeln("}",ID,indent); // while(1)
writeln("prev = " + final_prev + ";",ID,indent);
}
void GeneralizedPackratParser::encode(Plus *cur,int ID=-1,int indent=0) {
Node* plus = new Node;
plus->setType(6); // SEQUENCE
plus->add(cur->get());
{
Node* tmp = new Node;
Star* star = new Star;
star->set(cur->get());
tmp->setValue(star);
plus->add(tmp);
}
encode(plus,ID,indent);
}
void GeneralizedPackratParser::encode(Any *cur,int ID=-1,int indent=0) { // MODIFIED
writeln("tmp.clear();",ID,indent);
std::string i = "i" + itos(suffix++);
writeln("for(int "+i+"=0;"+i+"<(int)prev.size();++"+i+") {",ID,indent), ++indent;
writeln("if( prev["+i+"] == FAIL ) {",ID,indent), ++indent;
writeln("if(!(!tmp.empty()&&tmp.front()==FAIL)) {",ID,indent), ++indent;
writeln("tmp.push_front(FAIL);",ID,indent);
--indent, writeln("}",ID,indent); // if(!(!tmp.empty()
writeln("continue;",ID,indent);
--indent, writeln("}",ID,indent); // if ( prev[j]
//writeln("if(prev["+i+"]<m&&(isgraph((char)I[prev["+i+"]])||(I[prev["+i+"]]==' '))) {//any character",ID,indent), ++indent;
writeln("if(prev["+i+"]<m) {//any character",ID,indent), ++indent;
writeln("tmp.push_back(prev["+i+"]+1);",ID,indent);
--indent, writeln("} else {",ID,indent), ++indent;
writeln("if(!( !tmp.empty() && tmp.front() == FAIL )){",ID,indent), ++indent;
writeln("tmp.push_front(FAIL);",ID,indent);
--indent, writeln("}",ID,indent);
--indent, writeln("}",ID,indent); // else
--indent, writeln("}",ID,indent); // for
writeln("prev = tmp;",ID,indent);
}
void GeneralizedPackratParser::encode(Range *cur,int ID=-1,int indent=0) { // MODIFIED
std::string cs = cur->get();
std::string condition = "";
std::string i = "i" + itos(suffix++);
for(int j=0;j<(int)cs.size();++j) {
if( j ) {
condition += "||";
}
if( j+2 < (int)cs.size() && cs[j+1] == '-' ) { // incorrect
for(char c=cs[j];c<=cs[j+2];++c) {
if( c != cs[j] ) condition += "||";
if( !( c == '\\' || c == '\'' || c == '"' ) && ( isgraph(c) || c == ' ' ) ) {
condition += ("I[prev["+i+"]]=='"+std::string(1,c)+"'");
} else {
condition += ("I[prev["+i+"]]==(char)"+itos((int)c)+"");
}
}
j += 2;
} else {
if( !( cs[j] == '\\' || cs[j] == '\'' ) && ( isgraph(cs[j]) || cs[j] == ' ' ) ) {
condition += ("I[prev["+i+"]]=='"+std::string(1,cs[j])+"'");
} else {
condition += ("I[prev["+i+"]]==(char)"+itos((int)cs[j])+"");
}
}
}
writeln("tmp.clear();",ID,indent);
writeln("for(int "+i+"=0;"+i+"<(int)prev.size();++"+i+") {",ID,indent), ++indent;
writeln("if( prev["+i+"] == FAIL ) {",ID,indent), ++indent;
writeln("if(!(!tmp.empty()&&tmp.front()==FAIL)) {",ID,indent), ++indent;
writeln("tmp.push_front(FAIL);",ID,indent);
--indent, writeln("}",ID,indent); // if(!(!tmp.empty()
writeln("continue;",ID,indent);
--indent, writeln("}",ID,indent); // if ( prev[j]
writeln("if(prev["+i+"]<m&&("+condition+")) {",ID,indent), ++indent;
writeln("tmp.push_back(prev["+i+"]+1);",ID,indent);
--indent, writeln("} else {",ID,indent), ++indent;
writeln("if(!( !tmp.empty() && tmp.front() == FAIL )){",ID,indent), ++indent;
writeln("tmp.push_front(FAIL);",ID,indent);
--indent, writeln("}",ID,indent);
--indent, writeln("}",ID,indent); // else
--indent, writeln("}",ID,indent); // for
writeln("prev = tmp;",ID,indent);
}
void GeneralizedPackratParser::encode(Gpeg_string *tmp,int ID=-1,int indent=0) { // MODIFIED
std::string str = tmp->get();
for(int i=0;i<(int)str.size();++i) {
writeln("tmp.clear();",ID,indent);
std::string j = "i" + itos(suffix++);
writeln("for(int "+j+"=0;"+j+"<(int)prev.size();++"+j+") {",ID,indent), ++indent;
writeln("if( prev["+j+"] == FAIL ) {",ID,indent), ++indent;
writeln("if(!(!tmp.empty()&&tmp.front()==FAIL)) {",ID,indent), ++indent;
writeln("tmp.push_front(FAIL);",ID,indent);
--indent, writeln("}",ID,indent); // if(!(!tmp.empty()
writeln("continue;",ID,indent);
--indent, writeln("}",ID,indent); // if ( prev[j]
char value = str[i];
if( !( value == '\\' ) && ( isgraph(value) || value == ' ' ) ) {
writeln("if(prev["+j+"]<m&&I[prev["+j+"]]=='"+std::string(1,value)+"') {",ID,indent), ++indent;
} else {
writeln("if(prev["+j+"]<m&&I[prev["+j+"]]==(char)"+itos((int)value)+") {",ID,indent), ++indent;
}
writeln("tmp.push_back(prev["+j+"]+1);",ID,indent);
--indent, writeln("} else {",ID,indent), ++indent;
writeln("if(!( !tmp.empty() && tmp[0] == FAIL )){",ID,indent), ++indent;
writeln("tmp.push_front(FAIL);",ID,indent);
--indent, writeln("}",ID,indent);
--indent, writeln("}",ID,indent); // else
--indent, writeln("}",ID,indent); // for
writeln("prev = tmp;",ID,indent);
}
}
void GeneralizedPackratParser::encode(Grouping *tmp,int ID=-1,int indent=0) {
assert( false ); /* DO NOT USE THIS FUNCTION */
Node *next = tmp->get();
encode(next,ID,indent);
}
| [
"nariyoshichidamm@gmail.com"
] | nariyoshichidamm@gmail.com |
bc0268aaea4e444881376806a7d19fc62a095947 | e84443e84862584ca69a4ee6bfe1656d96c9540b | /Queue.h | fdc0b9ce467dc815b0c8cf28c5f8ae21097c47b2 | [] | no_license | eemonn/separate-compilation | 70f218d3ee680e67d7a1146b9c0c90cb23badcbb | 5f49de471bc3897f682a21ec0bfe85887b1b614c | refs/heads/master | 2022-04-25T11:43:41.610796 | 2020-04-29T17:33:13 | 2020-04-29T17:33:13 | 259,995,437 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 542 | h | #pragma once
#include "ListItem.h"
class Node;
class Queue : public ListItem{
private:
Node *front; // front of queue.
Node *back; // back of queue
int size; // size of queue.
public:
Queue();
int getSize(); // how many elements are in queue?
bool isEmpty(); // is queue empty?
void enqueue(ListItem *item); // add item to queue.
ListItem *getFront(); // look at first item in queue.
ListItem *dequeue(); // remove first item from queue.
~Queue();
}; // class Queue
| [
"noreply@github.com"
] | noreply@github.com |
2b0d3576e80ac316df548a36a960735017bfa771 | f362652d4ec9d5528a40e713034403c56a4386e9 | /Practica3/modelo_jerarquico.h | 719db321008d455fcda5894a9a8ef3d974d3f0fa | [] | no_license | xexugarcia95/IG | 663995e162959d8ed876c6716fa898d8d3316e4b | 78f9daa7976196af569ca180b5d0fd90beb3d51f | refs/heads/master | 2021-01-12T17:49:05.313741 | 2016-11-29T16:03:56 | 2016-11-29T16:03:56 | 69,396,244 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 797 | h | #ifndef _MODELO_JERARQUICO_H_
#define _MODELO_JERARQUICO_H_
#include <GL/glut.h>
#include <stdlib.h>
#include <vertex.h>
#include <vector>
#include "revolucion.h"
#include "model_ply.h"
#include "figura.h"
#include "cubo.h"
struct modelo_jerarquico : public figura
{
cubo cu=cubo(50);
modelo_jerarquico();
void dibujar_modelo(int modo,float r,float mov,float mov2,float variable);
void estructura(int modo);
void pared_trasera(int modo);
void pared_lateral_izq(int modo);
void pared_lateral_der(int modo);
void techo(int modo);
void suelo(int modo);
void suelo2(int modo);
void cajon(int modo,float mov);
void cajon2(int modo,float mov);
void separador(int modo);
void cajones(int modo,float mov,float mov2);
void puerta(int modo,float rotacion,float variable);
};
#endif | [
"xexugarcia95@gmail.com"
] | xexugarcia95@gmail.com |
5b715a09f54e7fe82f5d2c33193b53d322378b7f | 133d0f38b3da2c51bf52bcdfa11d62978b94d031 | /testAutocad/vendor/ifc-sdk/src/ifc2x3/IfcSectionReinforcementProperties.cpp | baaa1249e462b70774532da1defc9fe76185833f | [] | no_license | Aligon42/ImportIFC | 850404f1e1addf848e976b0351d9e217a72f868a | 594001fc0942d356eb0d0472c959195151510493 | refs/heads/master | 2023-08-15T08:00:14.056542 | 2021-07-05T13:49:28 | 2021-07-05T13:49:28 | 361,410,709 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 12,404 | cpp | // IFC SDK : IFC2X3 C++ Early Classes
// Copyright (C) 2009 CSTB
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// The full license is in Licence.txt file included with this
// distribution or is available at :
// http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
#include <ifc2x3/IfcSectionReinforcementProperties.h>
#include <ifc2x3/CopyOp.h>
#include <ifc2x3/IfcReinforcementBarProperties.h>
#include <ifc2x3/IfcSectionProperties.h>
#include <ifc2x3/Visitor.h>
#include <Step/BaseCopyOp.h>
#include <Step/BaseEntity.h>
#include <Step/BaseExpressDataSet.h>
#include <Step/BaseObject.h>
#include <Step/Referenced.h>
#include <Step/SPFFunctions.h>
#include <string>
#include "precompiled.h"
using namespace ifc2x3;
IfcSectionReinforcementProperties::IfcSectionReinforcementProperties(Step::Id id, Step::SPFData *args) : Step::BaseEntity(id, args) {
m_longitudinalStartPosition = Step::getUnset(m_longitudinalStartPosition);
m_longitudinalEndPosition = Step::getUnset(m_longitudinalEndPosition);
m_transversePosition = Step::getUnset(m_transversePosition);
m_reinforcementRole = IfcReinforcingBarRoleEnum_UNSET;
m_sectionDefinition = NULL;
}
IfcSectionReinforcementProperties::~IfcSectionReinforcementProperties() {
}
bool IfcSectionReinforcementProperties::acceptVisitor(Step::BaseVisitor *visitor) {
return static_cast< Visitor * > (visitor)->visitIfcSectionReinforcementProperties(this);
}
const std::string &IfcSectionReinforcementProperties::type() const {
return IfcSectionReinforcementProperties::s_type.getName();
}
const Step::ClassType &IfcSectionReinforcementProperties::getClassType() {
return IfcSectionReinforcementProperties::s_type;
}
const Step::ClassType &IfcSectionReinforcementProperties::getType() const {
return IfcSectionReinforcementProperties::s_type;
}
bool IfcSectionReinforcementProperties::isOfType(const Step::ClassType &t) const {
return IfcSectionReinforcementProperties::s_type == t ? true : Step::BaseObject::isOfType(t);
}
IfcLengthMeasure IfcSectionReinforcementProperties::getLongitudinalStartPosition() {
if (Step::BaseObject::inited()) {
return m_longitudinalStartPosition;
}
else {
return Step::getUnset(m_longitudinalStartPosition);
}
}
const IfcLengthMeasure IfcSectionReinforcementProperties::getLongitudinalStartPosition() const {
IfcSectionReinforcementProperties * deConstObject = const_cast< IfcSectionReinforcementProperties * > (this);
return deConstObject->getLongitudinalStartPosition();
}
void IfcSectionReinforcementProperties::setLongitudinalStartPosition(IfcLengthMeasure value) {
m_longitudinalStartPosition = value;
}
void IfcSectionReinforcementProperties::unsetLongitudinalStartPosition() {
m_longitudinalStartPosition = Step::getUnset(getLongitudinalStartPosition());
}
bool IfcSectionReinforcementProperties::testLongitudinalStartPosition() const {
return !Step::isUnset(getLongitudinalStartPosition());
}
IfcLengthMeasure IfcSectionReinforcementProperties::getLongitudinalEndPosition() {
if (Step::BaseObject::inited()) {
return m_longitudinalEndPosition;
}
else {
return Step::getUnset(m_longitudinalEndPosition);
}
}
const IfcLengthMeasure IfcSectionReinforcementProperties::getLongitudinalEndPosition() const {
IfcSectionReinforcementProperties * deConstObject = const_cast< IfcSectionReinforcementProperties * > (this);
return deConstObject->getLongitudinalEndPosition();
}
void IfcSectionReinforcementProperties::setLongitudinalEndPosition(IfcLengthMeasure value) {
m_longitudinalEndPosition = value;
}
void IfcSectionReinforcementProperties::unsetLongitudinalEndPosition() {
m_longitudinalEndPosition = Step::getUnset(getLongitudinalEndPosition());
}
bool IfcSectionReinforcementProperties::testLongitudinalEndPosition() const {
return !Step::isUnset(getLongitudinalEndPosition());
}
IfcLengthMeasure IfcSectionReinforcementProperties::getTransversePosition() {
if (Step::BaseObject::inited()) {
return m_transversePosition;
}
else {
return Step::getUnset(m_transversePosition);
}
}
const IfcLengthMeasure IfcSectionReinforcementProperties::getTransversePosition() const {
IfcSectionReinforcementProperties * deConstObject = const_cast< IfcSectionReinforcementProperties * > (this);
return deConstObject->getTransversePosition();
}
void IfcSectionReinforcementProperties::setTransversePosition(IfcLengthMeasure value) {
m_transversePosition = value;
}
void IfcSectionReinforcementProperties::unsetTransversePosition() {
m_transversePosition = Step::getUnset(getTransversePosition());
}
bool IfcSectionReinforcementProperties::testTransversePosition() const {
return !Step::isUnset(getTransversePosition());
}
IfcReinforcingBarRoleEnum IfcSectionReinforcementProperties::getReinforcementRole() {
if (Step::BaseObject::inited()) {
return m_reinforcementRole;
}
else {
return IfcReinforcingBarRoleEnum_UNSET;
}
}
const IfcReinforcingBarRoleEnum IfcSectionReinforcementProperties::getReinforcementRole() const {
IfcSectionReinforcementProperties * deConstObject = const_cast< IfcSectionReinforcementProperties * > (this);
return deConstObject->getReinforcementRole();
}
void IfcSectionReinforcementProperties::setReinforcementRole(IfcReinforcingBarRoleEnum value) {
m_reinforcementRole = value;
}
void IfcSectionReinforcementProperties::unsetReinforcementRole() {
m_reinforcementRole = IfcReinforcingBarRoleEnum_UNSET;
}
bool IfcSectionReinforcementProperties::testReinforcementRole() const {
return getReinforcementRole() != IfcReinforcingBarRoleEnum_UNSET;
}
IfcSectionProperties *IfcSectionReinforcementProperties::getSectionDefinition() {
if (Step::BaseObject::inited()) {
return m_sectionDefinition.get();
}
else {
return NULL;
}
}
const IfcSectionProperties *IfcSectionReinforcementProperties::getSectionDefinition() const {
IfcSectionReinforcementProperties * deConstObject = const_cast< IfcSectionReinforcementProperties * > (this);
return deConstObject->getSectionDefinition();
}
void IfcSectionReinforcementProperties::setSectionDefinition(const Step::RefPtr< IfcSectionProperties > &value) {
m_sectionDefinition = value;
}
void IfcSectionReinforcementProperties::unsetSectionDefinition() {
m_sectionDefinition = Step::getUnset(getSectionDefinition());
}
bool IfcSectionReinforcementProperties::testSectionDefinition() const {
return !Step::isUnset(getSectionDefinition());
}
Set_IfcReinforcementBarProperties_1_n &IfcSectionReinforcementProperties::getCrossSectionReinforcementDefinitions() {
if (Step::BaseObject::inited()) {
return m_crossSectionReinforcementDefinitions;
}
else {
m_crossSectionReinforcementDefinitions.setUnset(true);
return m_crossSectionReinforcementDefinitions;
}
}
const Set_IfcReinforcementBarProperties_1_n &IfcSectionReinforcementProperties::getCrossSectionReinforcementDefinitions() const {
IfcSectionReinforcementProperties * deConstObject = const_cast< IfcSectionReinforcementProperties * > (this);
return deConstObject->getCrossSectionReinforcementDefinitions();
}
void IfcSectionReinforcementProperties::setCrossSectionReinforcementDefinitions(const Set_IfcReinforcementBarProperties_1_n &value) {
m_crossSectionReinforcementDefinitions = value;
}
void IfcSectionReinforcementProperties::unsetCrossSectionReinforcementDefinitions() {
m_crossSectionReinforcementDefinitions.clear();
m_crossSectionReinforcementDefinitions.setUnset(true);
}
bool IfcSectionReinforcementProperties::testCrossSectionReinforcementDefinitions() const {
return !m_crossSectionReinforcementDefinitions.isUnset();
}
bool IfcSectionReinforcementProperties::init() {
std::string arg;
arg = m_args->getNext();
if (arg == "$" || arg == "*") {
m_longitudinalStartPosition = Step::getUnset(m_longitudinalStartPosition);
}
else {
m_longitudinalStartPosition = Step::spfToReal(arg);
}
arg = m_args->getNext();
if (arg == "$" || arg == "*") {
m_longitudinalEndPosition = Step::getUnset(m_longitudinalEndPosition);
}
else {
m_longitudinalEndPosition = Step::spfToReal(arg);
}
arg = m_args->getNext();
if (arg == "$" || arg == "*") {
m_transversePosition = Step::getUnset(m_transversePosition);
}
else {
m_transversePosition = Step::spfToReal(arg);
}
arg = m_args->getNext();
if (arg == "$" || arg == "*") {
m_reinforcementRole = IfcReinforcingBarRoleEnum_UNSET;
}
else {
if (arg == ".MAIN.") {
m_reinforcementRole = IfcReinforcingBarRoleEnum_MAIN;
}
else if (arg == ".SHEAR.") {
m_reinforcementRole = IfcReinforcingBarRoleEnum_SHEAR;
}
else if (arg == ".LIGATURE.") {
m_reinforcementRole = IfcReinforcingBarRoleEnum_LIGATURE;
}
else if (arg == ".STUD.") {
m_reinforcementRole = IfcReinforcingBarRoleEnum_STUD;
}
else if (arg == ".PUNCHING.") {
m_reinforcementRole = IfcReinforcingBarRoleEnum_PUNCHING;
}
else if (arg == ".EDGE.") {
m_reinforcementRole = IfcReinforcingBarRoleEnum_EDGE;
}
else if (arg == ".RING.") {
m_reinforcementRole = IfcReinforcingBarRoleEnum_RING;
}
else if (arg == ".USERDEFINED.") {
m_reinforcementRole = IfcReinforcingBarRoleEnum_USERDEFINED;
}
else if (arg == ".NOTDEFINED.") {
m_reinforcementRole = IfcReinforcingBarRoleEnum_NOTDEFINED;
}
}
arg = m_args->getNext();
if (arg == "$" || arg == "*") {
m_sectionDefinition = NULL;
}
else {
m_sectionDefinition = static_cast< IfcSectionProperties * > (m_expressDataSet->get(Step::getIdParam(arg)));
}
arg = m_args->getNext();
if (arg == "$" || arg == "*") {
m_crossSectionReinforcementDefinitions.setUnset(true);
}
else {
m_crossSectionReinforcementDefinitions.setUnset(false);
while (true) {
std::string str1;
Step::getSubParameter(arg, str1);
if (str1 != "") {
Step::RefPtr< IfcReinforcementBarProperties > attr2;
attr2 = static_cast< IfcReinforcementBarProperties * > (m_expressDataSet->get(Step::getIdParam(str1)));
if (attr2.valid()) m_crossSectionReinforcementDefinitions.insert(attr2);
}
else {
break;
}
}
}
return true;
}
void IfcSectionReinforcementProperties::copy(const IfcSectionReinforcementProperties &obj, const CopyOp ©op) {
Step::Set< Step::RefPtr< IfcReinforcementBarProperties >, 1 >::const_iterator it_m_crossSectionReinforcementDefinitions;
Step::BaseEntity::copy(obj, copyop);
setLongitudinalStartPosition(obj.m_longitudinalStartPosition);
setLongitudinalEndPosition(obj.m_longitudinalEndPosition);
setTransversePosition(obj.m_transversePosition);
setReinforcementRole(obj.m_reinforcementRole);
setSectionDefinition((IfcSectionProperties*)copyop(obj.m_sectionDefinition.get()));
for (it_m_crossSectionReinforcementDefinitions = obj.m_crossSectionReinforcementDefinitions.begin(); it_m_crossSectionReinforcementDefinitions != obj.m_crossSectionReinforcementDefinitions.end(); ++it_m_crossSectionReinforcementDefinitions) {
Step::RefPtr< IfcReinforcementBarProperties > copyTarget = (IfcReinforcementBarProperties *) (copyop((*it_m_crossSectionReinforcementDefinitions).get()));
m_crossSectionReinforcementDefinitions.insert(copyTarget.get());
}
return;
}
IFC2X3_EXPORT Step::ClassType IfcSectionReinforcementProperties::s_type("IfcSectionReinforcementProperties");
| [
"antoine.cacheux@procal.fr"
] | antoine.cacheux@procal.fr |
8c40310501a12766ae0112c0132b316482f27316 | 0b715a5559280f99bf11d5e0ec08750505729c15 | /engine/source/gfx/D3D9/gfxD3D9TextureManager.h | 346933a9e2795c2a4c26cc0691d5685b93192a44 | [] | no_license | MBU-Team/OpenMBU | ee24dbd21eca66c9b269626d269e89b90fbcbcda | 4227ce343d3e1af20ec9a5548b1e65060fb208d4 | refs/heads/master | 2023-09-04T22:27:34.705946 | 2023-08-10T01:07:31 | 2023-08-10T01:07:31 | 338,863,302 | 71 | 16 | null | 2023-09-02T19:42:09 | 2021-02-14T17:41:11 | C++ | UTF-8 | C++ | false | false | 1,656 | h | //-----------------------------------------------------------------------------
// Torque Game Engine Advanced
//
// Copyright (c) 2003 GarageGames.Com
//-----------------------------------------------------------------------------
#ifndef _GFX_D3D_Texture_Manager_H_
#define _GFX_D3D_Texture_Manager_H_
#include "console/console.h"
#include "gfx/gfxTextureManager.h"
#include "gfx/D3D9/gfxD3D9TextureObject.h"
#include "util/safeRelease.h"
// #define D3D_TEXTURE_SPEW
//*****************************************************************************
// GFX D3D Texture Manager
//*****************************************************************************
class GFXD3D9TextureManager : public GFXTextureManager
{
friend class GFXD3D9TextureObject;
U32 mCurTexSet[TEXTURE_STAGE_COUNT];
private:
LPDIRECT3DDEVICE9 mD3DDevice;
D3DCAPS9 mDeviceCaps;
void innerCreateTexture(GFXD3D9TextureObject *obj, U32 height, U32 width,
U32 depth, GFXFormat format, GFXTextureProfile *profile, U32 numMipLevels,
bool forceMips = false);
protected:
GFXTextureObject *_createTexture(U32 height, U32 width, U32 depth, GFXFormat format,
GFXTextureProfile *profile, U32 numMipLevels, bool forceMips = false);
bool _loadTexture(GFXTextureObject *texture, DDSFile *dds);
bool _loadTexture(GFXTextureObject *texture, GBitmap *bmp);
bool _loadTexture(GFXTextureObject *texture, void *raw);
bool _refreshTexture(GFXTextureObject *texture);
bool _freeTexture(GFXTextureObject *texture, bool zombify = false);
U32 _getTotalVideoMemory();
public:
GFXD3D9TextureManager( LPDIRECT3DDEVICE9 d3ddevice );
};
#endif
| [
"39096122+HumanGamer@users.noreply.github.com"
] | 39096122+HumanGamer@users.noreply.github.com |
3e99163365ba8bd0b4eafbc08dd3516e5fd1d92b | 6fc5748266fa1fa12d324d192dbc4edda5ea24fc | /code/ghostlib/Kinect2Starter.cpp | aa842d2d19c8ffc12cf8549900b698c2d426611c | [] | no_license | abardam/ghost-system | 906486d2e1bddcbdd6d697418a89c4eeae9ed3b0 | bd221326c890317cf37570a602e8856ed9a0fb91 | refs/heads/master | 2016-08-08T14:24:27.348627 | 2015-06-05T00:56:14 | 2015-06-05T00:56:14 | 20,339,932 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,691 | cpp | #include "Kinect2Starter.h"
#include "KinectManager.h"
#include <Kinect.h>
#include <iostream>
void DumpHR(HRESULT hr)
{
//
//if (hr < 0)
// hr += 0x100000000;
//if (hr & 0x80000000)
// std::cout << ("Error code") << std::endl;
//else
// std::cout << ("Success code") << std::endl;
//
//auto facility = (hr & 0x7FFF0000) >> 16;
//
//std::cout << "Facility " << facility << std::endl;
//
//auto scode = hr & 0x0000FFFF;
//
//std::cout << "SCode " << scode << std::endl;
}
namespace KINECT{
IKinectSensor * m_pKinectSensor;
ICoordinateMapper * m_pCoordinateMapper;
IBodyFrameReader * m_pBodyFrameReader;
IColorFrameReader * m_pColorFrameReader;
IDepthFrameReader * m_pDepthFrameReader;
IBodyIndexFrameReader * m_pBodyIndexFrameReader;
INT64 m_nStartTime;
RGBQUAD * m_pDepthRGBX;
USHORT * m_pDepth;
RGBQUAD * m_pColorRGBX;
DepthSpacePoint * m_pColorDepthMap;
USHORT * m_pDepthMappedToColor;
int * m_pDepthXMappedToColor;
int * m_pDepthYMappedToColor;
RGBQUAD * m_pBodyColorRGBX;
Joint * m_pJoints;
UCHAR m_nBodyIndex;
unsigned int m_nDepthWidth;
unsigned int m_nDepthHeight;
unsigned int m_nColorWidth;
unsigned int m_nColorHeight;
bool m_bCalculateDepthRGBX;
bool m_bMapDepthToColor;
bool m_bSkeletonIsGood;
bool m_bColorDepthMapCalculated;
void InitKinect2Starter(){
m_pDepthRGBX = new RGBQUAD[CAPTURE_SIZE_X_DEPTH * CAPTURE_SIZE_Y_DEPTH];
m_pDepth = new USHORT[CAPTURE_SIZE_X_DEPTH * CAPTURE_SIZE_Y_DEPTH];
m_pColorRGBX = new RGBQUAD[CAPTURE_SIZE_X_COLOR * CAPTURE_SIZE_Y_COLOR];
m_pColorDepthMap = new DepthSpacePoint[CAPTURE_SIZE_X_COLOR * CAPTURE_SIZE_Y_COLOR];
m_pDepthXMappedToColor = new int[CAPTURE_SIZE_X_COLOR * CAPTURE_SIZE_Y_COLOR];
m_pDepthYMappedToColor = new int[CAPTURE_SIZE_X_COLOR * CAPTURE_SIZE_Y_COLOR];
m_pDepthMappedToColor = new USHORT[CAPTURE_SIZE_X_COLOR * CAPTURE_SIZE_Y_COLOR];
m_pBodyColorRGBX = new RGBQUAD[CAPTURE_SIZE_X_COLOR * CAPTURE_SIZE_Y_COLOR];
m_pJoints = new Joint[JointType_Count];
m_nStartTime = 0;
m_bCalculateDepthRGBX = false;
m_bMapDepthToColor = true;
m_bSkeletonIsGood = false;
m_nBodyIndex = 0xff;
m_bColorDepthMapCalculated = false;
}
void DestroyKinect2Starter(){
if(m_pDepthRGBX){
delete [] m_pDepthRGBX;
m_pDepthRGBX = NULL;
}
if(m_pDepth){
delete [] m_pDepth;
m_pDepth = NULL;
}
if(m_pColorRGBX){
delete [] m_pColorRGBX;
m_pColorRGBX = NULL;
}
if(m_pColorDepthMap){
delete [] m_pColorDepthMap;
}
if(m_pDepthMappedToColor){
delete[] m_pDepthMappedToColor;
}
if (m_pDepthXMappedToColor){
delete[] m_pDepthXMappedToColor;
}
if (m_pDepthYMappedToColor){
delete[] m_pDepthYMappedToColor;
}
if(m_pBodyColorRGBX){
delete [] m_pBodyColorRGBX;
}
if(m_pJoints){
delete [] m_pJoints;
}
}
HRESULT InitializeDefaultSensor()
{
HRESULT hr;
hr = GetDefaultKinectSensor(&m_pKinectSensor);
if (FAILED(hr))
{
return hr;
}
if (m_pKinectSensor)
{
// Initialize the Kinect and get coordinate mapper and the body reader
IBodyFrameSource* pBodyFrameSource = NULL;
hr = m_pKinectSensor->Open();
if (SUCCEEDED(hr))
{
hr = m_pKinectSensor->get_CoordinateMapper(&m_pCoordinateMapper);
}
if (SUCCEEDED(hr))
{
hr = m_pKinectSensor->get_BodyFrameSource(&pBodyFrameSource);
}
if (SUCCEEDED(hr))
{
hr = pBodyFrameSource->OpenReader(&m_pBodyFrameReader);
}
SafeRelease(pBodyFrameSource);
// get the color reader
IColorFrameSource* pColorFrameSource = NULL;
if (SUCCEEDED(hr))
{
hr = m_pKinectSensor->get_ColorFrameSource(&pColorFrameSource);
}
if (SUCCEEDED(hr))
{
hr = pColorFrameSource->OpenReader(&m_pColorFrameReader);
}
SafeRelease(pColorFrameSource);
// get the depth reader
IDepthFrameSource* pDepthFrameSource = NULL;
if (SUCCEEDED(hr))
{
hr = m_pKinectSensor->get_DepthFrameSource(&pDepthFrameSource);
}
if (SUCCEEDED(hr))
{
hr = pDepthFrameSource->OpenReader(&m_pDepthFrameReader);
}
SafeRelease(pDepthFrameSource);
//get the body frame index reader
IBodyIndexFrameSource * pBodyIndexFrameSource = NULL;
if(SUCCEEDED(hr)){
hr = m_pKinectSensor->get_BodyIndexFrameSource(&pBodyIndexFrameSource);
}
if(SUCCEEDED(hr)){
hr = pBodyIndexFrameSource->OpenReader(&m_pBodyIndexFrameReader);
}
SafeRelease(pBodyIndexFrameSource);
}
if (!m_pKinectSensor || FAILED(hr))
{
std::cout << "no ready Kinect found!";
return E_FAIL;
}
return hr;
}
void CalculateColorDepthMap(){
HRESULT hr = m_pCoordinateMapper->MapColorFrameToDepthSpace(m_nDepthWidth*m_nDepthHeight, m_pDepth, m_nColorWidth*m_nColorHeight, m_pColorDepthMap);
if(SUCCEEDED(hr)){
m_bColorDepthMapCalculated = true;
}
}
//after calling this, get the depth fram with GetDepth or GetDepthRGBX
void UpdateDepth(){
if (!m_pDepthFrameReader)
{
return;
}
IDepthFrame* pDepthFrame = NULL;
HRESULT hr = m_pDepthFrameReader->AcquireLatestFrame(&pDepthFrame);
if (SUCCEEDED(hr))
{
INT64 nTime = 0;
IFrameDescription* pFrameDescription = NULL;
int nWidth = 0;
int nHeight = 0;
USHORT nDepthMinReliableDistance = 0;
USHORT nDepthMaxReliableDistance = 0;
UINT nBufferSize = 0;
UINT16 *pBuffer = NULL;
hr = pDepthFrame->get_RelativeTime(&nTime);
if (SUCCEEDED(hr))
{
hr = pDepthFrame->get_FrameDescription(&pFrameDescription);
}
if (SUCCEEDED(hr))
{
hr = pFrameDescription->get_Width(&nWidth);
}
if (SUCCEEDED(hr))
{
m_nDepthWidth = nWidth;
hr = pFrameDescription->get_Height(&nHeight);
}
if (SUCCEEDED(hr))
{
m_nDepthHeight = nHeight;
hr = pDepthFrame->get_DepthMinReliableDistance(&nDepthMinReliableDistance);
}
if (SUCCEEDED(hr))
{
hr = pDepthFrame->get_DepthMaxReliableDistance(&nDepthMaxReliableDistance);
}
if (SUCCEEDED(hr))
{
hr = pDepthFrame->AccessUnderlyingBuffer(&nBufferSize, &pBuffer);
}
if (SUCCEEDED(hr))
{
if(m_bCalculateDepthRGBX)
ProcessDepth(nTime, pBuffer, nWidth, nHeight, nDepthMinReliableDistance, nDepthMaxReliableDistance);
else
ProcessDepthNoRGBX(nTime, pBuffer, nWidth, nHeight, nDepthMinReliableDistance, nDepthMaxReliableDistance);
if(!m_bColorDepthMapCalculated){
CalculateColorDepthMap();
}
if(m_bMapDepthToColor && m_nColorWidth > 0 && m_nColorHeight > 0 && SUCCEEDED(hr) && m_bColorDepthMapCalculated){
ProcessDepthToColor(m_pDepth, m_nDepthWidth, m_nDepthHeight, m_pColorDepthMap, m_nColorWidth, m_nColorHeight);
}
}
SafeRelease(pFrameDescription);
}
else{
DumpHR(hr);
}
SafeRelease(pDepthFrame);
}
void ProcessDepth(INT64 nTime, const UINT16* pBuffer, int nWidth, int nHeight, USHORT nMinDepth, USHORT nMaxDepth)
{
if (!m_nStartTime)
{
m_nStartTime = nTime;
}
// Make sure we've received valid data
if (m_pDepthRGBX && m_pDepth && pBuffer)
{
RGBQUAD* pRGBX = m_pDepthRGBX;
USHORT * pDepth = m_pDepth;
// end pixel is start + width*height - 1
const UINT16* pBufferEnd = pBuffer + (nWidth * nHeight);
while (pBuffer < pBufferEnd)
{
USHORT depth = *pBuffer;
*pDepth = depth;
// To convert to a byte, we're discarding the most-significant
// rather than least-significant bits.
// We're preserving detail, although the intensity will "wrap."
// Values outside the reliable depth range are mapped to 0 (black).
// Note: Using conditionals in this loop could degrade performance.
// Consider using a lookup table instead when writing production code.
BYTE intensity = static_cast<BYTE>((depth >= nMinDepth) && (depth <= nMaxDepth) ? (depth % 256) : 0);
pRGBX->rgbRed = intensity;
pRGBX->rgbGreen = intensity;
pRGBX->rgbBlue = intensity;
++pRGBX;
++pDepth;
++pBuffer;
}
}
}
void ProcessDepthNoRGBX(INT64 nTime, const UINT16* pBuffer, int nWidth, int nHeight, USHORT nMinDepth, USHORT nMaxDepth)
{
if (!m_nStartTime)
{
m_nStartTime = nTime;
}
// Make sure we've received valid data
if (m_pDepth && pBuffer)
{
USHORT * pDepth = m_pDepth;
// end pixel is start + width*height - 1
const UINT16* pBufferEnd = pBuffer + (nWidth * nHeight);
while (pBuffer < pBufferEnd)
{
USHORT depth = *pBuffer;
*pDepth = depth;
++pDepth;
++pBuffer;
}
}
}
void ProcessDepthToColor(const USHORT * pDepthBuffer, int nDepthWidth, int nDepthHeight, const DepthSpacePoint * pColorDepthMap, int nColorWidth, int nColorHeight){
int colorSize = nColorWidth * nColorHeight;
if(pDepthBuffer && pColorDepthMap){
USHORT * pDepthMappedToColor = m_pDepthMappedToColor;
int * pDepthXMappedToColor = m_pDepthXMappedToColor;
int * pDepthYMappedToColor = m_pDepthYMappedToColor;
const DepthSpacePoint * pBufferEnd = pColorDepthMap + colorSize;
while(pColorDepthMap < pBufferEnd){
DepthSpacePoint depthSpacePoint = *pColorDepthMap;
int pointerValue = depthSpacePoint.X + depthSpacePoint.Y * nDepthWidth;
*pDepthMappedToColor = pDepthBuffer[pointerValue];
*pDepthXMappedToColor = depthSpacePoint.X;
*pDepthYMappedToColor = depthSpacePoint.Y;
++pColorDepthMap;
++pDepthMappedToColor;
++pDepthXMappedToColor;
++pDepthYMappedToColor;
}
}
}
void UpdateColor()
{
if (!m_pColorFrameReader)
{
return;
}
IColorFrame* pColorFrame = NULL;
HRESULT hr = m_pColorFrameReader->AcquireLatestFrame(&pColorFrame);
if (SUCCEEDED(hr))
{
INT64 nTime = 0;
IFrameDescription* pFrameDescription = NULL;
int nWidth = 0;
int nHeight = 0;
ColorImageFormat imageFormat = ColorImageFormat_None;
UINT nBufferSize = 0;
RGBQUAD *pBuffer = NULL;
hr = pColorFrame->get_RelativeTime(&nTime);
if (SUCCEEDED(hr))
{
hr = pColorFrame->get_FrameDescription(&pFrameDescription);
}
if (SUCCEEDED(hr))
{
hr = pFrameDescription->get_Width(&nWidth);
}
if (SUCCEEDED(hr))
{
m_nColorWidth = nWidth;
hr = pFrameDescription->get_Height(&nHeight);
}
if (SUCCEEDED(hr))
{
m_nColorHeight = nHeight;
hr = pColorFrame->get_RawColorImageFormat(&imageFormat);
}
if (SUCCEEDED(hr))
{
if (imageFormat == ColorImageFormat_Bgra)
{
hr = pColorFrame->AccessRawUnderlyingBuffer(&nBufferSize, reinterpret_cast<BYTE**>(&pBuffer));
}
else if (m_pColorRGBX)
{
pBuffer = m_pColorRGBX;
nBufferSize = nWidth * nHeight * sizeof(RGBQUAD);
hr = pColorFrame->CopyConvertedFrameDataToArray(nBufferSize, reinterpret_cast<BYTE*>(pBuffer), ColorImageFormat_Bgra);
}
else
{
hr = E_FAIL;
}
}
if (SUCCEEDED(hr))
{
{
ProcessColor(nTime, pBuffer, nWidth, nHeight);
}
}
SafeRelease(pFrameDescription);
}
else{
DumpHR(hr);
}
SafeRelease(pColorFrame);
}
void ProcessColor(INT64 nTime, RGBQUAD* pBuffer, int nWidth, int nHeight)
{
if (!m_nStartTime)
{
m_nStartTime = nTime;
}
// Make sure we've received valid data
if (pBuffer)
{
RGBQUAD * pColor = m_pColorRGBX;
// end pixel is start + width*height - 1
const RGBQUAD * pBufferEnd = pBuffer + (nWidth * nHeight);
while (pBuffer < pBufferEnd)
{
RGBQUAD color = *pBuffer;
*pColor = color;
++pColor;
++pBuffer;
}
}
}
void UpdateBody()
{
if (!m_pBodyFrameReader)
{
return;
}
IBodyFrame* pBodyFrame = NULL;
HRESULT hr = m_pBodyFrameReader->AcquireLatestFrame(&pBodyFrame);
if (SUCCEEDED(hr))
{
INT64 nTime = 0;
hr = pBodyFrame->get_RelativeTime(&nTime);
IBody* ppBodies[BODY_COUNT] = {0};
if (SUCCEEDED(hr))
{
hr = pBodyFrame->GetAndRefreshBodyData(_countof(ppBodies), ppBodies);
}
if (SUCCEEDED(hr))
{
ProcessBody(nTime, _countof(ppBodies), ppBodies);
}
for (int i = 0; i < _countof(ppBodies); ++i)
{
SafeRelease(ppBodies[i]);
}
}
SafeRelease(pBodyFrame);
}
void ProcessBody(unsigned int nTime, unsigned int nBodyCount, IBody * ppBodies[6]){
UCHAR bestBody = 0xff;
float bestScore = 0;
float trackingStateTable[3];
trackingStateTable[TrackingState_Inferred] = 0.5;
trackingStateTable[TrackingState_NotTracked] = 0;
trackingStateTable[TrackingState_Tracked] = 1;
for(int i=0;i<nBodyCount;++i){
IBody * body = ppBodies[i];
BOOLEAN bodyTracked;
HRESULT hr = body->get_IsTracked(&bodyTracked);
if(!SUCCEEDED(hr) || !bodyTracked) continue;
Joint joints[JointType_Count];
hr = body->GetJoints(JointType_Count, joints);
if(!SUCCEEDED(hr)) continue;
float score=0;
for(int j=0;j<JointType_Count;++j){
score += trackingStateTable[joints[j].TrackingState];
}
if(score > bestScore){
bestScore = score;
bestBody = i;
}
}
if (bestBody == 0xff){
m_bSkeletonIsGood = false;
m_nBodyIndex = 0xff;
return;
}
HRESULT hr = ppBodies[bestBody]->GetJoints(JointType_Count, m_pJoints);
if(!SUCCEEDED(hr)){
std::cerr << "Error saving joints\n";
m_bSkeletonIsGood = false;
m_nBodyIndex = 0xff;
}else{
m_bSkeletonIsGood = true;
m_nBodyIndex = bestBody;
}
}
void UpdateBodyFrameIndex(){
if(!m_pBodyIndexFrameReader){
return;
}
if(m_nDepthWidth == 0 || m_nDepthHeight == 0 || m_nColorWidth == 0 || m_nColorHeight == 0){
return;
}
if(m_nBodyIndex == 0xff){
return;
}
IBodyIndexFrame * pBodyIndexFrame = NULL;
HRESULT hr = m_pBodyIndexFrameReader->AcquireLatestFrame(&pBodyIndexFrame);
if(SUCCEEDED(hr)){
unsigned int nBufferSize = 0;
unsigned char * pBuffer = NULL;
if(SUCCEEDED(hr)){
hr = pBodyIndexFrame->AccessUnderlyingBuffer(&nBufferSize, &pBuffer);
}
if(SUCCEEDED(hr)){
hr = m_pCoordinateMapper->MapColorFrameToDepthSpace(m_nDepthWidth*m_nDepthHeight, m_pDepth, m_nColorWidth*m_nColorHeight, m_pColorDepthMap);
}
if(SUCCEEDED(hr)){
ProcessBodyFrameIndexColor(pBuffer, m_nDepthWidth, m_nDepthHeight, m_pColorDepthMap, m_nColorWidth, m_nColorHeight);
}
}
SafeRelease(pBodyIndexFrame);
}
void ProcessBodyFrameIndexColor(unsigned char * pBodyIndexBuffer, unsigned int nDepthWidth, unsigned int nDepthHeight, const DepthSpacePoint * pColorDepthMap, int nColorWidth, int nColorHeight){
int colorSize = nColorWidth * nColorHeight;
if(pBodyIndexBuffer && pColorDepthMap){
RGBQUAD * pBodyColorRGBX = m_pBodyColorRGBX;
RGBQUAD * pColorRGBX = m_pColorRGBX;
const DepthSpacePoint * pBufferEnd = pColorDepthMap + colorSize;
while(pColorDepthMap < pBufferEnd){
DepthSpacePoint depthSpacePoint = *pColorDepthMap;
int pointerValue = depthSpacePoint.X + depthSpacePoint.Y * nDepthWidth;
if (pointerValue > 0){
unsigned char bodyIndex = pBodyIndexBuffer[pointerValue];
if (bodyIndex == m_nBodyIndex)
*pBodyColorRGBX = *pColorRGBX;
else{
pBodyColorRGBX->rgbBlue = 0xff;
pBodyColorRGBX->rgbGreen = 0xff;
pBodyColorRGBX->rgbRed = 0xff;
pBodyColorRGBX->rgbReserved = 0;
}
}
else{
pBodyColorRGBX->rgbBlue = 0;
pBodyColorRGBX->rgbGreen = 0;
pBodyColorRGBX->rgbRed = 0;
pBodyColorRGBX->rgbReserved = 0;
}
++pColorDepthMap;
++pBodyColorRGBX;
++pColorRGBX;
}
}
}
//legacy
void mapDepthToSkeleton(float * nDepthX, float * nDepthY, long * nDepth, float * nCameraX, float * nCameraY, float * nCameraZ){
if(!m_pCoordinateMapper){
return;
}
DepthSpacePoint depthSpacePoint;
depthSpacePoint.X = *nDepthX;
depthSpacePoint.Y = *nDepthY;
CameraSpacePoint cameraSpacePoint;
m_pCoordinateMapper->MapDepthPointToCameraSpace(depthSpacePoint, *nDepth, &cameraSpacePoint);
*nCameraX = cameraSpacePoint.X;
*nCameraY = cameraSpacePoint.Y;
*nCameraZ = cameraSpacePoint.Z;
}
RGBQUAD * GetDepthRGBX(){
return m_pDepthRGBX;
}
USHORT * GetDepth(){
return m_pDepth;
}
RGBQUAD * GetColorRGBX(){
return m_pColorRGBX;
}
USHORT * GetDepthMappedToColor(){
return m_pDepthMappedToColor;
}
int * GetDepthXMappedToColor(){
return m_pDepthXMappedToColor;
}
int * GetDepthYMappedToColor(){
return m_pDepthYMappedToColor;
}
RGBQUAD * GetBodyColorRGBX(){
return m_pBodyColorRGBX;
}
Joint * GetJoints(){
return m_pJoints;
}
unsigned int getDepthWidth(){
return m_nDepthWidth;
}
unsigned int getDepthHeight(){
return m_nDepthHeight;
}
unsigned int getColorWidth(){
return m_nColorWidth;
}
unsigned int getColorHeight(){
return m_nColorHeight;
}
bool getSkeletonIsGood(){
return m_bSkeletonIsGood;
}
ICoordinateMapper * getCoordinateMapper(){
return m_pCoordinateMapper;
}
} | [
"enzodayrit11@gmail.com"
] | enzodayrit11@gmail.com |
fea14a01307a98f84e89732abea8fe12b7dcb50f | aa4669a80c56029423c8587d9eac3f69c6d5a1fd | /testproj/bin/android/obj/src/flash/events/HTTPStatusEvent.cpp | 31e1213f27174d7a264b94affe6b959ee8045a4d | [] | no_license | shadowofsoul/testproj | aa9c04bfd72262f2aaaa5c1cf366ab2f5c5385ec | e31016cb0cedf7b966b166f99cfd41f36896ac1e | refs/heads/master | 2021-01-01T18:54:42.559141 | 2014-02-08T00:09:25 | 2014-02-08T00:09:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,786 | cpp | #include <hxcpp.h>
#ifndef INCLUDED_Std
#include <Std.h>
#endif
#ifndef INCLUDED_flash_events_Event
#include <flash/events/Event.h>
#endif
#ifndef INCLUDED_flash_events_HTTPStatusEvent
#include <flash/events/HTTPStatusEvent.h>
#endif
namespace flash{
namespace events{
Void HTTPStatusEvent_obj::__construct(::String type,hx::Null< bool > __o_bubbles,hx::Null< bool > __o_cancelable,hx::Null< int > __o_status)
{
HX_STACK_PUSH("HTTPStatusEvent::new","flash/events/HTTPStatusEvent.hx",12);
bool bubbles = __o_bubbles.Default(false);
bool cancelable = __o_cancelable.Default(false);
int status = __o_status.Default(0);
{
HX_STACK_LINE(14)
super::__construct(type,bubbles,cancelable);
HX_STACK_LINE(16)
this->status = status;
}
;
return null();
}
HTTPStatusEvent_obj::~HTTPStatusEvent_obj() { }
Dynamic HTTPStatusEvent_obj::__CreateEmpty() { return new HTTPStatusEvent_obj; }
hx::ObjectPtr< HTTPStatusEvent_obj > HTTPStatusEvent_obj::__new(::String type,hx::Null< bool > __o_bubbles,hx::Null< bool > __o_cancelable,hx::Null< int > __o_status)
{ hx::ObjectPtr< HTTPStatusEvent_obj > result = new HTTPStatusEvent_obj();
result->__construct(type,__o_bubbles,__o_cancelable,__o_status);
return result;}
Dynamic HTTPStatusEvent_obj::__Create(hx::DynamicArray inArgs)
{ hx::ObjectPtr< HTTPStatusEvent_obj > result = new HTTPStatusEvent_obj();
result->__construct(inArgs[0],inArgs[1],inArgs[2],inArgs[3]);
return result;}
::String HTTPStatusEvent_obj::toString( ){
HX_STACK_PUSH("HTTPStatusEvent::toString","flash/events/HTTPStatusEvent.hx",28);
HX_STACK_THIS(this);
HX_STACK_LINE(28)
return ((((((((HX_CSTRING("[HTTPStatusEvent type=") + this->get_type()) + HX_CSTRING(" bubbles=")) + ::Std_obj::string(this->get_bubbles())) + HX_CSTRING(" cancelable=")) + ::Std_obj::string(this->get_cancelable())) + HX_CSTRING(" status=")) + this->status) + HX_CSTRING("]"));
}
::flash::events::Event HTTPStatusEvent_obj::clone( ){
HX_STACK_PUSH("HTTPStatusEvent::clone","flash/events/HTTPStatusEvent.hx",21);
HX_STACK_THIS(this);
HX_STACK_LINE(21)
return ::flash::events::HTTPStatusEvent_obj::__new(this->get_type(),this->get_bubbles(),this->get_cancelable(),this->status);
}
::String HTTPStatusEvent_obj::HTTP_STATUS;
HTTPStatusEvent_obj::HTTPStatusEvent_obj()
{
}
void HTTPStatusEvent_obj::__Mark(HX_MARK_PARAMS)
{
HX_MARK_BEGIN_CLASS(HTTPStatusEvent);
HX_MARK_MEMBER_NAME(status,"status");
super::__Mark(HX_MARK_ARG);
HX_MARK_END_CLASS();
}
void HTTPStatusEvent_obj::__Visit(HX_VISIT_PARAMS)
{
HX_VISIT_MEMBER_NAME(status,"status");
super::__Visit(HX_VISIT_ARG);
}
Dynamic HTTPStatusEvent_obj::__Field(const ::String &inName,bool inCallProp)
{
switch(inName.length) {
case 5:
if (HX_FIELD_EQ(inName,"clone") ) { return clone_dyn(); }
break;
case 6:
if (HX_FIELD_EQ(inName,"status") ) { return status; }
break;
case 8:
if (HX_FIELD_EQ(inName,"toString") ) { return toString_dyn(); }
break;
case 11:
if (HX_FIELD_EQ(inName,"HTTP_STATUS") ) { return HTTP_STATUS; }
}
return super::__Field(inName,inCallProp);
}
Dynamic HTTPStatusEvent_obj::__SetField(const ::String &inName,const Dynamic &inValue,bool inCallProp)
{
switch(inName.length) {
case 6:
if (HX_FIELD_EQ(inName,"status") ) { status=inValue.Cast< int >(); return inValue; }
break;
case 11:
if (HX_FIELD_EQ(inName,"HTTP_STATUS") ) { HTTP_STATUS=inValue.Cast< ::String >(); return inValue; }
}
return super::__SetField(inName,inValue,inCallProp);
}
void HTTPStatusEvent_obj::__GetFields(Array< ::String> &outFields)
{
outFields->push(HX_CSTRING("status"));
super::__GetFields(outFields);
};
static ::String sStaticFields[] = {
HX_CSTRING("HTTP_STATUS"),
String(null()) };
static ::String sMemberFields[] = {
HX_CSTRING("toString"),
HX_CSTRING("clone"),
HX_CSTRING("status"),
String(null()) };
static void sMarkStatics(HX_MARK_PARAMS) {
HX_MARK_MEMBER_NAME(HTTPStatusEvent_obj::__mClass,"__mClass");
HX_MARK_MEMBER_NAME(HTTPStatusEvent_obj::HTTP_STATUS,"HTTP_STATUS");
};
static void sVisitStatics(HX_VISIT_PARAMS) {
HX_VISIT_MEMBER_NAME(HTTPStatusEvent_obj::__mClass,"__mClass");
HX_VISIT_MEMBER_NAME(HTTPStatusEvent_obj::HTTP_STATUS,"HTTP_STATUS");
};
Class HTTPStatusEvent_obj::__mClass;
void HTTPStatusEvent_obj::__register()
{
hx::Static(__mClass) = hx::RegisterClass(HX_CSTRING("flash.events.HTTPStatusEvent"), hx::TCanCast< HTTPStatusEvent_obj> ,sStaticFields,sMemberFields,
&__CreateEmpty, &__Create,
&super::__SGetClass(), 0, sMarkStatics, sVisitStatics);
}
void HTTPStatusEvent_obj::__boot()
{
HTTP_STATUS= HX_CSTRING("httpStatus");
}
} // end namespace flash
} // end namespace events
| [
"david@y-developments.com"
] | david@y-developments.com |
887ff391111025c099dfbc7a1754dab79f89487a | 53bbde66a89cf44fa459509a0c5154df2a447494 | /tracking/src/tracker_object.cpp | 8e0b6d4d0e42e2cb6b02924699158eb2e654ec51 | [] | no_license | marketto89/open_ptrack | 0fb41c9d3047d79a0aa4116be9be73185ce2de86 | f3790b6aa1139f6b72c48ec43e8ee890e2fa704d | HEAD | 2019-07-06T15:58:08.375880 | 2017-09-26T21:34:58 | 2017-09-26T21:34:58 | 103,685,443 | 37 | 10 | null | null | null | null | UTF-8 | C++ | false | false | 18,681 | cpp | /*
* Software License Agreement (BSD License)
*
* Copyright (c) 2011-2012, Matteo Munaro [matteo.munaro@dei.unipd.it], Filippo Basso [filippo.basso@dei.unipd.it]
* Copyright (c) 2013-, Open Perception, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the copyright holder(s) nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Author: Matteo Munaro [matteo.munaro@dei.unipd.it], Filippo Basso [filippo.basso@dei.unipd.it]
*
*/
#include <opencv2/opencv.hpp>
#include <open_ptrack/tracking/tracker_object.h>
namespace open_ptrack
{
namespace tracking
{
TrackerObject::TrackerObject(
double gate_distance,
bool detector_likelihood,
std::vector<double> likelihood_weights,
bool velocity_in_motion_term,
double min_confidence,
double min_confidence_detections,
double sec_before_old,
double sec_before_fake,
double sec_remain_new,
int detections_to_validate,
double period,
double position_variance,
double acceleration_variance,
std::string world_frame_id,
bool debug_mode,
bool vertical) :
gate_distance_(gate_distance),
detector_likelihood_(detector_likelihood),
likelihood_weights_(likelihood_weights),
velocity_in_motion_term_(velocity_in_motion_term),
min_confidence_(min_confidence),
min_confidence_detections_(min_confidence_detections),
sec_before_old_(sec_before_old),
sec_before_fake_(sec_before_fake),
sec_remain_new_(sec_remain_new),
detections_to_validate_(detections_to_validate),
period_(period),
position_variance_(position_variance),
acceleration_variance_(acceleration_variance),
world_frame_id_(world_frame_id),
debug_mode_(debug_mode),
vertical_(vertical)
{
tracks_counter_ = 0;
}
TrackerObject::~TrackerObject()
{
// TODO Auto-generated destructor stub
}
void
TrackerObject::newFrame(const std::vector<open_ptrack::detection::Detection>& detections)
{
detections_.clear();
unassociated_detections_.clear();
lost_tracks_.clear();
new_tracks_.clear();
detections_ = detections;
ros::Time current_detections_time = detections_[0].getSource()->getTime();
for(std::list<open_ptrack::tracking::TrackObject*>::iterator it = tracks_.begin(); it != tracks_.end();)
{
open_ptrack::tracking::TrackObject* t = *it;
bool deleted = false;
if(((t->getVisibility() == TrackObject::NOT_VISIBLE && (t->getSecFromLastHighConfidenceDetection(current_detections_time)) >= sec_before_old_)
|| (!t->isValidated() && t->getSecFromFirstDetection(current_detections_time) >= sec_before_fake_)))
{
if (debug_mode_)
{
std::cout << "Track " << t->getId() << " DELETED" << std::endl;
}
delete t;
it = tracks_.erase(it);
deleted = true;
}
else if(!t->isValidated() && t->getUpdatesWithEnoughConfidence() == detections_to_validate_)
{
t->validate();
if (debug_mode_)
{
std::cout << "Track " << t->getId() << " VALIDATED" << std::endl;
}
}
else if(t->getStatus() == TrackObject::NEW && t->getSecFromFirstDetection(current_detections_time) >= sec_remain_new_)
{
t->setStatus(TrackObject::NORMAL);
if (debug_mode_)
{
std::cout << "Track " << t->getId() << " set to NORMAL" << std::endl;
}
}
if(!deleted)
{
if(t->getStatus() == TrackObject::NEW && t->getVisibility() == TrackObject::VISIBLE)
new_tracks_.push_back(t);
if(t->getVisibility() == TrackObject::NOT_VISIBLE)
lost_tracks_.push_back(t);
it++;
}
}
}
void
TrackerObject::updateTracks()
{
createDistanceMatrix();
createCostMatrix();
// Solve Global Nearest Neighbor problem:
Munkres munkres;
cost_matrix_ = munkres.solve(cost_matrix_, false); // rows: targets (tracks), cols: detections
updateDetectedTracks();
fillUnassociatedDetections();
updateLostTracks();
createNewTracks();
}
void
TrackerObject::toMarkerArray(visualization_msgs::MarkerArray::Ptr& msg)
{
for(std::list<open_ptrack::tracking::TrackObject*>::iterator it =
tracks_.begin(); it != tracks_.end(); it++)
{
open_ptrack::tracking::TrackObject* t = *it;
t->createMarker(msg);
}
}
void
TrackerObject::toMsg(opt_msgs::TrackArray::Ptr& msg)
{
for(std::list<open_ptrack::tracking::TrackObject*>::iterator it =
tracks_.begin(); it != tracks_.end(); it++)
{
open_ptrack::tracking::TrackObject* t = *it;
opt_msgs::Track track;
t->toMsg(track, vertical_);
msg->tracks.push_back(track);
}
}
void
TrackerObject::toMsg(opt_msgs::TrackArray::Ptr& msg,
std::string& source_frame_id)
{
for(std::list<open_ptrack::tracking::TrackObject*>::iterator it =
tracks_.begin(); it != tracks_.end(); it++)
{
open_ptrack::tracking::TrackObject* t = *it;
if (strcmp(t->getDetectionSource()->getFrameId().c_str(),
source_frame_id.c_str()) == 0) // if strings are equal
{
opt_msgs::Track track;
t->toMsg(track, vertical_);
// // For publishing only not occluded tracks:
// if (track.visibility < 2)
// msg->tracks.push_back(track);
// For publishing all tracks:
msg->tracks.push_back(track);
}
}
}
void
TrackerObject::to_object_name_Msg(opt_msgs::ObjectNameArray::Ptr& msg)
{
if(association_for_initialize_objectnames_.size()==tracks_.size())
{
int index=0;
for(std::list<open_ptrack::tracking::TrackObject*>::iterator it = tracks_.begin(); it != tracks_.end(); it++)
{
open_ptrack::tracking::TrackObject* t = *it;
opt_msgs::ObjectName object_name_msg;
object_name_msg.object_name=t->object_name_;
object_name_msg.no=association_for_initialize_objectnames_[index];
msg->object_names.push_back(object_name_msg);
index++;
// std::cout<<"send message with object name:"<<t->object_name_<<std::endl;
}
}
association_for_initialize_objectnames_.clear();
}
void
TrackerObject::getAliveIDs (opt_msgs::IDArray::Ptr& msg)
{
for(std::list<open_ptrack::tracking::TrackObject*>::iterator it = tracks_.begin(); it != tracks_.end(); it++)
{
open_ptrack::tracking::TrackObject* t = *it;
msg->ids.push_back ((*it)->getId());
}
msg->max_ID = tracks_counter_;
}
size_t
TrackerObject::appendToPointCloud(pcl::PointCloud<pcl::PointXYZRGB>::Ptr& pointcloud, size_t starting_index, size_t max_size)
{
for(size_t i = 0; i < tracks_.size() && pointcloud->size() < max_size; i++)
{
pcl::PointXYZRGB point;
pointcloud->push_back(point);
}
for(std::list<open_ptrack::tracking::TrackObject*>::iterator it = tracks_.begin(); it != tracks_.end(); it++)
{
open_ptrack::tracking::TrackObject* t = *it;
if(t->getPointXYZRGB(pointcloud->points[starting_index]))
starting_index = (starting_index + 1) % max_size;
}
return starting_index;
}
/************************ protected methods ************************/
int
TrackerObject::createNewTrack(open_ptrack::detection::Detection& detection)
{
if(detection.getConfidence() < min_confidence_)
return -1;
open_ptrack::tracking::TrackObject* t;
t = new open_ptrack::tracking::TrackObject(
++tracks_counter_,
world_frame_id_,
position_variance_,
acceleration_variance_,
period_,
velocity_in_motion_term_ );
t->init(detection.getWorldCentroid()(0), detection.getWorldCentroid()(1),detection.getWorldCentroid()(2),
detection.getHeight(), detection.getDistance(), detection.getObjectName(),detection.getSource());
bool first_update = true;
t->update(detection.getWorldCentroid()(0), detection.getWorldCentroid()(1), detection.getWorldCentroid()(2),
detection.getHeight(), detection.getDistance(), detection.getObjectName(),0.0,
detection.getConfidence(), min_confidence_, min_confidence_detections_, detection.getSource(), first_update);
ROS_INFO("Created %d", t->getId());
tracks_.push_back(t);
return tracks_counter_;
}
void
TrackerObject::createDistanceMatrix()
{
distance_matrix_ = cv::Mat_<double>(tracks_.size(), detections_.size());
int track = 0;
for(std::list<TrackObject*>::iterator it = tracks_.begin(); it != tracks_.end(); it++)
{
//double x, y, height, vx, vz;
TrackObject* t = *it;
//t->predict(x, y, height, vx, vz);
int measure = 0;
for(std::vector<open_ptrack::detection::Detection>::iterator dit = detections_.begin(); dit != detections_.end(); dit++)
{
double detector_likelihood;
// Compute detector likelihood:
if (detector_likelihood_)
{
detector_likelihood = dit->getConfidence();
// detector_likelihood = log((dit->getConfidence() + 3) / 6);
}
else
{
detector_likelihood = 0;
}
// Compute motion likelihood:
double motion_likelihood = t->getMahalanobisDistance(
dit->getWorldCentroid()(0),
dit->getWorldCentroid()(1),
dit->getSource()->getTime());
// Compute joint likelihood and put it in the distance matrix:
distance_matrix_(track, measure++) = likelihood_weights_[0] * detector_likelihood + likelihood_weights_[1] * motion_likelihood;
// Remove NaN and inf:
if (isnan(distance_matrix_(track, measure-1)) | (not std::isfinite(distance_matrix_(track, measure-1))))
distance_matrix_(track, measure-1) = 2*gate_distance_;
// std::cout << (*it)->getId() << ": " << "Motion likelihood: " << likelihood_weights_[0] * motion_likelihood << std::endl;
// if (detector_likelihood_)
// std::cout << (*it)->getId() << ": " << "Detector likelihood: " << likelihood_weights_[1] * dit->getConfidence() << std::endl;
// std::cout << (*it)->getId() << ": " << "JOINT LIKELIHOOD: " << distance_matrix_(track, measure-1) << std::endl;
/*ROS_INFO("%d(%f, %f) = %f", t->getId(),
dit->getWorldCentroid()(0),
dit->getWorldCentroid()(1),
distance_matrix_(track, measure - 1));*/
}
track++;
}
// std::cout << "Distance matrix:" << std::endl;
// for(int row = 0; row < distance_matrix_.rows; row++)
// {
// for(int col = 0; col < distance_matrix_.cols; col++)
// {
// std::cout.width(8);
// std::cout << distance_matrix_(row,col) << ",";
// }
// std::cout << std::endl;
// }
// std::cout << std::endl;
}
void
TrackerObject::createCostMatrix()
{
cost_matrix_ = distance_matrix_.clone();
for(int i = 0; i < distance_matrix_.rows; i++)
{
for(int j = 0; j < distance_matrix_.cols; j++)
{
if(distance_matrix_(i, j) > gate_distance_)
cost_matrix_(i, j) = 1000000.0;
}
}
// std::cout << "Munkres input matrix:" << std::endl;
// for(int row = 0; row < cost_matrix_.rows; row++)
// {
// for(int col = 0; col < cost_matrix_.cols; col++)
// {
// std::cout.width(8);
// std::cout << cost_matrix_(row,col) << ",";
// }
// std::cout << std::endl;
// }
// std::cout << std::endl;
}
void
TrackerObject::updateDetectedTracks()
{
// std::cout << "Munkres output matrix:" << std::endl;
// for(int row = 0; row < cost_matrix_.rows; row++) {
// for(int col = 0; col < cost_matrix_.cols; col++) {
// std::cout.width(1);
// std::cout << cost_matrix_(row,col) << ",";
// }
// std::cout << std::endl;
// }
// std::cout << std::endl;
// Iterate over every track:
int track = 0;
for(std::list<open_ptrack::tracking::TrackObject*>::iterator it = tracks_.begin(); it != tracks_.end(); it++)
{
bool updated = false;
open_ptrack::tracking::TrackObject* t = *it;
for(int measure = 0; measure < cost_matrix_.cols; measure++)
{
// If a detection<->track association has been found:
if(cost_matrix_(track, measure) == 0.0 && distance_matrix_(track, measure) <= gate_distance_)
{
open_ptrack::detection::Detection& d = detections_[measure];
// If the detection has enough confidence in the current frame or in a recent past:
// if ((t->getLowConfidenceConsecutiveFrames() < 10) || ((d.getConfidence() - 0.5) > min_confidence_detections_))
if ((t->getLowConfidenceConsecutiveFrames() < 10) || (d.getConfidence() > ((min_confidence_ + min_confidence_detections_)/2)))
{
//for object tracking
association_for_initialize_objectnames_.push_back(measure);
// Update track with the associated detection:
bool first_update = false;
t->update(d.getWorldCentroid()(0), d.getWorldCentroid()(1), d.getWorldCentroid()(2),d.getHeight(),
d.getDistance(),d.getObjectName(), distance_matrix_(track, measure),
d.getConfidence(), min_confidence_, min_confidence_detections_,
d.getSource(), first_update);
t->setVisibility(d.isOccluded() ? TrackObject::OCCLUDED : TrackObject::VISIBLE);
updated = true;
break;
}
else
{
//std::cout << "Id: " << t->getId() << ", lowConfConsFrames: " << t->getLowConfidenceConsecutiveFrames() << ", newConf: " << d.getConfidence()<< std::endl;
}
}
}
if(!updated)
{
if(t->getVisibility() != TrackObject::NOT_VISIBLE)
{
t->setVisibility(TrackObject::NOT_VISIBLE);
//t->update();
}
}
track++;
}
// std::cout << std::endl;
}
void
TrackerObject::fillUnassociatedDetections()
{
// Fill a list with detections not associated to any track:
if(cost_matrix_.cols == 0 && detections_.size() > 0)
{
for(size_t measure = 0; measure < detections_.size(); measure++)
unassociated_detections_.push_back(detections_[measure]);
}
else
{
for(int measure = 0; measure < cost_matrix_.cols; measure++)
{
bool associated = false;
for(int track = 0; track < cost_matrix_.rows; track++)
{
if(cost_matrix_(track, measure) == 0.0)
{
if(distance_matrix_(track, measure) > gate_distance_)
break;
associated = true;
}
}
if(!associated/* && detections_[measure].getConfidence() > min_confidence_*/)
{
unassociated_detections_.push_back(detections_[measure]);
}
}
}
}
void
TrackerObject::updateLostTracks()
{
//for(std::list<open_ptrack::tracking::Track*>::iterator it = lost_tracks_.begin(); it != lost_tracks_.end(); it++)
// (*it)->update();
}
void
TrackerObject::createNewTracks()
{
for(std::list<open_ptrack::detection::Detection>::iterator dit = unassociated_detections_.begin();
dit != unassociated_detections_.end(); dit++)
{
createNewTrack(*dit);
}
}
void
TrackerObject::setMinConfidenceForTrackInitialization (double min_confidence)
{
min_confidence_ = min_confidence;
}
void
TrackerObject::setSecBeforeOld (double sec_before_old)
{
sec_before_old_ = sec_before_old;
}
void
TrackerObject::setSecBeforeFake (double sec_before_fake)
{
sec_before_fake_ = sec_before_fake;
}
void
TrackerObject::setSecRemainNew (double sec_remain_new)
{
sec_remain_new_ = sec_remain_new;
}
void
TrackerObject::setDetectionsToValidate (int detections_to_validate)
{
detections_to_validate_ = detections_to_validate;
}
void
TrackerObject::setDetectorLikelihood (bool detector_likelihood)
{
detector_likelihood_ = detector_likelihood;
}
void
TrackerObject::setLikelihoodWeights (double detector_weight, double motion_weight)
{
likelihood_weights_[0] = detector_weight;
likelihood_weights_[1] = motion_weight;
}
void
TrackerObject::setVelocityInMotionTerm (bool velocity_in_motion_term, double acceleration_variance, double position_variance)
{
velocity_in_motion_term_ = velocity_in_motion_term;
acceleration_variance_ = acceleration_variance;
position_variance_ = position_variance;
// Update all existing tracks:
for(std::list<open_ptrack::tracking::TrackObject*>::iterator it = tracks_.begin(); it != tracks_.end(); it++)
{
open_ptrack::tracking::TrackObject* t = *it;
t->setVelocityInMotionTerm (velocity_in_motion_term_, acceleration_variance_, position_variance_);
}
}
void
TrackerObject::setAccelerationVariance (double acceleration_variance)
{
acceleration_variance_ = acceleration_variance;
// Update all existing tracks:
for(std::list<open_ptrack::tracking::TrackObject*>::iterator it = tracks_.begin(); it != tracks_.end(); it++)
{
open_ptrack::tracking::TrackObject* t = *it;
t->setAccelerationVariance (acceleration_variance_);
}
}
void
TrackerObject::setPositionVariance (double position_variance)
{
position_variance_ = position_variance;
// Update all existing tracks:
for(std::list<open_ptrack::tracking::TrackObject*>::iterator it = tracks_.begin(); it != tracks_.end(); it++)
{
open_ptrack::tracking::TrackObject* t = *it;
t->setPositionVariance (position_variance_);
}
}
void
TrackerObject::setGateDistance (double gate_distance)
{
gate_distance_ = gate_distance;
}
} /* namespace tracking */
} /* namespace open_ptrack */
| [
"carraromarco89@gmail.com"
] | carraromarco89@gmail.com |
e0cd1b4936b4e15f4bd5878e4db740186431d238 | 1dcb0ac0e3f62a61389677b1e3e938a49addac1d | /macroslib/tests/expectations/pass_objects_as_param_simple.cpp | 0dad17f6e4d3825ca10d50065b65ae08ab1c92fd | [
"BSD-3-Clause"
] | permissive | MichaelMcCulloch/rust_swig | 2815dfaf2da391372ad7861627852051074e21ce | bbd6e80916e548f9736d8bcf9be59740f6fa5e3d | refs/heads/master | 2020-06-02T14:58:07.707167 | 2019-06-10T15:52:27 | 2019-06-10T15:52:27 | 191,198,039 | 0 | 0 | BSD-3-Clause | 2019-06-10T15:48:40 | 2019-06-10T15:48:39 | null | UTF-8 | C++ | false | false | 1,957 | cpp | "typedef struct FooOpaque FooOpaque;";
"void TestPassObjectsAsParams_f1(const TestPassObjectsAsParamsOpaque * const self, const FooOpaque * a_0);";
"void TestPassObjectsAsParams_f2(const TestPassObjectsAsParamsOpaque * const self, FooOpaque * a_0);";
"void TestPassObjectsAsParams_f3(const TestPassObjectsAsParamsOpaque * const self, FooOpaque * a_0);";
"void TestPassObjectsAsParams_f3_a(const TestPassObjectsAsParamsOpaque * const self, BooOpaque * a_0);";
"void TestPassObjectsAsParams_f4(const FooOpaque * a_0);";
"void TestPassObjectsAsParams_f5(FooOpaque * a_0);";
"void f1(const Foo & a_0) const noexcept";
"void f2(Foo a_0) const noexcept";
"void f3(Foo & a_0) const noexcept";
"void f3_a(Boo & a_0) const noexcept";
"static void f4(const Foo & a_0) noexcept";
"static void f5(Foo a_0) noexcept";
r#"inline void TestPassObjectsAsParamsWrapper<OWN_DATA>::f1(const Foo & a_0) const noexcept
{
TestPassObjectsAsParams_f1(this->self_, static_cast<const FooOpaque *>(a_0));
}"#;
r#"inline void TestPassObjectsAsParamsWrapper<OWN_DATA>::f2(Foo a_0) const noexcept
{
TestPassObjectsAsParams_f2(this->self_, a_0.release());
}"#;
r#"inline void TestPassObjectsAsParamsWrapper<OWN_DATA>::f3(Foo & a_0) const noexcept
{
TestPassObjectsAsParams_f3(this->self_, static_cast<FooOpaque *>(a_0));
}"#;
r#"template<bool OWN_DATA>
inline void TestPassObjectsAsParamsWrapper<OWN_DATA>::f3_a(Boo & a_0) const noexcept
{
TestPassObjectsAsParams_f3_a(this->self_, static_cast<BooOpaque *>(a_0));
}"#;
r#"template<bool OWN_DATA>
inline void TestPassObjectsAsParamsWrapper<OWN_DATA>::f4(const Foo & a_0) noexcept
{
TestPassObjectsAsParams_f4(static_cast<const FooOpaque *>(a_0));
}"#;
r#"template<bool OWN_DATA>
inline void TestPassObjectsAsParamsWrapper<OWN_DATA>::f5(Foo a_0) noexcept
{
TestPassObjectsAsParams_f5(a_0.release());
}"#;
| [
"dushistov@mail.ru"
] | dushistov@mail.ru |
785787f5fa58a5ba020ad14a276ea60e19a6d3db | 9bae2f8bddb7f62c6ef3bb0f8e0e66130dc62329 | /src/serialization/serializers/json/jsonDecoder.cpp | 4e5239a80927c442e4205bc95e1f810da607a294 | [] | no_license | smarrog/smr-library-cpp | 545ac0f3c0126996b004db8aa8d24c7e8db3cfc8 | e885fd6aee836d5f9629fe48255a5ff833b51b77 | refs/heads/master | 2020-05-16T13:57:07.756578 | 2019-07-02T15:39:08 | 2019-07-02T15:39:08 | 183,088,155 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,228 | cpp | #include "jsonDecoder.hpp"
#include "serialization/utils.hpp"
#include "serialization/exceptions.hpp"
#include <string>
#include <vector>
#include <map>
#include <iostream>
#include <sstream>
using namespace smr;
void checkWord(std::istream& is, const std::string& word) {
for (auto c : word) {
if (c != static_cast<char>(is.get())) {
throw std::runtime_error("Failed to read expected word: " + word);
}
}
}
void skipSpaces(std::istream& is) {
while (is.peek() != -1 && std::isspace(is.peek())) {
is.ignore();
}
}
void readExponent(std::ostream& os, std::istream& is) {
auto next = is.get();
if (next != 'e' && next != 'E') {
throw UnexpectedTokenException(next);
}
tokenToStream(os, next);
next = is.peek();
if (next == '-' || next == '+') {
tokenToStream(os, next);
is.ignore(1);
}
while (std::isdigit(is.peek())) {
tokenToStream(os, is.get());
}
}
void readFractal(std::ostream& os, std::istream& is) {
auto next = is.peek();
if (next != '.') {
readExponent(os, is);
return;
}
tokenToStream(os, '.');
is.ignore();
while (std::isdigit(is.peek())) {
tokenToStream(os, is.get());
}
if (is.peek() == 'e' || is.peek() == 'E') {
readExponent(os, is);
}
}
Serializable JsonDecoder::decode() {
auto value = decodeSerializable();
skipSpaces(_is);
if (_is.peek() != -1) {
throw UnexpectedTokenException(_is.peek());
}
return value;
}
Serializable JsonDecoder::decodeSerializable() {
skipSpaces(_is);
switch (_is.peek()) {
case '[':
return decodeArray();
case '{':
return decodeObject();
case '"':
return decodeString();
case 't':
checkWord(_is, "true");
return true;
case 'f':
checkWord(_is, "false");
return false;
case 'n':
checkWord(_is, "null");
return nullptr;
case '-':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return decodeNumber();
default:
throw UnexpectedTokenException(_is.peek());
}
}
Serializable JsonDecoder::decodeArray() {
checkToken(_is, '[');
Array result;
skipSpaces(_is);
if (_is.peek() == ']') {
_is.ignore();
return result;
}
while (_is.peek() != -1) {
result.emplace_back(decodeSerializable());
skipSpaces(_is);
if (_is.peek() == ',') {
_is.ignore();
continue;
}
if (_is.peek() == ']') {
_is.ignore();
return result;
}
throw UnexpectedTokenException(_is.peek());
}
throw UnexpectedEofException();
}
Serializable JsonDecoder::decodeObject() {
checkToken(_is, '{');
Object result;
skipSpaces(_is);
if (_is.peek() == '}') {
_is.ignore();
return result;
}
while (_is.peek() != -1) {
std::string key = decodeString().asString();
skipSpaces(_is);
checkToken(_is, ':');
skipSpaces(_is);
result.emplace(move(key), decodeSerializable());
skipSpaces(_is);
if (_is.peek() == ',') {
_is.ignore();
skipSpaces(_is);
continue;
}
if (_is.peek() == '}') {
_is.ignore();
return result;
}
throw UnexpectedTokenException(_is.peek());
}
throw UnexpectedEofException("object");
}
Serializable JsonDecoder::decodeString() {
checkToken(_is, '"');
std::ostringstream oss;
while (_is.peek() != -1) {
auto next = _is.peek();
if (next == '"') {
_is.ignore();
return oss.str();
} else if (next == '\\') {
utf8SymbolToStream(oss, getEscaped(_is));
} else if (next < ' ' && next != '\t' && next != '\r' && next != '\n') {
throw UnexpectedTokenException(next);
} else if (next > 0b1111'1101) {
throw UnexpectedTokenException(next);
} else if (next < 0b1000'0000) {
tokenToStream(oss, _is.get());
} else {
utf8SymbolToStream(oss, getUtf8Symbol(_is));
}
}
throw UnexpectedEofException("string");
}
Serializable JsonDecoder::decodeNumber() {
bool isNegative = _is.peek() == '-';
if (isNegative) {
_is.ignore();
}
auto left = 0ull;
while (_is.peek() != -1) {
auto next = _is.peek();
if (std::isdigit(next)) {
left = (left << 3) + (left << 1) + next - 48;
_is.ignore();
if (_is.peek() == -1) {
return isNegative ? -static_cast<int>(left) : static_cast<int>(left);
}
} else if (next == '.' || next == 'e' || next == 'E') {
std::ostringstream right;
readFractal(right, _is);
return std::stod((isNegative ? '-' : '+') + std::string(std::to_string(left) + right.str()));
} else if (left > INT32_MAX) {
return isNegative ? -static_cast<double>(left) : static_cast<double>(left);
} else {
return isNegative ? -static_cast<int>(left) : static_cast<int>(left);
}
}
throw UnexpectedEofException("number");
} | [
"smr@live.ru"
] | smr@live.ru |
1316984b6c79691c6eacf5db7eb82fbd6e08f27a | 3f47459adef1cca22194f319c55a57f5c292fa6a | /CatBox/ClientUnit.h | af4bff8168e2aa00b0c320c8a34f456312941ccc | [] | no_license | BackupTheBerlios/catbox-svn | 1e5c5f4f5a74265edd1130942c4da558b6a6ed52 | 417501e72b941cc8ff70c3b19d4a24df6d2741ee | refs/heads/master | 2021-01-01T17:57:41.600175 | 2007-03-27T09:27:26 | 2007-03-27T09:27:26 | 40,667,414 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 239 | h | #ifndef CLIENTUNIT_H_
#define CLIENTUNIT_H_
#include <iostream>
#include "CSocket.h"
using namespace std;
class ClientUnit
{
protected:
public:
ClientUnit();
virtual ~ClientUnit();
CSocket *cClientSocket;
};
#endif /*CLIENTUNIT_H_*/
| [
"pixman@b0f48c23-7a0f-0410-98b5-b31d7b8841d2"
] | pixman@b0f48c23-7a0f-0410-98b5-b31d7b8841d2 |
eb51e87825a5b25b881a90a13baa963350a7c245 | 89dcccb951d343f1936a8329aa539ba5a4f6f91b | /방민형/비행기/비행기/stdafx.cpp | 3c47cc1d97babc50ab93f35929666976321fa16b | [] | no_license | nakta1617/sbs20120806 | 4d89f8f19c0283254b4d159384b6f3a6edadbf32 | f5dadb04028bd1b98300f02225dcd89d4051f78f | refs/heads/master | 2021-01-24T02:16:52.794883 | 2012-08-17T10:55:55 | 2012-08-17T10:55:55 | null | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 335 | cpp | // stdafx.cpp : 표준 포함 파일만 들어 있는 소스 파일입니다.
// 비행기.pch는 미리 컴파일된 헤더가 됩니다.
// stdafx.obj에는 미리 컴파일된 형식 정보가 포함됩니다.
#include "stdafx.h"
// TODO: 필요한 추가 헤더는
// 이 파일이 아닌 STDAFX.H에서 참조합니다.
| [
"raspisanie@naver.com"
] | raspisanie@naver.com |
93771ab8bbd5deb60b128f9ab45ae96593409a6c | fea3c6d33572d8968639746b8afdc6cfa4c400de | /SPOJ/AMR10A/AMR10A.cpp | 551768c9ddfee8f59c336ad111d6a5c42f8be05e | [] | no_license | linmx0130/OJCode | f99ae2163828891dfe05cd0510391dbfad27430c | fbadd1ab4640c85edc1d2a8e58cd570ecebb91fb | refs/heads/master | 2020-03-30T03:51:03.731960 | 2016-11-05T19:43:17 | 2016-11-05T19:43:17 | 5,111,571 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 733 | cpp | #include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#define MAXN 50005
int N,Q;
struct Point
{
double x,y;
Point operator- (Point & t)
{
Point ret;
ret.x=x-t.x;
ret.y=y-t.y;
return ret;
}
double det(const Point & t)
{
return x*t.y-y*t.x;
}
}D[MAXN];
double F[MAXN];
int main()
{
scanf("%d%d",&N,&Q);
for (int i=0;i<N;++i)
{
scanf("%lf%lf",&D[i].x,&D[i].y);
}
F[0]=0;F[1]=0;
for (int i=2;i<N;++i)
{
F[i]=F[i-1]+(D[i]-D[0]).det(D[i-1]-D[0]);
}
double S=F[N-1];
for (;Q;Q--)
{
int a,b;
scanf("%d%d",&a,&b);
double t1=(D[b]-D[0]).det(D[a]-D[0]);
double s2=F[b]-F[a]-t1;
double s1=S-s2;
if (s1<s2) printf("%.1lf\n",s1/2.0);
else printf("%.1lf\n",s2/2.0);
}
return 0;
}
| [
"linmx0130@163.com"
] | linmx0130@163.com |
c6916067e3f4261acc6093d9db27c8de69a38c17 | bd1fea86d862456a2ec9f56d57f8948456d55ee6 | /000/103/286/CWE427_Uncontrolled_Search_Path_Element__wchar_t_file_83.h | 6649a5dc3c72d6c2508cb092322692cedde4daf1 | [] | no_license | CU-0xff/juliet-cpp | d62b8485104d8a9160f29213368324c946f38274 | d8586a217bc94cbcfeeec5d39b12d02e9c6045a2 | refs/heads/master | 2021-03-07T15:44:19.446957 | 2020-03-10T12:45:40 | 2020-03-10T12:45:40 | 246,275,244 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,432 | h | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE427_Uncontrolled_Search_Path_Element__wchar_t_file_83.h
Label Definition File: CWE427_Uncontrolled_Search_Path_Element.label.xml
Template File: sources-sink-83.tmpl.h
*/
/*
* @description
* CWE: 427 Uncontrolled Search Path Element
* BadSource: file Read input from a file
* GoodSource: Use a hardcoded path
* Sinks:
* BadSink : Set the environment variable
* Flow Variant: 83 Data flow: data passed to class constructor and destructor by declaring the class object on the stack
*
* */
#include "std_testcase.h"
#include <wchar.h>
#ifdef _WIN32
#define NEW_PATH L"%SystemRoot%\\system32"
#define PUTENV _wputenv
#else
#define NEW_PATH L"/bin"
#define PUTENV putenv
#endif
namespace CWE427_Uncontrolled_Search_Path_Element__wchar_t_file_83
{
#ifndef OMITBAD
class CWE427_Uncontrolled_Search_Path_Element__wchar_t_file_83_bad
{
public:
CWE427_Uncontrolled_Search_Path_Element__wchar_t_file_83_bad(wchar_t * dataCopy);
~CWE427_Uncontrolled_Search_Path_Element__wchar_t_file_83_bad();
private:
wchar_t * data;
};
#endif /* OMITBAD */
#ifndef OMITGOOD
class CWE427_Uncontrolled_Search_Path_Element__wchar_t_file_83_goodG2B
{
public:
CWE427_Uncontrolled_Search_Path_Element__wchar_t_file_83_goodG2B(wchar_t * dataCopy);
~CWE427_Uncontrolled_Search_Path_Element__wchar_t_file_83_goodG2B();
private:
wchar_t * data;
};
#endif /* OMITGOOD */
}
| [
"frank@fischer.com.mt"
] | frank@fischer.com.mt |
701106d435825ff46c0e351e65210f58b4f59335 | 53758d03b112554ce9afbae9ea4f85acf9f5bb64 | /1_LinkedLists/38_removeLoop1.cpp | b74e6f579d647f24ee30f708d699d73bf00fce65 | [] | no_license | skalva404/geeksCoding | 47f3795cce9bbaa761b89a97667ed9231a3a783e | 58ae1d4a1b65bf849456209295fa0e696b51ed8c | refs/heads/master | 2020-04-26T17:25:14.069994 | 2015-06-22T06:39:59 | 2015-06-22T06:39:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,412 | cpp | //given a linked list detect if there is a loop nd remove it
//using hash map
//O(n) time
//O(n) space
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<map>
using namespace std;
struct node
{
int data;
struct node *next;
struct node *arbitptr;
};
typedef struct node Listnode;
typedef Listnode *Listnodeptr;
void printList(Listnodeptr startptr)
{
if(startptr)
{
while(startptr)
{
printf("%d-->",startptr->data);
startptr = startptr->next;
}
printf("NULL\n\n");
}
else
{
printf("list is empty\n");
}
}
void insert(Listnodeptr *startptr, int data)
{
Listnodeptr newnode = (Listnode *)malloc(sizeof(Listnode));
Listnodeptr preptr=NULL;
Listnodeptr currentptr = *startptr;
if(newnode)
{
newnode->data = data;
newnode->next = NULL;
while(currentptr != NULL)//iterate to the end
{
preptr = currentptr;
currentptr = currentptr->next;
}
if(preptr == NULL)//if list is empty
{
*startptr = newnode;
}
else //else insert at the end of the list
{
preptr->next = newnode;
}
}
else
{
printf("error: out of memory\n");
}
}
//delete func
void deleteList(Listnodeptr *startptr)
{
Listnodeptr temp;
while(*startptr != NULL)
{
temp= *startptr;
*startptr = (*startptr)->next;
printf("%d deleted\n",temp->data);
free(temp);
}
}
//detect nd remove loop
void removeLoop(Listnodeptr start)
{
if(start==NULL)
{
printf("empty list\n");
return;
}
map<Listnodeptr,int> m1;
map<Listnodeptr,int>::iterator i;
Listnodeptr cur=start,pre;
while(cur!=NULL)
{
i=m1.find(cur);
if(i==m1.end()) //if first occurrence of node, insert its address in map
{
m1.insert(pair<Listnodeptr,int>(cur,1));
pre=cur;
cur=cur->next;
}
else //repeating node => loop
{
printf("loop is present n starts at %d\n",cur->data);
pre->next=NULL;
printf("loop broken\n");
return;
}
}
printf("no loop present\n");
}
int main()
{
Listnodeptr startptr = NULL;
int n, data, i,nValue;
int hasLoop = 0;//false
printf("enter the no of elements in the list: ");
scanf("%d",&n);
printf("enter all the elements: ");
for(i=0;i<n;i++)
{
scanf("%d",&data);
insert(&startptr,data);
}
printList(startptr);
Listnodeptr cur=startptr;
while(cur->next!=NULL)
cur=cur->next;
cur->next=startptr->next; //insert loop from last to second node
removeLoop(startptr);
printList(startptr);
return 0;
}
| [
"subash.k3110@outlook.com"
] | subash.k3110@outlook.com |
439609be3a209fcb4b530676c628cc8b42b3f37a | 13ca0b6930f9c17684d0065c0dab34bfd1e0cca1 | /modules/client/sync/rooms/ephemeral.cc | 032b3281d9413f2b89e0884d1c1414b3a78226be | [
"BSD-3-Clause",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | InspectorDidi/construct | 064ea432c30a71a5e0ba100e623d334418234588 | 64a5eec565ab8664a010de31ba72a569206f3eef | refs/heads/master | 2020-07-03T13:57:32.453475 | 2019-08-09T02:58:44 | 2019-08-09T03:01:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,710 | cc | // Matrix Construct
//
// Copyright (C) Matrix Construct Developers, Authors & Contributors
// Copyright (C) 2016-2018 Jason Volk <jason@zemos.net>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice is present in all copies. The
// full license for this software is available in the LICENSE file.
ircd::mapi::header
IRCD_MODULE
{
"Client Sync :Rooms Ephemeral"
};
namespace ircd::m::sync
{
static bool rooms_ephemeral_events_polylog(data &);
static bool rooms_ephemeral_polylog(data &);
static bool rooms_ephemeral_linear(data &);
extern item rooms_ephemeral;
}
decltype(ircd::m::sync::rooms_ephemeral)
ircd::m::sync::rooms_ephemeral
{
"rooms.ephemeral",
rooms_ephemeral_polylog,
rooms_ephemeral_linear
};
bool
ircd::m::sync::rooms_ephemeral_linear(data &data)
{
bool ret{false};
m::sync::for_each("rooms.ephemeral", [&data, &ret]
(item &item)
{
json::stack::checkpoint checkpoint
{
*data.out
};
if(item.linear(data))
ret = true;
else
checkpoint.rollback();
return true;
});
return ret;
}
bool
ircd::m::sync::rooms_ephemeral_polylog(data &data)
{
return rooms_ephemeral_events_polylog(data);
}
bool
ircd::m::sync::rooms_ephemeral_events_polylog(data &data)
{
json::stack::array array
{
*data.out, "events"
};
bool ret{false};
m::sync::for_each("rooms.ephemeral", [&data, &ret]
(item &item)
{
json::stack::checkpoint checkpoint
{
*data.out
};
if(item.polylog(data))
{
ret = true;
data.out->invalidate_checkpoints();
}
else checkpoint.rollback();
return true;
});
return ret;
}
| [
"jason@zemos.net"
] | jason@zemos.net |
34f087549b2a460f1a064531c385e9c09129198d | 9bf61dc28ecf9e3ed884964685776a84c4719639 | /Algorithms/Symmetric Tree/SymmetricTree.cpp | 4574de68f0b95bd997625c2537a0f78566bc74e4 | [] | no_license | ms31dc/LeetCode | 3e9aea86a340ff8d72c448cb66b9d8d11827d26d | 2f6770ee242f86a58ad913d474611869f062f4ba | refs/heads/master | 2021-05-19T18:43:00.628710 | 2019-05-04T06:58:58 | 2019-05-04T06:58:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,650 | cpp | /**
* Definition for a binary tree node.
* struct TreeNode
* {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution
{
public:
bool isEqual(TreeNode* root1, TreeNode* root2)
{
if(root1 == NULL && root2 == NULL)
{
return true;
}
if(root1 == NULL || root2 == NULL)
{
return false;
}
if(root1->val == root2->val &&
isEqual(root1->left, root2->right) &&
isEqual(root1->right, root2->left))
{
return true;
}
else
{
return false;
}
}
bool isSymmetric(TreeNode* root)
{
return isEqual(root, root);
}
};
void trimLeftTrailingSpaces(string &input)
{
input.erase(input.begin(), find_if(input.begin(), input.end(), [](int ch)
{
return !isspace(ch);
}));
}
void trimRightTrailingSpaces(string &input)
{
input.erase(find_if(input.rbegin(), input.rend(), [](int ch)
{
return !isspace(ch);
}).base(), input.end());
}
TreeNode* stringToTreeNode(string input)
{
trimLeftTrailingSpaces(input);
trimRightTrailingSpaces(input);
input = input.substr(1, input.length() - 2);
if (!input.size())
{
return nullptr;
}
string item;
stringstream ss;
ss.str(input);
getline(ss, item, ',');
TreeNode* root = new TreeNode(stoi(item));
queue<TreeNode*> nodeQueue;
nodeQueue.push(root);
while (true)
{
TreeNode* node = nodeQueue.front();
nodeQueue.pop();
if (!getline(ss, item, ','))
{
break;
}
trimLeftTrailingSpaces(item);
if (item != "null")
{
int leftNumber = stoi(item);
node->left = new TreeNode(leftNumber);
nodeQueue.push(node->left);
}
if (!getline(ss, item, ','))
{
break;
}
trimLeftTrailingSpaces(item);
if (item != "null")
{
int rightNumber = stoi(item);
node->right = new TreeNode(rightNumber);
nodeQueue.push(node->right);
}
}
return root;
}
string boolToString(bool input)
{
return input ? "True" : "False";
}
int main()
{
string line;
while (getline(cin, line))
{
TreeNode* root = stringToTreeNode(line);
bool ret = Solution().isSymmetric(root);
string out = boolToString(ret);
cout << out << endl;
}
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
bd5c2e551af43b61c982e6b4d1932e2059fc3d69 | 5febc6cd3ba376e7cc8249c0316612cdbac9fd2d | /MapWalker.cpp | 595fc8668bd65f095a4c1080e5ddc67e30b45b3b | [] | no_license | thecherry94/Tilestrategy | a9582683c1420616f010b3529faf84a038f4fae7 | 62414818bca275e8b886cef8df40fbb914ad65bd | refs/heads/master | 2021-01-19T13:30:02.255912 | 2017-04-30T16:57:00 | 2017-04-30T16:57:00 | 88,092,512 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,516 | cpp | #include "MapWalker.hpp"
MapWalker::MapWalker()
{
}
MapWalker::MapWalker(Tilemap* p_map, sf::Vector2u pos, sf::Sprite& sprite, float speed)
: _p_map(p_map), _pfstate(NONE), _walk_idx(0), _walk_speed(speed)
{
setPosition((sf::Vector2f)pos);
setScale(_p_map->getScale());
_sprite = sprite;
}
void MapWalker::draw(sf::RenderTarget& target, sf::RenderStates states) const
{
states.transform *= getTransform();
target.draw(_sprite, states);
}
/*
* Calculates a path asynchronously and makes the walker move
* as soon as path is available
* Walker must be idle to be executed
*/
void MapWalker::move_to(sf::Vector2u pos, bool diagonal)
{
// Only do something new if idle
if (_pfstate != NONE)
return;
// Transform from world pos to map pos
sf::Vector2u map_pos = _p_map->screen_to_map_coords(getPosition());
// Create a functor
auto f = [](Tilemap* m, sf::Vector2u mp, sf::Vector2u p, bool dgl)
{
return m->get_path(mp, p, dgl);
};
// Run the async thread and find a path
_future_path = std::make_shared<std::future<Path>>(std::async(std::launch::async, f, _p_map, map_pos, pos, diagonal));
// Set state to calculating
_pfstate = CALCULATING;
}
void MapWalker::update(float dt)
{
// Nothing to do
if (_pfstate == NONE)
return;
// Execute this while the pathfinding is in progress
if (_pfstate == CALCULATING)
{
// Check if it's done
auto status = _future_path->wait_for(std::chrono::microseconds(10));
// If async call done
if (status == std::future_status::ready)
{
// Get the calculated path
_current_path = _future_path->get();
_future_path.reset();
// No path could be found
if (_current_path.size() < 1)
{
_pfstate = NONE;
return;
}
// The path is in backward order
_walk_idx = _current_path.size();
_pfstate = WALKING;
_clk.restart();
}
}
// A path is available and it's walking
if (_pfstate == WALKING)
{
// Did walker already wait long enough?
if (_clk.getElapsedTime().asMilliseconds() < 1000 / _walk_speed)
return;
// Restart the timer clock and reduce the position index
_clk.restart();
_walk_idx--;
// Did walker reach the end?
if (_walk_idx < 0)
{
// Add event for when action is done
_current_path.clear();
_pfstate = NONE;
return;
}
// Set it's position on the map
//
int tilesize = _p_map->get_tile_size(true);
sf::Vector2f p_path = (sf::Vector2f)_current_path[_walk_idx];
p_path.x *= tilesize;
p_path.y *= tilesize;
setPosition(p_path);
}
} | [
"philipp.kirsch94@googlemail.com"
] | philipp.kirsch94@googlemail.com |
d2551ab81e6eff72e24cf521804ddb9bc5becb5b | 514da49aba89d420d127d886fa2832c610b2d127 | /src/server.cpp | b1b0c680c95a17d1cd217979bc4b18cffb3624ca | [] | no_license | k3v1n1990s/DNS | eeed7205c9944afb533d79913bfad43b25572a31 | 6d5a3657126459304e06c466d5bb92be2ac3cd48 | refs/heads/master | 2022-01-05T13:42:30.170411 | 2018-09-17T13:31:22 | 2018-09-17T13:31:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,341 | cpp |
#define _WIN32_WINNT 0x0601
#include "server.h"
#include <boost/property_tree/json_parser.hpp>
[[nodiscard]] auto DNSServerCreateInfo::CreateFromFile(std::string const & fileName) -> DNSServerCreateInfo {
boost::property_tree::ptree config;
boost::property_tree::read_json(fileName, config);
DNSServerCreateInfo desc;
desc.FileNameCache = config.get<std::string>("FileNameCache");
desc.BindAdress = { config.get_child("BindAddress").get<std::string>("IP"), config.get_child("BindAddress").get<uint16_t>("Port") };
for (auto const&[_, tree] : config.get_child("DNSServers"))
desc.DNSServers.push_back({ tree.get<std::string>("IP"), tree.get<uint16_t>("Port") });
return desc;
}
DNSServer::DNSServer(DNSServerCreateInfo const& desc) {
namespace fs = std::experimental::filesystem;
m_UDPSock = std::make_shared<Sock>(m_IOService);
m_UDPSock->open(boost::asio::ip::udp::v4());
m_UDPSock->non_blocking(true);
m_UDPSock->bind({ boost::asio::ip::address::from_string(desc.BindAdress.first), desc.BindAdress.second });
m_FileNameCache = desc.FileNameCache;
m_DNSServers = desc.DNSServers;
m_IsRunApplication = true;
if (fs::exists(fs::path{ m_FileNameCache }))
m_Cache = DNS::Cache::Load(m_FileNameCache);
}
auto DNSServer::Run() -> void {
std::cout << "Application run ";
std::cout << " IP: " << m_UDPSock->local_endpoint().address().to_string();
std::cout << " Port:" << m_UDPSock->local_endpoint().port() << std::endl;
m_ThreadUpdateCache = std::make_unique<Thread>([&] {
while (m_IsRunApplication) {
auto currentTime = std::time(nullptr);
m_Cache.Update(currentTime);
std::this_thread::sleep_for(std::chrono::seconds{ 5 });
}
});
m_ThreadMain = std::make_unique<Thread>([&] {
while (m_IsRunApplication) {
Result reciverClientResult;
Result timerResult;
size_t dataSize;
auto timerHandler = [&](auto const& err) -> void { timerResult.reset(err); };
auto reciverClientHandler = [&](auto const& err, auto size) -> void { reciverClientResult.reset(err); dataSize = size; };
Buffer buffer;
Endpoint endpoint;
Timer timer{ m_IOService };
timer.expires_from_now(std::chrono::seconds(2));
timer.async_wait(timerHandler);
m_UDPSock->async_receive_from(boost::asio::buffer(buffer), endpoint, reciverClientHandler);
m_IOService.reset();
if (!this->WaitTimeout(m_UDPSock, timer, reciverClientResult, timerResult))
continue;
this->Connection(endpoint, DNS::Package::CreatePackageFromBuffer(buffer));
}
});
m_ThreadUpdateCache->join();
m_ThreadMain->join();
DNS::Cache::Save(m_FileNameCache, m_Cache);
m_IsExit = true;
}
auto DNSServer::Shutdown() -> void {
std::cout << "Application shutdown " << std::endl;
if (m_IsRunApplication) {
m_IsRunApplication = false;
while (!m_IsExit);
}
}
auto DNSServer::Connection(Endpoint const& endpoint, DNS::Package const& query) -> void {
if (m_Cache.ContainsKey({ query.Header.Flags, query.Questions.front().Name, query.Questions.front().Question })) {
auto name = query.Questions.front().Name;
name.erase(std::remove(name.begin(), name.end(), 0x07), name.end());
std::cout << "Get from cache: " << name.data() << std::endl;
Result senderResult;
Result timerResult;
auto timerHandler = [&](auto const& err) -> void { timerResult.reset(err); };
auto senderHandler = [&](auto const& err, auto size) -> void { senderResult.reset(err); };
Timer timer(m_IOService);
auto answer = m_Cache.Get({ query.Header.Flags, query.Questions.front().Name, query.Questions.front().Question });
answer.Header.ID = query.Header.ID;
{
timer.expires_from_now(std::chrono::seconds(2));
timer.async_wait(timerHandler);
m_UDPSock->async_send_to(boost::asio::buffer(DNS::Package::CreateBufferFromPackage(answer), DNS::Package::ComputeSize(answer)), endpoint, senderHandler);
m_IOService.reset();
this->WaitTimeout(m_UDPSock, timer, senderResult, timerResult);
}
} else {
for (auto const&[ip, port] : m_DNSServers) {
Result senderServerResult;
Result senderClientResult;
Result recieverServerResult;
Result timerResult;
auto timerHandler = [&](auto const& err) -> void { timerResult.reset(err); };
auto senderServerHandler = [&](auto const& err, auto size) -> void { senderServerResult.reset(err); };
auto senderClientHandler = [&](auto const& err, auto size) -> void { senderClientResult.reset(err); };
auto receiverServerHandler = [&](auto const& err, auto size) -> void { recieverServerResult.reset(err); };
Timer timer{ m_IOService };
auto sock = std::make_shared<Sock>(m_IOService, Endpoint{ boost::asio::ip::udp::v4(), 0 });
{
timer.expires_from_now(std::chrono::seconds(2));
timer.async_wait(timerHandler);
sock->async_send_to(boost::asio::buffer(DNS::Package::CreateBufferFromPackage(query), DNS::Package::ComputeSize(query)), { boost::asio::ip::address::from_string(ip), port }, senderServerHandler);
m_IOService.reset();
if (!this->WaitTimeout(sock, timer, senderServerResult, timerResult))
continue;
}
DNS::Package answer;
{
Buffer buffer;
timer.expires_from_now(std::chrono::seconds(2));
timer.async_wait(timerHandler);
sock->async_receive(boost::asio::buffer(buffer), receiverServerHandler);
m_IOService.reset();
if (!this->WaitTimeout(sock, timer, recieverServerResult, timerResult))
continue;
answer = std::move(DNS::Package::CreatePackageFromBuffer(buffer));
answer.Header.ID = query.Header.ID;
}
{
timer.expires_from_now(std::chrono::seconds(2));
timer.async_wait(timerHandler);
m_UDPSock->async_send_to(boost::asio::buffer(DNS::Package::CreateBufferFromPackage(answer), DNS::Package::ComputeSize(answer)), endpoint, senderClientHandler);
m_IOService.reset();
if (!this->WaitTimeout(m_UDPSock, timer, senderClientResult, timerResult))
continue;
}
m_Cache.Insert({ query.Header.Flags, answer.Questions.front().Name, answer.Questions.front().Question }, answer);
break;
}
}
}
auto DNSServer::WaitTimeout(SockPtr sock, Timer& timer, Result& operationResult, Result& timerResult) -> bool
{
while (m_IOService.run_one()) {
if (operationResult)
timer.cancel();
else if (timerResult)
sock->cancel();
}
return (*operationResult) ? false : true;
}
| [
"misha.friman@mail.ru"
] | misha.friman@mail.ru |
f7d7c216c7fa8b4d4bdd4297b2a62429e80d07c7 | c64090331e744ad3671d0ea72685847320245b0b | /C++ book/02-09/argc_argv.cpp | 39a47b0246476a18750b18d3c070b44e7501bf49 | [] | no_license | VigneshKumarKK/C-_training | ad21f8f4c530aca5b2c45c2f0f10450727cbe1ad | 3a06157a2a9cbbf385ef4e318d266b3351c8c4a9 | refs/heads/main | 2023-08-03T13:07:10.881755 | 2021-09-12T10:38:45 | 2021-09-12T10:38:45 | 400,407,338 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 215 | cpp | #include <iostream>
using namespace std;
int main(int argc, char** argv)
{
cout << "You have entered " << argc
<< " arguments:" << "\n";
for (int i = 0; i < argc; ++i)
cout << argv[i] << "\n";
return 0;
}
| [
"vigkec@gmail.com"
] | vigkec@gmail.com |
818235291b97067b5af4b1b4e13b4f38e9e9a86f | 9c5e26500d320b9dce13896c3afcb3d2fc6ebe0b | /services/identity/public/cpp/identity_manager.cc | 19efa647cf67a3ebcff473e94bed390ea8063e13 | [
"BSD-3-Clause"
] | permissive | zhaoming0/chromium-src | 835b2f1c4a00cce65dc5452157e16cf871d567a0 | ddccd3f6dba62870a038ecb7d68b28038fcbe5d9 | refs/heads/master | 2023-01-15T15:35:00.825036 | 2018-01-17T22:34:16 | 2018-01-17T22:34:16 | 167,121,109 | 0 | 0 | null | 2019-01-23T05:10:44 | 2019-01-23T05:10:43 | null | UTF-8 | C++ | false | false | 6,348 | cc | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "services/identity/public/cpp/identity_manager.h"
#include "base/memory/ptr_util.h"
#include "base/threading/sequenced_task_runner_handle.h"
namespace identity {
IdentityManager::IdentityManager(SigninManagerBase* signin_manager,
ProfileOAuth2TokenService* token_service)
: signin_manager_(signin_manager), token_service_(token_service) {
primary_account_info_ = signin_manager_->GetAuthenticatedAccountInfo();
signin_manager_->AddObserver(this);
token_service_->AddDiagnosticsObserver(this);
}
IdentityManager::~IdentityManager() {
signin_manager_->RemoveObserver(this);
token_service_->RemoveDiagnosticsObserver(this);
}
AccountInfo IdentityManager::GetPrimaryAccountInfo() {
#if defined(OS_CHROMEOS)
// On ChromeOS in production, the authenticated account is set very early in
// startup and never changed. Hence, the information held by the
// IdentityManager should always correspond to that held by SigninManager.
// NOTE: the above invariant is not guaranteed to hold in tests. If you
// are seeing this DCHECK go off in a testing context, it means that you need
// to set the IdentityManager's primary account info in the test at the place
// where you are setting the authenticated account info in the SigninManager.
// TODO(blundell): Add the API to do this once we hit the first case and
// document the API to use here.
DCHECK_EQ(signin_manager_->GetAuthenticatedAccountInfo().account_id,
primary_account_info_.account_id);
DCHECK_EQ(signin_manager_->GetAuthenticatedAccountInfo().gaia,
primary_account_info_.gaia);
DCHECK_EQ(signin_manager_->GetAuthenticatedAccountInfo().email,
primary_account_info_.email);
#endif
return primary_account_info_;
}
std::unique_ptr<PrimaryAccountAccessTokenFetcher>
IdentityManager::CreateAccessTokenFetcherForPrimaryAccount(
const std::string& oauth_consumer_name,
const OAuth2TokenService::ScopeSet& scopes,
PrimaryAccountAccessTokenFetcher::TokenCallback callback,
PrimaryAccountAccessTokenFetcher::Mode mode) {
return base::MakeUnique<PrimaryAccountAccessTokenFetcher>(
oauth_consumer_name, signin_manager_, token_service_, scopes,
std::move(callback), mode);
}
void IdentityManager::RemoveAccessTokenFromCache(
const AccountInfo& account_info,
const OAuth2TokenService::ScopeSet& scopes,
const std::string& access_token) {
// Call PO2TS asynchronously to mimic the eventual interaction with the
// Identity Service.
base::SequencedTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(&OAuth2TokenService::InvalidateAccessToken,
base::Unretained(token_service_),
account_info.account_id, scopes, access_token));
}
void IdentityManager::AddObserver(Observer* observer) {
observer_list_.AddObserver(observer);
}
void IdentityManager::RemoveObserver(Observer* observer) {
observer_list_.RemoveObserver(observer);
}
void IdentityManager::AddDiagnosticsObserver(DiagnosticsObserver* observer) {
diagnostics_observer_list_.AddObserver(observer);
}
void IdentityManager::RemoveDiagnosticsObserver(DiagnosticsObserver* observer) {
diagnostics_observer_list_.RemoveObserver(observer);
}
void IdentityManager::SetPrimaryAccountSynchronouslyForTests(
std::string gaia_id,
std::string email_address,
std::string refresh_token) {
signin_manager_->SetAuthenticatedAccountInfo(gaia_id, email_address);
primary_account_info_ = signin_manager_->GetAuthenticatedAccountInfo();
token_service_->UpdateCredentials(primary_account_info_.account_id,
refresh_token);
}
void IdentityManager::GoogleSigninSucceeded(const AccountInfo& account_info) {
// Fire observer callbacks asynchronously to mimic this callback itself coming
// in asynchronously from the Identity Service rather than synchronously from
// SigninManager.
base::SequencedTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(&IdentityManager::HandleGoogleSigninSucceeded,
base::Unretained(this), account_info));
}
void IdentityManager::GoogleSignedOut(const AccountInfo& account_info) {
// Fire observer callbacks asynchronously to mimic this callback itself coming
// in asynchronously from the Identity Service rather than synchronously from
// SigninManager.
base::SequencedTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(&IdentityManager::HandleGoogleSignedOut,
base::Unretained(this), account_info));
}
void IdentityManager::OnAccessTokenRequested(
const std::string& account_id,
const std::string& consumer_id,
const OAuth2TokenService::ScopeSet& scopes) {
// Fire observer callbacks asynchronously to mimic this callback itself coming
// in asynchronously from the Identity Service rather than synchronously from
// ProfileOAuth2TokenService.
base::SequencedTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(&IdentityManager::HandleOnAccessTokenRequested,
base::Unretained(this), account_id, consumer_id, scopes));
}
void IdentityManager::HandleGoogleSigninSucceeded(
const AccountInfo& account_info) {
primary_account_info_ = account_info;
for (auto& observer : observer_list_) {
observer.OnPrimaryAccountSet(account_info);
}
}
void IdentityManager::HandleGoogleSignedOut(const AccountInfo& account_info) {
DCHECK(account_info.account_id == primary_account_info_.account_id);
DCHECK(account_info.gaia == primary_account_info_.gaia);
DCHECK(account_info.email == primary_account_info_.email);
primary_account_info_ = AccountInfo();
for (auto& observer : observer_list_) {
observer.OnPrimaryAccountCleared(account_info);
}
}
void IdentityManager::HandleOnAccessTokenRequested(
const std::string& account_id,
const std::string& consumer_id,
const OAuth2TokenService::ScopeSet& scopes) {
for (auto& observer : diagnostics_observer_list_) {
observer.OnAccessTokenRequested(account_id, consumer_id, scopes);
}
}
} // namespace identity
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
a10e4f83d8fdc11ad7797db4bcf034f9062ed1d6 | 5d9db0b557a1433e6cc6d9bb46c34967ba6f6b97 | /cpp/LabGraph/Graph.h | 5db6c6944a369b90787fa5baa9e623245382f30d | [] | no_license | rouol/LabGraph | 153e34161d4f91caf3010a3aad49da212899becd | cfdeac1c2907822906935014d850b98e0425af19 | refs/heads/master | 2023-02-01T03:40:32.348007 | 2020-12-13T00:28:03 | 2020-12-13T00:28:03 | 320,948,780 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,305 | h | #pragma once
#include <map>
#include "Sequence.h"
#include "PriorityQueue.h"
//template <typename T>
//using Matrix = ArraySequence<ArraySequence<T>>;
using MatrixInt = ArraySequence<ArraySequence<int>>;
class Graph {
public:
virtual ~Graph() {}
virtual int CountVertex() const = 0;
virtual void AddArc(int from, int to, int weight = 1) = 0;
virtual void RemoveArc(int from, int t) = 0;
virtual int HasArc(int from, int to) const = 0;
};
ArraySequence<int> reconstructPath(int goal, std::map<int, int> cameFrom) {
ArraySequence<int> path = ArraySequence<int>();
int current = goal;
while (cameFrom[current] != -1) {
path.Append(current);
current = cameFrom[current];
}
path.Append(current);
return path;
}
template <typename T>
class MatrixGraph : public Graph {
private:
ArraySequence<T>* Values;
MatrixInt* AdjacencyMatrix;
MatrixInt* WeightMatrix;
int nVertex;
public:
/*
MatrixGraph() {
this->nVertex = 0;
this->ValueMatrix = new Matrix<T>();
this->AdjacencyMatrix = new MatrixInt();
this->WeightMatrix = new MatrixInt();
}
*/
MatrixGraph(int n) {
this->nVertex = n;
this->Values = new ArraySequence<T>(n, NULL);
this->AdjacencyMatrix = new MatrixInt(n, ArraySequence<int>(n, 0));
this->WeightMatrix = new MatrixInt(n, ArraySequence<int>(n, 0));
}
MatrixGraph(ArraySequence<T> arraySequence) {
this->nVertex = arraySequence.GetLength();
this->Values = new ArraySequence<T>(arraySequence);
this->AdjacencyMatrix = new MatrixInt(this->nVertex, ArraySequence<int>(this->nVertex, 0));
this->WeightMatrix = new MatrixInt(this->nVertex, ArraySequence<int>(this->nVertex, 0));
}
int CountVertex() const override {
return this->nVertex;
}
void AddArc(int from, int to, int weight) override {
// check if can be arc
if ((0 <= from < this->nVertex) && (0 <= to < this->nVertex)) {
(*(this->AdjacencyMatrix))[from][to] = 1;
(*(this->WeightMatrix))[from][to] = weight;
}
else {
throw std::exception("ImpossibleArcException");
}
}
void RemoveArc(int from, int to) override {
// check if can be arc
if ((0 <= from < this->nVertex) && (0 <= to < this->nVertex)) {
(*(this->AdjacencyMatrix))[from][to] = 0;
(*(this->WeightMatrix))[from][to] = 0;
}
else {
throw std::exception("ImpossibleArcException");
}
}
int HasArc(int from, int to) const override {
// check if can be arc
if ((0 <= from && from < this->nVertex) && (0 <= to && to < this->nVertex)) {
return (*(this->AdjacencyMatrix))[from][to];
}
else {
throw std::exception("ImpossibleArcException");
}
}
ArraySequence<T> Neighbors(int index) const {
ArraySequence<T> neighbors = ArraySequence<T>();
ArraySequence<int> line = (*(this->AdjacencyMatrix))[index];
for (size_t i = 0; i < line.GetLength(); i++) {
if (line[i] == 1) {
neighbors.Append((*(this->Values))[i]);
}
}
return neighbors;
}
ArraySequence<int> NeighborVertexs(int index) const {
ArraySequence<int> neighbors = ArraySequence<T>();
ArraySequence<int> line = (*(this->AdjacencyMatrix))[index];
for (size_t i = 0; i < line.GetLength(); i++) {
if (line[i] == 1) {
neighbors.Append(i);
}
}
return neighbors;
}
ArraySequence<int> DijkstraSearch(int start, int goal) const {
PriorityQueue<int> frontier = PriorityQueue<int>();
frontier.Enqueue(start, 0);
std::map<int, int> cameFrom = std::map<int, int>();
cameFrom[start] = -1;
std::map<int, int> costSoFar = std::map<int, int>();
costSoFar[start] = 0;
while (!frontier.IsEmpty()) {
int current = frontier.Dequeue();
if (current == goal) {
return reconstructPath(goal, cameFrom);
}
ArraySequence<int> neighborVertexs = this->NeighborVertexs(current);
for (size_t i = 0; i < neighborVertexs.GetLength(); i++) {
int next = neighborVertexs[i];
if (next == goal) {
cameFrom[goal] = current;
return reconstructPath(goal, cameFrom);
}
int newCost = costSoFar[current] + this->WeightMatrix->Get(current).Get(next);
if ((cameFrom.count(next) == 0) || (newCost < costSoFar[next])) {
costSoFar[next] = newCost;
frontier.Enqueue(next, newCost);
cameFrom[next] = current;
}
}
}
return NULL;
}
~MatrixGraph() {
delete this->Values;
delete this->AdjacencyMatrix;
delete this->WeightMatrix;
}
};
| [
"karrauln@yandex.ru"
] | karrauln@yandex.ru |
fd1c1f4798c817ad0fa9408eebf9b6695b423b7e | d5890e285b5d6d5789b0138f4ccd6bc478b36a00 | /foodcreator.h | 565d2da43a021cc0f74008089a43936eee5ed3ae | [] | no_license | Plizzz/Snake | 9a91f3655c9d90d0f7ccd2261fc8b7a8921289b3 | 0f47a2135b26711ec6f87d4f3a97555e7ec7f541 | refs/heads/master | 2021-01-12T12:46:09.456312 | 2016-10-14T09:53:43 | 2016-10-14T09:53:43 | 69,856,025 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 262 | h | #include "point.h"
#ifndef FOODCREATOR_H
#define FOODCREATOR_H
class Foodcreator
{
private:
int mapwight;
int mapheight;
char sym;
public:
Foodcreator(int mapwight, int mapheight, char sym);
Point CreateFood();
};
#endif // FOODCREATOR_H
| [
"pau7.1994@gmail.com"
] | pau7.1994@gmail.com |
fedce836118c8bcfb16781749aec61a70de3c543 | 26cffb726d50c3105f0ac29f74aae2cce4928bec | /Tut10 Specular lighting/lightclass.h | cdfa78edc3fcc8a120d6064ce0c2f716f151fcf6 | [] | no_license | jwkapple/DirectX11-Study | ce4388f49dbed14d2bd1500a24a15ecda66cfc24 | 88b0b61d9b02024a60e95ac669d6a30de8342cb1 | refs/heads/master | 2022-10-14T19:46:52.081137 | 2019-03-05T06:59:21 | 2019-03-05T06:59:21 | 168,720,700 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 663 | h | #pragma once
#include <DirectXMath.h>
using namespace DirectX;
class LightClass
{
public:
LightClass();
LightClass(const LightClass&);
~LightClass();
void SetSpecularPower(float);
void SetSpecularColor(float, float, float, float);
void SetAmbientColor(float, float, float, float);
void SetDiffuseColor(float, float, float, float);
void SetDirection(float, float, float);
float GetSpecularPower();
XMFLOAT4 GetSpecularColor();
XMFLOAT4 GetAmbientColor();
XMFLOAT4 GetDiffuseColor();
XMFLOAT3 GetDirection();
private:
float m_specularPower;
XMFLOAT4 m_specularColor;
XMFLOAT4 m_ambientColor;
XMFLOAT4 m_diffuseColor;
XMFLOAT3 m_direction;
}; | [
"jwkorange@gmail.com"
] | jwkorange@gmail.com |
bc6d47a9dbdf9d188a3267baad84d192ec2d85d8 | acf10cd62a1d20c84b80f8c743e0e296b60dae84 | /comprehensive_case/SavingsAccount.h | 1e04b190fdca21db969a06706cf3711103a00b5b | [] | no_license | LuckyCode1992/c-study | 6b60e87e8a2644e1b6ef255fae1f3c74a6484119 | ebb94db5685c065423f9ba5b971e3c26be360f93 | refs/heads/master | 2020-05-14T12:51:37.076569 | 2019-05-05T07:44:54 | 2019-05-05T07:44:54 | 181,800,732 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,109 | h | //
// Created by hxl on 2019/4/22.
//
#ifndef C_STUDY_SAVINGSACCOUNT_H
#define C_STUDY_SAVINGSACCOUNT_H
class SavingsAccount {
private:
int id; //账号
double balance;//余额
double rate;//存款的年利率
int lastDate;//上次变更余额的时间
double accumulation;//余额按日累加之和
//记录一笔账,date为日期,amount为金额,desc为说明
void record(int date, double amount);
//获得到指定日期为止的存款金额 按日累积值
double accumulate(int date) const {
return accumulation + balance * (date - lastDate);
}
public:
SavingsAccount(int date, int id, double rate);
int getId() {
return id;
}
double getBalance() {
return balance;
}
double getRate() {
return rate;
}
//存入现金
void deposit(int date, double amount);
//取出现金
void withdraw(int date, double amount);
//结算利息,每年1月1日调用一次函数
void settle(int date);
//显示账户信息
void show();
};
#endif //C_STUDY_SAVINGSACCOUNT_H
| [
"hxl19920401"
] | hxl19920401 |
4be989616d38a9e78fb1564c262589e45c8e35d9 | a88afe59192bd7327b870d5f1c3fd2589f480d46 | /include/musicalpatternmodel.h | c9f075e84979dbc0e044c2076b297d29e792d705 | [] | no_license | DIME-TILL-DEATH/Metronome | 6b61c96af86974acb139ffc038c00fdeb899b332 | be1003c34965915daa68c8d887064220859f40a4 | refs/heads/master | 2023-06-25T16:40:30.025966 | 2021-07-18T09:03:12 | 2021-07-18T09:03:12 | 372,821,405 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,200 | h | #ifndef MUSICALPATTERNMODEL_H
#define MUSICALPATTERNMODEL_H
#include <QAbstractListModel>
#include <QObject>
#include <QList>
#include <QHash>
#include "musicalnote.h"
#include "musicalbar.h"
#include "musicalpattern.h"
class MusicalPatternModel : public QAbstractListModel
{
Q_OBJECT
public:
MusicalPatternModel(MusicalPattern &barPattern) : m_barPattern{barPattern}{};
QHash<int, QByteArray> roleNames() const override;
int rowCount(const QModelIndex &parent) const override;
QVariant data(const QModelIndex& index = {}, int role = Qt::DisplayRole) const override;
bool setData(const QModelIndex &index, const QVariant &value, int role = BarRole) override;
bool insertRows(int row, int count, const QModelIndex &parent = QModelIndex()) override;
bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()) override;
bool addBar(const MusicalBar &newBar, quint16 barIndex);
bool removeBar(quint16 barIndex);
void updateModel();
private:
MusicalPattern& m_barPattern;
quint16 m_selectedBarIndex{0};
enum PatternRoles{
BarNumberRole= Qt::UserRole + 1,
BarRole
};
};
#endif // MUSICALPATTERNMODEL_H
| [
"uaas@list.ru"
] | uaas@list.ru |
64bcf90e5e63142f225d4ed2498c6f9d3f3dfe57 | 4b187bd1e89f6bcce100b7bd05b4ff202522bc4d | /OnlineJudgeSolutions/Codeforces/codeforces 1099D.cpp | 78be1dcf2375acda3083d5206a9057929cb07967 | [] | no_license | codefresher32/CompetitiveProgramming | e53133a906081e7931966216b55d4537730d8ba3 | 923009b9893bdb0162ef02e88ea4223dc8d85449 | refs/heads/master | 2021-04-13T06:51:04.428078 | 2020-03-24T13:40:16 | 2020-03-24T13:40:16 | 249,144,621 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 814 | cpp | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
vector<int>G[100005];
int a[100005],mn;
bool vis[100005],f;
void dfs(int s,int mx)
{
vis[s]=1;
for(int v:G[s]){
if(!vis[v]){
if(mx>a[v]&&a[v]){
f=1;
}
dfs(v,max(mx,a[v]));
}
}
mn=max(mn,a[s]);
return ;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n,m,u,v,x;
cin>>n;
for(int i=2;i<=n;i++){
cin>>u;
G[u].push_back(i);
G[i].push_back(u);
}
for(int i=1;i<=n;i++){
cin>>x;
a[i]=(x==-1)?0:x;
}
dfs(1,a[1]);
if(f){
cout<<-1<<endl;
}
else{
cout<<mn<<endl;
}
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
a6dd87e537c4cbfc0a2414a765e234f0c81e89a4 | 6c6e0c89cc895901cbd4667d500603d6160d386f | /Dialog/dis_gui_tablet.hpp | 1d4dc473b068dfc33d52695d37d48a612f1d6b6d | [] | no_license | rjy7wb/Dissension.Tanoa | 497b97264fd8768ccd70f04c49fe5585ba622ac1 | 7a41356a66058d495ead683d1c594197afe3c4ff | refs/heads/master | 2021-01-01T19:45:32.990291 | 2017-07-11T06:36:22 | 2017-07-11T06:36:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,490 | hpp | #define true 1
#define false 0
class RscDisTablet
{
idd= 27000;
movingEnable = false;
enableSimulation = true;
fadein=0;
duration = 1e+011;
fadeout=0;
onLoad= "_this select 0 displayCtrl 27300 ctrlShow false";
controlsBackground[]={};
controls[]=
{
RscTabletBack,
RscTabletTree,
RscTextInfo,
RscTabletPowerBtn,
RscPlayerInfo,
RscBtnBack,
RscPurchaseBtn,
RscTabletInfo
};
objects[]={};
class RscTabletBack : RscPicture
{
idc = 27001;
colorBackground[] = {0,0,0,1};
colorText[] = {1,1,1,1};
text = "Pictures\sTab_dissension.paa";
x = 0.125 * safezoneW + safezoneX;
y = 0.125 * safezoneH + safezoneY;
w = 0.75 * safezoneW;
h = 0.75 * safezoneH;
};
class RscBtnBack: RscText
{
idc = 27002;
colorBackground[] = {0,0,0,0.25};
colorText[] ={1,1,1,1};
text = "";
fixedWidth = 0;
x = 0.505 * safezoneW + safezoneX;
y = 0.705 * safezoneH + safezoneY;
w = 0.075 * safezoneW;
h = 0.05 * safezoneH;
style = 0;
shadow = 1;
};
class RscTabletPowerBtn: RscActiveText
{
idc = 27002;
x = 0.6425 * safezoneW + safezoneX;
y = 0.8 * safezoneH + safezoneY;
w = 0.03 * safezoneW;
h = 0.04 * safezoneH;
color[] = {1,1,1,0};
colorActive[] = {1,1,1,0};
colorDisabled[] = {1,1,1,0};
soundEnter[] = { "", 0, 1 }; // no sound
soundPush[] = { "", 0, 1 };
soundClick[] = {"\A3\ui_f\data\sound\RscButton\soundClick",0.09,1};
soundEscape[] = { "", 0, 1 };
action = "closeDialog 2";
text= "Pictures\sTab_dissension.paa";
tooltip = "Power";
default = true;
};
class RscTabletTree : RscTree
{
idc = 27100;
x = 0.205 * safezoneW + safezoneX;
y = 0.225 * safezoneH + safezoneY;
w = 0.29 * safezoneW;
h = 0.53 * safezoneH;
colorText[] = {1,1,1,1.0};
colorSelect[] = {1,1,1,0.7};
colorSelectText[] = {0,0,0,1};
colorBackground[] = {0,0,0,0.25};
colorSelectBackground[] = {0,0,0,0.5};
colorBorder[] = {0,0,0,0};
colorPicture[] = {1,1,1,1};
colorPictureSelected[] = {1,1,1,1};
colorPictureDisabled[] = {1,1,1,1};
colorPictureRight[] = {1,1,1,1};
colorPictureRightDisabled[] = {1,1,1,0.25};
colorPictureRightSelected[] = {0,0,0,1};
colorDisabled[] = {1,1,1,0.25};
borderSize = 0;
expandOnDoubleclick = 1;
maxHistoryDelay = 1;
colorArrow[] = {0,0,0,0};
colorMarked[] = {1,0.5,0,0.5};
colorMarkedText[] = {1,1,1,1};
colorMarkedSelected[] = {1,0.5,0,1};
onTreeSelChanged = "_this call dis_fnc_TreeSelChange;";
onTreeLButtonDown = "";
onTreeDblClick = "";
onTreeExpanded = "_this call dis_fnc_TreeExpanded;";
onTreeCollapsed = "";
onTreeMouseMove = "";
onTreeMouseHold = "";
onTreeMouseExit = "";
class ScrollBar: RscTreeScrollBar{};
};
class RscTextInfo: RscControlsGroup
{
idc = 27200;
x = 0.505 * safezoneW + safezoneX;
y = 0.225 * safezoneH + safezoneY;
w = 0.29 * safezoneW;
h = 0.47 * safezoneH;
class VScrollbar
{
idc = 20;
color[] = {1,1,1,0.5};
width = 0.021;
autoScrollEnabled = 0;
autoScrollSpeed = 0;
autoScrollRewind = 0;
colorActive[] = {1,1,1,1};
colorDisabled[] = {1,1,1,0.3};
thumb = "#(argb,8,8,3)color(0,0,0,1)";
arrowEmpty = "\A3\ui_f\data\GUI\RscCommon\rsccombo\arrow_combo_active_ca.paa";
arrowFull = "\A3\ui_f\data\GUI\RscCommon\rsccombo\arrow_combo_active_ca.paa";
border = "#(argb,8,8,3)color(1,1,1,1)";
};
sizeEx = 0.02;
class Controls
{
class textScrolltext: RscStructuredText
{
idc = 27201;
x = 0;
y = 0;
w = 0.28 * safezoneW;
h = 1;
text = "";
colorText[] = {1,1,1,1};
shadow = 0;
colorBackground[] = {0,0,0,0.25};
};
};
};
class RscPurchaseBtn: RscShortcutButton
{
idc = 27300;
text = "Purchase";
colorBackground[] = {0.4,0.4,0.4,1};
colorBackground2[] = {0.4,0.4,0.4,1};
colorBackgroundFocused[] = {0.4,0.4,0.4,1};
colorFocused[] = {1,1,1,1};
onButtonClick = "_this call dis_fnc_PurchaseVeh;";
x = 0.505 * safezoneW + safezoneX;
y = 0.705 * safezoneH + safezoneY;
w = 0.075 * safezoneW;
h = 0.05 * safezoneH;
size = "(((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
class TextPos
{
left = 0;
top = 0.015;
right = 0;
bottom = 0;
};
};
class RscAcceptBtn: RscShortcutButton
{
idc = 27301;
text = "Accept";
colorBackground[] = {0.4,0.4,0.4,1};
colorBackground2[] = {0.4,0.4,0.4,1};
colorBackgroundFocused[] = {0.4,0.4,0.4,1};
colorFocused[] = {1,1,1,1};
onButtonClick = "_this call dis_fnc_AcceptMission;";
x = 0.505 * safezoneW + safezoneX;
y = 0.705 * safezoneH + safezoneY;
w = 0.075 * safezoneW;
h = 0.05 * safezoneH;
size = "(((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
class TextPos
{
left = 0;
top = 0.015;
right = 0;
bottom = 0;
};
};
class RscPlayerInfo: RscStructuredText
{
idc = 27400;
colorText[] = {1,1,1,1};
class Attributes
{
font = "RobotoCondensed";
color = "#ffffff";
align = "left";
shadow = 1;
};
x = 0.58 * safezoneW + safezoneX;
y = 0.715 * safezoneH + safezoneY;
w = 0.215 * safezoneW;
h = 0.03 * safezoneH;
text = "";
size = "(((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
shadow = 1;
};
class RscTabletInfo: RscStructuredText
{
idc = 27500;
colorText[] = {0.5,0.5,0.5,0.25};
class Attributes
{
font = "RobotoCondensed";
color = "#ffffff";
align = "center";
shadow = 1;
};
x = 0.2 * safezoneW + safezoneX;
y = 0.80 * safezoneH + safezoneY;
w = 0.4 * safezoneW;
h = 0.03 * safezoneH;
text = "";
size = "(((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1.2)";
shadow = 1;
};
}; | [
"djsmith123@msn.com"
] | djsmith123@msn.com |
b9747dc9937442bda9061e2ef6889db130e73308 | 29dec11a2447cc9e8e301bbfa9db28491eb76f1e | /src/core/templarg/cmp.hxx | d74c8f5ea55a4adc991359a13acd98a9744a49fa | [] | no_license | kvr000/drt | 897a706523132b2a92273144da993a300947b555 | 28d859693046ecf96cdc70052bb4e2629833c740 | refs/heads/master | 2022-05-01T10:42:10.695069 | 2022-03-27T02:34:05 | 2022-03-27T02:34:05 | 222,618,569 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,793 | hxx | /**
* drt library
*
* drt multiplatform development toolkit
*
* ----------------------------------------------------------------------------------
*
* Copyright (C) 2004-2008 Zbyněk Vyškovský
*
* ----------------------------------------------------------------------------------
*
* LICENSE:
*
* This file is part of drt
*
* drt is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
*
* drt is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
* more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with drt; if not, write to the Free Software Foundation, Inc., 51
* Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* @copyright 2004-2008 Zbyněk Vyškovský
* @link mailto:kvr@matfyz.cz
* @link http://kvr.matfyz.cz/drt/
* @license http://www.gnu.org/licenses/lgpl.txt GNU Lesser General Public License v3
**/
#ifndef drcmp_h__
# define drcmp_h__
#include <dr/def_core.hxx>
#include <dr/Assert.hxx>
DR_NS_BEGIN
template <typename T>
DR_MINLINE int cmp(const T &t1, const T &t2)
{
return (t1 == t2)?0:(t1 < t2)?-1:1;
}
template <typename T>
class Compar
{
public:
static DR_MINLINE bool teq(const T &t1, const T &t2) { return t1 == t2; }
static DR_MINLINE int tcmp(const T &t1, const T &t2) { return cmp(t1, t2); }
static DR_MINLINE void txchg(T *t1, T *t2) { T t(*t1); *t1 = *t2; *t2 = t; }
};
template <typename T>
class ComparEq
{
public:
static DR_MINLINE bool teq(const T &t1, const T &t2) { return t1 == t2; }
static DR_MINLINE int tcmp(const T &t1, const T &t2) { DR_AssertInvalid(); return 0; }
static DR_MINLINE void txchg(T *t1, T *t2) { T t(*t1); *t1 = *t2; *t2 = t; }
};
template <typename T>
class ComparInv
{
public:
static DR_MINLINE bool teq(const T &t1, const T &t2) { DR_AssertInvalid(); return true; }
static DR_MINLINE int tcmp(const T &t1, const T &t2) { DR_AssertInvalid(); return 0; }
static DR_MINLINE void txchg(T *t1, T *t2) { T t(*t1); *t1 = *t2; *t2 = t; }
};
template <typename T> class Ref;
template <typename T>
class RCompar
{
public:
static DR_MINLINE bool teq(const Ref<T> &t1, const Ref<T> &t2) { return t1->eq(t2); }
static DR_MINLINE int tcmp(const Ref<T> &t1, const Ref<T> &t2) { return t1->cmp(t2); }
static DR_MINLINE void txchg(Ref<T> *t1, Ref<T> *t2) { t1->xchg(t2); }
static DR_MINLINE long khash(Ref<T> *t1) { return (*t1)->hash(); }
};
DR_NS_END
#endif
| [
"kvr000@gmail.com"
] | kvr000@gmail.com |
f842c67dc9d14fbec207fe4f084e8f828f9aa7b4 | 3938e2c780cd630af677d8ae0a1fd8bbd3c6fb64 | /SelectedTextTranslate/Source/Utilities/StringUtilities.h | 468f3a74a6d32550c990914efc0c005369fc6e94 | [] | no_license | killerDJO/SelectedTextTranslate | 7c4b34034115533e277e97df86eeef1c9b020943 | 17c9c3d8fdaf536e72f8d855e3de2a4a85ce4099 | refs/heads/master | 2020-04-06T06:29:04.591612 | 2017-10-28T18:13:10 | 2019-01-07T15:15:35 | 15,632,609 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 772 | h | #pragma once
class StringUtilities
{
public:
static wstring GetUtf16String(string text);
static wstring GetUtf16StringFromChar(const char* text);
static string GetUtf8String(wstring text);
static string GetUtf8StringFromChar(const wchar_t* text);
static wstring GetJsonString(nlohmann::json value);
static wchar_t* CopyWideChar(wstring text);
static wstring Format(const wstring format, ...);
static wstring Format(const wstring format, va_list args);
static vector<wstring> Split(const wstring &s, wchar_t delim);
static void ReplaceAll(wstring &str, const wstring &search, const wstring &replace);
static wstring LeftTrim(wstring str);
static wstring RightTrim(wstring str);
static wstring Trim(wstring str);
}; | [
"killerDJO@gmail.com"
] | killerDJO@gmail.com |
73361284dec8135cec76cd8842908d7dcb7c8df9 | 347fdd4d3b75c3ab0ecca61cf3671d2e6888e0d1 | /addons/vaOsc/libs/oscpack/src/OscOutboundPacketStream.cpp | b8e59fa562f0cd8cc43fb0565c1609810c1f30c9 | [] | no_license | sanyaade/VirtualAwesome | 29688648aa3f191cdd756c826b5c84f6f841b93f | 05f3db98500366be1e79da16f5e353e366aed01f | refs/heads/master | 2020-12-01T03:03:51.561884 | 2010-11-08T00:17:44 | 2010-11-08T00:17:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,362 | cpp | /*
oscpack -- Open Sound Control packet manipulation library
http://www.audiomulch.com/~rossb/oscpack
Copyright (c) 2004-2005 Ross Bencina <rossb@audiomulch.com>
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.
Any person wishing to distribute modifications to the Software is
requested to send the modifications to the original developer so that
they can be incorporated into the canonical version.
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 <oscpack/OscOutboundPacketStream.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#if defined(__WIN32__) || defined(WIN32)
#include <malloc.h> // for alloca
#endif
#include <oscpack/OscHostEndianness.h>
namespace osc{
static void FromInt32( char *p, int32 x )
{
#ifdef OSC_HOST_LITTLE_ENDIAN
union{
osc::int32 i;
char c[4];
} u;
u.i = x;
p[3] = u.c[0];
p[2] = u.c[1];
p[1] = u.c[2];
p[0] = u.c[3];
#else
*reinterpret_cast<int32*>(p) = x;
#endif
}
static void FromUInt32( char *p, uint32 x )
{
#ifdef OSC_HOST_LITTLE_ENDIAN
union{
osc::uint32 i;
char c[4];
} u;
u.i = x;
p[3] = u.c[0];
p[2] = u.c[1];
p[1] = u.c[2];
p[0] = u.c[3];
#else
*reinterpret_cast<uint32*>(p) = x;
#endif
}
static void FromInt64( char *p, int64 x )
{
#ifdef OSC_HOST_LITTLE_ENDIAN
union{
osc::int64 i;
char c[8];
} u;
u.i = x;
p[7] = u.c[0];
p[6] = u.c[1];
p[5] = u.c[2];
p[4] = u.c[3];
p[3] = u.c[4];
p[2] = u.c[5];
p[1] = u.c[6];
p[0] = u.c[7];
#else
*reinterpret_cast<int64*>(p) = x;
#endif
}
static void FromUInt64( char *p, uint64 x )
{
#ifdef OSC_HOST_LITTLE_ENDIAN
union{
osc::uint64 i;
char c[8];
} u;
u.i = x;
p[7] = u.c[0];
p[6] = u.c[1];
p[5] = u.c[2];
p[4] = u.c[3];
p[3] = u.c[4];
p[2] = u.c[5];
p[1] = u.c[6];
p[0] = u.c[7];
#else
*reinterpret_cast<uint64*>(p) = x;
#endif
}
static inline long RoundUp4( long x )
{
return ((x-1) & (~0x03L)) + 4;
}
OutboundPacketStream::OutboundPacketStream( char *buffer, unsigned long capacity )
: data_( buffer )
, end_( data_ + capacity )
, typeTagsCurrent_( end_ )
, messageCursor_( data_ )
, argumentCurrent_( data_ )
, elementSizePtr_( 0 )
, messageIsInProgress_( false )
{
}
OutboundPacketStream::~OutboundPacketStream()
{
}
char *OutboundPacketStream::BeginElement( char *beginPtr )
{
if( elementSizePtr_ == 0 ){
elementSizePtr_ = reinterpret_cast<uint32*>(data_);
return beginPtr;
}else{
// store an offset to the old element size ptr in the element size slot
// we store an offset rather than the actual pointer to be 64 bit clean.
*reinterpret_cast<uint32*>(beginPtr) =
(uint32)(reinterpret_cast<char*>(elementSizePtr_) - data_);
elementSizePtr_ = reinterpret_cast<uint32*>(beginPtr);
return beginPtr + 4;
}
}
void OutboundPacketStream::EndElement( char *endPtr )
{
assert( elementSizePtr_ != 0 );
if( elementSizePtr_ == reinterpret_cast<uint32*>(data_) ){
elementSizePtr_ = 0;
}else{
// while building an element, an offset to the containing element's
// size slot is stored in the elements size slot (or a ptr to data_
// if there is no containing element). We retrieve that here
uint32 *previousElementSizePtr =
(uint32*)(data_ + *reinterpret_cast<uint32*>(elementSizePtr_));
// then we store the element size in the slot, note that the element
// size does not include the size slot, hence the - 4 below.
uint32 elementSize =
(endPtr - reinterpret_cast<char*>(elementSizePtr_)) - 4;
FromUInt32( reinterpret_cast<char*>(elementSizePtr_), elementSize );
// finally, we reset the element size ptr to the containing element
elementSizePtr_ = previousElementSizePtr;
}
}
bool OutboundPacketStream::ElementSizeSlotRequired() const
{
return (elementSizePtr_ != 0);
}
void OutboundPacketStream::CheckForAvailableBundleSpace()
{
unsigned long required = Size() + ((ElementSizeSlotRequired())?4:0) + 16;
if( required > Capacity() )
throw OutOfBufferMemoryException();
}
void OutboundPacketStream::CheckForAvailableMessageSpace( const char *addressPattern )
{
// plus 4 for at least four bytes of type tag
unsigned long required = Size() + ((ElementSizeSlotRequired())?4:0)
+ RoundUp4(strlen(addressPattern) + 1) + 4;
if( required > Capacity() )
throw OutOfBufferMemoryException();
}
void OutboundPacketStream::CheckForAvailableArgumentSpace( long argumentLength )
{
// plus three for extra type tag, comma and null terminator
unsigned long required = (argumentCurrent_ - data_) + argumentLength
+ RoundUp4( (end_ - typeTagsCurrent_) + 3 );
if( required > Capacity() )
throw OutOfBufferMemoryException();
}
void OutboundPacketStream::Clear()
{
typeTagsCurrent_ = end_;
messageCursor_ = data_;
argumentCurrent_ = data_;
elementSizePtr_ = 0;
messageIsInProgress_ = false;
}
unsigned int OutboundPacketStream::Capacity() const
{
return end_ - data_;
}
unsigned int OutboundPacketStream::Size() const
{
unsigned int result = argumentCurrent_ - data_;
if( IsMessageInProgress() ){
// account for the length of the type tag string. the total type tag
// includes an initial comma, plus at least one terminating \0
result += RoundUp4( (end_ - typeTagsCurrent_) + 2 );
}
return result;
}
const char *OutboundPacketStream::Data() const
{
return data_;
}
bool OutboundPacketStream::IsReady() const
{
return (!IsMessageInProgress() && !IsBundleInProgress());
}
bool OutboundPacketStream::IsMessageInProgress() const
{
return messageIsInProgress_;
}
bool OutboundPacketStream::IsBundleInProgress() const
{
return (elementSizePtr_ != 0);
}
OutboundPacketStream& OutboundPacketStream::operator<<( const BundleInitiator& rhs )
{
if( IsMessageInProgress() )
throw MessageInProgressException();
CheckForAvailableBundleSpace();
messageCursor_ = BeginElement( messageCursor_ );
memcpy( messageCursor_, "#bundle\0", 8 );
FromUInt64( messageCursor_ + 8, rhs.timeTag );
messageCursor_ += 16;
argumentCurrent_ = messageCursor_;
return *this;
}
OutboundPacketStream& OutboundPacketStream::operator<<( const BundleTerminator& rhs )
{
(void) rhs;
if( !IsBundleInProgress() )
throw BundleNotInProgressException();
if( IsMessageInProgress() )
throw MessageInProgressException();
EndElement( messageCursor_ );
return *this;
}
OutboundPacketStream& OutboundPacketStream::operator<<( const BeginMessage& rhs )
{
if( IsMessageInProgress() )
throw MessageInProgressException();
CheckForAvailableMessageSpace( rhs.addressPattern );
messageCursor_ = BeginElement( messageCursor_ );
strcpy( messageCursor_, rhs.addressPattern );
unsigned long rhsLength = strlen(rhs.addressPattern);
messageCursor_ += rhsLength + 1;
// zero pad to 4-byte boundary
unsigned long i = rhsLength + 1;
while( i & 0x3 ){
*messageCursor_++ = '\0';
++i;
}
argumentCurrent_ = messageCursor_;
typeTagsCurrent_ = end_;
messageIsInProgress_ = true;
return *this;
}
OutboundPacketStream& OutboundPacketStream::operator<<( const MessageTerminator& rhs )
{
(void) rhs;
if( !IsMessageInProgress() )
throw MessageNotInProgressException();
int typeTagsCount = end_ - typeTagsCurrent_;
if( typeTagsCount ){
char *tempTypeTags = (char*)alloca(typeTagsCount);
memcpy( tempTypeTags, typeTagsCurrent_, typeTagsCount );
// slot size includes comma and null terminator
int typeTagSlotSize = RoundUp4( typeTagsCount + 2 );
uint32 argumentsSize = argumentCurrent_ - messageCursor_;
memmove( messageCursor_ + typeTagSlotSize, messageCursor_, argumentsSize );
messageCursor_[0] = ',';
// copy type tags in reverse (really forward) order
for( int i=0; i < typeTagsCount; ++i )
messageCursor_[i+1] = tempTypeTags[ (typeTagsCount-1) - i ];
char *p = messageCursor_ + 1 + typeTagsCount;
for( int i=0; i < (typeTagSlotSize - (typeTagsCount + 1)); ++i )
*p++ = '\0';
typeTagsCurrent_ = end_;
// advance messageCursor_ for next message
messageCursor_ += typeTagSlotSize + argumentsSize;
}else{
// send an empty type tags string
memcpy( messageCursor_, ",\0\0\0", 4 );
// advance messageCursor_ for next message
messageCursor_ += 4;
}
argumentCurrent_ = messageCursor_;
EndElement( messageCursor_ );
messageIsInProgress_ = false;
return *this;
}
OutboundPacketStream& OutboundPacketStream::operator<<( bool rhs )
{
CheckForAvailableArgumentSpace(0);
*(--typeTagsCurrent_) = (char)((rhs) ? TRUE_TYPE_TAG : FALSE_TYPE_TAG);
return *this;
}
OutboundPacketStream& OutboundPacketStream::operator<<( const NilType& rhs )
{
(void) rhs;
CheckForAvailableArgumentSpace(0);
*(--typeTagsCurrent_) = NIL_TYPE_TAG;
return *this;
}
OutboundPacketStream& OutboundPacketStream::operator<<( const InfinitumType& rhs )
{
(void) rhs;
CheckForAvailableArgumentSpace(0);
*(--typeTagsCurrent_) = INFINITUM_TYPE_TAG;
return *this;
}
OutboundPacketStream& OutboundPacketStream::operator<<( int32 rhs )
{
CheckForAvailableArgumentSpace(4);
*(--typeTagsCurrent_) = INT32_TYPE_TAG;
FromInt32( argumentCurrent_, rhs );
argumentCurrent_ += 4;
return *this;
}
OutboundPacketStream& OutboundPacketStream::operator<<( float rhs )
{
CheckForAvailableArgumentSpace(4);
*(--typeTagsCurrent_) = FLOAT_TYPE_TAG;
#ifdef OSC_HOST_LITTLE_ENDIAN
union{
float f;
char c[4];
} u;
u.f = rhs;
argumentCurrent_[3] = u.c[0];
argumentCurrent_[2] = u.c[1];
argumentCurrent_[1] = u.c[2];
argumentCurrent_[0] = u.c[3];
#else
*reinterpret_cast<float*>(argumentCurrent_) = rhs;
#endif
argumentCurrent_ += 4;
return *this;
}
OutboundPacketStream& OutboundPacketStream::operator<<( char rhs )
{
CheckForAvailableArgumentSpace(4);
*(--typeTagsCurrent_) = CHAR_TYPE_TAG;
FromInt32( argumentCurrent_, rhs );
argumentCurrent_ += 4;
return *this;
}
OutboundPacketStream& OutboundPacketStream::operator<<( const RgbaColor& rhs )
{
CheckForAvailableArgumentSpace(4);
*(--typeTagsCurrent_) = RGBA_COLOR_TYPE_TAG;
FromUInt32( argumentCurrent_, rhs );
argumentCurrent_ += 4;
return *this;
}
OutboundPacketStream& OutboundPacketStream::operator<<( const MidiMessage& rhs )
{
CheckForAvailableArgumentSpace(4);
*(--typeTagsCurrent_) = MIDI_MESSAGE_TYPE_TAG;
FromUInt32( argumentCurrent_, rhs );
argumentCurrent_ += 4;
return *this;
}
OutboundPacketStream& OutboundPacketStream::operator<<( int64 rhs )
{
CheckForAvailableArgumentSpace(8);
*(--typeTagsCurrent_) = INT64_TYPE_TAG;
FromInt64( argumentCurrent_, rhs );
argumentCurrent_ += 8;
return *this;
}
OutboundPacketStream& OutboundPacketStream::operator<<( const TimeTag& rhs )
{
CheckForAvailableArgumentSpace(8);
*(--typeTagsCurrent_) = TIME_TAG_TYPE_TAG;
FromUInt64( argumentCurrent_, rhs );
argumentCurrent_ += 8;
return *this;
}
OutboundPacketStream& OutboundPacketStream::operator<<( double rhs )
{
CheckForAvailableArgumentSpace(8);
*(--typeTagsCurrent_) = DOUBLE_TYPE_TAG;
#ifdef OSC_HOST_LITTLE_ENDIAN
union{
double f;
char c[8];
} u;
u.f = rhs;
argumentCurrent_[7] = u.c[0];
argumentCurrent_[6] = u.c[1];
argumentCurrent_[5] = u.c[2];
argumentCurrent_[4] = u.c[3];
argumentCurrent_[3] = u.c[4];
argumentCurrent_[2] = u.c[5];
argumentCurrent_[1] = u.c[6];
argumentCurrent_[0] = u.c[7];
#else
*reinterpret_cast<double*>(argumentCurrent_) = rhs;
#endif
argumentCurrent_ += 8;
return *this;
}
OutboundPacketStream& OutboundPacketStream::operator<<( const char *rhs )
{
CheckForAvailableArgumentSpace( RoundUp4(strlen(rhs) + 1) );
*(--typeTagsCurrent_) = STRING_TYPE_TAG;
strcpy( argumentCurrent_, rhs );
unsigned long rhsLength = strlen(rhs);
argumentCurrent_ += rhsLength + 1;
// zero pad to 4-byte boundary
unsigned long i = rhsLength + 1;
while( i & 0x3 ){
*argumentCurrent_++ = '\0';
++i;
}
return *this;
}
OutboundPacketStream& OutboundPacketStream::operator<<( const Symbol& rhs )
{
CheckForAvailableArgumentSpace( RoundUp4(strlen(rhs) + 1) );
*(--typeTagsCurrent_) = SYMBOL_TYPE_TAG;
strcpy( argumentCurrent_, rhs );
unsigned long rhsLength = strlen(rhs);
argumentCurrent_ += rhsLength + 1;
// zero pad to 4-byte boundary
unsigned long i = rhsLength + 1;
while( i & 0x3 ){
*argumentCurrent_++ = '\0';
++i;
}
return *this;
}
OutboundPacketStream& OutboundPacketStream::operator<<( const Blob& rhs )
{
CheckForAvailableArgumentSpace( 4 + RoundUp4(rhs.size) );
*(--typeTagsCurrent_) = BLOB_TYPE_TAG;
FromUInt32( argumentCurrent_, rhs.size );
argumentCurrent_ += 4;
memcpy( argumentCurrent_, rhs.data, rhs.size );
argumentCurrent_ += rhs.size;
// zero pad to 4-byte boundary
unsigned long i = rhs.size;
while( i & 0x3 ){
*argumentCurrent_++ = '\0';
++i;
}
return *this;
}
} // namespace osc
| [
"stefan@nortd.com"
] | stefan@nortd.com |
de9be65a03ccdb7b40fabb1474c2b56552221063 | 455a676e549f1fc1f889d7536c921126476acca2 | /llvm/lib/IR/BasicBlock.cpp | 9af2c664166705bcbfac02d01c9e4083454a11ee | [
"LicenseRef-scancode-other-permissive",
"NCSA",
"MIT",
"LLVM-exception",
"Apache-2.0"
] | permissive | neboat/opencilk-ppopp-23 | db342b1c1e83af424df7f5b1809c1ec1d19abf09 | 3fd08f23ef9b792f4a55e7aeebc7d44beddf3532 | refs/heads/main | 2023-04-13T22:44:17.301592 | 2023-01-06T22:16:27 | 2023-01-06T22:16:27 | 565,455,474 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,621 | cpp | //===-- BasicBlock.cpp - Implement BasicBlock related methods -------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements the BasicBlock class for the IR library.
//
//===----------------------------------------------------------------------===//
#include "llvm/IR/BasicBlock.h"
#include "SymbolTableListTraitsImpl.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/IR/CFG.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Type.h"
using namespace llvm;
#define DEBUG_TYPE "ir"
STATISTIC(NumInstrRenumberings, "Number of renumberings across all blocks");
ValueSymbolTable *BasicBlock::getValueSymbolTable() {
if (Function *F = getParent())
return F->getValueSymbolTable();
return nullptr;
}
LLVMContext &BasicBlock::getContext() const {
return getType()->getContext();
}
template <> void llvm::invalidateParentIListOrdering(BasicBlock *BB) {
BB->invalidateOrders();
}
// Explicit instantiation of SymbolTableListTraits since some of the methods
// are not in the public header file...
template class llvm::SymbolTableListTraits<Instruction>;
BasicBlock::BasicBlock(LLVMContext &C, const Twine &Name, Function *NewParent,
BasicBlock *InsertBefore)
: Value(Type::getLabelTy(C), Value::BasicBlockVal), Parent(nullptr) {
if (NewParent)
insertInto(NewParent, InsertBefore);
else
assert(!InsertBefore &&
"Cannot insert block before another block with no function!");
setName(Name);
}
void BasicBlock::insertInto(Function *NewParent, BasicBlock *InsertBefore) {
assert(NewParent && "Expected a parent");
assert(!Parent && "Already has a parent");
if (InsertBefore)
NewParent->getBasicBlockList().insert(InsertBefore->getIterator(), this);
else
NewParent->getBasicBlockList().push_back(this);
}
BasicBlock::~BasicBlock() {
validateInstrOrdering();
// If the address of the block is taken and it is being deleted (e.g. because
// it is dead), this means that there is either a dangling constant expr
// hanging off the block, or an undefined use of the block (source code
// expecting the address of a label to keep the block alive even though there
// is no indirect branch). Handle these cases by zapping the BlockAddress
// nodes. There are no other possible uses at this point.
if (hasAddressTaken()) {
assert(!use_empty() && "There should be at least one blockaddress!");
Constant *Replacement =
ConstantInt::get(llvm::Type::getInt32Ty(getContext()), 1);
while (!use_empty()) {
BlockAddress *BA = cast<BlockAddress>(user_back());
BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
BA->getType()));
BA->destroyConstant();
}
}
assert(getParent() == nullptr && "BasicBlock still linked into the program!");
dropAllReferences();
InstList.clear();
}
void BasicBlock::setParent(Function *parent) {
// Set Parent=parent, updating instruction symtab entries as appropriate.
InstList.setSymTabObject(&Parent, parent);
}
iterator_range<filter_iterator<BasicBlock::const_iterator,
std::function<bool(const Instruction &)>>>
BasicBlock::instructionsWithoutDebug(bool SkipPseudoOp) const {
std::function<bool(const Instruction &)> Fn = [=](const Instruction &I) {
return !isa<DbgInfoIntrinsic>(I) &&
!(SkipPseudoOp && isa<PseudoProbeInst>(I));
};
return make_filter_range(*this, Fn);
}
iterator_range<
filter_iterator<BasicBlock::iterator, std::function<bool(Instruction &)>>>
BasicBlock::instructionsWithoutDebug(bool SkipPseudoOp) {
std::function<bool(Instruction &)> Fn = [=](Instruction &I) {
return !isa<DbgInfoIntrinsic>(I) &&
!(SkipPseudoOp && isa<PseudoProbeInst>(I));
};
return make_filter_range(*this, Fn);
}
filter_iterator<BasicBlock::const_iterator,
std::function<bool(const Instruction &)>>::difference_type
BasicBlock::sizeWithoutDebug() const {
return std::distance(instructionsWithoutDebug().begin(),
instructionsWithoutDebug().end());
}
void BasicBlock::removeFromParent() {
getParent()->getBasicBlockList().remove(getIterator());
}
iplist<BasicBlock>::iterator BasicBlock::eraseFromParent() {
return getParent()->getBasicBlockList().erase(getIterator());
}
void BasicBlock::moveBefore(BasicBlock *MovePos) {
MovePos->getParent()->getBasicBlockList().splice(
MovePos->getIterator(), getParent()->getBasicBlockList(), getIterator());
}
void BasicBlock::moveAfter(BasicBlock *MovePos) {
MovePos->getParent()->getBasicBlockList().splice(
++MovePos->getIterator(), getParent()->getBasicBlockList(),
getIterator());
}
const Module *BasicBlock::getModule() const {
return getParent()->getParent();
}
const Instruction *BasicBlock::getTerminator() const {
if (InstList.empty() || !InstList.back().isTerminator())
return nullptr;
return &InstList.back();
}
const CallInst *BasicBlock::getTerminatingMustTailCall() const {
if (InstList.empty())
return nullptr;
const ReturnInst *RI = dyn_cast<ReturnInst>(&InstList.back());
if (!RI || RI == &InstList.front())
return nullptr;
const Instruction *Prev = RI->getPrevNode();
if (!Prev)
return nullptr;
if (Value *RV = RI->getReturnValue()) {
if (RV != Prev)
return nullptr;
// Look through the optional bitcast.
if (auto *BI = dyn_cast<BitCastInst>(Prev)) {
RV = BI->getOperand(0);
Prev = BI->getPrevNode();
if (!Prev || RV != Prev)
return nullptr;
}
}
if (auto *CI = dyn_cast<CallInst>(Prev)) {
if (CI->isMustTailCall())
return CI;
}
return nullptr;
}
const CallInst *BasicBlock::getTerminatingDeoptimizeCall() const {
if (InstList.empty())
return nullptr;
auto *RI = dyn_cast<ReturnInst>(&InstList.back());
if (!RI || RI == &InstList.front())
return nullptr;
if (auto *CI = dyn_cast_or_null<CallInst>(RI->getPrevNode()))
if (Function *F = CI->getCalledFunction())
if (F->getIntrinsicID() == Intrinsic::experimental_deoptimize)
return CI;
return nullptr;
}
const CallInst *BasicBlock::getPostdominatingDeoptimizeCall() const {
const BasicBlock* BB = this;
SmallPtrSet<const BasicBlock *, 8> Visited;
Visited.insert(BB);
while (auto *Succ = BB->getUniqueSuccessor()) {
if (!Visited.insert(Succ).second)
return nullptr;
BB = Succ;
}
return BB->getTerminatingDeoptimizeCall();
}
const Instruction* BasicBlock::getFirstNonPHI() const {
for (const Instruction &I : *this)
if (!isa<PHINode>(I))
return &I;
return nullptr;
}
const Instruction *BasicBlock::getFirstNonPHIOrDbg(bool SkipPseudoOp) const {
for (const Instruction &I : *this) {
if (isa<PHINode>(I) || isa<DbgInfoIntrinsic>(I))
continue;
if (SkipPseudoOp && isa<PseudoProbeInst>(I))
continue;
return &I;
}
return nullptr;
}
const Instruction *
BasicBlock::getFirstNonPHIOrDbgOrLifetime(bool SkipPseudoOp) const {
for (const Instruction &I : *this) {
if (isa<PHINode>(I) || isa<DbgInfoIntrinsic>(I))
continue;
if (I.isLifetimeStartOrEnd())
continue;
if (SkipPseudoOp && isa<PseudoProbeInst>(I))
continue;
return &I;
}
return nullptr;
}
const Instruction *
BasicBlock::getFirstNonPHIOrDbgOrSyncUnwind(bool SkipPseudoOp) const {
for (const Instruction &I : *this) {
if (isa<PHINode>(I) || isa<DbgInfoIntrinsic>(I))
continue;
if (SkipPseudoOp && isa<PseudoProbeInst>(I))
continue;
if (auto *CB = dyn_cast_or_null<CallBase>(&I))
if (const Function *Called = CB->getCalledFunction())
if (Intrinsic::sync_unwind == Called->getIntrinsicID())
continue;
return &I;
}
return nullptr;
}
BasicBlock::const_iterator BasicBlock::getFirstInsertionPt() const {
const Instruction *FirstNonPHI = getFirstNonPHI();
if (!FirstNonPHI)
return end();
const_iterator InsertPt = FirstNonPHI->getIterator();
if (InsertPt->isEHPad()) ++InsertPt;
return InsertPt;
}
void BasicBlock::dropAllReferences() {
for (Instruction &I : *this)
I.dropAllReferences();
}
const BasicBlock *BasicBlock::getSinglePredecessor() const {
const_pred_iterator PI = pred_begin(this), E = pred_end(this);
if (PI == E) return nullptr; // No preds.
const BasicBlock *ThePred = *PI;
++PI;
return (PI == E) ? ThePred : nullptr /*multiple preds*/;
}
const BasicBlock *BasicBlock::getUniquePredecessor() const {
const_pred_iterator PI = pred_begin(this), E = pred_end(this);
if (PI == E) return nullptr; // No preds.
const BasicBlock *PredBB = *PI;
++PI;
for (;PI != E; ++PI) {
if (*PI != PredBB)
return nullptr;
// The same predecessor appears multiple times in the predecessor list.
// This is OK.
}
return PredBB;
}
bool BasicBlock::hasNPredecessors(unsigned N) const {
return hasNItems(pred_begin(this), pred_end(this), N);
}
bool BasicBlock::hasNPredecessorsOrMore(unsigned N) const {
return hasNItemsOrMore(pred_begin(this), pred_end(this), N);
}
const BasicBlock *BasicBlock::getSingleSuccessor() const {
const_succ_iterator SI = succ_begin(this), E = succ_end(this);
if (SI == E) return nullptr; // no successors
const BasicBlock *TheSucc = *SI;
++SI;
return (SI == E) ? TheSucc : nullptr /* multiple successors */;
}
const BasicBlock *BasicBlock::getUniqueSuccessor() const {
const_succ_iterator SI = succ_begin(this), E = succ_end(this);
if (SI == E) return nullptr; // No successors
const BasicBlock *SuccBB = *SI;
++SI;
for (;SI != E; ++SI) {
if (*SI != SuccBB)
return nullptr;
// The same successor appears multiple times in the successor list.
// This is OK.
}
return SuccBB;
}
iterator_range<BasicBlock::phi_iterator> BasicBlock::phis() {
PHINode *P = empty() ? nullptr : dyn_cast<PHINode>(&*begin());
return make_range<phi_iterator>(P, nullptr);
}
void BasicBlock::removePredecessor(BasicBlock *Pred,
bool KeepOneInputPHIs) {
// Use hasNUsesOrMore to bound the cost of this assertion for complex CFGs.
assert((hasNUsesOrMore(16) || llvm::is_contained(predecessors(this), Pred)) &&
"Pred is not a predecessor!");
// Return early if there are no PHI nodes to update.
if (empty() || !isa<PHINode>(begin()))
return;
unsigned NumPreds = cast<PHINode>(front()).getNumIncomingValues();
for (PHINode &Phi : make_early_inc_range(phis())) {
Phi.removeIncomingValue(Pred, !KeepOneInputPHIs);
if (KeepOneInputPHIs)
continue;
// If we have a single predecessor, removeIncomingValue may have erased the
// PHI node itself.
if (NumPreds == 1)
continue;
// Try to replace the PHI node with a constant value.
if (Value *PhiConstant = Phi.hasConstantValue()) {
Phi.replaceAllUsesWith(PhiConstant);
Phi.eraseFromParent();
}
}
}
bool BasicBlock::canSplitPredecessors() const {
const Instruction *FirstNonPHI = getFirstNonPHI();
if (isa<LandingPadInst>(FirstNonPHI))
return true;
// This is perhaps a little conservative because constructs like
// CleanupBlockInst are pretty easy to split. However, SplitBlockPredecessors
// cannot handle such things just yet.
if (FirstNonPHI->isEHPad())
return false;
return true;
}
bool BasicBlock::isLegalToHoistInto() const {
auto *Term = getTerminator();
// No terminator means the block is under construction.
if (!Term)
return true;
// If the block has no successors, there can be no instructions to hoist.
assert(Term->getNumSuccessors() > 0);
// Instructions should not be hoisted across exception handling boundaries.
return !Term->isExceptionalTerminator();
}
bool BasicBlock::isEntryBlock() const {
const Function *F = getParent();
assert(F && "Block must have a parent function to use this API");
return this == &F->getEntryBlock();
}
BasicBlock *BasicBlock::splitBasicBlock(iterator I, const Twine &BBName,
bool Before) {
if (Before)
return splitBasicBlockBefore(I, BBName);
assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!");
assert(I != InstList.end() &&
"Trying to get me to create degenerate basic block!");
BasicBlock *New = BasicBlock::Create(getContext(), BBName, getParent(),
this->getNextNode());
// Save DebugLoc of split point before invalidating iterator.
DebugLoc Loc = I->getDebugLoc();
// Move all of the specified instructions from the original basic block into
// the new basic block.
New->getInstList().splice(New->end(), this->getInstList(), I, end());
// Add a branch instruction to the newly formed basic block.
BranchInst *BI = BranchInst::Create(New, this);
BI->setDebugLoc(Loc);
// Now we must loop through all of the successors of the New block (which
// _were_ the successors of the 'this' block), and update any PHI nodes in
// successors. If there were PHI nodes in the successors, then they need to
// know that incoming branches will be from New, not from Old (this).
//
New->replaceSuccessorsPhiUsesWith(this, New);
return New;
}
BasicBlock *BasicBlock::splitBasicBlockBefore(iterator I, const Twine &BBName) {
assert(getTerminator() &&
"Can't use splitBasicBlockBefore on degenerate BB!");
assert(I != InstList.end() &&
"Trying to get me to create degenerate basic block!");
assert((!isa<PHINode>(*I) || getSinglePredecessor()) &&
"cannot split on multi incoming phis");
BasicBlock *New = BasicBlock::Create(getContext(), BBName, getParent(), this);
// Save DebugLoc of split point before invalidating iterator.
DebugLoc Loc = I->getDebugLoc();
// Move all of the specified instructions from the original basic block into
// the new basic block.
New->getInstList().splice(New->end(), this->getInstList(), begin(), I);
// Loop through all of the predecessors of the 'this' block (which will be the
// predecessors of the New block), replace the specified successor 'this'
// block to point at the New block and update any PHI nodes in 'this' block.
// If there were PHI nodes in 'this' block, the PHI nodes are updated
// to reflect that the incoming branches will be from the New block and not
// from predecessors of the 'this' block.
for (BasicBlock *Pred : predecessors(this)) {
Instruction *TI = Pred->getTerminator();
TI->replaceSuccessorWith(this, New);
this->replacePhiUsesWith(Pred, New);
}
// Add a branch instruction from "New" to "this" Block.
BranchInst *BI = BranchInst::Create(this, New);
BI->setDebugLoc(Loc);
return New;
}
void BasicBlock::replacePhiUsesWith(BasicBlock *Old, BasicBlock *New) {
// N.B. This might not be a complete BasicBlock, so don't assume
// that it ends with a non-phi instruction.
for (Instruction &I : *this) {
PHINode *PN = dyn_cast<PHINode>(&I);
if (!PN)
break;
PN->replaceIncomingBlockWith(Old, New);
}
}
void BasicBlock::replaceSuccessorsPhiUsesWith(BasicBlock *Old,
BasicBlock *New) {
Instruction *TI = getTerminator();
if (!TI)
// Cope with being called on a BasicBlock that doesn't have a terminator
// yet. Clang's CodeGenFunction::EmitReturnBlock() likes to do this.
return;
for (BasicBlock *Succ : successors(TI))
Succ->replacePhiUsesWith(Old, New);
}
void BasicBlock::replaceSuccessorsPhiUsesWith(BasicBlock *New) {
this->replaceSuccessorsPhiUsesWith(this, New);
}
bool BasicBlock::isLandingPad() const {
return isa<LandingPadInst>(getFirstNonPHI());
}
const LandingPadInst *BasicBlock::getLandingPadInst() const {
return dyn_cast<LandingPadInst>(getFirstNonPHI());
}
Optional<uint64_t> BasicBlock::getIrrLoopHeaderWeight() const {
const Instruction *TI = getTerminator();
if (MDNode *MDIrrLoopHeader =
TI->getMetadata(LLVMContext::MD_irr_loop)) {
MDString *MDName = cast<MDString>(MDIrrLoopHeader->getOperand(0));
if (MDName->getString().equals("loop_header_weight")) {
auto *CI = mdconst::extract<ConstantInt>(MDIrrLoopHeader->getOperand(1));
return Optional<uint64_t>(CI->getValue().getZExtValue());
}
}
return Optional<uint64_t>();
}
BasicBlock::iterator llvm::skipDebugIntrinsics(BasicBlock::iterator It) {
while (isa<DbgInfoIntrinsic>(It))
++It;
return It;
}
void BasicBlock::renumberInstructions() {
unsigned Order = 0;
for (Instruction &I : *this)
I.Order = Order++;
// Set the bit to indicate that the instruction order valid and cached.
BasicBlockBits Bits = getBasicBlockBits();
Bits.InstrOrderValid = true;
setBasicBlockBits(Bits);
NumInstrRenumberings++;
}
#ifndef NDEBUG
/// In asserts builds, this checks the numbering. In non-asserts builds, it
/// is defined as a no-op inline function in BasicBlock.h.
void BasicBlock::validateInstrOrdering() const {
if (!isInstrOrderValid())
return;
const Instruction *Prev = nullptr;
for (const Instruction &I : *this) {
assert((!Prev || Prev->comesBefore(&I)) &&
"cached instruction ordering is incorrect");
Prev = &I;
}
}
#endif
| [
"neboat@mit.edu"
] | neboat@mit.edu |
226df106d3ac6f53f0b1e52d795414f8f7151df9 | 6984b40d7046fcf1f18a93cff9585176b1b692f4 | /ĐỒ ÁN TH KTLT/1712884/Project/main.cpp | d5df1403c4d2a49fdf0c31630ae74af7f79c7603 | [] | no_license | nguyennthanhhtungg/-N-TH-KTLT | 4d5f8dfb6095105370f5aaddeb92617a1194880e | 03c8c50fb44e0d2dfe900430dfd3b7ebe0d1d1da | refs/heads/master | 2020-03-14T06:28:03.293818 | 2018-05-17T16:31:17 | 2018-05-17T16:31:17 | 131,484,742 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 29,429 | cpp | #define _CRT_SECURE_NO_WARNINGS
#ifdef UNICODE
#define UNICODE
#endif
#include <iostream>
#include <conio.h>
#include <Windows.h>
#include <thread>
#include <time.h>
#include <fstream>
using namespace std;
#pragma comment(lib, "winmm.lib")
//Hằng số
#define MAX_CAR 17
#define MAX_CAR_LENGTH 20
#define MAX_SPEED 3
//Biến toàn cục
POINT** X; //Mảng chứa MAX_CAR xe
POINT Y; //Đại diện người qua đường
int cnt = 0; //Biến hỗ trợ trong quá trình tăng tốc xe di chuyển
int MOVING; //Biến xác định hướng di chuyển của người
int SPEED; //Tốc độ xe chạy (xem như level)
int HEIGH_CONSOLE = 20, WIDTH_CONSOLE = 80; //Độ rộng và độ cao của màn hình Console
bool STATE; //Trạng thái sống/chết của người qua đường
unsigned long times = 0; //Thời gian chơi Game
int Level = 0; //Đại diện cấp bậc người chơi
char Ambulance[3][8]; //Mảng chứa các ký tự ghép thành xe cứu thương
int PauseTimes; //Thời gian tạm dừng xe
int ColorCar; //Tô màu cho xe
int ColorBoard; //Tô màu cho viền bảng
int ColorPerson; //Tô màu cho nhân vật
int DANHDAUVITRIY[79] = { NULL }; //Đánh dấu vị trí người chơi đến đích
//bool KT; //Kiểm tra load Game
int Speed; //Tốc độ hờ
int LEVEL; //Level hờ
int x, y; //Vị trí người hờ
/*Cố định kích thước màn hình Console*/
void FixConsoleWindow()
{
HWND consoleWindow = GetConsoleWindow();
LONG style = GetWindowLong(consoleWindow, GWL_STYLE);
style = style & ~(WS_MAXIMIZEBOX) & ~(WS_THICKFRAME);
SetWindowLong(consoleWindow, GWL_STYLE, style);
}
/*Xử lý tọa độ trên màn hình Console*/
void GotoXY(int x, int y)
{
COORD coord;
coord.X = x;
coord.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
/*Hàm xử lý Color Game*/
void TextColor(int color)
{
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color);
}
/*Hàm xử lý vẽ đèn xanh đèn đỏ*/
void DrawLight(int color)
{
for (int i = 2; i < HEIGH_CONSOLE; i += 2)
{
GotoXY(1, i);
TextColor(color);
cout << (char)(219);
}
TextColor(15);
}
/*Hàm khởi tạo dữ liệu mặc định ban đầu*/
void ResetData()
{
MOVING = 'D'; //Ban đầu cho người di chuyển sang phải
SPEED = 1; //Tốc độ lúc đầu
Y = { 40,19 }; //Vị trí lúc đầu của người
//Tạo mảng xe chạy
if (X == NULL)
{
X = new POINT*[MAX_CAR];
for (int i = 0; i < MAX_CAR; i++)
X[i] = new POINT[MAX_CAR_LENGTH];
for (int i = 0; i < MAX_CAR; i++)
{
int temp = (rand() % (WIDTH_CONSOLE - MAX_CAR_LENGTH)) + 1;
for (int j = 0; j < MAX_CAR_LENGTH; j++)
{
X[i][j].x = temp + j;
X[i][j].y = 2 + i;
}
}
}
}
/*Vẽ hình chữ nhật bao quanh làm phạm vi*/
void DrawBoard(int x, int y, int width, int height, int ColorBoard, int curPosX = 0, int curPosY = 0)
{
if (ColorBoard != NULL)
{
TextColor(ColorBoard);
}
else
{
TextColor(15);
}
GotoXY(x, y); cout << '*';
for (int i = 1; i < width; i++)cout << '*';
cout << '*';
GotoXY(x, height + y); cout << '*';
for (int i = 1; i < width; i++)cout << '*';
cout << '*';
for (int i = y + 1; i < height + y; i++)
{
GotoXY(x, i); cout << '*';
GotoXY(x + width, i); cout << '*';
}
GotoXY(curPosX, curPosY);
TextColor(15);
}
/*Vẽ xe cứu thương*/
void DrawAmbulance()
{
Ambulance[0][0] = (char)(218);
Ambulance[0][1] = (char)(196);
Ambulance[0][2] = (char)(196);
Ambulance[0][3] = (char)(196);
Ambulance[0][4] = (char)(196);
Ambulance[0][5] = (char)(191);
Ambulance[1][0] = (char)(179);
Ambulance[1][2] = (char)(43);
Ambulance[1][4] = (char)(179);
Ambulance[1][6] = (char)(92);
Ambulance[1][7] = (char)(95);
Ambulance[2][0] = (char)(192);
Ambulance[2][1] = (char)(233);
Ambulance[2][2] = (char)(196);
Ambulance[2][3] = (char)(196);
Ambulance[2][4] = (char)(193);
Ambulance[2][5] = (char)(196);
Ambulance[2][6] = (char)(233);
Ambulance[2][7] = (char)(217);
}
/*Xây dựng hàm StartGame*/
void StartGame()
{
system("cls");
ResetData(); //Khởi tạo dữ liệu gốc
DrawBoard(0, 0, WIDTH_CONSOLE, HEIGH_CONSOLE, ColorBoard); //Vẽ màn hình game
STATE = true; //Bắt đầu cho Thread chạy
GotoXY(90, 1);
printf_s("%d", Level);
}
/*Hàm ExitGame() và PauseGame()*/
void GabageCollect() //Hàm dọn dẹp tài nguyên
{
for (int i = 0; i < MAX_CAR; i++)
{
delete[] X[i];
}
delete[] X;
}
void ExitGame(HANDLE t) //Hàm thoát Game
{
system("cls");
TerminateThread(t, 0);
GabageCollect();
}
void PauseGame(HANDLE t)
{
SuspendThread(t);
}
/*Hàm xử lý khi người đụng xe*/
void ProcessDead()
{
STATE = 0;
GotoXY(0, HEIGH_CONSOLE + 2);
printf_s("Dead, type y to continue or anykey to exit");
}
/*Hàm xử lý khi người băng qua đường thành công*/
void ProcessFinish(POINT &p)
{
SPEED == MAX_SPEED ? SPEED = 1 : SPEED++;
p = { 40,19 }; //Vị trí lúc ban đầu của người
MOVING = 'D'; //Ban đầu cho người di chuyển sang phải
}
/*Xử lý va chạm khi Y đã va chạm với các Y đã về trước đó*/
void XuLyVaChamY_Y(POINT Y, int *VT)
{
if ((Y.y) == 1)
{
if (*(VT + Y.x) == 1)
{
int i = 0;
while (i < WIDTH_CONSOLE + 1)
{
if (*(VT + i) == 1)
{
*(VT + i) = { NULL };
}
i++;
}
Level = 0;
ProcessDead();
}
else
{
*(VT + Y.x) = 1;
Level++;
GotoXY(90, 1);
printf_s("%d", Level);
}
}
}
/*Hàm thêm chữ BACK*/
void DrawLetterBack()
{
char GIAODIEN[2][4] = { NULL };
GIAODIEN[0][0] = char(47);
GIAODIEN[0][1] = char(205);
GIAODIEN[0][2] = char(205);
GIAODIEN[0][3] = char(205);
GIAODIEN[1][0] = char(92);
GIAODIEN[1][1] = char(205);
GIAODIEN[1][2] = char(205);
GIAODIEN[1][3] = char(205);
for (int i = 0; i < 2; i++)
{
GotoXY(0, i + 27);
for (int j = 0; j < 4; j++)
{
cout << GIAODIEN[i][j];
}
cout << endl;
}
}
/*Hàm thêm ký tự nhập từ bàn phím*/
void KeyPress()
{
GotoXY(86, 26);
printf_s("Developer: Nguyen Thanh Tung");
GotoXY(86, 27);
printf_s("MSSV: 1712884");
GotoXY(86, 28);
printf_s("Class: 17CTT7");
GotoXY(82, 1);
printf_s("Level: ");
GotoXY(95, 1);
printf_s("SPEED: ");
GotoXY(103, 1);
printf_s("%d", SPEED);
GotoXY(82, 3);
printf_s("Times: ");
GotoXY(82, 5);
printf_s("PRESS L TO SAVE GAME");
GotoXY(82, 7);
printf_s("PRESS T TO LOAD GAME");
GotoXY(82, 9);
printf_s("PRESS P TO PAUSE GAME");
GotoXY(82, 11);
printf_s("PRESS ESC TO EXIT GAME");
GotoXY(82, 13);
printf_s("PRESS:");
GotoXY(97, 14);
printf_s("W (GO UP)");
GotoXY(97, 15);
printf_s("%c",124);
GotoXY(82, 16);
printf_s(" A %c %c %c D", 196, 254, 196);
GotoXY(82, 17);
printf_s("(GO LEFT) %c (GO RIGHT)",124);
GotoXY(97, 18);
printf_s("S (GO DOWN)");
GotoXY(1, 26);
printf_s("SETTING (PRESS R)");
DrawLetterBack();
}
/*Hàm vẽ các toa xe*/
void DrawCars(const char* s,int ColorCar)
{
if (ColorCar != NULL)
{
TextColor(ColorCar);
}
else
{
TextColor(15);
}
for (int i = 0; i < MAX_CAR; i++)
{
for (int j = 0; j < MAX_CAR_LENGTH; j++)
{
GotoXY(X[i][j].x, X[i][j].y);
printf_s(s);
}
}
TextColor(15);
}
/*Hàm vẽ người qua đường*/
void DrawSticker(const POINT& p, const char* s, int ColorPerson)
{
if (ColorPerson != NULL)
{
TextColor(ColorPerson);
}
else
{
TextColor(15);
}
GotoXY(p.x, p.y);
printf_s(s);
TextColor(15);
}
/*Hàm kiểm tra xem người qua đường có đụng xe không*/
bool IsImpact(const POINT& p, int d)
{
if (d == 1 || d == 19) return false;
for (int i = 0; i < MAX_CAR_LENGTH; i++)
{
if (p.x == X[d - 2][i].x && p.y == X[d - 2][i].y) return true;
}
return false;
}
/*Hàm xử lý di chuyển của xe*/
void MoveCars(int& PauseTimes)
{
for (int i = 1; i < MAX_CAR; i += 2)
{
cnt = 0;
do
{
cnt++;
for (int j = 0; j < MAX_CAR_LENGTH - 1; j++)
{
X[i][j] = X[i][j + 1];
}
X[i][MAX_CAR_LENGTH - 1].x + 1 == WIDTH_CONSOLE ? X[i][MAX_CAR_LENGTH - 1].x = 1 : X[i][MAX_CAR_LENGTH - 1].x++; //Kiểm tra xem xe có đụng màn hình không
} while (cnt < SPEED);
}
PauseTimes++;
if (PauseTimes >= 1 && PauseTimes <= 30)
{
DrawLight(10);
for (int i = 0; i < MAX_CAR; i += 2)
{
cnt = 0;
do
{
cnt++;
for (int j = MAX_CAR_LENGTH - 1; j > 0; j--)
{
X[i][j] = X[i][j - 1];
}
X[i][0].x - 2 == 0 ? X[i][0].x = WIDTH_CONSOLE - 1 : X[i][0].x--; //Kiểm tra xem xe có đụng màn hình không
} while (cnt < SPEED);
}
}
else
{
DrawLight(4);
}
if (PauseTimes == 50)
{
PauseTimes = 0;
}
}
/*Hàm xử lý di chuyển của xe cứu thương*/
void MoveAmbulance(POINT p, int x, int y)
{
for (int k = 1; k < WIDTH_CONSOLE - 8; k++)
{
GotoXY(k, p.y - 1);
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 8; j++)
{
cout << Ambulance[i][j];
}
GotoXY(k, p.y + i);
}
Sleep(120);
if (k == x - 8)
{
GotoXY(k, p.y - 2);
TextColor(5);
printf_s("Help me.!!");
TextColor(15);
Sleep(1000);
GotoXY(k, p.y - 2);
printf_s(" ");
}
GotoXY(k, p.y - 1);
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 8; j++)
{
cout << " ";
}
GotoXY(k, p.y + +i);
}
}
}
/*Hàm xóa xe (xóa có nghĩa là không vẽ)*/
void EraseCars()
{
for (int i = 0; i < MAX_CAR; i += 2)
{
cnt = 0;
do
{
GotoXY(X[i][MAX_CAR_LENGTH - 1 - cnt].x, X[i][MAX_CAR_LENGTH - 1 - cnt].y);
printf_s(" ");
cnt++;
} while (cnt < SPEED);
}
for (int i = 1; i < MAX_CAR; i += 2)
{
cnt = 0;
do
{
GotoXY(X[i][0 + cnt].x, X[i][0 + cnt].y);
printf_s(" ");
cnt++;
} while (cnt < SPEED);
}
}
/*Hàm xử lý di chuyển Y*/
void MoveRight() //Di chuyển qua phải
{
if (Y.x < WIDTH_CONSOLE - 1)
{
DrawSticker(Y, " ", ColorPerson);
Y.x++;
DrawSticker(Y, "Y", ColorPerson);
}
}
void MoveLeft() //Di chuyển qua trái
{
if (Y.x > 1)
{
DrawSticker(Y, " ", ColorPerson);
Y.x--;
DrawSticker(Y, "Y", ColorPerson);
}
}
void MoveDown() //Di chuyển xuống
{
if (Y.y < HEIGH_CONSOLE - 1)
{
DrawSticker(Y, " ", ColorPerson);
Y.y++;
DrawSticker(Y, "Y", ColorPerson);
}
}
void MoveUp() //Di chuyển lên
{
if (Y.y > 1)
{
DrawSticker(Y, " ", ColorPerson);
Y.y--;
DrawSticker(Y, "Y", ColorPerson);
}
}
/*Hàm xử lý về thời gian chơi Game*/
void SaveTimes()
{
while (1)
{
GotoXY(90, 3);
times++;
printf_s("%d", times);
Sleep(1000);
GotoXY(90, 3);
printf_s(" ");
}
}
/*Hàm tạo hiệu ứng khi va chạm*/
void HieuUng(POINT p)
{
system("cls");
DrawBoard(0, 0, WIDTH_CONSOLE, HEIGH_CONSOLE, ColorBoard);
KeyPress();
GotoXY(p.x, p.y);
cout << "X";
GotoXY(35, 10);
TextColor(10);
printf("You die");
TextColor(15);
//const wchar_t Sound[14] = L"ambulance.wav";
STATE = 0;
PlaySound("ambulance1.wav", NULL, SND_FILENAME);
PlaySound("ambulance2.wav", NULL, SND_ASYNC);
MoveAmbulance(Y, p.x, p.y);
}
/*Hàm xử lý tiểu trình khi băng qua đường*/
void SubThread()
{
GotoXY(90, 1);
printf_s("%d", Level);
//int DANHDAUVITRIY[81] = { NULL };
int PauseTimes = 0;
while (1)
{
PlaySound("Off Limits.wav", NULL, SND_ASYNC);
if (STATE == true)
{
switch (MOVING)
{
case 'A':
MoveLeft();
break;
case 'D':
MoveRight();
break;
case 'W':
MoveUp();
break;
case 'S':
MoveDown();
break;
}
MOVING = ' '; //Tạm khóa không cho di chuyển, chờ nhận phím từ hàm main
EraseCars();
MoveCars(PauseTimes);
DrawCars(".",ColorCar);
//DrawBoard(0, 0, WIDTH_CONSOLE, HEIGH_CONSOLE);
KeyPress();
if (IsImpact(Y, Y.y))
{
PlaySound("smb_mariodie.wav", NULL, SND_FILENAME);
int i = 0;
while (i < WIDTH_CONSOLE)
{
if (*(DANHDAUVITRIY + i) == 1)
{
*(DANHDAUVITRIY + i) = { NULL };
}
i++;
}
Level = 0;
HieuUng(Y);
ProcessDead(); //Kiểm tra xe có đụng không
}
XuLyVaChamY_Y(Y, DANHDAUVITRIY);
if (Y.y == 1)
{
//PauseGame(t1.native_handle());
//PauseGame(t2.native_handle());
if (STATE == true)
{
PlaySound("smb_1-up.wav", NULL, SND_FILENAME);
GotoXY(35, 10);
TextColor(10);
printf("Level up");
TextColor(15);
Sleep(1500);
GotoXY(35, 10);
printf(" ");
}
else
{
PlaySound("smb_1-up.wav", NULL, SND_FILENAME);
GotoXY(35, 10);
TextColor(10);
printf("Collide");
TextColor(10);
Sleep(1500);
}
ProcessFinish(Y); //Kiểm tra xem về đích chưa
}
Sleep(150); //Hàm ngủ theo tốc độ SPEED
}
}
}
/*Làm ẩn con trỏ chuột trên màn hình Console*/
void Nocursortype()
{
CONSOLE_CURSOR_INFO Info;
Info.bVisible = FALSE;
Info.dwSize = 20;
SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &Info);
}
/*Lưu thông tin Game khi đang chơi*/
void SaveInformation(fstream &fs)
{
fs.seekg(0);
for (int i = 0; i < 79; i++)
{
fs << *(DANHDAUVITRIY + i) << " ";
}
fs << endl;
fs << Y.x << endl;
fs << Y.y << endl;
fs << Level << endl;
fs << SPEED << endl;
fs << times << endl;
}
/*Hàm xử lý Lưu game*/
void SaveGame(fstream& fs, char *FileName)
{
GotoXY(82, 20);
cout << "----------SAVE GAME----------";
GotoXY(85, 21);
cout << "File location:";
cin >> FileName;
strcat(FileName, ".txt");
fs.open(FileName, ios::out);
if (fs.fail())
{
cout << "Khong the mo tap tin" << endl;
_getch();
return;
}
fs << Level << endl;
fs << SPEED << endl;
fs << times << endl;
}
/*Hàm xử lý lấy thông tin Game đã lưu*/
void GetInformation(fstream& fs, char *FileName)
{
int Information;
GotoXY(82, 20);
printf_s("----------LOAD GAME----------");
GotoXY(82, 21);
printf_s("File location: ");
cin >> FileName;
strcat(FileName, ".txt");
fs.open(FileName, ios::in);
if (fs.fail())
{
GotoXY(82, 21);
cout << "Khong the tim thay tap tin";
_getch();
return;
}
fs.seekg(0);
for (int i = 0; i < 79; i++)
{
fs >> Information;
*(DANHDAUVITRIY + i) = Information;
}
fs >> Information;
Y.x = Information;
fs >> Information;
Y.y = Information;
fs >> Information;
Level = Information;
fs >> Information;
SPEED = Information;
fs >> Information;
times = Information;
}
/*Hàm vẽ chữ Game*/
void DrawLetterGame()
{
char GIAODIEN[5][50] = { NULL };
//G
GIAODIEN[0][0] = char(201);
GIAODIEN[0][1] = char(205);
GIAODIEN[0][2] = char(205);
GIAODIEN[0][3] = char(205);
GIAODIEN[0][4] = char(184);
GIAODIEN[1][0] = char(186);
GIAODIEN[2][0] = char(186);
GIAODIEN[2][3] = char(201);
GIAODIEN[2][4] = char(203);
GIAODIEN[3][0] = char(186);
GIAODIEN[3][4] = char(186);
GIAODIEN[4][0] = char(200);
GIAODIEN[4][1] = char(205);
GIAODIEN[4][2] = char(205);
GIAODIEN[4][3] = char(205);
GIAODIEN[4][4] = char(202);
//a
GIAODIEN[2][6] = char(205);
GIAODIEN[2][7] = char(205);
GIAODIEN[2][8] = char(205);
GIAODIEN[2][9] = char(183);
GIAODIEN[3][6] = char(201);
GIAODIEN[3][7] = char(205);
GIAODIEN[3][8] = char(205);
GIAODIEN[3][9] = char(186);
GIAODIEN[4][6] = char(200);
GIAODIEN[4][7] = char(205);
GIAODIEN[4][8] = char(205);
GIAODIEN[4][9] = char(202);
//m
GIAODIEN[2][11] = char(201);
GIAODIEN[2][12] = char(205);
GIAODIEN[2][13] = char(209);
GIAODIEN[2][14] = char(205);
GIAODIEN[2][15] = char(187);
GIAODIEN[3][11] = char(186);
GIAODIEN[3][13] = char(186);
GIAODIEN[3][15] = char(186);
GIAODIEN[4][11] = char(208);
GIAODIEN[4][13] = char(208);
GIAODIEN[4][15] = char(208);
//e
GIAODIEN[2][17] = char(201);
GIAODIEN[2][18] = char(205);
GIAODIEN[2][19] = char(205);
GIAODIEN[2][20] = char(187);
GIAODIEN[3][17] = char(204);
GIAODIEN[3][18] = char(205);
GIAODIEN[3][19] = char(205);
GIAODIEN[3][20] = char(188);
GIAODIEN[4][17] = char(200);
GIAODIEN[4][18] = char(205);
GIAODIEN[4][19] = char(205);
GIAODIEN[4][20] = char(190);
TextColor(4);
for (int i = 0; i < 5; i++)
{
GotoXY(65, i + 2);
for (int j = 0; j < 30; j++)
{
cout << GIAODIEN[i][j];
}
cout << endl;
}
}
/*Hàm vẽ chữ STREET*/
void DrawLetterStreet()
{
char GIAODIEN[5][40] = { NULL };
//S
GIAODIEN[0][0] = char(201);
GIAODIEN[0][1] = char(205);
GIAODIEN[0][2] = char(205);
GIAODIEN[0][3] = char(205);
GIAODIEN[0][4] = char(184);
GIAODIEN[1][0] = char(186);
GIAODIEN[2][0] = char(200);
GIAODIEN[2][1] = char(205);
GIAODIEN[2][2] = char(205);
GIAODIEN[2][3] = char(205);
GIAODIEN[2][4] = char(187);
GIAODIEN[3][4] = char(186);
GIAODIEN[4][0] = char(200);
GIAODIEN[4][1] = char(205);
GIAODIEN[4][2] = char(205);
GIAODIEN[4][3] = char(205);
GIAODIEN[4][4] = char(188);
//T
GIAODIEN[0][6] = char(201);
GIAODIEN[0][7] = char(205);
GIAODIEN[0][8] = char(205);
GIAODIEN[0][9] = char(203);
GIAODIEN[0][10] = char(205);
GIAODIEN[0][11] = char(205);
GIAODIEN[0][12] = char(187);
GIAODIEN[1][9] = char(186);
GIAODIEN[2][9] = char(186);
GIAODIEN[3][9] = char(186);
GIAODIEN[4][9] = char(208);
//R
GIAODIEN[0][14] = char(201);
GIAODIEN[0][15] = char(205);
GIAODIEN[0][16] = char(205);
GIAODIEN[0][17] = char(205);
GIAODIEN[0][18] = char(187);
GIAODIEN[1][14] = char(186);
GIAODIEN[1][18] = char(186);
GIAODIEN[2][14] = char(204);
GIAODIEN[2][15] = char(209);
GIAODIEN[2][16] = char(205);
GIAODIEN[2][17] = char(205);
GIAODIEN[2][18] = char(188);
GIAODIEN[3][14] = char(186);
GIAODIEN[3][16] = char(92);
GIAODIEN[3][17] = char(92);
GIAODIEN[4][14] = char(211);
GIAODIEN[4][17] = char(92);
GIAODIEN[4][18] = char(92);
//E
GIAODIEN[0][20] = char(201);
GIAODIEN[0][21] = char(205);
GIAODIEN[0][22] = char(205);
GIAODIEN[0][23] = char(205);
GIAODIEN[1][20] = char(186);
GIAODIEN[2][20] = char(204);
GIAODIEN[2][21] = char(205);
GIAODIEN[2][22] = char(205);
GIAODIEN[2][23] = char(205);
GIAODIEN[3][20] = char(186);
GIAODIEN[4][20] = char(200);
GIAODIEN[4][21] = char(205);
GIAODIEN[4][22] = char(205);
GIAODIEN[4][23] = char(205);
//E
GIAODIEN[0][25] = char(201);
GIAODIEN[0][26] = char(205);
GIAODIEN[0][27] = char(205);
GIAODIEN[0][28] = char(205);
GIAODIEN[1][25] = char(186);
GIAODIEN[2][25] = char(204);
GIAODIEN[2][26] = char(205);
GIAODIEN[2][27] = char(205);
GIAODIEN[2][28] = char(205);
GIAODIEN[3][25] = char(186);
GIAODIEN[4][25] = char(200);
GIAODIEN[4][26] = char(205);
GIAODIEN[4][27] = char(205);
GIAODIEN[4][28] = char(205);
//T
GIAODIEN[0][30] = char(201);
GIAODIEN[0][31] = char(205);
GIAODIEN[0][32] = char(205);
GIAODIEN[0][33] = char(203);
GIAODIEN[0][34] = char(205);
GIAODIEN[0][35] = char(205);
GIAODIEN[0][36] = char(187);
GIAODIEN[1][33] = char(186);
GIAODIEN[2][33] = char(186);
GIAODIEN[3][33] = char(186);
GIAODIEN[4][33] = char(208);
TextColor(10);
for (int i = 0; i < 5; i++)
{
GotoXY(55, i + 8);
for (int j = 0; j < 40; j++)
{
cout << GIAODIEN[i][j];
}
cout << endl;
}
}
/*Hàm vẽ chữ CROSSING*/
void DrawLetterCrosing()
{
char GIAODIEN[5][48] = { NULL };
//C
GIAODIEN[0][0] = char(201);
GIAODIEN[0][1] = char(205);
GIAODIEN[0][2] = char(205);
GIAODIEN[0][3] = char(205);
GIAODIEN[0][4] = char(205);
GIAODIEN[0][4] = char(187);
GIAODIEN[1][0] = char(186);
GIAODIEN[2][0] = char(186);
GIAODIEN[3][0] = char(186);
GIAODIEN[4][0] = char(200);
GIAODIEN[4][1] = char(205);
GIAODIEN[4][2] = char(205);
GIAODIEN[4][3] = char(205);
GIAODIEN[4][4] = char(188);
//R
GIAODIEN[0][6] = char(201);
GIAODIEN[0][7] = char(205);
GIAODIEN[0][8] = char(205);
GIAODIEN[0][9] = char(205);
GIAODIEN[0][10] = char(187);
GIAODIEN[1][6] = char(186);
GIAODIEN[1][10] = char(186);
GIAODIEN[2][6] = char(204);
GIAODIEN[2][7] = char(209);
GIAODIEN[2][8] = char(205);
GIAODIEN[2][9] = char(205);
GIAODIEN[2][10] = char(188);
GIAODIEN[3][6] = char(186);
GIAODIEN[3][8] = char(92);
GIAODIEN[3][9] = char(92);
GIAODIEN[4][6] = char(211);
GIAODIEN[4][9] = char(92);
GIAODIEN[4][10] = char(92);
//O
GIAODIEN[0][12] = char(201);
GIAODIEN[0][13] = char(205);
GIAODIEN[0][14] = char(205);
GIAODIEN[0][15] = char(205);
GIAODIEN[0][16] = char(205);
GIAODIEN[0][16] = char(187);
GIAODIEN[1][12] = char(186);
GIAODIEN[2][12] = char(186);
GIAODIEN[3][12] = char(186);
GIAODIEN[4][12] = char(200);
GIAODIEN[4][13] = char(205);
GIAODIEN[4][14] = char(205);
GIAODIEN[4][15] = char(205);
GIAODIEN[4][16] = char(188);
GIAODIEN[1][16] = char(186);
GIAODIEN[2][16] = char(186);
GIAODIEN[3][16] = char(186);
//S
GIAODIEN[0][18] = char(201);
GIAODIEN[0][19] = char(205);
GIAODIEN[0][20] = char(205);
GIAODIEN[0][21] = char(205);
GIAODIEN[0][22] = char(184);
GIAODIEN[1][18] = char(186);
GIAODIEN[2][18] = char(200);
GIAODIEN[2][19] = char(205);
GIAODIEN[2][20] = char(205);
GIAODIEN[2][21] = char(205);
GIAODIEN[2][22] = char(187);
GIAODIEN[3][22] = char(186);
GIAODIEN[4][18] = char(200);
GIAODIEN[4][19] = char(205);
GIAODIEN[4][20] = char(205);
GIAODIEN[4][21] = char(205);
GIAODIEN[4][22] = char(188);
//S
GIAODIEN[0][24] = char(201);
GIAODIEN[0][25] = char(205);
GIAODIEN[0][26] = char(205);
GIAODIEN[0][27] = char(205);
GIAODIEN[0][28] = char(184);
GIAODIEN[1][24] = char(186);
GIAODIEN[2][24] = char(200);
GIAODIEN[2][25] = char(205);
GIAODIEN[2][26] = char(205);
GIAODIEN[2][27] = char(205);
GIAODIEN[2][28] = char(187);
GIAODIEN[3][28] = char(186);
GIAODIEN[4][24] = char(200);
GIAODIEN[4][25] = char(205);
GIAODIEN[4][26] = char(205);
GIAODIEN[4][27] = char(205);
GIAODIEN[4][28] = char(188);
//I
GIAODIEN[0][30] = char(210);
GIAODIEN[1][30] = char(186);
GIAODIEN[2][30] = char(186);
GIAODIEN[3][30] = char(186);
GIAODIEN[4][30] = char(208);
//N
GIAODIEN[0][32] = char(210);
GIAODIEN[1][32] = char(186);
GIAODIEN[2][32] = char(186);
GIAODIEN[3][32] = char(186);
GIAODIEN[4][32] = char(208);
GIAODIEN[0][33] = char(92);
GIAODIEN[1][33] = char(92);
GIAODIEN[1][34] = char(92);
GIAODIEN[2][34] = char(92);
GIAODIEN[2][35] = char(92);
GIAODIEN[3][35] = char(92);
GIAODIEN[3][36] = char(92);
GIAODIEN[4][36] = char(92);
GIAODIEN[0][37] = char(210);
GIAODIEN[1][37] = char(186);
GIAODIEN[2][37] = char(186);
GIAODIEN[3][37] = char(186);
GIAODIEN[4][37] = char(208);
//G
GIAODIEN[0][39] = char(201);
GIAODIEN[0][40] = char(205);
GIAODIEN[0][41] = char(205);
GIAODIEN[0][42] = char(205);
GIAODIEN[0][43] = char(184);
GIAODIEN[1][39] = char(186);
GIAODIEN[2][39] = char(186);
GIAODIEN[2][42] = char(201);
GIAODIEN[2][43] = char(203);
GIAODIEN[3][39] = char(186);
GIAODIEN[3][43] = char(186);
GIAODIEN[4][39] = char(200);
GIAODIEN[4][40] = char(205);
GIAODIEN[4][41] = char(205);
GIAODIEN[4][42] = char(205);
GIAODIEN[4][43] = char(202);
TextColor(13);
for (int i = 0; i < 5; i++)
{
GotoXY(70, i + 14);
for (int j = 0; j < 48; j++)
{
cout << GIAODIEN[i][j];
}
cout << endl;
}
}
/*Hàm vẽ viền Giao diện*/
void DrawHem()
{
TextColor(4);
for (int i = 0; i < 120; i++)
{
cout << char(177);
}
for (int i = 0; i < 30; i++)
{
GotoXY(0, i);
cout << char(177);
cout << char(177);
GotoXY(118, i);
cout << char(177);
cout << char(177);
}
for (int i = 1; i < 119; i++)
{
GotoXY(i, 29);
cout << char(177);
}
}
/*Hàm xử lý MENU*/
void DrawChoose()
{
TextColor(4);
for (int i = 7; i < 15; i++)
{
GotoXY(13, i);
cout << char(178);
GotoXY(29, i);
cout << char(178);
}
GotoXY(16, 6);
cout << "_-_-MENU-_-_";
GotoXY(15, 7);
cout << "<1>_NEW GAME";
GotoXY(15, 9);
cout << "<2>_LOAD GAME";
GotoXY(15, 11);
cout << "<3>_SETTINGS";
GotoXY(15, 13);
cout << "<4>_EXIT GAME";
TextColor(15);
}
/*Hàm thêm nhạc nền*/
void BackgroundMusic()
{
PlaySound("Off Limits.wav", NULL, SND_ASYNC);
}
/*Hàm xử lý thông tin sinh viên*/
void DrawInformationStudent(int &Choose)
{
TextColor(1);
GotoXY(74, 24);
cout << "FULL NAME: NGUYEN THANH TUNG";
GotoXY(74, 25);
cout << "MSSV: 1712884";
GotoXY(74, 26);
cout << "17CTT7 UNIVERSITY OF SCIENCE";
GotoXY(74, 27);
cout << "LECTURER: TRUONG TOAN THINH";
BackgroundMusic();
cin >> Choose;
if (Choose == 1)
{
GotoXY(15, 7);
TextColor(10);
printf("<1>_NEW GAME");
TextColor(15);
}
else if (Choose == 2)
{
GotoXY(15, 9);
TextColor(10);
printf("<2>_LOAD GAME");
TextColor(15);
}
else if (Choose == 3)
{
GotoXY(15, 11);
TextColor(10);
cout << "<3>_SETTINGS";
TextColor(15);
}
else if (Choose == 4)
{
GotoXY(15, 13);
TextColor(10);
cout << "<4>_EXIT GAME";
TextColor(15);
}
Sleep(500);
if (Choose != NULL)
{
PlaySound(NULL, NULL, SND_PURGE);
}
}
/*Hàm lựa chọn Setting*/
void DrawSetting()
{
for (int i = 0; i < 256; i++)
{
TextColor(i);
printf(" Press: %d ", i);
TextColor(15);
printf(": %d", i);
}
TextColor(15);
printf_s("\n");
printf_s("Color Car: \n");
printf_s("Color Board: \n");
printf_s("Color Person: \n");
TextColor(15);
}
/*Hàm lựa chọn khi Press R*/
void PressSetting()
{
GotoXY(2, 4);
for (int i = 0; i < 62; i++)
{
TextColor(i);
cout << char(219);
}
TextColor(10);
GotoXY(4, 6);
printf_s("Color Car: \n");
GotoXY(4, 7);
printf_s("Color Board: \n");
GotoXY(4, 8);
printf_s("Color Person: \n");
TextColor(15);
}
/*Hàm vẽ nút Return*/
void DrawLetterReturn()
{
char GIAODIEN[2][4] = { NULL };
GIAODIEN[0][0] = char(205);
GIAODIEN[0][1] = char(205);
GIAODIEN[0][2] = char(205);
GIAODIEN[0][3] = char(92);
GIAODIEN[1][0] = char(205);
GIAODIEN[1][1] = char(205);
GIAODIEN[1][2] = char(205);
GIAODIEN[1][3] = char(47);
for (int i = 0; i < 2; i++)
{
GotoXY(113, i + 27);
for (int j = 0; j < 4; j++)
{
cout << GIAODIEN[i][j];
}
}
GotoXY(100, 26);
printf("RETURN (PRESS R)");
}
/*Hàm in vị trí người chơi đã đến đích*/
void DrawPlayer()
{
GotoXY(1, 1);
TextColor(ColorPerson);
for (int i = 0; i < WIDTH_CONSOLE - 1; i++)
{
if (*(DANHDAUVITRIY + i + 1) == 1)
{
GotoXY(i + 1, 1);
printf("Y");
}
else
{
continue;
}
}
TextColor(15);
}
void main()
{
int Choose;
int KT = 0;
fstream fs;
int temp;
char FileName[31];
DrawAmbulance();
FixConsoleWindow();
Nocursortype();
DrawHem();
DrawLetterGame();
DrawLetterStreet();
DrawLetterCrosing();
DrawChoose();
DrawInformationStudent(Choose);
while (1)
{
if (Choose == 1)
{
srand(time(NULL));
StartGame();
thread t1(SaveTimes);
thread t2(SubThread);
if (KT == 1)
{
SPEED = Speed;
Level = LEVEL;
Y.x = x;
Y.y = y;
DrawPlayer();
KT = 0;
}
while (1)
{
temp = toupper(_getch());
if (STATE == 1)
{
if (temp == 27)
{
ExitGame(t1.native_handle());
ExitGame(t2.native_handle());
return;
}
else if (temp == 'P')
{
PlaySound("smb_pause.wav", NULL, SND_FILENAME);
PauseGame(t1.native_handle());
PauseGame(t2.native_handle());
}
else if (temp == 'L')
{
PlaySound("smb_pause.wav", NULL, SND_FILENAME);
PauseGame(t1.native_handle());
PauseGame(t2.native_handle());
SaveGame(fs, FileName);
}
else if (temp == 'T')
{
PlaySound("smb_pause.wav", NULL, SND_FILENAME);
PauseGame(t1.native_handle());
PauseGame(t2.native_handle());
GetInformation(fs, FileName);
system("cls");
DrawBoard(0, 0, WIDTH_CONSOLE, HEIGH_CONSOLE, 0, 0);
DrawPlayer();
/*system("cls");*/
system("cls");
DrawBoard(0, 0, WIDTH_CONSOLE, HEIGH_CONSOLE, 0, 0);
GotoXY(40, 19);
printf(" ");
DrawPlayer();
/*_getch();*/
continue;
}
else if (temp == 'R')
{
PlaySound("smb_pause.wav", NULL, SND_FILENAME);
/*ExitGame(t2.native_handle());*/
PauseGame(t1.native_handle());
PauseGame(t2.native_handle());
system("cls");
DrawHem();
DrawLetterGame();
DrawLetterStreet();
DrawLetterCrosing();
PressSetting();
DrawLetterReturn();
GotoXY(15, 6);
cin >> ColorCar;
GotoXY(17, 7);
cin >> ColorBoard;
GotoXY(18, 8);
cin >> ColorPerson;
char press;
press = toupper(_getch());
if (press == 'R')
{
/*StartGame();*/
system("cls");
DrawBoard(0, 0, WIDTH_CONSOLE, HEIGH_CONSOLE,0,0);
DrawPlayer();
continue;
}
/* _getch();*/
/* ExitGame(t1.native_handle());*/
}
else
{
ResumeThread((HANDLE)t1.native_handle());
ResumeThread((HANDLE)t2.native_handle());
if (temp == 'D' || temp == 'A' || temp == 'W' || temp == 'S')
{
MOVING = temp;
}
if (!fs.fail())
{
SaveInformation(fs);
}
}
}
else
{
if (temp == 'Y')StartGame();
else
{
ExitGame(t1.native_handle());
ExitGame(t2.native_handle());
return;
}
}
}
}
else if (Choose == 2)
{
GetInformation(fs, FileName);
Speed = SPEED;
LEVEL = Level;
x = Y.x;
y = Y.y;
KT = 1;
/*DrawPlayer();*/
Choose = 1; continue;
}
else if (Choose == 3)
{
system("cls");
DrawSetting();
GotoXY(11, 39);
cin >> ColorCar;
GotoXY(13, 40);
cin >> ColorBoard;
GotoXY(14, 41);
cin >> ColorPerson;
system("cls");
DrawHem();
DrawLetterGame();
DrawLetterStreet();
DrawLetterCrosing();
DrawChoose();
DrawInformationStudent(Choose); continue;
}
else if (Choose == 4)
{
break;
}
else
{
return;
}
}
PlaySound("smb_gameover.wav", NULL, SND_FILENAME);
} | [
"nguyenthanhtung990818@gmail.com"
] | nguyenthanhtung990818@gmail.com |
73263779ee3f91a4752277f0d651c68562c6f388 | 696e35ccdf167c3f6b1a7f5458406d3bb81987c9 | /chrome/browser/chromeos/login/screens/multidevice_setup_screen.cc | c7346f8afdfc0a04c9850ae9ceda2d040f9a0f33 | [
"BSD-3-Clause"
] | permissive | mgh3326/iridium-browser | 064e91a5e37f4e8501ea971483bd1c76297261c3 | e7de6a434d2659f02e94917be364a904a442d2d0 | refs/heads/master | 2023-03-30T16:18:27.391772 | 2019-04-24T02:14:32 | 2019-04-24T02:14:32 | 183,128,065 | 0 | 0 | BSD-3-Clause | 2019-11-30T06:06:02 | 2019-04-24T02:04:51 | null | UTF-8 | C++ | false | false | 3,544 | cc | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/login/screens/multidevice_setup_screen.h"
#include "base/feature_list.h"
#include "base/logging.h"
#include "base/metrics/histogram_macros.h"
#include "chrome/browser/chromeos/login/screens/multidevice_setup_screen_view.h"
#include "chrome/browser/chromeos/login/users/chrome_user_manager_util.h"
#include "chrome/browser/chromeos/multidevice_setup/multidevice_setup_client_factory.h"
#include "chrome/browser/chromeos/multidevice_setup/oobe_completion_tracker_factory.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chromeos/services/multidevice_setup/public/cpp/multidevice_setup_client.h"
#include "chromeos/services/multidevice_setup/public/cpp/oobe_completion_tracker.h"
namespace chromeos {
namespace {
constexpr const char kAcceptedSetupUserAction[] = "setup-accepted";
constexpr const char kDeclinedSetupUserAction[] = "setup-declined";
} // namespace
MultiDeviceSetupScreen::MultiDeviceSetupScreen(
BaseScreenDelegate* base_screen_delegate,
MultiDeviceSetupScreenView* view)
: BaseScreen(base_screen_delegate, OobeScreen::SCREEN_MULTIDEVICE_SETUP),
view_(view) {
DCHECK(view_);
view_->Bind(this);
}
MultiDeviceSetupScreen::~MultiDeviceSetupScreen() {
view_->Bind(nullptr);
}
void MultiDeviceSetupScreen::Show() {
// Only attempt the setup flow for non-guest users.
if (chrome_user_manager_util::IsPublicSessionOrEphemeralLogin()) {
ExitScreen();
return;
}
multidevice_setup::MultiDeviceSetupClient* client =
multidevice_setup::MultiDeviceSetupClientFactory::GetForProfile(
ProfileManager::GetActiveUserProfile());
if (!client) {
ExitScreen();
return;
}
// If there is no eligible multi-device host phone or if there is a phone and
// it has already been set, skip the setup flow.
if (client->GetHostStatus().first !=
multidevice_setup::mojom::HostStatus::kEligibleHostExistsButNoHostSet) {
VLOG(1) << "Skipping MultiDevice setup screen; host status: "
<< client->GetHostStatus().first;
ExitScreen();
return;
}
view_->Show();
// Record that user was presented with setup flow to prevent spam
// notifications from suggesting setup in the future.
multidevice_setup::OobeCompletionTracker* oobe_completion_tracker =
multidevice_setup::OobeCompletionTrackerFactory::GetForProfile(
ProfileManager::GetActiveUserProfile());
DCHECK(oobe_completion_tracker);
oobe_completion_tracker->MarkOobeShown();
}
void MultiDeviceSetupScreen::Hide() {
view_->Hide();
}
void MultiDeviceSetupScreen::OnUserAction(const std::string& action_id) {
if (action_id == kAcceptedSetupUserAction) {
RecordMultiDeviceSetupOOBEUserChoiceHistogram(
MultiDeviceSetupOOBEUserChoice::kAccepted);
ExitScreen();
} else if (action_id == kDeclinedSetupUserAction) {
RecordMultiDeviceSetupOOBEUserChoiceHistogram(
MultiDeviceSetupOOBEUserChoice::kDeclined);
ExitScreen();
} else {
BaseScreen::OnUserAction(action_id);
NOTREACHED();
}
}
void MultiDeviceSetupScreen::RecordMultiDeviceSetupOOBEUserChoiceHistogram(
MultiDeviceSetupOOBEUserChoice value) {
UMA_HISTOGRAM_ENUMERATION("MultiDeviceSetup.OOBE.UserChoice", value);
}
void MultiDeviceSetupScreen::ExitScreen() {
Finish(ScreenExitCode::MULTIDEVICE_SETUP_FINISHED);
}
} // namespace chromeos
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
8e1a8fa9f4ed194d56e129ba5f4eef7901b84bf6 | ea19bf6e584237823c73980a9bfcce7d4feeddb9 | /General_NetSDK_Chn_Win32_IS_V3.42.0.R.141029/NetSDK_Chn_Bin/演示程序源码/分类应用/参数配置/ClientDemo5/DlgDVR.h | 6cb016e3523a13f04b4908ecb89be48a86109f29 | [] | no_license | fantasydreams/VS | ba6989bab048e718461207b0946c62b32f25471d | 49a141e41952b2a841e7951eb55c1e399c8c3bc0 | refs/heads/master | 2020-04-05T10:12:16.663691 | 2015-04-07T15:21:35 | 2015-04-07T15:21:35 | 29,297,592 | 2 | 3 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 1,605 | h | #if !defined(AFX_DLGDVR_H__0BE1B67A_144A_4D50_80BC_4A84BDFFF514__INCLUDED_)
#define AFX_DLGDVR_H__0BE1B67A_144A_4D50_80BC_4A84BDFFF514__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// DlgDVR.h : header file
//
#include "dhnetsdk.h"
#include "DlgMsgHandle.h"
#include "dhconfigsdk.h"
/////////////////////////////////////////////////////////////////////////////
// CDlgDVR dialog
class CDlgDVR : public CDialog
{
// Construction
public:
CDlgDVR(CWnd* pParent = NULL); // standard constructor
~CDlgDVR();
// Dialog Data
//{{AFX_DATA(CDlgDVR)
enum { IDD = IDD_DIALOG_DVR };
BOOL m_bIPColl;
//}}AFX_DATA
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CDlgDVR)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
public:
void SetLoginHandle(LONG lLogin, BOOL bNewProtocol){m_lLogin = lLogin; m_bNewProtocol = bNewProtocol;}
void GetIPCollisionCfg();
void SetIPCollisionCfg();
protected:
// Generated message map functions
//{{AFX_MSG(CDlgDVR)
afx_msg void OnButtonSave();
afx_msg void OnButtonRead();
virtual BOOL OnInitDialog();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
private:
LLONG m_lLogin;
CDlgMsgHandle m_dlgMsgHandle;
BOOL m_bNewProtocol;
ALARM_IP_COLLISION_CFG m_stuIPCollCfg;//ip³åÍ»ÅäÖÃ
CFG_IPCONFLICT_INFO *m_stuIPConflitInfo;
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_DLGDVR_H__0BE1B67A_144A_4D50_80BC_4A84BDFFF514__INCLUDED_)
| [
"1164695923@qq.com"
] | 1164695923@qq.com |
71a1285f30e1e76f767000ed3fa5b100dbbb6e4b | 3cf79286ee1ffa88ce4033599c40519271bc4af7 | /Week02/230A.cpp | 713a309a514fc8ed50af69ff22f618ba3211a7e9 | [
"MIT"
] | permissive | AAlab1819/izzyengelbert-00000018656 | 3362bf50f335d23bb52b95e895f7cb238ea9f898 | db39c00ebb0fce76b457c49b7a6bd2c9ad522e2e | refs/heads/master | 2020-03-27T14:59:05.589858 | 2018-10-31T17:27:23 | 2018-10-31T17:27:23 | 146,691,211 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,926 | cpp | #include <iostream>
using namespace std;
int partition(int arr[], int arr1[], int low, int high);
void quicksort(int arr[], int arr1[], int low, int high);
void quickSort(int arr[], int arr1[], int low, int high)
{
int pi;
if (low < high)
{
/* pi is partitioning index, arr[p] is now
at right place */
pi = partition(arr, arr1, low, high);
quickSort(arr, arr1, low, pi - 1); // Before pi
quickSort(arr, arr1, pi + 1, high); // After pi
}
}
int partition (int arr[], int arr1[], int low, int high)
{
// pivot (Element to be placed at right position)
int pivot = arr[high];
int i = (low - 1); // Index of smaller element
for (int j = low; j <= high- 1; j++)
{
// If current element is smaller than or
// equal to pivot
if (arr[j] <= pivot)
{
i++; // increment index of smaller element
int temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
temp = arr1[j];
arr1[j] = arr1[i];
arr1[i] = temp;
//swap arr[i] and arr[j]
}
}
int temp = arr[high];
arr[high] = arr[i + 1];
arr[i + 1] = temp;
temp = arr1[high];
arr1[high] = arr1[i + 1];
arr1[i + 1] = temp;
//swap arr[i + 1] and arr[high])
return (i + 1);
}
int main(){
bool able = true;
int strength;
int n;
cin>>strength>>n;
int dragonStrength[n];
int dragonBonus[n];
for(int i=0; i<n;++i){
cin>>dragonStrength[i]>>dragonBonus[i];
}
quickSort(dragonStrength, dragonBonus, 0, n-1);
for(int i=0 ; i<n ; ++i){
if(strength>dragonStrength[i]){
strength += dragonBonus[i];
}else{
able = false;
break;
}
}
cout<<endl;
if(able){
cout<<"YES";
}else{
cout<<"NO";
}
return 0;
}
| [
"izzyengelbert@gmail.com"
] | izzyengelbert@gmail.com |
5c2beb09872359704eacec3636f8fa58f7ea4e8a | 44cf55a4c2eed8da013236ee312673f7e1e4566e | /ideas/procpp/mixin_handler/tests/httpgateway.cpp | 5c46998331d6833a31ced00934f95ae2269b0d16 | [] | no_license | wangxx2026/universe | fe0709a0b2dd289815a481cad98a28b3a43b5f5f | d10dd5517e53d196da6a38c1530384093a9812db | refs/heads/master | 2020-03-21T17:45:12.260873 | 2018-03-08T02:51:00 | 2018-03-08T02:51:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 491 | cpp | #include "ReactHandler.h"
int main()
{
ClientServer server;
HttpGateway proto(server);
server.on<HttpGateway::ON_REQUEST_URI>(Utils::to_function([&server](HttpRequest& req, HttpProviderAddress& target_address, bool& ok) {
ok = true;
target_address.host = "blog.csdn.net";
target_address.port = 80;
target_address.path = "/jasonliuvip/article/details/23567843";
}));
server.listen(8082, proto);
server.event_loop();
return 0;
}
| [
"652732310@qq.com"
] | 652732310@qq.com |
84f816ca58dd75709ff5a4de9b48ce4e016afa1a | d681c2fea675acfe3e0eed164248fa661f16593c | /tests/impl/containers_traverse_test.cpp | ff2e71a33acb8b256d3eb6f45295599e608b39e7 | [
"BSD-3-Clause"
] | permissive | opensoft/asynqro | 5efc081aa7b5a607f3b7267fbe3959ff986d87f0 | 23cac7e31bc5719a207fcb77e370bfeebaaf7593 | refs/heads/master | 2020-04-24T04:48:51.222426 | 2019-01-21T02:26:29 | 2019-01-21T02:35:48 | 171,717,061 | 4 | 0 | BSD-3-Clause | 2019-02-20T17:16:58 | 2019-02-20T17:16:58 | null | UTF-8 | C++ | false | false | 13,730 | cpp | #include "asynqro/impl/containers_traverse.h"
#include "gtest/gtest.h"
#include <QHash>
#include <QLinkedList>
#include <QList>
#include <QMap>
#include <QSet>
#include <QVector>
#include <list>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <vector>
using namespace asynqro;
template <typename Container>
class SingleSocketedContainersTraverseTest : public testing::Test
{
public:
using Source = Container;
};
template <typename Container>
class DoubleSocketedContainersTraverseTest : public testing::Test
{
public:
using Source = Container;
auto toVector(const Container &x)
{
std::vector<typename Container::key_type> result;
for (auto it = x.cbegin(); it != x.cend(); ++it) {
if constexpr (detail::IsSpecialization_V<Container, QMap> || detail::IsSpecialization_V<Container, QMultiMap>)
result.push_back(it.key());
else
result.push_back(it->first);
}
return result;
}
};
template <typename Container>
class SingleSocketedUnorderedContainersTraverseTest : public testing::Test
{
public:
using Source = Container;
auto toVector(const Container &x)
{
std::vector<typename Container::value_type> result;
std::copy(x.begin(), x.end(), std::back_inserter(result));
std::sort(result.begin(), result.end());
return result;
}
};
template <typename Container>
class DoubleSocketedUnorderedContainersTraverseTest : public testing::Test
{
public:
using Source = Container;
auto toVector(const Container &x)
{
std::vector<typename Container::key_type> result;
for (auto it = x.cbegin(); it != x.cend(); ++it) {
if constexpr (detail::IsSpecialization_V<Container, QHash> || detail::IsSpecialization_V<Container, QMultiHash>)
result.push_back(it.key());
else
result.push_back(it->first);
}
std::sort(result.begin(), result.end());
return result;
}
};
using SingleSocketedContainersTypes = ::testing::Types<QVector<int>, QList<int>, QLinkedList<int>, std::vector<int>,
std::set<int>, std::multiset<int>, std::list<int>>;
TYPED_TEST_CASE(SingleSocketedContainersTraverseTest, SingleSocketedContainersTypes);
TYPED_TEST(SingleSocketedContainersTraverseTest, findIf)
{
typename TestFixture::Source testContainer = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int result;
auto oddPredicate = [](int x) -> bool { return x % 2; };
auto bigValuePredicate = [](int x) -> bool { return x > 42; };
auto equalPredicate = [](int x) -> bool { return x == 5; };
result = traverse::findIf(testContainer, oddPredicate, -1);
ASSERT_EQ(1, result);
result = traverse::findIf(testContainer, bigValuePredicate, -1);
ASSERT_EQ(-1, result);
result = traverse::findIf(testContainer, bigValuePredicate, 50);
ASSERT_EQ(50, result);
result = traverse::findIf(testContainer, bigValuePredicate);
ASSERT_EQ(0, result);
result = traverse::findIf(testContainer, equalPredicate);
EXPECT_EQ(5, result);
}
TYPED_TEST(SingleSocketedContainersTraverseTest, findIfEmpty)
{
typename TestFixture::Source emptyContainer;
int result = traverse::findIf(emptyContainer, [](int x) -> bool { return x % 2; }, -1);
EXPECT_EQ(-1, result);
}
TYPED_TEST(SingleSocketedContainersTraverseTest, filter)
{
typename TestFixture::Source testContainer = {1, 2, 3, 4, 5, 6, 7, 8, 9};
typename TestFixture::Source result;
auto oddPredicate = [](int x) -> bool { return x % 2; };
auto bigValuePredicate = [](int x) -> bool { return x > 42; };
auto equalPredicate = [](int x) -> bool { return x == 5; };
result = traverse::filter(testContainer, oddPredicate);
ASSERT_EQ(5, result.size());
auto resultIt = result.cbegin();
EXPECT_EQ(1, *resultIt);
EXPECT_EQ(3, *(++resultIt));
EXPECT_EQ(5, *(++resultIt));
EXPECT_EQ(7, *(++resultIt));
EXPECT_EQ(9, *(++resultIt));
result = traverse::filter(testContainer, bigValuePredicate);
ASSERT_EQ(0, result.size());
result = traverse::filter(testContainer, equalPredicate);
ASSERT_EQ(1, result.size());
EXPECT_EQ(5, *result.cbegin());
}
TYPED_TEST(SingleSocketedContainersTraverseTest, filterEmpty)
{
typename TestFixture::Source emptyContainer;
typename TestFixture::Source result = traverse::filter(emptyContainer, [](int x) -> bool { return x % 2; });
EXPECT_EQ(0, result.size());
}
using SingleSocketedUnorderedContainersTypes =
::testing::Types<QSet<int>, std::unordered_set<int>, std::unordered_multiset<int>>;
TYPED_TEST_CASE(SingleSocketedUnorderedContainersTraverseTest, SingleSocketedUnorderedContainersTypes);
TYPED_TEST(SingleSocketedUnorderedContainersTraverseTest, findIf)
{
typename TestFixture::Source testContainer = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int result;
auto oddPredicate = [](int x) -> bool { return x % 2; };
auto bigValuePredicate = [](int x) -> bool { return x > 42; };
auto equalPredicate = [](int x) -> bool { return x == 5; };
result = traverse::findIf(testContainer, oddPredicate, -1);
ASSERT_TRUE((QSet<int>{1, 3, 5, 7, 9}).contains(result));
result = traverse::findIf(testContainer, bigValuePredicate, -1);
ASSERT_EQ(-1, result);
result = traverse::findIf(testContainer, bigValuePredicate, 50);
ASSERT_EQ(50, result);
result = traverse::findIf(testContainer, bigValuePredicate);
ASSERT_EQ(0, result);
result = traverse::findIf(testContainer, equalPredicate);
EXPECT_EQ(5, result);
}
TYPED_TEST(SingleSocketedUnorderedContainersTraverseTest, findIfEmpty)
{
typename TestFixture::Source emptyContainer;
int result = traverse::findIf(emptyContainer, [](int x) -> bool { return x % 2; }, -1);
EXPECT_EQ(-1, result);
}
TYPED_TEST(SingleSocketedUnorderedContainersTraverseTest, filter)
{
typename TestFixture::Source testContainer = {1, 2, 3, 4, 5, 6, 7, 8, 9};
typename TestFixture::Source result;
auto oddPredicate = [](int x) -> bool { return x % 2; };
auto bigValuePredicate = [](int x) -> bool { return x > 42; };
auto equalPredicate = [](int x) -> bool { return x == 5; };
result = traverse::filter(testContainer, oddPredicate);
ASSERT_EQ(5, result.size());
auto vectorizedResult = this->toVector(result);
auto resultIt = vectorizedResult.cbegin();
EXPECT_EQ(1, *resultIt);
EXPECT_EQ(3, *(++resultIt));
EXPECT_EQ(5, *(++resultIt));
EXPECT_EQ(7, *(++resultIt));
EXPECT_EQ(9, *(++resultIt));
result = traverse::filter(testContainer, bigValuePredicate);
ASSERT_EQ(0, result.size());
result = traverse::filter(testContainer, equalPredicate);
ASSERT_EQ(1, result.size());
EXPECT_EQ(5, *result.cbegin());
}
TYPED_TEST(SingleSocketedUnorderedContainersTraverseTest, filterEmpty)
{
typename TestFixture::Source emptyContainer;
typename TestFixture::Source result = traverse::filter(emptyContainer, [](int x) -> bool { return x % 2; });
EXPECT_EQ(0, result.size());
}
using DoubleSocketedContainersTypes =
::testing::Types<QMap<int, bool>, QMultiMap<int, bool>, std::map<int, bool>, std::multimap<int, bool>>;
TYPED_TEST_CASE(DoubleSocketedContainersTraverseTest, DoubleSocketedContainersTypes);
TYPED_TEST(DoubleSocketedContainersTraverseTest, findIf)
{
typename TestFixture::Source testContainer = {{1, true}, {2, false}, {3, true}, {4, false}, {5, true},
{6, false}, {7, true}, {8, false}, {9, true}};
QPair<int, bool> result;
auto oddPredicate = [](int, bool y) -> bool { return y; };
auto bigValuePredicate = [](int x, bool) -> bool { return x > 42; };
auto equalPredicate = [](int x, bool) -> bool { return x == 5; };
result = traverse::findIf(testContainer, oddPredicate, qMakePair(-1, false));
ASSERT_EQ(1, result.first);
ASSERT_TRUE(result.second);
result = traverse::findIf(testContainer, bigValuePredicate, qMakePair(-1, false));
EXPECT_EQ(-1, result.first);
EXPECT_FALSE(result.second);
result = traverse::findIf(testContainer, bigValuePredicate, qMakePair(50, true));
EXPECT_EQ(50, result.first);
EXPECT_TRUE(result.second);
result = traverse::findIf(testContainer, bigValuePredicate);
EXPECT_EQ(0, result.first);
EXPECT_FALSE(result.second);
result = traverse::findIf(testContainer, equalPredicate);
EXPECT_EQ(5, result.first);
EXPECT_TRUE(result.second);
}
TYPED_TEST(DoubleSocketedContainersTraverseTest, findIfEmpty)
{
typename TestFixture::Source emptyContainer;
QPair<int, bool> result = traverse::findIf(emptyContainer, [](int, bool y) -> bool { return y; },
qMakePair(-1, false));
EXPECT_EQ(-1, result.first);
EXPECT_FALSE(result.second);
}
TYPED_TEST(DoubleSocketedContainersTraverseTest, filter)
{
typename TestFixture::Source testContainer = {{1, true}, {2, false}, {3, true}, {4, false}, {5, true},
{6, false}, {7, true}, {8, false}, {9, true}};
typename TestFixture::Source result;
auto oddPredicate = [](int, bool y) -> bool { return y; };
auto bigValuePredicate = [](int x, bool) -> bool { return x > 42; };
auto equalPredicate = [](int x, bool) -> bool { return x == 5; };
result = traverse::filter(testContainer, oddPredicate);
ASSERT_EQ(5, result.size());
auto vectorizedResult = this->toVector(result);
auto resultIt = vectorizedResult.cbegin();
EXPECT_EQ(1, *resultIt);
EXPECT_EQ(3, *(++resultIt));
EXPECT_EQ(5, *(++resultIt));
EXPECT_EQ(7, *(++resultIt));
EXPECT_EQ(9, *(++resultIt));
result = traverse::filter(testContainer, bigValuePredicate);
ASSERT_EQ(0, result.size());
result = traverse::filter(testContainer, equalPredicate);
ASSERT_EQ(1, result.size());
vectorizedResult = this->toVector(result);
EXPECT_EQ(5, *vectorizedResult.cbegin());
}
TYPED_TEST(DoubleSocketedContainersTraverseTest, filterEmpty)
{
typename TestFixture::Source emptyContainer;
typename TestFixture::Source result = traverse::filter(emptyContainer, [](int, bool y) -> bool { return y; });
EXPECT_EQ(0, result.size());
}
using DoubleSocketedUnorderedContainersTypes = ::testing::Types<
QHash<int, bool>, QMultiHash<int, bool>, std::unordered_map<int, bool>, std::unordered_multimap<int, bool>>;
TYPED_TEST_CASE(DoubleSocketedUnorderedContainersTraverseTest, DoubleSocketedUnorderedContainersTypes);
TYPED_TEST(DoubleSocketedUnorderedContainersTraverseTest, findIf)
{
typename TestFixture::Source testContainer = {{1, true}, {2, false}, {3, true}, {4, false}, {5, true},
{6, false}, {7, true}, {8, false}, {9, true}};
QPair<int, bool> result;
auto oddPredicate = [](int, bool y) -> bool { return y; };
auto bigValuePredicate = [](int x, bool) -> bool { return x > 42; };
auto equalPredicate = [](int x, bool) -> bool { return x == 5; };
result = traverse::findIf(testContainer, oddPredicate, qMakePair(-1, false));
ASSERT_TRUE((QSet<int>{1, 3, 5, 7, 9}).contains(result.first));
ASSERT_TRUE(result.second);
result = traverse::findIf(testContainer, bigValuePredicate, qMakePair(-1, false));
EXPECT_EQ(-1, result.first);
EXPECT_FALSE(result.second);
result = traverse::findIf(testContainer, bigValuePredicate, qMakePair(50, true));
EXPECT_EQ(50, result.first);
EXPECT_TRUE(result.second);
result = traverse::findIf(testContainer, bigValuePredicate);
EXPECT_EQ(0, result.first);
EXPECT_FALSE(result.second);
result = traverse::findIf(testContainer, equalPredicate);
EXPECT_EQ(5, result.first);
EXPECT_TRUE(result.second);
}
TYPED_TEST(DoubleSocketedUnorderedContainersTraverseTest, findIfEmpty)
{
typename TestFixture::Source emptyContainer;
QPair<int, bool> result = traverse::findIf(emptyContainer, [](int, bool y) -> bool { return y; },
qMakePair(-1, false));
EXPECT_EQ(-1, result.first);
EXPECT_FALSE(result.second);
}
TYPED_TEST(DoubleSocketedUnorderedContainersTraverseTest, filter)
{
typename TestFixture::Source testContainer = {{1, true}, {2, false}, {3, true}, {4, false}, {5, true},
{6, false}, {7, true}, {8, false}, {9, true}};
typename TestFixture::Source result;
auto oddPredicate = [](int, bool y) -> bool { return y; };
auto bigValuePredicate = [](int x, bool) -> bool { return x > 42; };
auto equalPredicate = [](int x, bool) -> bool { return x == 5; };
result = traverse::filter(testContainer, oddPredicate);
ASSERT_EQ(5, result.size());
auto vectorizedResult = this->toVector(result);
auto resultIt = vectorizedResult.cbegin();
EXPECT_EQ(1, *resultIt);
EXPECT_EQ(3, *(++resultIt));
EXPECT_EQ(5, *(++resultIt));
EXPECT_EQ(7, *(++resultIt));
EXPECT_EQ(9, *(++resultIt));
result = traverse::filter(testContainer, bigValuePredicate);
ASSERT_EQ(0, result.size());
result = traverse::filter(testContainer, equalPredicate);
ASSERT_EQ(1, result.size());
vectorizedResult = this->toVector(result);
EXPECT_EQ(5, *vectorizedResult.cbegin());
}
TYPED_TEST(DoubleSocketedUnorderedContainersTraverseTest, filterEmpty)
{
typename TestFixture::Source emptyContainer;
typename TestFixture::Source result = traverse::filter(emptyContainer, [](int, bool y) -> bool { return y; });
EXPECT_EQ(0, result.size());
}
| [
"kormalev.denis@gmail.com"
] | kormalev.denis@gmail.com |
dc3b97fb9856bab0a9dda5b02e010a948e47101c | 60e7862f77f07a35a3d599d703b8909a66a9d4b6 | /include/votca/ctp/polarfrag.h | bf42e991e6a4c1c03a7009f7bfe46cc7f6c1cf9e | [
"Apache-2.0"
] | permissive | jimbach/ctp | bbe2eb682ca14f08cab426455a9638230d43ff18 | e5b33f074f81c6e6859dfaacada1b6c992c67c2b | refs/heads/master | 2021-01-02T05:56:47.850923 | 2019-11-22T22:55:19 | 2019-11-22T22:55:19 | 239,518,739 | 0 | 0 | Apache-2.0 | 2020-02-10T13:30:08 | 2020-02-10T13:30:08 | null | UTF-8 | C++ | false | false | 1,676 | h | #ifndef VOTCA_CTP_POLARFRAG_H
#define VOTCA_CTP_POLARFRAG_H
#include <votca/ctp/apolarsite.h>
#include <boost/serialization/vector.hpp>
#include <boost/serialization/base_object.hpp>
namespace votca { namespace ctp {
// Forward declarations
class PolarSeg;
class PolarFrag : public std::vector<APolarSite*>
{
public:
~PolarFrag();
int getId() const { return _id; }
const string &getName() const { return _name; }
const votca::tools::vec &CalcPosCenterOfGeom();
const votca::tools::vec &CalcPosPolarWeights();
const votca::tools::vec &getPos() { return _pos; }
void GeneratePermInduCgSite(bool do_cg_polarizabilities);
APolarSite *getInduCgSite() { return _indu_cg_site; }
APolarSite *getPermCgSite() { return _perm_cg_site; }
// Serialization interface
template<class Archive>
void serialize(Archive &arch, const unsigned int version) {
arch & boost::serialization::base_object< vector<APolarSite*> >(*this);
arch & _id;
arch & _name;
arch & _pseg;
arch & _pos;
return;
}
friend class PolarSeg;
friend class boost::serialization::access;
private:
PolarFrag()
: _id(-1), _name(""), _pseg(NULL), _pos(vec(0,0,0)),
_indu_cg_site(NULL), _perm_cg_site(NULL) {}
PolarFrag(PolarSeg *pseg, int id, string name)
: _id(id), _name(name), _pseg(pseg), _pos(vec(0,0,0)),
_indu_cg_site(NULL), _perm_cg_site(NULL) {}
int _id;
string _name;
PolarSeg *_pseg;
votca::tools::vec _pos;
APolarSite *_indu_cg_site;
APolarSite *_perm_cg_site;
};
}}
#endif | [
"carl.poelking@mpip-mainz.mpg.de"
] | carl.poelking@mpip-mainz.mpg.de |
7699be46f158db573474e4d72c06984be05ab407 | 0f9b27ccd0f7ab7a114569e493800fc5c8da6050 | /data_structures/SelectionSort.cpp | 472938a4a04705983baf9caf6314b1d8d3859c92 | [] | no_license | LifeofAGeek/cpp-practice | bc9ccf9f5f377252cc1817a204b29dd8e9bf9693 | e4161941f7912efab5d48b3b0a7732c9c2ee6ace | refs/heads/master | 2022-11-24T09:22:54.794271 | 2020-07-23T04:40:03 | 2020-07-23T04:40:03 | 281,887,321 | 0 | 0 | null | 2020-07-23T07:51:15 | 2020-07-23T07:51:14 | null | UTF-8 | C++ | false | false | 794 | cpp | #include <iostream>
using namespace std;
void selection_sort(int arr[], int n)
{
for (int i = 0; i < n - 1; i++)
{
int min_index = i;
for (int j = i+1;j<n;j++)
{
if (arr[j]<arr[min_index])
{
min_index = j;
}
}
int temp = arr[i];
arr[i] = arr[min_index];
arr[min_index] = temp;
}
}
void display(int arr[],int n)
{
cout<<"sorted array is : ";
for(int i = 0;i<n;i++)
{
cout<<arr[i]<<" ";
}
}
int main()
{
cout << "enter the size of the array: ";
int n;
cin >> n;
int arr[n];
cout<<"enter the elements : ";
for (int i = 0;i<n;i++)
{
cin>>arr[i];
}
selection_sort(arr, n);
display(arr,n);
return 0;
} | [
"aditya.mca19.du@gmail.com"
] | aditya.mca19.du@gmail.com |
1750fc5e96fc116d329c06c93501bf0c77ad442d | 4afc6182476e8e381ea0913f7b1205edf384a029 | /.build/iOS-Debug/include/app/Fuse.Scripting.NativePromise2_PromiseClosure__string__string.h | 4e854551200347e5daa40c9e9456fb50284a82c6 | [] | no_license | noircynical/soscon_demoproject | 45a4b5594582447001c2895e24cf2e6566095a63 | aab19822fb8bc46715e6b41ac785faf7a128d9e7 | refs/heads/master | 2021-01-10T05:41:33.994651 | 2015-10-28T04:27:43 | 2015-10-28T04:27:43 | 45,085,497 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,042 | h | // This file was generated based on '/usr/local/share/uno/Packages/Fuse.Scripting/0.11.3/$.uno'.
// WARNING: Changes might be lost if you edit this file directly.
#ifndef __APP_FUSE_SCRIPTING_NATIVE_PROMISE2_PROMISE_CLOSURE__STRING__STRING_H__
#define __APP_FUSE_SCRIPTING_NATIVE_PROMISE2_PROMISE_CLOSURE__STRING__STRING_H__
#include <app/Uno.Object.h>
#include <Uno.h>
namespace app { namespace Fuse { namespace Scripting { struct Context; } } }
namespace app { namespace Fuse { namespace Scripting { struct Function; } } }
namespace app { namespace Uno { namespace Threading { struct Future__string; } } }
namespace app { namespace Uno { struct Exception; } }
namespace app {
namespace Fuse {
namespace Scripting {
struct NativePromise2_PromiseClosure__string__string;
struct NativePromise2_PromiseClosure__string__string__uType : ::uClassType
{
};
NativePromise2_PromiseClosure__string__string__uType* NativePromise2_PromiseClosure__string__string__typeof();
void NativePromise2_PromiseClosure__string__string___ObjInit(NativePromise2_PromiseClosure__string__string* __this, ::app::Fuse::Scripting::Context* context, ::app::Uno::Threading::Future__string* promise, ::uDelegate* converter);
void NativePromise2_PromiseClosure__string__string__InternalResolve(NativePromise2_PromiseClosure__string__string* __this);
NativePromise2_PromiseClosure__string__string* NativePromise2_PromiseClosure__string__string__New_1(::uStatic* __this, ::app::Fuse::Scripting::Context* context, ::app::Uno::Threading::Future__string* promise, ::uDelegate* converter);
void NativePromise2_PromiseClosure__string__string__Reject(NativePromise2_PromiseClosure__string__string* __this, ::app::Uno::Exception* reason);
void NativePromise2_PromiseClosure__string__string__Resolve(NativePromise2_PromiseClosure__string__string* __this, ::uString* result);
::uObject* NativePromise2_PromiseClosure__string__string__Run(NativePromise2_PromiseClosure__string__string* __this, ::uArray* args);
struct NativePromise2_PromiseClosure__string__string : ::uObject
{
::uStrong< ::app::Fuse::Scripting::Context*> _c;
::uStrong< ::app::Uno::Threading::Future__string*> _promise;
::uStrong< ::app::Fuse::Scripting::Function*> _resolve;
::uStrong< ::app::Fuse::Scripting::Function*> _reject;
::uStrong< ::uDelegate*> _converter;
::uStrong< ::uString*> _result;
void _ObjInit(::app::Fuse::Scripting::Context* context, ::app::Uno::Threading::Future__string* promise, ::uDelegate* converter) { NativePromise2_PromiseClosure__string__string___ObjInit(this, context, promise, converter); }
void InternalResolve() { NativePromise2_PromiseClosure__string__string__InternalResolve(this); }
void Reject(::app::Uno::Exception* reason) { NativePromise2_PromiseClosure__string__string__Reject(this, reason); }
void Resolve(::uString* result) { NativePromise2_PromiseClosure__string__string__Resolve(this, result); }
::uObject* Run(::uArray* args) { return NativePromise2_PromiseClosure__string__string__Run(this, args); }
};
}}}
#endif
| [
"0101rgb@gmail.com"
] | 0101rgb@gmail.com |
1917a8a389c47e5c35625378399483c6d66332f5 | 1e6c47ffab5e5a17bce613be57695b8eaf9a5ef2 | /Week_09/最后一个单词的长度.cpp | 3e420a14f33590cb3343df0db192caca02ead2a4 | [] | no_license | wh15513683215/algorithm016 | dc79254c5f0133b3cfe4439ddd702c5d17077595 | 8566dd54bfd5c613aa43530b264dd44a7058420d | refs/heads/master | 2023-01-22T03:03:26.393577 | 2020-11-26T15:18:38 | 2020-11-26T15:18:38 | 293,465,111 | 0 | 0 | null | 2020-09-07T08:17:48 | 2020-09-07T08:17:47 | null | UTF-8 | C++ | false | false | 306 | cpp | class Solution {
public:
int lengthOfLastWord(string s) {
int index = s.size() - 1;
// 去后导0
while (index >= 0 && isspace(s[index])) --index;
int cnt = 0;
// 开始统计
while (index >= 0 && isalpha(s[index--])) ++cnt;
return cnt;
}
};
| [
"wh15513683215@163.com"
] | wh15513683215@163.com |
31861a305eed56a382996c97d76615e14040f8a7 | 3be032c14c9b659ba4c1dfd599f8c85257688317 | /dist/ios/include/Fuse.Input.PointerReleased.h | 6f37083b8c84e0d1551a69a5b8bbb10e90355898 | [] | no_license | gncvalente/18app | 5433674c6f86d204af81290aa61eef07bb897cf5 | 40968aa4e3e7c044ce14cd2488313dd5a45d9b1b | refs/heads/master | 2021-07-21T01:43:39.091532 | 2017-10-31T12:44:48 | 2017-10-31T12:44:48 | 106,106,556 | 3 | 0 | null | 2017-10-07T15:02:43 | 2017-10-07T15:02:43 | null | UTF-8 | C++ | false | false | 930 | h | // This file was generated based on /usr/local/share/uno/Packages/Fuse.Nodes/1.3.1/Input/PointerEvents.uno.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Fuse.Input.PointerReleasedArgs.h>
#include <Fuse.Input.PointerReleasedHandler.h>
#include <Fuse.VisualEvent-2.h>
namespace g{namespace Fuse{namespace Input{struct PointerReleased;}}}
namespace g{
namespace Fuse{
namespace Input{
// internal sealed class PointerReleased :64
// {
::g::Fuse::VisualEvent_type* PointerReleased_typeof();
void PointerReleased__ctor_1_fn(PointerReleased* __this);
void PointerReleased__Invoke_fn(PointerReleased* __this, uDelegate* handler, uObject* sender, ::g::Fuse::Input::PointerReleasedArgs* args);
void PointerReleased__New1_fn(PointerReleased** __retval);
struct PointerReleased : ::g::Fuse::VisualEvent
{
void ctor_1();
static PointerReleased* New1();
};
// }
}}} // ::g::Fuse::Input
| [
"giuseppe.toto@gmail.com"
] | giuseppe.toto@gmail.com |
6eecd5b5773f47d0f200aa4a25374f21276a98c2 | fba41f794edf2b3b8349504290c2f3c6275a56c4 | /Code C++/STL Code/Upper_bound.cpp | ca1432b7c0bd3dbb4b66c629fe109cd32a58d83e | [] | no_license | Nirob-0812/Cpp-Code | df7485b97b053baeb47055d47cc05c67d0815156 | af73be5a2e472739b1dca1a6d86fb6b33d3cf1f3 | refs/heads/main | 2023-02-28T22:25:57.805178 | 2021-01-27T10:04:51 | 2021-01-27T10:04:51 | 333,297,406 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 414 | cpp | #include<iostream>
#include<vector>
#include<string>
#include<iterator>
#include<algorithm>
using namespace std;
int main()
{
vector<int>vec={1,3,4,5,6,8,9};
vector<int>::iterator it;
it=upper_bound(vec.begin(),vec.end(),1);
cout<<((it==vec.end())?"Not Found":to_string(*it));
//if(it==vec.end())
// cout<<"Not Found"<<endl;
//else
// cout<<*it<<endl;
}
| [
"noreply@github.com"
] | noreply@github.com |
1f6efecb0ab1f672fcd83618a1261cfae135c371 | d49f64c9a31bc9a253d61fd5d1c198dca7be3cc7 | /mediapipe/python/pybind/image_frame.cc | 0747f08f1b08ec72e34aa6eeb04e684d952b4d49 | [
"Apache-2.0"
] | permissive | Weco/mediapipe | 9a38524dc5b864b072aecf13dfc9bcb5d944ffdc | 01e253f80a68bd812b18b94267d398de13775907 | refs/heads/master | 2023-01-23T19:44:57.649655 | 2020-11-13T17:26:03 | 2020-11-13T17:26:03 | 312,380,765 | 2 | 0 | Apache-2.0 | 2020-11-12T20:17:14 | 2020-11-12T19:52:15 | null | UTF-8 | C++ | false | false | 14,901 | cc | // Copyright 2020 The MediaPipe Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "mediapipe/python/pybind/image_frame_util.h"
#include "mediapipe/python/pybind/util.h"
#include "pybind11/stl.h"
namespace mediapipe {
namespace python {
namespace {
template <typename T>
py::array GenerateContiguousDataArrayHelper(const ImageFrame& image_frame,
const py::object& py_object) {
std::vector<int> shape{image_frame.Height(), image_frame.Width()};
if (image_frame.NumberOfChannels() > 1) {
shape.push_back(image_frame.NumberOfChannels());
}
py::array_t<T, py::array::c_style> contiguous_data;
if (image_frame.IsContiguous()) {
contiguous_data = py::array_t<T, py::array::c_style>(
shape, reinterpret_cast<const T*>(image_frame.PixelData()), py_object);
} else {
auto contiguous_data_copy =
absl::make_unique<T[]>(image_frame.Width() * image_frame.Height() *
image_frame.NumberOfChannels());
image_frame.CopyToBuffer(contiguous_data_copy.get(),
image_frame.PixelDataSizeStoredContiguously());
auto capsule = py::capsule(contiguous_data_copy.get(), [](void* data) {
if (data) {
delete[] reinterpret_cast<T*>(data);
}
});
contiguous_data = py::array_t<T, py::array::c_style>(
shape, contiguous_data_copy.release(), capsule);
}
// In both cases, the underlying data is not writable in Python.
py::detail::array_proxy(contiguous_data.ptr())->flags &=
~py::detail::npy_api::NPY_ARRAY_WRITEABLE_;
return contiguous_data;
}
py::array GenerateContiguousDataArray(const ImageFrame& image_frame,
const py::object& py_object) {
switch (image_frame.ChannelSize()) {
case sizeof(uint8):
return GenerateContiguousDataArrayHelper<uint8>(image_frame, py_object)
.cast<py::array>();
case sizeof(uint16):
return GenerateContiguousDataArrayHelper<uint16>(image_frame, py_object)
.cast<py::array>();
case sizeof(float):
return GenerateContiguousDataArrayHelper<float>(image_frame, py_object)
.cast<py::array>();
break;
default:
throw RaisePyError(PyExc_RuntimeError,
"Unsupported image frame channel size. Data is not "
"uint8, uint16, or float?");
}
}
// Generates a contiguous data pyarray object on demand.
// This function only accepts an image frame object that already stores
// contiguous data. The output py::array points to the raw pixel data array of
// the image frame object directly.
py::array GenerateDataPyArrayOnDemand(const ImageFrame& image_frame,
const py::object& py_object) {
if (!image_frame.IsContiguous()) {
throw RaisePyError(PyExc_RuntimeError,
"GenerateDataPyArrayOnDemand must take an ImageFrame "
"object that stores contiguous data.");
}
return GenerateContiguousDataArray(image_frame, py_object);
}
// Gets the cached contiguous data array from the "__contiguous_data" attribute.
// If the attribute doesn't exist, the function calls
// GenerateContiguousDataArray() to generate the contiguous data pyarray object,
// which realigns and copies the data from the original image frame object.
// Then, the data array object is cached in the "__contiguous_data" attribute.
// This function only accepts an image frame object that stores non-contiguous
// data.
py::array GetCachedContiguousDataAttr(const ImageFrame& image_frame,
const py::object& py_object) {
if (image_frame.IsContiguous()) {
throw RaisePyError(PyExc_RuntimeError,
"GetCachedContiguousDataAttr must take an ImageFrame "
"object that stores non-contiguous data.");
}
py::object get_data_attr =
py::getattr(py_object, "__contiguous_data", py::none());
if (image_frame.IsEmpty()) {
throw RaisePyError(PyExc_RuntimeError, "ImageFrame is unallocated.");
}
// If __contiguous_data attr doesn't store data yet, generates the contiguous
// data array object and caches the result.
if (get_data_attr.is_none()) {
py_object.attr("__contiguous_data") =
GenerateContiguousDataArray(image_frame, py_object);
}
return py_object.attr("__contiguous_data").cast<py::array>();
}
template <typename T>
py::object GetValue(const ImageFrame& image_frame, const std::vector<int>& pos,
const py::object& py_object) {
py::array_t<T, py::array::c_style> output_array =
image_frame.IsContiguous()
? GenerateDataPyArrayOnDemand(image_frame, py_object)
: GetCachedContiguousDataAttr(image_frame, py_object);
if (pos.size() == 2) {
return py::cast(static_cast<T>(output_array.at(pos[0], pos[1])));
} else if (pos.size() == 3) {
return py::cast(static_cast<T>(output_array.at(pos[0], pos[1], pos[2])));
}
return py::none();
}
} // namespace
namespace py = pybind11;
void ImageFrameSubmodule(pybind11::module* module) {
py::module m =
module->def_submodule("image_frame", "MediaPipe image frame module");
py::options options;
options.disable_function_signatures();
// ImageFormat
py::enum_<mediapipe::ImageFormat::Format> image_format(
m, "ImageFormat",
R"doc(An enum describing supported raw image formats.
SRGB: sRGB, interleaved: one byte for R, then one byte for G, then one byte
for B for each pixel.
SRGBA: sRGBA, interleaved: one byte for R, one byte for G, one byte for B, one
byte for alpha or unused.
SBGRA: sBGRA, interleaved: one byte for B, one byte for G, one byte for R, one
byte for alpha or unused.
GRAY8: Grayscale, one byte per pixel.
GRAY16: Grayscale, one uint16 per pixel.
SRGB48: sRGB, interleaved, each component is a uint16.
SRGBA64: sRGBA, interleaved, each component is a uint16.
VEC32F1: One float per pixel.
VEC32F2: Two floats per pixel.
)doc");
image_format.value("SRGB", mediapipe::ImageFormat::SRGB)
.value("SRGBA", mediapipe::ImageFormat::SRGBA)
.value("SBGRA", mediapipe::ImageFormat::SBGRA)
.value("GRAY8", mediapipe::ImageFormat::GRAY8)
.value("GRAY16", mediapipe::ImageFormat::GRAY16)
.value("SRGB48", mediapipe::ImageFormat::SRGB48)
.value("SRGBA64", mediapipe::ImageFormat::SRGBA64)
.value("VEC32F1", mediapipe::ImageFormat::VEC32F1)
.value("VEC32F2", mediapipe::ImageFormat::VEC32F2)
.export_values();
// ImageFrame
py::class_<ImageFrame> image_frame(
m, "ImageFrame",
R"doc(A container for storing an image or a video frame, in one of several formats.
Formats supported by ImageFrame are listed in the ImageFormat enum.
Pixels are encoded row-major in an interleaved fashion. ImageFrame supports
uint8, uint16, and float as its data types.
ImageFrame can be created by copying the data from a numpy ndarray that stores
the pixel data continuously. An ImageFrame may realign the input data on its
default alignment boundary during creation. The data in an ImageFrame will
become immutable after creation.
Creation examples:
import cv2
cv_mat = cv2.imread(input_file)[:, :, ::-1]
rgb_frame = mp.ImageFrame(format=ImageFormat.SRGB, data=cv_mat)
gray_frame = mp.ImageFrame(
format=ImageFormat.GRAY, data=cv2.cvtColor(cv_mat, cv2.COLOR_RGB2GRAY))
from PIL import Image
pil_img = Image.new('RGB', (60, 30), color = 'red')
image_frame = mp.ImageFrame(
format=mp.ImageFormat.SRGB, data=np.asarray(pil_img))
The pixel data in an ImageFrame can be retrieved as a numpy ndarray by calling
`ImageFrame.numpy_view()`. The returned numpy ndarray is a reference to the
internal data and itself is unwritable. If the callers want to modify the
numpy ndarray, it's required to obtain a copy of it.
Pixel data retrieval examples:
for channel in range(num_channel):
for col in range(width):
for row in range(height):
print(image_frame[row, col, channel])
output_ndarray = image_frame.numpy_view()
print(output_ndarray[0, 0, 0])
copied_ndarray = np.copy(output_ndarray)
copied_ndarray[0,0,0] = 0
)doc",
py::dynamic_attr());
image_frame
.def(
py::init([](mediapipe::ImageFormat::Format format,
const py::array_t<uint8, py::array::c_style>& data) {
if (format != mediapipe::ImageFormat::GRAY8 &&
format != mediapipe::ImageFormat::SRGB &&
format != mediapipe::ImageFormat::SRGBA) {
throw RaisePyError(PyExc_RuntimeError,
"uint8 image data should be one of the GRAY8, "
"SRGB, and SRGBA MediaPipe image formats.");
}
return CreateImageFrame<uint8>(format, data);
}),
R"doc(For uint8 data type, valid ImageFormat are GRAY8, SGRB, and SRGBA.)doc",
py::arg("image_format"), py::arg("data").noconvert())
.def(
py::init([](mediapipe::ImageFormat::Format format,
const py::array_t<uint16, py::array::c_style>& data) {
if (format != mediapipe::ImageFormat::GRAY16 &&
format != mediapipe::ImageFormat::SRGB48 &&
format != mediapipe::ImageFormat::SRGBA64) {
throw RaisePyError(
PyExc_RuntimeError,
"uint16 image data should be one of the GRAY16, "
"SRGB48, and SRGBA64 MediaPipe image formats.");
}
return CreateImageFrame<uint16>(format, data);
}),
R"doc(For uint16 data type, valid ImageFormat are GRAY16, SRGB48, and SRGBA64.)doc",
py::arg("image_format"), py::arg("data").noconvert())
.def(
py::init([](mediapipe::ImageFormat::Format format,
const py::array_t<float, py::array::c_style>& data) {
if (format != mediapipe::ImageFormat::VEC32F1 &&
format != mediapipe::ImageFormat::VEC32F2) {
throw RaisePyError(
PyExc_RuntimeError,
"float image data should be either VEC32F1 or VEC32F2 "
"MediaPipe image formats.");
}
return CreateImageFrame<float>(format, data);
}),
R"doc(For float data type, valid ImageFormat are VEC32F1 and VEC32F2.)doc",
py::arg("image_format"), py::arg("data").noconvert());
image_frame.def(
"numpy_view",
[](ImageFrame& self) {
py::object py_object =
py::cast(self, py::return_value_policy::reference);
// If the image frame data is contiguous, generates the data pyarray
// object on demand because 1) making a pyarray by referring to the
// existing image frame pixel data is relatively cheap and 2) caching
// the pyarray object in an attribute of the image frame is problematic:
// the image frame object and the data pyarray object refer to each
// other, which causes gc fails to free the pyarray after use.
// For the non-contiguous cases, gets a cached data pyarray object from
// the image frame pyobject attribute. This optimization is to avoid the
// expensive data realignment and copy operations happening more than
// once.
return self.IsContiguous()
? GenerateDataPyArrayOnDemand(self, py_object)
: GetCachedContiguousDataAttr(self, py_object);
},
R"doc(Return the image frame pixel data as an unwritable numpy ndarray.
Realign the pixel data to be stored contiguously and return a reference to the
unwritable numpy ndarray. If the callers want to modify the numpy array data,
it's required to obtain a copy of the ndarray.
Returns:
An unwritable numpy ndarray.
Examples:
output_ndarray = image_frame.numpy_view()
copied_ndarray = np.copy(output_ndarray)
copied_ndarray[0,0,0] = 0
)doc");
image_frame.def(
"__getitem__",
[](ImageFrame& self, const std::vector<int>& pos) {
if (pos.size() != 3 &&
!(pos.size() == 2 && self.NumberOfChannels() == 1)) {
throw RaisePyError(
PyExc_IndexError,
absl::StrCat("Invalid index dimension: ", pos.size()).c_str());
}
py::object py_object =
py::cast(self, py::return_value_policy::reference);
switch (self.ByteDepth()) {
case 1:
return GetValue<uint8>(self, pos, py_object);
case 2:
return GetValue<uint16>(self, pos, py_object);
case 4:
return GetValue<float>(self, pos, py_object);
default:
return py::object();
}
},
R"doc(Use the indexer operators to access pixel data.
Raises:
IndexError: If the index is invalid or out of bounds.
Examples:
for channel in range(num_channel):
for col in range(width):
for row in range(height):
print(image_frame[row, col, channel])
)doc");
image_frame
.def(
"is_contiguous", &ImageFrame::IsContiguous,
R"doc(Return True if the pixel data is stored contiguously (without any alignment padding areas).)doc")
.def("is_empty", &ImageFrame::IsEmpty,
R"doc(Return True if the pixel data is unallocated.)doc")
.def(
"is_aligned", &ImageFrame::IsAligned,
R"doc(Return True if each row of the data is aligned to alignment boundary, which must be 1 or a power of 2.
Args:
alignment_boundary: An integer.
Returns:
A boolean.
Examples:
image_frame.is_aligned(16)
)doc");
image_frame.def_property_readonly("width", &ImageFrame::Width)
.def_property_readonly("height", &ImageFrame::Height)
.def_property_readonly("channels", &ImageFrame::NumberOfChannels)
.def_property_readonly("byte_depth", &ImageFrame::ByteDepth)
.def_property_readonly("image_format", &ImageFrame::Format);
}
} // namespace python
} // namespace mediapipe
#include "mediapipe/framework/type_map.h"
MEDIAPIPE_REGISTER_TYPE(::mediapipe::ImageFrame, "::mediapipe::ImageFrame",
nullptr, nullptr);
| [
"chuoling@google.com"
] | chuoling@google.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.