blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 986
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 145
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 122
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
158ad381ec837f28fe07ac762b0849138d12073d | c8bca2e7cd5556382a7f00531c5f24dc7d5daf27 | /mainwindow.h | e2ce7b8ceddcb96b464dac367fe08fdc451abecc | [] | no_license | McVago/8Reinas | 46dc67e1af8c0b53d757847ad4014718c1b3cbbb | 92ef313f8d859275c83f4be723fd09efa8872876 | refs/heads/master | 2020-04-05T03:01:21.602546 | 2018-11-07T06:18:18 | 2018-11-07T06:18:18 | 156,498,576 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 735 | h | #ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QGraphicsScene>
#include <QGraphicsPixmapItem>
#include <QGraphicsView>
#include <QGraphicsRectItem>
#include <vector>
#include<bits/stdc++.h>
#define N 8
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
void generateboard();
private slots:
void on_pushButton_clicked();
private:
Ui::MainWindow *ui;
QGraphicsScene* scene;
QGraphicsPixmapItem* queen;
std::vector<QGraphicsPixmapItem*> queens;
std::vector<int> solutions;
int solutionNumber;
};
#endif // MAINWINDOW_H
| [
"andresmcvago@gmail.com"
] | andresmcvago@gmail.com |
45e01e51701e536231d14282c06c58e362d39994 | 2b339e93f27f300983112fa8bd5bb3f58dcee51a | /source/scene/object/make.hpp | eaa99d85919878c64620ee0644172c7ebee8661e | [] | no_license | octopus-prime/gamma-ray-2 | caf11e2b2f2d349f2845233b1fa8ef163d8ce690 | 873fad52635b48875469ad4a28903a438e0a7bbe | refs/heads/master | 2021-01-10T05:47:58.255511 | 2017-12-22T17:57:14 | 2017-12-22T17:57:14 | 51,027,037 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 256 | hpp | /*
* make.hpp
*
* Created on: 22.02.2015
* Author: mike_gresens
*/
#pragma once
#include "description.hpp"
#include "instance.hpp"
namespace rt {
namespace scene {
namespace object {
instance_t
make(const description_t& description);
}
}
}
| [
"mike_gresens@notebook"
] | mike_gresens@notebook |
af3037dbbcd012b90cb644281d16204cdceba83a | 9d0001b4035a61a31aba84de99966aa40adb4643 | /src/rtavis.cpp | 521db0cd5edb3082565719f2d59215f789112e03 | [
"MIT"
] | permissive | tiantianhan/rtavis | 4548833374cbea4c8cf0b8b792b0d5a1a762a17f | 325cbe22b28b98924cf8ff0dd6444e39bea1e17d | refs/heads/master | 2023-05-13T02:45:04.728165 | 2021-06-10T12:33:17 | 2021-06-10T12:33:17 | 285,031,941 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,403 | cpp | /**
* @file rtavis.cpp
* @author tina
* @brief Raytracer practice project based on the "Raytracing in One Weekend"
* series by Peter Shirley https://raytracing.github.io/
* @version 0.2
* @date 2021-05-30
*
* @copyright https://opensource.org/licenses/MIT
*
* Loads a file of sphere model information and render as ppm file.
*
*/
#include <iostream>
#include <fstream>
#include <cstring>
#include "..\tests\test.hpp"
#include "raytracer.hpp"
#include "utils\timer.hpp"
#include "io\load_obj.hpp"
// Inputs
struct main_inputs{
std::string in_file_path;
size_t image_width;
size_t image_height;
std::string out_file_path;
double aspect_ratio;
size_t samples_per_pixel;
size_t max_ray_recursion_depth;
};
// Defaults
const std::string default_input_file = "";
const std::string default_output_file = "rtavis_out.ppm";
const double default_aspect_ratio = 16.0 / 9.0;
const size_t default_samples_per_pixel = 3;
const size_t default_max_ray_recursion_depth = 10;
// Declarations
std::ostream& operator<<(std::ostream &out, const main_inputs& inputs);
bool parse_args(int argc, char *argv[], main_inputs& inputs);
void print_usage();
void set_default_args();
int main(int argc, char *argv[]){
// Parse inputs
main_inputs inputs;
bool is_success = parse_args(argc, argv, inputs);
if(!is_success){
print_usage();
std::cerr << "Error parsing arguments, exiting.\n";
return 1;
}
std::cout << "Got inputs: \n" << inputs << "\n\n";
// Output file
std::cout << "Opening output file...\n";
std::ofstream out_image;
out_image.open(inputs.out_file_path);
if(out_image.is_open() == false)
std::cout << "Failed to open output file " << inputs.out_file_path << "\n";
// Input file
std::cout << "Opening input file...\n";
std::ifstream in_file;
in_file.open(inputs.in_file_path);
if(in_file.is_open() == false)
std::cout << "Failed to open input file " << inputs.in_file_path << "\n";
// Setup raytracer
Raytracer raytracer(inputs.image_width, inputs.image_height);
raytracer.samples_per_pixel = inputs.samples_per_pixel;
raytracer.max_ray_recursion_depth = inputs.max_ray_recursion_depth;
// Load
if(in_file.is_open() == false){
raytracer.load_default_world();
} else {
raytracer.load(in_file);
}
// Render
Timer render_timer;
raytracer.render(out_image);
std::cout << "Render time: " << render_timer << "\n";
// Test // TODO: Write more tests?
//std::cout << "\nTesting load obj file...\n";
//tiny_obj_loader_test(inputs.in_file_path);
// test();
in_file.close();
out_image.close();
std::cout << "All done.\n";
return 0;
}
// Argument parsing helpers
std::ostream& operator<<(std::ostream &out, const main_inputs& inputs){
return out << "Input file path: " << inputs.in_file_path << "\n"
<< "Output file path: " << inputs.out_file_path << "\n"
<< "Image size: " << inputs.image_width << " x "
<< inputs.image_height << " "
<< "Aspect ratio: " << inputs.aspect_ratio << "\n"
<< "Samples per pixel: " << inputs.samples_per_pixel << "\n"
<< "Max recursion depth: " << inputs.max_ray_recursion_depth;
}
void print_usage(){
std::cerr << "Usage: rtavis image_width "
<< "[-i in_file_path]"
<< "[-o out_file_path]"
<< "[-spp samples_per_pixel] "
<< "[-depth max_ray_recursion_depth]\n";
}
void set_default_args(main_inputs &inputs){
inputs.in_file_path = default_input_file;
inputs.out_file_path = default_output_file;
std::cout << "Using default aspect ratio\n";
inputs.aspect_ratio = default_aspect_ratio;
inputs.image_height = round(inputs.image_width / inputs.aspect_ratio);
inputs.samples_per_pixel = default_samples_per_pixel;
inputs.max_ray_recursion_depth = default_max_ray_recursion_depth;
}
//Parse arguments. Returns true if successful and false if not successful.
bool parse_args(int argc, char *argv[], main_inputs& inputs){
const int opt_arg_start = 2;
const int total_arg = 10;
// Check number of arguments
if(argc < opt_arg_start || argc > total_arg){
return false;
}
// Arguments
int temp_width = atoi(argv[1]);
if(temp_width <= 0){
std::cerr << "Width should be an integer > 0\n";
return false;
}
inputs.image_width = temp_width;
// Defaults
set_default_args(inputs);
// Optional arguments
for(int i = opt_arg_start; i < argc; i+=2){
if((i + 1) >= argc) break;
if(strcmp(argv[i], "-i") == 0){
inputs.in_file_path = std::string(argv[i + 1]);
} else if(strcmp(argv[i], "-o") == 0){
inputs.out_file_path = std::string(argv[i + 1]);
} else if(strcmp(argv[i], "-spp") == 0){
int temp_smp = atoi(argv[i + 1]);
if(temp_smp <= 0){
std::cerr << "Samples per pixel should be an integer >= 1, using default.\n";
} else {
inputs.samples_per_pixel = temp_smp;
}
} else if(strcmp(argv[i], "-depth") == 0){
int temp_maxr = atoi(argv[i + 1]);
if(temp_maxr <= 0){
std::cerr << "Max recursion depth should be an integer >= 1, using default.\n";
} else {
inputs.max_ray_recursion_depth = temp_maxr;
}
} else {
std::cerr << argv[i] << " is not recognized flag\n";
return false;
}
}
return true;
} | [
"tina.han.tiantian@gmail.com"
] | tina.han.tiantian@gmail.com |
773626907369c5ea8ebd4a13f1d339a9eb69f100 | 089985f5f295d6fc9b4d9a92cddb4d07cdc50c86 | /iOS/PrivateFrameworks/iWorkImport.framework/Frameworks/EquationKit.framework/Frameworks/KeynoteQuicklook.framework/Frameworks/NumbersQuicklook.framework/Frameworks/PagesQuicklook.framework/CDStructures.h | 88028f597d692f1e254eabb4873360324b20a977 | [] | no_license | lawrence-liuyue/Apple-Runtime-Headers | 6035855edbf558300c62bcf77c77cc38fcd08305 | 5e50ad05dfd7d7b69fc2e0e685765fc054166b3c | refs/heads/master | 2022-12-05T19:04:26.333712 | 2020-08-28T16:48:15 | 2020-08-28T16:48:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,408 | h | //
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Oct 15 2018 10:31:50).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#pragma mark Blocks
typedef void (^CDUnknownBlockType)(void); // return type and parameters are unknown
#pragma mark Named Structures
struct CGAffineTransform {
double a;
double b;
double c;
double d;
double tx;
double ty;
};
struct CGPoint {
double x;
double y;
};
struct CGRect {
struct CGPoint origin;
struct CGSize size;
};
struct CGSize {
double width;
double height;
};
struct TPSectionEnumerator {
id _field1;
unsigned long long _field2;
struct _NSRange _field3;
struct _NSRange _field4;
};
struct _NSRange {
unsigned long long location;
unsigned long long length;
};
struct __tree_end_node<std::__1::__tree_node_base<void *>*> {
struct __tree_node_base<void *> *__left_;
};
struct multimap<unsigned long, TPPageLayout *, std::__1::less<unsigned long>, std::__1::allocator<std::__1::pair<const unsigned long, TPPageLayout *>>> {
struct __tree<std::__1::__value_type<unsigned long, TPPageLayout *>, std::__1::__map_value_compare<unsigned long, std::__1::__value_type<unsigned long, TPPageLayout *>, std::__1::less<unsigned long>, true>, std::__1::allocator<std::__1::__value_type<unsigned long, TPPageLayout *>>> {
struct __tree_end_node<std::__1::__tree_node_base<void *>*> *__begin_node_;
struct __compressed_pair<std::__1::__tree_end_node<std::__1::__tree_node_base<void *>*>, std::__1::allocator<std::__1::__tree_node<std::__1::__value_type<unsigned long, TPPageLayout *>, void *>>> {
struct __tree_end_node<std::__1::__tree_node_base<void *>*> __value_;
} __pair1_;
struct __compressed_pair<unsigned long, std::__1::__map_value_compare<unsigned long, std::__1::__value_type<unsigned long, TPPageLayout *>, std::__1::less<unsigned long>, true>> {
unsigned long long __value_;
} __pair3_;
} __tree_;
};
struct pair<double, double> {
double _field1;
double _field2;
};
#pragma mark Typedef'd Structures
// Template types
typedef struct multimap<unsigned long, TPPageLayout *, std::__1::less<unsigned long>, std::__1::allocator<std::__1::pair<const unsigned long, TPPageLayout *>>> {
struct __tree<std::__1::__value_type<unsigned long, TPPageLayout *>, std::__1::__map_value_compare<unsigned long, std::__1::__value_type<unsigned long, TPPageLayout *>, std::__1::less<unsigned long>, true>, std::__1::allocator<std::__1::__value_type<unsigned long, TPPageLayout *>>> {
struct __tree_end_node<std::__1::__tree_node_base<void *>*> *__begin_node_;
struct __compressed_pair<std::__1::__tree_end_node<std::__1::__tree_node_base<void *>*>, std::__1::allocator<std::__1::__tree_node<std::__1::__value_type<unsigned long, TPPageLayout *>, void *>>> {
struct __tree_end_node<std::__1::__tree_node_base<void *>*> __value_;
} __pair1_;
struct __compressed_pair<unsigned long, std::__1::__map_value_compare<unsigned long, std::__1::__value_type<unsigned long, TPPageLayout *>, std::__1::less<unsigned long>, true>> {
unsigned long long __value_;
} __pair3_;
} __tree_;
} multimap_41f9c887;
typedef struct pair<double, double> {
double _field1;
double _field2;
} pair_b2618ff2;
| [
"leo.natan@outlook.com"
] | leo.natan@outlook.com |
9b19c521481e32d73eebadfe55e9e60f5f0a31d6 | 6bc516189b66e17a9395ce676926ba74ea72f2f9 | /Competitive Programming 3/Chapter 2/1DArray/UVA755.cpp | 926c14b2755962014f5672bf6620abec6eb66e16 | [] | no_license | michaelzhiluo/UVA-Online-Judge | 1b1915af75e2f24b53715cfc4269631e289a78e0 | 1e653b79a3fa0f8161763899023c3ae2635ab328 | refs/heads/master | 2021-01-17T18:10:58.760890 | 2017-07-20T09:02:47 | 2017-07-20T09:02:47 | 71,186,964 | 2 | 1 | null | 2016-10-18T06:05:54 | 2016-10-17T22:35:42 | Java | UTF-8 | C++ | false | false | 1,638 | cpp | #include <iostream>
#include <bits/stdc++.h>
using namespace std;
string convertToString(char* c){
string answer = "";
for(int i=0; i<strlen(c); i++){
int x = (int)c[i];
if(x >= 48 && x<=57){
answer+=c[i];
}else if(x>=65 && x<= 67){
answer+='2';
}else if(x>=68 && x<= 70){
answer+='3';
}else if(x>=71 && x<= 73){
answer+='4';
}else if(x>=74 && x<= 76){
answer+='5';
}else if(x>=77 && x<= 79){
answer+='6';
}else if(x>=80 && x<= 83 && x!=81){
answer+='7';
}else if(x>=84 && x<= 86){
answer+='8';
}else if(x>=87 && x<= 89){
answer+='9';
}
}
return answer.substr(0, 3) + "-" + answer.substr(3);
}
bool pairCompare(pair<string, int>& firstElem, pair<string, int>& secondElem){
return firstElem.first < secondElem.first;
}
int main(){
int TC, length;
char c[1000];
scanf("%d", &TC);
map<string, int> phonenumber;
vector< pair<string, int> > answer;
loop:
while(TC--){
answer.clear();
phonenumber.clear();
scanf("%d\n", &length);
while(length--){
fgets(c, 1000, stdin);
string temp = convertToString(c);
if(phonenumber.find(temp) == phonenumber.end()){
phonenumber[temp] = 1;
}else{
phonenumber[temp]++;
}
}
for(map<string, int>::iterator i = phonenumber.begin(); i!= phonenumber.end(); i++){
if(i->second>1){
answer.push_back(make_pair(i->first, i->second));
}
}
sort(answer.begin(), answer.end(), pairCompare);
for(int i=0; i<answer.size(); i++){
printf("%s %d\n", answer[i].first.c_str(), answer[i].second);
}
if(answer.size() ==0){
printf("No duplicates.\n");
}
if(TC){
printf("\n");
}
}
return 0;
} | [
"michael.luo@berkeley.edu"
] | michael.luo@berkeley.edu |
ba6d7c419415601f98a0d725e84be9c08b68b2fc | cf7cfaf8483150bdf38b393bfb43d8c3f33481d7 | /D3d8to9/d3d8to9_device.cpp | 7ddf0e35d718420c0d8d1659d73391b293355b60 | [
"Zlib"
] | permissive | StanleyRS/dxwrapper | 4d084101c6feb985d2815827820154693c7147c4 | ba53b5987e04d8d9bf21f5879ee07d3ffbfa1495 | refs/heads/master | 2020-03-21T04:48:59.287489 | 2018-06-20T06:49:26 | 2018-06-20T06:49:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 72,268 | cpp | /**
* Copyright (C) 2015 Patrick Mours. All rights reserved.
* License: https://github.com/crosire/d3d8to9#license
*/
#include "d3dx9.hpp"
#include "d3d8to9.hpp"
#include <regex>
#include <assert.h>
struct VertexShaderInfo
{
IDirect3DVertexShader9 *Shader;
IDirect3DVertexDeclaration9 *Declaration;
};
// IDirect3DDevice8
Direct3DDevice8::Direct3DDevice8(Direct3D8 *d3d, IDirect3DDevice9 *ProxyInterface, BOOL EnableZBufferDiscarding) :
D3D(d3d), ProxyInterface(ProxyInterface), ZBufferDiscarding(EnableZBufferDiscarding)
{
ProxyAddressLookupTable = new AddressLookupTable(this);
PaletteFlag = SupportsPalettes();
}
Direct3DDevice8::~Direct3DDevice8()
{
delete ProxyAddressLookupTable;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::QueryInterface(REFIID riid, void **ppvObj)
{
if (ppvObj == nullptr)
{
return E_POINTER;
}
if (riid == __uuidof(this) ||
riid == __uuidof(IUnknown))
{
AddRef();
*ppvObj = this;
return S_OK;
}
return ProxyInterface->QueryInterface(riid, ppvObj);
}
ULONG STDMETHODCALLTYPE Direct3DDevice8::AddRef()
{
return ProxyInterface->AddRef();
}
ULONG STDMETHODCALLTYPE Direct3DDevice8::Release()
{
ULONG LastRefCount = ProxyInterface->Release();
if (LastRefCount == 0)
{
delete this;
}
return LastRefCount;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::TestCooperativeLevel()
{
return ProxyInterface->TestCooperativeLevel();
}
UINT STDMETHODCALLTYPE Direct3DDevice8::GetAvailableTextureMem()
{
return ProxyInterface->GetAvailableTextureMem();
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::ResourceManagerDiscardBytes(DWORD Bytes)
{
UNREFERENCED_PARAMETER(Bytes);
return ProxyInterface->EvictManagedResources();
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetDirect3D(Direct3D8 **ppD3D8)
{
if (ppD3D8 == nullptr)
{
return D3DERR_INVALIDCALL;
}
D3D->AddRef();
*ppD3D8 = D3D;
return D3D_OK;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetDeviceCaps(D3DCAPS8 *pCaps)
{
if (pCaps == nullptr)
{
return D3DERR_INVALIDCALL;
}
D3DCAPS9 DeviceCaps;
const HRESULT hr = ProxyInterface->GetDeviceCaps(&DeviceCaps);
if (FAILED(hr))
{
return hr;
}
ConvertCaps(DeviceCaps, *pCaps);
return D3D_OK;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetDisplayMode(D3DDISPLAYMODE *pMode)
{
return ProxyInterface->GetDisplayMode(0, pMode);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetCreationParameters(D3DDEVICE_CREATION_PARAMETERS *pParameters)
{
return ProxyInterface->GetCreationParameters(pParameters);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::SetCursorProperties(UINT XHotSpot, UINT YHotSpot, Direct3DSurface8 *pCursorBitmap)
{
if (pCursorBitmap == nullptr)
{
return D3DERR_INVALIDCALL;
}
return ProxyInterface->SetCursorProperties(XHotSpot, YHotSpot, pCursorBitmap->GetProxyInterface());
}
void STDMETHODCALLTYPE Direct3DDevice8::SetCursorPosition(UINT XScreenSpace, UINT YScreenSpace, DWORD Flags)
{
ProxyInterface->SetCursorPosition(XScreenSpace, YScreenSpace, Flags);
}
BOOL STDMETHODCALLTYPE Direct3DDevice8::ShowCursor(BOOL bShow)
{
return ProxyInterface->ShowCursor(bShow);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::CreateAdditionalSwapChain(D3DPRESENT_PARAMETERS8 *pPresentationParameters, Direct3DSwapChain8 **ppSwapChain)
{
#ifndef D3D8TO9NOLOG
LOG << "Redirecting '" << "IDirect3DDevice8::CreateAdditionalSwapChain" << "(" << this << ", " << pPresentationParameters << ", " << ppSwapChain << ")' ..." << std::endl;
#endif
if (pPresentationParameters == nullptr || ppSwapChain == nullptr)
{
return D3DERR_INVALIDCALL;
}
*ppSwapChain = nullptr;
D3DPRESENT_PARAMETERS PresentParams;
ConvertPresentParameters(*pPresentationParameters, PresentParams);
// Get multisample quality level
if (PresentParams.MultiSampleType != D3DMULTISAMPLE_NONE)
{
DWORD QualityLevels = 0;
D3DDEVICE_CREATION_PARAMETERS CreationParams;
ProxyInterface->GetCreationParameters(&CreationParams);
if (D3D->GetProxyInterface()->CheckDeviceMultiSampleType(CreationParams.AdapterOrdinal,
CreationParams.DeviceType, PresentParams.BackBufferFormat, PresentParams.Windowed,
PresentParams.MultiSampleType, &QualityLevels) == S_OK &&
D3D->GetProxyInterface()->CheckDeviceMultiSampleType(CreationParams.AdapterOrdinal,
CreationParams.DeviceType, PresentParams.AutoDepthStencilFormat, PresentParams.Windowed,
PresentParams.MultiSampleType, &QualityLevels) == S_OK)
{
PresentParams.MultiSampleQuality = (QualityLevels != 0) ? QualityLevels - 1 : 0;
}
}
IDirect3DSwapChain9 *SwapChainInterface = nullptr;
const HRESULT hr = ProxyInterface->CreateAdditionalSwapChain(&PresentParams, &SwapChainInterface);
if (FAILED(hr))
{
return hr;
}
*ppSwapChain = new Direct3DSwapChain8(this, SwapChainInterface);
return D3D_OK;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::Reset(D3DPRESENT_PARAMETERS8 *pPresentationParameters)
{
#ifndef D3D8TO9NOLOG
LOG << "Redirecting '" << "IDirect3DDevice8::Reset" << "(" << this << ", " << pPresentationParameters << ")' ..." << std::endl;
#endif
if (pPresentationParameters == nullptr)
{
return D3DERR_INVALIDCALL;
}
D3DPRESENT_PARAMETERS PresentParams;
ConvertPresentParameters(*pPresentationParameters, PresentParams);
// Get multisample quality level
if (PresentParams.MultiSampleType != D3DMULTISAMPLE_NONE)
{
DWORD QualityLevels = 0;
D3DDEVICE_CREATION_PARAMETERS CreationParams;
ProxyInterface->GetCreationParameters(&CreationParams);
if (D3D->GetProxyInterface()->CheckDeviceMultiSampleType(CreationParams.AdapterOrdinal,
CreationParams.DeviceType, PresentParams.BackBufferFormat, PresentParams.Windowed,
PresentParams.MultiSampleType, &QualityLevels) == S_OK &&
D3D->GetProxyInterface()->CheckDeviceMultiSampleType(CreationParams.AdapterOrdinal,
CreationParams.DeviceType, PresentParams.AutoDepthStencilFormat, PresentParams.Windowed,
PresentParams.MultiSampleType, &QualityLevels) == S_OK)
{
PresentParams.MultiSampleQuality = (QualityLevels != 0) ? QualityLevels - 1 : 0;
}
}
return ProxyInterface->Reset(&PresentParams);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::Present(const RECT *pSourceRect, const RECT *pDestRect, HWND hDestWindowOverride, const RGNDATA *pDirtyRegion)
{
UNREFERENCED_PARAMETER(pDirtyRegion);
return ProxyInterface->Present(pSourceRect, pDestRect, hDestWindowOverride, nullptr);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetBackBuffer(UINT iBackBuffer, D3DBACKBUFFER_TYPE Type, Direct3DSurface8 **ppBackBuffer)
{
if (ppBackBuffer == nullptr)
{
return D3DERR_INVALIDCALL;
}
*ppBackBuffer = nullptr;
IDirect3DSurface9 *SurfaceInterface = nullptr;
const HRESULT hr = ProxyInterface->GetBackBuffer(0, iBackBuffer, Type, &SurfaceInterface);
if (FAILED(hr))
{
return hr;
}
*ppBackBuffer = ProxyAddressLookupTable->FindAddress<Direct3DSurface8>(SurfaceInterface);
return D3D_OK;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetRasterStatus(D3DRASTER_STATUS *pRasterStatus)
{
return ProxyInterface->GetRasterStatus(0, pRasterStatus);
}
void STDMETHODCALLTYPE Direct3DDevice8::SetGammaRamp(DWORD Flags, const D3DGAMMARAMP *pRamp)
{
ProxyInterface->SetGammaRamp(0, Flags, pRamp);
}
void STDMETHODCALLTYPE Direct3DDevice8::GetGammaRamp(D3DGAMMARAMP *pRamp)
{
ProxyInterface->GetGammaRamp(0, pRamp);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::CreateTexture(UINT Width, UINT Height, UINT Levels, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, Direct3DTexture8 **ppTexture)
{
if (ppTexture == nullptr)
{
return D3DERR_INVALIDCALL;
}
*ppTexture = nullptr;
if (Pool == D3DPOOL_DEFAULT)
{
D3DDEVICE_CREATION_PARAMETERS CreationParams;
ProxyInterface->GetCreationParameters(&CreationParams);
if ((Usage & D3DUSAGE_DYNAMIC) == 0 &&
SUCCEEDED(D3D->GetProxyInterface()->CheckDeviceFormat(CreationParams.AdapterOrdinal, CreationParams.DeviceType, D3DFMT_X8R8G8B8, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE, Format)))
{
Usage |= D3DUSAGE_RENDERTARGET;
}
else if (Usage != D3DUSAGE_DEPTHSTENCIL)
{
Usage |= D3DUSAGE_DYNAMIC;
}
}
IDirect3DTexture9 *TextureInterface = nullptr;
const HRESULT hr = ProxyInterface->CreateTexture(Width, Height, Levels, Usage, Format, Pool, &TextureInterface, nullptr);
if (FAILED(hr))
{
return hr;
}
*ppTexture = new Direct3DTexture8(this, TextureInterface);
return D3D_OK;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::CreateVolumeTexture(UINT Width, UINT Height, UINT Depth, UINT Levels, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, Direct3DVolumeTexture8 **ppVolumeTexture)
{
if (ppVolumeTexture == nullptr)
{
return D3DERR_INVALIDCALL;
}
*ppVolumeTexture = nullptr;
IDirect3DVolumeTexture9 *TextureInterface = nullptr;
const HRESULT hr = ProxyInterface->CreateVolumeTexture(Width, Height, Depth, Levels, Usage, Format, Pool, &TextureInterface, nullptr);
if (FAILED(hr))
{
return hr;
}
*ppVolumeTexture = new Direct3DVolumeTexture8(this, TextureInterface);
return D3D_OK;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::CreateCubeTexture(UINT EdgeLength, UINT Levels, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, Direct3DCubeTexture8 **ppCubeTexture)
{
if (ppCubeTexture == nullptr)
{
return D3DERR_INVALIDCALL;
}
*ppCubeTexture = nullptr;
IDirect3DCubeTexture9 *TextureInterface = nullptr;
const HRESULT hr = ProxyInterface->CreateCubeTexture(EdgeLength, Levels, Usage, Format, Pool, &TextureInterface, nullptr);
if (FAILED(hr))
{
return hr;
}
*ppCubeTexture = new Direct3DCubeTexture8(this, TextureInterface);
return D3D_OK;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::CreateVertexBuffer(UINT Length, DWORD Usage, DWORD FVF, D3DPOOL Pool, Direct3DVertexBuffer8 **ppVertexBuffer)
{
if (ppVertexBuffer == nullptr)
{
return D3DERR_INVALIDCALL;
}
*ppVertexBuffer = nullptr;
IDirect3DVertexBuffer9 *BufferInterface = nullptr;
const HRESULT hr = ProxyInterface->CreateVertexBuffer(Length, Usage, FVF, Pool, &BufferInterface, nullptr);
if (FAILED(hr))
{
return hr;
}
*ppVertexBuffer = new Direct3DVertexBuffer8(this, BufferInterface);
return D3D_OK;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::CreateIndexBuffer(UINT Length, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, Direct3DIndexBuffer8 **ppIndexBuffer)
{
if (ppIndexBuffer == nullptr)
{
return D3DERR_INVALIDCALL;
}
*ppIndexBuffer = nullptr;
IDirect3DIndexBuffer9 *BufferInterface = nullptr;
const HRESULT hr = ProxyInterface->CreateIndexBuffer(Length, Usage, Format, Pool, &BufferInterface, nullptr);
if (FAILED(hr))
{
return hr;
}
*ppIndexBuffer = new Direct3DIndexBuffer8(this, BufferInterface);
return D3D_OK;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::CreateRenderTarget(UINT Width, UINT Height, D3DFORMAT Format, D3DMULTISAMPLE_TYPE MultiSample, BOOL Lockable, Direct3DSurface8 **ppSurface)
{
if (ppSurface == nullptr)
{
return D3DERR_INVALIDCALL;
}
*ppSurface = nullptr;
DWORD QualityLevels = 0;
// Get multisample quality level
if (MultiSample != D3DMULTISAMPLE_NONE)
{
D3DDEVICE_CREATION_PARAMETERS CreationParams;
ProxyInterface->GetCreationParameters(&CreationParams);
D3D->GetProxyInterface()->CheckDeviceMultiSampleType(CreationParams.AdapterOrdinal, CreationParams.DeviceType, Format, FALSE, MultiSample, &QualityLevels);
QualityLevels = (QualityLevels != 0) ? QualityLevels - 1 : 0;
}
IDirect3DSurface9 *SurfaceInterface = nullptr;
HRESULT hr = ProxyInterface->CreateRenderTarget(Width, Height, Format, MultiSample, QualityLevels, Lockable, &SurfaceInterface, nullptr);
if (FAILED(hr))
{
return hr;
}
pCurrentRenderTarget = SurfaceInterface;
*ppSurface = new Direct3DSurface8(this, SurfaceInterface);
return D3D_OK;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::CreateDepthStencilSurface(UINT Width, UINT Height, D3DFORMAT Format, D3DMULTISAMPLE_TYPE MultiSample, Direct3DSurface8 **ppSurface)
{
if (ppSurface == nullptr)
{
return D3DERR_INVALIDCALL;
}
*ppSurface = nullptr;
DWORD QualityLevels = 0;
// Get multisample quality level
if (MultiSample != D3DMULTISAMPLE_NONE)
{
D3DDEVICE_CREATION_PARAMETERS CreationParams;
ProxyInterface->GetCreationParameters(&CreationParams);
D3D->GetProxyInterface()->CheckDeviceMultiSampleType(CreationParams.AdapterOrdinal, CreationParams.DeviceType, Format, FALSE, MultiSample, &QualityLevels);
QualityLevels = (QualityLevels != 0) ? QualityLevels - 1 : 0;
}
IDirect3DSurface9 *SurfaceInterface = nullptr;
HRESULT hr = ProxyInterface->CreateDepthStencilSurface(Width, Height, Format, MultiSample, QualityLevels, ZBufferDiscarding, &SurfaceInterface, nullptr);
if (FAILED(hr))
{
return hr;
}
*ppSurface = new Direct3DSurface8(this, SurfaceInterface);
return D3D_OK;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::CreateImageSurface(UINT Width, UINT Height, D3DFORMAT Format, Direct3DSurface8 **ppSurface)
{
#ifndef D3D8TO9NOLOG
LOG << "Redirecting '" << "IDirect3DDevice8::CreateImageSurface" << "(" << this << ", " << Width << ", " << Height << ", " << Format << ", " << ppSurface << ")' ..." << std::endl;
#endif
if (ppSurface == nullptr)
{
return D3DERR_INVALIDCALL;
}
*ppSurface = nullptr;
if (Format == D3DFMT_R8G8B8)
{
#ifndef D3D8TO9NOLOG
LOG << "> Replacing format 'D3DFMT_R8G8B8' with 'D3DFMT_X8R8G8B8' ..." << std::endl;
#endif
Format = D3DFMT_X8R8G8B8;
}
IDirect3DSurface9 *SurfaceInterface = nullptr;
const HRESULT hr = ProxyInterface->CreateOffscreenPlainSurface(Width, Height, Format, D3DPOOL_SYSTEMMEM, &SurfaceInterface, nullptr);
if (FAILED(hr))
{
#ifndef D3D8TO9NOLOG
LOG << "> 'IDirect3DDevice9::CreateOffscreenPlainSurface' failed with error code " << std::hex << hr << std::dec << "!" << std::endl;
#endif
return hr;
}
*ppSurface = new Direct3DSurface8(this, SurfaceInterface);
return D3D_OK;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::CopyRects(Direct3DSurface8 *pSourceSurface, const RECT *pSourceRectsArray, UINT cRects, Direct3DSurface8 *pDestinationSurface, const POINT *pDestPointsArray)
{
if (pSourceSurface == nullptr || pDestinationSurface == nullptr || pSourceSurface == pDestinationSurface)
{
return D3DERR_INVALIDCALL;
}
D3DSURFACE_DESC SourceDesc, DestinationDesc;
pSourceSurface->GetProxyInterface()->GetDesc(&SourceDesc);
pDestinationSurface->GetProxyInterface()->GetDesc(&DestinationDesc);
if (SourceDesc.Format != DestinationDesc.Format)
{
return D3DERR_INVALIDCALL;
}
HRESULT hr = D3DERR_INVALIDCALL;
if (cRects == 0)
{
cRects = 1;
}
for (UINT i = 0; i < cRects; i++)
{
RECT SourceRect, DestinationRect;
if (pSourceRectsArray != nullptr)
{
SourceRect = pSourceRectsArray[i];
}
else
{
SourceRect.left = 0;
SourceRect.right = SourceDesc.Width;
SourceRect.top = 0;
SourceRect.bottom = SourceDesc.Height;
}
if (pDestPointsArray != nullptr)
{
DestinationRect.left = pDestPointsArray[i].x;
DestinationRect.right = DestinationRect.left + (SourceRect.right - SourceRect.left);
DestinationRect.top = pDestPointsArray[i].y;
DestinationRect.bottom = DestinationRect.top + (SourceRect.bottom - SourceRect.top);
}
else
{
DestinationRect = SourceRect;
}
if (SourceDesc.Pool == D3DPOOL_MANAGED || DestinationDesc.Pool != D3DPOOL_DEFAULT)
{
if (D3DXLoadSurfaceFromSurface != nullptr)
{
hr = D3DXLoadSurfaceFromSurface(pDestinationSurface->GetProxyInterface(), nullptr, &DestinationRect, pSourceSurface->GetProxyInterface(), nullptr, &SourceRect, D3DX_FILTER_NONE, 0);
}
else
{
hr = D3DERR_INVALIDCALL;
}
}
else if (SourceDesc.Pool == D3DPOOL_DEFAULT)
{
hr = ProxyInterface->StretchRect(pSourceSurface->GetProxyInterface(), &SourceRect, pDestinationSurface->GetProxyInterface(), &DestinationRect, D3DTEXF_NONE);
}
else if (SourceDesc.Pool == D3DPOOL_SYSTEMMEM)
{
const POINT pt = { DestinationRect.left, DestinationRect.top };
hr = ProxyInterface->UpdateSurface(pSourceSurface->GetProxyInterface(), &SourceRect, pDestinationSurface->GetProxyInterface(), &pt);
}
if (FAILED(hr))
{
#ifndef D3D8TO9NOLOG
LOG << "Failed to translate 'IDirect3DDevice8::CopyRects' call from '[" << SourceDesc.Width << "x" << SourceDesc.Height << ", " << SourceDesc.Format << ", " << SourceDesc.MultiSampleType << ", " << SourceDesc.Usage << ", " << SourceDesc.Pool << "]' to '[" << DestinationDesc.Width << "x" << DestinationDesc.Height << ", " << DestinationDesc.Format << ", " << DestinationDesc.MultiSampleType << ", " << DestinationDesc.Usage << ", " << DestinationDesc.Pool << "]'!" << std::endl;
#endif
break;
}
}
return hr;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::UpdateTexture(Direct3DBaseTexture8 *pSourceTexture, Direct3DBaseTexture8 *pDestinationTexture)
{
if (pSourceTexture == nullptr || pDestinationTexture == nullptr || pSourceTexture->GetType() != pDestinationTexture->GetType())
{
return D3DERR_INVALIDCALL;
}
IDirect3DBaseTexture9 *SourceBaseTextureInterface, *DestinationBaseTextureInterface;
switch (pSourceTexture->GetType())
{
case D3DRTYPE_TEXTURE:
SourceBaseTextureInterface = static_cast<Direct3DTexture8 *>(pSourceTexture)->GetProxyInterface();
DestinationBaseTextureInterface = static_cast<Direct3DTexture8 *>(pDestinationTexture)->GetProxyInterface();
break;
case D3DRTYPE_VOLUMETEXTURE:
SourceBaseTextureInterface = static_cast<Direct3DVolumeTexture8 *>(pSourceTexture)->GetProxyInterface();
DestinationBaseTextureInterface = static_cast<Direct3DVolumeTexture8 *>(pDestinationTexture)->GetProxyInterface();
break;
case D3DRTYPE_CUBETEXTURE:
SourceBaseTextureInterface = static_cast<Direct3DCubeTexture8 *>(pSourceTexture)->GetProxyInterface();
DestinationBaseTextureInterface = static_cast<Direct3DCubeTexture8 *>(pDestinationTexture)->GetProxyInterface();
break;
default:
return D3DERR_INVALIDCALL;
}
return ProxyInterface->UpdateTexture(SourceBaseTextureInterface, DestinationBaseTextureInterface);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetFrontBuffer(Direct3DSurface8 *pDestSurface)
{
if (pDestSurface == nullptr)
{
return D3DERR_INVALIDCALL;
}
return ProxyInterface->GetFrontBufferData(0, pDestSurface->GetProxyInterface());
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::SetRenderTarget(Direct3DSurface8 *pRenderTarget, Direct3DSurface8 *pNewZStencil)
{
HRESULT hr;
if (pRenderTarget != nullptr)
{
hr = ProxyInterface->SetRenderTarget(0, pRenderTarget->GetProxyInterface());
if (FAILED(hr))
{
return hr;
}
pCurrentRenderTarget = pRenderTarget->GetProxyInterface();
}
if (pNewZStencil != nullptr)
{
hr = ProxyInterface->SetDepthStencilSurface(pNewZStencil->GetProxyInterface());
if (FAILED(hr))
{
return hr;
}
}
else
{
ProxyInterface->SetDepthStencilSurface(nullptr);
}
return D3D_OK;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetRenderTarget(Direct3DSurface8 **ppRenderTarget)
{
if (ppRenderTarget == nullptr)
{
return D3DERR_INVALIDCALL;
}
IDirect3DSurface9 *SurfaceInterface = nullptr;
const HRESULT hr = ProxyInterface->GetRenderTarget(0, &SurfaceInterface);
if (FAILED(hr))
{
return hr;
}
pCurrentRenderTarget = SurfaceInterface;
*ppRenderTarget = ProxyAddressLookupTable->FindAddress<Direct3DSurface8>(SurfaceInterface);
return D3D_OK;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetDepthStencilSurface(Direct3DSurface8 **ppZStencilSurface)
{
if (ppZStencilSurface == nullptr)
{
return D3DERR_INVALIDCALL;
}
IDirect3DSurface9 *SurfaceInterface = nullptr;
const HRESULT hr = ProxyInterface->GetDepthStencilSurface(&SurfaceInterface);
if (FAILED(hr))
{
return hr;
}
*ppZStencilSurface = ProxyAddressLookupTable->FindAddress<Direct3DSurface8>(SurfaceInterface);
return D3D_OK;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::BeginScene()
{
return ProxyInterface->BeginScene();
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::EndScene()
{
return ProxyInterface->EndScene();
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::Clear(DWORD Count, const D3DRECT *pRects, DWORD Flags, D3DCOLOR Color, float Z, DWORD Stencil)
{
return ProxyInterface->Clear(Count, pRects, Flags, Color, Z, Stencil);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::SetTransform(D3DTRANSFORMSTATETYPE State, const D3DMATRIX *pMatrix)
{
return ProxyInterface->SetTransform(State, pMatrix);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetTransform(D3DTRANSFORMSTATETYPE State, D3DMATRIX *pMatrix)
{
return ProxyInterface->GetTransform(State, pMatrix);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::MultiplyTransform(D3DTRANSFORMSTATETYPE State, const D3DMATRIX *pMatrix)
{
return ProxyInterface->MultiplyTransform(State, pMatrix);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::SetViewport(const D3DVIEWPORT8 *pViewport)
{
if (pCurrentRenderTarget != nullptr)
{
D3DSURFACE_DESC Desc;
HRESULT hr = pCurrentRenderTarget->GetDesc(&Desc);
if (SUCCEEDED(hr) && (pViewport->Height > Desc.Height || pViewport->Width > Desc.Width))
{
return D3DERR_INVALIDCALL;
}
}
return ProxyInterface->SetViewport(pViewport);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetViewport(D3DVIEWPORT8 *pViewport)
{
return ProxyInterface->GetViewport(pViewport);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::SetMaterial(const D3DMATERIAL8 *pMaterial)
{
return ProxyInterface->SetMaterial(pMaterial);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetMaterial(D3DMATERIAL8 *pMaterial)
{
return ProxyInterface->GetMaterial(pMaterial);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::SetLight(DWORD Index, const D3DLIGHT8 *pLight)
{
return ProxyInterface->SetLight(Index, pLight);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetLight(DWORD Index, D3DLIGHT8 *pLight)
{
return ProxyInterface->GetLight(Index, pLight);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::LightEnable(DWORD Index, BOOL Enable)
{
return ProxyInterface->LightEnable(Index, Enable);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetLightEnable(DWORD Index, BOOL *pEnable)
{
return ProxyInterface->GetLightEnable(Index, pEnable);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::SetClipPlane(DWORD Index, const float *pPlane)
{
if (pPlane == nullptr || Index >= MAX_CLIP_PLANES) return D3DERR_INVALIDCALL;
memcpy(StoredClipPlanes[Index], pPlane, sizeof(StoredClipPlanes[0]));
return D3D_OK;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetClipPlane(DWORD Index, float *pPlane)
{
if (pPlane == nullptr || Index >= MAX_CLIP_PLANES) return D3DERR_INVALIDCALL;
memcpy(pPlane, StoredClipPlanes[Index], sizeof(StoredClipPlanes[0]));
return D3D_OK;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::SetRenderState(D3DRENDERSTATETYPE State, DWORD Value)
{
FLOAT Biased;
HRESULT hr;
switch (static_cast<DWORD>(State))
{
case D3DRS_LINEPATTERN:
case D3DRS_ZVISIBLE:
case D3DRS_EDGEANTIALIAS:
case D3DRS_PATCHSEGMENTS:
return D3DERR_INVALIDCALL;
case D3DRS_SOFTWAREVERTEXPROCESSING:
return D3D_OK;
case D3DRS_CLIPPLANEENABLE:
hr = ProxyInterface->SetRenderState(State, Value);
if (SUCCEEDED(hr))
{
ClipPlaneRenderState = Value;
}
return hr;
case D3DRS_ZBIAS:
Biased = static_cast<FLOAT>(Value) * -0.000005f;
Value = *reinterpret_cast<const DWORD *>(&Biased);
State = D3DRS_DEPTHBIAS;
default:
return ProxyInterface->SetRenderState(State, Value);
}
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetRenderState(D3DRENDERSTATETYPE State, DWORD *pValue)
{
if (pValue == nullptr)
{
return D3DERR_INVALIDCALL;
}
HRESULT hr;
*pValue = 0;
switch (static_cast<DWORD>(State))
{
case D3DRS_LINEPATTERN:
case D3DRS_ZVISIBLE:
case D3DRS_EDGEANTIALIAS:
return D3DERR_INVALIDCALL;
case D3DRS_ZBIAS:
hr = ProxyInterface->GetRenderState(D3DRS_DEPTHBIAS, pValue);
*pValue = static_cast<DWORD>(*reinterpret_cast<const FLOAT *>(pValue) * -500000.0f);
return hr;
case D3DRS_SOFTWAREVERTEXPROCESSING:
*pValue = ProxyInterface->GetSoftwareVertexProcessing();
return D3D_OK;
case D3DRS_PATCHSEGMENTS:
*pValue = 1;
return D3D_OK;
default:
return ProxyInterface->GetRenderState(State, pValue);
}
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::BeginStateBlock()
{
return ProxyInterface->BeginStateBlock();
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::EndStateBlock(DWORD *pToken)
{
if (pToken == nullptr)
{
return D3DERR_INVALIDCALL;
}
return ProxyInterface->EndStateBlock(reinterpret_cast<IDirect3DStateBlock9 **>(pToken));
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::ApplyStateBlock(DWORD Token)
{
if (Token == 0)
{
return D3DERR_INVALIDCALL;
}
return reinterpret_cast<IDirect3DStateBlock9 *>(Token)->Apply();
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::CaptureStateBlock(DWORD Token)
{
if (Token == 0)
{
return D3DERR_INVALIDCALL;
}
return reinterpret_cast<IDirect3DStateBlock9 *>(Token)->Capture();
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::DeleteStateBlock(DWORD Token)
{
if (Token == 0)
{
return D3DERR_INVALIDCALL;
}
reinterpret_cast<IDirect3DStateBlock9 *>(Token)->Release();
return D3D_OK;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::CreateStateBlock(D3DSTATEBLOCKTYPE Type, DWORD *pToken)
{
#ifndef D3D8TO9NOLOG
LOG << "Redirecting '" << "IDirect3DDevice8::CreateStateBlock" << "(" << Type << ", " << pToken << ")' ..." << std::endl;
#endif
if (pToken == nullptr)
{
return D3DERR_INVALIDCALL;
}
return ProxyInterface->CreateStateBlock(Type, reinterpret_cast<IDirect3DStateBlock9 **>(pToken));
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::SetClipStatus(const D3DCLIPSTATUS8 *pClipStatus)
{
return ProxyInterface->SetClipStatus(pClipStatus);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetClipStatus(D3DCLIPSTATUS8 *pClipStatus)
{
return ProxyInterface->GetClipStatus(pClipStatus);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetTexture(DWORD Stage, Direct3DBaseTexture8 **ppTexture)
{
if (ppTexture == nullptr)
{
return D3DERR_INVALIDCALL;
}
*ppTexture = nullptr;
IDirect3DBaseTexture9 *BaseTextureInterface = nullptr;
const HRESULT hr = ProxyInterface->GetTexture(Stage, &BaseTextureInterface);
if (FAILED(hr))
{
return hr;
}
if (BaseTextureInterface != nullptr)
{
IDirect3DTexture9 *TextureInterface = nullptr;
IDirect3DCubeTexture9 *CubeTextureInterface = nullptr;
IDirect3DVolumeTexture9 *VolumeTextureInterface = nullptr;
switch (BaseTextureInterface->GetType())
{
case D3DRTYPE_TEXTURE:
BaseTextureInterface->QueryInterface(IID_PPV_ARGS(&TextureInterface));
*ppTexture = ProxyAddressLookupTable->FindAddress<Direct3DTexture8>(TextureInterface);
break;
case D3DRTYPE_VOLUMETEXTURE:
BaseTextureInterface->QueryInterface(IID_PPV_ARGS(&VolumeTextureInterface));
*ppTexture = ProxyAddressLookupTable->FindAddress<Direct3DVolumeTexture8>(VolumeTextureInterface);
break;
case D3DRTYPE_CUBETEXTURE:
BaseTextureInterface->QueryInterface(IID_PPV_ARGS(&CubeTextureInterface));
*ppTexture = ProxyAddressLookupTable->FindAddress<Direct3DCubeTexture8>(CubeTextureInterface);
break;
default:
return D3DERR_INVALIDCALL;
}
}
return D3D_OK;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::SetTexture(DWORD Stage, Direct3DBaseTexture8 *pTexture)
{
if (pTexture == nullptr)
{
return ProxyInterface->SetTexture(Stage, nullptr);
}
IDirect3DBaseTexture9 *BaseTextureInterface;
switch (pTexture->GetType())
{
case D3DRTYPE_TEXTURE:
BaseTextureInterface = static_cast<Direct3DTexture8 *>(pTexture)->GetProxyInterface();
break;
case D3DRTYPE_VOLUMETEXTURE:
BaseTextureInterface = static_cast<Direct3DVolumeTexture8 *>(pTexture)->GetProxyInterface();
break;
case D3DRTYPE_CUBETEXTURE:
BaseTextureInterface = static_cast<Direct3DCubeTexture8 *>(pTexture)->GetProxyInterface();
break;
default:
return D3DERR_INVALIDCALL;
}
return ProxyInterface->SetTexture(Stage, BaseTextureInterface);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetTextureStageState(DWORD Stage, D3DTEXTURESTAGESTATETYPE Type, DWORD *pValue)
{
switch (static_cast<DWORD>(Type))
{
case D3DTSS_ADDRESSU:
return ProxyInterface->GetSamplerState(Stage, D3DSAMP_ADDRESSU, pValue);
case D3DTSS_ADDRESSV:
return ProxyInterface->GetSamplerState(Stage, D3DSAMP_ADDRESSV, pValue);
case D3DTSS_ADDRESSW:
return ProxyInterface->GetSamplerState(Stage, D3DSAMP_ADDRESSW, pValue);
case D3DTSS_BORDERCOLOR:
return ProxyInterface->GetSamplerState(Stage, D3DSAMP_BORDERCOLOR, pValue);
case D3DTSS_MAGFILTER:
return ProxyInterface->GetSamplerState(Stage, D3DSAMP_MAGFILTER, pValue);
case D3DTSS_MINFILTER:
return ProxyInterface->GetSamplerState(Stage, D3DSAMP_MINFILTER, pValue);
case D3DTSS_MIPFILTER:
return ProxyInterface->GetSamplerState(Stage, D3DSAMP_MIPFILTER, pValue);
case D3DTSS_MIPMAPLODBIAS:
return ProxyInterface->GetSamplerState(Stage, D3DSAMP_MIPMAPLODBIAS, pValue);
case D3DTSS_MAXMIPLEVEL:
return ProxyInterface->GetSamplerState(Stage, D3DSAMP_MAXMIPLEVEL, pValue);
case D3DTSS_MAXANISOTROPY:
return ProxyInterface->GetSamplerState(Stage, D3DSAMP_MAXANISOTROPY, pValue);
default:
return ProxyInterface->GetTextureStageState(Stage, Type, pValue);
}
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::SetTextureStageState(DWORD Stage, D3DTEXTURESTAGESTATETYPE Type, DWORD Value)
{
switch (static_cast<DWORD>(Type))
{
case D3DTSS_ADDRESSU:
return ProxyInterface->SetSamplerState(Stage, D3DSAMP_ADDRESSU, Value);
case D3DTSS_ADDRESSV:
return ProxyInterface->SetSamplerState(Stage, D3DSAMP_ADDRESSV, Value);
case D3DTSS_ADDRESSW:
return ProxyInterface->SetSamplerState(Stage, D3DSAMP_ADDRESSW, Value);
case D3DTSS_BORDERCOLOR:
return ProxyInterface->SetSamplerState(Stage, D3DSAMP_BORDERCOLOR, Value);
case D3DTSS_MAGFILTER:
return ProxyInterface->SetSamplerState(Stage, D3DSAMP_MAGFILTER, Value);
case D3DTSS_MINFILTER:
return ProxyInterface->SetSamplerState(Stage, D3DSAMP_MINFILTER, Value);
case D3DTSS_MIPFILTER:
return ProxyInterface->SetSamplerState(Stage, D3DSAMP_MIPFILTER, Value);
case D3DTSS_MIPMAPLODBIAS:
return ProxyInterface->SetSamplerState(Stage, D3DSAMP_MIPMAPLODBIAS, Value);
case D3DTSS_MAXMIPLEVEL:
return ProxyInterface->SetSamplerState(Stage, D3DSAMP_MAXMIPLEVEL, Value);
case D3DTSS_MAXANISOTROPY:
return ProxyInterface->SetSamplerState(Stage, D3DSAMP_MAXANISOTROPY, Value);
default:
return ProxyInterface->SetTextureStageState(Stage, Type, Value);
}
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::ValidateDevice(DWORD *pNumPasses)
{
return ProxyInterface->ValidateDevice(pNumPasses);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetInfo(DWORD DevInfoID, void *pDevInfoStruct, DWORD DevInfoStructSize)
{
UNREFERENCED_PARAMETER(DevInfoID);
UNREFERENCED_PARAMETER(pDevInfoStruct);
UNREFERENCED_PARAMETER(DevInfoStructSize);
#ifndef D3D8TO9NOLOG
LOG << "Redirecting '" << "IDirect3DDevice8::GetInfo" << "(" << this << ", " << DevInfoID << ", " << pDevInfoStruct << ", " << DevInfoStructSize << ")' ..." << std::endl;
#endif
return S_FALSE;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::SetPaletteEntries(UINT PaletteNumber, const PALETTEENTRY *pEntries)
{
if (pEntries == nullptr)
{
return D3DERR_INVALIDCALL;
}
return ProxyInterface->SetPaletteEntries(PaletteNumber, pEntries);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetPaletteEntries(UINT PaletteNumber, PALETTEENTRY *pEntries)
{
if (pEntries == nullptr)
{
return D3DERR_INVALIDCALL;
}
return ProxyInterface->GetPaletteEntries(PaletteNumber, pEntries);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::SetCurrentTexturePalette(UINT PaletteNumber)
{
if (!PaletteFlag)
{
return D3DERR_INVALIDCALL;
}
return ProxyInterface->SetCurrentTexturePalette(PaletteNumber);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetCurrentTexturePalette(UINT *pPaletteNumber)
{
if (!PaletteFlag)
{
return D3DERR_INVALIDCALL;
}
return ProxyInterface->GetCurrentTexturePalette(pPaletteNumber);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::DrawPrimitive(D3DPRIMITIVETYPE PrimitiveType, UINT StartVertex, UINT PrimitiveCount)
{
ApplyClipPlanes();
return ProxyInterface->DrawPrimitive(PrimitiveType, StartVertex, PrimitiveCount);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::DrawIndexedPrimitive(D3DPRIMITIVETYPE PrimitiveType, UINT MinIndex, UINT NumVertices, UINT StartIndex, UINT PrimitiveCount)
{
ApplyClipPlanes();
return ProxyInterface->DrawIndexedPrimitive(PrimitiveType, CurrentBaseVertexIndex, MinIndex, NumVertices, StartIndex, PrimitiveCount);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::DrawPrimitiveUP(D3DPRIMITIVETYPE PrimitiveType, UINT PrimitiveCount, const void *pVertexStreamZeroData, UINT VertexStreamZeroStride)
{
ApplyClipPlanes();
return ProxyInterface->DrawPrimitiveUP(PrimitiveType, PrimitiveCount, pVertexStreamZeroData, VertexStreamZeroStride);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::DrawIndexedPrimitiveUP(D3DPRIMITIVETYPE PrimitiveType, UINT MinVertexIndex, UINT NumVertexIndices, UINT PrimitiveCount, const void *pIndexData, D3DFORMAT IndexDataFormat, const void *pVertexStreamZeroData, UINT VertexStreamZeroStride)
{
ApplyClipPlanes();
return ProxyInterface->DrawIndexedPrimitiveUP(PrimitiveType, MinVertexIndex, NumVertexIndices, PrimitiveCount, pIndexData, IndexDataFormat, pVertexStreamZeroData, VertexStreamZeroStride);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::ProcessVertices(UINT SrcStartIndex, UINT DestIndex, UINT VertexCount, Direct3DVertexBuffer8 *pDestBuffer, DWORD Flags)
{
if (pDestBuffer == nullptr)
{
return D3DERR_INVALIDCALL;
}
return ProxyInterface->ProcessVertices(SrcStartIndex, DestIndex, VertexCount, pDestBuffer->GetProxyInterface(), nullptr, Flags);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::CreateVertexShader(const DWORD *pDeclaration, const DWORD *pFunction, DWORD *pHandle, DWORD Usage)
{
UNREFERENCED_PARAMETER(Usage);
#ifndef D3D8TO9NOLOG
LOG << "Redirecting '" << "IDirect3DDevice8::CreateVertexShader" << "(" << this << ", " << pDeclaration << ", " << pFunction << ", " << pHandle << ", " << Usage << ")' ..." << std::endl;
#endif
if (pDeclaration == nullptr || pHandle == nullptr)
{
return D3DERR_INVALIDCALL;
}
*pHandle = 0;
UINT ElementIndex = 0;
const UINT ElementLimit = 32;
std::string ConstantsCode;
WORD Stream = 0, Offset = 0;
DWORD VertexShaderInputs[ElementLimit];
D3DVERTEXELEMENT9 VertexElements[ElementLimit];
#ifndef D3D8TO9NOLOG
LOG << "> Translating vertex declaration ..." << std::endl;
#endif
static const BYTE DeclTypes[][2] =
{
{ D3DDECLTYPE_FLOAT1, 4 },
{ D3DDECLTYPE_FLOAT2, 8 },
{ D3DDECLTYPE_FLOAT3, 12 },
{ D3DDECLTYPE_FLOAT4, 16 },
{ D3DDECLTYPE_D3DCOLOR, 4 },
{ D3DDECLTYPE_UBYTE4, 4 },
{ D3DDECLTYPE_SHORT2, 4 },
{ D3DDECLTYPE_SHORT4, 8 },
{ D3DDECLTYPE_UBYTE4N, 4 },
{ D3DDECLTYPE_SHORT2N, 4 },
{ D3DDECLTYPE_SHORT4N, 8 },
{ D3DDECLTYPE_USHORT2N, 4 },
{ D3DDECLTYPE_USHORT4N, 8 },
{ D3DDECLTYPE_UDEC3, 6 },
{ D3DDECLTYPE_DEC3N, 6 },
{ D3DDECLTYPE_FLOAT16_2, 8 },
{ D3DDECLTYPE_FLOAT16_4, 16 }
};
static const BYTE DeclAddressUsages[][2] =
{
{ D3DDECLUSAGE_POSITION, 0 },
{ D3DDECLUSAGE_BLENDWEIGHT, 0 },
{ D3DDECLUSAGE_BLENDINDICES, 0 },
{ D3DDECLUSAGE_NORMAL, 0 },
{ D3DDECLUSAGE_PSIZE, 0 },
{ D3DDECLUSAGE_COLOR, 0 },
{ D3DDECLUSAGE_COLOR, 1 },
{ D3DDECLUSAGE_TEXCOORD, 0 },
{ D3DDECLUSAGE_TEXCOORD, 1 },
{ D3DDECLUSAGE_TEXCOORD, 2 },
{ D3DDECLUSAGE_TEXCOORD, 3 },
{ D3DDECLUSAGE_TEXCOORD, 4 },
{ D3DDECLUSAGE_TEXCOORD, 5 },
{ D3DDECLUSAGE_TEXCOORD, 6 },
{ D3DDECLUSAGE_TEXCOORD, 7 },
{ D3DDECLUSAGE_POSITION, 1 },
{ D3DDECLUSAGE_NORMAL, 1 }
};
while (ElementIndex < ElementLimit)
{
const DWORD Token = *pDeclaration;
const DWORD TokenType = (Token & D3DVSD_TOKENTYPEMASK) >> D3DVSD_TOKENTYPESHIFT;
if (Token == D3DVSD_END())
{
break;
}
else if (TokenType == D3DVSD_TOKEN_STREAM)
{
Stream = static_cast<WORD>((Token & D3DVSD_STREAMNUMBERMASK) >> D3DVSD_STREAMNUMBERSHIFT);
Offset = 0;
}
else if (TokenType == D3DVSD_TOKEN_STREAMDATA && !(Token & 0x10000000))
{
VertexElements[ElementIndex].Stream = Stream;
VertexElements[ElementIndex].Offset = Offset;
const DWORD type = (Token & D3DVSD_DATATYPEMASK) >> D3DVSD_DATATYPESHIFT;
VertexElements[ElementIndex].Type = DeclTypes[type][0];
Offset += DeclTypes[type][1];
VertexElements[ElementIndex].Method = D3DDECLMETHOD_DEFAULT;
const DWORD Address = (Token & D3DVSD_VERTEXREGMASK) >> D3DVSD_VERTEXREGSHIFT;
VertexElements[ElementIndex].Usage = DeclAddressUsages[Address][0];
VertexElements[ElementIndex].UsageIndex = DeclAddressUsages[Address][1];
VertexShaderInputs[ElementIndex++] = Address;
}
else if (TokenType == D3DVSD_TOKEN_STREAMDATA && (Token & 0x10000000))
{
Offset += ((Token & D3DVSD_SKIPCOUNTMASK) >> D3DVSD_SKIPCOUNTSHIFT) * sizeof(DWORD);
}
else if (TokenType == D3DVSD_TOKEN_TESSELLATOR && !(Token & 0x10000000))
{
VertexElements[ElementIndex].Stream = Stream;
VertexElements[ElementIndex].Offset = Offset;
const DWORD UsageType = (Token & D3DVSD_VERTEXREGINMASK) >> D3DVSD_VERTEXREGINSHIFT;
for (UINT r = 0; r < ElementIndex; ++r)
{
if (VertexElements[r].Usage == DeclAddressUsages[UsageType][0] && VertexElements[r].UsageIndex == DeclAddressUsages[UsageType][1])
{
VertexElements[ElementIndex].Stream = VertexElements[r].Stream;
VertexElements[ElementIndex].Offset = VertexElements[r].Offset;
break;
}
}
VertexElements[ElementIndex].Type = D3DDECLTYPE_FLOAT3;
VertexElements[ElementIndex].Method = D3DDECLMETHOD_CROSSUV;
const DWORD Address = (Token & 0xF);
VertexElements[ElementIndex].Usage = DeclAddressUsages[Address][0];
VertexElements[ElementIndex].UsageIndex = DeclAddressUsages[Address][1];
if (VertexElements[ElementIndex].Usage == D3DDECLUSAGE_BLENDINDICES)
{
VertexElements[ElementIndex].Method = D3DDECLMETHOD_DEFAULT;
}
VertexShaderInputs[ElementIndex++] = Address;
}
else if (TokenType == D3DVSD_TOKEN_TESSELLATOR && (Token & 0x10000000))
{
VertexElements[ElementIndex].Stream = 0;
VertexElements[ElementIndex].Offset = 0;
VertexElements[ElementIndex].Type = D3DDECLTYPE_UNUSED;
VertexElements[ElementIndex].Method = D3DDECLMETHOD_UV;
const DWORD Address = (Token & 0xF);
VertexElements[ElementIndex].Usage = DeclAddressUsages[Address][0];
VertexElements[ElementIndex].UsageIndex = DeclAddressUsages[Address][1];
if (VertexElements[ElementIndex].Usage == D3DDECLUSAGE_BLENDINDICES)
{
VertexElements[ElementIndex].Method = D3DDECLMETHOD_DEFAULT;
}
VertexShaderInputs[ElementIndex++] = Address;
}
else if (TokenType == D3DVSD_TOKEN_CONSTMEM)
{
const DWORD RegisterCount = 4 * ((Token & D3DVSD_CONSTCOUNTMASK) >> D3DVSD_CONSTCOUNTSHIFT);
DWORD Address = (Token & D3DVSD_CONSTADDRESSMASK) >> D3DVSD_CONSTADDRESSSHIFT;
for (DWORD RegisterIndex = 0; RegisterIndex < RegisterCount; RegisterIndex += 4, ++Address)
{
ConstantsCode += " def c" + std::to_string(Address) + ", " +
std::to_string(*reinterpret_cast<const float *>(&pDeclaration[RegisterIndex + 1])) + ", " +
std::to_string(*reinterpret_cast<const float *>(&pDeclaration[RegisterIndex + 2])) + ", " +
std::to_string(*reinterpret_cast<const float *>(&pDeclaration[RegisterIndex + 3])) + ", " +
std::to_string(*reinterpret_cast<const float *>(&pDeclaration[RegisterIndex + 4])) + " /* vertex declaration constant */\n";
}
pDeclaration += RegisterCount;
}
else
{
#ifndef D3D8TO9NOLOG
LOG << "> Failed because token type '" << TokenType << "' is not supported!" << std::endl;
#endif
return D3DERR_INVALIDCALL;
}
++pDeclaration;
}
const D3DVERTEXELEMENT9 Terminator = D3DDECL_END();
VertexElements[ElementIndex] = Terminator;
HRESULT hr;
VertexShaderInfo *ShaderInfo;
if (pFunction != nullptr)
{
#ifndef D3D8TO9NOLOG
LOG << "> Disassembling shader and translating assembly to Direct3D 9 compatible code ..." << std::endl;
#endif
if (*pFunction < D3DVS_VERSION(1, 0) || *pFunction > D3DVS_VERSION(1, 1))
{
#ifndef D3D8TO9NOLOG
LOG << "> Failed because of version mismatch ('" << std::showbase << std::hex << *pFunction << std::dec << std::noshowbase << "')! Only 'vs_1_x' shaders are supported." << std::endl;
#endif
return D3DERR_INVALIDCALL;
}
ID3DXBuffer *Disassembly = nullptr, *Assembly = nullptr, *ErrorBuffer = nullptr;
if (D3DXDisassembleShader != nullptr)
{
hr = D3DXDisassembleShader(pFunction, FALSE, nullptr, &Disassembly);
}
else
{
hr = D3DERR_INVALIDCALL;
}
if (FAILED(hr))
{
#ifndef D3D8TO9NOLOG
LOG << "> Failed to disassemble shader with error code " << std::hex << hr << std::dec << "!" << std::endl;
#endif
return hr;
}
std::string SourceCode(static_cast<const char *>(Disassembly->GetBufferPointer()), Disassembly->GetBufferSize() - 1);
#ifndef D3D8TO9NOLOG
LOG << "> Dumping original shader assembly:" << std::endl << std::endl << SourceCode << std::endl;
#endif
const size_t VersionPosition = SourceCode.find("vs_1_");
assert(VersionPosition != std::string::npos);
if (SourceCode.at(VersionPosition + 5) == '0')
{
#ifndef D3D8TO9NOLOG
LOG << "> Replacing version 'vs_1_0' with 'vs_1_1' ..." << std::endl;
#endif
SourceCode.replace(VersionPosition, 6, "vs_1_1");
}
size_t DeclPosition = VersionPosition + 7;
for (UINT k = 0; k < ElementIndex; k++)
{
std::string DeclCode = " ";
switch (VertexElements[k].Usage)
{
case D3DDECLUSAGE_POSITION:
DeclCode += "dcl_position";
break;
case D3DDECLUSAGE_BLENDWEIGHT:
DeclCode += "dcl_blendweight";
break;
case D3DDECLUSAGE_BLENDINDICES:
DeclCode += "dcl_blendindices";
break;
case D3DDECLUSAGE_NORMAL:
DeclCode += "dcl_normal";
break;
case D3DDECLUSAGE_PSIZE:
DeclCode += "dcl_psize";
break;
case D3DDECLUSAGE_COLOR:
DeclCode += "dcl_color";
break;
case D3DDECLUSAGE_TEXCOORD:
DeclCode += "dcl_texcoord";
break;
}
if (VertexElements[k].UsageIndex > 0)
{
DeclCode += std::to_string(VertexElements[k].UsageIndex);
}
DeclCode += " v" + std::to_string(VertexShaderInputs[k]) + '\n';
SourceCode.insert(DeclPosition, DeclCode);
DeclPosition += DeclCode.length();
}
#pragma region Fill registers with default value
SourceCode.insert(DeclPosition, ConstantsCode);
// Get number of arithmetic instructions used
const size_t InstructionPosition = SourceCode.find("instruction");
size_t InstructionCount = InstructionPosition > 2 && InstructionPosition < SourceCode.size() ? strtoul(SourceCode.substr(InstructionPosition - 4, 4).c_str(), nullptr, 10) : 0;
for (size_t j = 0; j < 8; j++)
{
const std::string reg = "oT" + std::to_string(j);
if (SourceCode.find(reg) != std::string::npos && InstructionCount < 128)
{
++InstructionCount;
SourceCode.insert(DeclPosition + ConstantsCode.size(), " mov " + reg + ", c0 /* initialize output register " + reg + " */\n");
}
}
for (size_t j = 0; j < 2; j++)
{
const std::string reg = "oD" + std::to_string(j);
if (SourceCode.find(reg) != std::string::npos && InstructionCount < 128)
{
++InstructionCount;
SourceCode.insert(DeclPosition + ConstantsCode.size(), " mov " + reg + ", c0 /* initialize output register " + reg + " */\n");
}
}
for (size_t j = 0; j < 12; j++)
{
const std::string reg = "r" + std::to_string(j);
if (SourceCode.find(reg) != std::string::npos && InstructionCount < 128)
{
++InstructionCount;
SourceCode.insert(DeclPosition + ConstantsCode.size(), " mov " + reg + ", c0 /* initialize register " + reg + " */\n");
}
}
#pragma endregion
SourceCode = std::regex_replace(SourceCode, std::regex(" \\/\\/ vs\\.1\\.1\\n((?! ).+\\n)+"), "");
SourceCode = std::regex_replace(SourceCode, std::regex("([^\\n]\\n)[\\s]*#line [0123456789]+.*\\n"), "$1");
SourceCode = std::regex_replace(SourceCode, std::regex("(oFog|oPts)\\.x"), "$1 /* removed swizzle */");
SourceCode = std::regex_replace(SourceCode, std::regex("(add|sub|mul|min|max) (oFog|oPts), ([cr][0-9]+), (.+)\\n"), "$1 $2, $3.x /* added swizzle */, $4\n");
SourceCode = std::regex_replace(SourceCode, std::regex("(add|sub|mul|min|max) (oFog|oPts), (.+), ([cr][0-9]+)\\n"), "$1 $2, $3, $4.x /* added swizzle */\n");
SourceCode = std::regex_replace(SourceCode, std::regex("mov (oFog|oPts)(.*), (-?)([crv][0-9]+(?![\\.0-9]))"), "mov $1$2, $3$4.x /* select single component */");
// Destination register cannot be the same as first source register for m*x* instructions.
if (std::regex_search(SourceCode, std::regex("m.x.")))
{
// Check for unused register
size_t r;
for (r = 0; r < 12; r++)
{
if (SourceCode.find("r" + std::to_string(r)) == std::string::npos) break;
}
// Check if first source register is the same as the destination register
for (size_t j = 0; j < 12; j++)
{
const std::string reg = "(m.x.) (r" + std::to_string(j) + "), ((-?)r" + std::to_string(j) + "([\\.xyzw]*))(?![0-9])";
while (std::regex_search(SourceCode, std::regex(reg)))
{
// If there is enough remaining instructions and an unused register then update to use a temp register
if (r < 12 && InstructionCount < 128)
{
++InstructionCount;
SourceCode = std::regex_replace(SourceCode, std::regex(reg),
"mov r" + std::to_string(r) + ", $2 /* added line */\n $1 $2, $4r" + std::to_string(r) + "$5 /* changed $3 to r" + std::to_string(r) + " */",
std::regex_constants::format_first_only);
}
// Disable line to prevent assembly error
else
{
SourceCode = std::regex_replace(SourceCode, std::regex("(.*" + reg + ".*)"), "/*$1*/ /* disabled this line */");
break;
}
}
}
}
#ifndef D3D8TO9NOLOG
LOG << "> Dumping translated shader assembly:" << std::endl << std::endl << SourceCode << std::endl;
#endif
if (D3DXAssembleShader != nullptr)
{
hr = D3DXAssembleShader(SourceCode.data(), static_cast<UINT>(SourceCode.size()), nullptr, nullptr, D3DXASM_FLAGS, &Assembly, &ErrorBuffer);
}
else
{
hr = D3DERR_INVALIDCALL;
}
Disassembly->Release();
if (FAILED(hr))
{
if (ErrorBuffer != nullptr)
{
#ifndef D3D8TO9NOLOG
LOG << "> Failed to reassemble shader:" << std::endl << std::endl << static_cast<const char *>(ErrorBuffer->GetBufferPointer()) << std::endl;
#endif
ErrorBuffer->Release();
}
else
{
#ifndef D3D8TO9NOLOG
LOG << "> Failed to reassemble shader with error code " << std::hex << hr << std::dec << "!" << std::endl;
#endif
}
return hr;
}
ShaderInfo = new VertexShaderInfo();
hr = ProxyInterface->CreateVertexShader(static_cast<const DWORD *>(Assembly->GetBufferPointer()), &ShaderInfo->Shader);
Assembly->Release();
}
else
{
ShaderInfo = new VertexShaderInfo();
ShaderInfo->Shader = nullptr;
hr = D3D_OK;
}
if (SUCCEEDED(hr))
{
hr = ProxyInterface->CreateVertexDeclaration(VertexElements, &ShaderInfo->Declaration);
if (SUCCEEDED(hr))
{
// Since 'Shader' is at least 8 byte aligned, we can safely shift it to right and end up not overwriting the top bit
assert((reinterpret_cast<DWORD>(ShaderInfo) & 1) == 0);
const DWORD ShaderMagic = reinterpret_cast<DWORD>(ShaderInfo) >> 1;
*pHandle = ShaderMagic | 0x80000000;
}
else
{
#ifndef D3D8TO9NOLOG
LOG << "> 'IDirect3DDevice9::CreateVertexDeclaration' failed with error code " << std::hex << hr << std::dec << "!" << std::endl;
#endif
if (ShaderInfo->Shader != nullptr)
{
ShaderInfo->Shader->Release();
}
}
}
else
{
#ifndef D3D8TO9NOLOG
LOG << "> 'IDirect3DDevice9::CreateVertexShader' failed with error code " << std::hex << hr << std::dec << "!" << std::endl;
#endif
}
if (FAILED(hr))
{
delete ShaderInfo;
}
return hr;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::SetVertexShader(DWORD Handle)
{
HRESULT hr;
if ((Handle & 0x80000000) == 0)
{
ProxyInterface->SetVertexShader(nullptr);
hr = ProxyInterface->SetFVF(Handle);
CurrentVertexShaderHandle = 0;
}
else
{
const DWORD handleMagic = Handle << 1;
VertexShaderInfo *const ShaderInfo = reinterpret_cast<VertexShaderInfo *>(handleMagic);
hr = ProxyInterface->SetVertexShader(ShaderInfo->Shader);
ProxyInterface->SetVertexDeclaration(ShaderInfo->Declaration);
CurrentVertexShaderHandle = Handle;
}
return hr;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetVertexShader(DWORD *pHandle)
{
if (pHandle == nullptr)
{
return D3DERR_INVALIDCALL;
}
if (CurrentVertexShaderHandle == 0)
{
return ProxyInterface->GetFVF(pHandle);
}
else
{
*pHandle = CurrentVertexShaderHandle;
return D3D_OK;
}
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::DeleteVertexShader(DWORD Handle)
{
if ((Handle & 0x80000000) == 0)
{
return D3DERR_INVALIDCALL;
}
if (CurrentVertexShaderHandle == Handle)
{
SetVertexShader(0);
}
const DWORD HandleMagic = Handle << 1;
VertexShaderInfo *const ShaderInfo = reinterpret_cast<VertexShaderInfo *>(HandleMagic);
if (ShaderInfo->Shader != nullptr)
{
ShaderInfo->Shader->Release();
}
if (ShaderInfo->Declaration != nullptr)
{
ShaderInfo->Declaration->Release();
}
delete ShaderInfo;
return D3D_OK;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::SetVertexShaderConstant(DWORD Register, const void *pConstantData, DWORD ConstantCount)
{
return ProxyInterface->SetVertexShaderConstantF(Register, static_cast<const float *>(pConstantData), ConstantCount);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetVertexShaderConstant(DWORD Register, void *pConstantData, DWORD ConstantCount)
{
return ProxyInterface->GetVertexShaderConstantF(Register, static_cast<float *>(pConstantData), ConstantCount);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetVertexShaderDeclaration(DWORD Handle, void *pData, DWORD *pSizeOfData)
{
UNREFERENCED_PARAMETER(Handle);
UNREFERENCED_PARAMETER(pData);
UNREFERENCED_PARAMETER(pSizeOfData);
#ifndef D3D8TO9NOLOG
LOG << "Redirecting '" << "IDirect3DDevice8::GetVertexShaderDeclaration" << "(" << this << ", " << Handle << ", " << pData << ", " << pSizeOfData << ")' ..." << std::endl;
LOG << "> 'IDirect3DDevice8::GetVertexShaderDeclaration' is not implemented!" << std::endl;
#endif
return D3DERR_INVALIDCALL;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetVertexShaderFunction(DWORD Handle, void *pData, DWORD *pSizeOfData)
{
#ifndef D3D8TO9NOLOG
LOG << "Redirecting '" << "IDirect3DDevice8::GetVertexShaderFunction" << "(" << this << ", " << Handle << ", " << pData << ", " << pSizeOfData << ")' ..." << std::endl;
#endif
if ((Handle & 0x80000000) == 0)
{
return D3DERR_INVALIDCALL;
}
const DWORD HandleMagic = Handle << 1;
IDirect3DVertexShader9 *VertexShaderInterface = reinterpret_cast<VertexShaderInfo *>(HandleMagic)->Shader;
if (VertexShaderInterface == nullptr)
{
return D3DERR_INVALIDCALL;
}
#ifndef D3D8TO9NOLOG
LOG << "> Returning translated shader byte code." << std::endl;
#endif
return VertexShaderInterface->GetFunction(pData, reinterpret_cast<UINT *>(pSizeOfData));
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::SetStreamSource(UINT StreamNumber, Direct3DVertexBuffer8 *pStreamData, UINT Stride)
{
if (pStreamData == nullptr)
{
return D3DERR_INVALIDCALL;
}
return ProxyInterface->SetStreamSource(StreamNumber, pStreamData->GetProxyInterface(), 0, Stride);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetStreamSource(UINT StreamNumber, Direct3DVertexBuffer8 **ppStreamData, UINT *pStride)
{
if (ppStreamData == nullptr)
{
return D3DERR_INVALIDCALL;
}
else
{
*ppStreamData = nullptr;
}
UINT StreamOffset = 0;
IDirect3DVertexBuffer9 *VertexBufferInterface = nullptr;
const HRESULT hr = ProxyInterface->GetStreamSource(StreamNumber, &VertexBufferInterface, &StreamOffset, pStride);
if (FAILED(hr))
{
return hr;
}
if (VertexBufferInterface != nullptr)
{
*ppStreamData = ProxyAddressLookupTable->FindAddress<Direct3DVertexBuffer8>(VertexBufferInterface);
}
return D3D_OK;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::SetIndices(Direct3DIndexBuffer8 *pIndexData, UINT BaseVertexIndex)
{
if (pIndexData == nullptr || BaseVertexIndex > 0x7FFFFFFF)
{
return D3DERR_INVALIDCALL;
}
CurrentBaseVertexIndex = static_cast<INT>(BaseVertexIndex);
return ProxyInterface->SetIndices(pIndexData->GetProxyInterface());
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetIndices(Direct3DIndexBuffer8 **ppIndexData, UINT *pBaseVertexIndex)
{
if (ppIndexData == nullptr)
{
return D3DERR_INVALIDCALL;
}
*ppIndexData = nullptr;
if (pBaseVertexIndex != nullptr)
{
*pBaseVertexIndex = static_cast<UINT>(CurrentBaseVertexIndex);
}
IDirect3DIndexBuffer9 *IntexBufferInterface = nullptr;
const HRESULT hr = ProxyInterface->GetIndices(&IntexBufferInterface);
if (FAILED(hr))
{
return hr;
}
if (IntexBufferInterface != nullptr)
{
*ppIndexData = ProxyAddressLookupTable->FindAddress<Direct3DIndexBuffer8>(IntexBufferInterface);
}
return D3D_OK;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::CreatePixelShader(const DWORD *pFunction, DWORD *pHandle)
{
#ifndef D3D8TO9NOLOG
LOG << "Redirecting '" << "IDirect3DDevice8::CreatePixelShader" << "(" << this << ", " << pFunction << ", " << pHandle << ")' ..." << std::endl;
#endif
if (pFunction == nullptr || pHandle == nullptr)
{
return D3DERR_INVALIDCALL;
}
*pHandle = 0;
#ifndef D3D8TO9NOLOG
LOG << "> Disassembling shader and translating assembly to Direct3D 9 compatible code ..." << std::endl;
#endif
if (*pFunction < D3DPS_VERSION(1, 0) || *pFunction > D3DPS_VERSION(1, 4))
{
#ifndef D3D8TO9NOLOG
LOG << "> Failed because of version mismatch ('" << std::showbase << std::hex << *pFunction << std::dec << std::noshowbase << "')! Only 'ps_1_x' shaders are supported." << std::endl;
#endif
return D3DERR_INVALIDCALL;
}
ID3DXBuffer *Disassembly = nullptr, *Assembly = nullptr, *ErrorBuffer = nullptr;
HRESULT hr = D3DERR_INVALIDCALL;
if (D3DXDisassembleShader != nullptr)
{
hr = D3DXDisassembleShader(pFunction, FALSE, nullptr, &Disassembly);
}
if (FAILED(hr))
{
#ifndef D3D8TO9NOLOG
LOG << "> Failed to disassemble shader with error code " << std::hex << hr << std::dec << "!" << std::endl;
#endif
return hr;
}
std::string SourceCode(static_cast<const char *>(Disassembly->GetBufferPointer()), Disassembly->GetBufferSize() - 1);
const size_t VersionPosition = SourceCode.find("ps_1_");
assert(VersionPosition != std::string::npos);
if (SourceCode.at(VersionPosition + 5) == '0')
{
#ifndef D3D8TO9NOLOG
LOG << "> Replacing version 'ps_1_0' with 'ps_1_1' ..." << std::endl;
#endif
SourceCode.replace(VersionPosition, 6, "ps_1_1");
}
// Get number of arithmetic instructions used
const size_t ArithmeticPosition = SourceCode.find("arithmetic");
size_t ArithmeticCount = ArithmeticPosition > 2 && ArithmeticPosition < SourceCode.size() ? strtoul(SourceCode.substr(ArithmeticPosition - 2, 2).c_str(), nullptr, 10) : 0;
ArithmeticCount = (ArithmeticCount != 0) ? ArithmeticCount : 10; // Default to 10
// Remove lines when " // ps.1.1" string is found and the next line does not start with a space
SourceCode = std::regex_replace(SourceCode,
std::regex(" \\/\\/ ps\\.1\\.[1-4]\\n((?! ).+\\n)+"),
"");
// Remove debug lines
SourceCode = std::regex_replace(SourceCode,
std::regex("([^\\n]\\n)[\\s]*#line [0123456789]+.*\\n"),
"$1");
// Fix '-' modifier for constant values when using 'add' arithmetic by changing it to use 'sub'
SourceCode = std::regex_replace(SourceCode,
std::regex("(add)([_satxd248]*) (r[0-9][\\.wxyz]*), ((1-|)[crtv][0-9][\\.wxyz_abdis2]*), (-)(c[0-9][\\.wxyz]*)(_bx2|_bias|_x2|_d[zbwa]|)(?![_\\.wxyz])"),
"sub$2 $3, $4, $7$8 /* changed 'add' to 'sub' removed modifier $6 */");
// Create temporary varables for ps_1_4
std::string SourceCode14 = SourceCode;
int ArithmeticCount14 = ArithmeticCount;
// Fix modifiers for constant values by using any remaining arithmetic places to add an instruction to move the constant value to a temporary register
while (std::regex_search(SourceCode, std::regex("-c[0-9]|c[0-9][\\.wxyz]*_")) && ArithmeticCount < 8)
{
// Make sure that the dest register is not already being used
std::string tmpLine = "\n" + std::regex_replace(SourceCode, std::regex("1?-(c[0-9])[\\._a-z0-9]*|(c[0-9])[\\.wxyz]*_[a-z0-9]*"), "-$1$2") + "\n";
size_t start = tmpLine.substr(0, tmpLine.find("-c")).rfind("\n") + 1;
tmpLine = tmpLine.substr(start, tmpLine.find("\n", start) - start);
const std::string destReg = std::regex_replace(tmpLine, std::regex("[ \\+]+[a-z_\\.0-9]+ (r[0-9]).*-c[0-9].*"),"$1");
const std::string sourceReg = std::regex_replace(tmpLine, std::regex("[ \\+]+[a-z_\\.0-9]+ r[0-9][\\._a-z0-9]*, (.*)-c[0-9](.*)"), "$1$2");
if (sourceReg.find(destReg) != std::string::npos)
{
break;
}
// Replace one constant modifier using the dest register as a temporary register
size_t SourceSize = SourceCode.size();
SourceCode = std::regex_replace(SourceCode,
std::regex(" (...)(_[_satxd248]*|) (r[0-9])([\\.wxyz]*), (1?-?[crtv][0-9][\\.wxyz_abdis2]*, )?(1?-?[crtv][0-9][\\.wxyz_abdis2]*, )?(1?-?[crtv][0-9][\\.wxyz_abdis2]*, )?((1?-)(c[0-9])([\\.wxyz]*)(_bx2|_bias|_x2|_d[zbwa]|)|(1?-?)(c[0-9])([\\.wxyz]*)(_bx2|_bias|_x2|_d[zbwa]))(?![_\\.wxyz])"),
" mov $3$4, $10$11$14$15 /* added line */\n $1$2 $3$4, $5$6$9$13$3$12$16 /* changed $10$11$14$15 to $3 */", std::regex_constants::format_first_only);
// Replace one constant modifier on coissued commands using the dest register as a temporary register
if (SourceSize == SourceCode.size())
{
SourceCode = std::regex_replace(SourceCode,
std::regex("( .*\\n) \\+ (...)(_[_satxd248]*|) (r[0-9])([\\.wxyz]*), (1?-?[crtv][0-9][\\.wxyz_abdis2]*, )?(1?-?[crtv][0-9][\\.wxyz_abdis2]*, )?(1?-?[crtv][0-9][\\.wxyz_abdis2]*, )?((1?-)(c[0-9])([\\.wxyz]*)(_bx2|_bias|_x2|_d[zbwa]|)|(1?-?)(c[0-9])([\\.wxyz]*)(_bx2|_bias|_x2|_d[zbwa]))(?![_\\.wxyz])"),
" mov $4$5, $11$12$15$16 /* added line */\n$1 + $2$3 $4$5, $6$7$10$14$4$13$17 /* changed $11$12$15$16 to $4 */", std::regex_constants::format_first_only);
}
if (SourceSize == SourceCode.size())
{
break;
}
ArithmeticCount++;
}
// Check if this should be converted to ps_1_4
if (std::regex_search(SourceCode, std::regex("-c[0-9]|c[0-9][\\.wxyz]*_")) && // Check for modifiers on constants
!std::regex_search(SourceCode, std::regex("tex[bcdmr]")) && // Verify unsupported instructions are not used
std::regex_search(SourceCode, std::regex("ps_1_[0-3]"))) // Verify PixelShader is using version 1.0 to 1.3
{
bool ConvertError = false;
bool RegisterUsed[7] = { false };
RegisterUsed[6] = true;
struct MyStrings
{
std::string dest;
std::string source;
};
std::vector<MyStrings> ReplaceReg;
std::string NewSourceCode = " ps_1_4 /* converted */\n";
// Ensure at least one command will be above the phase marker
bool PhaseMarkerSet = (ArithmeticCount14 >= 8);
if (SourceCode14.find("def c") == std::string::npos && !PhaseMarkerSet)
{
for (size_t j = 0; j < 8; j++)
{
const std::string reg = "c" + std::to_string(j);
if (SourceCode14.find(reg) == std::string::npos)
{
PhaseMarkerSet = true;
NewSourceCode.append(" def " + reg + ", 0, 0, 0, 0 /* added line */\n");
break;
}
}
}
// Update registers to use different numbers from textures
size_t FirstReg = 0;
for (size_t j = 0; j < 2; j++)
{
const std::string reg = "r" + std::to_string(j);
if (SourceCode14.find(reg) != std::string::npos)
{
while (SourceCode14.find("t" + std::to_string(FirstReg)) != std::string::npos ||
(SourceCode14.find("r" + std::to_string(FirstReg)) != std::string::npos && j != FirstReg))
{
FirstReg++;
}
SourceCode14 = std::regex_replace(SourceCode14, std::regex(reg), "r" + std::to_string(FirstReg));
FirstReg++;
}
}
// Set phase location
size_t PhasePosition = NewSourceCode.length();
size_t TexturePosition = 0;
// Loop through each line
size_t LinePosition = 1;
std::string NewLine = SourceCode14;
while (true)
{
// Get next line
size_t tmpLinePos = SourceCode14.find("\n", LinePosition) + 1;
if (tmpLinePos == std::string::npos || tmpLinePos < LinePosition)
{
break;
}
LinePosition = tmpLinePos;
NewLine = SourceCode14.substr(LinePosition, SourceCode14.length());
tmpLinePos = NewLine.find("\n");
if (tmpLinePos != std::string::npos)
{
NewLine.resize(tmpLinePos);
}
// Skip 'ps_x_x' lines
if (std::regex_search(NewLine, std::regex("ps_._.")))
{
// Do nothing
}
// Check for 'def' and add before 'phase' statement
else if (NewLine.find("def c") != std::string::npos)
{
PhaseMarkerSet = true;
const std::string tmpLine = NewLine + "\n";
NewSourceCode.insert(PhasePosition, tmpLine);
PhasePosition += tmpLine.length();
}
// Check for 'tex' and update to 'texld'
else if (NewLine.find("tex t") != std::string::npos)
{
const std::string regNum = std::regex_replace(NewLine, std::regex(".*tex t([0-9]).*"), "$1");
const std::string tmpLine = " texld r" + regNum + ", t" + regNum + "\n";
// Mark as a texture register and add 'texld' statement before or after the 'phase' statement
const unsigned long Num = strtoul(regNum.c_str(), nullptr, 10);
RegisterUsed[(Num < 6) ? Num : 6] = true;
NewSourceCode.insert(PhasePosition, tmpLine);
if (PhaseMarkerSet)
{
TexturePosition += tmpLine.length();
}
else
{
PhaseMarkerSet = true;
PhasePosition += tmpLine.length();
}
}
// Other instructions
else
{
// Check for constant modifiers and update them to use unused temp register
if (std::regex_search(NewLine, std::regex("-c[0-9]|c[0-9][\\.wxyz]*_")))
{
for (size_t j = 0; j < 6; j++)
{
std::string reg = "r" + std::to_string(j);
if (NewSourceCode.find(reg) == std::string::npos)
{
const std::string constReg = std::regex_replace(NewLine, std::regex(".*-(c[0-9]).*|.*(c[0-9])[\\.wxyz]*_.*"), "$1$2");
// Check if this constant has modifiers in more than one line
if (std::regex_search(SourceCode14.substr(LinePosition + NewLine.length(), SourceCode14.length()), std::regex("-" + constReg + "|" + constReg + "[\\.wxyz]*_")))
{
// Find an unused register
while (j < 6 &&
(NewSourceCode.find("r" + std::to_string(j)) != std::string::npos ||
SourceCode14.find("r" + std::to_string(j)) != std::string::npos))
{
j++;
}
// Replace all constants with the unused register
if (j < 6)
{
reg = "r" + std::to_string(j);
SourceCode14 = std::regex_replace(SourceCode14, std::regex(constReg), reg);
}
}
const std::string tmpLine = " mov " + reg + ", " + constReg + "\n";
// Update the constant in this line and add 'mov' statement before or after the 'phase' statement
NewLine = std::regex_replace(NewLine, std::regex(constReg), reg);
if (ArithmeticCount14 < 8)
{
NewSourceCode.insert(PhasePosition + TexturePosition, tmpLine);
ArithmeticCount14++;
}
else
{
PhaseMarkerSet = true;
NewSourceCode.insert(PhasePosition, tmpLine);
PhasePosition += tmpLine.length();
}
break;
}
}
}
// Update register from vector once it is used for the last time
if (ReplaceReg.size() > 0)
{
for (size_t x = 0; x < ReplaceReg.size(); x++)
{
// Check if register is used in this line
if (NewLine.find(ReplaceReg[x].dest) != std::string::npos)
{
// Get position of all lines after this line
size_t start = LinePosition + NewLine.length();
// Move position to next line if the first line is a co-issed command
start = (SourceCode14.substr(start, 4).find("+") == std::string::npos) ? start : SourceCode14.find("\n", start + 1);
// Check if register is used in the code after this position
if (SourceCode14.find(ReplaceReg[x].dest, start) == std::string::npos)
{
// Update dest register using source register from the vector
NewLine = std::regex_replace(NewLine, std::regex("([ \\+]+[a-z_\\.0-9]+ )r[0-9](.*)"), "$1" + ReplaceReg[x].source + "$2");
ReplaceReg.erase(ReplaceReg.begin() + x);
break;
}
}
}
}
// Check if texture is no longer being used and update the dest register
if (std::regex_search(NewLine, std::regex("t[0-9]")))
{
const std::string texNum = std::regex_replace(NewLine, std::regex(".*t([0-9]).*"), "$1");
// Get position of all lines after this line
size_t start = LinePosition + NewLine.length();
// Move position to next line if the first line is a co-issed command
start = (SourceCode14.substr(start, 4).find("+") == std::string::npos) ? start : SourceCode14.find("\n", start + 1);
// Check if texture is used in the code after this position
if (SourceCode14.find("t" + texNum, start) == std::string::npos)
{
const std::string destRegNum = std::regex_replace(NewLine, std::regex("[ \\+]+[a-z_\\.0-9]+ r([0-9]).*"), "$1");
// Check if destination register is already being used by a texture register
const unsigned long Num = strtoul(destRegNum.c_str(), nullptr, 10);
if (!RegisterUsed[(Num < 6) ? Num : 6])
{
// Check if line is using more than one texture and error out
if (std::regex_search(std::regex_replace(NewLine, std::regex("t" + texNum), "r" + texNum), std::regex("t[0-9]")))
{
ConvertError = true;
break;
}
// Check if this is the first or last time the register is used
if (NewSourceCode.find("r" + destRegNum) == std::string::npos ||
SourceCode14.find("r" + destRegNum, start) == std::string::npos)
{
// Update dest register using texture register
NewLine = std::regex_replace(NewLine, std::regex("([ \\+]+[a-z_\\.0-9]+ )r[0-9](.*)"), "$1r" + texNum + "$2");
// Update code replacing all regsiters after the marked position with the texture register
const std::string tempSourceCode = std::regex_replace(SourceCode14.substr(start, SourceCode14.length()), std::regex("r" + destRegNum), "r" + texNum);
SourceCode14.resize(start);
SourceCode14.append(tempSourceCode);
}
else
{
// If register is still being used then add registers to vector to be replaced later
RegisterUsed[(Num < 6) ? Num : 6] = true;
MyStrings tempReplaceReg;
tempReplaceReg.dest = "r" + destRegNum;
tempReplaceReg.source = "r" + texNum;
ReplaceReg.push_back(tempReplaceReg);
}
}
}
}
// Add line to SourceCode
NewLine = std::regex_replace(NewLine, std::regex("t([0-9])"), "r$1") + "\n";
NewSourceCode.append(NewLine);
}
}
// Add 'phase' instruction
NewSourceCode.insert(PhasePosition, " phase\n");
// If no errors were encountered then check if code assembles
if (!ConvertError)
{
// Test if ps_1_4 assembles
if (SUCCEEDED(D3DXAssembleShader(NewSourceCode.data(), static_cast<UINT>(NewSourceCode.size()), nullptr, nullptr, 0, &Assembly, &ErrorBuffer)))
{
SourceCode = NewSourceCode;
}
else
{
#ifndef D3D8TO9NOLOG
LOG << "> Failed to convert shader to ps_1_4" << std::endl;
LOG << "> Dumping translated shader assembly:" << std::endl << std::endl << NewSourceCode << std::endl;
LOG << "> Failed to reassemble shader:" << std::endl << std::endl << static_cast<const char *>(ErrorBuffer->GetBufferPointer()) << std::endl;
#endif
}
}
}
// Change '-' modifier for constant values when using 'mad' arithmetic by changing it to use 'sub'
SourceCode = std::regex_replace(SourceCode,
std::regex("(mad)([_satxd248]*) (r[0-9][\\.wxyz]*), (1?-?[crtv][0-9][\\.wxyz_abdis2]*), (1?-?[crtv][0-9][\\.wxyz_abdis2]*), (-)(c[0-9][\\.wxyz]*)(_bx2|_bias|_x2|_d[zbwa]|)(?![_\\.wxyz])"),
"sub$2 $3, $4, $7$8 /* changed 'mad' to 'sub' removed $5 removed modifier $6 */");
// Remove trailing modifiers for constant values
SourceCode = std::regex_replace(SourceCode,
std::regex("(c[0-9][\\.wxyz]*)(_bx2|_bias|_x2|_d[zbwa])"),
"$1 /* removed modifier $2 */");
// Remove remaining modifiers for constant values
SourceCode = std::regex_replace(SourceCode,
std::regex("(1?-)(c[0-9][\\.wxyz]*(?![\\.wxyz]))"),
"$2 /* removed modifier $1 */");
#ifndef D3D8TO9NOLOG
LOG << "> Dumping translated shader assembly:" << std::endl << std::endl << SourceCode << std::endl;
#endif
if (D3DXAssembleShader != nullptr)
{
hr = D3DXAssembleShader(SourceCode.data(), static_cast<UINT>(SourceCode.size()), nullptr, nullptr, D3DXASM_FLAGS, &Assembly, &ErrorBuffer);
}
else
{
hr = D3DERR_INVALIDCALL;
}
Disassembly->Release();
if (FAILED(hr))
{
if (ErrorBuffer != nullptr)
{
#ifndef D3D8TO9NOLOG
LOG << "> Failed to reassemble shader:" << std::endl << std::endl << static_cast<const char *>(ErrorBuffer->GetBufferPointer()) << std::endl;
#endif
ErrorBuffer->Release();
}
else
{
#ifndef D3D8TO9NOLOG
LOG << "> Failed to reassemble shader with error code " << std::hex << hr << std::dec << "!" << std::endl;
#endif
}
return hr;
}
hr = ProxyInterface->CreatePixelShader(static_cast<const DWORD *>(Assembly->GetBufferPointer()), reinterpret_cast<IDirect3DPixelShader9 **>(pHandle));
if (FAILED(hr))
{
#ifndef D3D8TO9NOLOG
LOG << "> 'IDirect3DDevice9::CreatePixelShader' failed with error code " << std::hex << hr << std::dec << "!" << std::endl;
#endif
}
return hr;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::SetPixelShader(DWORD Handle)
{
CurrentPixelShaderHandle = Handle;
return ProxyInterface->SetPixelShader(reinterpret_cast<IDirect3DPixelShader9 *>(Handle));
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetPixelShader(DWORD *pHandle)
{
if (pHandle == nullptr)
{
return D3DERR_INVALIDCALL;
}
*pHandle = CurrentPixelShaderHandle;
return D3D_OK;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::DeletePixelShader(DWORD Handle)
{
if (Handle == 0)
{
return D3DERR_INVALIDCALL;
}
if (CurrentPixelShaderHandle == Handle)
{
SetPixelShader(0);
}
reinterpret_cast<IDirect3DPixelShader9 *>(Handle)->Release();
return D3D_OK;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::SetPixelShaderConstant(DWORD Register, const void *pConstantData, DWORD ConstantCount)
{
return ProxyInterface->SetPixelShaderConstantF(Register, static_cast<const float *>(pConstantData), ConstantCount);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetPixelShaderConstant(DWORD Register, void *pConstantData, DWORD ConstantCount)
{
return ProxyInterface->GetPixelShaderConstantF(Register, static_cast<float *>(pConstantData), ConstantCount);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetPixelShaderFunction(DWORD Handle, void *pData, DWORD *pSizeOfData)
{
#ifndef D3D8TO9NOLOG
LOG << "Redirecting '" << "IDirect3DDevice8::GetPixelShaderFunction" << "(" << this << ", " << Handle << ", " << pData << ", " << pSizeOfData << ")' ..." << std::endl;
#endif
if (Handle == 0)
{
return D3DERR_INVALIDCALL;
}
IDirect3DPixelShader9 *const PixelShaderInterface = reinterpret_cast<IDirect3DPixelShader9 *>(Handle);
#ifndef D3D8TO9NOLOG
LOG << "> Returning translated shader byte code." << std::endl;
#endif
return PixelShaderInterface->GetFunction(pData, reinterpret_cast<UINT *>(pSizeOfData));
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::DrawRectPatch(UINT Handle, const float *pNumSegs, const D3DRECTPATCH_INFO *pRectPatchInfo)
{
return ProxyInterface->DrawRectPatch(Handle, pNumSegs, pRectPatchInfo);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::DrawTriPatch(UINT Handle, const float *pNumSegs, const D3DTRIPATCH_INFO *pTriPatchInfo)
{
return ProxyInterface->DrawTriPatch(Handle, pNumSegs, pTriPatchInfo);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::DeletePatch(UINT Handle)
{
return ProxyInterface->DeletePatch(Handle);
}
void Direct3DDevice8::ApplyClipPlanes()
{
DWORD index = 0;
for (const auto clipPlane : StoredClipPlanes)
{
if ((ClipPlaneRenderState & (1 << index)) != 0)
{
ProxyInterface->SetClipPlane(index, clipPlane);
}
index++;
}
} | [
"elisha@novicemail.com"
] | elisha@novicemail.com |
67469017ab553267ea7d9221761cc14ea0e5d711 | c5df61ec848d64ade567218c24554f47cef011d6 | /Actions/EditStatement.cpp | b45ebd908f9a7a977e1af93e0beccd11775cefaf | [] | no_license | abdallahmagdy1993/Flowchart-Simulator | cfa46026bb4526a5698351ecb6a88157b3e40958 | 4a5350e0d5627bba6945833902e921c27521d6e3 | refs/heads/master | 2021-01-10T14:44:52.371199 | 2018-02-21T11:34:17 | 2018-02-21T11:34:17 | 53,350,385 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,536 | cpp | #include "EditStatement.h"
#include "..\ApplicationManager.h"
#include "..\Statements\Statement.h"
#include "..\GUI\input.h"
#include "..\GUI\Output.h"
#include <sstream>
using namespace std;
//constructor: set the ApplicationManager pointer inside this action
EditStatement::EditStatement(ApplicationManager *pAppManager):Action(pAppManager)
{Stat=NULL;}
void EditStatement::ReadActionParameters()
{
Input *pIn = pManager->GetInput();
Output *pOut = pManager->GetOutput();
Stat=pManager->GetSelectedStatement();
if(Stat==NULL)
{
pOut->PrintMessage("no selected Statement");
return;
}
}
void EditStatement::Execute()
{
ReadActionParameters();
Input *pIn = pManager->GetInput();
Output *pOut = pManager->GetOutput();
if(Stat==NULL)
return;
if(Stat->GetStatType()=="VAR"||Stat->GetStatType()=="SNGLOP"||Stat->GetStatType()=="COND")
{
pManager->deleteVariable(Stat->getVar(0));
pManager->deleteVariable(Stat->getVar(1));
}
else pManager->deleteVariable(Stat->getVar(0));
Stat->Edit(pOut,pIn);
if(Stat->GetStatType()=="VAR"||Stat->GetStatType()=="SNGLOP"||Stat->GetStatType()=="COND")
{
Variable *V=pManager->AddVariable(Stat->getVar(0));
if(V)
Stat->setVar(V,0);
V=pManager->AddVariable(Stat->getVar(1));
if(V)
Stat->setVar(V,1);
}
else {
Variable *V= pManager->AddVariable(Stat->getVar(0));
if(V)
Stat->setVar(V,0);
}
if(Stat->GetStatType()!="STRT"&&Stat->GetStatType()!="END")
Stat->PrintInfo(pOut);
pManager->setEditedDesign(true);
pManager->UndoRedo();
}
| [
"abdallahmagdy1993@gmail.com"
] | abdallahmagdy1993@gmail.com |
0d2d18769ada564287724aee183dd011c0a2f1df | 256d76e96e3a70d5b3b025d8baa098c82d77d7fd | /untitled/animatedgraphicsitem.cpp | 303dd63a82c15752b2b503b6ab538b0f4d2138db | [] | no_license | creepcontrol/rpg_game | 368faf67be59e17feef20571912a8769dd48120c | d7892903c6c2a9319b62e43e35b271709c0a884b | refs/heads/master | 2020-03-19T06:51:31.869467 | 2018-06-05T02:57:21 | 2018-06-05T02:57:21 | 136,060,925 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,184 | cpp | #include "animatedgraphicsitem.h"
AnimatedGraphicsItem::AnimatedGraphicsItem(QObject *parent)
: QObject(parent)
{
connect(&m_timer, SIGNAL(timeout()), SLOT(on_timerTick()));
}
void AnimatedGraphicsItem::animation(AnimationID animationId, Mode mode,
bool randomStartFrame, int framerate) {
m_frames = &ANIMATION_POOL.get(animationId);
m_mode = mode;
m_timer.stop();
m_nFrames = m_frames->size();
if(randomStartFrame)
m_curFrameIndex = qrand() % m_nFrames;
else
m_curFrameIndex = 0;
setPixmap(*(*m_frames)[m_curFrameIndex]);
if (framerate > 0) {
m_timer.setInterval(1000/framerate);
m_timer.start();
}
}
void AnimatedGraphicsItem::on_timerTick() {
++m_curFrameIndex;
if (m_mode == Loop) {
if (m_curFrameIndex >= m_nFrames)
m_curFrameIndex = 0;
setPixmap(*(*m_frames)[m_curFrameIndex]);
}
else
{
if (m_curFrameIndex >= m_nFrames) {
m_timer.stop();
hide();
emit animationFinished();
}
else {
setPixmap(*(*m_frames)[m_curFrameIndex]);
}
}
}
| [
"creepcontrol@gmail.com"
] | creepcontrol@gmail.com |
761aa352e617c854e196235dab5c7048c6175ef5 | 2a89b925f76509239527425939a16a710919ee21 | /Cubby-master/Sources/GameGUI/InventoryGUI.cpp | 54b1dbcd371e24206d2d58962d27f74fb7c10b3b | [] | no_license | Hamule/Cubbys | c7f595f80539190e4a01c89470c266a2e365d087 | d0a2e4b86a3b78e7a8457c33416c7199577ac075 | refs/heads/master | 2021-01-11T05:42:07.046885 | 2016-11-01T15:26:39 | 2016-11-01T15:26:39 | 71,549,076 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 62,388 | cpp | /*************************************************************************
> File Name: InventoryGUI.h
> Project Name: Cubby
> Author: Chan-Ho Chris Ohk
> Purpose: Inventory GUI class.
> Created Time: 2016/09/01
> Copyright (c) 2016, Chan-Ho Chris Ohk
*************************************************************************/
#include <algorithm>
#include <CubbyGame.h>
#include <Models/VoxelObject.h>
#include <Utils/Random.h>
#include "ActionBar.h"
#include "InventoryGUI.h"
// Constructor, Destructor
InventoryGUI::InventoryGUI(Renderer* pRenderer, OpenGLGUI* pGUI, FrontendManager* pFrontendManager, ChunkManager* pChunkManager, Player* pPlayer, InventoryManager* pInventoryManager, int windowWidth, int windowHeight)
{
m_pRenderer = pRenderer;
m_pGUI = pGUI;
m_pFrontendManager = pFrontendManager;
m_pChunkManager = pChunkManager;
m_pPlayer = pPlayer;
m_pInventoryManager = pInventoryManager;
m_windowWidth = windowWidth;
m_windowHeight = windowHeight;
// Inventory Window
m_pInventoryWindow = new GUIWindow(m_pRenderer, m_pFrontendManager->GetFrontendFontMedium(), "Inventory");
m_pInventoryWindow->AllowMoving(true);
m_pInventoryWindow->AllowClosing(false);
m_pInventoryWindow->AllowMinimizing(false);
m_pInventoryWindow->AllowScrolling(false);
m_pInventoryWindow->SetRenderTitleBar(true);
m_pInventoryWindow->SetRenderWindowBackground(true);
m_pInventoryWindow->SetApplicationDimensions(m_windowWidth, m_windowHeight);
m_pInventoryWindow->Hide();
m_pTitleBarIcon = new Icon(m_pRenderer, "", 44, 44);
m_pTitleBarIcon->SetDepth(4.0f);
m_pInventoryWindowBackgroundIcon = new Icon(m_pRenderer, "", 400, 211);
m_pInventoryWindowBackgroundIcon->SetDepth(1.0f);
m_pTitleBarBackgroundIcon = new Icon(m_pRenderer, "", 133, 35);
m_pTitleBarBackgroundIcon->SetDepth(1.0f);
m_pCloseExitButton = new Button(m_pRenderer, m_pFrontendManager->GetFrontendFont30(), m_pFrontendManager->GetFrontendFont30Outline(), "", Color(1.0f, 1.0f, 1.0f, 1.0f), Color(0.0f, 0.0f, 0.0f, 1.0f));
m_pCloseExitButton->SetLabelOffset(0, 5);
m_pCloseExitButton->SetCallBackFunction(_CloseExitPressed);
m_pCloseExitButton->SetCallBackData(this);
m_pDestroyIcon = new Icon(m_pRenderer, "", 175, 65);
m_pDestroyIcon->SetDepth(2.1f);
char destroyText[] = "DESTROY";
m_pDestroyLabel = new Label(m_pRenderer, m_pFrontendManager->GetFrontendFont50(), destroyText, Color(1.0f, 1.0f, 1.0f, 0.25f));
m_pDestroyLabel->SetOutline(true);
m_pDestroyLabel->SetOutlineColor(Color(0.0f, 0.0f, 0.0f, 1.0f));
m_pDestroyLabel->SetOutlineFont(m_pFrontendManager->GetFrontendFont50Outline());
m_pDestroyLabel->SetDepth(3.0f);
m_pDropIcon = new Icon(m_pRenderer, "", 175, 65);
m_pDropIcon->SetDepth(2.1f);
char dropText[] = "DROP";
m_pDropLabel = new Label(m_pRenderer, m_pFrontendManager->GetFrontendFont50(), dropText, Color(1.0f, 1.0f, 1.0f, 0.25f));
m_pDropLabel->SetOutline(true);
m_pDropLabel->SetOutlineColor(Color(0.0f, 0.0f, 0.0f, 1.0f));
m_pDropLabel->SetOutlineFont(m_pFrontendManager->GetFrontendFont50Outline());
m_pDropLabel->SetDepth(3.0f);
m_pInventoryWindow->SetBackgroundIcon(m_pInventoryWindowBackgroundIcon);
m_pInventoryWindow->SetTitlebarBackgroundIcon(m_pTitleBarBackgroundIcon);
m_pInventoryWindow->AddComponent(m_pTitleBarIcon);
m_pInventoryWindow->AddComponent(m_pCloseExitButton);
m_pInventoryBackgroundSlotBorderCommon = new Icon(m_pRenderer, "", 64, 64);
m_pInventoryBackgroundSlotBorderCommon->SetDepth(2.0f);
m_pInventoryBackgroundSlotBorderUncommon = new Icon(m_pRenderer, "", 64, 64);
m_pInventoryBackgroundSlotBorderUncommon->SetDepth(2.0f);
m_pInventoryBackgroundSlotBorderMagical = new Icon(m_pRenderer, "", 64, 64);
m_pInventoryBackgroundSlotBorderMagical->SetDepth(2.0f);
m_pInventoryBackgroundSlotBorderRare = new Icon(m_pRenderer, "", 64, 64);
m_pInventoryBackgroundSlotBorderRare->SetDepth(2.0f);
m_pInventoryBackgroundSlotBorderEpic = new Icon(m_pRenderer, "", 64, 64);
m_pInventoryBackgroundSlotBorderEpic->SetDepth(2.0f);
// Tooltip
m_pTooltipBackgroundCommon = new Icon(m_pRenderer, "", 200, 220);
m_pTooltipBackgroundCommon->SetDepth(5.5f);
m_pTooltipBackgroundUncommon = new Icon(m_pRenderer, "", 200, 220);
m_pTooltipBackgroundUncommon->SetDepth(5.5f);
m_pTooltipBackgroundMagical = new Icon(m_pRenderer, "", 200, 220);
m_pTooltipBackgroundMagical->SetDepth(5.5f);
m_pTooltipBackgroundRare = new Icon(m_pRenderer, "", 200, 220);
m_pTooltipBackgroundRare->SetDepth(5.5f);
m_pTooltipBackgroundEpic = new Icon(m_pRenderer, "", 200, 220);
m_pTooltipBackgroundEpic->SetDepth(5.5f);
char nameText[] = "[ITEM]";
m_pTooltipNameLabel = new Label(m_pRenderer, m_pFrontendManager->GetFrontendFont30(), nameText, Color(1.0f, 1.0f, 1.0f, 1.0f));
m_pTooltipNameLabel->SetOutline(true);
m_pTooltipNameLabel->SetOutlineColor(Color(0.0f, 0.0f, 0.0f, 1.0f));
m_pTooltipNameLabel->SetOutlineFont(m_pFrontendManager->GetFrontendFont30Outline());
m_pTooltipNameLabel->SetDepth(5.5f);
char descText[] = "[REPLACE ME]";
m_pTooltipDescriptionLabel = new FormattedLabel(m_pRenderer, m_pFrontendManager->GetFrontendFont25(), m_pFrontendManager->GetFrontendFont25(), m_pFrontendManager->GetFrontendFont25(), descText);
m_pTooltipDescriptionLabel->SetOutline(true);
m_pTooltipDescriptionLabel->SetColor(Color(1.0f, 1.0f, 1.0f, 1.0f));
m_pTooltipDescriptionLabel->SetOutlineColor(Color(0.0f, 0.0f, 0.0f, 1.0f));
m_pTooltipDescriptionLabel->SetOutlineFont(m_pFrontendManager->GetFrontendFont25Outline());
m_pTooltipDescriptionLabel->SetDepth(5.5f);
m_pTooltipDescriptionLabel->SetWordWrap(true);
char slotText[] = "[SLOT]";
m_pTooltipSlotLabel = new Label(m_pRenderer, m_pFrontendManager->GetFrontendFont20(), slotText, Color(0.5f, 0.5f, 0.5f, 1.0f));
m_pTooltipSlotLabel->SetOutline(true);
m_pTooltipSlotLabel->SetOutlineColor(Color(0.0f, 0.0f, 0.0f, 1.0f));
m_pTooltipSlotLabel->SetOutlineFont(m_pFrontendManager->GetFrontendFont20Outline());
m_pTooltipSlotLabel->SetDepth(5.5f);
char qualityText[] = "[QUALITY]";
m_pTooltipQualityLabel = new Label(m_pRenderer, m_pFrontendManager->GetFrontendFont20(), qualityText, Color(0.5f, 0.5f, 0.5f, 1.0f));
m_pTooltipQualityLabel->SetOutline(true);
m_pTooltipQualityLabel->SetOutlineColor(Color(0.0f, 0.0f, 0.0f, 1.0f));
m_pTooltipQualityLabel->SetOutlineFont(m_pFrontendManager->GetFrontendFont20Outline());
m_pTooltipQualityLabel->SetDepth(5.5f);
// Popup
char popupTitleText[] = "[POPUP TITLE]";
m_popupTitle = new Label(m_pRenderer, m_pFrontendManager->GetFrontendFont40(), popupTitleText, Color(1.0f, 0.0f, 0.0f, 1.0f));
m_popupTitle->SetOutline(true);
m_popupTitle->SetOutlineColor(Color(0.0f, 0.0f, 0.0f, 1.0f));
m_popupTitle->SetOutlineFont(m_pFrontendManager->GetFrontendFont40Outline());
m_popupTitle->SetDepth(9.0f);
char popupText[] = "[POPUP TEXT]";
m_popupText = new FormattedLabel(m_pRenderer, m_pFrontendManager->GetFrontendFont25(), m_pFrontendManager->GetFrontendFont25(), m_pFrontendManager->GetFrontendFont25(), popupText);
m_popupText->SetOutline(true);
m_popupText->SetColor(Color(1.0f, 1.0f, 1.0f, 1.0f));
m_popupText->SetOutlineColor(Color(0.0f, 0.0f, 0.0f, 1.0f));
m_popupText->SetOutlineFont(m_pFrontendManager->GetFrontendFont25Outline());
m_popupText->SetDepth(9.0f);
m_popupText->SetWordWrap(true);
m_popupText->SetHorizontalAlignment(HorizontalAlignment::Center);
m_pPopupBackgroundIcon = new Icon(m_pRenderer, "", 270, 200);
m_pPopupBackgroundIcon->SetDepth(2.0f);
m_pPopupConfirmButton = new Button(m_pRenderer, m_pFrontendManager->GetFrontendFont30(), m_pFrontendManager->GetFrontendFont30Outline(), "Yes", Color(1.0f, 1.0f, 1.0f, 1.0f), Color(0.0f, 0.0f, 0.0f, 1.0f));
m_pPopupConfirmButton->SetLabelOffset(0, 3);
m_pPopupConfirmButton->SetPressedOffset(0, -4);
m_pPopupConfirmButton->SetCallBackFunction(_PopupConfirmPressed);
m_pPopupConfirmButton->SetCallBackData(this);
m_pPopupConfirmButton->SetDepth(9.0f);
m_pPopupCancelButton = new Button(m_pRenderer, m_pFrontendManager->GetFrontendFont30(), m_pFrontendManager->GetFrontendFont30Outline(), "No", Color(1.0f, 1.0f, 1.0f, 1.0f), Color(0.0f, 0.0f, 0.0f, 1.0f));
m_pPopupCancelButton->SetLabelOffset(0, 3);
m_pPopupCancelButton->SetPressedOffset(0, -4);
m_pPopupCancelButton->SetCallBackFunction(_PopupCancelPressed);
m_pPopupCancelButton->SetCallBackData(this);
m_pPopupCancelButton->SetDepth(9.1f);
SetWindowDimensions(m_windowWidth, m_windowHeight);
m_pInventoryItemToDelete = nullptr;
// Load delay
m_loadDelay = false;
m_loadDelayTime = 0.0f;
m_loaded = false;
}
InventoryGUI::~InventoryGUI()
{
delete m_pInventoryWindow;
delete m_pTitleBarIcon;
delete m_pTitleBarBackgroundIcon;
delete m_pInventoryWindowBackgroundIcon;
delete m_pCloseExitButton;
delete m_pDestroyIcon;
delete m_pDestroyLabel;
delete m_pDropIcon;
delete m_pDropLabel;
delete m_pInventoryBackgroundSlotBorderCommon;
delete m_pInventoryBackgroundSlotBorderUncommon;
delete m_pInventoryBackgroundSlotBorderMagical;
delete m_pInventoryBackgroundSlotBorderRare;
delete m_pInventoryBackgroundSlotBorderEpic;
// Tooltip
delete m_pTooltipBackgroundCommon;
delete m_pTooltipBackgroundUncommon;
delete m_pTooltipBackgroundMagical;
delete m_pTooltipBackgroundRare;
delete m_pTooltipBackgroundEpic;
delete m_pTooltipNameLabel;
delete m_pTooltipDescriptionLabel;
delete m_pTooltipSlotLabel;
delete m_pTooltipQualityLabel;
// Popup
delete m_popupTitle;
delete m_popupText;
delete m_pPopupConfirmButton;
delete m_pPopupCancelButton;
delete m_pPopupBackgroundIcon;
}
void InventoryGUI::SetCharacterGUI(CharacterGUI* pCharacterGUI)
{
m_pCharacterGUI = pCharacterGUI;
}
void InventoryGUI::SetLootGUI(LootGUI* pLootGUI)
{
m_pLootGUI = pLootGUI;
}
void InventoryGUI::SetActionBar(ActionBar* pActionBar)
{
m_pActionBar = pActionBar;
}
void InventoryGUI::SetItemManager(ItemManager *pItemManager)
{
m_pItemManager = pItemManager;
}
// Skinning the GUI
void InventoryGUI::SkinGUI()
{
std::string themeName = CubbyGame::GetInstance()->GetModsManager()->GetHUDTextureTheme();
std::string iconName = "Resources/textures/gui/" + themeName + "/InventoryGUI/inventory_title_icon.tga";
m_pTitleBarIcon->SetIcon(iconName);
iconName = "Resources/textures/gui/" + themeName + "/InventoryGUI/inventory_window_background.tga";
m_pInventoryWindowBackgroundIcon->SetIcon(iconName);
iconName = "Resources/textures/gui/" + themeName + "/InventoryGUI/titlebar_background.tga";
m_pTitleBarBackgroundIcon->SetIcon(iconName);
m_pInventoryWindow->SetBackgroundIcon(m_pInventoryWindowBackgroundIcon);
m_pInventoryWindow->SetTitlebarBackgroundIcon(m_pTitleBarBackgroundIcon);
Point location = m_pInventoryWindow->GetLocation();
m_pInventoryWindow->SetDimensions(location.x, location.y, m_inventoryWindowWidth, m_inventoryWindowHeight);
m_pInventoryWindow->SetTitleBarDimensions(0, 0, m_titlebarWidth, m_titlebarHeight);
iconName = "Resources/textures/gui/" + themeName + "/InventoryGUI/delete_background.tga";
m_pDestroyIcon->SetIcon(iconName);
iconName = "Resources/textures/gui/" + themeName + "/InventoryGUI/drop_background.tga";
m_pDropIcon->SetIcon(iconName);
iconName = "Resources/textures/gui/" + themeName + "/common/popup_background.tga";
m_pPopupBackgroundIcon->SetIcon(iconName);
m_pFrontendManager->SetButtonIcons(m_pPopupConfirmButton, ButtonSize::Size110x47);
m_pFrontendManager->SetButtonIcons(m_pPopupCancelButton, ButtonSize::Size110x47);
m_pCloseExitButton->SetDefaultIcon(m_pFrontendManager->GetCloseExitButtonIcon());
m_pCloseExitButton->SetHoverIcon(m_pFrontendManager->GetCloseExitButtonIconHover());
m_pCloseExitButton->SetSelectedIcon(m_pFrontendManager->GetCloseExitButtonIconPressed());
m_pCloseExitButton->SetDisabledIcon(m_pFrontendManager->GetCloseExitButtonIcon());
iconName = "Resources/textures/gui/" + themeName + "/common/items/border_common.tga";
m_pInventoryBackgroundSlotBorderCommon->SetIcon(iconName);
iconName = "Resources/textures/gui/" + themeName + "/common/items/border_uncommon.tga";
m_pInventoryBackgroundSlotBorderUncommon->SetIcon(iconName);
iconName = "Resources/textures/gui/" + themeName + "/common/items/border_magical.tga";
m_pInventoryBackgroundSlotBorderMagical->SetIcon(iconName);
iconName = "Resources/textures/gui/" + themeName + "/common/items/border_rare.tga";
m_pInventoryBackgroundSlotBorderRare->SetIcon(iconName);
iconName = "Resources/textures/gui/" + themeName + "/common/items/border_epic.tga";
m_pInventoryBackgroundSlotBorderEpic->SetIcon(iconName);
iconName = "Resources/textures/gui/" + themeName + "/common/Tooltips/tooltip_background_common.tga";
m_pTooltipBackgroundCommon->SetIcon(iconName);
iconName = "Resources/textures/gui/" + themeName + "/common/Tooltips/tooltip_background_uncommon.tga";
m_pTooltipBackgroundUncommon->SetIcon(iconName);
iconName = "Resources/textures/gui/" + themeName + "/common/Tooltips/tooltip_background_magical.tga";
m_pTooltipBackgroundMagical->SetIcon(iconName);
iconName = "Resources/textures/gui/" + themeName + "/common/Tooltips/tooltip_background_rare.tga";
m_pTooltipBackgroundRare->SetIcon(iconName);
iconName = "Resources/textures/gui/" + themeName + "/common/Tooltips/tooltip_background_epic.tga";
m_pTooltipBackgroundEpic->SetIcon(iconName);
m_pPopupConfirmButton->SetNormalLabelColor(m_pFrontendManager->GetNormalFontColor());
m_pPopupConfirmButton->SetHoverLabelColor(m_pFrontendManager->GetHoverFontColor());
m_pPopupConfirmButton->SetPressedLabelColor(m_pFrontendManager->GetPressedFontColor());
m_pPopupCancelButton->SetNormalLabelColor(m_pFrontendManager->GetNormalFontColor());
m_pPopupCancelButton->SetHoverLabelColor(m_pFrontendManager->GetHoverFontColor());
m_pPopupCancelButton->SetPressedLabelColor(m_pFrontendManager->GetPressedFontColor());
m_pInventoryManager->SetInventoryGUINeedsUpdate(true);
}
// ReSharper disable once CppMemberFunctionMayBeStatic
void InventoryGUI::UnSkinGUI() const
{
// Do nothing
}
// Loading
void InventoryGUI::Load(bool loadDelay, float loadDelayTime)
{
m_loadDelay = loadDelay;
m_loadDelayTime = loadDelayTime;
if (m_pInventoryManager->InventoryGUINeedsUpdate())
{
DeleteInventoryItems();
CreateInventoryItems();
UpdateActionBar();
for (size_t i = 0; i < m_vpInventorySlotItems.size(); ++i)
{
m_pInventoryWindow->AddComponent(m_vpInventorySlotItems[i]->m_pInventoryIcon);
}
}
if (m_loadDelay == false)
{
m_pGUI->AddWindow(m_pInventoryWindow);
m_pInventoryWindow->Show();
}
m_pPopupConfirmButton->SetLabelColor(m_pFrontendManager->GetNormalFontColor());
m_pPopupCancelButton->SetLabelColor(m_pFrontendManager->GetNormalFontColor());
m_pressedX = 0;
m_pressedY = 0;
m_pPressedInventoryItem = nullptr;
m_toolTipVisible = false;
m_tooltipAppearDelayTimer = 0.0f;
m_toolTipComponentsAdded = false;
m_tooltipQuality = ItemQuality::Common;
m_pInventoryItemToDelete = nullptr;
m_loaded = true;
}
void InventoryGUI::Unload()
{
m_loadDelay = false;
m_loadDelayTime = 0.0f;
HideTooltip();
m_pGUI->RemoveWindow(m_pInventoryWindow);
if (m_pPressedInventoryItem != nullptr)
{
m_pPressedInventoryItem->m_pInventoryIcon->SetDepth(3.0f);
m_pInventoryWindow->DepthSortComponentChildren();
m_pPressedInventoryItem->m_pInventoryIcon->SetLocation(m_pressedX, m_pressedY);
}
ClosePopup();
m_pGUI->RemoveComponent(m_pPopupBackgroundIcon);
m_pInventoryWindow->RemoveComponent(m_pDestroyIcon);
m_pInventoryWindow->RemoveComponent(m_pDestroyLabel);
m_pInventoryWindow->RemoveComponent(m_pDropIcon);
m_pInventoryWindow->RemoveComponent(m_pDropLabel);
m_loaded = false;
if (CubbyGame::GetInstance()->IsGUIWindowStillDisplayed() == false)
{
CubbyGame::GetInstance()->TurnCursorOff(false);
if (CubbyGame::GetInstance()->ShouldRestorePreviousCameraMode())
{
CubbyGame::GetInstance()->RestorePreviousCameraMode();
CubbyGame::GetInstance()->InitializeCameraRotation();
}
}
}
bool InventoryGUI::IsLoadDelayed() const
{
return (m_loadDelay == true && m_loadDelayTime > 0.0f);
}
void InventoryGUI::SetWindowDimensions(int windowWidth, int windowHeight)
{
m_windowWidth = windowWidth;
m_windowHeight = windowHeight;
m_inventoryWindowWidth = 412;
m_inventoryWindowHeight = 212;
m_titlebarWidth = 153;
m_titlebarHeight = 35;
m_popupWidth = 270;
m_popupHeight = 200;
m_popupBorderSpacer = 25;
m_popupTitleSpacer = 35;
m_popupIconSize = 50;
m_popupIconSpacer = 10;
m_pInventoryWindow->SetDimensions(m_windowWidth - 434, 175, m_inventoryWindowWidth, m_inventoryWindowHeight);
m_pInventoryWindow->SetTitleBarDimensions(0, 0, m_titlebarWidth, m_titlebarHeight);
m_pInventoryWindow->SetTitleOffset(50, 5);
m_pInventoryWindow->SetApplicationDimensions(m_windowWidth, m_windowHeight);
m_pInventoryWindow->SetApplicationBorder(25, 15, 10, 40);
m_pTitleBarIcon->SetDimensions(0, m_inventoryWindowHeight, 44, 44);
m_pCloseExitButton->SetDimensions(m_inventoryWindowWidth - 32, m_inventoryWindowHeight, 32, 32);
int x;
int y;
int width;
int height;
GetDestroySlotDimensions(&x, &y, &width, &height);
m_pDestroyIcon->SetDimensions(x, y, width, height);
int textWidth = m_pRenderer->GetFreeTypeTextWidth(m_pFrontendManager->GetFrontendFont50(), "%s", m_pDestroyLabel->GetText().c_str());
int textHeight = m_pRenderer->GetFreeTypeTextHeight(m_pFrontendManager->GetFrontendFont50(), "%s", m_pDestroyLabel->GetText().c_str());
m_pDestroyLabel->SetLocation(x + static_cast<int>((width * 0.5f) - (textWidth * 0.5f)), y + static_cast<int>((height * 0.5f) - (textHeight * 0.5f)) + 5);
GetDropSlotDimensions(&x, &y, &width, &height);
m_pDropIcon->SetDimensions(x, y, width, height);
textWidth = m_pRenderer->GetFreeTypeTextWidth(m_pFrontendManager->GetFrontendFont50(), "%s", m_pDropLabel->GetText().c_str());
textHeight = m_pRenderer->GetFreeTypeTextHeight(m_pFrontendManager->GetFrontendFont50(), "%s", m_pDropLabel->GetText().c_str());
m_pDropLabel->SetLocation(x + static_cast<int>((width * 0.5f) - (textWidth * 0.5f)), y + static_cast<int>((height * 0.5f) - (textHeight * 0.5f)) + 5);
// Popup
m_pPopupBackgroundIcon->SetDimensions(static_cast<int>((windowWidth * 0.5f) - (m_popupWidth * 0.5f)), static_cast<int>((windowHeight * 0.5f) - (m_popupHeight * 0.5f)) + 100, m_popupWidth, m_popupHeight);
}
// ReSharper disable once CppMemberFunctionMayBeStatic
void InventoryGUI::GetInventoryDimensions(int indexX, int indexY, int* x, int* y, int* width, int *height) const
{
int slotSize = 64;
int slotSpacer = 4;
int borderSize = 4;
int xSlotPos = borderSize + ((slotSize + slotSpacer) * indexX);
int ySlotPos = 4 + borderSize + ((slotSize + slotSpacer) * indexY);
*x = xSlotPos;
*y = ySlotPos;
*width = slotSize;
*height = slotSize;
}
// ReSharper disable once CppMemberFunctionMayBeStatic
void InventoryGUI::GetDestroySlotDimensions(int* x, int* y, int* width, int* height) const
{
*x = 220;
*y = -75;
*width = 175;
*height = 65;
}
// ReSharper disable once CppMemberFunctionMayBeStatic
void InventoryGUI::GetDropSlotDimensions(int* x, int* y, int* width, int* height) const
{
*x = 10;
*y = -75;
*width = 175;
*height = 65;
}
GUIWindow* InventoryGUI::GetInventoryWindow() const
{
return m_pInventoryWindow;
}
void InventoryGUI::CreateInventoryItems()
{
// Item draggable Buttons
for (int i = 0; i < MAX_NUM_SLOTS_VERTICAL; ++i)
{
for (int j = 0; j < MAX_NUM_SLOTS_HORIZONTAL; ++j)
{
InventoryItem* pItem = m_pInventoryManager->GetInventoryItemForSlot(j, i);
if (pItem != nullptr)
{
int x;
int y;
int width;
int height;
GetInventoryDimensions(j, i, &x, &y, &width, &height);
DraggableRenderRectangle* pNewSlotItem = new DraggableRenderRectangle(m_pRenderer);
switch (pItem->m_itemQuality)
{
case ItemQuality::Common: { pNewSlotItem->SetIcon(m_pInventoryBackgroundSlotBorderCommon); break; }
case ItemQuality::Uncommon: { pNewSlotItem->SetIcon(m_pInventoryBackgroundSlotBorderUncommon); break; }
case ItemQuality::Magical: { pNewSlotItem->SetIcon(m_pInventoryBackgroundSlotBorderMagical); break; }
case ItemQuality::Rare: { pNewSlotItem->SetIcon(m_pInventoryBackgroundSlotBorderRare); break; }
case ItemQuality::Epic: { pNewSlotItem->SetIcon(m_pInventoryBackgroundSlotBorderEpic); break; }
default: throw std::logic_error("Invalid ItemQuality in CreateInventoryItems()");
}
pNewSlotItem->SetDimensions(x, y, width, height);
pNewSlotItem->SetDepth(3.0f);
char itemTexture[128];
sprintf(itemTexture, "%s", pItem->m_iconFileName.c_str());
pNewSlotItem->AddIcon(m_pRenderer, itemTexture, 64, 64, 56, 56, 4, 4, 1.5f);
std::string themeName = CubbyGame::GetInstance()->GetModsManager()->GetHUDTextureTheme();
switch (pItem->m_itemQuality)
{
case ItemQuality::Common:
{
std::string itemBackgroundIcon = "Resources/textures/gui/" + themeName + "/common/items/item_background_common.tga";
pNewSlotItem->AddIcon(m_pRenderer, itemBackgroundIcon.c_str(), 64, 64, 64, 64, 0, 0, 1.0f);
break;
}
case ItemQuality::Uncommon:
{
std::string itemBackgroundIcon = "Resources/textures/gui/" + themeName + "/common/items/item_background_uncommon.tga";
pNewSlotItem->AddIcon(m_pRenderer, itemBackgroundIcon.c_str(), 64, 64, 64, 64, 0, 0, 1.0f);
break;
}
case ItemQuality::Magical:
{
std::string itemBackgroundIcon = "Resources/textures/gui/" + themeName + "/common/items/item_background_magical.tga";
pNewSlotItem->AddIcon(m_pRenderer, itemBackgroundIcon.c_str(), 64, 64, 64, 64, 0, 0, 1.0f);
break;
}
case ItemQuality::Rare:
{
std::string itemBackgroundIcon = "Resources/textures/gui/" + themeName + "/common/items/item_background_rare.tga";
pNewSlotItem->AddIcon(m_pRenderer, itemBackgroundIcon.c_str(), 64, 64, 64, 64, 0, 0, 1.0f);
break;
}
case ItemQuality::Epic:
{
std::string itemBackgroundIcon = "Resources/textures/gui/" + themeName + "/common/items/item_background_epic.tga";
pNewSlotItem->AddIcon(m_pRenderer, itemBackgroundIcon.c_str(), 64, 64, 64, 64, 0, 0, 1.0f);
break;
}
default: throw std::logic_error("Invalid ItemQuality in CreateInventoryItems()");
}
if (pItem->m_quantity != -1)
{
char quantity[128];
sprintf(quantity, "%i", pItem->m_quantity);
int textWidth = m_pRenderer->GetFreeTypeTextWidth(m_pFrontendManager->GetFrontendFont18(), "%s", quantity);
pNewSlotItem->AddText(m_pRenderer, m_pFrontendManager->GetFrontendFont18(), m_pFrontendManager->GetFrontendFont18Outline(), quantity, Color(1.0f, 1.0f, 1.0f, 1.0f), width - 10 - textWidth, 8, true, Color(0.0f, 0.0f, 0.0f, 1.0f));
}
InventorySlotItem* pNewItem = new InventorySlotItem();
pNewItem->m_pInventoryGUI = this;
pNewItem->m_pInventoryItem = pItem;
pNewItem->m_pInventoryIcon = pNewSlotItem;
pNewItem->m_slotX = j;
pNewItem->m_slotY = i;
pNewItem->m_dropshadowAdded = false;
pNewItem->m_erase = false;
m_vpInventorySlotItems.push_back(pNewItem);
pNewSlotItem->SetPressedCallBackFunction(_InventoryItemPressed);
pNewSlotItem->SetPressedCallBackData(pNewItem);
pNewSlotItem->SetReleasedCallBackFunction(_InventoryItemReleased);
pNewSlotItem->SetReleasedCallBackData(pNewItem);
pNewSlotItem->SetEnterCallBackFunction(_InventoryItemEntered);
pNewSlotItem->SetEnterCallBackData(pNewItem);
pNewSlotItem->SetExitCallBackFunction(_InventoryItemExited);
pNewSlotItem->SetExitCallBackData(pNewItem);
}
}
}
m_pInventoryManager->SetInventoryGUINeedsUpdate(false);
}
void InventoryGUI::DeleteInventoryItems()
{
// Clear item draggable buttons
for (size_t i = 0; i < m_vpInventorySlotItems.size(); ++i)
{
m_pInventoryWindow->RemoveComponent(m_vpInventorySlotItems[i]->m_pInventoryIcon);
delete m_vpInventorySlotItems[i]->m_pInventoryIcon;
m_vpInventorySlotItems[i]->m_pInventoryIcon = nullptr;
delete m_vpInventorySlotItems[i];
m_vpInventorySlotItems[i] = nullptr;
}
m_vpInventorySlotItems.clear();
}
void InventoryGUI::UpdateActionBar()
{
// We need to relink the action bar to the inventory GUI, since we have deleted and re-created the inventory buttons
for (size_t i = 0; i < m_vpInventorySlotItems.size(); ++i)
{
for (int j = 0; j < ActionBar::MAX_NUM_ACTION_SLOTS; ++j)
{
ActionButtonItem* pActionBarItem = m_pActionBar->GetActionButtonForSlot(j);
if (pActionBarItem != nullptr)
{
if (pActionBarItem->m_inventoryX == m_vpInventorySlotItems[i]->m_slotX && pActionBarItem->m_inventoryY == m_vpInventorySlotItems[i]->m_slotY)
{
if (pActionBarItem->m_inventoryX == -1 && pActionBarItem->m_inventoryY == -1)
{
if (pActionBarItem->m_equipSlot == m_vpInventorySlotItems[i]->m_pInventoryItem->m_equipSlot)
{
// In the situation where the loaded action button has a -1, -1 slot index, we also need to check the item slot type before assigning this pointer
pActionBarItem->m_itemTitle = m_vpInventorySlotItems[i]->m_pInventoryItem->m_title;
}
}
else
{
pActionBarItem->m_itemTitle = m_vpInventorySlotItems[i]->m_pInventoryItem->m_title;
}
}
}
}
}
}
// Tooltips
void InventoryGUI::UpdateToolTipAppear(float dt)
{
if (m_toolTipVisible)
{
if (m_tooltipAppearDelayTimer <= 0.0f)
{
if (m_toolTipComponentsAdded == false)
{
switch (m_tooltipQuality)
{
case ItemQuality::Common: { m_pInventoryWindow->AddComponent(m_pTooltipBackgroundCommon); break; }
case ItemQuality::Uncommon: { m_pInventoryWindow->AddComponent(m_pTooltipBackgroundUncommon); break; }
case ItemQuality::Magical: { m_pInventoryWindow->AddComponent(m_pTooltipBackgroundMagical); break; }
case ItemQuality::Rare: { m_pInventoryWindow->AddComponent(m_pTooltipBackgroundRare); break; }
case ItemQuality::Epic: { m_pInventoryWindow->AddComponent(m_pTooltipBackgroundEpic); break; }
default: throw std::logic_error("Invalid ItemQuality in UpdateToolTipAppear()");
}
m_pInventoryWindow->AddComponent(m_pTooltipNameLabel);
m_pInventoryWindow->AddComponent(m_pTooltipDescriptionLabel);
m_pInventoryWindow->AddComponent(m_pTooltipSlotLabel);
m_pInventoryWindow->AddComponent(m_pTooltipQualityLabel);
m_toolTipComponentsAdded = true;
}
}
else
{
m_tooltipAppearDelayTimer -= dt;
}
}
}
void InventoryGUI::ShowTooltip(InventorySlotItem* pInventoryItem)
{
if (m_toolTipVisible == true)
{
return;
}
// Set the focused window when we show a tooltip
m_pInventoryWindow->SetFocusWindow();
// Replace the tooltip name
m_pTooltipNameLabel->SetText(pInventoryItem->m_pInventoryItem->m_title);
// Replace the tooltip description
std::string DescriptionText = pInventoryItem->m_pInventoryItem->m_description + pInventoryItem->m_pInventoryItem->GetStatsAttributeString();
m_pTooltipDescriptionLabel->SetText(DescriptionText);
// Replace the tooltip equipslot text
char slotText[32];
switch (pInventoryItem->m_pInventoryItem->m_equipSlot)
{
case EquipSlot::NoSlot: { sprintf(slotText, ""); break; }
case EquipSlot::LeftHand:
{
if (pInventoryItem->m_pInventoryItem->m_right)
{
sprintf(slotText, "Two Handed");
}
else
{
sprintf(slotText, "Left Hand");
}
break;
}
case EquipSlot::RightHand:
{
if (pInventoryItem->m_pInventoryItem->m_left)
{
sprintf(slotText, "Two Handed");
}
else
{
sprintf(slotText, "Right Hand");
}
break;
}
case EquipSlot::Head: { sprintf(slotText, "Head"); break; }
case EquipSlot::Shoulders: { sprintf(slotText, "Shoulders"); break; }
case EquipSlot::Body: { sprintf(slotText, "Body"); break; }
case EquipSlot::Legs: { sprintf(slotText, "Legs"); break; }
case EquipSlot::Hand: { sprintf(slotText, "Hand"); break; }
case EquipSlot::Feet: { sprintf(slotText, "Feet"); break; }
case EquipSlot::Accessory1: { sprintf(slotText, "Accessory 1"); break; }
case EquipSlot::Accessory2: { sprintf(slotText, "Accessory 2"); break; }
default: throw std::logic_error("Invalid EquipSlot in ShowTooltip()");
}
m_pTooltipSlotLabel->SetText(slotText);
// Replace the tooltip quality text
char qualityText[32];
Color qualityColor;
switch (pInventoryItem->m_pInventoryItem->m_itemQuality)
{
case ItemQuality::Common: { sprintf(qualityText, "Common"); qualityColor = Color(0.5f, 0.5f, 0.5f, 1.0f); break; }
case ItemQuality::Uncommon: { sprintf(qualityText, "Uncommon"); qualityColor = Color(0.95f, 1.0f, 0.2f, 1.0f); break; }
case ItemQuality::Magical: { sprintf(qualityText, "Magical"); qualityColor = Color(0.0f, 1.0f, 0.0f, 1.0f); break; }
case ItemQuality::Rare: { sprintf(qualityText, "Rare"); qualityColor = Color(0.0f, 0.5f, 1.0f, 1.0f); break; }
case ItemQuality::Epic: { sprintf(qualityText, "Epic"); qualityColor = Color(0.64f, 0.2f, 0.93f, 1.0f); break; }
default: throw std::logic_error("Invalid ItemQuality in ShowTooltip()");
}
m_pTooltipQualityLabel->SetText(qualityText);
m_pTooltipQualityLabel->SetColor(qualityColor);
m_pTooltipNameLabel->SetColor(qualityColor);
// Set tooltip dimensions
m_tooltipWidth = 200;
m_tooltipHeight = 220;
m_tooltipDescBorder = 15;
int x;
int y;
int width;
int height;
GetInventoryDimensions(pInventoryItem->m_slotX, pInventoryItem->m_slotY, &x, &y, &width, &height);
if (CubbyGame::GetInstance()->GetWindowCursorX() > m_tooltipWidth + 50)
{
x = x + 20 - m_tooltipWidth;
}
else
{
x = x + 30;
}
if ((m_windowHeight - CubbyGame::GetInstance()->GetWindowCursorY()) > m_windowHeight - m_tooltipHeight - 50)
{
y = y + 20 - m_tooltipHeight;
}
else
{
y = y + 30;
}
m_pTooltipBackgroundCommon->SetDimensions(x, y, m_tooltipWidth, m_tooltipHeight);
m_pTooltipBackgroundUncommon->SetDimensions(x, y, m_tooltipWidth, m_tooltipHeight);
m_pTooltipBackgroundMagical->SetDimensions(x, y, m_tooltipWidth, m_tooltipHeight);
m_pTooltipBackgroundRare->SetDimensions(x, y, m_tooltipWidth, m_tooltipHeight);
m_pTooltipBackgroundEpic->SetDimensions(x, y, m_tooltipWidth, m_tooltipHeight);
int textWidth = m_pRenderer->GetFreeTypeTextWidth(m_pFrontendManager->GetFrontendFont30(), "%s", m_pTooltipNameLabel->GetText().c_str());
m_pTooltipNameLabel->SetLocation(x + static_cast<int>(m_tooltipWidth * 0.5f) - static_cast<int>(textWidth * 0.5f), y + m_tooltipHeight - 35);
m_pTooltipDescriptionLabel->SetDimensions(x + m_tooltipDescBorder, y + m_tooltipDescBorder, m_tooltipWidth - (m_tooltipDescBorder * 2), m_tooltipHeight - (m_tooltipDescBorder * 2) - 35);
m_pTooltipSlotLabel->SetLocation(x + m_tooltipDescBorder, y + m_tooltipDescBorder);
textWidth = m_pRenderer->GetFreeTypeTextWidth(m_pFrontendManager->GetFrontendFont20(), "%s", m_pTooltipQualityLabel->GetText().c_str());
m_pTooltipQualityLabel->SetLocation(x + m_tooltipWidth - m_tooltipDescBorder - textWidth, y + m_tooltipDescBorder);
m_tooltipQuality = pInventoryItem->m_pInventoryItem->m_itemQuality;
m_tooltipAppearDelayTimer = m_pFrontendManager->GetToolTipAppearDelay();
m_toolTipVisible = true;
m_toolTipComponentsAdded = false;
}
void InventoryGUI::HideTooltip()
{
m_pInventoryWindow->RemoveComponent(m_pTooltipBackgroundCommon);
m_pInventoryWindow->RemoveComponent(m_pTooltipBackgroundUncommon);
m_pInventoryWindow->RemoveComponent(m_pTooltipBackgroundMagical);
m_pInventoryWindow->RemoveComponent(m_pTooltipBackgroundRare);
m_pInventoryWindow->RemoveComponent(m_pTooltipBackgroundEpic);
m_pInventoryWindow->RemoveComponent(m_pTooltipNameLabel);
m_pInventoryWindow->RemoveComponent(m_pTooltipDescriptionLabel);
m_pInventoryWindow->RemoveComponent(m_pTooltipSlotLabel);
m_pInventoryWindow->RemoveComponent(m_pTooltipQualityLabel);
m_toolTipVisible = false;
}
void InventoryGUI::OpenPopup(std::string popupTitle, std::string popupText) const
{
m_pPopupConfirmButton->SetLabelColor(m_pFrontendManager->GetNormalFontColor());
m_pPopupCancelButton->SetLabelColor(m_pFrontendManager->GetNormalFontColor());
int textWidth = m_pRenderer->GetFreeTypeTextWidth(m_pFrontendManager->GetFrontendFont40(), "%s", popupTitle.c_str());
m_popupTitle->SetLocation(static_cast<int>((m_windowWidth * 0.5f) - (textWidth * 0.5f)), static_cast<int>((m_windowHeight * 0.5f) + (m_popupHeight * 0.5f)) - m_popupTitleSpacer - m_popupBorderSpacer + 100);
m_popupText->SetDimensions(static_cast<int>((m_windowWidth * 0.5f) - (m_popupWidth * 0.5f)) + m_popupBorderSpacer, static_cast<int>((m_windowHeight * 0.5f) - (m_popupHeight * 0.5f)) + 100, m_popupWidth - (m_popupBorderSpacer * 2), m_popupHeight - m_popupBorderSpacer - m_popupTitleSpacer);
m_pPopupConfirmButton->SetDimensions(static_cast<int>((m_windowWidth * 0.5f) + (m_popupWidth * 0.5f)) - static_cast<int>(m_popupBorderSpacer * 0.5f) - 110, static_cast<int>((m_windowHeight * 0.5f) - (m_popupIconSize * 0.5f)) - 50 + 100, 110, 47);
m_pPopupCancelButton->SetDimensions(static_cast<int>((m_windowWidth * 0.5f) - (m_popupWidth * 0.5f)) + static_cast<int>(m_popupBorderSpacer * 0.5f), static_cast<int>((m_windowHeight * 0.5f) - (m_popupIconSize * 0.5f)) - 50 + 100, 110, 47);
m_popupTitle->SetText(popupTitle);
m_popupText->SetText(popupText);
m_pGUI->AddComponent(m_popupTitle);
m_pGUI->AddComponent(m_popupText);
m_pGUI->AddComponent(m_pPopupConfirmButton);
m_pGUI->AddComponent(m_pPopupCancelButton);
m_pGUI->AddComponent(m_pPopupBackgroundIcon);
}
void InventoryGUI::ClosePopup() const
{
m_pGUI->RemoveComponent(m_popupTitle);
m_pGUI->RemoveComponent(m_popupText);
m_pGUI->RemoveComponent(m_pPopupConfirmButton);
m_pGUI->RemoveComponent(m_pPopupCancelButton);
m_pGUI->RemoveComponent(m_pPopupBackgroundIcon);
}
bool InventoryGUI::IsLoaded() const
{
return m_loaded;
}
InventorySlotItem* InventoryGUI::GetInventorySlotItem(int x, int y)
{
for (size_t i = 0; i < m_vpInventorySlotItems.size(); ++i)
{
if (m_vpInventorySlotItems[i]->m_slotX == x && m_vpInventorySlotItems[i]->m_slotY == y)
{
return m_vpInventorySlotItems[i];
}
}
return nullptr;
}
InventorySlotItem* InventoryGUI::GetInventorySlotItemEquipped(EquipSlot equipSlot)
{
InventoryItem* pInventoryItem = m_pInventoryManager->GetInventoryItemForEquipSlot(equipSlot);
if (pInventoryItem != nullptr)
{
for (size_t i = 0; i < m_vpInventorySlotItems.size(); ++i)
{
if (m_vpInventorySlotItems[i]->m_pInventoryItem == pInventoryItem)
{
return m_vpInventorySlotItems[i];
}
}
}
return nullptr;
}
void InventoryGUI::SetEquippedItem(EquipSlot equipSlot, std::string title)
{
m_pEquippedItems[static_cast<int>(equipSlot)] = title;
}
void InventoryGUI::SetBlockType(InventoryItem* pInventoryItem)
{
if (pInventoryItem->m_item == ItemType::BlockDirt)
{
m_pPlayer->SetNowBlock(ItemType::BlockDirt);
}
else if (pInventoryItem->m_item == ItemType::BlockSnow)
{
m_pPlayer->SetNowBlock(ItemType::BlockSnow);
}
else if (pInventoryItem->m_item == ItemType::BlockSand)
{
m_pPlayer->SetNowBlock(ItemType::BlockSand);
}
else if (pInventoryItem->m_item == ItemType::BlockWood)
{
m_pPlayer->SetNowBlock(ItemType::BlockWood);
}
else if (pInventoryItem->m_item == ItemType::BlockGrass)
{
m_pPlayer->SetNowBlock(ItemType::BlockGrass);
}
}
void InventoryGUI::EquipItem(InventoryItem* pInventoryItem, int inventoryX, int inventoryY)
{
// Set the player to know that we have equipped an item
m_pPlayer->EquipItem(pInventoryItem);
SetBlockType(pInventoryItem);
// If we already have an item in this equipment slot, switch it out
if (m_pEquippedItems[static_cast<int>(pInventoryItem->m_equipSlot)] != "")
{
m_pActionBar->UpdateActionBarSlots(m_pEquippedItems[static_cast<int>(pInventoryItem->m_equipSlot)], inventoryX, inventoryY);
}
m_pActionBar->UpdateActionBarSlots(pInventoryItem, -1, -1);
// Equip the new item
m_pEquippedItems[static_cast<int>(pInventoryItem->m_equipSlot)] = pInventoryItem->m_title;
}
void InventoryGUI::EquipItem(LootSlotItem* pLootItem) const
{
// Set the player to know that we have equipped an item
m_pPlayer->EquipItem(pLootItem->m_pInventoryItem);
}
void InventoryGUI::EquipItem(InventorySlotItem* pInventoryItem)
{
// Set the player to know that we have equipped an item
m_pPlayer->EquipItem(pInventoryItem->m_pInventoryItem);
// If we already have an item in this equipment slot, switch it out
if (m_pEquippedItems[static_cast<int>(pInventoryItem->m_pInventoryItem->m_equipSlot)] != "")
{
m_pActionBar->UpdateActionBarSlots(m_pEquippedItems[static_cast<int>(pInventoryItem->m_pInventoryItem->m_equipSlot)], pInventoryItem->m_slotX, pInventoryItem->m_slotY);
}
m_pActionBar->UpdateActionBarSlots(pInventoryItem->m_pInventoryItem, -1, -1);
// Equip the new item
m_pEquippedItems[static_cast<int>(pInventoryItem->m_pInventoryItem->m_equipSlot)] = pInventoryItem->m_pInventoryItem->m_title;
pInventoryItem->m_slotX = -1;
pInventoryItem->m_slotY = -1;
}
void InventoryGUI::UnequipItem(EquipSlot equipSlot, bool left, bool right)
{
m_pEquippedItems[static_cast<int>(equipSlot)] = "";
m_pPlayer->UnequipItem(equipSlot, left, right);
}
void InventoryGUI::Update(float dt)
{
if (m_loadDelay == true)
{
if (m_loadDelayTime <= 0.0f)
{
m_loadDelay = false;
m_pGUI->AddWindow(m_pInventoryWindow);
m_pInventoryWindow->Show();
}
else
{
m_loadDelayTime -= dt;
}
}
UpdateToolTipAppear(dt);
// Check if the inventory GUI needs update (we have moved items in the inventory or got new items)
if (m_pInventoryManager->InventoryGUINeedsUpdate() && IsLoaded() == true)
{
m_pGUI->RemoveWindow(m_pInventoryWindow);
DeleteInventoryItems();
CreateInventoryItems();
UpdateActionBar();
for (size_t i = 0; i < m_vpInventorySlotItems.size(); ++i)
{
m_pInventoryWindow->AddComponent(m_vpInventorySlotItems[i]->m_pInventoryIcon);
}
m_pGUI->AddWindow(m_pInventoryWindow);
m_pInventoryWindow->Show();
}
}
void InventoryGUI::_InventoryItemPressed(void* pData)
{
InventorySlotItem* pInventoryItem = static_cast<InventorySlotItem*>(pData);
pInventoryItem->m_pInventoryGUI->InventoryItemPressed(pInventoryItem);
}
void InventoryGUI::InventoryItemPressed(InventorySlotItem* pInventoryItem)
{
m_pPressedInventoryItem = pInventoryItem;
Dimensions dimensions = m_pPressedInventoryItem->m_pInventoryIcon->GetDimensions();
m_pressedX = dimensions.x;
m_pressedY = dimensions.y;
m_pInventoryWindow->AddComponent(m_pDestroyIcon);
m_pInventoryWindow->AddComponent(m_pDestroyLabel);
m_pInventoryWindow->AddComponent(m_pDropIcon);
m_pInventoryWindow->AddComponent(m_pDropLabel);
// Temporarily increase the depth of the dragged icon
if (m_pPressedInventoryItem->m_dropshadowAdded == false)
{
m_pPressedInventoryItem->m_dropshadowAdded = true;
m_pPressedInventoryItem->m_pInventoryIcon->SetDepth(5.0f);
//m_pPressedInventoryItem->m_pInventoryIcon->SetLocation(m_pressedX - 4, m_pressedY + 4);
std::string themeName = CubbyGame::GetInstance()->GetModsManager()->GetHUDTextureTheme();
std::string dropShadowIcon = "Resources/textures/gui/" + themeName + "/common/items/drop_shadow.tga";
m_pPressedInventoryItem->m_pInventoryIcon->AddIcon(m_pRenderer, dropShadowIcon.c_str(), 64, 64, 64, 64, 4, -4, 0.5f);
}
m_pInventoryWindow->DepthSortComponentChildren();
HideTooltip();
}
bool IsNeedErase(InventorySlotItem* item)
{
bool isNeedErase = item->m_erase;
if (isNeedErase == true)
{
delete item->m_pInventoryIcon;
delete item;
}
return isNeedErase;
}
void InventoryGUI::_InventoryItemReleased(void* pData)
{
InventorySlotItem* pInventoryItem = static_cast<InventorySlotItem*>(pData);
pInventoryItem->m_pInventoryGUI->InventoryItemReleased(pInventoryItem);
}
void InventoryGUI::InventoryItemReleased(InventorySlotItem* pInventoryItem)
{
if (m_pPressedInventoryItem == nullptr)
{
return;
}
m_pPressedInventoryItem = nullptr;
if (m_pPlayer->IsCrafting())
{
// Don't allow to do any inventory changing if we are crafting.
// Reset back to the original position
pInventoryItem->m_pInventoryIcon->SetLocation(m_pressedX, m_pressedY);
if (pInventoryItem->m_dropshadowAdded == true)
{
pInventoryItem->m_dropshadowAdded = false;
std::string themeName = CubbyGame::GetInstance()->GetModsManager()->GetHUDTextureTheme();
std::string dropShadowIcon = "Resources/textures/gui/" + themeName + "/common/items/drop_shadow.tga";
pInventoryItem->m_pInventoryIcon->RemoveIcon(dropShadowIcon.c_str());
}
m_pInventoryWindow->RemoveComponent(m_pDestroyIcon);
m_pInventoryWindow->RemoveComponent(m_pDestroyLabel);
m_pInventoryWindow->RemoveComponent(m_pDropIcon);
m_pInventoryWindow->RemoveComponent(m_pDropLabel);
return;
}
// Figure out if we need to change to a different inventory slot
int x;
int y;
int width;
int height;
POINT mouse = { CubbyGame::GetInstance()->GetWindowCursorX(), (m_windowHeight - CubbyGame::GetInstance()->GetWindowCursorY()) };
bool switched = false;
for (int i = 0; i < MAX_NUM_SLOTS_VERTICAL; ++i)
{
for (int j = 0; j < MAX_NUM_SLOTS_HORIZONTAL; ++j)
{
GetInventoryDimensions(j, i, &x, &y, &width, &height);
// Check if we released (mouse cursor) in the boundary of another slot
if (mouse.x > m_pInventoryWindow->GetDimensions().x + x && mouse.x < m_pInventoryWindow->GetDimensions().x + x + width && mouse.y > m_pInventoryWindow->GetDimensions().y + y && mouse.y < m_pInventoryWindow->GetDimensions().y + y + height)
{
if (pInventoryItem->m_pInventoryItem->m_equipped == true)
{
// Check if another inventory item already exists in this slot
InventorySlotItem* pInventorySlotItem = GetInventorySlotItem(j, i);
if (pInventorySlotItem == nullptr)
{
// We are unequipping an item that is in one of the equipment slots
m_pInventoryManager->UnequipItem(j, i, pInventoryItem->m_pInventoryItem->m_equipSlot);
UnequipItem(pInventoryItem->m_pInventoryItem->m_equipSlot, pInventoryItem->m_pInventoryItem->m_left, pInventoryItem->m_pInventoryItem->m_right);
// Set the new location for the released inventory icon
pInventoryItem->m_slotX = j;
pInventoryItem->m_slotY = i;
pInventoryItem->m_pInventoryIcon->SetLocation(x, y);
m_pActionBar->UpdateActionBarSlots(pInventoryItem->m_pInventoryItem, j, i);
switched = true;
}
else
{
if (pInventorySlotItem->m_pInventoryItem->m_equipSlot == pInventoryItem->m_pInventoryItem->m_equipSlot)
{
// We are swapping an equipped item for one in the inventory
UnequipItem(pInventoryItem->m_pInventoryItem->m_equipSlot, pInventoryItem->m_pInventoryItem->m_left, pInventoryItem->m_pInventoryItem->m_right);
m_pInventoryManager->UnequipItem(j, i, pInventoryItem->m_pInventoryItem->m_equipSlot);
// Equip the new item
//m_pInventoryManager->EquipInventoryItem(pInventorySlotItem->m_slotX, pInventorySlotItem->m_slotY, pInventorySlotItem->m_pInventoryItem->m_equipSlot);
EquipItem(pInventorySlotItem);
// Set the new location for the released inventory icon
pInventoryItem->m_slotX = j;
pInventoryItem->m_slotY = i;
pInventoryItem->m_pInventoryIcon->SetLocation(x, y);
switched = true;
}
}
}
else
{
// Check if another inventory item already exists in this slot
InventorySlotItem* pInventorySlotItem = GetInventorySlotItem(j, i);
// Switch the inventory item in this slot to the pressed (previous) position
if (pInventorySlotItem != nullptr)
{
pInventorySlotItem->m_slotX = pInventoryItem->m_slotX;
pInventorySlotItem->m_slotY = pInventoryItem->m_slotY;
pInventorySlotItem->m_pInventoryIcon->SetLocation(m_pressedX, m_pressedY);
m_pActionBar->UpdateActionBarSlots(pInventorySlotItem->m_pInventoryItem, pInventoryItem->m_slotX, pInventoryItem->m_slotY);
}
// Switch the items in the inventory manager
m_pInventoryManager->SwitchInventoryItems(pInventoryItem->m_slotX, pInventoryItem->m_slotY, j, i);
// Set the new location for the released inventory icon
pInventoryItem->m_slotX = j;
pInventoryItem->m_slotY = i;
pInventoryItem->m_pInventoryIcon->SetLocation(x, y);
m_pActionBar->UpdateActionBarSlots(pInventoryItem->m_pInventoryItem, j, i);
switched = true;
}
}
}
}
if (switched)
{
ShowTooltip(pInventoryItem);
}
bool equipped = false;
bool deleted = false;
if (switched == false)
{
if (pInventoryItem->m_pInventoryItem->m_equipSlot != EquipSlot::NoSlot)
{
// Check if we need to equip the item after dropping on the player portrait
if (m_pCharacterGUI->IsLoaded())
{
m_pCharacterGUI->GetPlayerPortraitDimensions(&x, &y, &width, &height);
GUIWindow* pCharacterWindow = m_pCharacterGUI->GetCharacterWindow();
if (mouse.x > pCharacterWindow->GetDimensions().x + x && mouse.x < pCharacterWindow->GetDimensions().x + x + width && mouse.y > pCharacterWindow->GetDimensions().y + y && mouse.y < pCharacterWindow->GetDimensions().y + y + height)
{
if (pInventoryItem->m_pInventoryItem->m_equipped == false)
{
// Dual handed weapon checks
if (pInventoryItem->m_pInventoryItem->m_equipSlot == EquipSlot::RightHand)
{
InventoryItem* pLeftHanded = m_pInventoryManager->GetInventoryItemForEquipSlot(EquipSlot::LeftHand);
if (pInventoryItem->m_pInventoryItem->m_left || (pLeftHanded != nullptr && pLeftHanded->m_right))
{
int slotX;
int slotY;
// Unequip the left hand slot since we are dual handed, OR the already equipped left hand item needs both hands
UnequipItem(EquipSlot::LeftHand, false, false);
if (m_pInventoryManager->UnequipItemToFreeInventorySlot(EquipSlot::LeftHand, &slotX, &slotY) == false)
{
// We can't fit the other item in the inventory
}
else if (pLeftHanded != nullptr)
{
m_pActionBar->UpdateActionBarSlots(pLeftHanded, slotX, slotY);
}
}
}
if (pInventoryItem->m_pInventoryItem->m_equipSlot == EquipSlot::LeftHand)
{
InventoryItem* pRightHanded = m_pInventoryManager->GetInventoryItemForEquipSlot(EquipSlot::RightHand);
if (pInventoryItem->m_pInventoryItem->m_right || (pRightHanded != nullptr && pRightHanded->m_left))
{
int slotX;
int slotY;
// Unequip the right hand slot since we are dual handed, OR the already equipped right hand item needs both hands
UnequipItem(EquipSlot::RightHand, false, false);
if (m_pInventoryManager->UnequipItemToFreeInventorySlot(EquipSlot::RightHand, &slotX, &slotY) == false)
{
// We can't fit the other item in the inventory
}
else if (pRightHanded != nullptr)
{
m_pActionBar->UpdateActionBarSlots(pRightHanded, slotX, slotY);
}
}
}
m_pPlayer->UnequipItem(pInventoryItem->m_pInventoryItem->m_equipSlot, pInventoryItem->m_pInventoryItem->m_left, pInventoryItem->m_pInventoryItem->m_right);
m_pInventoryManager->EquipInventoryItem(pInventoryItem->m_slotX, pInventoryItem->m_slotY, pInventoryItem->m_pInventoryItem->m_equipSlot);
EquipItem(pInventoryItem);
m_pInventoryWindow->RemoveComponent(pInventoryItem->m_pInventoryIcon);
pInventoryItem->m_erase = true;
m_vpInventorySlotItems.erase(remove_if(m_vpInventorySlotItems.begin(), m_vpInventorySlotItems.end(), IsNeedErase), m_vpInventorySlotItems.end());
m_pInventoryManager->SetInventoryGUINeedsUpdate(true);
m_pInventoryManager->SetCharacterGUINeedsUpdate(true);
m_pCharacterGUI->HideEquipHover();
equipped = true;
}
}
if (equipped == false)
{
// Check if we need to equip the item after dropping on a equipment slot
switch (pInventoryItem->m_pInventoryItem->m_equipSlot)
{
case EquipSlot::NoSlot: { x = 0; y = 0; width = 0; height = 0; } break;
case EquipSlot::RightHand: { m_pCharacterGUI->GetPlayerWeaponRightDimensions(&x, &y, &width, &height); } break;
case EquipSlot::LeftHand: { m_pCharacterGUI->GetPlayerWeaponLeftDimensions(&x, &y, &width, &height); } break;
case EquipSlot::Head: { m_pCharacterGUI->GetPlayerHeadDimensions(&x, &y, &width, &height); } break;
case EquipSlot::Shoulders: { m_pCharacterGUI->GetPlayerShoulderDimensions(&x, &y, &width, &height); } break;
case EquipSlot::Body: { m_pCharacterGUI->GetPlayerBodyDimensions(&x, &y, &width, &height); } break;
case EquipSlot::Legs: { m_pCharacterGUI->GetPlayerLegsDimensions(&x, &y, &width, &height); } break;
case EquipSlot::Hand: { m_pCharacterGUI->GetPlayerHandDimensions(&x, &y, &width, &height); } break;
case EquipSlot::Feet: { m_pCharacterGUI->GetPlayerFeetDimensions(&x, &y, &width, &height); } break;
case EquipSlot::Accessory1: { m_pCharacterGUI->GetPlayerAccessory1Dimensions(&x, &y, &width, &height); } break;
case EquipSlot::Accessory2: { m_pCharacterGUI->GetPlayerAccessory2Dimensions(&x, &y, &width, &height); } break;
default: throw std::logic_error("Invalid EquipSlot in InventoryItemReleased()");
}
GUIWindow* pCharacterWindow2 = m_pCharacterGUI->GetCharacterWindow();
if (mouse.x > pCharacterWindow2->GetDimensions().x + x && mouse.x < pCharacterWindow2->GetDimensions().x + x + width && mouse.y > pCharacterWindow2->GetDimensions().y + y && mouse.y < pCharacterWindow2->GetDimensions().y + y + height)
{
if (pInventoryItem->m_pInventoryItem->m_equipped == false)
{
// Dual handed weapon checks
if (pInventoryItem->m_pInventoryItem->m_equipSlot == EquipSlot::RightHand)
{
InventoryItem* pLeftHanded = m_pInventoryManager->GetInventoryItemForEquipSlot(EquipSlot::LeftHand);
if (pInventoryItem->m_pInventoryItem->m_left || (pLeftHanded != nullptr && pLeftHanded->m_right))
{
int slotX;
int slotY;
// Unequip the left hand slot since we are dual handed, OR the already equipped left hand item needs both hands
UnequipItem(EquipSlot::LeftHand, false, false);
if (m_pInventoryManager->UnequipItemToFreeInventorySlot(EquipSlot::LeftHand, &slotX, &slotY) == false)
{
// We can't fit the other item in the inventory
}
else if (pLeftHanded != nullptr)
{
m_pActionBar->UpdateActionBarSlots(pLeftHanded, slotX, slotY);
}
}
}
if (pInventoryItem->m_pInventoryItem->m_equipSlot == EquipSlot::LeftHand)
{
InventoryItem* pRightHanded = m_pInventoryManager->GetInventoryItemForEquipSlot(EquipSlot::RightHand);
if (pInventoryItem->m_pInventoryItem->m_right || (pRightHanded != nullptr && pRightHanded->m_left))
{
int slotX;
int slotY;
// Unequip the right hand slot since we are dual handed, OR the already equipped right hand item needs both hands
UnequipItem(EquipSlot::RightHand, false, false);
if (m_pInventoryManager->UnequipItemToFreeInventorySlot(EquipSlot::RightHand, &slotX, &slotY) == false)
{
// We can't fit the other item in the inventory
}
else if (pRightHanded != nullptr)
{
m_pActionBar->UpdateActionBarSlots(pRightHanded, slotX, slotY);
}
}
}
m_pPlayer->UnequipItem(pInventoryItem->m_pInventoryItem->m_equipSlot, pInventoryItem->m_pInventoryItem->m_left, pInventoryItem->m_pInventoryItem->m_right);
m_pInventoryManager->EquipInventoryItem(pInventoryItem->m_slotX, pInventoryItem->m_slotY, pInventoryItem->m_pInventoryItem->m_equipSlot);
EquipItem(pInventoryItem);
m_pInventoryWindow->RemoveComponent(pInventoryItem->m_pInventoryIcon);
pInventoryItem->m_erase = true;
m_vpInventorySlotItems.erase(remove_if(m_vpInventorySlotItems.begin(), m_vpInventorySlotItems.end(), IsNeedErase), m_vpInventorySlotItems.end());
m_pInventoryManager->SetInventoryGUINeedsUpdate(true);
m_pInventoryManager->SetCharacterGUINeedsUpdate(true);
m_pCharacterGUI->HideEquipHover();
equipped = true;
}
}
}
}
}
if (equipped == false)
{
// Check if we have released on a loot slot
if (m_pLootGUI->IsLoaded())
{
for (int i = 0; i < LootGUI::MAX_NUM_SLOTS_VERTICAL; ++i)
{
for (int j = 0; j < LootGUI::MAX_NUM_SLOTS_HORIZONTAL; ++j)
{
m_pLootGUI->GetLootDimensions(j, i, &x, &y, &width, &height);
GUIWindow* pLootWindow = m_pLootGUI->GetLootWindow();
// Check if we released (mouse cursor) in the boundary of another slot
if (mouse.x > pLootWindow->GetDimensions().x + x && mouse.x < pLootWindow->GetDimensions().x + x + width && mouse.y > pLootWindow->GetDimensions().y + y && mouse.y < pLootWindow->GetDimensions().y + y + height)
{
if (m_pLootGUI->GetLootSlotItem(j, i) == NULL) // ONLY if an item doesn't already exist in the loot slot position
{
m_pLootGUI->AddLootItemFromInventory(pInventoryItem->m_pInventoryItem, j, i);
m_pInventoryManager->RemoveInventoryItem(pInventoryItem->m_slotX, pInventoryItem->m_slotY);
m_pActionBar->RemoveInventoryItemFromActionBar(pInventoryItem->m_pInventoryItem->m_title);
m_pInventoryWindow->RemoveComponent(pInventoryItem->m_pInventoryIcon);
pInventoryItem->m_erase = true;
m_vpInventorySlotItems.erase(remove_if(m_vpInventorySlotItems.begin(), m_vpInventorySlotItems.end(), IsNeedErase), m_vpInventorySlotItems.end());
m_pCharacterGUI->HideEquipHover();
switched = true;
deleted = true;
}
}
}
}
}
// Check if we released on a action bar slot
if (CubbyGame::GetInstance()->GetCubbySettings()->m_renderGUI)
{
if (m_pActionBar->IsLoaded())
{
for (int i = 0; i < ActionBar::MAX_NUM_ACTION_SLOTS; ++i)
{
m_pActionBar->GetActionSlotDimensions(i, &x, &y, &width, &height);
// Check if we released (mouse cursor) in the boundary of another slot
if (mouse.x > x && mouse.x < x + width && mouse.y > y && mouse.y < y + height)
{
m_pActionBar->AddItemToActionBar(pInventoryItem->m_pInventoryItem, i, pInventoryItem->m_slotX, pInventoryItem->m_slotY);
m_pActionBar->ExportActionBar(m_pPlayer->GetName());
}
}
}
}
if (switched == false)
{
// Check if we need to drop the item into the world
GetDropSlotDimensions(&x, &y, &width, &height);
if (mouse.x > m_pInventoryWindow->GetDimensions().x + x && mouse.x < m_pInventoryWindow->GetDimensions().x + x + width && mouse.y > m_pInventoryWindow->GetDimensions().y + y && mouse.y < m_pInventoryWindow->GetDimensions().y + y + height)
{
if (pInventoryItem->m_slotX == -1 && pInventoryItem->m_slotY == -1)
{
// Do nothing
}
else
{
// Drop the item in the world
glm::vec3 vel = glm::vec3(GetRandomNumber(-1, 1, 2), 0.0f, GetRandomNumber(-1, 1, 2)) * GetRandomNumber(2, 3, 2);
Item* pItem = m_pItemManager->CreateItem(m_pPlayer->GetCenter(), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 0.0f, 0.0f), pInventoryItem->m_pInventoryItem->m_fileName.c_str(), ItemType::DroppedItem, pInventoryItem->m_pInventoryItem->m_title.c_str(), true, false, 0.08f);
if (pItem != nullptr)
{
pItem->SetGravityDirection(glm::vec3(0.0f, -1.0f, 0.0f));
pItem->SetVelocity(normalize(vel)*4.5f + glm::vec3(0.0f, 9.5f + GetRandomNumber(3, 6, 2), 0.0f));
pItem->SetRotation(glm::vec3(0.0f, GetRandomNumber(0, 360, 2), 0.0f));
pItem->SetAngularVelocity(glm::vec3(0.0f, 90.0f, 0.0f));
pItem->SetDroppedItem(pInventoryItem->m_pInventoryItem->m_fileName.c_str(), pInventoryItem->m_pInventoryItem->m_iconFileName.c_str(), pInventoryItem->m_pInventoryItem->m_itemType, pInventoryItem->m_pInventoryItem->m_item, pInventoryItem->m_pInventoryItem->m_status, pInventoryItem->m_pInventoryItem->m_equipSlot, pInventoryItem->m_pInventoryItem->m_itemQuality, pInventoryItem->m_pInventoryItem->m_left, pInventoryItem->m_pInventoryItem->m_right, pInventoryItem->m_pInventoryItem->m_title.c_str(), pInventoryItem->m_pInventoryItem->m_description.c_str(), pInventoryItem->m_pInventoryItem->m_placementR, pInventoryItem->m_pInventoryItem->m_placementG, pInventoryItem->m_pInventoryItem->m_placementB, pInventoryItem->m_pInventoryItem->m_quantity);
pItem->SetCollisionEnabled(false);
for (int i = 0; i < static_cast<int>(pInventoryItem->m_pInventoryItem->m_vpStatAttributes.size()); ++i)
{
pItem->GetDroppedInventoryItem()->AddStatAttribute(pInventoryItem->m_pInventoryItem->m_vpStatAttributes[i]->GetType(), pInventoryItem->m_pInventoryItem->m_vpStatAttributes[i]->GetModifyAmount());
}
int numY = pItem->GetVoxelItem()->GetAnimatedSection(0)->pVoxelObject->GetQubicleModel()->GetQubicleMatrix(0)->m_matrixSizeY;
pItem->GetVoxelItem()->SetRenderOffset(glm::vec3(0.0f, numY * 0.5f, 0.0f));
}
m_pInventoryManager->RemoveInventoryItem(pInventoryItem->m_slotX, pInventoryItem->m_slotY);
m_pActionBar->RemoveInventoryItemFromActionBar(pInventoryItem->m_pInventoryItem->m_title);
m_pInventoryWindow->RemoveComponent(pInventoryItem->m_pInventoryIcon);
pInventoryItem->m_erase = true;
m_vpInventorySlotItems.erase(remove_if(m_vpInventorySlotItems.begin(), m_vpInventorySlotItems.end(), IsNeedErase), m_vpInventorySlotItems.end());
m_pCharacterGUI->HideEquipHover();
switched = true;
deleted = true;
}
}
// Check if we need to delete the item
GetDestroySlotDimensions(&x, &y, &width, &height);
if (mouse.x > m_pInventoryWindow->GetDimensions().x + x && mouse.x < m_pInventoryWindow->GetDimensions().x + x + width && mouse.y > m_pInventoryWindow->GetDimensions().y + y && mouse.y < m_pInventoryWindow->GetDimensions().y + y + height)
{
if (pInventoryItem->m_slotX == -1 && pInventoryItem->m_slotY == -1)
{
// Do nothing
}
else
{
if (CubbyGame::GetInstance()->GetCubbySettings()->m_confirmItemDelete)
{
char popupTitle[256];
sprintf(popupTitle, "Delete");
char popupText[256];
sprintf(popupText, "Are you sure you want to delete [C=Custom(00A2E8)]%s[C=White]?", pInventoryItem->m_pInventoryItem->m_title.c_str());
OpenPopup(popupTitle, popupText);
m_pInventoryItemToDelete = pInventoryItem;
m_pCharacterGUI->HideEquipHover();
switched = false;
deleted = false;
}
else
{
if (pInventoryItem != nullptr)
{
m_pInventoryManager->RemoveInventoryItem(pInventoryItem->m_slotX, pInventoryItem->m_slotY);
m_pActionBar->RemoveInventoryItemFromActionBar(pInventoryItem->m_pInventoryItem->m_title);
m_pInventoryWindow->RemoveComponent(pInventoryItem->m_pInventoryIcon);
pInventoryItem->m_erase = true;
m_vpInventorySlotItems.erase(remove_if(m_vpInventorySlotItems.begin(), m_vpInventorySlotItems.end(), IsNeedErase), m_vpInventorySlotItems.end());
switched = true;
deleted = true;
}
}
}
}
}
}
}
// Revert depth back to normal for inventory icons
if (deleted == false && equipped == false)
{
pInventoryItem->m_pInventoryIcon->SetDepth(3.0f);
if (pInventoryItem->m_dropshadowAdded == true)
{
pInventoryItem->m_dropshadowAdded = false;
std::string themeName = CubbyGame::GetInstance()->GetModsManager()->GetHUDTextureTheme();
std::string dropShadowIcon = "Resources/textures/gui/" + themeName + "/common/items/drop_shadow.tga";
pInventoryItem->m_pInventoryIcon->RemoveIcon(dropShadowIcon.c_str());
}
m_pInventoryWindow->DepthSortComponentChildren();
}
// Reset back to the original position
if (switched == false && equipped == false)
{
pInventoryItem->m_pInventoryIcon->SetLocation(m_pressedX, m_pressedY);
if (pInventoryItem->m_dropshadowAdded == true)
{
pInventoryItem->m_dropshadowAdded = false;
std::string themeName = CubbyGame::GetInstance()->GetModsManager()->GetHUDTextureTheme();
std::string dropShadowIcon = "Resources/textures/gui/" + themeName + "/common/items/drop_shadow.tga";
pInventoryItem->m_pInventoryIcon->RemoveIcon(dropShadowIcon.c_str());
}
}
m_pInventoryWindow->RemoveComponent(m_pDestroyIcon);
m_pInventoryWindow->RemoveComponent(m_pDestroyLabel);
m_pInventoryWindow->RemoveComponent(m_pDropIcon);
m_pInventoryWindow->RemoveComponent(m_pDropLabel);
}
void InventoryGUI::_InventoryItemEntered(void* pData)
{
InventorySlotItem* pInventoryItem = static_cast<InventorySlotItem*>(pData);
pInventoryItem->m_pInventoryGUI->InventoryItemEntered(pInventoryItem);
}
void InventoryGUI::InventoryItemEntered(InventorySlotItem* pInventoryItem)
{
ShowTooltip(pInventoryItem);
if (m_pCharacterGUI->IsLoaded())
{
m_pCharacterGUI->ShowEquipHover(pInventoryItem->m_pInventoryItem->m_equipSlot);
}
}
void InventoryGUI::_InventoryItemExited(void* pData)
{
InventorySlotItem* pInventoryItem = static_cast<InventorySlotItem*>(pData);
pInventoryItem->m_pInventoryGUI->InventoryItemExited(pInventoryItem);
}
void InventoryGUI::InventoryItemExited(InventorySlotItem* pInventoryItem)
{
HideTooltip();
m_pCharacterGUI->HideEquipHover();
}
void InventoryGUI::_CloseExitPressed(void *pData)
{
InventoryGUI* pInventoryGUI = static_cast<InventoryGUI*>(pData);
pInventoryGUI->CloseExitPressed();
}
void InventoryGUI::CloseExitPressed()
{
Unload();
}
void InventoryGUI::_PopupConfirmPressed(void* pData)
{
InventoryGUI* pInventoryGUI = static_cast<InventoryGUI*>(pData);
pInventoryGUI->PopupConfirmPressed();
}
void InventoryGUI::PopupConfirmPressed()
{
if (m_pInventoryItemToDelete != nullptr)
{
m_pInventoryManager->RemoveInventoryItem(m_pInventoryItemToDelete->m_slotX, m_pInventoryItemToDelete->m_slotY);
m_pActionBar->RemoveInventoryItemFromActionBar(m_pInventoryItemToDelete->m_pInventoryItem->m_title);
m_pInventoryWindow->RemoveComponent(m_pInventoryItemToDelete->m_pInventoryIcon);
m_pInventoryItemToDelete->m_erase = true;
m_vpInventorySlotItems.erase(remove_if(m_vpInventorySlotItems.begin(), m_vpInventorySlotItems.end(), IsNeedErase), m_vpInventorySlotItems.end());
}
ClosePopup();
}
void InventoryGUI::_PopupCancelPressed(void* pData)
{
InventoryGUI* pInventoryGUI = static_cast<InventoryGUI*>(pData);
pInventoryGUI->PopupCancelPressed();
}
void InventoryGUI::PopupCancelPressed()
{
m_pInventoryItemToDelete = nullptr;
ClosePopup();
} | [
"black4roach@gmail.com"
] | black4roach@gmail.com |
e1b1a85d62118ce9d4025a013e63333d3cc70173 | 9dc335630cb97246a7d67ddf652b404701cece61 | /CAD/CAD_Verano/Ejercicio2_5_Wtime_SEND/Ejercicio2_5_Wtime_SEND.cpp | 25bb60e4e0ab93f41cedffbe53616efe22f7739c | [] | 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 | UTF-8 | C++ | false | false | 1,006 | cpp | #include <stdio.h>
#include "mpi.h"
int main(int argc, char* arcv[]) {
int nombre_proceso, total_procesos, flag = 0, origen, destino;
//double inicio, termina;
int valor;
MPI_Status status;
MPI_Init(NULL, NULL);
MPI_Comm_rank(MPI_COMM_WORLD, &nombre_proceso);
MPI_Comm_size(MPI_COMM_WORLD, &total_procesos);
if (nombre_proceso != 0)
{
valor = 1;
destino = 0;
MPI_Send(&valor, 1, MPI_INT, destino, flag, MPI_COMM_WORLD);
printf("Esclavo. Proceso: %d enviando valor %d a master.", nombre_proceso, valor);
}
else
{
for (int origen = 1; origen < total_procesos; origen++)
{
//Inicia el intervalo
double inicio = MPI_Wtime();
MPI_Recv(&valor, 1, MPI_INT, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
//Finaliza el intervalo
double termina = MPI_Wtime();
printf("Master. Proceso: %d ha recibido el valor %d del proceso %d. Tiempo de proceso: %f\n",
nombre_proceso, valor, status.MPI_SOURCE, (termina - inicio));
}
}
MPI_Finalize();
return 0;
} | [
"androidgalaxys42@gmail.com"
] | androidgalaxys42@gmail.com |
62bda1f85a7d459e8f2cad6be7f7d0bf96c66924 | 1f1cc05377786cc2aa480cbdfde3736dd3930f73 | /xulrunner-sdk-26/xulrunner-sdk/include/nsIDOMConstructor.h | c270c51a698330dd5af8ba987a42a84abce9f5c5 | [
"Apache-2.0"
] | permissive | julianpistorius/gp-revolution-gaia | 84c3ec5e2f3b9e76f19f45badc18d5544bb76e0d | 6e27b83efb0d4fa4222eaf25fb58b062e6d9d49e | refs/heads/master | 2021-01-21T02:49:54.000389 | 2014-03-27T09:58:17 | 2014-03-27T09:58:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,438 | h | /*
* DO NOT EDIT. THIS FILE IS GENERATED FROM /builds/slave/m-cen-l64-xr-ntly-000000000000/build/dom/interfaces/base/nsIDOMConstructor.idl
*/
#ifndef __gen_nsIDOMConstructor_h__
#define __gen_nsIDOMConstructor_h__
#ifndef __gen_domstubs_h__
#include "domstubs.h"
#endif
/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
/* starting interface: nsIDOMDOMConstructor */
#define NS_IDOMDOMCONSTRUCTOR_IID_STR "0ccbcf19-d1b4-489e-984c-cd8c43672bb9"
#define NS_IDOMDOMCONSTRUCTOR_IID \
{0x0ccbcf19, 0xd1b4, 0x489e, \
{ 0x98, 0x4c, 0xcd, 0x8c, 0x43, 0x67, 0x2b, 0xb9 }}
class NS_NO_VTABLE nsIDOMDOMConstructor : public nsISupports {
public:
NS_DECLARE_STATIC_IID_ACCESSOR(NS_IDOMDOMCONSTRUCTOR_IID)
/* AString toString (); */
NS_IMETHOD ToString(nsAString & _retval) = 0;
};
NS_DEFINE_STATIC_IID_ACCESSOR(nsIDOMDOMConstructor, NS_IDOMDOMCONSTRUCTOR_IID)
/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSIDOMDOMCONSTRUCTOR \
NS_IMETHOD ToString(nsAString & _retval);
/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSIDOMDOMCONSTRUCTOR(_to) \
NS_IMETHOD ToString(nsAString & _retval) { return _to ToString(_retval); }
/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSIDOMDOMCONSTRUCTOR(_to) \
NS_IMETHOD ToString(nsAString & _retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->ToString(_retval); }
#if 0
/* Use the code below as a template for the implementation class for this interface. */
/* Header file */
class nsDOMDOMConstructor : public nsIDOMDOMConstructor
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIDOMDOMCONSTRUCTOR
nsDOMDOMConstructor();
private:
~nsDOMDOMConstructor();
protected:
/* additional members */
};
/* Implementation file */
NS_IMPL_ISUPPORTS1(nsDOMDOMConstructor, nsIDOMDOMConstructor)
nsDOMDOMConstructor::nsDOMDOMConstructor()
{
/* member initializers and constructor code */
}
nsDOMDOMConstructor::~nsDOMDOMConstructor()
{
/* destructor code */
}
/* AString toString (); */
NS_IMETHODIMP nsDOMDOMConstructor::ToString(nsAString & _retval)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* End of implementation class template. */
#endif
#endif /* __gen_nsIDOMConstructor_h__ */
| [
"luis@geeksphone.com"
] | luis@geeksphone.com |
c47cc29a6ae02a5b03b9e9ffa0fff38ab9f059bf | 19b4aea6c829b272ae29692ccc51f9ab8dcf573f | /src/winrt/impl/Windows.UI.Notifications.Management.2.h | 20032b7daeb18f2bf52ef5814e9421c8a7cb9575 | [
"MIT"
] | permissive | liquidboy/X | 9665573b6e30dff8912ab64a8daf08f9f3176628 | bf94a0af4dd06ab6c66027afdcda88eda0b4ae47 | refs/heads/master | 2022-12-10T17:41:15.490231 | 2021-12-07T01:31:38 | 2021-12-07T01:31:38 | 51,222,325 | 29 | 9 | null | 2021-08-04T21:30:44 | 2016-02-06T21:16:04 | C++ | UTF-8 | C++ | false | false | 665 | h | // C++/WinRT v1.0.170906.1
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
#include "winrt/impl/Windows.UI.Notifications.1.h"
#include "winrt/impl/Windows.UI.Notifications.Management.1.h"
WINRT_EXPORT namespace winrt::Windows::UI::Notifications::Management {
}
namespace winrt::impl {
}
WINRT_EXPORT namespace winrt::Windows::UI::Notifications::Management {
struct WINRT_EBO UserNotificationListener :
Windows::UI::Notifications::Management::IUserNotificationListener
{
UserNotificationListener(std::nullptr_t) noexcept {}
static Windows::UI::Notifications::Management::UserNotificationListener Current();
};
}
| [
"fajardo_jf@hotmail.com"
] | fajardo_jf@hotmail.com |
301a8e3d88bc32f6110059c54ca1cbc7f30c5861 | 6d6906fd33e913fcb904f83fa24d6c18bfe64e72 | /Mainwind/Mainwind/GeneratedFiles/Release/moc_trprint.cpp | 16ff29b8a2b5d6e9837daa62c3d075ba1ee25b81 | [] | no_license | thunderning/blood | d2ef5043e88a7e45d7a547f37a7bf6eb019c86c3 | f9e5f51834b15a26e1a873d8f02e877c97d77f9b | refs/heads/master | 2021-01-21T13:08:20.707739 | 2016-03-28T17:47:32 | 2016-03-28T17:47:32 | 54,815,760 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,558 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'trprint.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.6.0)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../trprint.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'trprint.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.6.0. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
struct qt_meta_stringdata_trprint_t {
QByteArrayData data[1];
char stringdata0[8];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_trprint_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_trprint_t qt_meta_stringdata_trprint = {
{
QT_MOC_LITERAL(0, 0, 7) // "trprint"
},
"trprint"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_trprint[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
0, 0, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
0 // eod
};
void trprint::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
Q_UNUSED(_o);
Q_UNUSED(_id);
Q_UNUSED(_c);
Q_UNUSED(_a);
}
const QMetaObject trprint::staticMetaObject = {
{ &QDialog::staticMetaObject, qt_meta_stringdata_trprint.data,
qt_meta_data_trprint, qt_static_metacall, Q_NULLPTR, Q_NULLPTR}
};
const QMetaObject *trprint::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *trprint::qt_metacast(const char *_clname)
{
if (!_clname) return Q_NULLPTR;
if (!strcmp(_clname, qt_meta_stringdata_trprint.stringdata0))
return static_cast<void*>(const_cast< trprint*>(this));
return QDialog::qt_metacast(_clname);
}
int trprint::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QDialog::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
return _id;
}
QT_END_MOC_NAMESPACE
| [
"498279281@qq.com"
] | 498279281@qq.com |
e8391581cd9a3ddc9d67059feeeda8181aa7b2ce | c646eda22844eb3aadc832a55dc8a7a8d8b28656 | /CodeForces/ProblemSet/788A--Functions again.cpp | c6a7f386afc53770c3d40fc57fe3c31a29f27acf | [] | no_license | daidai21/ExerciseProblem | 78f41f20f6d12cd71c510241d5fe829af676a764 | cdc526fdb4ee1ca8e0d6334fecc4932d55019cea | refs/heads/master | 2021-11-22T21:54:13.106707 | 2021-11-14T10:54:37 | 2021-11-14T10:54:37 | 213,108,530 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,182 | cpp | // https://codeforces.com/problemset/problem/788/A
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; ++i)
cin >> a[i];
vector<int> b(n);
for (int i = 0; i < n - 1; ++i)
b[i] = abs(a[i] - a[i + 1]);
vector<vector<long long int>> dp(2, vector<long long int>(n));
dp[1][0] = b[0];
dp[0][0] = 0;
long long int res = dp[1][0];
for (int i = 1; i < n - 1; ++i) {
dp[1][i] = max(0LL + b[i], dp[0][i - 1] + b[i]);
dp[0][i] = dp[1][i - 1] - b[i];
res = max(res, dp[1][i]);
res = max(res, dp[0][i]);
}
cout << res << endl;
return 0;
}
/*
// overtime
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; ++i)
cin >> a[i];
int result = 0;
for (int l = 0; l < n - 1; ++l) {
for (int r = l + 1; r < n; ++r) {
int f_sum = 0;
for (int i = l; i < r; ++i) {
f_sum += abs(a[i] - a[i + 1]) * pow(-1, i - l);
}
result = max(result, f_sum);
}
}
cout << result << endl;
return 0;
}
*/
| [
"daidai4269@aliyun.com"
] | daidai4269@aliyun.com |
537c9254e256c3f42220a3ba90b0a0c8e16f8e39 | 6d59b8fa0ac393720a687a8d5cbe80ab25ff97a4 | /aws-cpp-sdk-ssm/include/aws/ssm/model/UpdateOpsItemRequest.h | 17ab82e46155f72509939309c9f192be48ff2d69 | [
"MIT",
"Apache-2.0",
"JSON"
] | permissive | 175703252/aws-sdk-cpp | 20149ad1b06d5b7759fb01a45bf1214e298ba306 | c07bd636471ba79f709b03a489a1a036b655d3b2 | refs/heads/master | 2021-03-10T20:43:30.772193 | 2020-03-10T19:19:04 | 2020-03-10T19:19:04 | 246,483,735 | 1 | 0 | Apache-2.0 | 2020-03-11T05:34:57 | 2020-03-11T05:34:56 | null | UTF-8 | C++ | false | false | 44,417 | h | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#pragma once
#include <aws/ssm/SSM_EXPORTS.h>
#include <aws/ssm/SSMRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSMap.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/ssm/model/OpsItemStatus.h>
#include <aws/ssm/model/OpsItemDataValue.h>
#include <aws/ssm/model/OpsItemNotification.h>
#include <aws/ssm/model/RelatedOpsItem.h>
#include <utility>
namespace Aws
{
namespace SSM
{
namespace Model
{
/**
*/
class AWS_SSM_API UpdateOpsItemRequest : public SSMRequest
{
public:
UpdateOpsItemRequest();
// Service request name is the Operation name which will send this request out,
// each operation should has unique request name, so that we can get operation's name from this request.
// Note: this is not true for response, multiple operations may have the same response name,
// so we can not get operation's name from response.
inline virtual const char* GetServiceRequestName() const override { return "UpdateOpsItem"; }
Aws::String SerializePayload() const override;
Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;
/**
* <p>Update the information about the OpsItem. Provide enough information so that
* users reading this OpsItem for the first time understand the issue. </p>
*/
inline const Aws::String& GetDescription() const{ return m_description; }
/**
* <p>Update the information about the OpsItem. Provide enough information so that
* users reading this OpsItem for the first time understand the issue. </p>
*/
inline bool DescriptionHasBeenSet() const { return m_descriptionHasBeenSet; }
/**
* <p>Update the information about the OpsItem. Provide enough information so that
* users reading this OpsItem for the first time understand the issue. </p>
*/
inline void SetDescription(const Aws::String& value) { m_descriptionHasBeenSet = true; m_description = value; }
/**
* <p>Update the information about the OpsItem. Provide enough information so that
* users reading this OpsItem for the first time understand the issue. </p>
*/
inline void SetDescription(Aws::String&& value) { m_descriptionHasBeenSet = true; m_description = std::move(value); }
/**
* <p>Update the information about the OpsItem. Provide enough information so that
* users reading this OpsItem for the first time understand the issue. </p>
*/
inline void SetDescription(const char* value) { m_descriptionHasBeenSet = true; m_description.assign(value); }
/**
* <p>Update the information about the OpsItem. Provide enough information so that
* users reading this OpsItem for the first time understand the issue. </p>
*/
inline UpdateOpsItemRequest& WithDescription(const Aws::String& value) { SetDescription(value); return *this;}
/**
* <p>Update the information about the OpsItem. Provide enough information so that
* users reading this OpsItem for the first time understand the issue. </p>
*/
inline UpdateOpsItemRequest& WithDescription(Aws::String&& value) { SetDescription(std::move(value)); return *this;}
/**
* <p>Update the information about the OpsItem. Provide enough information so that
* users reading this OpsItem for the first time understand the issue. </p>
*/
inline UpdateOpsItemRequest& WithDescription(const char* value) { SetDescription(value); return *this;}
/**
* <p>Add new keys or edit existing key-value pairs of the OperationalData map in
* the OpsItem object.</p> <p>Operational data is custom data that provides useful
* reference details about the OpsItem. For example, you can specify log files,
* error strings, license keys, troubleshooting tips, or other relevant data. You
* enter operational data as key-value pairs. The key has a maximum length of 128
* characters. The value has a maximum size of 20 KB.</p> <important>
* <p>Operational data keys <i>can't</i> begin with the following: amazon, aws,
* amzn, ssm, /amazon, /aws, /amzn, /ssm.</p> </important> <p>You can choose to
* make the data searchable by other users in the account or you can restrict
* search access. Searchable data means that all users with access to the OpsItem
* Overview page (as provided by the <a>DescribeOpsItems</a> API action) can view
* and search on the specified data. Operational data that is not searchable is
* only viewable by users who have access to the OpsItem (as provided by the
* <a>GetOpsItem</a> API action).</p> <p>Use the <code>/aws/resources</code> key in
* OperationalData to specify a related resource in the request. Use the
* <code>/aws/automations</code> key in OperationalData to associate an Automation
* runbook with the OpsItem. To view AWS CLI example commands that use these keys,
* see <a
* href="http://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-creating-OpsItems.html#OpsCenter-manually-create-OpsItems">Creating
* OpsItems Manually</a> in the <i>AWS Systems Manager User Guide</i>.</p>
*/
inline const Aws::Map<Aws::String, OpsItemDataValue>& GetOperationalData() const{ return m_operationalData; }
/**
* <p>Add new keys or edit existing key-value pairs of the OperationalData map in
* the OpsItem object.</p> <p>Operational data is custom data that provides useful
* reference details about the OpsItem. For example, you can specify log files,
* error strings, license keys, troubleshooting tips, or other relevant data. You
* enter operational data as key-value pairs. The key has a maximum length of 128
* characters. The value has a maximum size of 20 KB.</p> <important>
* <p>Operational data keys <i>can't</i> begin with the following: amazon, aws,
* amzn, ssm, /amazon, /aws, /amzn, /ssm.</p> </important> <p>You can choose to
* make the data searchable by other users in the account or you can restrict
* search access. Searchable data means that all users with access to the OpsItem
* Overview page (as provided by the <a>DescribeOpsItems</a> API action) can view
* and search on the specified data. Operational data that is not searchable is
* only viewable by users who have access to the OpsItem (as provided by the
* <a>GetOpsItem</a> API action).</p> <p>Use the <code>/aws/resources</code> key in
* OperationalData to specify a related resource in the request. Use the
* <code>/aws/automations</code> key in OperationalData to associate an Automation
* runbook with the OpsItem. To view AWS CLI example commands that use these keys,
* see <a
* href="http://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-creating-OpsItems.html#OpsCenter-manually-create-OpsItems">Creating
* OpsItems Manually</a> in the <i>AWS Systems Manager User Guide</i>.</p>
*/
inline bool OperationalDataHasBeenSet() const { return m_operationalDataHasBeenSet; }
/**
* <p>Add new keys or edit existing key-value pairs of the OperationalData map in
* the OpsItem object.</p> <p>Operational data is custom data that provides useful
* reference details about the OpsItem. For example, you can specify log files,
* error strings, license keys, troubleshooting tips, or other relevant data. You
* enter operational data as key-value pairs. The key has a maximum length of 128
* characters. The value has a maximum size of 20 KB.</p> <important>
* <p>Operational data keys <i>can't</i> begin with the following: amazon, aws,
* amzn, ssm, /amazon, /aws, /amzn, /ssm.</p> </important> <p>You can choose to
* make the data searchable by other users in the account or you can restrict
* search access. Searchable data means that all users with access to the OpsItem
* Overview page (as provided by the <a>DescribeOpsItems</a> API action) can view
* and search on the specified data. Operational data that is not searchable is
* only viewable by users who have access to the OpsItem (as provided by the
* <a>GetOpsItem</a> API action).</p> <p>Use the <code>/aws/resources</code> key in
* OperationalData to specify a related resource in the request. Use the
* <code>/aws/automations</code> key in OperationalData to associate an Automation
* runbook with the OpsItem. To view AWS CLI example commands that use these keys,
* see <a
* href="http://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-creating-OpsItems.html#OpsCenter-manually-create-OpsItems">Creating
* OpsItems Manually</a> in the <i>AWS Systems Manager User Guide</i>.</p>
*/
inline void SetOperationalData(const Aws::Map<Aws::String, OpsItemDataValue>& value) { m_operationalDataHasBeenSet = true; m_operationalData = value; }
/**
* <p>Add new keys or edit existing key-value pairs of the OperationalData map in
* the OpsItem object.</p> <p>Operational data is custom data that provides useful
* reference details about the OpsItem. For example, you can specify log files,
* error strings, license keys, troubleshooting tips, or other relevant data. You
* enter operational data as key-value pairs. The key has a maximum length of 128
* characters. The value has a maximum size of 20 KB.</p> <important>
* <p>Operational data keys <i>can't</i> begin with the following: amazon, aws,
* amzn, ssm, /amazon, /aws, /amzn, /ssm.</p> </important> <p>You can choose to
* make the data searchable by other users in the account or you can restrict
* search access. Searchable data means that all users with access to the OpsItem
* Overview page (as provided by the <a>DescribeOpsItems</a> API action) can view
* and search on the specified data. Operational data that is not searchable is
* only viewable by users who have access to the OpsItem (as provided by the
* <a>GetOpsItem</a> API action).</p> <p>Use the <code>/aws/resources</code> key in
* OperationalData to specify a related resource in the request. Use the
* <code>/aws/automations</code> key in OperationalData to associate an Automation
* runbook with the OpsItem. To view AWS CLI example commands that use these keys,
* see <a
* href="http://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-creating-OpsItems.html#OpsCenter-manually-create-OpsItems">Creating
* OpsItems Manually</a> in the <i>AWS Systems Manager User Guide</i>.</p>
*/
inline void SetOperationalData(Aws::Map<Aws::String, OpsItemDataValue>&& value) { m_operationalDataHasBeenSet = true; m_operationalData = std::move(value); }
/**
* <p>Add new keys or edit existing key-value pairs of the OperationalData map in
* the OpsItem object.</p> <p>Operational data is custom data that provides useful
* reference details about the OpsItem. For example, you can specify log files,
* error strings, license keys, troubleshooting tips, or other relevant data. You
* enter operational data as key-value pairs. The key has a maximum length of 128
* characters. The value has a maximum size of 20 KB.</p> <important>
* <p>Operational data keys <i>can't</i> begin with the following: amazon, aws,
* amzn, ssm, /amazon, /aws, /amzn, /ssm.</p> </important> <p>You can choose to
* make the data searchable by other users in the account or you can restrict
* search access. Searchable data means that all users with access to the OpsItem
* Overview page (as provided by the <a>DescribeOpsItems</a> API action) can view
* and search on the specified data. Operational data that is not searchable is
* only viewable by users who have access to the OpsItem (as provided by the
* <a>GetOpsItem</a> API action).</p> <p>Use the <code>/aws/resources</code> key in
* OperationalData to specify a related resource in the request. Use the
* <code>/aws/automations</code> key in OperationalData to associate an Automation
* runbook with the OpsItem. To view AWS CLI example commands that use these keys,
* see <a
* href="http://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-creating-OpsItems.html#OpsCenter-manually-create-OpsItems">Creating
* OpsItems Manually</a> in the <i>AWS Systems Manager User Guide</i>.</p>
*/
inline UpdateOpsItemRequest& WithOperationalData(const Aws::Map<Aws::String, OpsItemDataValue>& value) { SetOperationalData(value); return *this;}
/**
* <p>Add new keys or edit existing key-value pairs of the OperationalData map in
* the OpsItem object.</p> <p>Operational data is custom data that provides useful
* reference details about the OpsItem. For example, you can specify log files,
* error strings, license keys, troubleshooting tips, or other relevant data. You
* enter operational data as key-value pairs. The key has a maximum length of 128
* characters. The value has a maximum size of 20 KB.</p> <important>
* <p>Operational data keys <i>can't</i> begin with the following: amazon, aws,
* amzn, ssm, /amazon, /aws, /amzn, /ssm.</p> </important> <p>You can choose to
* make the data searchable by other users in the account or you can restrict
* search access. Searchable data means that all users with access to the OpsItem
* Overview page (as provided by the <a>DescribeOpsItems</a> API action) can view
* and search on the specified data. Operational data that is not searchable is
* only viewable by users who have access to the OpsItem (as provided by the
* <a>GetOpsItem</a> API action).</p> <p>Use the <code>/aws/resources</code> key in
* OperationalData to specify a related resource in the request. Use the
* <code>/aws/automations</code> key in OperationalData to associate an Automation
* runbook with the OpsItem. To view AWS CLI example commands that use these keys,
* see <a
* href="http://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-creating-OpsItems.html#OpsCenter-manually-create-OpsItems">Creating
* OpsItems Manually</a> in the <i>AWS Systems Manager User Guide</i>.</p>
*/
inline UpdateOpsItemRequest& WithOperationalData(Aws::Map<Aws::String, OpsItemDataValue>&& value) { SetOperationalData(std::move(value)); return *this;}
/**
* <p>Add new keys or edit existing key-value pairs of the OperationalData map in
* the OpsItem object.</p> <p>Operational data is custom data that provides useful
* reference details about the OpsItem. For example, you can specify log files,
* error strings, license keys, troubleshooting tips, or other relevant data. You
* enter operational data as key-value pairs. The key has a maximum length of 128
* characters. The value has a maximum size of 20 KB.</p> <important>
* <p>Operational data keys <i>can't</i> begin with the following: amazon, aws,
* amzn, ssm, /amazon, /aws, /amzn, /ssm.</p> </important> <p>You can choose to
* make the data searchable by other users in the account or you can restrict
* search access. Searchable data means that all users with access to the OpsItem
* Overview page (as provided by the <a>DescribeOpsItems</a> API action) can view
* and search on the specified data. Operational data that is not searchable is
* only viewable by users who have access to the OpsItem (as provided by the
* <a>GetOpsItem</a> API action).</p> <p>Use the <code>/aws/resources</code> key in
* OperationalData to specify a related resource in the request. Use the
* <code>/aws/automations</code> key in OperationalData to associate an Automation
* runbook with the OpsItem. To view AWS CLI example commands that use these keys,
* see <a
* href="http://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-creating-OpsItems.html#OpsCenter-manually-create-OpsItems">Creating
* OpsItems Manually</a> in the <i>AWS Systems Manager User Guide</i>.</p>
*/
inline UpdateOpsItemRequest& AddOperationalData(const Aws::String& key, const OpsItemDataValue& value) { m_operationalDataHasBeenSet = true; m_operationalData.emplace(key, value); return *this; }
/**
* <p>Add new keys or edit existing key-value pairs of the OperationalData map in
* the OpsItem object.</p> <p>Operational data is custom data that provides useful
* reference details about the OpsItem. For example, you can specify log files,
* error strings, license keys, troubleshooting tips, or other relevant data. You
* enter operational data as key-value pairs. The key has a maximum length of 128
* characters. The value has a maximum size of 20 KB.</p> <important>
* <p>Operational data keys <i>can't</i> begin with the following: amazon, aws,
* amzn, ssm, /amazon, /aws, /amzn, /ssm.</p> </important> <p>You can choose to
* make the data searchable by other users in the account or you can restrict
* search access. Searchable data means that all users with access to the OpsItem
* Overview page (as provided by the <a>DescribeOpsItems</a> API action) can view
* and search on the specified data. Operational data that is not searchable is
* only viewable by users who have access to the OpsItem (as provided by the
* <a>GetOpsItem</a> API action).</p> <p>Use the <code>/aws/resources</code> key in
* OperationalData to specify a related resource in the request. Use the
* <code>/aws/automations</code> key in OperationalData to associate an Automation
* runbook with the OpsItem. To view AWS CLI example commands that use these keys,
* see <a
* href="http://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-creating-OpsItems.html#OpsCenter-manually-create-OpsItems">Creating
* OpsItems Manually</a> in the <i>AWS Systems Manager User Guide</i>.</p>
*/
inline UpdateOpsItemRequest& AddOperationalData(Aws::String&& key, const OpsItemDataValue& value) { m_operationalDataHasBeenSet = true; m_operationalData.emplace(std::move(key), value); return *this; }
/**
* <p>Add new keys or edit existing key-value pairs of the OperationalData map in
* the OpsItem object.</p> <p>Operational data is custom data that provides useful
* reference details about the OpsItem. For example, you can specify log files,
* error strings, license keys, troubleshooting tips, or other relevant data. You
* enter operational data as key-value pairs. The key has a maximum length of 128
* characters. The value has a maximum size of 20 KB.</p> <important>
* <p>Operational data keys <i>can't</i> begin with the following: amazon, aws,
* amzn, ssm, /amazon, /aws, /amzn, /ssm.</p> </important> <p>You can choose to
* make the data searchable by other users in the account or you can restrict
* search access. Searchable data means that all users with access to the OpsItem
* Overview page (as provided by the <a>DescribeOpsItems</a> API action) can view
* and search on the specified data. Operational data that is not searchable is
* only viewable by users who have access to the OpsItem (as provided by the
* <a>GetOpsItem</a> API action).</p> <p>Use the <code>/aws/resources</code> key in
* OperationalData to specify a related resource in the request. Use the
* <code>/aws/automations</code> key in OperationalData to associate an Automation
* runbook with the OpsItem. To view AWS CLI example commands that use these keys,
* see <a
* href="http://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-creating-OpsItems.html#OpsCenter-manually-create-OpsItems">Creating
* OpsItems Manually</a> in the <i>AWS Systems Manager User Guide</i>.</p>
*/
inline UpdateOpsItemRequest& AddOperationalData(const Aws::String& key, OpsItemDataValue&& value) { m_operationalDataHasBeenSet = true; m_operationalData.emplace(key, std::move(value)); return *this; }
/**
* <p>Add new keys or edit existing key-value pairs of the OperationalData map in
* the OpsItem object.</p> <p>Operational data is custom data that provides useful
* reference details about the OpsItem. For example, you can specify log files,
* error strings, license keys, troubleshooting tips, or other relevant data. You
* enter operational data as key-value pairs. The key has a maximum length of 128
* characters. The value has a maximum size of 20 KB.</p> <important>
* <p>Operational data keys <i>can't</i> begin with the following: amazon, aws,
* amzn, ssm, /amazon, /aws, /amzn, /ssm.</p> </important> <p>You can choose to
* make the data searchable by other users in the account or you can restrict
* search access. Searchable data means that all users with access to the OpsItem
* Overview page (as provided by the <a>DescribeOpsItems</a> API action) can view
* and search on the specified data. Operational data that is not searchable is
* only viewable by users who have access to the OpsItem (as provided by the
* <a>GetOpsItem</a> API action).</p> <p>Use the <code>/aws/resources</code> key in
* OperationalData to specify a related resource in the request. Use the
* <code>/aws/automations</code> key in OperationalData to associate an Automation
* runbook with the OpsItem. To view AWS CLI example commands that use these keys,
* see <a
* href="http://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-creating-OpsItems.html#OpsCenter-manually-create-OpsItems">Creating
* OpsItems Manually</a> in the <i>AWS Systems Manager User Guide</i>.</p>
*/
inline UpdateOpsItemRequest& AddOperationalData(Aws::String&& key, OpsItemDataValue&& value) { m_operationalDataHasBeenSet = true; m_operationalData.emplace(std::move(key), std::move(value)); return *this; }
/**
* <p>Add new keys or edit existing key-value pairs of the OperationalData map in
* the OpsItem object.</p> <p>Operational data is custom data that provides useful
* reference details about the OpsItem. For example, you can specify log files,
* error strings, license keys, troubleshooting tips, or other relevant data. You
* enter operational data as key-value pairs. The key has a maximum length of 128
* characters. The value has a maximum size of 20 KB.</p> <important>
* <p>Operational data keys <i>can't</i> begin with the following: amazon, aws,
* amzn, ssm, /amazon, /aws, /amzn, /ssm.</p> </important> <p>You can choose to
* make the data searchable by other users in the account or you can restrict
* search access. Searchable data means that all users with access to the OpsItem
* Overview page (as provided by the <a>DescribeOpsItems</a> API action) can view
* and search on the specified data. Operational data that is not searchable is
* only viewable by users who have access to the OpsItem (as provided by the
* <a>GetOpsItem</a> API action).</p> <p>Use the <code>/aws/resources</code> key in
* OperationalData to specify a related resource in the request. Use the
* <code>/aws/automations</code> key in OperationalData to associate an Automation
* runbook with the OpsItem. To view AWS CLI example commands that use these keys,
* see <a
* href="http://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-creating-OpsItems.html#OpsCenter-manually-create-OpsItems">Creating
* OpsItems Manually</a> in the <i>AWS Systems Manager User Guide</i>.</p>
*/
inline UpdateOpsItemRequest& AddOperationalData(const char* key, OpsItemDataValue&& value) { m_operationalDataHasBeenSet = true; m_operationalData.emplace(key, std::move(value)); return *this; }
/**
* <p>Add new keys or edit existing key-value pairs of the OperationalData map in
* the OpsItem object.</p> <p>Operational data is custom data that provides useful
* reference details about the OpsItem. For example, you can specify log files,
* error strings, license keys, troubleshooting tips, or other relevant data. You
* enter operational data as key-value pairs. The key has a maximum length of 128
* characters. The value has a maximum size of 20 KB.</p> <important>
* <p>Operational data keys <i>can't</i> begin with the following: amazon, aws,
* amzn, ssm, /amazon, /aws, /amzn, /ssm.</p> </important> <p>You can choose to
* make the data searchable by other users in the account or you can restrict
* search access. Searchable data means that all users with access to the OpsItem
* Overview page (as provided by the <a>DescribeOpsItems</a> API action) can view
* and search on the specified data. Operational data that is not searchable is
* only viewable by users who have access to the OpsItem (as provided by the
* <a>GetOpsItem</a> API action).</p> <p>Use the <code>/aws/resources</code> key in
* OperationalData to specify a related resource in the request. Use the
* <code>/aws/automations</code> key in OperationalData to associate an Automation
* runbook with the OpsItem. To view AWS CLI example commands that use these keys,
* see <a
* href="http://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-creating-OpsItems.html#OpsCenter-manually-create-OpsItems">Creating
* OpsItems Manually</a> in the <i>AWS Systems Manager User Guide</i>.</p>
*/
inline UpdateOpsItemRequest& AddOperationalData(const char* key, const OpsItemDataValue& value) { m_operationalDataHasBeenSet = true; m_operationalData.emplace(key, value); return *this; }
/**
* <p>Keys that you want to remove from the OperationalData map.</p>
*/
inline const Aws::Vector<Aws::String>& GetOperationalDataToDelete() const{ return m_operationalDataToDelete; }
/**
* <p>Keys that you want to remove from the OperationalData map.</p>
*/
inline bool OperationalDataToDeleteHasBeenSet() const { return m_operationalDataToDeleteHasBeenSet; }
/**
* <p>Keys that you want to remove from the OperationalData map.</p>
*/
inline void SetOperationalDataToDelete(const Aws::Vector<Aws::String>& value) { m_operationalDataToDeleteHasBeenSet = true; m_operationalDataToDelete = value; }
/**
* <p>Keys that you want to remove from the OperationalData map.</p>
*/
inline void SetOperationalDataToDelete(Aws::Vector<Aws::String>&& value) { m_operationalDataToDeleteHasBeenSet = true; m_operationalDataToDelete = std::move(value); }
/**
* <p>Keys that you want to remove from the OperationalData map.</p>
*/
inline UpdateOpsItemRequest& WithOperationalDataToDelete(const Aws::Vector<Aws::String>& value) { SetOperationalDataToDelete(value); return *this;}
/**
* <p>Keys that you want to remove from the OperationalData map.</p>
*/
inline UpdateOpsItemRequest& WithOperationalDataToDelete(Aws::Vector<Aws::String>&& value) { SetOperationalDataToDelete(std::move(value)); return *this;}
/**
* <p>Keys that you want to remove from the OperationalData map.</p>
*/
inline UpdateOpsItemRequest& AddOperationalDataToDelete(const Aws::String& value) { m_operationalDataToDeleteHasBeenSet = true; m_operationalDataToDelete.push_back(value); return *this; }
/**
* <p>Keys that you want to remove from the OperationalData map.</p>
*/
inline UpdateOpsItemRequest& AddOperationalDataToDelete(Aws::String&& value) { m_operationalDataToDeleteHasBeenSet = true; m_operationalDataToDelete.push_back(std::move(value)); return *this; }
/**
* <p>Keys that you want to remove from the OperationalData map.</p>
*/
inline UpdateOpsItemRequest& AddOperationalDataToDelete(const char* value) { m_operationalDataToDeleteHasBeenSet = true; m_operationalDataToDelete.push_back(value); return *this; }
/**
* <p>The Amazon Resource Name (ARN) of an SNS topic where notifications are sent
* when this OpsItem is edited or changed.</p>
*/
inline const Aws::Vector<OpsItemNotification>& GetNotifications() const{ return m_notifications; }
/**
* <p>The Amazon Resource Name (ARN) of an SNS topic where notifications are sent
* when this OpsItem is edited or changed.</p>
*/
inline bool NotificationsHasBeenSet() const { return m_notificationsHasBeenSet; }
/**
* <p>The Amazon Resource Name (ARN) of an SNS topic where notifications are sent
* when this OpsItem is edited or changed.</p>
*/
inline void SetNotifications(const Aws::Vector<OpsItemNotification>& value) { m_notificationsHasBeenSet = true; m_notifications = value; }
/**
* <p>The Amazon Resource Name (ARN) of an SNS topic where notifications are sent
* when this OpsItem is edited or changed.</p>
*/
inline void SetNotifications(Aws::Vector<OpsItemNotification>&& value) { m_notificationsHasBeenSet = true; m_notifications = std::move(value); }
/**
* <p>The Amazon Resource Name (ARN) of an SNS topic where notifications are sent
* when this OpsItem is edited or changed.</p>
*/
inline UpdateOpsItemRequest& WithNotifications(const Aws::Vector<OpsItemNotification>& value) { SetNotifications(value); return *this;}
/**
* <p>The Amazon Resource Name (ARN) of an SNS topic where notifications are sent
* when this OpsItem is edited or changed.</p>
*/
inline UpdateOpsItemRequest& WithNotifications(Aws::Vector<OpsItemNotification>&& value) { SetNotifications(std::move(value)); return *this;}
/**
* <p>The Amazon Resource Name (ARN) of an SNS topic where notifications are sent
* when this OpsItem is edited or changed.</p>
*/
inline UpdateOpsItemRequest& AddNotifications(const OpsItemNotification& value) { m_notificationsHasBeenSet = true; m_notifications.push_back(value); return *this; }
/**
* <p>The Amazon Resource Name (ARN) of an SNS topic where notifications are sent
* when this OpsItem is edited or changed.</p>
*/
inline UpdateOpsItemRequest& AddNotifications(OpsItemNotification&& value) { m_notificationsHasBeenSet = true; m_notifications.push_back(std::move(value)); return *this; }
/**
* <p>The importance of this OpsItem in relation to other OpsItems in the
* system.</p>
*/
inline int GetPriority() const{ return m_priority; }
/**
* <p>The importance of this OpsItem in relation to other OpsItems in the
* system.</p>
*/
inline bool PriorityHasBeenSet() const { return m_priorityHasBeenSet; }
/**
* <p>The importance of this OpsItem in relation to other OpsItems in the
* system.</p>
*/
inline void SetPriority(int value) { m_priorityHasBeenSet = true; m_priority = value; }
/**
* <p>The importance of this OpsItem in relation to other OpsItems in the
* system.</p>
*/
inline UpdateOpsItemRequest& WithPriority(int value) { SetPriority(value); return *this;}
/**
* <p>One or more OpsItems that share something in common with the current
* OpsItems. For example, related OpsItems can include OpsItems with similar error
* messages, impacted resources, or statuses for the impacted resource.</p>
*/
inline const Aws::Vector<RelatedOpsItem>& GetRelatedOpsItems() const{ return m_relatedOpsItems; }
/**
* <p>One or more OpsItems that share something in common with the current
* OpsItems. For example, related OpsItems can include OpsItems with similar error
* messages, impacted resources, or statuses for the impacted resource.</p>
*/
inline bool RelatedOpsItemsHasBeenSet() const { return m_relatedOpsItemsHasBeenSet; }
/**
* <p>One or more OpsItems that share something in common with the current
* OpsItems. For example, related OpsItems can include OpsItems with similar error
* messages, impacted resources, or statuses for the impacted resource.</p>
*/
inline void SetRelatedOpsItems(const Aws::Vector<RelatedOpsItem>& value) { m_relatedOpsItemsHasBeenSet = true; m_relatedOpsItems = value; }
/**
* <p>One or more OpsItems that share something in common with the current
* OpsItems. For example, related OpsItems can include OpsItems with similar error
* messages, impacted resources, or statuses for the impacted resource.</p>
*/
inline void SetRelatedOpsItems(Aws::Vector<RelatedOpsItem>&& value) { m_relatedOpsItemsHasBeenSet = true; m_relatedOpsItems = std::move(value); }
/**
* <p>One or more OpsItems that share something in common with the current
* OpsItems. For example, related OpsItems can include OpsItems with similar error
* messages, impacted resources, or statuses for the impacted resource.</p>
*/
inline UpdateOpsItemRequest& WithRelatedOpsItems(const Aws::Vector<RelatedOpsItem>& value) { SetRelatedOpsItems(value); return *this;}
/**
* <p>One or more OpsItems that share something in common with the current
* OpsItems. For example, related OpsItems can include OpsItems with similar error
* messages, impacted resources, or statuses for the impacted resource.</p>
*/
inline UpdateOpsItemRequest& WithRelatedOpsItems(Aws::Vector<RelatedOpsItem>&& value) { SetRelatedOpsItems(std::move(value)); return *this;}
/**
* <p>One or more OpsItems that share something in common with the current
* OpsItems. For example, related OpsItems can include OpsItems with similar error
* messages, impacted resources, or statuses for the impacted resource.</p>
*/
inline UpdateOpsItemRequest& AddRelatedOpsItems(const RelatedOpsItem& value) { m_relatedOpsItemsHasBeenSet = true; m_relatedOpsItems.push_back(value); return *this; }
/**
* <p>One or more OpsItems that share something in common with the current
* OpsItems. For example, related OpsItems can include OpsItems with similar error
* messages, impacted resources, or statuses for the impacted resource.</p>
*/
inline UpdateOpsItemRequest& AddRelatedOpsItems(RelatedOpsItem&& value) { m_relatedOpsItemsHasBeenSet = true; m_relatedOpsItems.push_back(std::move(value)); return *this; }
/**
* <p>The OpsItem status. Status can be <code>Open</code>, <code>In
* Progress</code>, or <code>Resolved</code>. For more information, see <a
* href="http://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-working-with-OpsItems-editing-details.html">Editing
* OpsItem Details</a> in the <i>AWS Systems Manager User Guide</i>.</p>
*/
inline const OpsItemStatus& GetStatus() const{ return m_status; }
/**
* <p>The OpsItem status. Status can be <code>Open</code>, <code>In
* Progress</code>, or <code>Resolved</code>. For more information, see <a
* href="http://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-working-with-OpsItems-editing-details.html">Editing
* OpsItem Details</a> in the <i>AWS Systems Manager User Guide</i>.</p>
*/
inline bool StatusHasBeenSet() const { return m_statusHasBeenSet; }
/**
* <p>The OpsItem status. Status can be <code>Open</code>, <code>In
* Progress</code>, or <code>Resolved</code>. For more information, see <a
* href="http://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-working-with-OpsItems-editing-details.html">Editing
* OpsItem Details</a> in the <i>AWS Systems Manager User Guide</i>.</p>
*/
inline void SetStatus(const OpsItemStatus& value) { m_statusHasBeenSet = true; m_status = value; }
/**
* <p>The OpsItem status. Status can be <code>Open</code>, <code>In
* Progress</code>, or <code>Resolved</code>. For more information, see <a
* href="http://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-working-with-OpsItems-editing-details.html">Editing
* OpsItem Details</a> in the <i>AWS Systems Manager User Guide</i>.</p>
*/
inline void SetStatus(OpsItemStatus&& value) { m_statusHasBeenSet = true; m_status = std::move(value); }
/**
* <p>The OpsItem status. Status can be <code>Open</code>, <code>In
* Progress</code>, or <code>Resolved</code>. For more information, see <a
* href="http://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-working-with-OpsItems-editing-details.html">Editing
* OpsItem Details</a> in the <i>AWS Systems Manager User Guide</i>.</p>
*/
inline UpdateOpsItemRequest& WithStatus(const OpsItemStatus& value) { SetStatus(value); return *this;}
/**
* <p>The OpsItem status. Status can be <code>Open</code>, <code>In
* Progress</code>, or <code>Resolved</code>. For more information, see <a
* href="http://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-working-with-OpsItems-editing-details.html">Editing
* OpsItem Details</a> in the <i>AWS Systems Manager User Guide</i>.</p>
*/
inline UpdateOpsItemRequest& WithStatus(OpsItemStatus&& value) { SetStatus(std::move(value)); return *this;}
/**
* <p>The ID of the OpsItem.</p>
*/
inline const Aws::String& GetOpsItemId() const{ return m_opsItemId; }
/**
* <p>The ID of the OpsItem.</p>
*/
inline bool OpsItemIdHasBeenSet() const { return m_opsItemIdHasBeenSet; }
/**
* <p>The ID of the OpsItem.</p>
*/
inline void SetOpsItemId(const Aws::String& value) { m_opsItemIdHasBeenSet = true; m_opsItemId = value; }
/**
* <p>The ID of the OpsItem.</p>
*/
inline void SetOpsItemId(Aws::String&& value) { m_opsItemIdHasBeenSet = true; m_opsItemId = std::move(value); }
/**
* <p>The ID of the OpsItem.</p>
*/
inline void SetOpsItemId(const char* value) { m_opsItemIdHasBeenSet = true; m_opsItemId.assign(value); }
/**
* <p>The ID of the OpsItem.</p>
*/
inline UpdateOpsItemRequest& WithOpsItemId(const Aws::String& value) { SetOpsItemId(value); return *this;}
/**
* <p>The ID of the OpsItem.</p>
*/
inline UpdateOpsItemRequest& WithOpsItemId(Aws::String&& value) { SetOpsItemId(std::move(value)); return *this;}
/**
* <p>The ID of the OpsItem.</p>
*/
inline UpdateOpsItemRequest& WithOpsItemId(const char* value) { SetOpsItemId(value); return *this;}
/**
* <p>A short heading that describes the nature of the OpsItem and the impacted
* resource.</p>
*/
inline const Aws::String& GetTitle() const{ return m_title; }
/**
* <p>A short heading that describes the nature of the OpsItem and the impacted
* resource.</p>
*/
inline bool TitleHasBeenSet() const { return m_titleHasBeenSet; }
/**
* <p>A short heading that describes the nature of the OpsItem and the impacted
* resource.</p>
*/
inline void SetTitle(const Aws::String& value) { m_titleHasBeenSet = true; m_title = value; }
/**
* <p>A short heading that describes the nature of the OpsItem and the impacted
* resource.</p>
*/
inline void SetTitle(Aws::String&& value) { m_titleHasBeenSet = true; m_title = std::move(value); }
/**
* <p>A short heading that describes the nature of the OpsItem and the impacted
* resource.</p>
*/
inline void SetTitle(const char* value) { m_titleHasBeenSet = true; m_title.assign(value); }
/**
* <p>A short heading that describes the nature of the OpsItem and the impacted
* resource.</p>
*/
inline UpdateOpsItemRequest& WithTitle(const Aws::String& value) { SetTitle(value); return *this;}
/**
* <p>A short heading that describes the nature of the OpsItem and the impacted
* resource.</p>
*/
inline UpdateOpsItemRequest& WithTitle(Aws::String&& value) { SetTitle(std::move(value)); return *this;}
/**
* <p>A short heading that describes the nature of the OpsItem and the impacted
* resource.</p>
*/
inline UpdateOpsItemRequest& WithTitle(const char* value) { SetTitle(value); return *this;}
/**
* <p>Specify a new category for an OpsItem.</p>
*/
inline const Aws::String& GetCategory() const{ return m_category; }
/**
* <p>Specify a new category for an OpsItem.</p>
*/
inline bool CategoryHasBeenSet() const { return m_categoryHasBeenSet; }
/**
* <p>Specify a new category for an OpsItem.</p>
*/
inline void SetCategory(const Aws::String& value) { m_categoryHasBeenSet = true; m_category = value; }
/**
* <p>Specify a new category for an OpsItem.</p>
*/
inline void SetCategory(Aws::String&& value) { m_categoryHasBeenSet = true; m_category = std::move(value); }
/**
* <p>Specify a new category for an OpsItem.</p>
*/
inline void SetCategory(const char* value) { m_categoryHasBeenSet = true; m_category.assign(value); }
/**
* <p>Specify a new category for an OpsItem.</p>
*/
inline UpdateOpsItemRequest& WithCategory(const Aws::String& value) { SetCategory(value); return *this;}
/**
* <p>Specify a new category for an OpsItem.</p>
*/
inline UpdateOpsItemRequest& WithCategory(Aws::String&& value) { SetCategory(std::move(value)); return *this;}
/**
* <p>Specify a new category for an OpsItem.</p>
*/
inline UpdateOpsItemRequest& WithCategory(const char* value) { SetCategory(value); return *this;}
/**
* <p>Specify a new severity for an OpsItem.</p>
*/
inline const Aws::String& GetSeverity() const{ return m_severity; }
/**
* <p>Specify a new severity for an OpsItem.</p>
*/
inline bool SeverityHasBeenSet() const { return m_severityHasBeenSet; }
/**
* <p>Specify a new severity for an OpsItem.</p>
*/
inline void SetSeverity(const Aws::String& value) { m_severityHasBeenSet = true; m_severity = value; }
/**
* <p>Specify a new severity for an OpsItem.</p>
*/
inline void SetSeverity(Aws::String&& value) { m_severityHasBeenSet = true; m_severity = std::move(value); }
/**
* <p>Specify a new severity for an OpsItem.</p>
*/
inline void SetSeverity(const char* value) { m_severityHasBeenSet = true; m_severity.assign(value); }
/**
* <p>Specify a new severity for an OpsItem.</p>
*/
inline UpdateOpsItemRequest& WithSeverity(const Aws::String& value) { SetSeverity(value); return *this;}
/**
* <p>Specify a new severity for an OpsItem.</p>
*/
inline UpdateOpsItemRequest& WithSeverity(Aws::String&& value) { SetSeverity(std::move(value)); return *this;}
/**
* <p>Specify a new severity for an OpsItem.</p>
*/
inline UpdateOpsItemRequest& WithSeverity(const char* value) { SetSeverity(value); return *this;}
private:
Aws::String m_description;
bool m_descriptionHasBeenSet;
Aws::Map<Aws::String, OpsItemDataValue> m_operationalData;
bool m_operationalDataHasBeenSet;
Aws::Vector<Aws::String> m_operationalDataToDelete;
bool m_operationalDataToDeleteHasBeenSet;
Aws::Vector<OpsItemNotification> m_notifications;
bool m_notificationsHasBeenSet;
int m_priority;
bool m_priorityHasBeenSet;
Aws::Vector<RelatedOpsItem> m_relatedOpsItems;
bool m_relatedOpsItemsHasBeenSet;
OpsItemStatus m_status;
bool m_statusHasBeenSet;
Aws::String m_opsItemId;
bool m_opsItemIdHasBeenSet;
Aws::String m_title;
bool m_titleHasBeenSet;
Aws::String m_category;
bool m_categoryHasBeenSet;
Aws::String m_severity;
bool m_severityHasBeenSet;
};
} // namespace Model
} // namespace SSM
} // namespace Aws
| [
"aws-sdk-cpp-automation@github.com"
] | aws-sdk-cpp-automation@github.com |
ef34cc352c8eafd2e5571dda4bdedc276821767b | 1b3d343ce1e8dfbacc3c698294798d0abd52c9a2 | /Deploy/Instance/EEuclideo.200.50.5.tpp | 154169f585005e0d66c567ee182c78457fe3f33b | [] | no_license | lyandut/MyTravelingPurchaser | 3ecdf849bd19473e92742ed4c6d8d99078351fd0 | dca14f3d31e185c1a6f7bbd4a2e7a5cb3b0bd08c | refs/heads/master | 2020-05-02T06:10:47.227729 | 2019-04-19T07:50:53 | 2019-04-19T07:50:53 | 177,788,811 | 0 | 1 | null | 2019-04-19T07:50:54 | 2019-03-26T12:56:50 | C++ | UTF-8 | C++ | false | false | 35,222 | tpp | NAME :
TYPE : TPP
COMMENT :
DIMENSION : 200
EDGE_WEIGHT_TYPE : EUC_2D
DISPLAY_DATA_TYPE : COORD_DISPLAY
NODE_COORD_SECTION :
1 967 758
2 394 203
3 879 938
4 567 109
5 676 257
6 101 591
7 332 853
8 267 469
9 124 382
10 344 154
11 145 14
12 516 987
13 961 3
14 529 410
15 143 270
16 353 901
17 264 748
18 81 119
19 662 648
20 228 314
21 905 329
22 905 213
23 158 149
24 683 282
25 531 3
26 436 676
27 18 952
28 639 979
29 956 145
30 365 75
31 415 719
32 977 679
33 443 34
34 798 81
35 682 3
36 396 564
37 332 277
38 777 491
39 426 436
40 773 957
41 440 186
42 610 458
43 114 225
44 413 46
45 370 779
46 122 786
47 474 75
48 441 917
49 109 216
50 998 791
51 219 370
52 331 551
53 648 85
54 18 50
55 521 792
56 961 978
57 594 395
58 68 819
59 809 115
60 166 564
61 237 952
62 14 312
63 369 931
64 421 585
65 905 188
66 804 252
67 520 332
68 900 605
69 350 950
70 102 118
71 934 40
72 72 504
73 435 141
74 300 220
75 256 466
76 784 493
77 394 798
78 805 763
79 705 202
80 325 587
81 390 105
82 839 910
83 437 715
84 491 788
85 641 594
86 906 552
87 634 979
88 32 45
89 96 332
90 266 352
91 798 26
92 845 168
93 825 626
94 932 506
95 828 233
96 69 194
97 338 908
98 81 776
99 599 572
100 540 217
101 142 422
102 769 776
103 377 801
104 822 473
105 110 64
106 825 908
107 90 646
108 53 915
109 248 985
110 398 52
111 194 467
112 247 532
113 352 328
114 284 951
115 900 824
116 144 19
117 223 913
118 795 600
119 691 593
120 50 801
121 657 875
122 685 748
123 498 738
124 639 746
125 699 13
126 799 893
127 481 22
128 402 833
129 350 686
130 760 226
131 487 905
132 245 710
133 794 17
134 286 461
135 610 336
136 238 244
137 188 924
138 992 686
139 638 607
140 408 314
141 621 183
142 183 78
143 205 585
144 911 555
145 248 647
146 782 735
147 528 3
148 421 299
149 20 707
150 760 631
151 20 999
152 875 208
153 899 843
154 894 513
155 426 278
156 827 23
157 462 101
158 667 572
159 199 820
160 636 981
161 531 140
162 984 952
163 439 636
164 176 612
165 656 151
166 463 864
167 26 282
168 734 539
169 708 343
170 732 450
171 330 833
172 94 902
173 822 293
174 699 434
175 250 206
176 574 210
177 135 191
178 771 166
179 803 403
180 317 242
181 243 343
182 524 977
183 882 209
184 965 201
185 941 392
186 531 750
187 486 410
188 548 779
189 85 982
190 5 291
191 533 215
192 426 523
193 407 173
194 689 186
195 576 429
196 819 325
197 953 772
198 183 138
199 714 385
200 55 82
DEMAND_SECTION :
50
1 1
2 1
3 1
4 1
5 1
6 1
7 1
8 1
9 1
10 1
11 1
12 1
13 1
14 1
15 1
16 1
17 1
18 1
19 1
20 1
21 1
22 1
23 1
24 1
25 1
26 1
27 1
28 1
29 1
30 1
31 1
32 1
33 1
34 1
35 1
36 1
37 1
38 1
39 1
40 1
41 1
42 1
43 1
44 1
45 1
46 1
47 1
48 1
49 1
50 1
OFFER_SECTION :
1 0
2 19 48 10 1 47 9 1 46 3 1 43 8 1 38 1 1 36 6 1 35 8 1 33 10 1 32 7 1 25 5 1 19 6 1 17 3 1 16 9 1 15 6 1 14 6 1 13 10 1 12 7 1 8 7 1 1 3 1
3 19 47 3 1 46 3 1 45 5 1 43 8 1 42 10 1 41 5 1 35 3 1 32 9 1 31 4 1 25 3 1 23 3 1 15 9 1 12 6 1 10 2 1 8 1 1 7 10 1 6 1 1 2 4 1 1 5 1
4 23 50 4 1 48 2 1 46 6 1 45 1 1 43 8 1 41 1 1 38 10 1 34 3 1 33 9 1 30 7 1 29 5 1 25 1 1 21 9 1 19 4 1 15 2 1 14 9 1 11 5 1 10 6 1 9 9 1 8 7 1 6 5 1 5 8 1 2 6 1
5 31 50 5 1 48 10 1 47 10 1 46 5 1 45 5 1 43 3 1 41 3 1 39 9 1 36 6 1 35 6 1 34 4 1 33 4 1 32 3 1 31 6 1 30 9 1 29 7 1 26 4 1 25 5 1 23 10 1 21 8 1 20 7 1 15 9 1 14 8 1 12 8 1 10 10 1 9 5 1 8 10 1 6 8 1 4 8 1 3 5 1 1 10 1
6 28 48 10 1 47 6 1 46 1 1 45 7 1 44 10 1 43 10 1 41 6 1 39 1 1 38 3 1 36 5 1 35 1 1 33 7 1 32 10 1 31 7 1 26 6 1 25 2 1 20 6 1 19 5 1 18 4 1 15 3 1 14 3 1 13 1 1 12 1 1 9 6 1 8 3 1 3 9 1 2 9 1 1 7 1
7 24 47 5 1 46 1 1 45 2 1 43 7 1 41 7 1 36 6 1 35 9 1 34 1 1 33 2 1 32 6 1 31 7 1 25 1 1 24 2 1 20 4 1 18 3 1 17 5 1 16 10 1 14 3 1 13 10 1 12 10 1 10 10 1 8 6 1 4 3 1 1 2 1
8 18 46 7 1 43 3 1 41 2 1 35 10 1 34 8 1 33 5 1 31 8 1 30 9 1 25 7 1 23 10 1 22 6 1 15 7 1 14 1 1 12 7 1 11 3 1 8 10 1 7 4 1 6 9 1
9 26 50 1 1 47 5 1 46 9 1 45 7 1 43 5 1 41 3 1 36 3 1 34 3 1 33 4 1 32 8 1 31 4 1 30 6 1 29 4 1 25 3 1 23 4 1 21 2 1 20 1 1 15 5 1 14 3 1 13 1 1 12 10 1 10 4 1 8 9 1 6 9 1 5 1 1 1 4 1
10 22 48 6 1 47 10 1 46 3 1 45 6 1 43 4 1 40 9 1 38 1 1 36 6 1 33 5 1 32 9 1 28 1 1 25 9 1 20 5 1 19 6 1 15 4 1 14 7 1 13 8 1 9 5 1 8 7 1 4 6 1 2 7 1 1 10 1
11 21 47 2 1 46 4 1 44 6 1 43 10 1 41 10 1 37 1 1 36 6 1 34 6 1 33 2 1 32 7 1 30 4 1 25 6 1 21 4 1 18 8 1 15 5 1 13 7 1 10 6 1 8 9 1 6 7 1 2 6 1 1 2 1
12 25 48 5 1 47 9 1 46 7 1 45 7 1 43 1 1 40 7 1 36 8 1 35 4 1 33 10 1 32 7 1 31 9 1 28 4 1 25 3 1 24 9 1 23 8 1 20 6 1 16 9 1 14 1 1 13 9 1 12 3 1 9 5 1 8 9 1 7 7 1 4 10 1 1 9 1
13 21 47 8 1 46 3 1 43 2 1 42 8 1 41 10 1 37 1 1 35 4 1 34 9 1 32 5 1 31 8 1 25 8 1 23 4 1 22 9 1 21 6 1 18 1 1 15 8 1 13 7 1 12 6 1 8 4 1 6 6 1 2 1 1
14 22 50 6 1 46 10 1 45 2 1 44 3 1 43 7 1 41 3 1 34 4 1 33 4 1 31 3 1 30 9 1 29 10 1 25 6 1 21 8 1 20 5 1 15 6 1 14 3 1 12 5 1 10 8 1 8 9 1 6 8 1 4 3 1 2 4 1
15 23 48 4 1 47 9 1 45 4 1 44 2 1 43 8 1 41 8 1 40 4 1 38 6 1 34 8 1 33 1 1 32 10 1 28 1 1 25 6 1 21 4 1 20 10 1 19 5 1 14 2 1 13 5 1 9 2 1 8 2 1 4 8 1 2 3 1 1 1 1
16 23 48 1 1 47 5 1 46 5 1 44 10 1 43 9 1 37 10 1 36 2 1 35 3 1 33 6 1 32 4 1 31 9 1 25 10 1 23 1 1 19 7 1 18 6 1 17 5 1 15 3 1 14 1 1 13 9 1 12 1 1 8 8 1 2 3 1 1 1 1
17 27 50 7 1 47 2 1 46 7 1 45 10 1 43 2 1 41 5 1 35 7 1 34 9 1 32 4 1 31 9 1 30 1 1 29 9 1 25 1 1 23 9 1 22 1 1 16 10 1 15 6 1 14 6 1 13 6 1 12 2 1 11 1 1 10 3 1 8 4 1 7 3 1 6 10 1 5 1 1 1 8 1
18 27 48 10 1 46 5 1 45 5 1 43 8 1 42 10 1 41 10 1 40 9 1 35 2 1 34 4 1 33 1 1 31 1 1 30 4 1 28 3 1 25 8 1 23 2 1 21 10 1 20 8 1 15 6 1 14 8 1 12 2 1 11 5 1 9 3 1 8 6 1 7 5 1 6 4 1 4 6 1 1 9 1
19 29 50 3 1 47 1 1 46 1 1 45 4 1 44 8 1 43 9 1 41 6 1 37 10 1 34 8 1 33 9 1 32 4 1 30 4 1 29 3 1 25 8 1 21 10 1 20 5 1 18 6 1 16 8 1 15 4 1 14 4 1 13 1 1 10 4 1 9 4 1 8 2 1 6 8 1 5 10 1 4 6 1 2 10 1 1 5 1
20 18 48 3 1 47 6 1 45 8 1 44 2 1 41 6 1 39 4 1 38 7 1 33 4 1 26 2 1 25 8 1 20 3 1 19 10 1 14 8 1 13 2 1 9 10 1 8 1 1 3 3 1 2 6 1
21 25 50 4 1 47 3 1 46 6 1 45 1 1 43 9 1 41 4 1 36 1 1 34 10 1 33 6 1 32 1 1 29 8 1 25 8 1 21 4 1 18 2 1 17 9 1 15 3 1 14 6 1 13 1 1 10 7 1 9 5 1 8 3 1 6 6 1 5 4 1 2 5 1 1 9 1
22 16 47 5 1 46 9 1 43 10 1 35 7 1 32 9 1 31 4 1 25 3 1 24 10 1 23 9 1 16 1 1 15 1 1 13 7 1 12 10 1 8 1 1 7 10 1 1 3 1
23 18 47 9 1 46 9 1 43 4 1 41 2 1 35 4 1 34 2 1 31 5 1 30 3 1 25 2 1 23 8 1 21 9 1 18 10 1 15 3 1 13 1 1 12 6 1 10 9 1 8 3 1 6 1 1
24 25 50 8 1 48 7 1 47 3 1 46 10 1 45 5 1 43 2 1 41 9 1 40 1 1 34 6 1 33 3 1 32 7 1 31 9 1 29 8 1 28 8 1 25 2 1 20 10 1 15 3 1 14 9 1 12 1 1 10 2 1 9 3 1 8 6 1 5 5 1 4 6 1 1 7 1
25 20 48 7 1 47 2 1 46 5 1 45 3 1 44 2 1 41 4 1 38 4 1 37 4 1 34 1 1 33 8 1 25 8 1 19 10 1 18 3 1 15 6 1 14 9 1 13 10 1 9 5 1 8 2 1 6 10 1 2 4 1
26 20 50 7 1 47 6 1 46 9 1 45 3 1 43 10 1 41 5 1 36 9 1 34 1 1 32 3 1 30 8 1 25 3 1 21 8 1 18 3 1 16 4 1 15 1 1 13 10 1 10 4 1 8 6 1 5 10 1 1 7 1
27 25 47 6 1 46 9 1 44 4 1 43 10 1 42 8 1 41 2 1 37 10 1 35 3 1 34 10 1 33 8 1 31 6 1 25 8 1 24 1 1 23 4 1 18 6 1 16 9 1 15 3 1 14 9 1 13 1 1 12 7 1 8 9 1 7 8 1 6 1 1 2 4 1 1 7 1
28 21 46 6 1 45 2 1 43 9 1 41 4 1 34 4 1 33 10 1 31 6 1 30 4 1 25 1 1 22 3 1 21 7 1 20 8 1 16 10 1 15 4 1 14 2 1 12 9 1 10 4 1 8 7 1 6 6 1 4 6 1 1 9 1
29 23 50 4 1 48 8 1 47 1 1 46 1 1 45 10 1 43 10 1 41 7 1 40 9 1 34 1 1 33 1 1 29 6 1 28 9 1 25 8 1 21 5 1 20 2 1 15 4 1 14 8 1 13 9 1 10 3 1 9 10 1 8 5 1 6 3 1 4 8 1
30 24 50 3 1 48 9 1 47 10 1 46 9 1 45 9 1 44 5 1 43 1 1 41 5 1 38 4 1 37 10 1 34 4 1 33 3 1 32 2 1 29 7 1 25 5 1 20 5 1 19 9 1 18 3 1 14 4 1 13 10 1 10 2 1 8 10 1 4 10 1 2 9 1
31 22 47 1 1 46 5 1 44 4 1 43 5 1 41 9 1 38 1 1 36 1 1 35 1 1 33 1 1 32 10 1 25 5 1 19 3 1 17 8 1 16 7 1 15 5 1 14 10 1 13 3 1 12 3 1 8 7 1 6 2 1 2 9 1 1 7 1
32 19 47 5 1 46 9 1 43 7 1 42 2 1 36 2 1 35 10 1 32 9 1 31 6 1 25 1 1 23 1 1 16 10 1 15 1 1 14 4 1 13 7 1 12 8 1 8 3 1 7 5 1 6 10 1 1 9 1
33 24 50 8 1 47 2 1 46 10 1 45 2 1 44 4 1 43 4 1 41 8 1 34 7 1 30 6 1 29 4 1 25 10 1 21 8 1 16 6 1 15 5 1 14 10 1 13 7 1 12 9 1 11 1 1 10 9 1 8 4 1 6 6 1 5 4 1 2 1 1 1 3 1
34 17 50 9 1 48 4 1 45 3 1 41 4 1 39 9 1 33 2 1 29 9 1 26 6 1 25 3 1 20 9 1 19 6 1 14 7 1 12 3 1 9 1 1 8 5 1 4 7 1 3 8 1
35 20 48 8 1 47 4 1 46 10 1 45 8 1 44 7 1 43 2 1 38 8 1 36 8 1 33 2 1 32 9 1 25 1 1 19 3 1 18 3 1 15 5 1 14 7 1 13 3 1 9 8 1 8 9 1 6 10 1 2 8 1
36 30 50 5 1 47 2 1 46 9 1 45 2 1 43 5 1 41 5 1 36 7 1 35 2 1 34 1 1 33 10 1 32 4 1 31 10 1 30 9 1 29 2 1 25 8 1 24 2 1 21 6 1 18 1 1 17 4 1 16 3 1 15 8 1 14 6 1 13 10 1 12 3 1 10 7 1 8 6 1 7 5 1 6 7 1 5 8 1 1 8 1
37 21 48 10 1 46 6 1 45 2 1 44 10 1 43 8 1 41 8 1 38 6 1 35 10 1 34 4 1 33 4 1 31 2 1 25 6 1 23 1 1 19 7 1 15 4 1 14 3 1 12 1 1 8 5 1 7 1 1 6 10 1 2 7 1
38 23 50 3 1 47 4 1 46 4 1 45 9 1 43 6 1 41 5 1 36 6 1 34 10 1 32 8 1 30 8 1 29 3 1 25 4 1 21 4 1 20 5 1 17 10 1 15 6 1 14 2 1 13 4 1 10 4 1 8 7 1 6 4 1 5 7 1 1 1 1
39 27 50 4 1 48 6 1 46 8 1 45 6 1 44 8 1 42 10 1 41 9 1 40 3 1 38 6 1 35 9 1 33 3 1 31 2 1 29 10 1 28 3 1 25 7 1 23 4 1 20 3 1 19 6 1 15 10 1 14 9 1 12 2 1 10 8 1 9 6 1 8 1 1 6 1 1 4 6 1 2 3 1
40 17 47 1 1 46 7 1 44 3 1 43 9 1 41 3 1 37 8 1 36 7 1 34 5 1 33 8 1 32 1 1 25 9 1 18 7 1 14 6 1 13 6 1 8 2 1 2 1 1 1 7 1
41 21 47 9 1 46 4 1 45 5 1 43 4 1 41 2 1 36 5 1 35 2 1 33 10 1 32 8 1 31 8 1 25 3 1 24 1 1 16 8 1 15 7 1 14 4 1 12 2 1 8 7 1 7 9 1 6 4 1 2 10 1 1 8 1
42 20 50 3 1 46 8 1 45 10 1 43 4 1 42 4 1 41 4 1 35 5 1 34 2 1 31 3 1 30 7 1 25 7 1 23 3 1 22 10 1 21 10 1 15 6 1 12 7 1 10 6 1 8 10 1 6 7 1 5 8 1
43 26 50 1 1 48 6 1 46 1 1 45 1 1 43 9 1 41 5 1 38 9 1 34 2 1 33 8 1 31 3 1 30 10 1 29 1 1 25 8 1 23 2 1 21 3 1 20 1 1 19 10 1 15 7 1 14 2 1 12 2 1 10 10 1 9 1 1 8 3 1 6 8 1 4 5 1 2 7 1
44 22 48 3 1 47 5 1 45 6 1 44 6 1 43 9 1 40 7 1 38 1 1 36 3 1 33 5 1 32 1 1 28 2 1 25 4 1 20 6 1 19 5 1 18 6 1 14 9 1 13 5 1 9 3 1 8 8 1 4 6 1 2 7 1 1 9 1
45 26 47 1 1 46 2 1 45 9 1 44 9 1 43 6 1 41 4 1 37 8 1 36 5 1 35 6 1 34 3 1 33 9 1 32 9 1 31 5 1 25 2 1 23 9 1 19 1 1 18 8 1 17 6 1 15 2 1 14 2 1 13 4 1 12 3 1 8 8 1 6 5 1 2 2 1 1 6 1
46 17 47 2 1 46 7 1 45 8 1 43 6 1 41 9 1 35 1 1 32 7 1 31 10 1 25 1 1 23 3 1 16 5 1 15 7 1 14 8 1 12 9 1 8 7 1 7 3 1 1 9 1
47 21 47 9 1 46 8 1 43 3 1 42 2 1 41 6 1 35 8 1 34 10 1 33 1 1 31 10 1 30 10 1 25 3 1 23 2 1 21 2 1 19 8 1 15 7 1 14 10 1 13 4 1 12 5 1 11 3 1 8 1 1 6 10 1
48 22 50 10 1 47 1 1 46 6 1 45 10 1 43 7 1 41 7 1 34 1 1 33 9 1 32 5 1 29 9 1 28 8 1 25 8 1 21 6 1 20 6 1 15 3 1 14 1 1 10 10 1 9 4 1 8 6 1 5 1 1 4 8 1 1 7 1
49 26 48 3 1 47 2 1 46 8 1 45 4 1 44 7 1 41 3 1 39 4 1 38 7 1 35 2 1 34 7 1 33 1 1 31 5 1 26 6 1 25 9 1 23 7 1 20 1 1 19 10 1 15 3 1 14 7 1 13 4 1 12 10 1 9 4 1 8 5 1 6 10 1 3 2 1 2 8 1
50 16 47 2 1 46 2 1 43 10 1 36 1 1 35 10 1 32 4 1 31 7 1 25 2 1 18 8 1 17 4 1 13 5 1 12 9 1 8 2 1 7 6 1 2 9 1 1 10 1
51 20 48 6 1 47 4 1 46 9 1 43 7 1 36 7 1 35 10 1 33 9 1 32 5 1 31 10 1 25 3 1 24 2 1 23 10 1 16 3 1 15 5 1 14 1 1 13 6 1 12 6 1 8 10 1 7 2 1 1 2 1
52 23 48 4 1 46 10 1 45 9 1 43 4 1 41 10 1 39 5 1 34 3 1 33 7 1 31 6 1 30 7 1 26 3 1 25 2 1 23 3 1 21 10 1 20 8 1 15 2 1 14 5 1 12 9 1 10 1 1 9 2 1 8 9 1 6 8 1 3 7 1
53 24 50 6 1 48 1 1 47 2 1 46 8 1 45 3 1 41 1 1 40 8 1 35 2 1 34 3 1 33 4 1 31 6 1 29 1 1 28 3 1 25 2 1 23 1 1 20 8 1 15 2 1 14 8 1 12 3 1 10 3 1 9 3 1 8 10 1 5 4 1 4 4 1
54 23 48 4 1 47 4 1 46 5 1 45 7 1 44 4 1 43 5 1 38 3 1 37 9 1 35 3 1 33 7 1 31 9 1 25 9 1 19 4 1 18 9 1 15 6 1 14 3 1 13 3 1 12 3 1 8 10 1 7 6 1 6 1 1 2 8 1 1 10 1
55 25 48 2 1 47 8 1 46 6 1 45 3 1 43 5 1 40 2 1 36 7 1 35 3 1 33 5 1 32 4 1 31 5 1 28 7 1 25 5 1 23 4 1 20 5 1 18 9 1 16 2 1 15 7 1 14 9 1 13 3 1 12 6 1 9 8 1 8 8 1 4 4 1 1 10 1
56 22 47 10 1 46 1 1 44 5 1 43 3 1 42 7 1 37 3 1 35 7 1 33 1 1 32 4 1 31 3 1 25 1 1 23 7 1 18 1 1 16 2 1 15 2 1 13 6 1 12 8 1 8 6 1 7 1 1 6 8 1 2 4 1 1 2 1
57 26 50 8 1 48 1 1 46 8 1 45 4 1 43 7 1 41 3 1 35 6 1 34 2 1 33 10 1 31 10 1 30 4 1 29 8 1 25 5 1 24 2 1 22 1 1 21 3 1 20 5 1 16 4 1 15 2 1 14 7 1 12 6 1 10 7 1 8 8 1 7 3 1 6 9 1 1 5 1
58 18 50 3 1 48 10 1 46 3 1 45 7 1 41 1 1 40 3 1 33 10 1 29 7 1 28 8 1 25 1 1 20 6 1 15 3 1 14 3 1 10 9 1 9 6 1 8 9 1 6 7 1 4 4 1
59 28 50 4 1 48 10 1 47 3 1 46 4 1 45 1 1 44 9 1 43 8 1 41 5 1 38 10 1 37 1 1 35 7 1 34 6 1 33 2 1 32 2 1 31 6 1 29 9 1 25 8 1 20 2 1 19 7 1 18 4 1 14 1 1 13 7 1 12 10 1 10 3 1 8 5 1 5 6 1 2 3 1 1 9 1
60 23 47 5 1 46 4 1 45 1 1 43 9 1 41 6 1 36 1 1 35 9 1 34 1 1 32 9 1 31 1 1 30 8 1 25 8 1 22 10 1 17 5 1 16 5 1 15 10 1 14 3 1 13 10 1 12 8 1 11 1 1 8 6 1 6 1 1 1 6 1
61 24 48 1 1 46 5 1 45 2 1 43 6 1 41 4 1 40 1 1 39 9 1 35 1 1 33 2 1 31 10 1 28 8 1 26 9 1 25 7 1 23 2 1 20 1 1 15 2 1 14 8 1 12 6 1 9 9 1 8 1 1 7 5 1 6 6 1 4 7 1 3 4 1
62 27 50 9 1 47 7 1 46 10 1 45 9 1 44 7 1 43 10 1 41 6 1 37 6 1 34 3 1 32 8 1 30 2 1 29 6 1 25 9 1 21 7 1 20 1 1 18 6 1 16 9 1 15 10 1 14 4 1 13 1 1 11 6 1 10 2 1 8 2 1 6 6 1 5 10 1 2 6 1 1 10 1
63 26 49 6 1 48 1 1 46 9 1 45 8 1 43 4 1 41 7 1 38 9 1 35 9 1 33 5 1 31 5 1 28 9 1 26 5 1 25 2 1 24 5 1 20 1 1 19 8 1 16 10 1 15 4 1 14 10 1 12 1 1 9 8 1 8 3 1 6 9 1 4 7 1 3 8 1 1 4 1
64 19 47 10 1 46 2 1 44 10 1 43 6 1 41 2 1 38 1 1 36 2 1 34 4 1 33 7 1 32 1 1 31 9 1 25 6 1 19 1 1 18 1 1 13 2 1 12 3 1 8 9 1 2 5 1 1 2 1
65 27 48 4 1 47 9 1 46 4 1 45 5 1 43 1 1 41 6 1 36 9 1 35 9 1 33 2 1 32 8 1 31 5 1 26 8 1 25 9 1 24 2 1 17 2 1 16 5 1 15 2 1 14 3 1 13 3 1 12 3 1 9 7 1 8 6 1 7 9 1 6 2 1 3 4 1 2 4 1 1 2 1
66 17 46 7 1 45 4 1 43 2 1 41 9 1 35 8 1 34 10 1 33 4 1 31 6 1 25 6 1 23 10 1 20 4 1 15 7 1 14 10 1 12 4 1 8 8 1 7 6 1 6 7 1
67 23 50 4 1 46 6 1 45 6 1 43 6 1 41 5 1 35 4 1 34 8 1 33 1 1 31 9 1 30 2 1 29 9 1 25 6 1 23 5 1 21 1 1 20 3 1 15 5 1 14 10 1 12 1 1 10 1 1 8 3 1 6 4 1 5 9 1 4 3 1
68 26 48 8 1 47 7 1 46 2 1 45 1 1 44 2 1 43 7 1 41 7 1 40 8 1 38 7 1 37 7 1 35 1 1 34 2 1 33 7 1 31 4 1 28 2 1 25 2 1 20 9 1 19 2 1 18 10 1 14 7 1 13 8 1 12 3 1 9 8 1 8 10 1 4 10 1 2 9 1
69 25 47 4 1 46 8 1 45 6 1 44 7 1 43 3 1 38 8 1 37 7 1 36 10 1 35 3 1 33 1 1 32 4 1 25 2 1 20 5 1 19 8 1 18 1 1 16 6 1 15 5 1 14 4 1 13 8 1 12 7 1 8 9 1 6 9 1 4 9 1 2 9 1 1 8 1
70 19 47 3 1 46 7 1 43 5 1 41 4 1 36 5 1 35 9 1 34 7 1 32 3 1 31 4 1 25 1 1 23 1 1 16 3 1 15 1 1 13 4 1 12 8 1 8 5 1 7 2 1 6 10 1 1 9 1
71 21 46 7 1 45 2 1 43 1 1 42 6 1 41 9 1 35 7 1 34 7 1 33 2 1 31 3 1 25 4 1 23 7 1 22 4 1 20 10 1 15 2 1 14 5 1 12 1 1 10 2 1 8 4 1 6 3 1 4 9 1 1 9 1
72 23 50 4 1 46 6 1 45 10 1 43 3 1 41 3 1 35 6 1 34 5 1 33 7 1 31 3 1 30 7 1 29 9 1 25 8 1 23 1 1 21 2 1 20 3 1 15 7 1 14 3 1 12 2 1 10 5 1 8 2 1 6 10 1 4 1 1 1 9 1
73 22 48 3 1 46 3 1 45 3 1 44 9 1 43 5 1 41 1 1 40 3 1 38 10 1 33 5 1 28 2 1 25 1 1 20 5 1 19 1 1 16 8 1 15 7 1 14 10 1 12 5 1 9 7 1 8 8 1 4 1 1 2 2 1 1 4 1
74 21 47 2 1 46 7 1 44 7 1 43 6 1 41 7 1 38 5 1 37 1 1 36 1 1 35 7 1 33 10 1 32 3 1 25 2 1 19 2 1 18 3 1 17 5 1 14 4 1 13 5 1 12 8 1 8 2 1 2 7 1 1 3 1
75 23 47 4 1 46 6 1 45 2 1 43 3 1 41 7 1 36 8 1 35 2 1 33 7 1 32 3 1 31 1 1 25 3 1 23 10 1 20 7 1 16 7 1 15 10 1 14 6 1 13 4 1 12 1 1 10 8 1 9 3 1 8 4 1 7 10 1 1 10 1
76 14 46 6 1 41 5 1 35 2 1 34 9 1 31 5 1 30 7 1 25 7 1 23 9 1 21 10 1 15 9 1 12 7 1 11 2 1 8 5 1 6 10 1
77 25 50 6 1 49 8 1 47 7 1 46 5 1 45 6 1 43 10 1 41 6 1 34 5 1 33 8 1 31 2 1 29 1 1 28 6 1 25 10 1 21 3 1 20 7 1 16 4 1 15 6 1 14 6 1 12 8 1 10 3 1 9 2 1 8 5 1 5 2 1 4 2 1 1 5 1
78 25 48 7 1 47 1 1 46 2 1 45 2 1 44 9 1 43 9 1 40 10 1 38 7 1 37 4 1 33 5 1 31 10 1 28 4 1 26 8 1 25 3 1 20 4 1 19 1 1 15 9 1 14 10 1 13 6 1 9 5 1 8 6 1 6 10 1 4 4 1 3 5 1 2 6 1
79 18 47 2 1 46 10 1 45 7 1 43 5 1 41 7 1 36 1 1 33 1 1 32 3 1 25 6 1 18 3 1 17 1 1 15 8 1 14 7 1 13 8 1 10 8 1 8 2 1 6 3 1 1 7 1
80 24 48 10 1 46 8 1 45 2 1 44 8 1 43 7 1 41 8 1 38 8 1 35 10 1 34 6 1 33 9 1 31 3 1 25 3 1 24 8 1 23 10 1 19 6 1 16 1 1 15 10 1 14 1 1 12 9 1 8 2 1 7 6 1 6 8 1 2 4 1 1 4 1
81 23 47 2 1 46 8 1 45 3 1 43 9 1 41 9 1 36 3 1 34 2 1 32 7 1 31 9 1 30 2 1 25 6 1 23 5 1 21 10 1 18 2 1 17 7 1 15 9 1 14 7 1 13 6 1 12 9 1 10 6 1 8 9 1 6 6 1 1 3 1
82 31 50 3 1 48 5 1 47 1 1 46 4 1 45 5 1 43 8 1 42 2 1 41 1 1 40 6 1 36 10 1 35 10 1 34 3 1 33 4 1 32 10 1 31 5 1 29 2 1 28 4 1 25 9 1 23 10 1 20 6 1 15 4 1 14 5 1 13 6 1 12 9 1 10 6 1 9 6 1 8 10 1 6 8 1 5 8 1 4 5 1 1 7 1
83 23 50 1 1 48 7 1 47 4 1 46 5 1 45 1 1 44 7 1 43 8 1 41 5 1 38 8 1 37 6 1 35 6 1 33 9 1 31 4 1 29 1 1 25 8 1 19 1 1 18 9 1 14 6 1 13 10 1 12 1 1 8 4 1 2 10 1 1 10 1
84 19 47 4 1 46 10 1 45 1 1 43 9 1 36 2 1 33 1 1 32 10 1 25 7 1 20 1 1 18 4 1 16 1 1 15 4 1 14 3 1 13 4 1 12 8 1 8 6 1 4 10 1 2 9 1 1 5 1
85 20 50 1 1 46 5 1 45 6 1 43 1 1 42 4 1 41 6 1 35 5 1 34 8 1 31 8 1 25 3 1 23 5 1 16 2 1 15 1 1 14 8 1 12 8 1 10 4 1 8 2 1 7 1 1 6 6 1 1 6 1
86 24 48 3 1 46 3 1 45 9 1 43 10 1 41 1 1 38 4 1 35 10 1 34 5 1 33 4 1 31 7 1 30 7 1 25 7 1 22 9 1 21 9 1 19 10 1 15 2 1 14 7 1 12 8 1 11 4 1 10 8 1 9 8 1 8 5 1 6 10 1 2 6 1
87 25 50 10 1 48 4 1 47 10 1 46 5 1 45 3 1 43 2 1 41 1 1 40 1 1 36 9 1 35 3 1 33 5 1 32 2 1 29 10 1 28 6 1 25 2 1 20 4 1 18 7 1 14 8 1 13 8 1 12 6 1 10 6 1 9 3 1 8 4 1 4 2 1 1 2 1
88 23 48 6 1 47 3 1 46 1 1 44 6 1 43 6 1 41 8 1 38 5 1 37 3 1 35 2 1 33 7 1 32 2 1 31 8 1 25 3 1 23 6 1 19 4 1 18 3 1 15 2 1 14 2 1 13 1 1 12 5 1 8 3 1 7 2 1 2 2 1
89 21 47 4 1 46 2 1 45 10 1 43 9 1 41 2 1 36 1 1 35 7 1 34 6 1 32 2 1 31 3 1 25 8 1 22 4 1 17 6 1 16 3 1 15 7 1 13 4 1 12 4 1 10 2 1 8 2 1 6 9 1 1 3 1
90 15 46 8 1 43 8 1 41 9 1 35 5 1 34 6 1 31 5 1 25 10 1 23 7 1 15 4 1 14 6 1 12 10 1 8 8 1 7 3 1 6 3 1 1 5 1
91 29 50 4 1 48 2 1 47 5 1 46 8 1 45 4 1 43 10 1 41 8 1 36 9 1 35 9 1 34 3 1 33 4 1 32 7 1 31 1 1 30 1 1 29 5 1 25 4 1 23 2 1 21 2 1 19 8 1 15 5 1 14 9 1 12 3 1 11 8 1 10 7 1 9 6 1 8 7 1 6 1 1 5 6 1 1 2 1
92 22 49 10 1 48 5 1 47 4 1 45 10 1 44 9 1 43 6 1 41 1 1 39 8 1 38 7 1 33 4 1 28 2 1 26 5 1 25 4 1 20 5 1 19 10 1 14 4 1 9 4 1 8 4 1 4 2 1 3 10 1 2 1 1 1 7 1
93 28 47 8 1 46 8 1 45 8 1 44 3 1 43 3 1 41 6 1 37 8 1 36 8 1 35 2 1 34 5 1 33 5 1 32 5 1 31 5 1 25 5 1 23 9 1 20 8 1 19 8 1 18 3 1 15 10 1 14 6 1 13 10 1 12 8 1 10 7 1 8 6 1 6 4 1 4 1 1 2 4 1 1 3 1
94 23 47 2 1 46 8 1 43 10 1 41 9 1 36 10 1 35 10 1 34 9 1 33 5 1 32 9 1 31 4 1 25 3 1 24 6 1 23 5 1 19 7 1 17 7 1 16 8 1 15 1 1 13 7 1 12 8 1 8 5 1 7 2 1 6 10 1 1 2 1
95 20 47 4 1 46 9 1 43 10 1 41 8 1 36 5 1 35 4 1 34 9 1 32 1 1 31 1 1 25 1 1 23 1 1 18 7 1 15 9 1 13 3 1 12 2 1 10 8 1 8 4 1 7 6 1 6 1 1 1 10 1
96 24 50 9 1 47 7 1 46 5 1 45 7 1 44 5 1 43 1 1 41 5 1 34 6 1 32 3 1 31 3 1 30 3 1 29 8 1 25 8 1 21 8 1 20 5 1 15 1 1 14 3 1 12 1 1 10 1 1 8 1 1 6 1 1 5 1 1 2 8 1 1 3 1
97 25 48 6 1 47 1 1 46 8 1 45 1 1 44 10 1 43 10 1 41 2 1 40 8 1 38 1 1 36 10 1 34 9 1 33 8 1 32 3 1 28 1 1 25 6 1 21 6 1 20 8 1 19 7 1 18 6 1 14 3 1 13 4 1 9 4 1 8 1 1 4 5 1 2 3 1
98 15 47 6 1 46 7 1 44 9 1 43 4 1 37 6 1 36 9 1 33 6 1 32 6 1 25 1 1 18 3 1 14 2 1 13 2 1 8 5 1 2 8 1 1 8 1
99 25 47 8 1 46 8 1 45 5 1 44 6 1 43 5 1 41 5 1 37 4 1 36 3 1 35 8 1 34 7 1 32 2 1 31 10 1 25 10 1 23 10 1 21 3 1 18 9 1 16 2 1 15 6 1 13 6 1 12 6 1 8 6 1 7 10 1 6 3 1 2 2 1 1 2 1
100 24 47 9 1 46 2 1 43 10 1 42 1 1 41 1 1 35 6 1 34 3 1 33 7 1 32 4 1 31 7 1 25 3 1 24 4 1 23 7 1 22 2 1 18 5 1 16 1 1 15 3 1 13 2 1 12 4 1 11 1 1 8 1 1 7 10 1 6 10 1 1 10 1
101 25 50 10 1 47 1 1 46 4 1 45 5 1 43 8 1 41 2 1 36 3 1 35 10 1 34 4 1 33 9 1 32 9 1 30 5 1 29 10 1 25 6 1 21 4 1 20 1 1 15 1 1 14 10 1 13 2 1 12 10 1 10 7 1 8 3 1 6 2 1 4 4 1 1 4 1
102 26 48 6 1 47 8 1 46 7 1 45 10 1 44 10 1 43 3 1 41 8 1 40 4 1 38 10 1 34 3 1 33 8 1 32 10 1 30 6 1 27 1 1 25 5 1 21 5 1 20 4 1 19 5 1 15 6 1 14 2 1 10 9 1 9 2 1 8 2 1 6 6 1 4 3 1 2 8 1
103 21 47 2 1 46 1 1 44 6 1 43 6 1 41 7 1 37 3 1 36 2 1 34 8 1 33 4 1 32 5 1 30 1 1 25 4 1 18 8 1 17 4 1 15 1 1 13 2 1 12 5 1 8 2 1 6 3 1 2 3 1 1 5 1
104 17 47 5 1 46 9 1 45 7 1 43 5 1 41 9 1 35 8 1 32 7 1 31 3 1 25 5 1 23 10 1 16 7 1 15 2 1 13 5 1 12 3 1 8 2 1 7 9 1 1 3 1
105 22 47 6 1 46 2 1 44 10 1 43 2 1 41 8 1 37 7 1 35 2 1 34 3 1 32 2 1 31 6 1 30 9 1 25 9 1 23 6 1 21 2 1 18 7 1 15 8 1 13 7 1 12 5 1 11 8 1 8 10 1 6 9 1 2 7 1
106 32 50 8 1 49 4 1 48 8 1 47 6 1 46 1 1 45 5 1 43 2 1 41 8 1 36 3 1 35 2 1 34 2 1 33 10 1 32 6 1 31 8 1 29 8 1 28 6 1 25 2 1 24 5 1 23 2 1 21 5 1 20 3 1 16 10 1 15 1 1 14 5 1 13 10 1 12 3 1 10 9 1 9 6 1 8 3 1 5 3 1 4 5 1 1 5 1
107 26 48 6 1 47 3 1 46 7 1 45 8 1 44 9 1 41 5 1 38 7 1 37 6 1 35 7 1 34 10 1 33 5 1 31 4 1 26 3 1 25 4 1 22 7 1 19 4 1 18 9 1 15 8 1 14 10 1 13 3 1 12 1 1 9 6 1 8 1 1 6 1 1 3 6 1 2 8 1
108 19 47 5 1 46 8 1 45 3 1 43 7 1 36 9 1 35 8 1 33 8 1 32 10 1 31 1 1 25 4 1 18 6 1 17 8 1 15 1 1 14 8 1 13 4 1 12 1 1 8 1 1 6 1 1 1 7 1
109 20 47 4 1 46 7 1 43 2 1 41 1 1 35 3 1 34 7 1 32 9 1 31 7 1 25 2 1 24 2 1 23 5 1 18 1 1 16 7 1 15 5 1 13 6 1 12 5 1 8 4 1 7 7 1 6 3 1 1 3 1
110 20 47 9 1 46 2 1 45 4 1 41 5 1 34 1 1 33 5 1 31 3 1 30 1 1 25 3 1 23 1 1 21 5 1 20 10 1 15 1 1 14 2 1 13 1 1 12 8 1 10 3 1 8 7 1 6 5 1 4 4 1
111 28 50 10 1 48 7 1 47 9 1 46 7 1 45 9 1 44 8 1 43 7 1 41 9 1 40 3 1 37 9 1 34 3 1 33 10 1 29 8 1 28 1 1 25 8 1 20 9 1 19 5 1 15 4 1 14 10 1 13 9 1 10 8 1 9 1 1 8 9 1 6 1 1 5 7 1 4 3 1 2 8 1 1 5 1
112 23 48 9 1 47 6 1 46 7 1 45 2 1 44 7 1 43 8 1 41 9 1 38 9 1 37 8 1 35 5 1 33 8 1 32 1 1 25 9 1 19 3 1 18 6 1 16 1 1 15 4 1 14 9 1 13 10 1 12 9 1 8 1 1 2 8 1 1 9 1
113 22 47 9 1 46 1 1 43 3 1 41 3 1 36 10 1 35 9 1 34 7 1 33 6 1 32 2 1 31 7 1 25 9 1 23 7 1 18 9 1 16 10 1 15 5 1 14 9 1 13 9 1 12 1 1 8 2 1 7 2 1 6 4 1 1 3 1
114 14 46 1 1 43 7 1 42 6 1 41 2 1 35 1 1 31 3 1 25 7 1 23 1 1 15 1 1 12 7 1 8 1 1 7 9 1 6 8 1 1 2 1
115 24 50 6 1 47 5 1 46 10 1 45 5 1 43 7 1 41 6 1 35 6 1 34 3 1 33 6 1 31 9 1 30 10 1 25 7 1 22 7 1 21 10 1 15 5 1 14 5 1 13 5 1 12 7 1 11 9 1 10 5 1 9 10 1 8 7 1 6 6 1 2 5 1
116 22 50 4 1 48 4 1 46 2 1 45 5 1 43 2 1 41 3 1 40 9 1 34 2 1 33 7 1 30 3 1 29 1 1 27 4 1 25 7 1 21 1 1 20 4 1 15 10 1 14 4 1 12 8 1 10 3 1 9 1 1 6 9 1 4 7 1
117 26 48 5 1 47 1 1 46 5 1 45 3 1 44 6 1 43 5 1 41 3 1 38 4 1 37 7 1 35 4 1 33 5 1 32 6 1 31 10 1 25 2 1 23 7 1 19 1 1 18 5 1 15 1 1 14 4 1 13 3 1 12 6 1 8 8 1 7 8 1 6 6 1 2 3 1 1 6 1
118 16 47 9 1 46 8 1 45 5 1 43 2 1 36 6 1 35 8 1 32 6 1 31 4 1 25 6 1 17 8 1 16 10 1 14 3 1 13 2 1 12 3 1 8 4 1 1 2 1
119 19 46 10 1 44 7 1 43 7 1 42 1 1 41 4 1 38 8 1 35 1 1 33 1 1 31 10 1 25 1 1 23 5 1 19 10 1 15 7 1 14 7 1 12 3 1 8 8 1 7 8 1 6 3 1 2 5 1
120 21 50 6 1 46 7 1 45 6 1 43 10 1 41 9 1 34 4 1 30 3 1 29 3 1 25 10 1 21 1 1 20 8 1 16 2 1 15 1 1 14 8 1 11 8 1 10 9 1 8 10 1 6 10 1 5 8 1 4 3 1 1 6 1
121 23 49 8 1 48 2 1 47 7 1 46 8 1 45 4 1 44 1 1 40 9 1 38 9 1 33 1 1 28 6 1 26 4 1 25 4 1 20 9 1 19 8 1 15 10 1 14 4 1 13 3 1 9 5 1 8 5 1 6 9 1 4 5 1 3 4 1 2 6 1
122 19 47 7 1 46 3 1 45 7 1 44 5 1 43 1 1 37 7 1 36 5 1 33 4 1 32 10 1 31 10 1 25 10 1 19 9 1 18 4 1 14 9 1 13 4 1 12 2 1 8 8 1 2 7 1 1 9 1
123 22 47 2 1 46 7 1 44 2 1 43 2 1 41 1 1 36 4 1 35 9 1 33 1 1 32 2 1 31 8 1 25 1 1 24 3 1 17 8 1 16 5 1 15 6 1 13 3 1 12 2 1 8 1 1 7 3 1 6 3 1 2 7 1 1 5 1
124 20 47 6 1 46 6 1 45 8 1 43 4 1 41 7 1 36 6 1 35 5 1 34 4 1 32 4 1 31 2 1 25 5 1 23 5 1 17 5 1 15 4 1 14 4 1 13 1 1 12 2 1 8 4 1 6 5 1 1 1 1
125 26 50 2 1 48 2 1 46 3 1 45 2 1 44 10 1 43 6 1 41 10 1 35 1 1 34 6 1 33 7 1 31 4 1 30 6 1 29 10 1 25 7 1 23 3 1 21 3 1 20 2 1 15 1 1 14 2 1 12 4 1 10 9 1 8 3 1 6 5 1 5 4 1 2 2 1 1 10 1
126 23 48 6 1 46 8 1 45 2 1 44 8 1 43 7 1 41 8 1 40 6 1 38 9 1 33 1 1 31 5 1 28 9 1 25 8 1 23 8 1 20 8 1 19 4 1 15 1 1 14 7 1 12 7 1 9 2 1 8 2 1 4 7 1 2 8 1 1 1 1
127 26 50 4 1 47 1 1 46 10 1 45 6 1 44 6 1 43 3 1 41 8 1 37 3 1 36 5 1 34 2 1 33 10 1 32 8 1 31 5 1 29 7 1 25 9 1 23 6 1 18 10 1 15 7 1 14 1 1 13 4 1 12 5 1 10 8 1 8 1 1 6 7 1 2 9 1 1 6 1
128 19 47 10 1 46 7 1 44 6 1 43 9 1 35 9 1 33 4 1 32 1 1 31 10 1 25 2 1 23 6 1 16 5 1 15 3 1 14 8 1 12 3 1 8 2 1 7 5 1 6 2 1 2 7 1 1 4 1
129 24 46 4 1 45 2 1 43 3 1 42 6 1 41 9 1 35 4 1 34 5 1 33 4 1 31 3 1 30 9 1 25 9 1 23 9 1 22 7 1 20 5 1 19 10 1 15 3 1 14 10 1 12 8 1 11 5 1 8 7 1 6 2 1 4 6 1 2 4 1 1 8 1
130 24 50 1 1 47 7 1 46 8 1 45 4 1 43 7 1 41 7 1 36 8 1 34 7 1 33 5 1 32 5 1 30 7 1 29 4 1 25 2 1 21 5 1 20 8 1 18 2 1 15 10 1 14 2 1 13 10 1 10 8 1 8 5 1 6 10 1 4 3 1 1 3 1
131 23 48 6 1 46 8 1 45 2 1 44 6 1 43 4 1 40 4 1 38 6 1 35 4 1 33 4 1 31 4 1 27 8 1 25 2 1 23 1 1 20 1 1 19 4 1 15 5 1 14 9 1 12 2 1 9 8 1 8 3 1 7 8 1 3 2 1 2 5 1
132 22 47 8 1 46 7 1 45 2 1 44 8 1 43 9 1 41 4 1 37 1 1 36 2 1 34 5 1 32 10 1 30 2 1 25 6 1 21 5 1 18 9 1 17 1 1 15 4 1 13 10 1 10 7 1 8 4 1 6 5 1 2 2 1 1 8 1
133 26 48 4 1 46 1 1 45 1 1 44 1 1 43 8 1 40 1 1 38 8 1 35 8 1 33 6 1 31 6 1 28 5 1 25 7 1 23 8 1 20 2 1 19 3 1 16 2 1 15 8 1 14 7 1 12 1 1 9 3 1 8 10 1 7 10 1 6 6 1 4 2 1 2 3 1 1 3 1
134 20 47 8 1 46 1 1 43 5 1 41 4 1 36 2 1 35 1 1 34 3 1 32 7 1 31 10 1 30 9 1 25 9 1 23 1 1 21 6 1 15 5 1 13 7 1 12 2 1 11 1 1 8 6 1 6 1 1 1 9 1
135 26 50 4 1 49 7 1 47 1 1 46 2 1 45 6 1 43 7 1 41 1 1 40 9 1 35 5 1 34 4 1 33 2 1 31 2 1 29 2 1 28 2 1 25 3 1 23 3 1 21 7 1 20 4 1 15 7 1 14 8 1 12 10 1 10 2 1 9 3 1 8 1 1 5 8 1 4 4 1
136 22 48 5 1 47 5 1 46 1 1 45 8 1 44 4 1 43 3 1 41 10 1 38 10 1 37 8 1 36 3 1 33 7 1 32 10 1 25 10 1 19 3 1 18 5 1 14 7 1 13 7 1 9 2 1 8 10 1 3 1 1 2 2 1 1 10 1
137 20 48 9 1 47 7 1 46 2 1 43 1 1 36 7 1 35 6 1 33 1 1 32 9 1 31 9 1 25 10 1 23 9 1 18 1 1 17 1 1 15 4 1 14 10 1 13 9 1 12 7 1 8 7 1 7 5 1 1 6 1
138 24 46 5 1 45 5 1 43 9 1 41 5 1 35 8 1 34 1 1 33 3 1 31 1 1 30 1 1 25 10 1 24 2 1 23 10 1 21 5 1 20 2 1 16 7 1 15 4 1 14 9 1 12 10 1 10 4 1 9 9 1 8 2 1 7 5 1 6 8 1 1 5 1
139 18 48 2 1 46 5 1 43 3 1 41 10 1 35 8 1 34 7 1 33 7 1 31 3 1 30 10 1 25 2 1 23 6 1 21 8 1 15 8 1 14 1 1 12 3 1 10 8 1 8 6 1 6 2 1
140 28 50 10 1 48 4 1 47 5 1 46 9 1 45 6 1 43 3 1 42 5 1 41 2 1 40 8 1 35 2 1 34 3 1 33 2 1 31 8 1 29 10 1 28 4 1 25 6 1 23 1 1 20 3 1 15 1 1 14 1 1 13 4 1 12 1 1 10 10 1 9 3 1 8 9 1 6 1 1 5 6 1 4 2 1
141 19 48 4 1 47 4 1 46 3 1 44 2 1 38 5 1 37 8 1 35 10 1 33 4 1 32 4 1 31 3 1 25 6 1 23 1 1 19 9 1 18 9 1 14 8 1 13 5 1 12 3 1 8 1 1 2 1 1
142 18 47 5 1 46 6 1 44 5 1 43 3 1 41 7 1 37 5 1 36 6 1 35 8 1 32 4 1 31 5 1 25 5 1 18 4 1 16 1 1 13 4 1 12 1 1 8 5 1 2 9 1 1 1 1
143 17 48 5 1 46 2 1 43 5 1 42 6 1 35 7 1 33 9 1 31 5 1 24 10 1 23 3 1 16 1 1 15 1 1 14 8 1 12 5 1 8 7 1 7 7 1 6 10 1 1 2 1
144 17 50 8 1 46 3 1 45 8 1 41 7 1 35 10 1 34 7 1 33 4 1 31 3 1 30 5 1 25 3 1 22 1 1 21 10 1 15 3 1 12 3 1 11 7 1 10 7 1 6 7 1
145 26 50 8 1 48 6 1 47 10 1 46 10 1 45 5 1 44 1 1 43 6 1 41 2 1 39 10 1 35 4 1 34 9 1 33 4 1 31 4 1 29 9 1 27 5 1 25 1 1 21 10 1 20 8 1 14 7 1 12 8 1 10 10 1 9 8 1 8 10 1 4 7 1 3 7 1 2 9 1
146 18 48 6 1 47 7 1 46 6 1 45 3 1 44 8 1 38 5 1 37 1 1 33 9 1 32 7 1 31 4 1 25 1 1 19 9 1 18 4 1 14 1 1 13 2 1 12 10 1 8 1 1 2 2 1
147 25 48 9 1 47 2 1 46 8 1 45 7 1 43 9 1 41 10 1 36 5 1 35 5 1 33 5 1 32 1 1 31 1 1 25 4 1 24 5 1 20 10 1 17 9 1 16 3 1 15 2 1 14 9 1 13 3 1 12 5 1 9 4 1 8 7 1 7 1 1 6 8 1 1 3 1
148 12 46 2 1 43 3 1 41 10 1 35 4 1 34 1 1 33 2 1 31 7 1 23 1 1 15 8 1 12 7 1 7 6 1 6 5 1
149 28 50 10 1 47 1 1 46 5 1 45 6 1 43 1 1 41 3 1 35 10 1 34 2 1 33 10 1 32 10 1 31 10 1 30 9 1 29 1 1 25 1 1 24 6 1 21 6 1 20 6 1 16 7 1 15 9 1 14 10 1 12 2 1 11 10 1 10 10 1 9 4 1 8 10 1 6 1 1 5 8 1 1 6 1
150 28 49 3 1 48 6 1 47 1 1 46 5 1 45 9 1 44 2 1 41 7 1 40 9 1 38 3 1 34 10 1 33 1 1 32 1 1 31 2 1 28 3 1 25 5 1 22 1 1 20 7 1 19 5 1 15 1 1 14 3 1 13 8 1 12 9 1 9 7 1 8 4 1 6 5 1 4 10 1 3 2 1 2 8 1
151 25 48 7 1 47 1 1 46 8 1 45 10 1 44 8 1 43 9 1 41 10 1 37 1 1 36 7 1 35 10 1 34 5 1 33 7 1 32 4 1 31 2 1 25 4 1 20 2 1 19 8 1 18 8 1 14 4 1 13 9 1 12 6 1 9 1 1 8 3 1 2 4 1 1 9 1
152 22 50 10 1 47 1 1 46 2 1 45 3 1 43 2 1 41 3 1 36 1 1 35 5 1 34 10 1 32 10 1 31 9 1 25 4 1 24 1 1 16 6 1 15 9 1 14 5 1 13 3 1 12 10 1 10 4 1 8 8 1 7 9 1 1 4 1
153 16 46 4 1 45 10 1 43 9 1 41 3 1 35 3 1 34 6 1 33 7 1 31 4 1 23 1 1 20 2 1 15 9 1 14 3 1 12 10 1 7 5 1 6 3 1 1 4 1
154 25 50 2 1 47 9 1 46 7 1 45 2 1 44 3 1 43 7 1 41 5 1 35 8 1 34 6 1 31 10 1 30 10 1 29 6 1 25 10 1 23 4 1 21 4 1 20 10 1 15 9 1 14 5 1 12 4 1 10 4 1 8 4 1 6 8 1 5 6 1 2 8 1 1 2 1
155 23 48 2 1 47 6 1 46 2 1 45 6 1 44 3 1 43 9 1 40 5 1 38 10 1 35 1 1 33 7 1 32 3 1 28 3 1 25 1 1 20 4 1 19 3 1 16 10 1 14 8 1 12 10 1 9 10 1 8 3 1 4 7 1 2 3 1 1 6 1
156 22 47 4 1 46 2 1 45 1 1 44 4 1 43 3 1 41 5 1 37 5 1 36 9 1 34 8 1 32 4 1 31 5 1 25 5 1 23 7 1 18 8 1 15 6 1 14 1 1 13 4 1 12 4 1 8 8 1 6 7 1 2 5 1 1 3 1
157 23 50 7 1 47 5 1 46 5 1 45 4 1 43 5 1 41 9 1 35 10 1 33 2 1 32 3 1 31 4 1 29 2 1 25 3 1 23 2 1 20 1 1 16 9 1 15 7 1 14 2 1 12 2 1 10 2 1 8 3 1 7 4 1 4 3 1 1 5 1
158 19 47 5 1 46 10 1 42 6 1 41 10 1 35 6 1 34 7 1 33 1 1 31 7 1 30 1 1 25 3 1 23 1 1 22 10 1 15 10 1 14 3 1 13 1 1 12 10 1 11 1 1 8 1 1 6 6 1
159 26 50 1 1 48 8 1 46 4 1 45 6 1 43 1 1 41 8 1 38 4 1 34 6 1 33 2 1 30 8 1 29 8 1 25 9 1 21 5 1 20 5 1 19 3 1 16 10 1 15 1 1 14 9 1 12 4 1 10 3 1 9 1 1 8 3 1 5 4 1 4 4 1 2 5 1 1 4 1
160 19 48 8 1 47 8 1 45 4 1 44 7 1 43 6 1 39 4 1 38 3 1 33 5 1 27 2 1 25 3 1 20 5 1 19 7 1 15 9 1 14 5 1 9 8 1 8 6 1 3 8 1 2 1 1 1 6 1
161 21 47 7 1 46 4 1 45 6 1 44 2 1 43 4 1 41 10 1 37 10 1 36 10 1 34 6 1 32 4 1 25 8 1 20 6 1 18 1 1 17 10 1 16 9 1 14 9 1 13 1 1 10 7 1 8 7 1 2 3 1 1 4 1
162 19 46 5 1 45 3 1 43 4 1 42 10 1 35 3 1 33 5 1 31 7 1 25 9 1 24 7 1 23 5 1 16 8 1 15 5 1 14 3 1 12 9 1 9 2 1 8 9 1 7 6 1 6 8 1 1 9 1
163 30 50 10 1 47 10 1 46 5 1 45 1 1 44 6 1 43 6 1 41 6 1 37 9 1 35 5 1 34 3 1 32 6 1 31 9 1 30 10 1 29 5 1 25 10 1 23 4 1 21 1 1 20 8 1 18 9 1 15 6 1 14 4 1 13 3 1 12 5 1 11 6 1 10 4 1 8 3 1 6 9 1 5 2 1 2 8 1 1 5 1
164 20 50 3 1 48 1 1 46 8 1 45 8 1 41 9 1 40 4 1 34 5 1 33 10 1 29 3 1 28 6 1 25 4 1 21 1 1 20 7 1 15 10 1 14 7 1 10 2 1 9 1 1 8 1 1 5 3 1 4 5 1
165 19 48 4 1 47 2 1 46 5 1 45 6 1 44 9 1 43 2 1 41 1 1 38 7 1 37 4 1 33 1 1 25 8 1 19 1 1 14 4 1 13 2 1 9 1 1 8 9 1 3 8 1 2 1 1 1 9 1
166 19 47 2 1 46 3 1 44 1 1 43 6 1 36 8 1 35 4 1 33 4 1 32 3 1 31 7 1 25 9 1 23 8 1 18 10 1 16 9 1 15 5 1 13 5 1 12 4 1 8 3 1 2 6 1 1 10 1
167 26 50 6 1 47 10 1 46 7 1 45 2 1 43 9 1 41 9 1 36 5 1 35 1 1 32 2 1 31 4 1 29 5 1 25 10 1 24 5 1 23 2 1 20 8 1 17 4 1 16 1 1 15 1 1 14 3 1 13 9 1 12 6 1 10 10 1 8 9 1 7 7 1 6 2 1 1 4 1
168 15 46 9 1 43 7 1 41 4 1 35 6 1 34 1 1 31 3 1 30 7 1 25 2 1 23 2 1 21 4 1 15 7 1 12 9 1 10 1 1 8 1 1 6 1 1
169 28 50 7 1 48 9 1 47 3 1 46 6 1 45 9 1 43 6 1 41 5 1 40 3 1 36 9 1 35 5 1 34 5 1 33 7 1 32 2 1 31 4 1 29 1 1 28 5 1 25 8 1 21 8 1 20 6 1 14 10 1 13 5 1 12 9 1 10 9 1 9 4 1 8 5 1 5 6 1 4 5 1 1 6 1
170 22 48 4 1 47 7 1 46 9 1 44 6 1 41 2 1 38 9 1 37 10 1 34 1 1 33 6 1 32 10 1 31 3 1 25 10 1 23 4 1 19 2 1 18 7 1 15 7 1 14 6 1 13 2 1 12 5 1 8 10 1 6 6 1 2 1 1
171 18 50 6 1 47 1 1 46 9 1 45 1 1 43 8 1 41 7 1 36 10 1 35 9 1 32 8 1 25 1 1 18 8 1 16 9 1 15 1 1 13 7 1 12 6 1 10 8 1 8 8 1 1 10 1
172 17 47 3 1 46 3 1 45 4 1 43 5 1 42 7 1 35 6 1 32 9 1 31 2 1 25 4 1 23 9 1 15 3 1 14 10 1 12 4 1 8 3 1 7 7 1 6 10 1 1 2 1
173 21 50 9 1 47 1 1 46 6 1 45 7 1 44 7 1 43 10 1 41 8 1 34 2 1 32 3 1 30 2 1 25 1 1 22 8 1 21 9 1 15 4 1 11 9 1 10 2 1 8 6 1 6 4 1 5 7 1 2 4 1 1 5 1
174 27 50 9 1 48 4 1 47 9 1 46 9 1 45 4 1 43 3 1 41 4 1 39 10 1 35 10 1 33 10 1 31 6 1 29 2 1 27 5 1 25 10 1 23 4 1 20 8 1 16 6 1 15 1 1 14 7 1 12 8 1 10 5 1 9 3 1 8 9 1 7 9 1 4 8 1 3 9 1 1 2 1
175 23 47 9 1 46 4 1 44 4 1 43 3 1 41 7 1 38 3 1 37 10 1 34 4 1 33 3 1 32 8 1 30 6 1 25 5 1 21 3 1 19 10 1 18 7 1 15 8 1 14 10 1 13 10 1 10 6 1 8 6 1 6 2 1 2 2 1 1 9 1
176 24 48 7 1 47 6 1 46 2 1 45 2 1 43 4 1 41 10 1 36 2 1 35 6 1 34 1 1 33 10 1 32 5 1 31 10 1 25 6 1 24 3 1 23 5 1 21 8 1 17 6 1 16 7 1 15 10 1 14 8 1 13 3 1 12 8 1 8 7 1 1 6 1
177 22 47 7 1 46 10 1 45 10 1 43 1 1 41 9 1 36 10 1 35 3 1 34 3 1 33 4 1 32 7 1 31 9 1 25 1 1 23 6 1 15 4 1 14 3 1 13 4 1 12 5 1 10 8 1 8 8 1 7 3 1 6 6 1 1 10 1
178 19 50 2 1 46 2 1 45 10 1 43 8 1 41 1 1 34 5 1 33 7 1 31 3 1 30 3 1 29 1 1 25 9 1 21 7 1 15 4 1 14 3 1 12 5 1 11 6 1 10 4 1 6 2 1 5 1 1
179 28 50 9 1 48 3 1 47 7 1 46 1 1 45 2 1 43 3 1 41 5 1 40 2 1 38 6 1 36 10 1 35 10 1 34 9 1 33 9 1 32 7 1 31 1 1 28 4 1 25 9 1 20 10 1 19 2 1 14 9 1 13 6 1 12 10 1 10 9 1 9 3 1 8 5 1 4 9 1 3 8 1 1 1 1
180 21 47 2 1 46 5 1 44 7 1 43 3 1 37 8 1 36 1 1 35 7 1 33 6 1 32 6 1 31 10 1 25 7 1 23 6 1 19 2 1 18 1 1 15 10 1 13 4 1 12 7 1 8 1 1 7 10 1 2 8 1 1 6 1
181 24 47 10 1 46 10 1 45 10 1 43 10 1 41 7 1 36 1 1 35 4 1 34 3 1 32 6 1 31 9 1 30 3 1 25 9 1 24 2 1 21 4 1 16 5 1 15 9 1 14 5 1 13 6 1 12 10 1 10 3 1 8 2 1 7 3 1 6 10 1 1 6 1
182 28 48 8 1 47 4 1 46 9 1 45 4 1 44 10 1 43 4 1 41 8 1 40 3 1 37 7 1 35 1 1 34 8 1 33 10 1 31 4 1 28 3 1 25 1 1 23 6 1 22 5 1 20 9 1 18 5 1 15 5 1 14 3 1 13 1 1 12 8 1 9 9 1 8 9 1 6 9 1 4 3 1 2 5 1
183 27 50 7 1 48 8 1 47 3 1 46 2 1 45 6 1 43 2 1 41 7 1 36 3 1 35 5 1 34 9 1 33 1 1 32 3 1 31 7 1 30 8 1 29 1 1 25 10 1 21 3 1 20 6 1 15 8 1 14 5 1 13 6 1 12 10 1 10 9 1 9 3 1 8 7 1 6 1 1 5 8 1
184 23 48 7 1 46 1 1 45 2 1 44 4 1 41 9 1 40 10 1 38 9 1 34 7 1 33 1 1 31 10 1 28 9 1 25 4 1 23 2 1 20 3 1 19 2 1 15 1 1 14 9 1 12 3 1 9 2 1 8 8 1 6 7 1 4 1 1 2 4 1
185 21 47 2 1 46 3 1 44 7 1 43 4 1 41 2 1 37 9 1 36 9 1 35 8 1 34 8 1 32 2 1 25 7 1 21 6 1 18 10 1 15 7 1 13 3 1 12 2 1 10 7 1 8 7 1 6 8 1 2 3 1 1 10 1
186 16 47 10 1 46 10 1 43 7 1 35 7 1 32 10 1 31 9 1 25 3 1 24 4 1 23 6 1 16 7 1 15 1 1 13 6 1 12 7 1 8 9 1 7 2 1 1 9 1
187 21 48 8 1 47 9 1 46 5 1 42 6 1 41 8 1 35 4 1 34 6 1 33 3 1 32 10 1 31 10 1 30 2 1 25 3 1 23 9 1 22 8 1 15 2 1 14 3 1 13 1 1 12 6 1 11 3 1 8 10 1 6 8 1
188 24 50 9 1 48 9 1 46 10 1 45 10 1 43 3 1 41 6 1 40 7 1 35 4 1 34 1 1 33 3 1 31 8 1 30 1 1 29 5 1 28 2 1 25 9 1 21 5 1 20 4 1 15 9 1 14 1 1 12 5 1 10 4 1 9 1 1 5 4 1 4 8 1
189 26 48 1 1 47 3 1 46 5 1 45 2 1 44 1 1 41 5 1 39 4 1 38 4 1 34 3 1 33 3 1 32 2 1 31 1 1 30 9 1 26 2 1 25 6 1 20 4 1 19 9 1 15 5 1 14 2 1 13 6 1 11 9 1 9 6 1 8 5 1 6 7 1 3 2 1 2 5 1
190 18 47 8 1 46 10 1 45 7 1 44 2 1 43 5 1 37 6 1 36 3 1 33 2 1 32 4 1 31 10 1 25 5 1 18 3 1 17 2 1 13 1 1 12 3 1 8 7 1 2 4 1 1 2 1
191 21 47 5 1 46 10 1 43 8 1 41 5 1 35 10 1 34 5 1 33 2 1 32 3 1 31 8 1 25 9 1 24 5 1 23 4 1 18 3 1 16 10 1 15 7 1 13 7 1 12 9 1 8 3 1 7 8 1 6 10 1 1 5 1
192 19 46 1 1 43 2 1 41 9 1 35 7 1 34 5 1 33 4 1 31 5 1 30 3 1 24 2 1 23 6 1 21 8 1 16 7 1 15 2 1 14 5 1 12 4 1 10 10 1 8 2 1 6 8 1 1 10 1
193 27 50 10 1 48 6 1 47 3 1 46 9 1 45 4 1 41 9 1 40 7 1 34 6 1 33 8 1 31 6 1 29 6 1 28 4 1 25 4 1 22 6 1 21 7 1 20 4 1 18 6 1 15 9 1 14 5 1 13 4 1 12 1 1 10 3 1 9 6 1 8 8 1 6 6 1 5 6 1 4 6 1
194 27 50 2 1 48 5 1 47 3 1 46 4 1 45 4 1 44 3 1 43 3 1 41 1 1 38 3 1 37 7 1 35 7 1 33 3 1 31 2 1 29 10 1 25 2 1 23 7 1 20 6 1 19 5 1 15 3 1 14 1 1 13 7 1 12 1 1 9 5 1 8 6 1 4 10 1 2 5 1 1 8 1
195 21 47 5 1 46 1 1 45 7 1 43 7 1 41 2 1 36 1 1 35 10 1 34 1 1 33 10 1 32 8 1 25 10 1 18 3 1 16 7 1 15 3 1 14 6 1 13 6 1 12 6 1 10 5 1 8 8 1 6 5 1 1 3 1
196 26 50 1 1 48 7 1 46 8 1 45 9 1 43 4 1 41 9 1 35 7 1 34 8 1 33 4 1 32 7 1 31 3 1 29 10 1 25 3 1 24 10 1 23 4 1 20 10 1 16 2 1 15 3 1 14 4 1 12 1 1 10 5 1 8 5 1 7 10 1 6 7 1 5 1 1 1 6 1
197 17 47 5 1 46 7 1 43 4 1 41 1 1 34 2 1 31 7 1 30 3 1 25 6 1 22 6 1 21 9 1 15 6 1 13 2 1 12 9 1 10 4 1 8 5 1 6 1 1 1 4 1
198 22 50 4 1 48 6 1 46 9 1 45 2 1 43 1 1 41 1 1 40 10 1 34 10 1 33 2 1 31 3 1 29 9 1 28 9 1 25 2 1 20 2 1 15 6 1 14 8 1 12 7 1 10 8 1 9 4 1 8 2 1 4 3 1 1 6 1
199 23 48 7 1 47 5 1 46 3 1 44 9 1 43 4 1 41 2 1 38 7 1 37 7 1 34 4 1 33 9 1 32 7 1 31 4 1 25 2 1 23 10 1 19 9 1 18 4 1 15 9 1 14 3 1 13 5 1 12 9 1 8 7 1 6 8 1 2 2 1
200 25 50 1 1 47 4 1 46 6 1 45 3 1 44 2 1 43 2 1 41 5 1 36 3 1 35 5 1 33 4 1 32 8 1 29 4 1 25 2 1 20 1 1 18 1 1 16 3 1 15 4 1 14 3 1 13 4 1 12 7 1 10 2 1 8 5 1 4 8 1 2 2 1 1 3 1
EOF
| [
"noreply@github.com"
] | lyandut.noreply@github.com |
bcd9f6a671924c2265125c27ec4b9c8def3e1f98 | b26e71da234b9076e0c3ef9a5ae2d917964b63f6 | /lib/indrnn_forward_gpu.cu.cc | 1dbef1a83d8a49d12d178428959f70dcc999b0a2 | [
"Apache-2.0"
] | permissive | sarwar3328/haste | cc1f95e2ab15163d01ee05457e99ce91c94c9b5b | 9da2454584d5b5bc9b2ae84a3fa2b271306ec622 | refs/heads/master | 2022-10-20T15:31:27.005169 | 2020-07-04T23:17:53 | 2020-07-04T23:55:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,515 | cc | // Copyright 2020 LMNT, Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ==============================================================================
#include <cublas_v2.h>
#include <cuda_runtime_api.h>
#include "blas.h"
#include "haste.h"
#include "inline_ops.h"
namespace {
template<typename T, bool Training, bool ApplyZoneout>
__global__
void IndrnnFwdOps(
const int steps,
const int batch_size,
const int hidden_size,
const T* Wx,
const T* u,
const T* b,
const T* h,
T* h_out,
const float zoneout_prob,
const T* zoneout_mask) {
const int row = blockDim.x * blockIdx.x + threadIdx.x;
const int col = blockDim.y * blockIdx.y + threadIdx.y;
if (row >= hidden_size || col >= batch_size)
return;
const int idx = col * hidden_size + row;
const int NH = batch_size * hidden_size;
const T u_row = u[row];
const T b_row = b[row];
for (int i = 0; i < steps * NH; i += NH) {
const T a = Wx[idx + i] + u_row * h[idx + i] + b_row;
T cur_h_value = tanh(a);
if (ApplyZoneout) {
if (Training) {
cur_h_value = (cur_h_value - h[idx + i]) * zoneout_mask[idx + i] + h[idx + i];
} else {
cur_h_value = (zoneout_prob * h[idx + i]) + ((1.0f - zoneout_prob) * cur_h_value);
}
}
h_out[idx + i] = cur_h_value;
}
}
} // anonymous namespace
namespace haste {
namespace v0 {
namespace indrnn {
template<typename T>
struct ForwardPass<T>::private_data {
bool training;
int batch_size;
int input_size;
int hidden_size;
cublasHandle_t blas_handle;
cudaStream_t stream;
cudaStream_t sync_stream;
};
template<typename T>
ForwardPass<T>::ForwardPass(
const bool training,
const int batch_size,
const int input_size,
const int hidden_size,
const cublasHandle_t& blas_handle,
const cudaStream_t& stream) : data_(new private_data) {
data_->training = training;
data_->batch_size = batch_size;
data_->input_size = input_size;
data_->hidden_size = hidden_size;
data_->blas_handle = blas_handle;
data_->sync_stream = stream;
cudaStreamCreate(&data_->stream);
}
template<typename T>
ForwardPass<T>::~ForwardPass() {
if (data_->sync_stream) {
cudaEvent_t event;
cudaEventCreateWithFlags(&event, cudaEventDisableTiming);
cudaEventRecord(event, data_->stream);
cudaStreamWaitEvent(data_->sync_stream, event, 0);
cudaEventDestroy(event);
} else {
cudaStreamSynchronize(data_->stream);
}
cudaStreamDestroy(data_->stream);
delete data_;
}
template<typename T>
void ForwardPass<T>::Run(
const int steps,
const T* W,
const T* u,
const T* b,
const T* x,
T* h,
T* workspace,
const float zoneout_prob,
const T* zoneout_mask) {
static const T alpha = static_cast<T>(1.0);
static const T beta = static_cast<T>(0.0);
const bool training = data_->training;
const int batch_size = data_->batch_size;
const int input_size = data_->input_size;
const int hidden_size = data_->hidden_size;
const cublasHandle_t blas_handle = data_->blas_handle;
const cudaStream_t stream = data_->stream;
cudaStream_t save_stream;
cublasGetStream(blas_handle, &save_stream);
cublasSetStream(blas_handle, stream);
blas<T>::gemm(blas_handle,
CUBLAS_OP_N, CUBLAS_OP_N,
hidden_size, steps * batch_size, input_size,
&alpha,
W, hidden_size,
x, input_size,
&beta,
workspace, hidden_size);
const dim3 blockDim(64, 16);
const dim3 gridDim(
(hidden_size + blockDim.x - 1) / blockDim.x,
(batch_size + blockDim.y - 1) / blockDim.y);
const int NH = batch_size * hidden_size;
if (training) {
if (zoneout_prob && zoneout_mask) {
IndrnnFwdOps<T, true, true><<<gridDim, blockDim, 0, stream>>>(
steps,
batch_size,
hidden_size,
workspace,
u,
b,
h,
h + NH,
zoneout_prob,
zoneout_mask);
} else {
IndrnnFwdOps<T, true, false><<<gridDim, blockDim, 0, stream>>>(
steps,
batch_size,
hidden_size,
workspace,
u,
b,
h,
h + NH,
0.0f,
nullptr);
}
} else {
if (zoneout_prob && zoneout_mask) {
IndrnnFwdOps<T, false, true><<<gridDim, blockDim, 0, stream>>>(
steps,
batch_size,
hidden_size,
workspace,
u,
b,
h,
h + NH,
zoneout_prob,
zoneout_mask);
} else {
IndrnnFwdOps<T, false, false><<<gridDim, blockDim, 0, stream>>>(
steps,
batch_size,
hidden_size,
workspace,
u,
b,
h,
h + NH,
0.0f,
nullptr);
}
}
cublasSetStream(blas_handle, save_stream);
}
template class ForwardPass<float>;
template class ForwardPass<double>;
} // namespace indrnn
} // namespace v0
} // namespace haste
| [
"sharvil.nanavati@gmail.com"
] | sharvil.nanavati@gmail.com |
33dec7675f7089fb4ad7dd5aed3f0064cf09a79e | 003946cd741b4f838715bd62b3b12bcf35021df1 | /wifibotIH/WIFIBOT8IH/mainwindow.cpp | ffc9070a21cc3abfd84f4aa6ddccad8781d10b57 | [] | no_license | ethanS06/wifibotf | b3d1aa22281cf10e8b866c62e51255d31b758629 | ccf08d264ae28b45336b3b34b8afec47d9058750 | refs/heads/main | 2023-05-31T19:00:34.315314 | 2021-06-17T15:01:59 | 2021-06-17T15:01:59 | 377,639,037 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,244 | cpp | #include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QObject>
#include <QWebEngineView>
//constructueurd de la mainwindow
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
this->setStyleSheet("background-color: grey;");
this->minot = new MyRobot(this); //instancie un robot dans la mainwindow
//this->minot->doConnect();
//this->minot->Stop();
view = new QWebEngineView(parent);
ui->gridLayout->addWidget(view);
//connect signal
connect(minot, SIGNAL(updateUI(QByteArray)), this, SLOT(update_Robot_Information()));
}
MainWindow::~MainWindow()
{
delete ui;
}
/*permet de gérer les entrées clavier pour effectuer des actions sur le robot
* a chaque touche pressez on effectue la suite d'instruction qui se trouve dans le case specifié
*/
void MainWindow::keyPressEvent(QKeyEvent *event)
{
QNetworkRequest request;
QNetworkAccessManager *manager = new QNetworkAccessManager();
switch(event->key() ){
case Qt :: Key_8 :
qDebug()<<"you pressed on 8";
this->minot->mouvement(150,150,80);
break;
case Qt :: Key_2 :
qDebug()<<"you pressed on 2";
this->minot->mouvement(150,150,0);
break;
case Qt :: Key_4 :
qDebug()<<"you pressed on 4";
this->minot->mouvement(150,150,16);
break;
case Qt :: Key_6 :
qDebug()<<"you pressed on 6";
this->minot->mouvement(150,150,64);
break;
case Qt :: Key_5 :
qDebug() << "you stopp the mouvement";
this->minot->Stop();
break;
case Qt :: Key_7 :
qDebug()<<"you pressed on 7";
this->minot->mouvement(100,150,80);
break;
case Qt :: Key_9 :
qDebug()<<"you pressed on 9";
this->minot->mouvement(150,100,80);
break;
case Qt :: Key_1 :
qDebug()<<"you pressed on 1";
this->minot->mouvement(100,150,00);
break;
case Qt :: Key_3 :
qDebug()<<"you pressed on 3";
this->minot->mouvement(150,100,00);
break;
case Qt :: Key_Alt :
qDebug() << "vous affichez la batterie en %" ;
this->minot->getBatteryPercent();
qDebug() <<"capteur avant IR gauche " <<(unsigned char) this->minot-> DataReceived[3];
qDebug() <<"capteur arriere IR gauche" <<(unsigned char)this->minot->DataReceived[12];
qDebug() <<"capteur avant IR droit" <<(unsigned char) this->minot-> DataReceived[11];
qDebug() <<"capteur arriere IR droite" <<(unsigned char)this->minot->DataReceived[4];
qDebug() <<"la vitesse gauche est de " << (unsigned char ) this->minot-> DataReceived[1];
qDebug() <<"la vitesse gauche est de " << (unsigned char ) this->minot-> DataReceived[10];
break;
case Qt :: Key_Z://camera vers le haut
request.setUrl(QUrl("http://192.168.1.106:8080/?action=command&dest=0&plugin=0&id=10094853&group=1&value=-255"));
manager->get(request);
break;
case Qt :: Key_D://camera vers la droite
request.setUrl(QUrl("http://192.168.1.106:8080/?action=command&dest=0&plugin=0&id=10094852&group=1&value=-255"));
manager->get(request);
break;
case Qt :: Key_S://camera vers le bas
request.setUrl(QUrl("http://192.168.1.106:8080/?action=command&dest=0&plugin=0&id=10094853&group=1&value=255"));
manager->get(request);
break;
case Qt :: Key_Q://camera vers la gauche
request.setUrl(QUrl("http://192.168.1.106:8080/?action=command&dest=0&plugin=0&id=10094852&group=1&value=255"));
manager->get(request);
break;
}
}
//permet de gérer le relachement des touches du clavier et ainsi permettre de controler le mouvement du robot par simple pression
void MainWindow::keyReleaseEvent(QKeyEvent *event)
{
switch(event->key() ){
case Qt :: Key_8 :
qDebug()<<"you stopped press on 8";
this->minot->Stop();
break;
case Qt :: Key_2:
qDebug()<<"you stopped press on 2";
this->minot->Stop();
break;
case Qt :: Key_6:
qDebug()<<"you stopped press on 6";
this->minot->Stop();
break;
case Qt :: Key_4:
qDebug()<<"you stopped press on 4";
this->minot->Stop();
break;
case Qt :: Key_7 :
qDebug()<<"you stopped press on 7";
this->minot->Stop();
break;
case Qt :: Key_9:
qDebug()<<"you stopped press on 9";
this->minot->Stop();
break;
case Qt :: Key_1:
qDebug()<<"you stopped press on 1";
this->minot->Stop();
break;
case Qt :: Key_3:
qDebug()<<"you stopped press on 3";
this->minot->Stop();
break;
}
}
//conexion au robot
void MainWindow::on_pushButton_3_clicked()
{
this->minot->doConnect();
minot->connected();
qDebug() << "you are connected" ;
}
//deconnexion au robot
void MainWindow::on_deconnection_clicked()
{
if(this->minot->doConnect2()){
this->minot->disConnect();
this-> minot->disconnected();
}
else
qDebug() <<"you cant disconnect to the robot for the moment";
}
//les fonctions suivante permette de gerer le mouvement du robot à la souris {
void MainWindow::on_Avancer_3_clicked()
{
qDebug() << "hey you dumbass" ;
}
void MainWindow::on_Avancer_3_pressed()
{
this->minot->mouvement(150,150,80);
}
void MainWindow::on_Avancer_3_released()
{
this->minot->Stop();
}
void MainWindow::on_Droite_3_pressed()
{
this->minot->mouvement(150,150,64);
}
void MainWindow::on_Droite_3_released()
{
this->minot->Stop();
}
void MainWindow::on_Reculer_3_pressed()
{
this->minot->mouvement(150,150,00);
}
void MainWindow::on_Reculer_3_released()
{
this->minot->Stop();
}
void MainWindow::on_Gauche_3_pressed()
{
this->minot->mouvement(150,150,16);
}
void MainWindow::on_Gauche_3_released()
{
this->minot->Stop();
}
void MainWindow::on_Droite_5_pressed()//deplacement robot avant-gauche
{
this->minot->mouvement(100,150,80);
}
void MainWindow::on_Droite_5_released()
{
this->minot->Stop();
}
void MainWindow::on_Droite_4_pressed()//deplacement robot avant-droite
{
this->minot->mouvement(150,100,80);
}
void MainWindow::on_Droite_4_released()
{
this->minot->Stop();
}
void MainWindow::on_Droite_6_pressed() //deplacement arriere-gauche
{
this->minot->mouvement(100,150,00);
}
void MainWindow::on_Droite_6_released()
{
this->minot->Stop();
}
void MainWindow::on_Droite_7_pressed() //deplacement arriere_droite
{
this->minot->mouvement(150,100,00);
}
void MainWindow::on_Droite_7_released()
{
this->minot->Stop();
}
// }
//move la camera vers le haut
void MainWindow::on_pushButton_clicked()
{
QNetworkRequest request;
request.setUrl(QUrl("http://192.168.1.106:8080/?action=command&dest=0&plugin=0&id=10094853&group=1&value=-255"));
QNetworkAccessManager *manager = new QNetworkAccessManager();
manager->get(request);
}
//move la camera vers la droite
void MainWindow::on_pushButton_4_clicked()
{
QNetworkRequest request;
request.setUrl(QUrl("http://192.168.1.106:8080/?action=command&dest=0&plugin=0&id=10094852&group=1&value=-255"));
QNetworkAccessManager *manager = new QNetworkAccessManager();
manager->get(request);
}
//mouv la caméra vers le bas
void MainWindow::on_pushButton_5_clicked()
{
QNetworkRequest request;
request.setUrl(QUrl("http://192.168.1.106:8080/?action=command&dest=0&plugin=0&id=10094853&group=1&value=255"));
QNetworkAccessManager *manager = new QNetworkAccessManager();
manager->get(request);
}
//mouv la camera vers la gauche
void MainWindow::on_pushButton_2_clicked()
{
QNetworkRequest request;
request.setUrl(QUrl("http://192.168.1.106:8080/?action=command&dest=0&plugin=0&id=10094852&group=1&value=255"));
QNetworkAccessManager *manager = new QNetworkAccessManager();
manager->get(request);
}
void MainWindow::on_pushButton_6_clicked()
{
view->load(QUrl("http://192.168.1.106:8080/?action=stream"));
view->show();
}
| [
"noreply@github.com"
] | ethanS06.noreply@github.com |
4d9fab3c0896b688475c2a057c130b38018a5838 | 2c7e90851722a92a6b321935c09a6e3f6650adb4 | /TabuSearch_for_TSP/AreaOfSolutions.cpp | f4d509696cd869eeaf3a24e3215f6b81274172c8 | [] | no_license | czarny247/ts-for-tsp | f68dd0f88a344e43b4000c8766dc49ba429d681b | b9f40723ea3a099499c7f4bc9c6c87f22b09ce8b | refs/heads/master | 2021-01-10T12:41:53.097427 | 2016-02-03T10:49:19 | 2016-02-03T10:49:19 | 50,418,228 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 209 | cpp | #include "AreaOfSolutions.h"
AreaOfSolutions::AreaOfSolutions()
{
}
void AreaOfSolutions::addSolution(Solution sol)
{
sSolutions.insert(&sol);
}
Solution AreaOfSolutions::getSolution(int position)
{
}
| [
"mateusz.hercun@gmail.com"
] | mateusz.hercun@gmail.com |
f524659e1a87b22561c381e1dbd213c38633f68c | 21ff46d8b8cfe1efd0722950e44076cbe2c803e5 | /glipf/include/glipf/sources/frame-source.h | 8fd37a272ab1167a74796ebdf89eb9d2d6701439 | [
"BSD-2-Clause"
] | permissive | cognitivesystems/smartcamera | 6ec5839f30a34ecd5e5e03bb430b842c73aa6f55 | 5374193260e6385becfe8086a70d21d650314beb | refs/heads/master | 2021-01-18T06:35:21.332981 | 2017-03-08T06:50:07 | 2017-03-08T06:50:07 | 84,283,927 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,288 | h | #ifndef sources_frame_source_h
#define sources_frame_source_h
#include "frame-properties.h"
#include <cstdint>
#include <stdexcept>
namespace glipf {
namespace sources {
/// Exception raised when a frame source fails to initialise.
class FrameSourceInitializationError : public std::runtime_error {
public:
using std::runtime_error::runtime_error;
};
/// Abstract base class defining the common API of all frame sources.
class FrameSource {
public:
virtual ~FrameSource() {};
/// Return the properties of frames produced by the frame source.
virtual const FrameProperties& getFrameProperties() const = 0;
/**
* Capture a frame and return its data.
*
* \note The number of bytes returned depends on the properties of the
* frame (as reported by @ref getFrameProperties) and can be
* calculated as follows:
* ~~~
* // frameSource is an instance of a concrete subclass of FrameSource
* std::pair<size_t, size_t> frameDimensions = frameSource.getFrameProperties.dimensions();
* size_t pixelCount = frameDimensions.first * frameDimensions.second;
* size_t byteCount = pixelCount * 3;
* ~~~
*/
virtual const uint8_t* grabFrame() = 0;
};
} // end namespace sources
} // end namespace glipf
#endif // sources_frame_source_h
| [
"surajnair1@gmail.com"
] | surajnair1@gmail.com |
50db7255c9c18f6b2ec05c24dbb716dab5dc0d07 | 3fbe1e13c6171a82416b29a82645832b4228c0e7 | /Source/UnderTheCouch/Player/PlayerNCamera.h | 6545d67714151a8a26be17d72a6a0c714e6f5fbd | [
"MIT"
] | permissive | codarth/UnderTheCouch | 4280727cd444157861c8b833ae5a5e5ac4f06fc4 | 896aea463cdfa98c846de999c66635ee79900abd | refs/heads/master | 2020-09-06T09:01:08.724348 | 2019-11-22T02:31:03 | 2019-11-22T02:31:03 | 220,380,896 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,829 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Pawn.h"
#include "PlayerNCamera.generated.h"
UCLASS()
class UNDERTHECOUCH_API APlayerNCamera : public APawn
{
GENERATED_BODY()
public:
// Sets default values for this pawn's properties
APlayerNCamera();
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
// Called to bind functionality to input
virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;
UPROPERTY(VisibleAnywhere, Category = Camera)
class USpringArmComponent* SpringArm;
class UCameraComponent* Camera;
UPROPERTY(VisibleAnywhere, Category = Display)
class UStaticMeshComponent* Mesh; // TODO: Don't really need a mesh
UPROPERTY(VisibleAnywhere, Category = Camera)
float TargetArmLength = 1000.0f;
UPROPERTY(VisibleAnywhere, Category = Camera)
bool bCameraLag = true;
UPROPERTY(VisibleAnywhere, Category = Camera)
float CameraLagSpeed = 5.0f;
UPROPERTY(VisibleAnywhere, Category = Movement)
float MovementScaler = 400.0f;
UPROPERTY(VisibleAnywhere, Category = Movement)
float ZoomMin = 50.0f;
UPROPERTY(VisibleAnywhere, Category = Movement)
float ZoomMax = 5000.0f;
UPROPERTY(VisibleAnywhere, Category = Movement)
float ZoomFactor = 50.0f;
// TODO: Remove UPROPERTY where not needed
private:
void MoveForward(float Value);
void MoveRight(float Value);
void CameraPan(float Value);
void CameraTilt(float Value);
void EnableRotate();
void DisableRotate();
void Zoom(float Value);
FVector2D MovementInput;
FRotator RotateInput;
bool b_RotateEnabled;
float PitchMin = -80.0f;
float PitchMax = -15.0f;
};
| [
"zimquo@gmail.com"
] | zimquo@gmail.com |
9676ac8495117e86a554b51a2183000b1cfa4933 | c6d9feead8cdf2cd0e489fdf406db5bdcd34469e | /Orange/src/Orange/Renderer/RenderCommand.cpp | c8f0dd1cb6169a180e06b3b9b23ce1d058fae5c3 | [
"Apache-2.0"
] | permissive | christianwaldmann/Orange | ca96f3e5e68dbf98ab9b821cf02651b60fea980e | 2f8ef0fe6a310e45e984733bdab65de9c31ca1a0 | refs/heads/master | 2023-03-09T14:32:13.075008 | 2021-03-01T11:57:15 | 2021-03-01T11:57:15 | 323,442,645 | 0 | 0 | Apache-2.0 | 2021-03-01T11:57:16 | 2020-12-21T20:38:19 | C++ | UTF-8 | C++ | false | false | 187 | cpp | #include "ogpch.h"
#include "RenderCommand.h"
#include "Platform/OpenGL/OpenGLRendererAPI.h"
namespace Orange {
RendererAPI* RenderCommand::s_RendererAPI = new OpenGLRendererAPI;
}
| [
"waldmann-christian@web.de"
] | waldmann-christian@web.de |
535925ac8d2b200c4ecdc09c255479f521637066 | fb7efe44f4d9f30d623f880d0eb620f3a81f0fbd | /chrome/browser/sync_file_system/local/local_file_change_tracker.cc | b8a8b232d206b51fa01b097b604754b22e5f5600 | [
"BSD-3-Clause"
] | permissive | wzyy2/chromium-browser | 2644b0daf58f8b3caee8a6c09a2b448b2dfe059c | eb905f00a0f7e141e8d6c89be8fb26192a88c4b7 | refs/heads/master | 2022-11-23T20:25:08.120045 | 2018-01-16T06:41:26 | 2018-01-16T06:41:26 | 117,618,467 | 3 | 2 | BSD-3-Clause | 2022-11-20T22:03:57 | 2018-01-16T02:09:10 | null | UTF-8 | C++ | false | false | 21,320 | cc | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/sync_file_system/local/local_file_change_tracker.h"
#include <stddef.h>
#include <utility>
#include "base/containers/circular_deque.h"
#include "base/containers/queue.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/macros.h"
#include "base/metrics/histogram_macros.h"
#include "base/sequenced_task_runner.h"
#include "base/stl_util.h"
#include "chrome/browser/sync_file_system/local/local_file_sync_status.h"
#include "chrome/browser/sync_file_system/syncable_file_system_util.h"
#include "storage/browser/fileapi/file_system_context.h"
#include "storage/browser/fileapi/file_system_file_util.h"
#include "storage/browser/fileapi/file_system_operation_context.h"
#include "storage/common/fileapi/file_system_util.h"
#include "third_party/leveldatabase/env_chromium.h"
#include "third_party/leveldatabase/src/include/leveldb/db.h"
#include "third_party/leveldatabase/src/include/leveldb/write_batch.h"
using storage::FileSystemContext;
using storage::FileSystemFileUtil;
using storage::FileSystemOperationContext;
using storage::FileSystemURL;
using storage::FileSystemURLSet;
namespace sync_file_system {
namespace {
const base::FilePath::CharType kDatabaseName[] =
FILE_PATH_LITERAL("LocalFileChangeTracker");
const char kMark[] = "d";
} // namespace
// A database class that stores local file changes in a local database. This
// object must be destructed on file_task_runner.
class LocalFileChangeTracker::TrackerDB {
public:
TrackerDB(const base::FilePath& base_path,
leveldb::Env* env_override);
SyncStatusCode MarkDirty(const std::string& url);
SyncStatusCode ClearDirty(const std::string& url);
SyncStatusCode GetDirtyEntries(base::queue<FileSystemURL>* dirty_files);
SyncStatusCode WriteBatch(std::unique_ptr<leveldb::WriteBatch> batch);
private:
enum RecoveryOption {
REPAIR_ON_CORRUPTION,
FAIL_ON_CORRUPTION,
};
SyncStatusCode Init(RecoveryOption recovery_option);
SyncStatusCode Repair(const std::string& db_path);
void HandleError(const base::Location& from_here,
const leveldb::Status& status);
const base::FilePath base_path_;
leveldb::Env* env_override_;
std::unique_ptr<leveldb::DB> db_;
SyncStatusCode db_status_;
DISALLOW_COPY_AND_ASSIGN(TrackerDB);
};
LocalFileChangeTracker::ChangeInfo::ChangeInfo() : change_seq(-1) {}
LocalFileChangeTracker::ChangeInfo::~ChangeInfo() {}
// LocalFileChangeTracker ------------------------------------------------------
LocalFileChangeTracker::LocalFileChangeTracker(
const base::FilePath& base_path,
leveldb::Env* env_override,
base::SequencedTaskRunner* file_task_runner)
: initialized_(false),
file_task_runner_(file_task_runner),
tracker_db_(new TrackerDB(base_path, env_override)),
current_change_seq_number_(0),
num_changes_(0) {
}
LocalFileChangeTracker::~LocalFileChangeTracker() {
DCHECK(file_task_runner_->RunsTasksInCurrentSequence());
tracker_db_.reset();
}
void LocalFileChangeTracker::OnStartUpdate(const FileSystemURL& url) {
DCHECK(file_task_runner_->RunsTasksInCurrentSequence());
if (base::ContainsKey(changes_, url) ||
base::ContainsKey(demoted_changes_, url)) {
return;
}
// TODO(nhiroki): propagate the error code (see http://crbug.com/152127).
MarkDirtyOnDatabase(url);
}
void LocalFileChangeTracker::OnEndUpdate(const FileSystemURL& url) {}
void LocalFileChangeTracker::OnCreateFile(const FileSystemURL& url) {
RecordChange(url, FileChange(FileChange::FILE_CHANGE_ADD_OR_UPDATE,
SYNC_FILE_TYPE_FILE));
}
void LocalFileChangeTracker::OnCreateFileFrom(const FileSystemURL& url,
const FileSystemURL& src) {
RecordChange(url, FileChange(FileChange::FILE_CHANGE_ADD_OR_UPDATE,
SYNC_FILE_TYPE_FILE));
}
void LocalFileChangeTracker::OnRemoveFile(const FileSystemURL& url) {
RecordChange(url, FileChange(FileChange::FILE_CHANGE_DELETE,
SYNC_FILE_TYPE_FILE));
}
void LocalFileChangeTracker::OnModifyFile(const FileSystemURL& url) {
RecordChange(url, FileChange(FileChange::FILE_CHANGE_ADD_OR_UPDATE,
SYNC_FILE_TYPE_FILE));
}
void LocalFileChangeTracker::OnCreateDirectory(const FileSystemURL& url) {
RecordChange(url, FileChange(FileChange::FILE_CHANGE_ADD_OR_UPDATE,
SYNC_FILE_TYPE_DIRECTORY));
}
void LocalFileChangeTracker::OnRemoveDirectory(const FileSystemURL& url) {
RecordChange(url, FileChange(FileChange::FILE_CHANGE_DELETE,
SYNC_FILE_TYPE_DIRECTORY));
}
void LocalFileChangeTracker::GetNextChangedURLs(
base::circular_deque<FileSystemURL>* urls,
int max_urls) {
DCHECK(file_task_runner_->RunsTasksInCurrentSequence());
DCHECK(urls);
urls->clear();
// Mildly prioritizes the URLs that older changes and have not been updated
// for a while.
for (ChangeSeqMap::iterator iter = change_seqs_.begin();
iter != change_seqs_.end() &&
(max_urls == 0 || urls->size() < static_cast<size_t>(max_urls));
++iter) {
urls->push_back(iter->second);
}
}
void LocalFileChangeTracker::GetChangesForURL(
const FileSystemURL& url, FileChangeList* changes) {
DCHECK(file_task_runner_->RunsTasksInCurrentSequence());
DCHECK(changes);
changes->clear();
FileChangeMap::iterator found = changes_.find(url);
if (found == changes_.end()) {
found = demoted_changes_.find(url);
if (found == demoted_changes_.end())
return;
}
*changes = found->second.change_list;
}
void LocalFileChangeTracker::ClearChangesForURL(const FileSystemURL& url) {
DCHECK(file_task_runner_->RunsTasksInCurrentSequence());
ClearDirtyOnDatabase(url);
mirror_changes_.erase(url);
demoted_changes_.erase(url);
FileChangeMap::iterator found = changes_.find(url);
if (found == changes_.end())
return;
change_seqs_.erase(found->second.change_seq);
changes_.erase(found);
UpdateNumChanges();
}
void LocalFileChangeTracker::CreateFreshMirrorForURL(
const storage::FileSystemURL& url) {
DCHECK(file_task_runner_->RunsTasksInCurrentSequence());
DCHECK(!base::ContainsKey(mirror_changes_, url));
mirror_changes_[url] = ChangeInfo();
}
void LocalFileChangeTracker::RemoveMirrorAndCommitChangesForURL(
const storage::FileSystemURL& url) {
DCHECK(file_task_runner_->RunsTasksInCurrentSequence());
FileChangeMap::iterator found = mirror_changes_.find(url);
if (found == mirror_changes_.end())
return;
mirror_changes_.erase(found);
if (base::ContainsKey(changes_, url) ||
base::ContainsKey(demoted_changes_, url)) {
MarkDirtyOnDatabase(url);
} else {
ClearDirtyOnDatabase(url);
}
UpdateNumChanges();
}
void LocalFileChangeTracker::ResetToMirrorAndCommitChangesForURL(
const storage::FileSystemURL& url) {
DCHECK(file_task_runner_->RunsTasksInCurrentSequence());
FileChangeMap::iterator found = mirror_changes_.find(url);
if (found == mirror_changes_.end() || found->second.change_list.empty()) {
ClearChangesForURL(url);
return;
}
const ChangeInfo& info = found->second;
if (base::ContainsKey(demoted_changes_, url)) {
DCHECK(!base::ContainsKey(changes_, url));
demoted_changes_[url] = info;
} else {
DCHECK(!base::ContainsKey(demoted_changes_, url));
change_seqs_[info.change_seq] = url;
changes_[url] = info;
}
RemoveMirrorAndCommitChangesForURL(url);
}
void LocalFileChangeTracker::DemoteChangesForURL(
const storage::FileSystemURL& url) {
DCHECK(file_task_runner_->RunsTasksInCurrentSequence());
FileChangeMap::iterator found = changes_.find(url);
if (found == changes_.end())
return;
DCHECK(!base::ContainsKey(demoted_changes_, url));
change_seqs_.erase(found->second.change_seq);
demoted_changes_.insert(*found);
changes_.erase(found);
UpdateNumChanges();
}
void LocalFileChangeTracker::PromoteDemotedChangesForURL(
const storage::FileSystemURL& url) {
DCHECK(file_task_runner_->RunsTasksInCurrentSequence());
FileChangeMap::iterator iter = demoted_changes_.find(url);
if (iter == demoted_changes_.end())
return;
FileChangeList::List change_list = iter->second.change_list.list();
// Make sure that this URL is in no queues.
DCHECK(!base::ContainsKey(change_seqs_, iter->second.change_seq));
DCHECK(!base::ContainsKey(changes_, url));
change_seqs_[iter->second.change_seq] = url;
changes_.insert(*iter);
demoted_changes_.erase(iter);
UpdateNumChanges();
}
bool LocalFileChangeTracker::PromoteDemotedChanges() {
DCHECK(file_task_runner_->RunsTasksInCurrentSequence());
if (demoted_changes_.empty())
return false;
while (!demoted_changes_.empty()) {
storage::FileSystemURL url = demoted_changes_.begin()->first;
PromoteDemotedChangesForURL(url);
}
UpdateNumChanges();
return true;
}
SyncStatusCode LocalFileChangeTracker::Initialize(
FileSystemContext* file_system_context) {
DCHECK(file_task_runner_->RunsTasksInCurrentSequence());
DCHECK(!initialized_);
DCHECK(file_system_context);
SyncStatusCode status = CollectLastDirtyChanges(file_system_context);
if (status == SYNC_STATUS_OK)
initialized_ = true;
return status;
}
void LocalFileChangeTracker::ResetForFileSystem(const GURL& origin,
storage::FileSystemType type) {
DCHECK(file_task_runner_->RunsTasksInCurrentSequence());
std::unique_ptr<leveldb::WriteBatch> batch(new leveldb::WriteBatch);
for (FileChangeMap::iterator iter = changes_.begin();
iter != changes_.end();) {
storage::FileSystemURL url = iter->first;
int change_seq = iter->second.change_seq;
// Advance |iter| before calling ResetForURL to avoid the iterator
// invalidation in it.
++iter;
if (url.origin() == origin && url.type() == type)
ResetForURL(url, change_seq, batch.get());
}
for (FileChangeMap::iterator iter = demoted_changes_.begin();
iter != demoted_changes_.end();) {
storage::FileSystemURL url = iter->first;
int change_seq = iter->second.change_seq;
// Advance |iter| before calling ResetForURL to avoid the iterator
// invalidation in it.
++iter;
if (url.origin() == origin && url.type() == type)
ResetForURL(url, change_seq, batch.get());
}
// Fail to apply batch to database wouldn't have critical effect, they'll be
// just marked deleted on next relaunch.
tracker_db_->WriteBatch(std::move(batch));
UpdateNumChanges();
}
void LocalFileChangeTracker::UpdateNumChanges() {
base::AutoLock lock(num_changes_lock_);
num_changes_ = static_cast<int64_t>(change_seqs_.size());
}
void LocalFileChangeTracker::GetAllChangedURLs(FileSystemURLSet* urls) {
DCHECK(file_task_runner_->RunsTasksInCurrentSequence());
base::circular_deque<FileSystemURL> url_deque;
GetNextChangedURLs(&url_deque, 0);
urls->clear();
urls->insert(url_deque.begin(), url_deque.end());
}
void LocalFileChangeTracker::DropAllChanges() {
DCHECK(file_task_runner_->RunsTasksInCurrentSequence());
changes_.clear();
change_seqs_.clear();
mirror_changes_.clear();
UpdateNumChanges();
}
SyncStatusCode LocalFileChangeTracker::MarkDirtyOnDatabase(
const FileSystemURL& url) {
std::string serialized_url;
if (!SerializeSyncableFileSystemURL(url, &serialized_url))
return SYNC_FILE_ERROR_INVALID_URL;
return tracker_db_->MarkDirty(serialized_url);
}
SyncStatusCode LocalFileChangeTracker::ClearDirtyOnDatabase(
const FileSystemURL& url) {
DCHECK(file_task_runner_->RunsTasksInCurrentSequence());
std::string serialized_url;
if (!SerializeSyncableFileSystemURL(url, &serialized_url))
return SYNC_FILE_ERROR_INVALID_URL;
return tracker_db_->ClearDirty(serialized_url);
}
SyncStatusCode LocalFileChangeTracker::CollectLastDirtyChanges(
FileSystemContext* file_system_context) {
DCHECK(file_task_runner_->RunsTasksInCurrentSequence());
base::queue<FileSystemURL> dirty_files;
const SyncStatusCode status = tracker_db_->GetDirtyEntries(&dirty_files);
if (status != SYNC_STATUS_OK)
return status;
FileSystemFileUtil* file_util =
file_system_context->sandbox_delegate()->sync_file_util();
DCHECK(file_util);
std::unique_ptr<FileSystemOperationContext> context(
new FileSystemOperationContext(file_system_context));
base::File::Info file_info;
base::FilePath platform_path;
while (!dirty_files.empty()) {
const FileSystemURL url = dirty_files.front();
dirty_files.pop();
DCHECK_EQ(url.type(), storage::kFileSystemTypeSyncable);
switch (file_util->GetFileInfo(context.get(), url,
&file_info, &platform_path)) {
case base::File::FILE_OK: {
if (!file_info.is_directory) {
RecordChange(url, FileChange(FileChange::FILE_CHANGE_ADD_OR_UPDATE,
SYNC_FILE_TYPE_FILE));
break;
}
RecordChange(url, FileChange(
FileChange::FILE_CHANGE_ADD_OR_UPDATE,
SYNC_FILE_TYPE_DIRECTORY));
// Push files and directories in this directory into |dirty_files|.
std::unique_ptr<FileSystemFileUtil::AbstractFileEnumerator> enumerator(
file_util->CreateFileEnumerator(context.get(), url));
base::FilePath path_each;
while (!(path_each = enumerator->Next()).empty()) {
dirty_files.push(CreateSyncableFileSystemURL(
url.origin(), path_each));
}
break;
}
case base::File::FILE_ERROR_NOT_FOUND: {
// File represented by |url| has already been deleted. Since we cannot
// figure out if this file was directory or not from the URL, file
// type is treated as SYNC_FILE_TYPE_UNKNOWN.
//
// NOTE: Directory to have been reverted (that is, ADD -> DELETE) is
// also treated as FILE_CHANGE_DELETE.
RecordChange(url, FileChange(FileChange::FILE_CHANGE_DELETE,
SYNC_FILE_TYPE_UNKNOWN));
break;
}
case base::File::FILE_ERROR_FAILED:
default:
// TODO(nhiroki): handle file access error (http://crbug.com/155251).
LOG(WARNING) << "Failed to access local file.";
break;
}
}
return SYNC_STATUS_OK;
}
void LocalFileChangeTracker::RecordChange(
const FileSystemURL& url, const FileChange& change) {
DCHECK(file_task_runner_->RunsTasksInCurrentSequence());
int change_seq = current_change_seq_number_++;
if (base::ContainsKey(demoted_changes_, url)) {
RecordChangeToChangeMaps(url, change, change_seq,
&demoted_changes_, nullptr);
} else {
RecordChangeToChangeMaps(url, change, change_seq, &changes_, &change_seqs_);
}
if (base::ContainsKey(mirror_changes_, url)) {
RecordChangeToChangeMaps(url, change, change_seq, &mirror_changes_,
nullptr);
}
UpdateNumChanges();
}
// static
void LocalFileChangeTracker::RecordChangeToChangeMaps(
const FileSystemURL& url,
const FileChange& change,
int new_change_seq,
FileChangeMap* changes,
ChangeSeqMap* change_seqs) {
ChangeInfo& info = (*changes)[url];
if (info.change_seq >= 0 && change_seqs)
change_seqs->erase(info.change_seq);
info.change_list.Update(change);
if (info.change_list.empty()) {
changes->erase(url);
return;
}
info.change_seq = new_change_seq;
if (change_seqs)
(*change_seqs)[info.change_seq] = url;
}
void LocalFileChangeTracker::ResetForURL(const storage::FileSystemURL& url,
int change_seq,
leveldb::WriteBatch* batch) {
mirror_changes_.erase(url);
demoted_changes_.erase(url);
change_seqs_.erase(change_seq);
changes_.erase(url);
std::string serialized_url;
if (!SerializeSyncableFileSystemURL(url, &serialized_url)) {
NOTREACHED() << "Failed to serialize: " << url.DebugString();
return;
}
batch->Delete(serialized_url);
}
// TrackerDB -------------------------------------------------------------------
LocalFileChangeTracker::TrackerDB::TrackerDB(const base::FilePath& base_path,
leveldb::Env* env_override)
: base_path_(base_path),
env_override_(env_override),
db_status_(SYNC_STATUS_OK) {}
SyncStatusCode LocalFileChangeTracker::TrackerDB::Init(
RecoveryOption recovery_option) {
if (db_.get() && db_status_ == SYNC_STATUS_OK)
return SYNC_STATUS_OK;
std::string path =
storage::FilePathToString(base_path_.Append(kDatabaseName));
leveldb_env::Options options;
options.max_open_files = 0; // Use minimum.
options.create_if_missing = true;
if (env_override_)
options.env = env_override_;
leveldb::Status status = leveldb_env::OpenDB(options, path, &db_);
UMA_HISTOGRAM_ENUMERATION("SyncFileSystem.TrackerDB.Open",
leveldb_env::GetLevelDBStatusUMAValue(status),
leveldb_env::LEVELDB_STATUS_MAX);
if (status.ok()) {
return SYNC_STATUS_OK;
}
HandleError(FROM_HERE, status);
if (!status.IsCorruption())
return LevelDBStatusToSyncStatusCode(status);
// Try to repair the corrupted DB.
switch (recovery_option) {
case FAIL_ON_CORRUPTION:
return SYNC_DATABASE_ERROR_CORRUPTION;
case REPAIR_ON_CORRUPTION:
return Repair(path);
}
NOTREACHED();
return SYNC_DATABASE_ERROR_FAILED;
}
SyncStatusCode LocalFileChangeTracker::TrackerDB::Repair(
const std::string& db_path) {
DCHECK(!db_.get());
LOG(WARNING) << "Attempting to repair TrackerDB.";
leveldb_env::Options options;
options.reuse_logs = false; // Compact log file if repairing.
options.max_open_files = 0; // Use minimum.
if (leveldb::RepairDB(db_path, options).ok() &&
Init(FAIL_ON_CORRUPTION) == SYNC_STATUS_OK) {
// TODO(nhiroki): perform some consistency checks between TrackerDB and
// syncable file system.
LOG(WARNING) << "Repairing TrackerDB completed.";
return SYNC_STATUS_OK;
}
LOG(WARNING) << "Failed to repair TrackerDB.";
return SYNC_DATABASE_ERROR_CORRUPTION;
}
// TODO(nhiroki): factor out the common methods into somewhere else.
void LocalFileChangeTracker::TrackerDB::HandleError(
const base::Location& from_here,
const leveldb::Status& status) {
LOG(ERROR) << "LocalFileChangeTracker::TrackerDB failed at: "
<< from_here.ToString() << " with error: " << status.ToString();
}
SyncStatusCode LocalFileChangeTracker::TrackerDB::MarkDirty(
const std::string& url) {
if (db_status_ != SYNC_STATUS_OK)
return db_status_;
db_status_ = Init(REPAIR_ON_CORRUPTION);
if (db_status_ != SYNC_STATUS_OK) {
db_.reset();
return db_status_;
}
leveldb::Status status = db_->Put(leveldb::WriteOptions(), url, kMark);
if (!status.ok()) {
HandleError(FROM_HERE, status);
db_status_ = LevelDBStatusToSyncStatusCode(status);
db_.reset();
return db_status_;
}
return SYNC_STATUS_OK;
}
SyncStatusCode LocalFileChangeTracker::TrackerDB::ClearDirty(
const std::string& url) {
if (db_status_ != SYNC_STATUS_OK)
return db_status_;
// Should not reach here before initializing the database. The database should
// be cleared after read, and should be initialized during read if
// uninitialized.
DCHECK(db_.get());
leveldb::Status status = db_->Delete(leveldb::WriteOptions(), url);
if (!status.ok() && !status.IsNotFound()) {
HandleError(FROM_HERE, status);
db_status_ = LevelDBStatusToSyncStatusCode(status);
db_.reset();
return db_status_;
}
return SYNC_STATUS_OK;
}
SyncStatusCode LocalFileChangeTracker::TrackerDB::GetDirtyEntries(
base::queue<FileSystemURL>* dirty_files) {
if (db_status_ != SYNC_STATUS_OK)
return db_status_;
db_status_ = Init(REPAIR_ON_CORRUPTION);
if (db_status_ != SYNC_STATUS_OK) {
db_.reset();
return db_status_;
}
std::unique_ptr<leveldb::Iterator> iter(
db_->NewIterator(leveldb::ReadOptions()));
iter->SeekToFirst();
FileSystemURL url;
while (iter->Valid()) {
if (!DeserializeSyncableFileSystemURL(iter->key().ToString(), &url)) {
LOG(WARNING) << "Failed to deserialize an URL. "
<< "TrackerDB might be corrupted.";
db_status_ = SYNC_DATABASE_ERROR_CORRUPTION;
iter.reset(); // Must delete before closing the database.
db_.reset();
return db_status_;
}
dirty_files->push(url);
iter->Next();
}
return SYNC_STATUS_OK;
}
SyncStatusCode LocalFileChangeTracker::TrackerDB::WriteBatch(
std::unique_ptr<leveldb::WriteBatch> batch) {
if (db_status_ != SYNC_STATUS_OK)
return db_status_;
leveldb::Status status = db_->Write(leveldb::WriteOptions(), batch.get());
if (!status.ok() && !status.IsNotFound()) {
HandleError(FROM_HERE, status);
db_status_ = LevelDBStatusToSyncStatusCode(status);
db_.reset();
return db_status_;
}
return SYNC_STATUS_OK;
}
} // namespace sync_file_system
| [
"jacob-chen@iotwrt.com"
] | jacob-chen@iotwrt.com |
80390b3d1bbc8cbfc0c3fd55f5f9f6e7652b527d | c0caed81b5b3e1498cbca4c1627513c456908e38 | /src/protocols/membrane/SetMembranePositionMover.hh | 1fd5646f575f7c7c76293bae02e98ef31b84af45 | [] | no_license | malaifa/source | 5b34ac0a4e7777265b291fc824da8837ecc3ee84 | fc0af245885de0fb82e0a1144422796a6674aeae | refs/heads/master | 2021-01-19T22:10:22.942155 | 2017-04-19T14:13:07 | 2017-04-19T14:13:07 | 88,761,668 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 7,028 | hh | // -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*-
// vi: set ts=2 noet:
//
// (c) Copyright Rosetta Commons Member Institutions.
// (c) This file is part of the Rosetta software suite and is made available under license.
// (c) The Rosetta software is developed by the contributing members of the Rosetta Commons.
// (c) For more information, see http://www.rosettacommons.org. Questions about this can be
// (c) addressed to University of Washington UW TechTransfer, email: license@u.washington.edu.
/// @file protocols/membrane/SetMembranePositionMover.hh
///
/// @brief Sets the membrane position normal and center
/// @details Sets the membrane position normal and center
/// CAUTION: ONLY FOR FLEXIBLE MEMBRANE AND FIXED PROTEIN!!!
/// Last Modified: 6/28/14
///
/// @author Rebecca Alford (rfalford12@gmail.com)
#ifndef INCLUDED_protocols_membrane_SetMembranePositionMover_hh
#define INCLUDED_protocols_membrane_SetMembranePositionMover_hh
// Unit Headers
#include <protocols/membrane/SetMembranePositionMover.fwd.hh>
// Project Headers
#include <protocols/moves/Mover.hh>
#include <protocols/simple_moves/UniformPositionMover.hh>
// Package Headers
#include <core/pose/Pose.fwd.hh>
#include <core/types.hh>
// Utility Headers
#include <numeric/xyzVector.hh>
namespace protocols {
namespace membrane {
/// @brief Membrane Position Translation-Rotation Mover
class SetMembranePositionMover : public protocols::moves::Mover {
public:
////////////////////
/// Constructors ///
////////////////////
/// @brief Construct a Default Membrane Position Mover
SetMembranePositionMover();
/// @brief Custom Constructor
/// @details Specify a new membrane center and normal
/// to move this position to
SetMembranePositionMover( core::Vector center, core::Vector normal );
/// @brief Copy Constructor
/// @details Make a deep copy of this mover object
SetMembranePositionMover( SetMembranePositionMover const & src );
/// @brief Assignment Operator
/// @details Make a deep copy of this mover object, overriding the assignment operator
SetMembranePositionMover &
operator=( SetMembranePositionMover const & src );
/// @brief Destructor
~SetMembranePositionMover();
/////////////////////
/// Mover Methods ///
/////////////////////
/// @brief Get the name of this mover
virtual std::string get_name() const;
/// @brief Apply Rotation/Translation to Membrane
/// @brief Translate the membrane position in this pose
/// to the new center position, and rotate to new normal
virtual void apply( core::pose::Pose & pose );
///////////////////////////////
/// Rosetta Scripts Methods ///
///////////////////////////////
/// @brief Create a Clone of this mover
virtual protocols::moves::MoverOP clone() const;
/// @brief Create a Fresh Instance of this Mover
virtual protocols::moves::MoverOP fresh_instance() const;
/// @brief Pase Rosetta Scripts Options for this Mover
void parse_my_tag(
utility::tag::TagCOP tag,
basic::datacache::DataMap &,
protocols::filters::Filters_map const &,
protocols::moves::Movers_map const &,
core::pose::Pose const &
);
private:
// Store new normal/center pair
core::Vector center_;
core::Vector normal_;
};
/// @brief Membrane Position Rotation Move
/// @details Rotate the orientation of the membrane position to a new
/// normal position. Applies rotation to jump
class SetMembraneNormalMover : public protocols::moves::Mover {
public:
////////////////////
/// Constructors ///
////////////////////
/// @brief Construct a Default Membrane Position Mover
SetMembraneNormalMover();
/// @brief Custom Constructor
/// @details Specify a new normal to rotate membranes to
/// to move this position to
SetMembraneNormalMover( core::Vector normal );
/// @brief Copy Constructor
/// @details Make a deep copy of this mover object
SetMembraneNormalMover( SetMembraneNormalMover const & src );
/// @brief Assignment Operator
/// @details Make a deep copy of this mover object, overriding the assignment operator
SetMembraneNormalMover &
operator=( SetMembraneNormalMover const & src );
/// @brief Destructor
~SetMembraneNormalMover();
/////////////////////
/// Mover Methods ///
/////////////////////
/// @brief Get the name of this mover
virtual std::string get_name() const;
/// @brief Apply Rotation to Membrane
/// @brief Rotate the membrane to the new normal position
virtual void apply( core::pose::Pose & pose );
///////////////////////////////
/// Rosetta Scripts Methods ///
///////////////////////////////
/// @brief Create a Clone of this mover
virtual protocols::moves::MoverOP clone() const;
/// @brief Create a Fresh Instance of this Mover
virtual protocols::moves::MoverOP fresh_instance() const;
/// @brief Pase Rosetta Scripts Options for this Mover
void parse_my_tag(
utility::tag::TagCOP tag,
basic::datacache::DataMap &,
protocols::filters::Filters_map const &,
protocols::moves::Movers_map const &,
core::pose::Pose const &
);
private:
// Store new normal
core::Vector normal_;
};
/// @brief Membrane Position Translation Move
/// @details Translate the center of the membrane stub ot the specified position
class SetMembraneCenterMover : public protocols::moves::Mover {
public:
////////////////////
/// Constructors ///
////////////////////
/// @brief Construct a Default Membrane Position Mover
SetMembraneCenterMover();
/// @brief Custom Constructor
/// @details Specify a new center position to translate this stub to
SetMembraneCenterMover( core::Vector center );
/// @brief Copy Constructor
/// @details Make a deep copy of this mover object
SetMembraneCenterMover( SetMembraneCenterMover const & src );
/// @brief Assignment Operator
/// @details Make a deep copy of this mover object, overriding the assignment operator
SetMembraneCenterMover &
operator=( SetMembraneCenterMover const & src );
/// @brief Destructor
~SetMembraneCenterMover();
/////////////////////
/// Mover Methods ///
/////////////////////
/// @brief Get the name of this mover
virtual std::string get_name() const;
/// @brief Apply Translation to membrane position
/// @brief Translate membrane position to new center
virtual void apply( core::pose::Pose & pose );
///////////////////////////////
/// Rosetta Scripts Methods ///
///////////////////////////////
/// @brief Create a Clone of this mover
virtual protocols::moves::MoverOP clone() const;
/// @brief Create a Fresh Instance of this Mover
virtual protocols::moves::MoverOP fresh_instance() const;
/// @brief Pase Rosetta Scripts Options for this Mover
void parse_my_tag(
utility::tag::TagCOP tag,
basic::datacache::DataMap &,
protocols::filters::Filters_map const &,
protocols::moves::Movers_map const &,
core::pose::Pose const &
);
private:
// Store new center
core::Vector center_;
};
} // membrane
} // protocols
#endif // #ifndef INCLUDED_protocols_membrane_SetMembranePositionMover_hh
| [
"malaifa@yahoo.com"
] | malaifa@yahoo.com |
5b4a885df5262141482424d32284165363627a18 | e862f48c627b8effec2a25b37c590ca4f2649fc0 | /src/pwiz-4209/pwiz/data/identdata/DiffTest.cpp | b98bb828c36bafe7d9103d40bc8c0039768934b9 | [
"Apache-2.0"
] | permissive | Bandeira/sps | ec82a77c315cf1aff9761c801d1dc63cb5c5e9f0 | 1809945c9e5a6836a753a434d2c8570941130021 | refs/heads/master | 2016-09-01T08:18:34.221603 | 2015-12-10T23:56:52 | 2015-12-10T23:56:52 | 47,741,477 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 39,750 | cpp | //
// $Id: DiffTest.cpp 4129 2012-11-20 00:05:37Z chambm $
//
//
// Original author: Robert Burke <robert.burke@proteowizard.org>
//
// Copyright 2009 Spielberg Family Center for Applied Proteomics
// University of Southern California, Los Angeles, California 90033
//
// 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 "Diff.hpp"
#include "TextWriter.hpp"
#include "examples.hpp"
#include "pwiz/utility/misc/unit.hpp"
#include "pwiz/utility/misc/Std.hpp"
#include <cstring>
using namespace pwiz::util;
using namespace pwiz::data;
using namespace pwiz::data::diff_impl;
using namespace pwiz::identdata;
namespace proteome = pwiz::proteome;
// TODO: Add Identifiable diff to all subclasses of Identifiable
ostream* os_ = 0;
const double epsilon = numeric_limits<double>::epsilon();
void testIdentifiable()
{
if (os_) *os_ << "testIdentifiable()\n";
Identifiable a, b;
a.id="id1";
a.name="a_name";
b = a;
Diff<Identifiable, DiffConfig> diff(a, b);
if (diff && os_) *os_ << diff_string<TextWriter>(diff) << endl;
unit_assert(!diff);
b.id="id2";
b.name="b_name";
diff(a, b);
if (os_) *os_ << diff_string<TextWriter>(diff) << endl;
unit_assert(diff);
//
// test handling for ids which often differ only
// by a trailing version number
//
b=a;
a.id += "_1.2.3";
b.id += "_1.2.4";
DiffConfig config;
Diff<Identifiable, DiffConfig> diff0(config);
diff0(a, b);
if (os_) *os_ << diff_string<TextWriter>(diff0) << endl;
unit_assert(diff0);
config.ignoreVersions = true;
Diff<Identifiable, DiffConfig> diff1(config);
diff1(a, b);
if (os_) *os_ << diff_string<TextWriter>(diff1) << endl;
unit_assert(!diff1);
a.id += "x"; // no longer looks like one of our version strings
Diff<Identifiable, DiffConfig> diff2(config);
diff2(a, b);
if (os_) *os_ << diff_string<TextWriter>(diff2) << endl;
unit_assert(diff2);
}
void testFragmentArray()
{
if (os_) *os_ << "testFragmentArray()\n";
FragmentArray a, b;
a.values.push_back(1.0);
a.measurePtr = MeasurePtr(new Measure("Measure_ref"));
b = a;
Diff<FragmentArray, DiffConfig> diff(a, b);
unit_assert(!diff);
if (os_) *os_ << diff_string<TextWriter>(diff) << endl;
a.values.push_back(2.1);
b.values.push_back(2.0);
b.measurePtr = MeasurePtr(new Measure("fer_erusaeM"));
diff(a, b);
// a diff was found
unit_assert(diff);
// the values of the diff are correct
unit_assert(diff.a_b.values.size() == 2);
unit_assert_equal(0.0, diff.a_b.values[0], 1e-6);
unit_assert_equal(0.1, diff.a_b.values[1], 1e-6);
unit_assert(diff.b_a.values.size() == 2);
unit_assert_equal(0.0, diff.b_a.values[0], 1e-6);
unit_assert_equal(-0.1, diff.b_a.values[1], 1e-6);
unit_assert(diff.a_b.measurePtr.get());
unit_assert(diff.a_b.measurePtr->id == "Measure_ref");
unit_assert(diff.b_a.measurePtr.get());
unit_assert(diff.b_a.measurePtr->id == "fer_erusaeM");
if (os_) *os_ << diff_string<TextWriter>(diff) << endl;
}
void testIonType()
{
if (os_) *os_ << "testIonType()\n";
IonType a, b;
a.index.push_back(1);
a.charge = 1;
a.cvid = MS_frag__a_ion;
a.fragmentArray.push_back(FragmentArrayPtr(new FragmentArray));
b = a;
Diff<IonType, DiffConfig> diff(a, b);
unit_assert(!diff);
if (os_ && diff) *os_ << diff_string<TextWriter>(diff) << endl;
b.index.back() = 2;
b.charge = 2;
b.cvid = MS_frag__z_ion;
b.fragmentArray.push_back(FragmentArrayPtr(new FragmentArray));
b.fragmentArray.back()->measurePtr = MeasurePtr(new Measure("Graduated_cylinder"));
diff(a, b);
// a diff was found
unit_assert(diff);
if (os_) *os_ << diff_string<TextWriter>(diff) << endl;
// and correctly
unit_assert(diff.a_b.index.size() == 1);
unit_assert(diff.b_a.index.size() == 1);
unit_assert_equal(*diff.a_b.index.begin(), 1.0, epsilon);
unit_assert_equal(*diff.b_a.index.begin(), 2.0, epsilon);
unit_assert_equal(diff.a_b.charge, 1.0, epsilon);
unit_assert_equal(diff.b_a.charge, 2.0, epsilon);
unit_assert(diff.a_b.cvid == MS_frag__a_ion);
unit_assert(diff.b_a.cvid == MS_frag__z_ion);
unit_assert(diff.b_a.fragmentArray.size() == 1);
unit_assert(diff.b_a.fragmentArray.back()->measurePtr.get());
unit_assert(diff.b_a.fragmentArray.back()->measurePtr->id == "Graduated_cylinder");
}
void testMeasure()
{
if (os_) *os_ << "testMeasure()\n";
Measure a, b;
a.set(MS_product_ion_m_z, 200);
b = a;
Diff<Measure, DiffConfig> diff(a, b);
unit_assert(!diff);
b.set(MS_product_ion_intensity, 1);
diff(a, b);
if (os_) *os_ << diff_string<TextWriter>(diff) << endl;
// diff was found
unit_assert(diff);
// and correctly
unit_assert(diff.a_b.cvParams.size() == 0);
unit_assert(diff.b_a.cvParams.size() == 1);
unit_assert(diff.b_a.hasCVParam(MS_product_ion_intensity));
}
void testSearchModification()
{
if (os_) *os_ << "testSearchModification()\n";
SearchModification a, b;
a.massDelta = 1;
a.residues.push_back('A');
a.residues.push_back('B');
a.set(UNIMOD_Gln__pyro_Glu);
b = a;
Diff<SearchModification, DiffConfig> diff(a, b);
unit_assert(!diff);
b.massDelta = 10;
b.residues.push_back('C');
b.cvParams.clear();
b.set(UNIMOD_Oxidation);
diff(a, b);
if (os_) *os_ << diff_string<TextWriter>(diff) << endl;
// diff was found
unit_assert(diff);
// and correctly
unit_assert_equal(diff.a_b.massDelta, 9, epsilon);
unit_assert_equal(diff.b_a.massDelta, 9, epsilon);
unit_assert(diff.a_b.residues.empty());
unit_assert(diff.b_a.residues.size() == 1 && diff.b_a.residues[0] == 'C');
unit_assert(!diff.a_b.cvParams.empty());
unit_assert(diff.a_b.cvParams[0].cvid == UNIMOD_Gln__pyro_Glu);
unit_assert(!diff.b_a.cvParams.empty());
unit_assert(diff.b_a.cvParams[0].cvid == UNIMOD_Oxidation);
}
void testPeptideEvidence()
{
if (os_) *os_ << "testPeptideEvidence()\n";
PeptideEvidence a, b;
Diff<PeptideEvidence, DiffConfig> diff(a, b);
if (os_) *os_ << diff_string<TextWriter>(diff) << endl;
unit_assert(!diff);
a.dbSequencePtr = DBSequencePtr(new DBSequence("DBSequence_ref"));
a.start = 1;
a.end = 6;
a.pre = '-';
a.post = '-';
a.translationTablePtr = TranslationTablePtr(new TranslationTable("TranslationTable_ref"));
a.frame = 0;
a.isDecoy = true;
a.set(MS_Mascot_score, 15.71);
b = a;
diff(a,b);
unit_assert(!diff);
b.dbSequencePtr = DBSequencePtr(new DBSequence("fer_ecneuqeSBD"));
b.start = 2;
b.end = 7;
b.pre = 'A';
b.post = 'A';
b.translationTablePtr = TranslationTablePtr(new TranslationTable("fer_elbaTnoitalsnarT"));
b.frame = 1;
b.isDecoy = false;
b.set(MS_Mascot_expectation_value, 0.0268534444565851);
diff(a, b);
if (os_) *os_ << diff_string<TextWriter>(diff) << endl;
// a diff was found
unit_assert(diff);
// and correctly
unit_assert(diff.a_b.dbSequencePtr.get());
unit_assert(diff.a_b.dbSequencePtr->id == "DBSequence_ref");
unit_assert(diff.b_a.dbSequencePtr.get());
unit_assert(diff.b_a.dbSequencePtr->id == "fer_ecneuqeSBD");
unit_assert(diff.a_b.translationTablePtr.get());
unit_assert(diff.a_b.translationTablePtr->id == "TranslationTable_ref");
unit_assert(diff.b_a.translationTablePtr.get());
unit_assert(diff.b_a.translationTablePtr->id == "fer_elbaTnoitalsnarT");
unit_assert_equal(diff.a_b.start, 1.0, epsilon);
unit_assert_equal(diff.b_a.start, 2.0, epsilon);
unit_assert_equal(diff.a_b.end, 6.0, epsilon);
unit_assert_equal(diff.b_a.end, 7.0, epsilon);
unit_assert(diff.a_b.pre == '-');
unit_assert(diff.b_a.pre == 'A');
unit_assert(diff.a_b.post == '-');
unit_assert(diff.b_a.post == 'A');
unit_assert_equal(diff.a_b.frame, 0.0, epsilon);
unit_assert_equal(diff.b_a.frame, 1.0, epsilon);
unit_assert(diff.a_b.isDecoy == true);
unit_assert(diff.b_a.isDecoy == false);
unit_assert(diff.a_b.cvParams.size() == 0);
unit_assert(diff.b_a.cvParams.size() == 1);
unit_assert(diff.b_a.hasCVParam(MS_Mascot_expectation_value));
}
void testProteinAmbiguityGroup()
{
if (os_) *os_ << "testProteinAmbiguityGroup()\n";
ProteinAmbiguityGroup a, b;
a.proteinDetectionHypothesis.push_back(ProteinDetectionHypothesisPtr(new ProteinDetectionHypothesis));
a.proteinDetectionHypothesis.back()->dbSequencePtr = DBSequencePtr(new DBSequence("DBSequence_ref"));
a.set(MS_Mascot_score, 164.4);
b = a;
Diff<ProteinAmbiguityGroup, DiffConfig> diff(a, b);
unit_assert(!diff);
b.proteinDetectionHypothesis.clear();
b.set(MS_Mascot_expectation_value, 0.0268534444565851);
diff(a, b);
if (os_) *os_ << diff_string<TextWriter>(diff) << endl;
// a diff was found
unit_assert(diff);
// and correctly
unit_assert(diff.a_b.proteinDetectionHypothesis.size() == 1);
unit_assert(diff.b_a.proteinDetectionHypothesis.size() == 0);
unit_assert(diff.a_b.proteinDetectionHypothesis.back()->dbSequencePtr->id == "DBSequence_ref");
unit_assert(diff.a_b.cvParams.size() == 0);
unit_assert(diff.b_a.cvParams.size() == 1);
unit_assert(diff.b_a.hasCVParam(MS_Mascot_expectation_value)); // TODO check vals also?
}
void testPeptideHypothesis()
{
if (os_) *os_ << "testPeptideHypothesis()\n";
PeptideHypothesis a, b;
Diff<PeptideHypothesis, DiffConfig> diff(a,b);
unit_assert(!diff);
a.peptideEvidencePtr = PeptideEvidencePtr(new PeptideEvidence("pe_a"));
a.spectrumIdentificationItemPtr.push_back(SpectrumIdentificationItemPtr(new SpectrumIdentificationItem("sii_a")));
b.peptideEvidencePtr = PeptideEvidencePtr(new PeptideEvidence("pe_b"));
b.spectrumIdentificationItemPtr.push_back(SpectrumIdentificationItemPtr(new SpectrumIdentificationItem("sii_b")));
diff(a,b);
if (os_) *os_ << diff_string<TextWriter>(diff) << endl;
// a diff was found
unit_assert(diff);
// and correctly
unit_assert(diff.a_b.peptideEvidencePtr.get());
unit_assert(diff.a_b.peptideEvidencePtr->id =="pe_a");
unit_assert(diff.b_a.peptideEvidencePtr.get());
unit_assert(diff.b_a.peptideEvidencePtr->id == "pe_b");
unit_assert(diff.a_b.spectrumIdentificationItemPtr.size() == 1);
unit_assert(diff.a_b.spectrumIdentificationItemPtr.back()->id =="sii_a");
unit_assert(diff.b_a.spectrumIdentificationItemPtr.size() == 1);
unit_assert(diff.b_a.spectrumIdentificationItemPtr.back()->id == "sii_b");
}
void testProteinDetectionHypothesis()
{
if (os_) *os_ << "testProteinDetectionHypothesis()\n";
ProteinDetectionHypothesis a, b;
Diff<ProteinDetectionHypothesis, DiffConfig> diff(a,b);
unit_assert(!diff);
a.dbSequencePtr = DBSequencePtr(new DBSequence("DBSequence_ref"));
b.dbSequencePtr = DBSequencePtr(new DBSequence("fer_ecneuqeSBD"));
a.passThreshold = true;
b.passThreshold = false;
a.peptideHypothesis.push_back(PeptideHypothesis());
b.peptideHypothesis.push_back(PeptideHypothesis());
a.peptideHypothesis.back().peptideEvidencePtr = PeptideEvidencePtr(new PeptideEvidence("pe_a"));
a.peptideHypothesis.back().spectrumIdentificationItemPtr.push_back(SpectrumIdentificationItemPtr(new SpectrumIdentificationItem("sii_a")));
b.peptideHypothesis.back().peptideEvidencePtr = PeptideEvidencePtr(new PeptideEvidence("pe_b"));
b.peptideHypothesis.back().spectrumIdentificationItemPtr.push_back(SpectrumIdentificationItemPtr(new SpectrumIdentificationItem("sii_b")));
a.set(MS_Mascot_expectation_value);
diff(a,b);
if (os_) *os_ << diff_string<TextWriter>(diff) << endl;
// a diff was found
unit_assert(diff);
// and correctly
unit_assert(diff.a_b.dbSequencePtr.get());
unit_assert(diff.a_b.dbSequencePtr->id =="DBSequence_ref");
unit_assert(diff.b_a.dbSequencePtr.get());
unit_assert(diff.b_a.dbSequencePtr->id == "fer_ecneuqeSBD");
unit_assert(diff.a_b.passThreshold == true);
unit_assert(diff.b_a.passThreshold == false);
unit_assert(diff.a_b.peptideHypothesis.size() == 1);
unit_assert(diff.b_a.peptideHypothesis.size() == 1);
unit_assert(diff.a_b.peptideHypothesis.back().peptideEvidencePtr->id == "pe_a");
unit_assert(diff.b_a.peptideHypothesis.back().peptideEvidencePtr->id == "pe_b");
unit_assert(diff.a_b.peptideHypothesis.back().spectrumIdentificationItemPtr.size() == 1);
unit_assert(diff.a_b.peptideHypothesis.back().spectrumIdentificationItemPtr.back()->id =="sii_a");
unit_assert(diff.b_a.peptideHypothesis.back().spectrumIdentificationItemPtr.size() == 1);
unit_assert(diff.b_a.peptideHypothesis.back().spectrumIdentificationItemPtr.back()->id == "sii_b");
unit_assert(diff.a_b.cvParams.size() == 1);
unit_assert(diff.b_a.cvParams.size() == 0);
unit_assert(diff.a_b.hasCVParam(MS_Mascot_expectation_value));
}
void testSpectrumIdentificationList()
{
if (os_) *os_ << "testSpectrumIdentificationList()\n";
SpectrumIdentificationList a, b;
Diff<SpectrumIdentificationList, DiffConfig> diff(a,b);
unit_assert(!diff);
a.numSequencesSearched = 9;
b.numSequencesSearched = 5;
MeasurePtr testMeasure(new Measure());
testMeasure->set(MS_Mascot_expectation_value);
a.fragmentationTable.push_back(testMeasure);
SpectrumIdentificationResultPtr testSIRPtr(new SpectrumIdentificationResult());
testSIRPtr->set(MS_Mascot_expectation_value);
a.spectrumIdentificationResult.push_back(testSIRPtr);
diff(a,b);
if (os_) *os_ << diff_string<TextWriter>(diff) << endl;
// a diff was found
unit_assert(diff);
// and correctly
unit_assert_equal(diff.a_b.numSequencesSearched,9.0,epsilon);
unit_assert_equal(diff.b_a.numSequencesSearched,5.0,epsilon);
unit_assert(diff.a_b.fragmentationTable.size() == 1);
unit_assert(diff.b_a.fragmentationTable.size() == 0);
unit_assert(diff.a_b.fragmentationTable.back()->hasCVParam(MS_Mascot_expectation_value));
unit_assert(diff.a_b.spectrumIdentificationResult.size() == 1);
unit_assert(diff.b_a.spectrumIdentificationResult.size() == 0);
unit_assert(diff.a_b.spectrumIdentificationResult.back()->hasCVParam(MS_Mascot_expectation_value));
}
void testProteinDetectionList()
{
if (os_) *os_ << "testProteinDetectionList()\n";
ProteinDetectionList a,b;
Diff<ProteinDetectionList, DiffConfig> diff(a,b);
unit_assert(!diff);
a.proteinAmbiguityGroup.push_back(ProteinAmbiguityGroupPtr(new ProteinAmbiguityGroup()));
a.proteinAmbiguityGroup.back()->set(MS_Mascot_expectation_value, 0.0268534444565851);
a.set(MS_frag__z_ion);
b.set(MS_frag__b_ion);
diff(a,b);
if (os_) *os_ << diff_string<TextWriter>(diff) << endl;
// a diff was found
unit_assert(diff);
// and correctly
unit_assert(diff.a_b.proteinAmbiguityGroup.size() == 1);
unit_assert(diff.b_a.proteinAmbiguityGroup.size() == 0);
unit_assert(diff.a_b.proteinAmbiguityGroup.back()->hasCVParam(MS_Mascot_expectation_value));
unit_assert(diff.a_b.cvParams.size() == 1);
unit_assert(diff.b_a.cvParams.size() == 1);
unit_assert(diff.a_b.hasCVParam(MS_frag__z_ion));
unit_assert(diff.b_a.hasCVParam(MS_frag__b_ion));
}
void testAnalysisData()
{
if (os_) *os_ << "testAnalysisData()\n";
AnalysisData a, b;
Diff<AnalysisData, DiffConfig> diff(a,b);
unit_assert(!diff);
a.spectrumIdentificationList.push_back(boost::shared_ptr<SpectrumIdentificationList>(new SpectrumIdentificationList()));
a.spectrumIdentificationList.back()->numSequencesSearched = 5;
b.spectrumIdentificationList.push_back(boost::shared_ptr<SpectrumIdentificationList>(new SpectrumIdentificationList()));
b.spectrumIdentificationList.back()->numSequencesSearched = 15;
a.proteinDetectionListPtr = ProteinDetectionListPtr(new ProteinDetectionList("rosemary"));
b.proteinDetectionListPtr = ProteinDetectionListPtr(new ProteinDetectionList("sage"));
diff(a,b);
if (os_) *os_ << diff_string<TextWriter>(diff) << endl;
// a diff was found
unit_assert(diff);
// and correctly
unit_assert(diff.a_b.spectrumIdentificationList.size() == 1);
unit_assert(diff.b_a.spectrumIdentificationList.size() == 1);
unit_assert_equal(diff.a_b.spectrumIdentificationList.back()->numSequencesSearched, 5.0, epsilon);
unit_assert_equal(diff.b_a.spectrumIdentificationList.back()->numSequencesSearched, 15.0, epsilon);
unit_assert(diff.a_b.proteinDetectionListPtr.get());
unit_assert(diff.b_a.proteinDetectionListPtr.get());
unit_assert(diff.a_b.proteinDetectionListPtr->id == "rosemary");
unit_assert(diff.b_a.proteinDetectionListPtr->id == "sage");
}
void testSearchDatabase()
{
if (os_) *os_ << "testSearchDatabase()" << endl;
SearchDatabase a, b;
Diff<SearchDatabase, DiffConfig> diff(a,b);
unit_assert(!diff);
a.version = "1.0";
b.version = "1.1";
a.releaseDate = "20090726";
b.releaseDate = "20090727";
a.numDatabaseSequences = 5;
b.numDatabaseSequences = 15;
a.numResidues = 3;
b.numResidues = 13;
a.fileFormat.cvid = MS_frag__z_ion;
a.databaseName.set(MS_frag__z_ion);
diff(a,b);
if (os_) *os_ << diff_string<TextWriter>(diff) << endl;
// a diff was found
unit_assert(diff);
// and correctly
unit_assert(diff.a_b.version == "1.0");
unit_assert(diff.b_a.version == "1.1");
unit_assert(diff.a_b.releaseDate == "20090726");
unit_assert(diff.b_a.releaseDate == "20090727");
unit_assert_equal(diff.a_b.numDatabaseSequences, 5.0, epsilon);
unit_assert_equal(diff.b_a.numDatabaseSequences, 15.0, epsilon);
unit_assert_equal(diff.a_b.numResidues, 3.0, epsilon);
unit_assert_equal(diff.b_a.numResidues, 13.0, epsilon);
unit_assert(!diff.a_b.fileFormat.empty());
unit_assert(diff.b_a.fileFormat.empty());
unit_assert(diff.a_b.fileFormat.cvid == MS_frag__z_ion);
unit_assert(diff.a_b.databaseName.cvParams.size() == 1);
unit_assert(diff.b_a.databaseName.cvParams.size() == 0);
unit_assert(diff.a_b.databaseName.hasCVParam(MS_frag__z_ion));
}
void testSpectraData()
{
if (os_) *os_ << "testSpectraData()\n" << endl;
SpectraData a, b;
Diff<SpectraData, DiffConfig> diff(a,b);
unit_assert(!diff);
a.location = "mahtomedi";
b.location = "white_bear_lake";
a.externalFormatDocumentation.push_back("wikipedia");
b.externalFormatDocumentation.push_back("ehow");
a.fileFormat.cvid = MS_frag__b_ion;
diff(a,b);
if (os_) *os_ << diff_string<TextWriter>(diff) << endl;
// a diff was found
unit_assert(diff);
// and correctly
unit_assert(diff.a_b.location == "mahtomedi");
unit_assert(diff.b_a.location == "white_bear_lake");
unit_assert(diff.a_b.externalFormatDocumentation.size() == 1);
unit_assert(diff.b_a.externalFormatDocumentation.size() == 1);
unit_assert(diff.a_b.externalFormatDocumentation.back() == "wikipedia");
unit_assert(diff.b_a.externalFormatDocumentation.back() == "ehow");
unit_assert(!diff.a_b.fileFormat.empty());
unit_assert(diff.b_a.fileFormat.empty());
unit_assert(diff.a_b.fileFormat.cvid == MS_frag__b_ion);
}
void testSourceFile()
{
if (os_) *os_ << "testSourceFile()\n" << endl;
SourceFile a,b;
Diff<SourceFile, DiffConfig> diff(a,b);
unit_assert(!diff);
a.location = "madison";
b.location = "middleton";
a.fileFormat.cvid = MS_wolf;
a.externalFormatDocumentation.push_back("The Idiot's Guide to External Formats");
b.externalFormatDocumentation.push_back("External Formats for Dummies");
a.set(MS_sample_number);
b.set(MS_sample_name);
diff(a,b);
if (os_) *os_ << diff_string<TextWriter>(diff) << endl;
// a diff was found
unit_assert(diff);
// and correctly
unit_assert(diff.a_b.location == "madison");
unit_assert(diff.b_a.location == "middleton");
unit_assert(!diff.a_b.fileFormat.empty());
unit_assert(diff.b_a.fileFormat.empty());
unit_assert(diff.a_b.fileFormat.cvid == MS_wolf);
unit_assert(diff.a_b.externalFormatDocumentation.size() == 1);
unit_assert(diff.b_a.externalFormatDocumentation.size() == 1);
unit_assert(diff.a_b.externalFormatDocumentation.back() == "The Idiot's Guide to External Formats");
unit_assert(diff.b_a.externalFormatDocumentation.back() == "External Formats for Dummies");
unit_assert(diff.a_b.cvParams.size() == 1);
unit_assert(diff.b_a.cvParams.size() == 1);
unit_assert(diff.a_b.hasCVParam(MS_sample_number));
unit_assert(diff.b_a.hasCVParam(MS_sample_name));
}
void testInputs()
{
if (os_) *os_ << "testInputs()\n";
Inputs a, b;
Diff<Inputs, DiffConfig> diff(a,b);
unit_assert(!diff);
a.sourceFile.push_back(SourceFilePtr(new SourceFile()));
a.sourceFile.back()->location = "Sector 9";
a.searchDatabase.push_back(SearchDatabasePtr(new SearchDatabase()));
a.searchDatabase.back()->numDatabaseSequences = 100;
a.spectraData.push_back(SpectraDataPtr(new SpectraData()));
a.spectraData.back()->location = "Cloud 9";
diff(a,b);
if (os_) *os_ << diff_string<TextWriter>(diff) << endl;
// a diff was found
unit_assert(diff);
// and correctly
unit_assert(diff.a_b.sourceFile.size() == 1);
unit_assert(diff.b_a.sourceFile.size() == 0);
unit_assert(diff.a_b.sourceFile.back()->location == "Sector 9");
unit_assert(diff.a_b.searchDatabase.size() == 1);
unit_assert(diff.b_a.searchDatabase.size() == 0);
unit_assert_equal(diff.a_b.searchDatabase.back()->numDatabaseSequences, 100.0, epsilon);
unit_assert(diff.a_b.spectraData.size() == 1);
unit_assert(diff.b_a.spectraData.size() == 0);
unit_assert(diff.a_b.spectraData.back()->location == "Cloud 9");
}
void testEnzyme()
{
if (os_) *os_ << "testEnzyme()\n";
Enzyme a,b;
Diff<Enzyme, DiffConfig> diff(a,b);
if (diff && os_) *os_ << diff_string<TextWriter>(diff) << endl;
unit_assert(!diff);
a.id = "Donald Trump";
b.id = "Donald Duck";
a.nTermGain = "y";
b.nTermGain = "n";
a.cTermGain = "y";
b.cTermGain = "n";
a.terminalSpecificity = proteome::Digestion::SemiSpecific;
b.terminalSpecificity = proteome::Digestion::FullySpecific;
a.missedCleavages = 1;
b.missedCleavages = 5;
a.minDistance = 2;
b.minDistance = 4;
a.siteRegexp = "^";
b.siteRegexp = "$";
a.enzymeName.set(MS_Trypsin);
diff(a,b);
if (os_) *os_ << diff_string<TextWriter>(diff) << endl;
// a diff was found
unit_assert(diff);
// and correctly
unit_assert(diff.a_b.id == "Donald Trump");
unit_assert(diff.b_a.id == "Donald Duck");
unit_assert(diff.a_b.nTermGain == "y");
unit_assert(diff.b_a.nTermGain == "n");
unit_assert(diff.a_b.cTermGain == "y");
unit_assert(diff.a_b.terminalSpecificity == proteome::Digestion::SemiSpecific);
unit_assert(diff.b_a.terminalSpecificity == proteome::Digestion::FullySpecific);
unit_assert(diff.b_a.cTermGain == "n");
unit_assert(diff.a_b.missedCleavages == 1);
unit_assert(diff.b_a.missedCleavages == 5);
unit_assert(diff.a_b.minDistance == 2);
unit_assert(diff.b_a.minDistance == 4);
unit_assert(diff.a_b.siteRegexp == "^");
unit_assert(diff.b_a.siteRegexp == "$");
unit_assert(diff.a_b.enzymeName.cvParams.size() == 1);
unit_assert(diff.b_a.enzymeName.cvParams.size() == 0);
unit_assert(diff.a_b.enzymeName.hasCVParam(MS_Trypsin));
}
void testEnzymes()
{
if (os_) *os_ << "testEnzymes()\n";
Enzymes a, b;
Diff<Enzymes, DiffConfig> diff(a, b);
if (diff && os_) *os_ << diff_string<TextWriter>(diff) << endl;
a.independent = "indep";
b.enzymes.push_back(EnzymePtr(new Enzyme()));
}
void testMassTable()
{
if (os_) *os_ << "testMassTable()\n";
MassTable a, b;
a.id = "id";
a.msLevel.push_back(1);
ResiduePtr c(new Residue());
a.residues.push_back(c);
AmbiguousResiduePtr d(new AmbiguousResidue());
a.ambiguousResidue.push_back(d);
b = a;
Diff<MassTable, DiffConfig> diff(a, b);
unit_assert(!diff);
b.id = "b_id";
diff(a, b);
unit_assert(diff);
a.id = "b_id";
b.msLevel.push_back(2);
diff(a, b);
unit_assert(diff);
b.msLevel.push_back(2);
b.residues.clear();
diff(a, b);
unit_assert(diff);
a.residues.clear();
b.ambiguousResidue.clear();
diff(a, b);
unit_assert(diff);
}
void testResidue()
{
if (os_) *os_ << "testResidue()\n";
Residue a, b;
a.code = 'A';
a.mass = 1.0;
b = a;
Diff<Residue, DiffConfig> diff(a, b);
unit_assert(!diff);
b.code = 'C';
b.mass = 2.0;
diff(a, b);
if (os_) *os_ << diff_string<TextWriter>(diff) << endl;
unit_assert(diff);
unit_assert(diff.a_b.code == 'A');
unit_assert(diff.b_a.code == 'C');
unit_assert_equal(diff.a_b.mass, 1.0, epsilon);
unit_assert_equal(diff.b_a.mass, 1.0, epsilon);
}
void testAmbiguousResidue()
{
if (os_) *os_ << "testAmbiguousResidue()\n";
AmbiguousResidue a, b;
a.code = 'Z';
a.set(MS_alternate_single_letter_codes, "E Q");
b = a;
Diff<AmbiguousResidue, DiffConfig> diff(a, b);
unit_assert(!diff);
b.code = 'B';
b.set(MS_alternate_single_letter_codes, "D N");
diff(a, b);
if (os_) *os_ << diff_string<TextWriter>(diff) << endl;
unit_assert(diff);
unit_assert(diff.a_b.code == 'Z');
unit_assert(diff.b_a.code == 'B');
unit_assert(diff.a_b.cvParam(MS_alternate_single_letter_codes).value == "E Q");
unit_assert(diff.b_a.cvParam(MS_alternate_single_letter_codes).value == "D N");
}
void testFilter()
{
if (os_) *os_ << "testFilter()\n";
Filter a, b;
a.filterType.set(MS_DB_filter_taxonomy);
a.include.set(MS_DB_PI_filter);
a.exclude.set(MS_translation_table);
b = a;
Diff<Filter, DiffConfig> diff(a, b);
unit_assert(!diff);
b.filterType.clear();
b.filterType.set(MS_database_filtering);
b.include.clear();
b.include.set(MS_DB_filter_on_accession_numbers);
b.exclude.clear();
b.exclude.set(MS_DB_MW_filter);
diff(a, b);
if (os_) *os_ << diff_string<TextWriter>(diff) << endl;
unit_assert(diff);
unit_assert(diff.a_b.filterType.hasCVParam(MS_DB_filter_taxonomy));
unit_assert(diff.b_a.filterType.hasCVParam(MS_database_filtering));
unit_assert(diff.a_b.include.hasCVParam(MS_DB_PI_filter));
unit_assert(diff.b_a.include.hasCVParam(MS_DB_filter_on_accession_numbers));
unit_assert(diff.a_b.exclude.hasCVParam(MS_translation_table));
unit_assert(diff.b_a.exclude.hasCVParam(MS_DB_MW_filter));
}
void testDatabaseTranslation()
{
if (os_) *os_ << "testDatabaseTranslation()\n";
DatabaseTranslation a, b;
a.frames.push_back(1);
a.frames.push_back(2);
TranslationTablePtr tt(new TranslationTable("TT_1", "TT_1"));
tt->set(MS_translation_table, "GATTACA");
tt->set(MS_translation_table_description, "http://somewhere.com");
a.translationTable.push_back(tt);
b = a;
Diff<DatabaseTranslation, DiffConfig> diff(a, b);
unit_assert(!diff);
b.translationTable.clear();
diff(a, b);
if (os_) *os_ << diff_string<TextWriter>(diff) << endl;
unit_assert(diff);
unit_assert_operator_equal(0, diff.a_b.frames.size());
unit_assert_operator_equal(0, diff.b_a.frames.size());
unit_assert_operator_equal(1, diff.a_b.translationTable.size());
unit_assert_operator_equal(0, diff.b_a.translationTable.size());
b = a;
b.frames.push_back(3);
diff(a, b);
if (os_) *os_ << diff_string<TextWriter>(diff) << endl;
unit_assert(diff);
unit_assert_operator_equal(0, diff.a_b.frames.size());
unit_assert_operator_equal(1, diff.b_a.frames.size());
unit_assert_operator_equal(0, diff.a_b.translationTable.size());
unit_assert_operator_equal(0, diff.b_a.translationTable.size());
}
void testSpectrumIdentificationProtocol()
{
if (os_) *os_ << "testSpectrumIdentificationProtocol()\n";
SpectrumIdentificationProtocol a("a_id", "a_name"), b;
a.analysisSoftwarePtr = AnalysisSoftwarePtr(new AnalysisSoftware("a_as"));
a.searchType.cvid = MS_pmf_search;
a.additionalSearchParams.set(MS_Sequest_CleavesAt, "cleavage");
SearchModificationPtr smp(new SearchModification());
smp->fixedMod = true;
a.modificationParams.push_back(smp);
a.enzymes.enzymes.push_back(EnzymePtr(new Enzyme("a_enzyme")));
a.massTable.push_back(MassTablePtr(new MassTable("mt_id")));
a.fragmentTolerance.set(MS_search_tolerance_plus_value, 1.0);
a.parentTolerance.set(MS_search_tolerance_plus_value, 2.0);
a.threshold.set(MS_search_tolerance_minus_value, 3.0);
FilterPtr filter = FilterPtr(new Filter());
filter->filterType.set(MS_FileFilter);
a.databaseFilters.push_back(filter);
a.databaseTranslation = DatabaseTranslationPtr(new DatabaseTranslation());
b = a;
Diff<SpectrumIdentificationProtocol, DiffConfig> diff(a, b);
unit_assert(!diff);
b.id = "b_id";
b.name = "b_name";
diff(a, b);
if (os_) *os_ << diff_string<TextWriter>(diff) << endl;
// TODO debug removal - put it back
//unit_assert(diff);
b.analysisSoftwarePtr = AnalysisSoftwarePtr(new AnalysisSoftware("b_as"));
b.searchType.cvid = MS_ms_ms_search;
b.additionalSearchParams.set(MS_Sequest_CleavesAt, "land");
b.modificationParams.clear();
b.enzymes.enzymes.clear();
b.massTable.clear();
b.fragmentTolerance.set(MS_search_tolerance_plus_value, 4.0);
b.parentTolerance.set(MS_search_tolerance_plus_value, 5.0);
b.threshold.set(MS_search_tolerance_minus_value, 6.0);
b.databaseFilters.clear();
diff(a, b);
if (os_) *os_ << diff_string<TextWriter>(diff) << endl;
unit_assert(diff);
}
void testProteinDetectionProtocol()
{
if (os_) *os_ << "testProteinDetectionProtocol()\n";
ProteinDetectionProtocol a("a_id", "a_name"), b;
a.analysisSoftwarePtr = AnalysisSoftwarePtr(new AnalysisSoftware());
a.analysisParams.set(MS_low_intensity_threshold);
a.threshold.set(MS_low_intensity_threshold);
b = a;
Diff<ProteinDetectionProtocol, DiffConfig> diff(a, b);
unit_assert(!diff);
b.id = "b_id";
b.name = "b_name";
diff(a, b);
if (os_) *os_ << diff_string<TextWriter>(diff) << endl;
//unit_assert(diff);
}
void testAnalysisProtocolCollection()
{
if (os_) *os_ << "testAnalysisProtocolCollection()\n";
}
void testContact()
{
if (os_) *os_ << "testContact()\n";
Contact a("a_id", "a_name"), b;
a.set(MS_contact_address, "address");
a.set(MS_contact_phone_number, "phone");
a.set(MS_contact_email, "email");
a.set(MS_contact_fax_number, "fax");
a.set(MS_contact_toll_free_phone_number, "tollFreePhone");
b = a;
Diff<Contact, DiffConfig> diff(a, b);
unit_assert(!diff);
b.id = "b_id";
b.name = "b_name";
diff(a, b);
if (os_) *os_ << diff_string<TextWriter>(diff) << endl;
unit_assert(diff);
b.set(MS_contact_address, "b_address");
b.set(MS_contact_phone_number, "b_phone");
b.set(MS_contact_email, "b_email");
b.set(MS_contact_fax_number, "b_fax");
b.set(MS_contact_toll_free_phone_number, "b_tollFreePhone");
diff(a, b);
if (os_) *os_ << diff_string<TextWriter>(diff) << endl;
unit_assert(diff);
}
void testPerson()
{
if (os_) *os_ << "testPerson()\n";
Person a, b;
a.lastName = "last";
a.firstName = "first";
a.midInitials = "mi";
a.affiliations.push_back(OrganizationPtr(new Organization("org")));
b = a;
Diff<Person, DiffConfig> diff(a, b);
unit_assert(!diff);
b.lastName = "smith";
diff(a, b);
unit_assert(diff);
a.lastName = "smith";
b.firstName = "john";
diff(a, b);
unit_assert(diff);
a.firstName = "john";
b.midInitials = "j.j.";
diff(a, b);
unit_assert(diff);
a.midInitials = "j.j.";
b.affiliations.clear();
diff(a, b);
unit_assert(diff);
}
void testOrganization()
{
if (os_) *os_ << "testOrganization()\n";
}
void testBibliographicReference()
{
if (os_) *os_ << "testBibliographicReference()\n";
}
void testProteinDetection()
{
if (os_) *os_ << "testProteinDetection()\n";
}
void testSpectrumIdentification()
{
if (os_) *os_ << "testSpectrumIdentification()\n";
}
void testAnalysisCollection()
{
if (os_) *os_ << "testAnalysisCollection()\n";
}
void testDBSequence()
{
if (os_) *os_ << "testDBSequence()\n";
}
void testModification()
{
if (os_) *os_ << "testModification()\n";
}
void testSubstitutionModification()
{
if (os_) *os_ << "testSubstitutionModification()\n";
}
void testPeptide()
{
if (os_) *os_ << "testPeptide()\n";
}
void testSequenceCollection()
{
if (os_) *os_ << "testSequenceCollection()\n";
}
void testSampleComponent()
{
if (os_) *os_ << "testSampleComponent()\n";
}
void testSample()
{
if (os_) *os_ << "testSample()\n";
Sample a, b;
a.contactRole.push_back(ContactRolePtr(new ContactRole(MS_role_type, ContactPtr(new Person("contactPtr")))));
b = a;
Diff<Sample, DiffConfig> diff(a, b);
if (os_) *os_ << diff_string<TextWriter>(diff) << endl;
unit_assert(!diff);
b.contactRole.back().reset(new ContactRole(MS_role_type, ContactPtr(new Person("fer_rehto"))));
b.set(MS_sample_name);
diff(a, b);
if (os_) *os_ << diff_string<TextWriter>(diff) << endl;
// a diff was found
unit_assert(diff);
// and correctly
unit_assert(diff.a_b.cvParams.size() == 0);
unit_assert(diff.b_a.cvParams.size() == 1);
unit_assert(diff.a_b.contactRole.size() == 1);
unit_assert(diff.b_a.contactRole.size() == 1);
unit_assert(diff.a_b.contactRole.back().get());
unit_assert(diff.b_a.contactRole.back().get());
unit_assert(diff.a_b.contactRole.back()->contactPtr.get());
unit_assert(diff.b_a.contactRole.back()->contactPtr.get());
unit_assert(diff.a_b.contactRole.back()->contactPtr->id == "contactPtr");
unit_assert(diff.b_a.contactRole.back()->contactPtr->id == "fer_rehto");
unit_assert(diff.b_a.hasCVParam(MS_sample_name));
}
void testSpectrumIdentificationItem()
{
if (os_) *os_ << "testSpectrumIdentificationItem()\n";
}
void testSpectrumIdentificationResult()
{
if (os_) *os_ << "testSpectrumIdentificationResult()\n";
}
void testAnalysisSampleCollection()
{
if (os_) *os_ << "testAnalysisSampleCollection()\n";
}
void testProvider()
{
if (os_) *os_ << "testProvider()\n";
}
void testContactRole()
{
if (os_) *os_ << "testContactRole()\n";
ContactRole a, b;
a.contactPtr = ContactPtr(new Person("cid", "cname"));
a.cvid = MS_software_vendor;
b = a;
Diff<ContactRole, DiffConfig> diff(a, b);
if (os_) *os_ << diff_string<TextWriter>(diff) << endl;
unit_assert(!diff);
b.contactPtr = ContactPtr(new Organization("cid2", "cname2"));
diff(a, b);
if (os_) *os_ << diff_string<TextWriter>(diff) << endl;
unit_assert(diff);
unit_assert(diff.b_a.contactPtr.get());
unit_assert(diff.a_b.contactPtr.get());
unit_assert(diff.a_b.contactPtr->id == "cid");
unit_assert(diff.b_a.contactPtr->id == "cid2");
unit_assert(diff.a_b.contactPtr->name == "cname");
unit_assert(diff.b_a.contactPtr->name == "cname2");
}
void testAnalysisSoftware()
{
if (os_) *os_ << "testAnalysisSoftware()\n";
AnalysisSoftware a, b;
Diff<AnalysisSoftware, DiffConfig> diff(a,b);
unit_assert(!diff);
// a.version
a.version="version";
// b.contactRole
// a.softwareName
// b.URI
b.URI="URI";
// a.customizations
a.customizations="customizations";
diff(a, b);
}
void testDataCollection()
{
if (os_) *os_ << "testDataCollection()\n";
DataCollection a, b;
Diff<DataCollection, DiffConfig> diff(a, b);
unit_assert(!diff);
// a.inputs
a.inputs.sourceFile.push_back(SourceFilePtr(new SourceFile()));
b.inputs.searchDatabase.push_back(SearchDatabasePtr(new SearchDatabase()));
a.inputs.spectraData.push_back(SpectraDataPtr(new SpectraData()));
// b.analysisData
b.analysisData.spectrumIdentificationList.push_back(SpectrumIdentificationListPtr(new SpectrumIdentificationList()));
diff(a, b);
if (os_) *os_ << diff_string<TextWriter>(diff) << endl;
}
void testIdentData()
{
if (os_) *os_ << "testIdentData()\n";
IdentData a, b;
examples::initializeTiny(a);
examples::initializeTiny(b);
Diff<IdentData, DiffConfig> diff(a, b);
unit_assert(!diff);
a.cvs.push_back(CV());
b.analysisSoftwareList.push_back(AnalysisSoftwarePtr(new AnalysisSoftware));
a.auditCollection.push_back(ContactPtr(new Contact()));
b.bibliographicReference.push_back(BibliographicReferencePtr(new BibliographicReference));
// a.analysisSampleCollection
// b.sequenceCollection
// a.analysisCollection
// b.analysisProtocolCollection
// a.dataCollection
// b.bibliographicReference
diff(a, b);
if (os_) *os_ << diff_string<TextWriter>(diff) << endl;
unit_assert(diff);
unit_assert(diff.a_b.cvs.size() == 1);
unit_assert(diff.b_a.cvs.empty());
}
void test()
{
testIdentifiable();
testContact();
testContactRole();
testFragmentArray();
testIonType();
testMeasure();
testPeptideEvidence();
testProteinAmbiguityGroup();
testProteinDetectionHypothesis();
testDataCollection();
testSpectrumIdentificationList();
testProteinDetectionList();
testAnalysisData();
testSearchDatabase();
testSpectraData();
testSourceFile();
testInputs();
testEnzyme();
testEnzymes();
testMassTable();
testResidue();
testAmbiguousResidue();
testFilter();
testDatabaseTranslation();
testSpectrumIdentificationProtocol();
testProteinDetectionProtocol();
testAnalysisProtocolCollection();
testPerson();
testOrganization();
testBibliographicReference();
testProteinDetection();
testSpectrumIdentification();
testAnalysisCollection();
testDBSequence();
testModification();
testSubstitutionModification();
testPeptide();
testSequenceCollection();
testSampleComponent();
testSample();
testSearchModification();
testSpectrumIdentificationItem();
testSpectrumIdentificationResult();
testAnalysisSampleCollection();
testProvider();
testAnalysisSoftware();
testAnalysisSoftware();
testIdentData();
}
int main(int argc, char* argv[])
{
TEST_PROLOG_EX(argc, argv, "_IdentData")
try
{
if (argc>1 && !strcmp(argv[1],"-v")) os_ = &cout;
test();
}
catch (exception& e)
{
TEST_FAILED(e.what())
}
catch (...)
{
TEST_FAILED("Caught unknown exception.")
}
TEST_EPILOG
}
| [
"ming@localhost"
] | ming@localhost |
1377b080d0fdfa25c2424a82328d14033b7c240b | bc7cdf36f7bb5cd09d93719171438a7680f5a604 | /src/server/game/Combat/HostileRefManager.cpp | 85afdf646077a26ffe196b288f6c13e9090623c1 | [] | no_license | bahajan95/BattleCore | 41f03a281770e4903be96a48930bd70a398aae72 | 88d436c9422a433d26fe89aff2ecfb3b11fba778 | refs/heads/master | 2020-04-10T00:49:28.254803 | 2015-05-17T22:10:34 | 2015-05-17T22:10:34 | 50,763,988 | 1 | 3 | null | 2016-01-31T07:43:00 | 2016-01-31T07:43:00 | null | UTF-8 | C++ | false | false | 5,289 | cpp | /*
* Copyright (C) 2008-2015 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "HostileRefManager.h"
#include "ThreatManager.h"
#include "Unit.h"
#include "DBCStructure.h"
#include "SpellMgr.h"
#include "SpellInfo.h"
HostileRefManager::~HostileRefManager()
{
deleteReferences();
}
//=================================================
// send threat to all my hateres for the victim
// The victim is hated than by them as well
// use for buffs and healing threat functionality
void HostileRefManager::threatAssist(Unit* victim, float baseThreat, SpellInfo const* threatSpell)
{
if (getSize() == 0)
return;
HostileReference* ref = getFirst();
float threat = ThreatCalcHelper::calcThreat(victim, iOwner, baseThreat, (threatSpell ? threatSpell->GetSchoolMask() : SPELL_SCHOOL_MASK_NORMAL), threatSpell);
threat /= getSize();
while (ref)
{
if (ThreatCalcHelper::isValidProcess(victim, ref->GetSource()->GetOwner(), threatSpell))
ref->GetSource()->doAddThreat(victim, threat);
ref = ref->next();
}
}
//=================================================
void HostileRefManager::addTempThreat(float threat, bool apply)
{
HostileReference* ref = getFirst();
while (ref)
{
if (apply)
{
if (ref->getTempThreatModifier() == 0.0f)
ref->addTempThreat(threat);
}
else
ref->resetTempThreat();
ref = ref->next();
}
}
//=================================================
void HostileRefManager::addThreatPercent(int32 percent)
{
HostileReference* ref = getFirst();
while (ref)
{
ref->addThreatPercent(percent);
ref = ref->next();
}
}
//=================================================
// The online / offline status is given to the method. The calculation has to be done before
void HostileRefManager::setOnlineOfflineState(bool isOnline)
{
HostileReference* ref = getFirst();
while (ref)
{
ref->setOnlineOfflineState(isOnline);
ref = ref->next();
}
}
//=================================================
// The online / offline status is calculated and set
void HostileRefManager::updateThreatTables()
{
HostileReference* ref = getFirst();
while (ref)
{
ref->updateOnlineStatus();
ref = ref->next();
}
}
//=================================================
// The references are not needed anymore
// tell the source to remove them from the list and free the mem
void HostileRefManager::deleteReferences()
{
HostileReference* ref = getFirst();
while (ref)
{
HostileReference* nextRef = ref->next();
ref->removeReference();
delete ref;
ref = nextRef;
}
}
//=================================================
// delete one reference, defined by faction
void HostileRefManager::deleteReferencesForFaction(uint32 faction)
{
HostileReference* ref = getFirst();
while (ref)
{
HostileReference* nextRef = ref->next();
if (ref->GetSource()->GetOwner()->GetFactionTemplateEntry()->faction == faction)
{
ref->removeReference();
delete ref;
}
ref = nextRef;
}
}
//=================================================
// delete one reference, defined by Unit
void HostileRefManager::deleteReference(Unit* creature)
{
HostileReference* ref = getFirst();
while (ref)
{
HostileReference* nextRef = ref->next();
if (ref->GetSource()->GetOwner() == creature)
{
ref->removeReference();
delete ref;
break;
}
ref = nextRef;
}
}
//=================================================
// set state for one reference, defined by Unit
void HostileRefManager::setOnlineOfflineState(Unit* creature, bool isOnline)
{
HostileReference* ref = getFirst();
while (ref)
{
HostileReference* nextRef = ref->next();
if (ref->GetSource()->GetOwner() == creature)
{
ref->setOnlineOfflineState(isOnline);
break;
}
ref = nextRef;
}
}
//=================================================
void HostileRefManager::UpdateVisibility()
{
HostileReference* ref = getFirst();
while (ref)
{
HostileReference* nextRef = ref->next();
if (!ref->GetSource()->GetOwner()->CanSeeOrDetect(GetOwner()))
{
nextRef = ref->next();
ref->removeReference();
delete ref;
}
ref = nextRef;
}
}
| [
"adonai@xaker.ru"
] | adonai@xaker.ru |
c920a7156d442d5c7df7618ac5e637bd96eafb7b | 5b2574dae711499728be550581c57754fb6531e3 | /Section 5/Video 5.5/main.cpp | 861590ce98e77a2d45b569d20b94c1718b4c8b96 | [
"MIT"
] | permissive | vabtree/Building-Blocks-of-Application-Development-with-C-source | 398398ab5516008a1894d822b87396190280bbec | 38b2a8883be76c7bf0d11605392256150d9f4074 | refs/heads/master | 2022-08-17T19:03:21.156356 | 2018-04-02T11:48:03 | 2018-04-02T11:48:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 735 | cpp | #include <iostream>
#include <vector>
// row -> |--|--|--|
// |--|--|--|
// |--|--|--|
// |--|--|--|
template <typename T = int>
class matrix
{
private:
size_t mRows, mCols;
std::vector<std::vector<T>* > mRowData;
public:
matrix(const size_t& rows, const size_t& cols)
{
mRows = rows;
mCols = cols;
mRowData.reserve(rows);
for (int i = 0; i < mRows; i++)
{
mRowData.push_back(new std::vector<T>(cols));
}
}
std::vector<T>& operator[](const size_t& row_id)
{
return *(mRowData[row_id]);
}
};
int main()
{
matrix<double> md(2, 2);
md[1][1] = 56.4;
std::cout << md[1][1] << std::endl;
return 0;
}
| [
"harshg@packtpub.com"
] | harshg@packtpub.com |
b058d460d924ce7fca3f1edb21e1e2bb1c100360 | 4f1212e6f69f1966d5ca900f6a8d5e5895186098 | /09. geometric objects/Rectangle.h | 8a07b5272bf9ffb34c3a9e4d15bf520cf6781b57 | [] | no_license | ffuis-aljosa/2017-OOP | ca6eb1ea28f88386a1b4ad22a1423960981f4124 | c95b9f5cd12be63f5dfec6fb3a5412012bd2665e | refs/heads/master | 2021-09-01T19:05:36.802715 | 2017-12-28T10:33:21 | 2017-12-28T10:33:21 | 109,244,939 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,208 | h | #ifndef RECTANGLE_H_INCLUDED
#define RECTANGLE_H_INCLUDED
#include "GeometricObject.h"
#include "Point.h"
#include <stdexcept>
using namespace std;
class Rectangle : GeometricObject
{
private:
Point upperLeftVertex;
double width;
double height;
public:
Rectangle(string _name, Point _upperLeftVertex,
double _width, double _height)
: GeometricObject(_name), upperLeftVertex(_upperLeftVertex)
{
setWidth(_width);
setHeight(_height);
}
void setWidth(double _width)
{
if (_width < 0)
throw runtime_error("Sirina ne moze biti manja od 0");
width = _width;
}
void setHeight(double _height)
{
if (_height < 0)
throw runtime_error("Visina ne moze biti manja od 0");
height = _height;
}
double area()
{
return width * height;
}
double circumference()
{
return 2 * (width + height);
}
Point getUpperLeftVertex()
{
return upperLeftVertex;
}
Point getLowerRightVertex()
{
return Point(upperLeftVertex.getX() + width, upperLeftVertex.getY() - height);
}
};
#endif // RECTANGLE_H_INCLUDED
| [
"a.sljuka@ffuis.edu.ba"
] | a.sljuka@ffuis.edu.ba |
1335d1662b3ec750463043fd84e4eb74a85ccda2 | 3ea4848953688c5ff2ca0c3a79b26372cc839dc8 | /reports/MinDegree.h | 7569a9659e4c63ba0ba23e1fca0a571f5c7639fa | [] | no_license | rostam/CGTea | a612b758b3d4448062cbd12b02fe3f0a5ae40f99 | 56291e8c7c5ad54e3d29aaf7a07caf0e4e4f6d57 | refs/heads/master | 2023-08-05T09:54:07.123882 | 2023-07-20T10:39:41 | 2023-07-20T10:39:41 | 212,271,988 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 794 | h | //
// Created by rostam on 15.10.19.
//
#ifndef CGTEA_MINDEGREE_H
#define CGTEA_MINDEGREE_H
#include "ReportInterface.h"
class MinDegree : public ReportInterface{
public:
string report(const Graph& g) override {
int min_degree = boost::num_vertices(g) + 1;
for_each_v_const(g, [&](Ver v){
int deg = boost::out_degree(v, g);
if(deg < min_degree) min_degree = deg;
});
return std::to_string(min_degree);
};
string name() const override {
return "Minimum degree";
};
string description() const override {
return "Minimum degree";
};
string type() const override {
return "int";
};
string category() const override {
return "General";
};
};
#endif //CGTEA_MAXDEGREE_H
| [
"rostamiev@gmail.com"
] | rostamiev@gmail.com |
040e368a17a634ecbc4759a869ffdfd9538b390a | 5108175f21c5c77e31ceca09597f6dc102655451 | /DX11UWA Left Handed/DX11UWA/DX11UWA/Content/ShaderStructures.h | 7468de419d2a1f6cd80304e0406976be16d2406c | [] | no_license | ConnorCraig25/GraphicsIIproject | 61e9c3784e08f82c565ea269dbb8c7be3e395224 | 19d47ef336f60930a2e1f6c36f920a14706758b4 | refs/heads/master | 2020-12-03T10:30:14.165896 | 2017-07-27T01:27:38 | 2017-07-27T01:27:38 | 95,605,355 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 505 | h | #pragma once
namespace DX11UWA
{
// Constant buffer used to send MVP matrices to the vertex shader.
struct ModelViewProjectionConstantBuffer
{
DirectX::XMFLOAT4X4 model;
DirectX::XMFLOAT4X4 view;
DirectX::XMFLOAT4X4 projection;
};
// Used to send per-vertex data to the vertex shader.
struct VertexPositionColor
{
DirectX::XMFLOAT3 pos;
DirectX::XMFLOAT3 color;
};
struct VertexPositionUVNormal
{
DirectX::XMFLOAT3 pos;
DirectX::XMFLOAT3 uv;
DirectX::XMFLOAT3 normal;
};
} | [
"ccraig@fullsail.edu"
] | ccraig@fullsail.edu |
d47ff2f0eb54b46cececd68203388d6c86c06f40 | 1e006c14837be0e7b6ed9a0f5870907638dfd402 | /usr/local/x86_64-pc-linux-gnu/x86_64-pc-linux-gnu/sys-root/usr/include/boost/fusion/container/generation/list_tie.hpp | 376f71d0fac341e358c6807e56a116d66d21af1c | [
"BSL-1.0"
] | permissive | slowfranklin/synology-ds | b9cd512d86ffc4d61949e6d72012b8cff8d58813 | 5a6dc5e1cfde5be3104f412e5a368bc8d615dfa6 | refs/heads/master | 2021-10-24T01:38:38.120574 | 2019-03-20T13:01:12 | 2019-03-20T13:01:12 | 176,933,470 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,502 | hpp | /*=============================================================================
Copyright (c) 2001-2011 Joel de Guzman
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#ifndef BOOST_PP_IS_ITERATING
#if !defined(FUSION_LIST_TIE_07192005_0109)
#define FUSION_LIST_TIE_07192005_0109
#include <boost/preprocessor/iterate.hpp>
#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/repetition/enum_params.hpp>
#include <boost/preprocessor/repetition/enum_binary_params.hpp>
#include <boost/preprocessor/repetition/enum_params_with_a_default.hpp>
#include <boost/preprocessor/repetition/repeat_from_to.hpp>
#include <boost/fusion/container/list/list.hpp>
#if !defined(BOOST_FUSION_DONT_USE_PREPROCESSED_FILES)
#include <boost/fusion/container/generation/detail/preprocessed/list_tie.hpp>
#else
#if defined(__WAVE__) && defined(BOOST_FUSION_CREATE_PREPROCESSED_FILES)
#pragma wave option(preserve: 2, line: 0, output: "detail/preprocessed/list_tie" FUSION_MAX_LIST_SIZE_STR".hpp")
#endif
/*=============================================================================
Copyright (c) 2001-2011 Joel de Guzman
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
This is an auto-generated file. Do not edit!
==============================================================================*/
#if defined(__WAVE__) && defined(BOOST_FUSION_CREATE_PREPROCESSED_FILES)
#pragma wave option(preserve: 1)
#endif
namespace boost { namespace fusion
{
struct void_;
namespace result_of
{
template <
BOOST_PP_ENUM_PARAMS_WITH_A_DEFAULT(
FUSION_MAX_LIST_SIZE, typename T, void_)
, typename Extra = void_
>
struct list_tie;
}
// $$$ shouldn't we remove_reference first to allow references? $$$
#define BOOST_FUSION_REF(z, n, data) BOOST_PP_CAT(T, n)&
#define BOOST_PP_FILENAME_1 <boost/fusion/container/generation/list_tie.hpp>
#define BOOST_PP_ITERATION_LIMITS (1, FUSION_MAX_LIST_SIZE)
#include BOOST_PP_ITERATE()
#undef BOOST_FUSION_REF
}}
#if defined(__WAVE__) && defined(BOOST_FUSION_CREATE_PREPROCESSED_FILES)
#pragma wave option(output: null)
#endif
#endif // BOOST_FUSION_DONT_USE_PREPROCESSED_FILES
#endif
#else // defined(BOOST_PP_IS_ITERATING)
///////////////////////////////////////////////////////////////////////////////
//
// Preprocessor vertical repetition code
//
///////////////////////////////////////////////////////////////////////////////
#define N BOOST_PP_ITERATION()
namespace result_of
{
template <BOOST_PP_ENUM_PARAMS(N, typename T)>
#define TEXT(z, n, text) , text
struct list_tie< BOOST_PP_ENUM_PARAMS(N, T) BOOST_PP_REPEAT_FROM_TO(BOOST_PP_DEC(N), FUSION_MAX_LIST_SIZE, TEXT, void_) >
#undef TEXT
{
typedef list<BOOST_PP_ENUM(N, BOOST_FUSION_REF, _)> type;
};
}
template <BOOST_PP_ENUM_PARAMS(N, typename T)>
BOOST_FUSION_GPU_ENABLED
inline list<BOOST_PP_ENUM(N, BOOST_FUSION_REF, _)>
list_tie(BOOST_PP_ENUM_BINARY_PARAMS(N, T, & _))
{
return list<BOOST_PP_ENUM(N, BOOST_FUSION_REF, _)>(
BOOST_PP_ENUM_PARAMS(N, _));
}
#undef N
#endif // defined(BOOST_PP_IS_ITERATING)
| [
"slow@samba.org"
] | slow@samba.org |
ca46c8696e0983329bcbd1a3e401c1b6f427ddf2 | f8328b71ffbf5ea2b25e9b016b20d9978357b08a | /hw1/src/example2.cpp | 1114614e6d4aa7a3240b4a50d02fd494a1aa5bee | [] | no_license | ChaseCarthen/cs791a | 5aaa351ac5e295966f48b9d40b6bf069f46d69a0 | 6c547c6e3e476938a7cfc958f588a4485acbe411 | refs/heads/master | 2020-04-11T10:05:00.647363 | 2014-09-28T08:48:07 | 2014-09-28T08:48:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,044 | cpp | #include <GL/glew.h>
#include "wx/wx.h"
#include "wx/sizer.h"
#include "wx/glcanvas.h"
#include <example2.h>
#include <shader.h>
#include <iostream>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/rotate_vector.hpp>
#include <gishandler.h>
#include <mainframe.h>
// include OpenGL
#ifdef __WXMAC__
#include "OpenGL/glu.h"
#include "OpenGL/gl.h"
#else
//#include <GL/glu.h>
#include <GL/gl.h>
#endif
using namespace std;
bool initialize();
/*struct Vertex
{
GLfloat position[3];
GLfloat color[3];
};*/
int cs=0;
GLuint program;
GLuint vbo_geometry;
GLuint elements;
GLuint texture;
//uniform locations
GLint loc_mvpmat;// Location of the modelviewprojection matrix in the shader
wxImage image;
//attribute locations
GLint loc_position;
GLint loc_color;
GLint shader_status;
GLint loc_height;
GLint colorm;
float max_height = 2;
//transform matrices
glm::mat4 model;//obj->world each object should have its own model matrix
glm::mat4 view;//world->eye
glm::mat4 projection;//eye->clip
glm::mat4 mvp;//premultiplied modelviewprojection
glm::vec3 position = glm::vec3(1.0, 20.0, 1.0);
glm::vec3 direction = {0,0,1.0};
int w = 640, h = 480;
float angle = 0;
float angle2 = 0;
class MyApp: public wxApp
{
virtual bool OnInit();
wxFrame *frame;
BasicGLPane * glPane;
public:
};
IMPLEMENT_APP(MyApp)
bool MyApp::OnInit()
{
wxBoxSizer* sizer = new wxBoxSizer(wxHORIZONTAL);
//frame = new wxFrame((wxFrame *)NULL, -1, wxT("Hello GL World"), wxPoint(50,50), wxSize(400,200));
int args[] = {WX_GL_RGBA, WX_GL_DOUBLEBUFFER, WX_GL_DEPTH_SIZE, 16, 0};
//glPane = new BasicGLPane( (wxFrame*) frame, args);
//sizer->Add(glPane, 1,wxEXPAND);
//glPane->starter = false;
//frame->SetSizer(sizer);
//frame->SetAutoLayout(true);
//cout << "Initializing!!" << std::endl;
//if(!initialize())
// return false;
//frame->Show();
//glPane->starter = true;
MainFrame *MainWin = new MainFrame(
_("Terrain Opener"), wxPoint(1, 1), wxSize(300, 200));
//MainWin->Show(TRUE); // show the window
SetTopWindow(MainWin); // and finally, set it as the main window
glPane = new BasicGLPane( (wxFrame*) MainWin, args);
sizer->Add(glPane, 1,wxEXPAND);
//glPane->starter = false;
MainWin->SetSizer(sizer);
MainWin->SetAutoLayout(true);
if(!initialize())
return false;
MainWin->Show(true);
return TRUE;
//return true;
}
// some useful events to use
void BasicGLPane::mouseMoved(wxMouseEvent& event) {}
void BasicGLPane::onCharEvent(wxKeyEvent& event)
{
}
void BasicGLPane::mouseDown(wxMouseEvent& event) {}
void BasicGLPane::mouseWheelMoved(wxMouseEvent& event) {}
void BasicGLPane::mouseReleased(wxMouseEvent& event) {}
void BasicGLPane::rightClick(wxMouseEvent& event) {}
void BasicGLPane::mouseLeftWindow(wxMouseEvent& event) {}
void BasicGLPane::keyPressed(wxKeyEvent& event)
{
if(event.GetKeyCode() == wxKeyCode('A'))
{
angle += 90;
}
else if(event.GetKeyCode() == wxKeyCode('D'))
{
angle -= 90;
}
if(event.GetKeyCode() == wxKeyCode('W'))
{
angle2 += 90;
}
else if(event.GetKeyCode() == wxKeyCode('S'))
{
angle2 -= 90;
}
//std::cout << " " << angle << "KEY PRESSLED2" << position.x << ":POSITION" << position.z << std::endl;
// std::cout << " " << angle << "KEY PRESSLED" << position.x << ":POSITION" << position.z << std::endl;
//direction.rotateY(90.0f);
direction = glm::vec3(0,0,1);
direction = glm::rotateY(direction,angle*3.14f/180.f);
direction = glm::rotateX(direction,angle2*3.14f/180.f);
glm::vec3 motionvector = glm::vec3(0,0,0);
if(event.GetKeyCode() == WXK_LEFT)
{
position.x -= 1;
}
if(event.GetKeyCode() == WXK_RIGHT)
{
position.x += 1;
}
if(event.GetKeyCode() == WXK_UP)
{
direction = glm::normalize(direction);
motionvector = 2.f*direction;
}
if(event.GetKeyCode() == WXK_DOWN)
{
direction = glm::normalize(direction);
motionvector = -2.f * direction;
}
position += motionvector;
view = glm::lookAt( position, //Eye Position
glm::vec3(position+direction), //Focus point
glm::vec3(0.0, 1.0, 0.0)); //Positive Y is up
Refresh();
}
void BasicGLPane::keyReleased(wxKeyEvent& event)
{
}
void BasicGLPane::InitializeGLEW()
{
//prepare2DViewport(0,0,getWidth(), getHeight());
// The current canvas has to be set before GLEW can be initialized.
wxGLCanvas::SetCurrent(*m_context);
GLenum err = glewInit();
// If Glew doesn't initialize correctly.
if(GLEW_OK != err)
{
std::cerr << "Error:" << glewGetString(err) << std::endl;
const GLubyte* String = glewGetErrorString(err);
wxMessageBox("GLEW is not initialized");
}
glEnable(GL_TEXTURE_1D);
wxInitAllImageHandlers();
image.LoadFile("colorMap.png");
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_1D, texture);
// sample: specify texture parameters
//glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
//glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
/* Linear filtering usually looks best for text */
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
//glTexParameterf(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
//glTexParameterf(GL_TEXTURE_1D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
// set the active texture
cout << "IMAGE DIM " << image.GetWidth() << " " << image.GetHeight() << endl;
glTexImage1D(GL_TEXTURE_1D, 0, GL_RGB, image.GetWidth(), 0, GL_RGB, GL_UNSIGNED_BYTE,
image.GetData());
}
// Vertices and faces of a simple cube to demonstrate 3D render
// source: http://www.opengl.org/resources/code/samples/glut_examples/examples/cube.c
GLfloat v[8][3];
GLint faces[6][4] = { /* Vertex indices for the 6 faces of a cube. */
{0, 1, 2, 3}, {3, 2, 6, 7}, {7, 6, 5, 4},
{4, 5, 1, 0}, {5, 6, 2, 1}, {7, 4, 0, 3} };
BasicGLPane::BasicGLPane(wxFrame* parent, int* args) :
wxGLCanvas(parent, wxID_ANY, args, wxDefaultPosition, wxDefaultSize, wxFULL_REPAINT_ON_RESIZE)
{
m_context = new wxGLContext(this);
Parent = parent;
// prepare a simple cube to demonstrate 3D render
// source: http://www.opengl.org/resources/code/samples/glut_examples/examples/cube.c
v[0][0] = v[1][0] = v[2][0] = v[3][0] = -1;
v[4][0] = v[5][0] = v[6][0] = v[7][0] = 1;
v[0][1] = v[1][1] = v[4][1] = v[5][1] = -1;
v[2][1] = v[3][1] = v[6][1] = v[7][1] = 1;
v[0][2] = v[3][2] = v[4][2] = v[7][2] = 1;
v[1][2] = v[2][2] = v[5][2] = v[6][2] = -1;
// To avoid flashing on MSW
SetBackgroundStyle(wxBG_STYLE_CUSTOM);
InitializeGLEW();
//parent->SetStatusText( "Welcome to wxWidgets!" );
std::cout << "Creating Context" << getWidth() << " " << getHeight() << std::endl;
//cout << "IMAGE DIMENSIONS" << image.GetWidth() << " " << image.GetHeight() << endl;
//initialize();
}
BasicGLPane::~BasicGLPane()
{
glDeleteProgram(program);
glDeleteBuffers(1, &vbo_geometry);
delete m_context;
}
void BasicGLPane::resized(wxSizeEvent& evt)
{
// wxGLCanvas::OnSize(evt);
glViewport( 0, 0, getWidth(), getHeight());
projection = glm::perspective( 45.0f, //the FoV typically 90 degrees is good which is what this is set to
float(getWidth())/float(getHeight()), //Aspect Ratio, so Circles stay Circular
0.01f, //Distance to the near plane, normally a small value like this
100.0f); //Distance to the far plane,
std::cout << "REFRESHING" << std::endl;
Refresh();
}
/** Inits the OpenGL viewport for drawing in 3D. */
void BasicGLPane::prepare3DViewport(int topleft_x, int topleft_y, int bottomrigth_x, int bottomrigth_y)
{
glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Black Background
glClearDepth(1.0f); // Depth Buffer Setup
glEnable(GL_DEPTH_TEST); // Enables Depth Testing
glDepthFunc(GL_LEQUAL); // The Type Of Depth Testing To Do
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
glEnable(GL_COLOR_MATERIAL);
glViewport(topleft_x, topleft_y, bottomrigth_x-topleft_x, bottomrigth_y-topleft_y);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
float ratio_w_h = (float)(bottomrigth_x-topleft_x)/(float)(bottomrigth_y-topleft_y);
gluPerspective(45 /*view angle*/, ratio_w_h, 0.1 /*clip close*/, 200 /*clip far*/);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
/** Inits the OpenGL viewport for drawing in 2D. */
void BasicGLPane::prepare2DViewport(int topleft_x, int topleft_y, int bottomrigth_x, int bottomrigth_y)
{
glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Black Background
glEnable(GL_TEXTURE_1D); // textures
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_BLEND);
glDisable(GL_DEPTH_TEST);
glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
glViewport(topleft_x, topleft_y, bottomrigth_x-topleft_x, bottomrigth_y-topleft_y);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(topleft_x, bottomrigth_x, bottomrigth_y, topleft_y);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
int BasicGLPane::getWidth()
{
return GetSize().x;
}
int BasicGLPane::getHeight()
{
return GetSize().y;
}
void BasicGLPane::render( wxPaintEvent& evt )
{
if(!IsShown()) return;
//return;
//if(starter)
//{
std::cout << "Rendering" << getWidth() << " " << getHeight() << std::endl;
wxGLCanvas::SetCurrent(*m_context);
wxPaintDC(this); // only to be used in paint events. use wxClientDC to paint outside the paint event
// glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//--Render the scene
//clear the screen
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glClearColor(0.0, 0.0, 0.2, 1.0);
//premultiply the matrix for this example
mvp = projection * view * model;
//enable the shader program
glUseProgram(program);
//upload the matrix to the shader
glUniformMatrix4fv(loc_mvpmat, 1, GL_FALSE, glm::value_ptr(mvp));
glUniform1f(loc_height,max_height);
//set up the Vertex Buffer Object so it can be drawn
glEnableVertexAttribArray(loc_position);
glEnableVertexAttribArray(loc_color);
glEnable(GL_TEXTURE_1D);
glUniform1i(colorm, 0);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_1D, texture);
glBindBuffer(GL_ARRAY_BUFFER, vbo_geometry);
std::cout << loc_position << " " << loc_color << std::endl;
//set pointers into the vbo for each of the attributes(position and color)
glVertexAttribPointer( loc_position,//location of attribute
3,//number of elements
GL_FLOAT,//type
GL_FALSE,//normalized?
sizeof(Vertex),//stride
0);//offset
glVertexAttribPointer( loc_color,
3,
GL_FLOAT,
GL_FALSE,
sizeof(Vertex),
(void*)offsetof(Vertex,color));
// Index buffer
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elements);
// Draw the triangles !
glDrawElements(
GL_LINES, // mode
cs, // count
GL_UNSIGNED_INT, // type
(void*)0 // element array buffer offset
);
//return;
//glDrawArrays(GL_TRIANGLES, 0, 36);//mode, starting index, count
//clean up
glDisableVertexAttribArray(loc_position);
glDisableVertexAttribArray(loc_color);
//swap the buffers
//glutSwapBuffers();
glFlush();
SwapBuffers();
//}
}
bool initialize()
{
GLuint vertex_shader;
GLuint frag_shader;
// A Cube!
Vertex geometry[] = { {{-1.0, -1.0, -1.0}, {0.0, 0.0, 0.0}},
{{-1.0, -1.0, 1.0}, {0.0, 0.0, 1.0}},
{{-1.0, 1.0, 1.0}, {0.0, 1.0, 1.0}},
{{1.0, 1.0, -1.0}, {1.0, 1.0, 0.0}},
{{-1.0, -1.0, -1.0}, {0.0, 0.0, 0.0}},
{{-1.0, 1.0, -1.0}, {0.0, 1.0, 0.0}},
{{1.0, -1.0, 1.0}, {1.0, 0.0, 1.0}},
{{-1.0, -1.0, -1.0}, {0.0, 0.0, 0.0}},
{{1.0, -1.0, -1.0}, {1.0, 0.0, 0.0}},
{{1.0, 1.0, -1.0}, {1.0, 1.0, 0.0}},
{{1.0, -1.0, -1.0}, {1.0, 0.0, 0.0}},
{{-1.0, -1.0, -1.0}, {0.0, 0.0, 0.0}},
{{-1.0, -1.0, -1.0}, {0.0, 0.0, 0.0}},
{{-1.0, 1.0, 1.0}, {0.0, 1.0, 1.0}},
{{-1.0, 1.0, -1.0}, {0.0, 1.0, 0.0}},
{{1.0, -1.0, 1.0}, {1.0, 0.0, 1.0}},
{{-1.0, -1.0, 1.0}, {0.0, 0.0, 1.0}},
{{-1.0, -1.0, -1.0}, {0.0, 0.0, 0.0}},
{{-1.0, 1.0, 1.0}, {0.0, 1.0, 1.0}},
{{-1.0, -1.0, 1.0}, {0.0, 0.0, 1.0}},
{{1.0, -1.0, 1.0}, {1.0, 0.0, 1.0}},
{{1.0, 1.0, 1.0}, {1.0, 1.0, 1.0}},
{{1.0, -1.0, -1.0}, {1.0, 0.0, 0.0}},
{{1.0, 1.0, -1.0}, {1.0, 1.0, 0.0}},
{{1.0, -1.0, -1.0}, {1.0, 0.0, 0.0}},
{{1.0, 1.0, 1.0}, {1.0, 1.0, 1.0}},
{{1.0, -1.0, 1.0}, {1.0, 0.0, 1.0}},
{{1.0, 1.0, 1.0}, {1.0, 1.0, 1.0}},
{{1.0, 1.0, -1.0}, {1.0, 1.0, 0.0}},
{{-1.0, 1.0, -1.0}, {0.0, 1.0, 0.0}},
{{1.0, 1.0, 1.0}, {1.0, 1.0, 1.0}},
{{-1.0, 1.0, -1.0}, {0.0, 1.0, 0.0}},
{{-1.0, 1.0, 1.0}, {0.0, 1.0, 1.0}},
{{1.0, 1.0, 1.0}, {1.0, 1.0, 1.0}},
{{-1.0, 1.0, 1.0}, {0.0, 1.0, 1.0}},
{{1.0, -1.0, 1.0}, {1.0, 0.0, 1.0}}
};
program = glCreateProgram();
vertex_shader = glCreateShader(GL_VERTEX_SHADER);
//shade2 = shader(vertex_shader);
frag_shader = glCreateShader(GL_FRAGMENT_SHADER);
//shade = shader(frag_shader);
shader shade2(vertex_shader);
shader shade(frag_shader);
if(!shade.open("../shaders/frag.shader"))
{
cout << "Failed to open shader" << std::endl;
return false;
}
if(!shade2.open("../shaders/vert.shader"))
{
cout << "Failed to open shader" << endl;
return false;
}
if(!shade.compile())
{
cout << "Failed to compile" << endl;
return false;
}
if(!shade2.compile())
{
cout << "failed to compile" << endl;
}
if(!shade2.link(program))
{
cout << "failed to link" << endl;
}
if(!shade.link(program))
{
cout << "failed to link" << endl;
}
//glTexImage2D(GL_TEXTURE_1D, 0, ship.bytes_per_pixel, ship.width, ship.height, 0, GetDataFormat(), GetDataType(), ship.pixel_data);
//glGetProgramiv(program, GL_LINK_STATUS, &shader_status);
//if(!shader_status)
//{
// std::cerr << "[F] THE SHADER PROGRAM FAILED TO LINK" << std::endl;
// return false;
//}
// Create a Vertex Buffer object to store this vertex info on the GPU
//glGenBuffers(1, &vbo_geometry);
//glBindBuffer(GL_ARRAY_BUFFER, vbo_geometry);
//glBufferData(GL_ARRAY_BUFFER, sizeof(geometry), geometry, GL_STATIC_DRAW);
vector<vector<float>> floatarr = vector<vector<float>>(getRawValuesFromFile("test.pgm"));
if(floatarr.size() == 0)
{
return false;
}
cout << "GOT RAW VALUES! " << floatarr.size() << endl;
float min=100000000,max=-100000;
for(int i =0; i < floatarr.size(); i++)
for(int j = 0; j < floatarr[i].size(); j++)
{
//cout << "LOOP" << j << " " << floatarr[i].size() << endl;
float v = floatarr[i][j];
if(v > max)
{
max = v;
}
if(v < min && v > 0)
{
min = v;
}
if(v < 0)
{
floatarr[i][j] = 0;
}
}
std::cout << "Creating Mesh" << min << " " << max<< std::endl;
cs=fromRawCreateMesh(floatarr,min,max,vbo_geometry,elements);
//Now we set the locations of the attributes and uniforms
//this allows us to access them easily while rendering
loc_position = glGetAttribLocation(program,
const_cast<const char*>("v_position"));
if(loc_position == -1)
{
std::cerr << "[F] POSITION NOT FOUND" << std::endl;
return false;
}
loc_color = glGetAttribLocation(program,
const_cast<const char*>("v_color"));
if(loc_color == -1)
{
std::cerr << "[F] V_COLOR NOT FOUND" << std::endl;
return false;
}
loc_height = glGetUniformLocation(program,
const_cast<const char*>("h"));
if(loc_height == -1)
{
std::cerr << "[F] HEIGHT NOT FOUND" << std::endl;
return false;
}
loc_mvpmat = glGetUniformLocation(program,
const_cast<const char*>("mvpMatrix"));
if(loc_mvpmat == -1)
{
std::cerr << "[F] MVPMATRIX NOT FOUND" << std::endl;
return false;
}
colorm = glGetUniformLocation(program, "tex");
if(colorm == -1)
{
std::cerr << "[F] Color Map NOT FOUND" << std::endl;
return false;
}
std::cout << loc_mvpmat << " " << loc_color << " " << loc_position << std::endl;
//--Init the view and projection matrices
// if you will be having a moving camera the view matrix will need to more dynamic
// ...Like you should update it before you render more dynamic
// for this project having them static will be fine
view = glm::lookAt( glm::vec3(0.0, 5.0, 0.0), //Eye Position
glm::vec3(0, 10.0, 1.0), //Focus point
glm::vec3(0.0, 1.0, 0.0)); //Positive Y is up
// projection = glm::perspective( 45.0f, //the FoV typically 90 degrees is good which is what this is set to
// float(w)/float(h), //Aspect Ratio, so Circles stay Circular
// 0.01f, //Distance to the near plane, normally a small value like this
// 100.0f); //Distance to the far plane,
//enable depth testing
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
return true;
}
| [
"chasec2331@gmail.com"
] | chasec2331@gmail.com |
3c02a2834fddef2c506acd451d4c30b28f958265 | 4f650c5c875862e3869730d8c5987adf84adc391 | /HBSSSE/mwSICARDActX/mwSICARDActXPropPage.h | 0e13fcd52700acdf661cc8ed0b0837cb1e129546 | [] | no_license | shenguotao/SSSE_HeBei | 4cf1bfcc82a23c40c1f0a2a4106f1c04a351f530 | 2eba065fe5dd62818823f78122642a2c1de62dd8 | refs/heads/master | 2021-01-01T05:07:45.948276 | 2017-01-20T15:30:45 | 2017-01-20T15:30:45 | 78,948,994 | 2 | 3 | null | 2017-01-20T15:27:33 | 2017-01-14T15:42:57 | C | GB18030 | C++ | false | false | 586 | h | #pragma once
// mwSICARDActXPropPage.h : CmwSICARDActXPropPage 属性页类的声明。
// CmwSICARDActXPropPage : 有关实现的信息,请参阅 mwSICARDActXPropPage.cpp。
class CmwSICARDActXPropPage : public COlePropertyPage
{
DECLARE_DYNCREATE(CmwSICARDActXPropPage)
DECLARE_OLECREATE_EX(CmwSICARDActXPropPage)
// 构造函数
public:
CmwSICARDActXPropPage();
// 对话框数据
enum { IDD = IDD_PROPPAGE_MWSICARDACTX };
// 实现
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
// 消息映射
protected:
DECLARE_MESSAGE_MAP()
};
| [
"18618219527@163.com"
] | 18618219527@163.com |
c2e1887f2762c8a084f9166f4ce578f62d0c160e | 9f214e4b1c0dd393ef6482d9f45752e888b7fc2c | /include/LinuxTCPClient.h | 5f72605f93941b0fa4f1ec1009bb540c155c24cc | [] | no_license | guedjm/Basic_abstration | dc1991c8e12fd768c1ccd4cf73f8732da901cb4f | cd0e4643575311431f96d4041212ed7320cc7eee | refs/heads/master | 2016-08-11T01:55:22.747166 | 2016-01-07T00:05:38 | 2016-01-07T00:05:38 | 49,168,736 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 784 | h |
#pragma once
#ifndef _WIN32
# include "ITCPClient.h"
# include "myTCPSocket.h"
class LinuxTCPClient : public ITCPClient
{
public:
LinuxTCPClient();
virtual ~LinuxTCPClient();
virtual int closeSock();
virtual int getWriteFd() const;
virtual bool writeAvailable() const;
virtual void writeAvailable(bool);
virtual void prepareData(std::string const &, int);
virtual bool pendingData() const;
virtual int writeData();
virtual int getReadFd() const;
virtual bool readAvailable() const;
virtual void readAvailable(bool);
virtual int readData(std::string &);
virtual int connectTo(std::string const &, short);
private:
bool _writeAvailable;
bool _readAvailable;
int _toSendLen;
std::string _toSend;
myTCPSocket _sock;
};
#endif
| [
"maxime.guedj@epitech.eu"
] | maxime.guedj@epitech.eu |
c5bb7e774e05dd5d67c790765ef044d68e379900 | 8dc84558f0058d90dfc4955e905dab1b22d12c08 | /content/test/gpu_browsertest_helpers.h | bdd296556d3fec426d52c0238120ce00c345ab7d | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | permissive | meniossin/src | 42a95cc6c4a9c71d43d62bc4311224ca1fd61e03 | 44f73f7e76119e5ab415d4593ac66485e65d700a | refs/heads/master | 2022-12-16T20:17:03.747113 | 2020-09-03T10:43:12 | 2020-09-03T10:43:12 | 263,710,168 | 1 | 0 | BSD-3-Clause | 2020-05-13T18:20:09 | 2020-05-13T18:20:08 | null | UTF-8 | C++ | false | false | 895 | h | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CONTENT_TEST_GPU_BROWSERTEST_HELPERS_H_
#define CONTENT_TEST_GPU_BROWSERTEST_HELPERS_H_
#include "base/memory/scoped_refptr.h"
namespace gpu {
class GpuChannelHost;
}
namespace ui {
class ContextProviderCommandBuffer;
}
namespace content {
// Synchronously establishes a connection to the GPU process and returns the
// GpuChannelHost.
scoped_refptr<gpu::GpuChannelHost>
GpuBrowsertestEstablishGpuChannelSyncRunLoop();
// Creates a new ContextProviderCommandBuffer using the provided
// GpuChannelHost.
scoped_refptr<ui::ContextProviderCommandBuffer> GpuBrowsertestCreateContext(
scoped_refptr<gpu::GpuChannelHost> gpu_channel_host);
} // namespace content
#endif // CONTENT_TEST_GPU_BROWSERTEST_HELPERS_H_
| [
"arnaud@geometry.ee"
] | arnaud@geometry.ee |
a4703cf45151c36fe1f049e3e41cffea5370f94c | d4c720f93631097ee048940d669e0859e85eabcf | /chrome/browser/ash/app_restore/app_launch_handler.cc | 5fb075bbddb9418f1362e8cc74517d5ad7459122 | [
"BSD-3-Clause"
] | permissive | otcshare/chromium-src | 26a7372773b53b236784c51677c566dc0ad839e4 | 3b920d87437d9293f654de1f22d3ea341e7a8b55 | refs/heads/webnn | 2023-03-21T03:20:15.377034 | 2023-01-25T21:19:44 | 2023-01-25T21:19:44 | 209,262,645 | 18 | 21 | BSD-3-Clause | 2023-03-23T06:20:07 | 2019-09-18T08:52:07 | null | UTF-8 | C++ | false | false | 8,621 | cc | // Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ash/app_restore/app_launch_handler.h"
#include <utility>
#include <vector>
#include "apps/launcher.h"
#include "base/bind.h"
#include "base/callback.h"
#include "base/task/single_thread_task_runner.h"
#include "chrome/browser/apps/app_service/app_service_proxy.h"
#include "chrome/browser/apps/app_service/app_service_proxy_factory.h"
#include "chrome/browser/apps/app_service/browser_app_launcher.h"
#include "chrome/browser/apps/app_service/metrics/app_platform_metrics.h"
#include "chrome/browser/profiles/profile.h"
#include "components/app_constants/constants.h"
#include "components/app_restore/full_restore_read_handler.h"
#include "components/services/app_service/public/cpp/app_launch_util.h"
#include "components/services/app_service/public/cpp/intent.h"
#include "components/services/app_service/public/cpp/types_util.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/common/extension.h"
namespace ash {
namespace {
// Returns apps::AppTypeName used for metrics.
apps::AppTypeName GetHistogrameAppType(apps::AppType app_type) {
switch (app_type) {
case apps::AppType::kUnknown:
return apps::AppTypeName::kUnknown;
case apps::AppType::kArc:
return apps::AppTypeName::kArc;
case apps::AppType::kBuiltIn:
case apps::AppType::kCrostini:
return apps::AppTypeName::kUnknown;
case apps::AppType::kChromeApp:
return apps::AppTypeName::kChromeApp;
case apps::AppType::kWeb:
return apps::AppTypeName::kWeb;
case apps::AppType::kMacOs:
case apps::AppType::kPluginVm:
case apps::AppType::kStandaloneBrowser:
case apps::AppType::kStandaloneBrowserChromeApp:
case apps::AppType::kRemote:
case apps::AppType::kBorealis:
case apps::AppType::kBruschetta:
case apps::AppType::kExtension:
case apps::AppType::kStandaloneBrowserExtension:
return apps::AppTypeName::kUnknown;
case apps::AppType::kSystemWeb:
return apps::AppTypeName::kSystemWeb;
}
}
} // namespace
AppLaunchHandler::AppLaunchHandler(Profile* profile) : profile_(profile) {}
AppLaunchHandler::~AppLaunchHandler() = default;
bool AppLaunchHandler::HasRestoreData() {
return restore_data_ && !restore_data_->app_id_to_launch_list().empty();
}
void AppLaunchHandler::OnAppUpdate(const apps::AppUpdate& update) {
if (update.AppId() == app_constants::kChromeAppId || !restore_data_ ||
!update.ReadinessChanged()) {
return;
}
if (!apps_util::IsInstalled(update.Readiness())) {
restore_data_->RemoveApp(update.AppId());
return;
}
// If the app is not ready, don't launch the app for the restoration.
if (update.Readiness() != apps::Readiness::kReady)
return;
// If there is no restore data or the launch list for the app is empty, don't
// launch the app.
const auto& app_id_to_launch_list = restore_data_->app_id_to_launch_list();
if (app_id_to_launch_list.find(update.AppId()) ==
app_id_to_launch_list.end()) {
return;
}
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE,
base::BindOnce(&AppLaunchHandler::LaunchApp, GetWeakPtrAppLaunchHandler(),
update.AppType(), update.AppId()));
}
void AppLaunchHandler::OnAppTypeInitialized(apps::AppType app_type) {
// Do nothing: overridden by subclasses.
}
void AppLaunchHandler::OnAppRegistryCacheWillBeDestroyed(
apps::AppRegistryCache* cache) {
apps::AppRegistryCache::Observer::Observe(nullptr);
}
void AppLaunchHandler::LaunchApps() {
// If there is no launch list from the restore data, we don't need to handle
// launching.
const auto& launch_list = restore_data_->app_id_to_launch_list();
if (launch_list.empty())
return;
// Observe AppRegistryCache to get the notification when the app is ready.
DCHECK(
apps::AppServiceProxyFactory::IsAppServiceAvailableForProfile(profile_));
auto* cache = &apps::AppServiceProxyFactory::GetForProfile(profile_)
->AppRegistryCache();
Observe(cache);
for (const auto app_type : cache->InitializedAppTypes()) {
OnAppTypeInitialized(app_type);
}
// Add the app to `app_ids` if there is a launch list from the restore data
// for the app.
std::set<std::string> app_ids;
cache->ForEachApp([&app_ids, &launch_list](const apps::AppUpdate& update) {
if (update.Readiness() == apps::Readiness::kReady &&
launch_list.find(update.AppId()) != launch_list.end()) {
app_ids.insert(update.AppId());
}
});
for (const auto& app_id : app_ids) {
// Chrome browser web pages are restored separately, so we don't need to
// launch browser windows.
if (app_id == app_constants::kChromeAppId)
continue;
LaunchApp(cache->GetAppType(app_id), app_id);
}
}
bool AppLaunchHandler::ShouldLaunchSystemWebAppOrChromeApp(
const std::string& app_id,
const ::app_restore::RestoreData::LaunchList& launch_list) {
return true;
}
void AppLaunchHandler::LaunchApp(apps::AppType app_type,
const std::string& app_id) {
DCHECK(restore_data_);
DCHECK_NE(app_id, app_constants::kChromeAppId);
const auto it = restore_data_->app_id_to_launch_list().find(app_id);
if (it == restore_data_->app_id_to_launch_list().end() ||
it->second.empty()) {
restore_data_->RemoveApp(app_id);
return;
}
switch (app_type) {
case apps::AppType::kArc:
// ArcAppLaunchHandler handles ARC apps restoration and ARC apps
// restoration could be delayed, so return to preserve the restore data
// for ARC apps.
return;
case apps::AppType::kChromeApp:
case apps::AppType::kWeb:
case apps::AppType::kSystemWeb:
case apps::AppType::kStandaloneBrowserChromeApp:
if (ShouldLaunchSystemWebAppOrChromeApp(app_id, it->second))
LaunchSystemWebAppOrChromeApp(app_type, app_id, it->second);
break;
case apps::AppType::kStandaloneBrowser:
// For Lacros, we can't use the AppService launch interface to restore,
// but call Lacros interface to restore with session restore.
return;
case apps::AppType::kBuiltIn:
case apps::AppType::kCrostini:
case apps::AppType::kPluginVm:
case apps::AppType::kUnknown:
case apps::AppType::kMacOs:
case apps::AppType::kRemote:
case apps::AppType::kBorealis:
case apps::AppType::kBruschetta:
case apps::AppType::kExtension:
case apps::AppType::kStandaloneBrowserExtension:
NOTREACHED();
break;
}
restore_data_->RemoveApp(app_id);
}
void AppLaunchHandler::LaunchSystemWebAppOrChromeApp(
apps::AppType app_type,
const std::string& app_id,
const app_restore::RestoreData::LaunchList& launch_list) {
auto* proxy = apps::AppServiceProxyFactory::GetForProfile(profile_);
DCHECK(proxy);
if (app_type == apps::AppType::kChromeApp ||
app_type == apps::AppType::kStandaloneBrowserChromeApp) {
OnExtensionLaunching(app_id);
}
for (const auto& it : launch_list) {
RecordRestoredAppLaunch(GetHistogrameAppType(app_type));
if (it.second->handler_id.has_value()) {
const extensions::Extension* extension =
extensions::ExtensionRegistry::Get(profile_)->GetInstalledExtension(
app_id);
if (extension) {
DCHECK(it.second->file_paths.has_value());
apps::LaunchPlatformAppWithFileHandler(profile_, extension,
it.second->handler_id.value(),
it.second->file_paths.value());
}
continue;
}
// Desk templates may have partial data. See http://crbug/1232520
if (!it.second->container.has_value() ||
!it.second->disposition.has_value() ||
!it.second->display_id.has_value()) {
continue;
}
apps::AppLaunchParams params(
app_id,
static_cast<apps::LaunchContainer>(it.second->container.value()),
static_cast<WindowOpenDisposition>(it.second->disposition.value()),
it.second->override_url.value_or(GURL()),
apps::LaunchSource::kFromFullRestore, it.second->display_id.value(),
it.second->file_paths.has_value() ? it.second->file_paths.value()
: std::vector<base::FilePath>{},
it.second->intent ? it.second->intent->Clone() : nullptr);
params.restore_id = it.first;
proxy->LaunchAppWithParams(std::move(params));
}
}
} // namespace ash
| [
"chromium-scoped@luci-project-accounts.iam.gserviceaccount.com"
] | chromium-scoped@luci-project-accounts.iam.gserviceaccount.com |
58cdcc41ef8e762eaef6c5a07bee85fefb2ea797 | 7f237f107ae6e22a2c4c87b7bf25a2e5cdb05b75 | /Source/Engine/Physics/MotionState.cpp | 434c780c0febd12183f6cd39db9879a8dfc675a0 | [] | no_license | rshageev/Avalanche | 9aecee505104cc0e8149837196c717d595b50e75 | 50e4316590cf2ebb1378390c8fb1256123abf948 | refs/heads/master | 2023-02-22T07:52:16.594639 | 2015-11-11T16:07:18 | 2015-11-11T16:07:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,047 | cpp | #include "stdafx.h"
#include "MotionState.h"
inline btVector3 toBtVec(const Vector3f &vec)
{
return btVector3(vec.x, vec.y, vec.z);
}
inline btQuaternion toBtQuat(const Quaternion &quat)
{
return btQuaternion(quat.x, quat.y, quat.z, quat.w);
}
inline Vector3f toAvVec(const btVector3 &vec)
{
return Vector3f(vec.getX(), vec.getY(), vec.getZ());
}
inline Quaternion toAvQuat(const btQuaternion &quat)
{
return Quaternion(quat.getX(), quat.getY(), quat.getZ(), quat.getW());
}
AvMotionState::AvMotionState(TransformComponent *transform)
: _transform(transform)
{
}
void AvMotionState::SetTransform(TransformComponent *transform)
{
_transform = transform;
}
void AvMotionState::getWorldTransform(btTransform &worldTrans) const
{
worldTrans.setOrigin( toBtVec(_transform->position) );
worldTrans.setRotation( toBtQuat(_transform->rotation) );
}
void AvMotionState::setWorldTransform(const btTransform &worldTrans)
{
_transform->position = toAvVec(worldTrans.getOrigin());
_transform->rotation = toAvQuat(worldTrans.getRotation());
}
| [
"renatsh@playrix.com"
] | renatsh@playrix.com |
2e1a6f8d454a8ae6a43db3f7f7f499022bc39784 | cf58d74018ed456f6a2ec9e9d83ccd4ba41e5a47 | /Hackerrank/absolutepermute.cpp | 25c76f148dfb06a0218ed4739aeb16f7fbd624b2 | [] | no_license | jaishreedhage/Competitive-coding | b0e2a8331e69e044f4b537102b17d3d9a923d985 | df57007a011a10f46e4cceb99a3aca6bc71f1982 | refs/heads/master | 2021-07-14T13:05:13.674795 | 2017-10-20T06:19:57 | 2017-10-20T06:19:57 | 107,639,988 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,038 | cpp | #include <map>
#include <set>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <string>
#include <bitset>
#include <cstdio>
#include <limits>
#include <vector>
#include <climits>
#include <cstring>
#include <cstdlib>
#include <fstream>
#include <numeric>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <unordered_map>
using namespace std;
int main(){
int t;
cin >> t;
for(int a0 = 0; a0 < t; a0++){
int n;
int k;
cin >> n >> k;
int ar[n+1]={0};
int flag=0;
for(int i=1;i<=n;i++){
if(i+k>=1 || i+k<=n){
}
else{
flag=1;
break;
}
}
if(flag==1)
cout<<-1<<endl;
else{
for(int i=1;i<=n;i++)
cout<<ar[i]<<" ";
cout<<endl;
}
}
return 0;
}
| [
"Jaishree_Dhage@Jaishrees-MacBook-Pro.local"
] | Jaishree_Dhage@Jaishrees-MacBook-Pro.local |
fea3041791633f282280de7af474849b18b0caf6 | c348efe40b4afac1de31e1cf93b800510f9d52f6 | /Riverside Community College (RCC)/CIS-17A/Final/Problem3/Prob3TableInherited.cpp | 0095b2352162aa5c42e94adc578caafb7971fedc | [] | no_license | acoustictime/CollegeCode | 5b57dc45459c35694e3df002a587bacc4f99f81a | a8ec647fa4b5a6a90f34f1c8715dfea88cefe6c6 | refs/heads/master | 2020-03-28T19:22:04.384018 | 2018-09-16T18:37:22 | 2018-09-16T18:37:22 | 148,968,472 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 371 | cpp | // Prob3TableInherited.cpp: implementation of the Prob3TableInherited class.
//
//////////////////////////////////////////////////////////////////////
#include "Prob3TableInherited.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
| [
"Acoustictime@James-MacBook-Pro.local"
] | Acoustictime@James-MacBook-Pro.local |
b5380aa233d4df481dd8161a3b664d1bff334eb6 | 0ceac58dc78b4f138dcd4f53f54880d654a64448 | /treeworks/code/mpi/tree_compute.hpp | a705b0b3e305c6c8d0ae0d3cb148629e5972ad40 | [] | no_license | mkmojo/inbox | a68e40b77e0af3f76fe34b0f792c837c287a75a8 | 8651374e1c4b5ded243a517b2e94b1b9a2928679 | refs/heads/master | 2021-05-29T05:51:08.314886 | 2015-10-29T18:05:14 | 2015-10-29T18:05:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,435 | hpp | /***
* Project: TreeWorks
*
* File: tree_compute.hpp
* Created: Mar 25, 2009
*
* Author: Abhinav Sarje <abhinav.sarje@gmail.com>
*/
#ifndef MPI_TREE_COMPUTE_HPP
#define MPI_TREE_COMPUTE_HPP
#include <vector>
#include <iterator>
#include "mpi_data.hpp"
#include "base_tree.hpp"
#include "specialized_generate.hpp"
#include "../jaz/sys_tools.hpp"
namespace tw
{
namespace mpi
{
class TreeCompute {
private:
enum AlgorithmChoice {
none,
local_computation,
no_dependency,
upward_acc_rev,
upward_acc_special,
upward_acc_general,
downward_acc_special,
downward_acc_general,
downward_acc_rev
}; // enum AlgorithmChoice
MPI_data mpi_data_;
public:
TreeCompute(MPI_Comm comm) { mpi_data_ = comm; }
// the upward accumulation special version
template<typename Tree>
bool generate_interaction_set(const Tree& t, UpwardAccumulationGenerate generate,
const typename Tree::tree_node &node,
std::vector<std::vector<typename Tree::tree_node> >& interaction_sets,
AlgorithmChoice& generate_type) {
//std::cout << mpi_data_.rank() << ". This is the curious case "
// << "of upward accumulation." << std::endl;
typedef typename Tree::tree_node tree_node;
std::vector<tree_node> temp_interaction_set;
std::back_insert_iterator<std::vector<tree_node> >
temp_interaction_set_iter(temp_interaction_set);
generate_type = upward_acc_special;
return generate(t, node, temp_interaction_set_iter);
} // generate_interaction_set()
// the downward accumulation special version
template<typename Tree>
bool generate_interaction_set(const Tree& t, DownwardAccumulationGenerate generate,
const typename Tree::tree_node &node,
std::vector<std::vector<typename Tree::tree_node> >& interaction_sets,
AlgorithmChoice& generate_type) {
//std::cout << mpi_data_.rank() << ". This is the curious case "
// << "of downward accumulation." << std::endl;
typedef typename Tree::tree_node tree_node;
std::vector<tree_node> temp_interaction_set;
std::back_insert_iterator<std::vector<tree_node> >
temp_interaction_set_iter(temp_interaction_set);
generate_type = downward_acc_special;
return generate(t, node, temp_interaction_set_iter);
} // generate_interaction_set()
// the general version
template<typename Tree, typename GenerateFunction>
bool generate_interaction_set(const Tree& t, GenerateFunction generate,
const typename Tree::tree_node &node,
std::vector<std::vector<typename Tree::tree_node> >& interaction_sets,
AlgorithmChoice& generate_type) {
//std::cout << mpi_data_.rank() << ". This is the curious case of generality."
// << std::endl;
typedef typename Tree::tree_node tree_node;
std::vector<tree_node> temp_interaction_set;
std::back_insert_iterator<std::vector<tree_node> >
temp_interaction_set_iter(temp_interaction_set);
bool temp_flag = generate(t, node, temp_interaction_set_iter);
interaction_sets.push_back(temp_interaction_set);
generate_type = none;
// test
//std::cout << mpi_data_.rank() << "." << " "
// << temp_interaction_set.size() << std::endl;
/*std::cout << mpi_data_.rank() << ". I-set of " << node.small_cell()
<< ", size = " << temp_interaction_set.size() << std::endl;
for(int i = 0; i < temp_interaction_set.size(); ++ i) {
std::cout << " " << i << ". " << temp_interaction_set[i].is_leaf()
<< " " << temp_interaction_set[i].level()
<< " " << temp_interaction_set[i].small_cell()
<< " " << temp_interaction_set[i].large_cell()
<< " (" << temp_interaction_set[i].parent().proc_id_
<< ", " << temp_interaction_set[i].parent().index_
<< ") " << temp_interaction_set[i].num_children()
<< " " << temp_interaction_set[i].num_points()
<< std::endl;
} // for */
return temp_flag;
} // generate_interaction_set()
template <typename Tree, typename GenerateFunction, typename CombineFunction>
bool operator()(Tree& t, GenerateFunction generate, CombineFunction combine) {
typedef Tree tree_type;
typedef typename Tree::tree_node tree_node;
typedef typename Tree::index_type index_type;
typedef typename Tree::iterator node_iterator;
if(mpi_data_.rank() == 0) std::cout << "+ performing tree compute ... ";
MPI_Barrier(mpi_data_.comm());
double tree_compute_total_time_s = MPI_Wtime();
double generate_time_s = MPI_Wtime();
// there are t.size() nodes in the local tree
// apply generate function to each of them
// and obtain a list of tree_nodes for each
std::vector<std::vector<tree_node> > interaction_sets;
bool dependency_flag = false;
AlgorithmChoice generate_type = none;
// apply generate function on all nodes of the tree
for(node_iterator iter = t.begin(); iter != t.end(); ++ iter) {
//unsigned long int memory = jaz::mem_usage();
//if(mpi_data_.rank() == 0)
// std::cout << mpi_data_.rank() << "." << temp << " Memory used in bytes = "
// << memory << std::endl;
//if(mpi_data_.rank() == 0)
//std::cout << mpi_data_.rank() << ". [" << (*iter).index().proc_id_ << ", "
// << (*iter).index().index_ << "], parent = ("
// << (*iter).parent().proc_id_ << ", "
// << (*iter).parent().index_ << ")" << std::endl;
AlgorithmChoice temp_generate_type = none;
bool temp_flag = generate_interaction_set(t, generate, *iter, interaction_sets,
temp_generate_type);
// check that flag for each call to generate returns the same thing
if(iter == t.begin()) {
dependency_flag = temp_flag;
generate_type = temp_generate_type;
} else {
if(temp_flag != dependency_flag) {
std::cerr << "Grave error: DEPENDENCY_FLAG of all interaction sets "
<< "are not the same! Aborting." << std::endl;
return false;
} // if
if(temp_generate_type != generate_type) {
std::cerr << "Grave error: Conflict in generate_type! Aborting."
<< std::endl;
return false;
} // if
} // if-else
} // for
MPI_Barrier(mpi_data_.comm());
double generate_time_e = MPI_Wtime();
double detection_time_s = MPI_Wtime();
AlgorithmChoice combine_case = none;
// identify the local computation case: each node has itself in its i-set
// each node should have 1 node in its i-set and it shud be itself
// (the dependency flag may be either true or false)
if(generate_type == none) {
int i = 0;
for(node_iterator iter = t.begin(); iter != t.end(); ++ iter, ++ i) {
// check if i-set sizes are == 1
if(interaction_sets[i].size() != 1) break;
// check if the node in i-set is itself
if(!(interaction_sets[i][0].index() == (*iter).index())) break;
} // for
if(i == interaction_sets.size()) generate_type = local_computation;
} // if
if(dependency_flag == false) {
// This is simple, just use each node in the interaction
// set of each local node and perform the computations. Call this case no_dep.
if(generate_type == local_computation) combine_case = local_computation;
else combine_case = no_dependency;
} else {
// if(dependency_flag == true), then using the interaction set of each local node,
// find a local consensus of the levels, the special cases of children/parent only,
// and conditions for uniqueness of parent, and then find a global consensus.
// If there is no global consensus, notify that dependency cannot be satisfied.
// Else, the following cases occur for each local node u and remote node v:
// * upward_acc_rev. each node in at most 1 i-set, and level(u) > level(v)
// * b. each node in at most 1 i-set, and level(u) < level(v)
// * c. each node has at most 1 in i-set, and level(u) > level(v)
// * downward_acc_rev. each node has at most 1 in i-set, and level(u) < level(v)
// Cases upward_acc_rev and b result in upward accumulation (where in
// upward_acc_rev, the tree is upside-down, and b is the original case of
// upward tree accumulation when all v are u's children).
// Cases c and downward_acc_rev result in downward accumulation (where in
// downward_acc_rev, the tree is upside-down, and c is the original case of
// downward tree accumulation).
// Case b -> either one of the following:
// * upward_acc_special: where each all (and only) children are in the i-set.
// * upward_acc_general: the other cases.
// Case c -> either one of the following:
// * downward_acc_special: where only the parent is present in i-set.
// * downward_acc_general: the other cases.
if(generate_type == local_computation) combine_case = local_computation;
else if(generate_type == upward_acc_special) combine_case = upward_acc_special;
else if(generate_type == downward_acc_special) combine_case = downward_acc_special;
else {
// detect the cases for the special cases of upward and downward accumulations
// check for special downward accumulation:
if(combine_case == none) {
//std::cout << "Checking for the special case of downward accumulation"
// << std::endl;
// for each node check if the I-set has only one node in it
// and check about the levels of the nodes
int i = 0;
for(node_iterator iter = t.begin(); iter != t.end(); ++ iter, ++ i) {
if(!(*iter).is_root()) {
// check if i-set sizes are == 1
if(interaction_sets[i].size() != 1) break;
// check if the node in i-set of each node is its parent
if(!interaction_sets[i][0].is_parent(*iter)) break;
} // if
} // for
if(i == interaction_sets.size()) combine_case = downward_acc_special;
} // if
// check for special upward accumulation:
if(combine_case == none) {
//std::cout << "Checking for the special case of upward accumulation"
// << std::endl;
// for each node check if the I-set has same # of nodes as its # of children
// and check for each node if it is its child
int i = 0;
for(node_iterator iter = t.begin(); iter != t.end(); ++ iter, ++ i) {
if(!(*iter).is_leaf()) {
// check if i-set sizes are == num of children
if((*iter).num_children() != interaction_sets[i].size()) break;
// check if the node in i-set of each node is its parent
bool break_flag = false;
for(int j = 0; j < interaction_sets[i].size(); ++j) {
if(!interaction_sets[i][j].is_child(*iter)) {
break_flag = true;
break;
} // if
} // for
if(break_flag) break;
} // if
} // for
if(i == interaction_sets.size()) combine_case = upward_acc_special;
} // if
// implement algorithm detection for other general cases
// ...
} // if-else
} // if-else
MPI_Barrier(mpi_data_.comm());
// find consensus combine_case among all procs
AlgorithmChoice* consensus = new AlgorithmChoice[mpi_data_.size()];
MPI_Allgather(&combine_case, 1, MPI_INT, consensus, 1, MPI_INT, mpi_data_.comm());
for(int i = 0; i < mpi_data_.size(); ++ i) {
if(consensus[i] != combine_case) {
std::cerr << "Error in obtaining consensus for computations! Aborting."
<< std::endl;
return false;
} // if
} // for
double detection_time_e = MPI_Wtime();
// Currently only the special cases, upward_acc_special and downward_acc_special,
// are implemented, were the nodes in the all i-sets are all children, or the parent,
// respectively. In these cases, new dependency forest is not constructed.
double compute_time_s = 0.0;
double compute_time_e = 0.0;
switch(combine_case) {
case local_computation:
// Local computation: apply the combine function to each node locally
//std::cout << "Local computations case." << std::endl;
compute_time_s = MPI_Wtime();
t.local_compute(combine, mpi_data_);
compute_time_e = MPI_Wtime();
break;
case no_dependency:
// look into the paper dealing with this case and do the corresponding
// implementation for special cases if needed.
// All the nodes in the interaction set are already available at the
// local processor, since they were required from the generate function.
//std::cout << mpi_data_.rank() << ". No dependency case." << std::endl;
compute_time_s = MPI_Wtime();
t.no_dependency_compute(combine, interaction_sets, mpi_data_);
compute_time_e = MPI_Wtime();
break;
case upward_acc_special:
// The Upward Accumulation: i-set has all and only the children, for all nodes
//std::cout << "Upward accumulation special case." << std::endl;
compute_time_s = MPI_Wtime();
t.upward_accumulate(combine, mpi_data_);
compute_time_e = MPI_Wtime();
break;
case downward_acc_special:
// The Downward Accumulation: i-set has only one node, and it is the
// parent, for all nodes
//std::cout << "Downward accumulation special case." << std::endl;
compute_time_s = MPI_Wtime();
t.downward_accumulate(combine, mpi_data_);
compute_time_e = MPI_Wtime();
break;
case upward_acc_rev:
case upward_acc_general:
case downward_acc_general:
case downward_acc_rev:
std::cout << "Not yet implemented!" << std::endl;
break;
default:
std::cerr << "Something went very wrong in algorithm detection." << std::endl;
return false;
} // switch
MPI_Barrier(mpi_data_.comm());
double tree_compute_total_time_e = MPI_Wtime();
if(mpi_data_.rank() == 0) {
std::cout << "done: "
<< (tree_compute_total_time_e - tree_compute_total_time_s) * 1000 << "ms"
<< " [g: " << (generate_time_e - generate_time_s) * 1000 << "ms"
<< ", d: " << (detection_time_e - detection_time_s) * 1000 << "ms"
<< ", c: " << (compute_time_e - compute_time_s) * 1000 << "ms]"
<< std::endl;
} // if
// test
/*if(mpi_data_.rank() == 0)
t.print_tree(); */
return true;
} // operator()()
}; // class TreeCompute
} // namespace mpi
} // namespace tw
#endif // MPI_TREE_COMPUTE_HPP
| [
"qiuqiyuan@gmail.com"
] | qiuqiyuan@gmail.com |
83e0c29352716abe2e8369a1cf4e610e6d198000 | 47bc067058e4d45f8729670b1bfa19aceaadc156 | /project_euler/10.cpp | 3116275a0d9f4a6b9e904b3332a6eca6004de9b0 | [] | no_license | return19/All-C-Codes | 0bd0df357cd4bbc6552e1d943df792a1b4d806bb | b1c2269d2436a0cd65a5ef022595300c4827520f | refs/heads/master | 2021-09-09T16:13:53.464406 | 2018-03-17T17:02:55 | 2018-03-17T17:02:55 | 125,650,568 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 717 | cpp | #include<bits/stdc++.h>
using namespace std;
long long s[1010000];
long long csum[1010000];
void solve()
{
long long i,j,k;
s[0]=s[1]=1;
for(i=2;i<1000100;i++)
{
if(s[i]==0)
{
k=2;
for(j=i*2;j<1000100;j=i*k)
{
s[j]=1;
k++;
}
}
}
for(i=2;i<1000100;i++)
{
if(s[i]==0)
{
csum[i]=i;
}
csum[i]+=csum[i-1];
}
}
int main()
{
long long test,i,j,k,t;
long long n;
scanf("%lld",&test);
solve();
for(t=0;t<test;t++)
{
scanf("%lld",&n);
printf("%lld\n",csum[n]);
}
return 0;
}
| [
"abhinandan1941996@gmail.com"
] | abhinandan1941996@gmail.com |
5d9dd011ffbf60e8abe7bcdd8961e6178dfc42dc | 31eae0d913d8b1af8ce0bc5fd516b0844efec1f3 | /Cpp/Modules/Include/LinearTableFunctionProvider.h | d274b9f300f0717c873eca0ca5e849f637fd35f3 | [] | no_license | Olov81/synth3 | 5424c52e8b081d9ebc1b30150f6656da81bd6a31 | 38b9945448b91b459a45da4b5545983ae3cd38a8 | refs/heads/master | 2022-12-19T15:51:00.723366 | 2020-08-19T20:43:17 | 2020-08-19T20:43:17 | 288,816,922 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 326 | h | #pragma once
#include "ILinearFunctionProvider.h"
class LinearTableFunctionProvider : public ILinearFunctionProvider
{
public:
LinearTableFunctionProvider(std::vector<LinearFunction> table);
LinearFunction GetFunction(const double& omega) const override;
private:
std::vector<LinearFunction> _table;
};
| [
"devnull@localhost"
] | devnull@localhost |
8b419af0aefdbf006a81711cd68e1b2ca35ff0af | 8f4b3f8fd51daa17af03fe483ed44cd88c3bf4ce | /ClassTeacher.cpp | 3b8e0d6ea6eaa544721aba482ac8375337c0d7bd | [] | no_license | urm0009/School | 6665d4003cd97a34bee617dff3cbfb1391f5483c | 1ddda8ac1739c09748e4d65ce616e96d27c6d502 | refs/heads/master | 2021-05-23T13:50:26.423884 | 2020-04-05T20:03:40 | 2020-04-05T20:03:40 | 253,321,375 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 27 | cpp | #include "ClassTeacher.h"
| [
"noreply@github.com"
] | urm0009.noreply@github.com |
eee4b829f37254710258b1df7b33f4e1bd34afd5 | fbecd060030896fed648e57493fd9f68e1134a78 | /src/ex12_10.cc | e11fe62689ab98f63b9cac4e2c08bc9fb3a7573a | [] | no_license | amoe/acceleratedcpp | 24e6594742619e3bea66d5f748aa394bf2e967da | 947c73c5b9bdf02f47fe09712f065278f337005e | refs/heads/master | 2023-01-07T15:53:31.586878 | 2020-11-03T08:52:53 | 2020-11-03T08:52:53 | 280,228,131 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,067 | cc | #include <list>
#include <iostream>
#include <vector>
#include "ex12_10.hh"
using std::list;
using std::vector;
using std::cout;
using std::endl;
void test_copy() {
Vec<int> nums;
nums.push_back(8);
nums.push_back(5);
nums.push_back(3);
nums.push_back(2);
Vec<int> nums2 = nums;
for (Vec<int>::const_iterator it = nums2.begin(); it != nums2.end(); it++) {
cout << *it << endl;
}
// This should never show up in the output
nums.push_back(42);
for (Vec<int>::const_iterator it = nums2.begin(); it != nums2.end(); it++) {
cout << *it << endl;
}
}
int main() {
cout << "Starting." << endl;
vector<int> fib1 = {8, 5, 3, 2};
Vec<int> fib2(fib1.begin(), fib1.end());
for (Vec<int>::const_iterator it = fib2.begin(); it != fib2.end(); it++) {
cout << *it << endl;
}
test_copy();
vector<char> foo = {'h', 'e', 'l', 'l', 'o'};
Str s4(foo.begin(), foo.end());
cout << "String value: '" << s4 << "'" << endl;
cout << "End." << endl;
return 0;
}
| [
"amoebae@gmail.com"
] | amoebae@gmail.com |
ac13d267ac51bada4bba07c52f58c392b5df6e17 | d0e9fbbbc0955cc349e04a862baaf48d27f35db5 | /src/Clickable.h | 55af0e97718a25d677b841742b965ca067b638fa | [] | no_license | clementschmitt/DataDefense | b346eb83514ad2b5a85ec7104e578944034b90bb | f45f993ec364db6b46f2d4ad68d64847ad68479f | refs/heads/master | 2021-01-22T06:38:17.205520 | 2013-11-27T16:42:37 | 2013-11-27T16:42:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 273 | h | #ifndef CLICKABLE_H
#define CLICKABLE_H
#include "VisibleGameObject.h"
class Clickable : public VisibleGameObject
{
public:
Clickable();
~Clickable();
void Callback( void (*f)());
void Exec() const;
private:
void (*_callback)();
};
#endif
| [
"mathieu.nerv@gmail.com"
] | mathieu.nerv@gmail.com |
fce426f439629cad0de3b0a89f0f51a20a887cfc | b30c7717acbcace38eaa9e8939b952dc3245ebd6 | /600-700/660.cpp | a98f38427cde48720c9651f24914f35208271531 | [
"MIT"
] | permissive | Thomaw/Project-Euler | e7dbfae93b26eb0d658c09e18fdaa932998d7a12 | bcad5d8a1fd3ebaa06fa52d92d286607e9372a8d | refs/heads/main | 2023-09-06T08:16:35.045015 | 2021-10-07T18:44:42 | 2021-10-07T18:44:42 | 407,856,542 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,315 | cpp | // are a, b, and c together n-pandigital
bool nPanDig[20];
bool nPandigital(int n, int a, int b, int c)
{
for (int u = 0; u < n; u++) nPanDig[u] = false;
int ct = 0, d, aa = a;
while (aa > 0)
{
d = aa % n;
if (nPanDig[d]) return false;
nPanDig[d] = true; ct++; aa /= n;
}
int bb = b;
while (bb > 0)
{
d = bb % n;
if (nPanDig[d]) return false;
nPanDig[d] = true; ct++; bb /= n;
}
int cc = c;
while (cc > 0)
{
d = cc % n;
if (nPanDig[d]) return false;
nPanDig[d] = true; ct++; cc /= n;
}
return (ct == n);
}
// Problem 660: Pandigital Triangles
void Problem660()
{
long long int m, n, a, b, c, aa, bb, cc, ans = 0, mx = 34012224;
m = 2; n = 1; a = m * m + m * n + n * n;
while (a < mx)
{
for (n = 1; n < m; n++)
if (((m - n) % 3) != 0)
if (GCD(m, n) == 1)
{
a = m * m + m * n + n * n;
b = 2 * m * n + n * n;
c = m * m - n * n;
aa = a; bb = b; cc = c;
while (aa < mx)
{
for (int w = 9; w <= 18; w++)
if (nPandigital(w, aa, bb, cc))
{
//cout << w << "-pan: " << aa << ", " << bb << ", " << cc << "\n";
ans += aa; break;
}
aa += a; bb += b; cc += c;
}
}
m++;
}
cout << "Problem 660: " << ans << "\n";
}
| [
"noreply@github.com"
] | Thomaw.noreply@github.com |
e280be99d7c819c83c01308c58ac3dbbcae5be63 | 10f96d8c37877439ae4d13e5248a4540ca85e65b | /src/palette.hpp | 77513384947f0ea43fd9fe4850aca60120ff714a | [] | no_license | jakubcerveny/hogtess | cca2f91ae01614d9a381b75862e24a29c2e84585 | 37508f86ada8d9d217b7181177891dd621ce0c23 | refs/heads/master | 2021-06-06T16:37:21.657442 | 2020-06-06T08:34:13 | 2020-06-06T08:34:13 | 106,323,937 | 13 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 209 | hpp | #ifndef hogtess_palette_hpp_included__
#define hogtess_palette_hpp_included__
const int RGB_Palette_3_Size = 65;
extern float RGB_Palette_3[RGB_Palette_3_Size][3];
#endif // hogtess_palette_hpp_included__
| [
"jakub.cerveny@gmail.com"
] | jakub.cerveny@gmail.com |
54d2f5cc086650db5e114da4bb6f13955cfbd674 | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_5662291475300352_0/C++/IITianUG/GoogleR3.cpp | ce90d7e7f4a9c3f08f881e8684a9f6628df552da | [] | no_license | alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417992 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 744 | cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
ifstream IF;
ofstream OF;
int t,trm,i,d[100],h[100],m[100],n,xx,yy;
IF.open("input.txt");
OF.open("output.txt");
IF>>t;
for(trm=1;trm<=t;trm++)
{
IF>>n;
for(i=0;i<n;i++)
{
IF>>d[i]>>h[i]>>m[i];
}
if(n==1)
OF<<"Case #"<<trm<<": "<<0<<endl;
else {
m[0]=m[0]/360+m[0]%360+d[0];
m[1]=m[1]/360+m[1]%360+d[1];
xx =max(m[0],m[1]);
yy = min(m[0],m[1]);
xx = xx/yy;
if(xx>=2)
OF<<"Case #"<<trm<<": "<<1<<endl;
else OF<<"Case #"<<trm<<": "<<0<<endl;
}
}
IF.close();
OF.close();
return 0;
}
| [
"eewestman@gmail.com"
] | eewestman@gmail.com |
d65424ec0226ae76f8e8256057106525623277a7 | 73851f9774cb398915b9351433fe13d52de1269d | /tests/vtm/FixedSizeMemoryManagerTest.cpp | 7529e1d17352aa53cd022a043c9b0421977973f0 | [
"Apache-2.0"
] | permissive | mvoronoy/OP.MagicTrie | 9aa980de539f6b51da58e920cb6a36ecee163755 | 33ce736d9e68e927eaa4adc0553836036b076e64 | refs/heads/main | 2023-06-24T03:50:53.133460 | 2023-06-15T19:16:22 | 2023-06-15T19:16:22 | 41,084,715 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,627 | cpp | #include <op/utest/unit_test.h>
#include <op/utest/unit_test_is.h>
#include <op/trie/Trie.h>
#include <op/vtm/SegmentManager.h>
#include <op/vtm/CacheManager.h>
#include <op/vtm/EventSourcingSegmentManager.h>
#include <set>
#include <cassert>
#include <iterator>
using namespace OP::trie;
using namespace OP::utest;
static const char *node_file_name = "FixedSizeMemoryManager.test";
static OP_CONSTEXPR(const) unsigned test_nodes_count_c = 101;
template <class FixedSizeMemoryManager, class SegmentTopology>
void test_Generic(OP::utest::TestRuntime &tresult, SegmentTopology& topology)
{
auto &mngr = topology.OP_TEMPL_METH(slot)<FixedSizeMemoryManager>();
auto b100 = mngr.allocate();
mngr.deallocate(b100);
tresult.assert_true(topology.segment_manager().available_segments() == 1);
topology._check_integrity();
std::vector<FarAddress> allocated_addrs(test_nodes_count_c);
//exhaust all nodes in single segment and check new segment allocation
for (auto i = 0; i < test_nodes_count_c; ++i)
{
OP::vtm::TransactionGuard op_g(topology.segment_manager().begin_transaction());
auto pos = mngr.allocate();
auto &wr = *topology.segment_manager().template wr_at<typename FixedSizeMemoryManager::payload_t>(pos);
tresult.assert_true(wr.inc == 57);
wr.inc += i;
op_g.commit();
allocated_addrs[i] = pos;
if ((i + 1) < test_nodes_count_c)
{
tresult.assert_true(
topology.segment_manager().available_segments() == 1,
OP_CODE_DETAILS(<< "There must be single segment"));
}
}
//as soon FixedSizeMemoryManager contains ThreadPool folowing line became probabilistic
//tresult.assert_true(topology.segment_manager().available_segments() == 1,
// OP_CODE_DETAILS(<<"There must be single segment"));
mngr.allocate();
tresult.assert_true(topology.segment_manager().available_segments() == 2,
OP_CODE_DETAILS(<<"New segment must be allocated"));
//test all values kept correct value
for (auto i = 0; i < test_nodes_count_c; ++i)
{
auto to_test = view<typename FixedSizeMemoryManager::payload_t>(topology, allocated_addrs[i]);
tresult.assert_true(i + 57 == to_test->inc, "Invalid value stored");
}
topology._check_integrity();
// now free all in random order and exhaust again
std::random_device rd;
std::mt19937 g(rd());
std::shuffle(allocated_addrs.begin(), allocated_addrs.end(), g);
for (const auto& addr : allocated_addrs)
{
mngr.deallocate(addr);
}
allocated_addrs.clear();
topology._check_integrity();
for (auto i = 0; i < 2*test_nodes_count_c; ++i)
{
OP::vtm::TransactionGuard op_g(topology.segment_manager().begin_transaction());
auto pos = mngr.allocate();
auto& wr = *topology.segment_manager().template wr_at<typename FixedSizeMemoryManager::payload_t>(pos);
tresult.assert_true(wr.inc == 57);
wr.inc += i;
op_g.commit();
allocated_addrs.push_back(pos);
if ((i + 2) < 2 * test_nodes_count_c)
{
tresult.assert_true(topology.segment_manager().available_segments() == 2,
OP_CODE_DETAILS(<< "No new segments must be allocated"));
}
}
//test all values kept correct value
for (auto i = 0; i < 2 * test_nodes_count_c; ++i)
{
auto to_test = view<typename FixedSizeMemoryManager::payload_t>(topology, allocated_addrs[i]);
tresult.assert_true(i + 57 == to_test->inc, "Invalid value stored");
}
}
void test_NodeManager(OP::utest::TestRuntime &tresult)
{
struct TestPayload
{/*The size of Payload selected to be bigger than FixedSizeMemoryManager::ZeroHeader */
TestPayload()
{
v1 = 0;
inc = 57;
v2 = 3.;
}
std::uint64_t v1;
std::uint32_t inc;
double v2;
};
typedef FixedSizeMemoryManager<TestPayload, test_nodes_count_c> test_node_manager_t;
auto tmngr1 = OP::trie::SegmentManager::OP_TEMPL_METH(create_new)<EventSourcingSegmentManager>(
node_file_name,
OP::trie::SegmentOptions()
.segment_size(0x110000));
SegmentTopology<test_node_manager_t> mngrToplogy (tmngr1);
test_Generic<test_node_manager_t>(tresult, mngrToplogy);
}
void test_Multialloc(OP::utest::TestRuntime& tresult)
{
struct TestPayload
{
TestPayload() = delete;
TestPayload(
double ax1, char ac1, int an1)
: x1(ax1), c1(ac1), n1(an1)
{}
TestPayload(const TestPayload&) = default;
double x1;
char c1;
int n1;
};
typedef FixedSizeMemoryManager<TestPayload, test_nodes_count_c> test_node_manager_t;
auto tmngr1 = OP::trie::SegmentManager::OP_TEMPL_METH(create_new) < EventSourcingSegmentManager > (node_file_name,
OP::trie::SegmentOptions()
.segment_size(0x110000));
SegmentTopology<test_node_manager_t> mngrToplogy(tmngr1);
auto &fmm = mngrToplogy.OP_TEMPL_METH(slot)< test_node_manager_t >();
TestPayload generation(5.7, 'a', 11);
OP::vtm::TransactionGuard op_g(mngrToplogy.segment_manager().begin_transaction());
constexpr size_t N = 10;
constexpr size_t const buf_size_c = test_nodes_count_c / N;
FarAddress result[buf_size_c];
fmm.allocate_n(result, std::extent_v<decltype(result)>, [&](size_t i, auto* p) {
return new (p) TestPayload{ generation };
});
op_g.commit();
for (auto i = 0; i < std::extent_v<decltype(result)>; ++i)
{
auto to_test = view<TestPayload>(mngrToplogy, result[i]);
tresult.assert_that<equals>(to_test->c1, generation.c1);
tresult.assert_that<equals>(to_test->n1, generation.n1);
tresult.assert_that<equals>(to_test->x1, generation.x1);
}
mngrToplogy._check_integrity();
for (auto p = std::begin(result); p != std::end(result); ++p)
{
fmm.deallocate(*p);
}
mngrToplogy._check_integrity();
tresult.assert_that<equals>(1, mngrToplogy.segment_manager().available_segments(),
OP_CODE_DETAILS(<<"There must be single segment"));
auto usage = fmm.usage_info();
tresult.assert_that<equals>(0, usage.first,
OP_CODE_DETAILS(<< "All must be free"));
tresult.assert_that<equals>(test_nodes_count_c, usage.second,
OP_CODE_DETAILS(<< "Free count must be:" << test_nodes_count_c));
FarAddress single;
fmm.allocate_n(&single, 0,
[&](size_t i, auto* ) {
tresult.fail("Lambda must not be called for 0-size");
});
tresult.assert_that<equals>(single, FarAddress{});
usage = fmm.usage_info();
tresult.assert_that<equals>(0, usage.first,
OP_CODE_DETAILS(<< "All must be free"));
tresult.assert_that<equals>(test_nodes_count_c, usage.second,
OP_CODE_DETAILS(<< "Free count must be:" << test_nodes_count_c));
generation.c1++, generation.n1++, generation.x1++;
std::vector<FarAddress> buffer;
//as soon as test_nodes_count_c is odd runing allocate_n several times
//going to surpass the segment threshold
for (size_t i = 0, blsz = 1; i < N+N/2; ++i, ++blsz)
{
buffer.resize(buffer.size() + blsz);
auto beg = buffer.end() - blsz;
fmm.allocate_n(&*beg, blsz, [&](size_t i, auto* ptr) {
return new (ptr) TestPayload(generation);
});
for (; beg != buffer.end(); ++beg)
{
auto to_test = view<TestPayload>(mngrToplogy, *beg);
tresult.assert_that<equals>(to_test->c1, generation.c1);
tresult.assert_that<equals>(to_test->n1, generation.n1);
tresult.assert_that<equals>(to_test->x1, generation.x1);
}
}
mngrToplogy._check_integrity();
tresult.assert_that<equals>(2, mngrToplogy.segment_manager().available_segments(),
OP_CODE_DETAILS(<< "There must be one more segment"));
for (const auto& addr : buffer)
{
fmm.deallocate(addr);
}
mngrToplogy._check_integrity();
usage = fmm.usage_info();
tresult.assert_that<equals>(0, usage.first,
OP_CODE_DETAILS(<< "All must be free"));
tresult.assert_that<equals>(2 * test_nodes_count_c, usage.second,
OP_CODE_DETAILS(<< "Free count must be:" << test_nodes_count_c));
}
void test_NodeManagerSmallPayload(OP::utest::TestRuntime &tresult)
{
struct TestPayloadSmall
{/*The size of Payload selected to be smaller than FixedSizeMemoryManager::ZeroHeader */
TestPayloadSmall()
{
inc = 57;
}
std::uint32_t inc;
};
//The size of payload smaller than FixedSizeMemoryManager::ZeroHeader
typedef FixedSizeMemoryManager<TestPayloadSmall, test_nodes_count_c> test_node_manager_t;
auto tmngr1 = OP::trie::SegmentManager::create_new<EventSourcingSegmentManager>(node_file_name,
OP::trie::SegmentOptions()
.segment_size(0x110000));
SegmentTopology<test_node_manager_t> mngrToplogy (tmngr1);
test_Generic<test_node_manager_t>(tresult, mngrToplogy);
}
static auto& module_suite = OP::utest::default_test_suite("FixedSizeMemoryManager")
.declare("general", test_NodeManager)
.declare("multialloc", test_Multialloc)
.declare("small-payload", test_NodeManagerSmallPayload)
;
| [
"mvoronoy@gmail.com"
] | mvoronoy@gmail.com |
d2799c1d768695c8806e5161343dbcc0d2f778f0 | 078d16366463370cc74caea92f9b35e43d9870be | /Module 3/part3-cute_measures/usecases/uc_broadcaster_publishes_sensor_readings/broadcaster_publishes_sensor_readings.h | c256074df44c4af3a904d55b52ac4fb9d3a4d515 | [
"MIT"
] | permissive | PacktPublishing/End-to-End-GUI-development-with-Qt5 | 6cac1289c6b03dbc94435d9c4ee971d7b71049b4 | 8ac713da23aac4b305b12ee1ef6ec60362bcd391 | refs/heads/master | 2023-02-03T09:16:34.581304 | 2023-01-30T09:56:23 | 2023-01-30T09:56:23 | 138,880,448 | 26 | 10 | null | null | null | null | UTF-8 | C++ | false | false | 399 | h | // broadcaster_publishes_sensor_readings.h
#ifndef BROADCASTER_PUBLISHES_SENSOR_READINGS_H
#define BROADCASTER_PUBLISHES_SENSOR_READINGS_H
//#include <QDebug>
namespace entities {
class Sensor;
class Broadcaster;
}
namespace usecases {
bool broadcaster_publishes_sensor_readings(entities::Broadcaster& broadcaster, entities::Sensor& sensor);
}
#endif // BROADCASTER_PUBLISHES_SENSOR_READINGS_H
| [
"35489117+gaurav-packt@users.noreply.github.com"
] | 35489117+gaurav-packt@users.noreply.github.com |
4e3856d5d7110fe9aa79aac856b4c631ff50d06b | cf8ddfc720bf6451c4ef4fa01684327431db1919 | /SDK/ARKSurvivalEvolved_PrimalItemStructure_StoneCeilingWithTrapdoor_classes.hpp | 4ad44ec774b82388273111f2f93c9a0e63c0d025 | [
"MIT"
] | permissive | git-Charlie/ARK-SDK | 75337684b11e7b9f668da1f15e8054052a3b600f | c38ca9925309516b2093ad8c3a70ed9489e1d573 | refs/heads/master | 2023-06-20T06:30:33.550123 | 2021-07-11T13:41:45 | 2021-07-11T13:41:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 983 | hpp | #pragma once
// ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_PrimalItemStructure_StoneCeilingWithTrapdoor_structs.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass PrimalItemStructure_StoneCeilingWithTrapdoor.PrimalItemStructure_StoneCeilingWithTrapdoor_C
// 0x0000 (0x0AE0 - 0x0AE0)
class UPrimalItemStructure_StoneCeilingWithTrapdoor_C : public UPrimalItemStructure_BaseCeilingWithTrapdoor_C
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass PrimalItemStructure_StoneCeilingWithTrapdoor.PrimalItemStructure_StoneCeilingWithTrapdoor_C");
return ptr;
}
void ExecuteUbergraph_PrimalItemStructure_StoneCeilingWithTrapdoor(int EntryPoint);
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"sergey.2bite@gmail.com"
] | sergey.2bite@gmail.com |
d6fa3666291e0e016324b03180fa0fb608a6cc21 | d6a05971f3a5b3ce7ea7b278d100985437b83e31 | /runtime/src/launcher/cpp/androidLauncher.cpp | aa40c34cb02aae3cedb84ac7e10bd377dffcdd0b | [
"Apache-2.0"
] | permissive | ftomassetti/kotlin-native | 66d52a402b3a8a433e932d1ffca0edf969ecf4d6 | f04827cd573792a70a0bea0f4d839ac4c50e42e5 | refs/heads/master | 2021-01-25T00:48:36.181450 | 2017-06-13T09:52:30 | 2017-06-17T18:23:08 | 94,693,619 | 0 | 0 | null | 2017-06-18T14:49:59 | 2017-06-18T14:49:59 | null | UTF-8 | C++ | false | false | 6,701 | cpp | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* 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 "Memory.h"
#include "Natives.h"
#include "Runtime.h"
#include "KString.h"
#include "Types.h"
#ifdef KONAN_ANDROID
#include <unistd.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/socket.h>
#include "androidLauncher.h"
#include <android/log.h>
#define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, "Konan_main", __VA_ARGS__))
#define LOGE(...) ((void)__android_log_print(ANDROID_LOG_ERROR, "Konan_main", __VA_ARGS__))
/* For debug builds, always enable the debug traces in this library */
#ifndef NDEBUG
# define LOGV(...) ((void)__android_log_print(ANDROID_LOG_VERBOSE, "Konan_main", __VA_ARGS__))
#else
# define LOGV(...) ((void)0)
#endif
//--- main --------------------------------------------------------------------//
extern "C" KInt Konan_start(const ObjHeader*);
namespace {
int pipeC, pipeKonan;
NativeActivityState nativeActivityState;
}
extern "C" void getNativeActivityState(NativeActivityState* state) {
state->activity = nativeActivityState.activity;
state->savedState = nativeActivityState.savedState;
state->savedStateSize = nativeActivityState.savedStateSize;
state->looper = nativeActivityState.looper;
}
extern "C" void notifySysEventProcessed() {
int8_t message;
write(pipeKonan, &message, sizeof(message));
}
namespace {
void* entry(void* param) {
ALooper* looper = ALooper_prepare(ALOOPER_PREPARE_ALLOW_NON_CALLBACKS);
ALooper_addFd(looper, pipeKonan, LOOPER_ID_SYS, ALOOPER_EVENT_INPUT, NULL, NULL);
nativeActivityState.looper = looper;
RuntimeState* state = InitRuntime();
if (state == nullptr) {
LOGE("Unable to init runtime\n");
return nullptr;
}
KInt exitStatus;
{
ObjHolder args;
AllocArrayInstance(theArrayTypeInfo, 0, args.slot());
exitStatus = Konan_start(args.obj());
}
DeinitRuntime(state);
return nullptr;
}
void runKonan_start() {
int pipes[2];
if (socketpair(AF_UNIX, SOCK_STREAM, 0, pipes)) {
LOGE("Could not create pipe: %s", strerror(errno));
return;
}
pipeC = pipes[0];
pipeKonan = pipes[1];
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
pthread_t thread;
pthread_create(&thread, &attr, entry, nullptr);
}
void putEventSynchronously(void* event) {
uint64_t value = static_cast<uint64_t>(reinterpret_cast<uintptr_t>(event));
if (write(pipeC, &value, sizeof(value)) != sizeof(value)) {
LOGE("Failure writing event: %s\n", strerror(errno));
}
int8_t response;
if (read(pipeC, &response, sizeof(response)) != sizeof(response)) {
LOGE("Failure reading response: %s\n", strerror(errno));
}
}
void onDestroy(ANativeActivity* activity) {
LOGV("onDestroy called");
NativeActivityEvent event = { DESTROY };
putEventSynchronously(&event);
}
void onStart(ANativeActivity* activity) {
LOGV("onStart called");
NativeActivityEvent event = { START };
putEventSynchronously(&event);
}
void onResume(ANativeActivity* activity) {
LOGV("onResume called");
NativeActivitySaveStateEvent event = { RESUME };
putEventSynchronously(&event);
}
void* onSaveInstanceState(ANativeActivity* activity, size_t* outLen) {
LOGV("onSaveInstanceState called");
NativeActivitySaveStateEvent event = { SAVE_INSTANCE_STATE };
putEventSynchronously(&event);
*outLen = event.savedStateSize;
return event.savedState;
}
void onPause(ANativeActivity* activity) {
LOGV("onPause called");
NativeActivityEvent event = { PAUSE };
putEventSynchronously(&event);
}
void onStop(ANativeActivity* activity) {
LOGV("onStop called");
NativeActivityEvent event = { STOP };
putEventSynchronously(&event);
}
void onConfigurationChanged(ANativeActivity* activity) {
LOGV("onConfigurationChanged called");
NativeActivityEvent event = { CONFIGURATION_CHANGED };
putEventSynchronously(&event);
}
void onLowMemory(ANativeActivity* activity) {
LOGV("onLowMemory called");
NativeActivityEvent event = { LOW_MEMORY };
putEventSynchronously(&event);
}
void onWindowFocusChanged(ANativeActivity* activity, int focused) {
LOGV("onWindowFocusChanged called");
NativeActivityEvent event = { focused ? WINDOW_GAINED_FOCUS : WINDOW_LOST_FOCUS };
putEventSynchronously(&event);
}
void onNativeWindowCreated(ANativeActivity* activity, ANativeWindow* window) {
LOGV("onNativeWindowCreated called");
NativeActivityWindowEvent event = { NATIVE_WINDOW_CREATED, window };
putEventSynchronously(&event);
}
void onNativeWindowDestroyed(ANativeActivity* activity, ANativeWindow* window) {
LOGV("onNativeWindowDestroyed called");
NativeActivityWindowEvent event = { NATIVE_WINDOW_DESTROYED, window };
putEventSynchronously(&event);
}
void onInputQueueCreated(ANativeActivity* activity, AInputQueue* queue) {
LOGV("onInputQueueCreated called");
NativeActivityQueueEvent event = { INPUT_QUEUE_CREATED, queue };
putEventSynchronously(&event);
}
void onInputQueueDestroyed(ANativeActivity* activity, AInputQueue* queue) {
LOGV("onInputQueueDestroyed called");
NativeActivityQueueEvent event = { INPUT_QUEUE_DESTROYED, queue };
putEventSynchronously(&event);
}
}
extern "C" void Konan_main(ANativeActivity* activity, void* savedState, size_t savedStateSize) {
nativeActivityState = {activity, savedState, savedStateSize};
activity->callbacks->onDestroy = onDestroy;
activity->callbacks->onStart = onStart;
activity->callbacks->onResume = onResume;
activity->callbacks->onSaveInstanceState = onSaveInstanceState;
activity->callbacks->onPause = onPause;
activity->callbacks->onStop = onStop;
activity->callbacks->onConfigurationChanged = onConfigurationChanged;
activity->callbacks->onLowMemory = onLowMemory;
activity->callbacks->onWindowFocusChanged = onWindowFocusChanged;
activity->callbacks->onNativeWindowCreated = onNativeWindowCreated;
activity->callbacks->onNativeWindowDestroyed = onNativeWindowDestroyed;
activity->callbacks->onInputQueueCreated = onInputQueueCreated;
activity->callbacks->onInputQueueDestroyed = onInputQueueDestroyed;
runKonan_start();
}
#endif // KONAN_ANDROID | [
"igor.chevdar@jetbrains.com"
] | igor.chevdar@jetbrains.com |
ba7cfa5d9d25fdd901bac35863af4c0aca5a7430 | 4ccf7aa23ae97ce06ebbea5ecb311d9e5604d28a | /unfinished/mainD.cpp | 310e4698069a68759500abb16135315c1f4865ff | [
"LicenseRef-scancode-other-permissive",
"MIT"
] | permissive | TieWay59/HappyACEveryday | 25682d30aafed3a51f645562fb7e5348e9515417 | 6474a05a9eafc83e9c185ba8e6d716f7d44eade0 | refs/heads/master | 2021-08-22T21:29:31.138853 | 2021-06-16T04:19:14 | 2021-06-16T04:19:14 | 190,430,779 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,615 | cpp | /*
* https://nanti.jisuanke.com/t/41402
*
*/
//#include <bits/stdc++.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <string.h>
#include <tuple>
#define _debug(x) cerr<<#x<<" = "<<x<<endl
using namespace std;
typedef long long ll;
const int MAXN = 2e3 + 59;
const int MAXM = 2e5 + 59;
const ll MOD = 998244353;
const ll INF = 0x0f0f0f0f;
int kase;
int n, m;
// 1 6 12 40
int main() {
// ios_base::sync_with_stdio(false);
// cin.tie(nullptr);
scanf("%d", &n);
ll ans = 0;
for (ll i = 1; i <= n; ++i) {
for (ll j = 1; j <= n; ++j) {
for (ll k = 1; k <= n; ++k) {
for (ll l = 1; l <= n; ++l) {
for (ll i1 = 1; i1 <= n; ++i1) {
for (int k1 = 1; k1 <= n; ++k1) {
for (int l1 = 1; l1 <= n; ++l1) {
for (int m1 = 1; m1 <= n; ++m1) {
if (i + j + k + l + i1 + k1 + l1 + m1 == i * j * k * l * i1 * k1 * l1 * m1) {
// _debug(i);
// _debug(j);
// _debug(k);
// _debug(l);
// _debug(i1);
// cerr << "===================" << endl;
ans++;
}
}
}
}
}
}
}
}
}
printf("%lld\n", ans);
return 0;
} | [
"tieway59@foxmail.com"
] | tieway59@foxmail.com |
67bccfce5c0cd898027f2a4696ca5583b53658da | 6d8109ce6bf17d3a15c6c4f5afa822f5457cdd72 | /src/discrete_space_information/environment_navxythetalat.cpp | f0802ef14deb265466f11f8bdce723cf2482a34e | [] | no_license | shivamvats/sbpl_mha | f7678b50cebed87305749ad00aa59789e6146987 | 03f7201525873a9cd8ec71a29a1f362821d62506 | refs/heads/master | 2021-01-18T02:35:58.234264 | 2016-06-01T18:25:26 | 2016-06-01T18:25:26 | 60,197,949 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 121,106 | cpp | /*
* Copyright (c) 2008, Maxim Likhachev
* 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 University of Pennsylvania 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.
*/
#include <cmath>
#include <cstring>
#include <ctime>
#include <sbpl/discrete_space_information/environment_navxythetalat.h>
#include <sbpl/utils/2Dgridsearch.h>
#include <sbpl/utils/key.h>
#include <sbpl/utils/mdp.h>
#include <sbpl/utils/mdpconfig.h>
using namespace std;
#if TIME_DEBUG
static clock_t time3_addallout = 0;
static clock_t time_gethash = 0;
static clock_t time_createhash = 0;
static clock_t time_getsuccs = 0;
#endif
static long int checks = 0;
#define XYTHETA2INDEX(X,Y,THETA) (THETA + X*EnvNAVXYTHETALATCfg.NumThetaDirs + \
Y*EnvNAVXYTHETALATCfg.EnvWidth_c*EnvNAVXYTHETALATCfg.NumThetaDirs)
//-----------------constructors/destructors-------------------------------
EnvironmentNAVXYTHETALATTICE::EnvironmentNAVXYTHETALATTICE()
{
EnvNAVXYTHETALATCfg.obsthresh = ENVNAVXYTHETALAT_DEFAULTOBSTHRESH;
//the value that pretty much makes it disabled
EnvNAVXYTHETALATCfg.cost_inscribed_thresh = EnvNAVXYTHETALATCfg.obsthresh;
//the value that pretty much makes it disabled
EnvNAVXYTHETALATCfg.cost_possibly_circumscribed_thresh = -1;
grid2Dsearchfromstart = NULL;
grid2Dsearchfromgoal = NULL;
bNeedtoRecomputeStartHeuristics = true;
bNeedtoRecomputeGoalHeuristics = true;
iteration = 0;
EnvNAVXYTHETALAT.bInitialized = false;
EnvNAVXYTHETALATCfg.actionwidth = NAVXYTHETALAT_DEFAULT_ACTIONWIDTH;
EnvNAVXYTHETALATCfg.NumThetaDirs = NAVXYTHETALAT_THETADIRS;
//no memory allocated in cfg yet
EnvNAVXYTHETALATCfg.Grid2D = NULL;
EnvNAVXYTHETALATCfg.ActionsV = NULL;
EnvNAVXYTHETALATCfg.PredActionsV = NULL;
}
EnvironmentNAVXYTHETALATTICE::~EnvironmentNAVXYTHETALATTICE()
{
SBPL_PRINTF("destroying XYTHETALATTICE\n");
if (grid2Dsearchfromstart != NULL) delete grid2Dsearchfromstart;
grid2Dsearchfromstart = NULL;
if (grid2Dsearchfromgoal != NULL) delete grid2Dsearchfromgoal;
grid2Dsearchfromgoal = NULL;
if (EnvNAVXYTHETALATCfg.Grid2D != NULL) {
for (int x = 0; x < EnvNAVXYTHETALATCfg.EnvWidth_c; x++)
delete[] EnvNAVXYTHETALATCfg.Grid2D[x];
delete[] EnvNAVXYTHETALATCfg.Grid2D;
EnvNAVXYTHETALATCfg.Grid2D = NULL;
}
//delete actions
if (EnvNAVXYTHETALATCfg.ActionsV != NULL) {
for (int tind = 0; tind < EnvNAVXYTHETALATCfg.NumThetaDirs; tind++)
delete[] EnvNAVXYTHETALATCfg.ActionsV[tind];
delete[] EnvNAVXYTHETALATCfg.ActionsV;
EnvNAVXYTHETALATCfg.ActionsV = NULL;
}
if (EnvNAVXYTHETALATCfg.PredActionsV != NULL) {
delete[] EnvNAVXYTHETALATCfg.PredActionsV;
EnvNAVXYTHETALATCfg.PredActionsV = NULL;
}
}
//---------------------------------------------------------------------
//-------------------problem specific and local functions---------------------
static unsigned int inthash(unsigned int key)
{
key += (key << 12);
key ^= (key >> 22);
key += (key << 4);
key ^= (key >> 9);
key += (key << 10);
key ^= (key >> 2);
key += (key << 7);
key ^= (key >> 12);
return key;
}
void EnvironmentNAVXYTHETALATTICE::SetConfiguration(int width, int height, const unsigned char* mapdata, int startx,
int starty, int starttheta, int goalx, int goaly, int goaltheta,
double cellsize_m, double nominalvel_mpersecs,
double timetoturn45degsinplace_secs,
const vector<sbpl_2Dpt_t> & robot_perimeterV)
{
EnvNAVXYTHETALATCfg.EnvWidth_c = width;
EnvNAVXYTHETALATCfg.EnvHeight_c = height;
EnvNAVXYTHETALATCfg.StartX_c = startx;
EnvNAVXYTHETALATCfg.StartY_c = starty;
EnvNAVXYTHETALATCfg.StartTheta = starttheta;
if (EnvNAVXYTHETALATCfg.StartX_c < 0 || EnvNAVXYTHETALATCfg.StartX_c >= EnvNAVXYTHETALATCfg.EnvWidth_c) {
SBPL_ERROR("ERROR: illegal start coordinates\n");
throw new SBPL_Exception();
}
if (EnvNAVXYTHETALATCfg.StartY_c < 0 || EnvNAVXYTHETALATCfg.StartY_c >= EnvNAVXYTHETALATCfg.EnvHeight_c) {
SBPL_ERROR("ERROR: illegal start coordinates\n");
throw new SBPL_Exception();
}
if (EnvNAVXYTHETALATCfg.StartTheta < 0 || EnvNAVXYTHETALATCfg.StartTheta >= EnvNAVXYTHETALATCfg.NumThetaDirs) {
SBPL_ERROR("ERROR: illegal start coordinates for theta\n");
throw new SBPL_Exception();
}
EnvNAVXYTHETALATCfg.EndX_c = goalx;
EnvNAVXYTHETALATCfg.EndY_c = goaly;
EnvNAVXYTHETALATCfg.EndTheta = goaltheta;
if (EnvNAVXYTHETALATCfg.EndX_c < 0 || EnvNAVXYTHETALATCfg.EndX_c >= EnvNAVXYTHETALATCfg.EnvWidth_c) {
SBPL_ERROR("ERROR: illegal goal coordinates\n");
throw new SBPL_Exception();
}
if (EnvNAVXYTHETALATCfg.EndY_c < 0 || EnvNAVXYTHETALATCfg.EndY_c >= EnvNAVXYTHETALATCfg.EnvHeight_c) {
SBPL_ERROR("ERROR: illegal goal coordinates\n");
throw new SBPL_Exception();
}
if (EnvNAVXYTHETALATCfg.EndTheta < 0 || EnvNAVXYTHETALATCfg.EndTheta >= EnvNAVXYTHETALATCfg.NumThetaDirs) {
SBPL_ERROR("ERROR: illegal goal coordinates for theta\n");
throw new SBPL_Exception();
}
EnvNAVXYTHETALATCfg.FootprintPolygon = robot_perimeterV;
EnvNAVXYTHETALATCfg.nominalvel_mpersecs = nominalvel_mpersecs;
EnvNAVXYTHETALATCfg.cellsize_m = cellsize_m;
EnvNAVXYTHETALATCfg.timetoturn45degsinplace_secs = timetoturn45degsinplace_secs;
//allocate the 2D environment
EnvNAVXYTHETALATCfg.Grid2D = new unsigned char*[EnvNAVXYTHETALATCfg.EnvWidth_c];
for (int x = 0; x < EnvNAVXYTHETALATCfg.EnvWidth_c; x++) {
EnvNAVXYTHETALATCfg.Grid2D[x] = new unsigned char[EnvNAVXYTHETALATCfg.EnvHeight_c];
}
//environment:
if (0 == mapdata) {
for (int y = 0; y < EnvNAVXYTHETALATCfg.EnvHeight_c; y++) {
for (int x = 0; x < EnvNAVXYTHETALATCfg.EnvWidth_c; x++) {
EnvNAVXYTHETALATCfg.Grid2D[x][y] = 0;
}
}
}
else {
for (int y = 0; y < EnvNAVXYTHETALATCfg.EnvHeight_c; y++) {
for (int x = 0; x < EnvNAVXYTHETALATCfg.EnvWidth_c; x++) {
EnvNAVXYTHETALATCfg.Grid2D[x][y] = mapdata[x + y * width];
}
}
}
}
void EnvironmentNAVXYTHETALATTICE::ReadConfiguration(FILE* fCfg)
{
//read in the configuration of environment and initialize EnvNAVXYTHETALATCfg structure
char sTemp[1024], sTemp1[1024];
int dTemp;
int x, y;
//discretization(cells)
if (fscanf(fCfg, "%s", sTemp) != 1) {
SBPL_ERROR("ERROR: ran out of env file early (discretization)\n");
throw new SBPL_Exception();
}
strcpy(sTemp1, "discretization(cells):");
if (strcmp(sTemp1, sTemp) != 0) {
SBPL_ERROR("ERROR: configuration file has incorrect format (discretization)\n");
SBPL_PRINTF("Expected %s got %s\n", sTemp1, sTemp);
throw new SBPL_Exception();
}
if (fscanf(fCfg, "%s", sTemp) != 1) {
SBPL_ERROR("ERROR: ran out of env file early (discretization)\n");
throw new SBPL_Exception();
}
EnvNAVXYTHETALATCfg.EnvWidth_c = atoi(sTemp);
if (fscanf(fCfg, "%s", sTemp) != 1) {
SBPL_ERROR("ERROR: ran out of env file early (discretization)\n");
throw new SBPL_Exception();
}
EnvNAVXYTHETALATCfg.EnvHeight_c = atoi(sTemp);
// Scan for optional NumThetaDirs parameter. Check for following obsthresh.
if (fscanf(fCfg, "%s", sTemp) != 1) {
SBPL_ERROR("ERROR: ran out of env file early\n");
throw new SBPL_Exception();
}
strcpy(sTemp1, "NumThetaDirs:");
if (strcmp(sTemp1, sTemp) != 0) {
// optional NumThetaDirs not available; default is NAVXYTHETALAT_THETADIRS (16)
strcpy(sTemp1, "obsthresh:");
if (strcmp(sTemp1, sTemp) != 0) {
SBPL_ERROR("ERROR: configuration file has incorrect format\n");
SBPL_PRINTF("Expected %s got %s\n", sTemp1, sTemp);
throw new SBPL_Exception();
}
else {
EnvNAVXYTHETALATCfg.NumThetaDirs = NAVXYTHETALAT_THETADIRS;
}
}
else {
if (fscanf(fCfg, "%s", sTemp) != 1) {
SBPL_ERROR("ERROR: ran out of env file early (NumThetaDirs)\n");
throw new SBPL_Exception();
}
EnvNAVXYTHETALATCfg.NumThetaDirs = atoi(sTemp);
//obsthresh:
if (fscanf(fCfg, "%s", sTemp) != 1) {
SBPL_ERROR("ERROR: ran out of env file early (obsthresh)\n");
throw new SBPL_Exception();
}
strcpy(sTemp1, "obsthresh:");
if (strcmp(sTemp1, sTemp) != 0) {
SBPL_ERROR("ERROR: configuration file has incorrect format\n");
SBPL_PRINTF("Expected %s got %s\n", sTemp1, sTemp);
SBPL_PRINTF("see existing examples of env files for the right format of heading\n");
throw new SBPL_Exception();
}
}
// obsthresh
if (fscanf(fCfg, "%s", sTemp) != 1) {
SBPL_ERROR("ERROR: ran out of env file early\n");
throw new SBPL_Exception();
}
EnvNAVXYTHETALATCfg.obsthresh = atoi(sTemp);
SBPL_PRINTF("obsthresh = %d\n", EnvNAVXYTHETALATCfg.obsthresh);
//cost_inscribed_thresh:
if (fscanf(fCfg, "%s", sTemp) != 1) {
SBPL_ERROR("ERROR: ran out of env file early\n");
throw new SBPL_Exception();
}
strcpy(sTemp1, "cost_inscribed_thresh:");
if (strcmp(sTemp1, sTemp) != 0) {
SBPL_ERROR("ERROR: configuration file has incorrect format\n");
SBPL_PRINTF("Expected %s got %s\n", sTemp1, sTemp);
SBPL_PRINTF("see existing examples of env files for the right format of heading\n");
throw new SBPL_Exception();
}
if (fscanf(fCfg, "%s", sTemp) != 1) {
SBPL_ERROR("ERROR: ran out of env file early\n");
throw new SBPL_Exception();
}
EnvNAVXYTHETALATCfg.cost_inscribed_thresh = atoi(sTemp);
SBPL_PRINTF("cost_inscribed_thresh = %d\n", EnvNAVXYTHETALATCfg.cost_inscribed_thresh);
//cost_possibly_circumscribed_thresh:
if (fscanf(fCfg, "%s", sTemp) != 1) {
SBPL_ERROR("ERROR: ran out of env file early\n");
throw new SBPL_Exception();
}
strcpy(sTemp1, "cost_possibly_circumscribed_thresh:");
if (strcmp(sTemp1, sTemp) != 0) {
SBPL_ERROR("ERROR: configuration file has incorrect format\n");
SBPL_PRINTF("Expected %s got %s\n", sTemp1, sTemp);
SBPL_PRINTF("see existing examples of env files for the right format of heading\n");
throw new SBPL_Exception();
}
if (fscanf(fCfg, "%s", sTemp) != 1) {
SBPL_ERROR("ERROR: ran out of env file early\n");
throw new SBPL_Exception();
}
EnvNAVXYTHETALATCfg.cost_possibly_circumscribed_thresh = atoi(sTemp);
SBPL_PRINTF("cost_possibly_circumscribed_thresh = %d\n", EnvNAVXYTHETALATCfg.cost_possibly_circumscribed_thresh);
//cellsize
if (fscanf(fCfg, "%s", sTemp) != 1) {
SBPL_ERROR("ERROR: ran out of env file early\n");
throw new SBPL_Exception();
}
strcpy(sTemp1, "cellsize(meters):");
if (strcmp(sTemp1, sTemp) != 0) {
SBPL_ERROR("ERROR: configuration file has incorrect format\n");
SBPL_PRINTF("Expected %s got %s\n", sTemp1, sTemp);
throw new SBPL_Exception();
}
if (fscanf(fCfg, "%s", sTemp) != 1) {
SBPL_ERROR("ERROR: ran out of env file early\n");
throw new SBPL_Exception();
}
EnvNAVXYTHETALATCfg.cellsize_m = atof(sTemp);
//speeds
if (fscanf(fCfg, "%s", sTemp) != 1) {
SBPL_ERROR("ERROR: ran out of env file early\n");
throw new SBPL_Exception();
}
strcpy(sTemp1, "nominalvel(mpersecs):");
if (strcmp(sTemp1, sTemp) != 0) {
SBPL_ERROR("ERROR: configuration file has incorrect format\n");
SBPL_PRINTF("Expected %s got %s\n", sTemp1, sTemp);
throw new SBPL_Exception();
}
if (fscanf(fCfg, "%s", sTemp) != 1) {
SBPL_ERROR("ERROR: ran out of env file early\n");
throw new SBPL_Exception();
}
EnvNAVXYTHETALATCfg.nominalvel_mpersecs = atof(sTemp);
if (fscanf(fCfg, "%s", sTemp) != 1) {
SBPL_ERROR("ERROR: ran out of env file early\n");
throw new SBPL_Exception();
}
strcpy(sTemp1, "timetoturn45degsinplace(secs):");
if (strcmp(sTemp1, sTemp) != 0) {
SBPL_ERROR("ERROR: configuration file has incorrect format\n");
SBPL_PRINTF("Expected %s got %s\n", sTemp1, sTemp);
throw new SBPL_Exception();
}
if (fscanf(fCfg, "%s", sTemp) != 1) {
SBPL_ERROR("ERROR: ran out of env file early\n");
throw new SBPL_Exception();
}
EnvNAVXYTHETALATCfg.timetoturn45degsinplace_secs = atof(sTemp);
//start(meters,rads):
if (fscanf(fCfg, "%s", sTemp) != 1) {
SBPL_ERROR("ERROR: ran out of env file early\n");
throw new SBPL_Exception();
}
if (fscanf(fCfg, "%s", sTemp) != 1) {
SBPL_ERROR("ERROR: ran out of env file early\n");
throw new SBPL_Exception();
}
EnvNAVXYTHETALATCfg.StartX_c = CONTXY2DISC(atof(sTemp), EnvNAVXYTHETALATCfg.cellsize_m);
if (fscanf(fCfg, "%s", sTemp) != 1) {
SBPL_ERROR("ERROR: ran out of env file early\n");
throw new SBPL_Exception();
}
EnvNAVXYTHETALATCfg.StartY_c = CONTXY2DISC(atof(sTemp), EnvNAVXYTHETALATCfg.cellsize_m);
if (fscanf(fCfg, "%s", sTemp) != 1) {
SBPL_ERROR("ERROR: ran out of env file early\n");
throw new SBPL_Exception();
}
EnvNAVXYTHETALATCfg.StartTheta = ContTheta2Disc(atof(sTemp), EnvNAVXYTHETALATCfg.NumThetaDirs);
if (EnvNAVXYTHETALATCfg.StartX_c < 0 || EnvNAVXYTHETALATCfg.StartX_c >= EnvNAVXYTHETALATCfg.EnvWidth_c) {
SBPL_ERROR("ERROR: illegal start coordinates\n");
throw new SBPL_Exception();
}
if (EnvNAVXYTHETALATCfg.StartY_c < 0 || EnvNAVXYTHETALATCfg.StartY_c >= EnvNAVXYTHETALATCfg.EnvHeight_c) {
SBPL_ERROR("ERROR: illegal start coordinates\n");
throw new SBPL_Exception();
}
if (EnvNAVXYTHETALATCfg.StartTheta < 0 || EnvNAVXYTHETALATCfg.StartTheta >= EnvNAVXYTHETALATCfg.NumThetaDirs) {
SBPL_ERROR("ERROR: illegal start coordinates for theta\n");
throw new SBPL_Exception();
}
//end(meters,rads):
if (fscanf(fCfg, "%s", sTemp) != 1) {
SBPL_ERROR("ERROR: ran out of env file early\n");
throw new SBPL_Exception();
}
if (fscanf(fCfg, "%s", sTemp) != 1) {
SBPL_ERROR("ERROR: ran out of env file early\n");
throw new SBPL_Exception();
}
EnvNAVXYTHETALATCfg.EndX_c = CONTXY2DISC(atof(sTemp), EnvNAVXYTHETALATCfg.cellsize_m);
if (fscanf(fCfg, "%s", sTemp) != 1) {
SBPL_ERROR("ERROR: ran out of env file early\n");
throw new SBPL_Exception();
}
EnvNAVXYTHETALATCfg.EndY_c = CONTXY2DISC(atof(sTemp), EnvNAVXYTHETALATCfg.cellsize_m);
if (fscanf(fCfg, "%s", sTemp) != 1) {
SBPL_ERROR("ERROR: ran out of env file early\n");
throw new SBPL_Exception();
}
EnvNAVXYTHETALATCfg.EndTheta = ContTheta2Disc(atof(sTemp), EnvNAVXYTHETALATCfg.NumThetaDirs);
;
if (EnvNAVXYTHETALATCfg.EndX_c < 0 || EnvNAVXYTHETALATCfg.EndX_c >= EnvNAVXYTHETALATCfg.EnvWidth_c) {
SBPL_ERROR("ERROR: illegal end coordinates\n");
throw new SBPL_Exception();
}
if (EnvNAVXYTHETALATCfg.EndY_c < 0 || EnvNAVXYTHETALATCfg.EndY_c >= EnvNAVXYTHETALATCfg.EnvHeight_c) {
SBPL_ERROR("ERROR: illegal end coordinates\n");
throw new SBPL_Exception();
}
if (EnvNAVXYTHETALATCfg.EndTheta < 0 || EnvNAVXYTHETALATCfg.EndTheta >= EnvNAVXYTHETALATCfg.NumThetaDirs) {
SBPL_ERROR("ERROR: illegal goal coordinates for theta\n");
throw new SBPL_Exception();
}
//allocate the 2D environment
EnvNAVXYTHETALATCfg.Grid2D = new unsigned char*[EnvNAVXYTHETALATCfg.EnvWidth_c];
for (x = 0; x < EnvNAVXYTHETALATCfg.EnvWidth_c; x++) {
EnvNAVXYTHETALATCfg.Grid2D[x] = new unsigned char[EnvNAVXYTHETALATCfg.EnvHeight_c];
}
//environment:
if (fscanf(fCfg, "%s", sTemp) != 1) {
SBPL_ERROR("ERROR: ran out of env file early\n");
throw new SBPL_Exception();
}
for (y = 0; y < EnvNAVXYTHETALATCfg.EnvHeight_c; y++)
for (x = 0; x < EnvNAVXYTHETALATCfg.EnvWidth_c; x++) {
if (fscanf(fCfg, "%d", &dTemp) != 1) {
SBPL_ERROR("ERROR: incorrect format of config file\n");
throw new SBPL_Exception();
}
EnvNAVXYTHETALATCfg.Grid2D[x][y] = dTemp;
}
}
bool EnvironmentNAVXYTHETALATTICE::ReadinCell(sbpl_xy_theta_cell_t* cell, FILE* fIn)
{
char sTemp[60];
if (fscanf(fIn, "%s", sTemp) == 0) return false;
cell->x = atoi(sTemp);
if (fscanf(fIn, "%s", sTemp) == 0) return false;
cell->y = atoi(sTemp);
if (fscanf(fIn, "%s", sTemp) == 0) return false;
cell->theta = atoi(sTemp);
//normalize the angle
cell->theta = NORMALIZEDISCTHETA(cell->theta, EnvNAVXYTHETALATCfg.NumThetaDirs);
return true;
}
bool EnvironmentNAVXYTHETALATTICE::ReadinPose(sbpl_xy_theta_pt_t* pose, FILE* fIn)
{
char sTemp[60];
if (fscanf(fIn, "%s", sTemp) == 0) return false;
pose->x = atof(sTemp);
if (fscanf(fIn, "%s", sTemp) == 0) return false;
pose->y = atof(sTemp);
if (fscanf(fIn, "%s", sTemp) == 0) return false;
pose->theta = atof(sTemp);
pose->theta = normalizeAngle(pose->theta);
return true;
}
bool EnvironmentNAVXYTHETALATTICE::ReadinMotionPrimitive(SBPL_xytheta_mprimitive* pMotPrim, FILE* fIn)
{
char sTemp[1024];
int dTemp;
char sExpected[1024];
int numofIntermPoses;
//read in actionID
strcpy(sExpected, "primID:");
if (fscanf(fIn, "%s", sTemp) == 0) return false;
if (strcmp(sTemp, sExpected) != 0) {
SBPL_ERROR("ERROR: expected %s but got %s\n", sExpected, sTemp);
return false;
}
if (fscanf(fIn, "%d", &pMotPrim->motprimID) != 1) return false;
//read in start angle
strcpy(sExpected, "startangle_c:");
if (fscanf(fIn, "%s", sTemp) == 0) return false;
if (strcmp(sTemp, sExpected) != 0) {
SBPL_ERROR("ERROR: expected %s but got %s\n", sExpected, sTemp);
return false;
}
if (fscanf(fIn, "%d", &dTemp) == 0) {
SBPL_ERROR("ERROR reading startangle\n");
return false;
}
pMotPrim->starttheta_c = dTemp;
//read in end pose
strcpy(sExpected, "endpose_c:");
if (fscanf(fIn, "%s", sTemp) == 0) return false;
if (strcmp(sTemp, sExpected) != 0) {
SBPL_ERROR("ERROR: expected %s but got %s\n", sExpected, sTemp);
return false;
}
if (ReadinCell(&pMotPrim->endcell, fIn) == false) {
SBPL_ERROR("ERROR: failed to read in endsearchpose\n");
return false;
}
//read in action cost
strcpy(sExpected, "additionalactioncostmult:");
if (fscanf(fIn, "%s", sTemp) == 0) return false;
if (strcmp(sTemp, sExpected) != 0) {
SBPL_ERROR("ERROR: expected %s but got %s\n", sExpected, sTemp);
return false;
}
if (fscanf(fIn, "%d", &dTemp) != 1) return false;
pMotPrim->additionalactioncostmult = dTemp;
//read in intermediate poses
strcpy(sExpected, "intermediateposes:");
if (fscanf(fIn, "%s", sTemp) == 0) return false;
if (strcmp(sTemp, sExpected) != 0) {
SBPL_ERROR("ERROR: expected %s but got %s\n", sExpected, sTemp);
return false;
}
if (fscanf(fIn, "%d", &numofIntermPoses) != 1) return false;
//all intermposes should be with respect to 0,0 as starting pose since it will be added later and should be done
//after the action is rotated by initial orientation
for (int i = 0; i < numofIntermPoses; i++) {
sbpl_xy_theta_pt_t intermpose;
if (ReadinPose(&intermpose, fIn) == false) {
SBPL_ERROR("ERROR: failed to read in intermediate poses\n");
return false;
}
pMotPrim->intermptV.push_back(intermpose);
}
//check that the last pose corresponds correctly to the last pose
sbpl_xy_theta_pt_t sourcepose;
sourcepose.x = DISCXY2CONT(0, EnvNAVXYTHETALATCfg.cellsize_m);
sourcepose.y = DISCXY2CONT(0, EnvNAVXYTHETALATCfg.cellsize_m);
sourcepose.theta = DiscTheta2Cont(pMotPrim->starttheta_c, EnvNAVXYTHETALATCfg.NumThetaDirs);
double mp_endx_m = sourcepose.x + pMotPrim->intermptV[pMotPrim->intermptV.size() - 1].x;
double mp_endy_m = sourcepose.y + pMotPrim->intermptV[pMotPrim->intermptV.size() - 1].y;
double mp_endtheta_rad = pMotPrim->intermptV[pMotPrim->intermptV.size() - 1].theta;
int endx_c = CONTXY2DISC(mp_endx_m, EnvNAVXYTHETALATCfg.cellsize_m);
int endy_c = CONTXY2DISC(mp_endy_m, EnvNAVXYTHETALATCfg.cellsize_m);
int endtheta_c = ContTheta2Disc(mp_endtheta_rad, EnvNAVXYTHETALATCfg.NumThetaDirs);
if (endx_c != pMotPrim->endcell.x || endy_c != pMotPrim->endcell.y || endtheta_c != pMotPrim->endcell.theta) {
SBPL_ERROR( "ERROR: incorrect primitive %d with startangle=%d "
"last interm point %f %f %f does not match end pose %d %d %d\n",
pMotPrim->motprimID, pMotPrim->starttheta_c,
pMotPrim->intermptV[pMotPrim->intermptV.size() - 1].x,
pMotPrim->intermptV[pMotPrim->intermptV.size() - 1].y,
pMotPrim->intermptV[pMotPrim->intermptV.size() - 1].theta,
pMotPrim->endcell.x, pMotPrim->endcell.y,
pMotPrim->endcell.theta);
return false;
}
return true;
}
bool EnvironmentNAVXYTHETALATTICE::ReadMotionPrimitives(FILE* fMotPrims)
{
char sTemp[1024], sExpected[1024];
float fTemp;
int dTemp;
int totalNumofActions = 0;
SBPL_PRINTF("Reading in motion primitives...");
//read in the resolution
strcpy(sExpected, "resolution_m:");
if (fscanf(fMotPrims, "%s", sTemp) == 0) return false;
if (strcmp(sTemp, sExpected) != 0) {
SBPL_ERROR("ERROR: expected %s but got %s\n", sExpected, sTemp);
return false;
}
if (fscanf(fMotPrims, "%f", &fTemp) == 0) return false;
if (fabs(fTemp - EnvNAVXYTHETALATCfg.cellsize_m) > ERR_EPS) {
SBPL_ERROR("ERROR: invalid resolution %f (instead of %f) in the dynamics file\n", fTemp,
EnvNAVXYTHETALATCfg.cellsize_m);
return false;
}
//read in the angular resolution
strcpy(sExpected, "numberofangles:");
if (fscanf(fMotPrims, "%s", sTemp) == 0) return false;
if (strcmp(sTemp, sExpected) != 0) {
SBPL_ERROR("ERROR: expected %s but got %s\n", sExpected, sTemp);
return false;
}
if (fscanf(fMotPrims, "%d", &dTemp) == 0) return false;
if (dTemp != EnvNAVXYTHETALATCfg.NumThetaDirs) {
SBPL_ERROR("ERROR: invalid angular resolution %d angles (instead of %d angles) in the motion primitives file\n",
dTemp, EnvNAVXYTHETALATCfg.NumThetaDirs);
return false;
}
//read in the total number of actions
strcpy(sExpected, "totalnumberofprimitives:");
if (fscanf(fMotPrims, "%s", sTemp) == 0) return false;
if (strcmp(sTemp, sExpected) != 0) {
SBPL_ERROR("ERROR: expected %s but got %s\n", sExpected, sTemp);
return false;
}
if (fscanf(fMotPrims, "%d", &totalNumofActions) == 0) {
return false;
}
for (int i = 0; i < totalNumofActions; i++) {
SBPL_xytheta_mprimitive motprim;
if (EnvironmentNAVXYTHETALATTICE::ReadinMotionPrimitive(&motprim, fMotPrims) == false) return false;
EnvNAVXYTHETALATCfg.mprimV.push_back(motprim);
}
SBPL_PRINTF("done ");
return true;
}
void EnvironmentNAVXYTHETALATTICE::ComputeReplanningDataforAction(EnvNAVXYTHETALATAction_t* action)
{
int j;
//iterate over all the cells involved in the action
sbpl_xy_theta_cell_t startcell3d, endcell3d;
for (int i = 0; i < (int)action->intersectingcellsV.size(); i++) {
//compute the translated affected search Pose - what state has an
//outgoing action whose intersecting cell is at 0,0
startcell3d.theta = action->starttheta;
startcell3d.x = -action->intersectingcellsV.at(i).x;
startcell3d.y = -action->intersectingcellsV.at(i).y;
//compute the translated affected search Pose - what state has an
//incoming action whose intersecting cell is at 0,0
endcell3d.theta = NORMALIZEDISCTHETA(action->endtheta, EnvNAVXYTHETALATCfg.NumThetaDirs);
endcell3d.x = startcell3d.x + action->dX;
endcell3d.y = startcell3d.y + action->dY;
//store the cells if not already there
for (j = 0; j < (int)affectedsuccstatesV.size(); j++) {
if (affectedsuccstatesV.at(j) == endcell3d) break;
}
if (j == (int)affectedsuccstatesV.size()) affectedsuccstatesV.push_back(endcell3d);
for (j = 0; j < (int)affectedpredstatesV.size(); j++) {
if (affectedpredstatesV.at(j) == startcell3d) break;
}
if (j == (int)affectedpredstatesV.size()) affectedpredstatesV.push_back(startcell3d);
}//over intersecting cells
//add the centers since with h2d we are using these in cost computations
//---intersecting cell = origin
//compute the translated affected search Pose - what state has an outgoing action whose intersecting cell is at 0,0
startcell3d.theta = action->starttheta;
startcell3d.x = -0;
startcell3d.y = -0;
//compute the translated affected search Pose - what state has an incoming action whose intersecting cell is at 0,0
endcell3d.theta = NORMALIZEDISCTHETA(action->endtheta, EnvNAVXYTHETALATCfg.NumThetaDirs);
endcell3d.x = startcell3d.x + action->dX;
endcell3d.y = startcell3d.y + action->dY;
//store the cells if not already there
for (j = 0; j < (int)affectedsuccstatesV.size(); j++) {
if (affectedsuccstatesV.at(j) == endcell3d) break;
}
if (j == (int)affectedsuccstatesV.size()) affectedsuccstatesV.push_back(endcell3d);
for (j = 0; j < (int)affectedpredstatesV.size(); j++) {
if (affectedpredstatesV.at(j) == startcell3d) break;
}
if (j == (int)affectedpredstatesV.size()) affectedpredstatesV.push_back(startcell3d);
//---intersecting cell = outcome state
//compute the translated affected search Pose - what state has an outgoing action whose intersecting cell is at 0,0
startcell3d.theta = action->starttheta;
startcell3d.x = -action->dX;
startcell3d.y = -action->dY;
//compute the translated affected search Pose - what state has an incoming action whose intersecting cell is at 0,0
endcell3d.theta = NORMALIZEDISCTHETA(action->endtheta, EnvNAVXYTHETALATCfg.NumThetaDirs);
endcell3d.x = startcell3d.x + action->dX;
endcell3d.y = startcell3d.y + action->dY;
for (j = 0; j < (int)affectedsuccstatesV.size(); j++) {
if (affectedsuccstatesV.at(j) == endcell3d) break;
}
if (j == (int)affectedsuccstatesV.size()) affectedsuccstatesV.push_back(endcell3d);
for (j = 0; j < (int)affectedpredstatesV.size(); j++) {
if (affectedpredstatesV.at(j) == startcell3d) break;
}
if (j == (int)affectedpredstatesV.size()) affectedpredstatesV.push_back(startcell3d);
}
//computes all the 3D states whose outgoing actions are potentially affected
//when cell (0,0) changes its status it also does the same for the 3D states
//whose incoming actions are potentially affected when cell (0,0) changes its
//status
void EnvironmentNAVXYTHETALATTICE::ComputeReplanningData()
{
//iterate over all actions
//orientations
for (int tind = 0; tind < EnvNAVXYTHETALATCfg.NumThetaDirs; tind++) {
//actions
for (int aind = 0; aind < EnvNAVXYTHETALATCfg.actionwidth; aind++) {
//compute replanning data for this action
ComputeReplanningDataforAction(&EnvNAVXYTHETALATCfg.ActionsV[tind][aind]);
}
}
}
//here motionprimitivevector contains actions only for 0 angle
void EnvironmentNAVXYTHETALATTICE::PrecomputeActionswithBaseMotionPrimitive(
vector<SBPL_xytheta_mprimitive>* motionprimitiveV)
{
SBPL_PRINTF("Pre-computing action data using base motion primitives...\n");
EnvNAVXYTHETALATCfg.ActionsV = new EnvNAVXYTHETALATAction_t*[EnvNAVXYTHETALATCfg.NumThetaDirs];
EnvNAVXYTHETALATCfg.PredActionsV = new vector<EnvNAVXYTHETALATAction_t*> [EnvNAVXYTHETALATCfg.NumThetaDirs];
vector<sbpl_2Dcell_t> footprint;
//iterate over source angles
for (int tind = 0; tind < EnvNAVXYTHETALATCfg.NumThetaDirs; tind++) {
SBPL_PRINTF("pre-computing for angle %d out of %d angles\n", tind, EnvNAVXYTHETALATCfg.NumThetaDirs);
EnvNAVXYTHETALATCfg.ActionsV[tind] = new EnvNAVXYTHETALATAction_t[motionprimitiveV->size()];
//compute sourcepose
sbpl_xy_theta_pt_t sourcepose;
sourcepose.x = DISCXY2CONT(0, EnvNAVXYTHETALATCfg.cellsize_m);
sourcepose.y = DISCXY2CONT(0, EnvNAVXYTHETALATCfg.cellsize_m);
sourcepose.theta = DiscTheta2Cont(tind, EnvNAVXYTHETALATCfg.NumThetaDirs);
//iterate over motion primitives
for (size_t aind = 0; aind < motionprimitiveV->size(); aind++) {
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].aind = aind;
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].starttheta = tind;
double mp_endx_m = motionprimitiveV->at(aind).intermptV[motionprimitiveV->at(aind).intermptV.size() - 1].x;
double mp_endy_m = motionprimitiveV->at(aind).intermptV[motionprimitiveV->at(aind).intermptV.size() - 1].y;
double mp_endtheta_rad =
motionprimitiveV->at(aind).intermptV[motionprimitiveV->at(aind).intermptV.size() - 1].theta;
double endx = sourcepose.x + (mp_endx_m * cos(sourcepose.theta) - mp_endy_m * sin(sourcepose.theta));
double endy = sourcepose.y + (mp_endx_m * sin(sourcepose.theta) + mp_endy_m * cos(sourcepose.theta));
int endx_c = CONTXY2DISC(endx, EnvNAVXYTHETALATCfg.cellsize_m);
int endy_c = CONTXY2DISC(endy, EnvNAVXYTHETALATCfg.cellsize_m);
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].endtheta = ContTheta2Disc(mp_endtheta_rad + sourcepose.theta,
EnvNAVXYTHETALATCfg.NumThetaDirs);
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].dX = endx_c;
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].dY = endy_c;
if (EnvNAVXYTHETALATCfg.ActionsV[tind][aind].dY != 0 || EnvNAVXYTHETALATCfg.ActionsV[tind][aind].dX != 0)
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].cost = (int)(ceil(NAVXYTHETALAT_COSTMULT_MTOMM
* EnvNAVXYTHETALATCfg.cellsize_m / EnvNAVXYTHETALATCfg.nominalvel_mpersecs
* sqrt((double)(EnvNAVXYTHETALATCfg.ActionsV[tind][aind].dX
* EnvNAVXYTHETALATCfg.ActionsV[tind][aind].dX + EnvNAVXYTHETALATCfg.ActionsV[tind][aind].dY
* EnvNAVXYTHETALATCfg.ActionsV[tind][aind].dY))));
else
//cost of turn in place
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].cost = (int)(NAVXYTHETALAT_COSTMULT_MTOMM
* EnvNAVXYTHETALATCfg.timetoturn45degsinplace_secs
* fabs(computeMinUnsignedAngleDiff(mp_endtheta_rad, 0)) / (PI_CONST / 4.0));
//compute and store interm points as well as intersecting cells
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].intersectingcellsV.clear();
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].intermptV.clear();
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].interm3DcellsV.clear();
sbpl_xy_theta_cell_t previnterm3Dcell;
previnterm3Dcell.theta = previnterm3Dcell.x = previnterm3Dcell.y = 0;
for (int pind = 0; pind < (int)motionprimitiveV->at(aind).intermptV.size(); pind++) {
sbpl_xy_theta_pt_t intermpt = motionprimitiveV->at(aind).intermptV[pind];
//rotate it appropriately
double rotx = intermpt.x * cos(sourcepose.theta) - intermpt.y * sin(sourcepose.theta);
double roty = intermpt.x * sin(sourcepose.theta) + intermpt.y * cos(sourcepose.theta);
intermpt.x = rotx;
intermpt.y = roty;
intermpt.theta = normalizeAngle(sourcepose.theta + intermpt.theta);
//store it (they are with reference to 0,0,stattheta (not
//sourcepose.x,sourcepose.y,starttheta (that is, half-bin))
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].intermptV.push_back(intermpt);
}
//now compute the intersecting cells for this motion (including ignoring the source footprint)
get_2d_motion_cells(EnvNAVXYTHETALATCfg.FootprintPolygon,
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].intermptV,
&EnvNAVXYTHETALATCfg.ActionsV[tind][aind].intersectingcellsV,
EnvNAVXYTHETALATCfg.cellsize_m);
#if DEBUG
SBPL_FPRINTF(fDeb,
"action tind=%d aind=%d: dX=%d dY=%d endtheta=%d (%.2f degs -> %.2f degs) "
"cost=%d (mprim: %.2f %.2f %.2f)\n",
tind,
(int)aind,
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].dX,
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].dY,
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].endtheta,
sourcepose.theta * 180.0 / PI_CONST,
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].intermptV[EnvNAVXYTHETALATCfg.ActionsV[tind][aind].intermptV.size() - 1].theta * 180.0 / PI_CONST,
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].cost,
mp_endx_m,
mp_endy_m,
mp_endtheta_rad);
#endif
//add to the list of backward actions
int targettheta = EnvNAVXYTHETALATCfg.ActionsV[tind][aind].endtheta;
if (targettheta < 0) targettheta = targettheta + EnvNAVXYTHETALATCfg.NumThetaDirs;
EnvNAVXYTHETALATCfg.PredActionsV[targettheta].push_back(&(EnvNAVXYTHETALATCfg.ActionsV[tind][aind]));
}
}
//set number of actions
EnvNAVXYTHETALATCfg.actionwidth = motionprimitiveV->size();
//now compute replanning data
ComputeReplanningData();
SBPL_PRINTF("done pre-computing action data based on motion primitives\n");
}
//here motionprimitivevector contains actions for all angles
void EnvironmentNAVXYTHETALATTICE::PrecomputeActionswithCompleteMotionPrimitive(
vector<SBPL_xytheta_mprimitive>* motionprimitiveV)
{
SBPL_PRINTF("Pre-computing action data using motion primitives for every angle...\n");
EnvNAVXYTHETALATCfg.ActionsV = new EnvNAVXYTHETALATAction_t*[EnvNAVXYTHETALATCfg.NumThetaDirs];
EnvNAVXYTHETALATCfg.PredActionsV = new vector<EnvNAVXYTHETALATAction_t*> [EnvNAVXYTHETALATCfg.NumThetaDirs];
vector<sbpl_2Dcell_t> footprint;
if (motionprimitiveV->size() % EnvNAVXYTHETALATCfg.NumThetaDirs != 0) {
SBPL_ERROR("ERROR: motionprimitives should be uniform across actions\n");
throw new SBPL_Exception();
}
EnvNAVXYTHETALATCfg.actionwidth = ((int)motionprimitiveV->size()) / EnvNAVXYTHETALATCfg.NumThetaDirs;
//iterate over source angles
int maxnumofactions = 0;
for (int tind = 0; tind < EnvNAVXYTHETALATCfg.NumThetaDirs; tind++) {
SBPL_PRINTF("pre-computing for angle %d out of %d angles\n", tind, EnvNAVXYTHETALATCfg.NumThetaDirs);
EnvNAVXYTHETALATCfg.ActionsV[tind] = new EnvNAVXYTHETALATAction_t[EnvNAVXYTHETALATCfg.actionwidth];
//compute sourcepose
sbpl_xy_theta_pt_t sourcepose;
sourcepose.x = DISCXY2CONT(0, EnvNAVXYTHETALATCfg.cellsize_m);
sourcepose.y = DISCXY2CONT(0, EnvNAVXYTHETALATCfg.cellsize_m);
sourcepose.theta = DiscTheta2Cont(tind, EnvNAVXYTHETALATCfg.NumThetaDirs);
//iterate over motion primitives
int numofactions = 0;
int aind = -1;
for (int mind = 0; mind < (int)motionprimitiveV->size(); mind++) {
//find a motion primitive for this angle
if (motionprimitiveV->at(mind).starttheta_c != tind) continue;
aind++;
numofactions++;
//action index
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].aind = aind;
//start angle
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].starttheta = tind;
//compute dislocation
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].endtheta = motionprimitiveV->at(mind).endcell.theta;
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].dX = motionprimitiveV->at(mind).endcell.x;
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].dY = motionprimitiveV->at(mind).endcell.y;
//compute and store interm points as well as intersecting cells
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].intersectingcellsV.clear();
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].intermptV.clear();
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].interm3DcellsV.clear();
sbpl_xy_theta_cell_t previnterm3Dcell;
previnterm3Dcell.x = 0;
previnterm3Dcell.y = 0;
// Compute all the intersected cells for this action (intermptV and interm3DcellsV)
for (int pind = 0; pind < (int)motionprimitiveV->at(mind).intermptV.size(); pind++) {
sbpl_xy_theta_pt_t intermpt = motionprimitiveV->at(mind).intermptV[pind];
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].intermptV.push_back(intermpt);
// also compute the intermediate discrete cells if not there already
sbpl_xy_theta_pt_t pose;
pose.x = intermpt.x + sourcepose.x;
pose.y = intermpt.y + sourcepose.y;
pose.theta = intermpt.theta;
sbpl_xy_theta_cell_t intermediate2dCell;
intermediate2dCell.x = CONTXY2DISC(pose.x, EnvNAVXYTHETALATCfg.cellsize_m);
intermediate2dCell.y = CONTXY2DISC(pose.y, EnvNAVXYTHETALATCfg.cellsize_m);
// add unique cells to the list
if (EnvNAVXYTHETALATCfg.ActionsV[tind][aind].interm3DcellsV.size() == 0 || intermediate2dCell.x
!= previnterm3Dcell.x || intermediate2dCell.y != previnterm3Dcell.y) {
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].interm3DcellsV.push_back(intermediate2dCell);
}
previnterm3Dcell = intermediate2dCell;
}
//compute linear and angular time
double linear_distance = 0;
for (unsigned int i = 1; i < EnvNAVXYTHETALATCfg.ActionsV[tind][aind].intermptV.size(); i++) {
double x0 = EnvNAVXYTHETALATCfg.ActionsV[tind][aind].intermptV[i - 1].x;
double y0 = EnvNAVXYTHETALATCfg.ActionsV[tind][aind].intermptV[i - 1].y;
double x1 = EnvNAVXYTHETALATCfg.ActionsV[tind][aind].intermptV[i].x;
double y1 = EnvNAVXYTHETALATCfg.ActionsV[tind][aind].intermptV[i].y;
double dx = x1 - x0;
double dy = y1 - y0;
linear_distance += sqrt(dx * dx + dy * dy);
}
double linear_time = linear_distance / EnvNAVXYTHETALATCfg.nominalvel_mpersecs;
double angular_distance =
fabs(computeMinUnsignedAngleDiff(DiscTheta2Cont(EnvNAVXYTHETALATCfg.ActionsV[tind][aind].endtheta,
EnvNAVXYTHETALATCfg.NumThetaDirs),
DiscTheta2Cont(EnvNAVXYTHETALATCfg.ActionsV[tind][aind].starttheta,
EnvNAVXYTHETALATCfg.NumThetaDirs)));
double angular_time = angular_distance / ((PI_CONST / 4.0) /
EnvNAVXYTHETALATCfg.timetoturn45degsinplace_secs);
//make the cost the max of the two times
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].cost =
(int)(ceil(NAVXYTHETALAT_COSTMULT_MTOMM * max(linear_time, angular_time)));
//use any additional cost multiplier
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].cost *= motionprimitiveV->at(mind).additionalactioncostmult;
//now compute the intersecting cells for this motion (including ignoring the source footprint)
get_2d_motion_cells(EnvNAVXYTHETALATCfg.FootprintPolygon, motionprimitiveV->at(mind).intermptV,
&EnvNAVXYTHETALATCfg.ActionsV[tind][aind].intersectingcellsV,
EnvNAVXYTHETALATCfg.cellsize_m);
#if DEBUG
SBPL_FPRINTF(fDeb,
"action tind=%2d aind=%2d: dX=%3d dY=%3d endtheta=%3d (%6.2f degs -> %6.2f degs) "
"cost=%4d (mprimID %3d: %3d %3d %3d) numofintermcells = %d numofintercells=%d\n",
tind,
aind,
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].dX,
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].dY,
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].endtheta,
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].intermptV[0].theta * 180 / PI_CONST,
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].intermptV[EnvNAVXYTHETALATCfg.ActionsV[tind][aind].intermptV.size() - 1].theta * 180 / PI_CONST, EnvNAVXYTHETALATCfg.ActionsV[tind][aind].cost,
motionprimitiveV->at(mind).motprimID, motionprimitiveV->at(mind).endcell.x,
motionprimitiveV->at(mind).endcell.y, motionprimitiveV->at(mind).endcell.theta,
(int)EnvNAVXYTHETALATCfg.ActionsV[tind][aind].interm3DcellsV.size(),
(int)EnvNAVXYTHETALATCfg.ActionsV[tind][aind].intersectingcellsV.size());
#endif
//add to the list of backward actions
int targettheta = EnvNAVXYTHETALATCfg.ActionsV[tind][aind].endtheta;
if (targettheta < 0) targettheta = targettheta + EnvNAVXYTHETALATCfg.NumThetaDirs;
EnvNAVXYTHETALATCfg.PredActionsV[targettheta].push_back(&(EnvNAVXYTHETALATCfg.ActionsV[tind][aind]));
}
if (maxnumofactions < numofactions) maxnumofactions = numofactions;
}
//at this point we don't allow nonuniform number of actions
if (motionprimitiveV->size() != (size_t)(EnvNAVXYTHETALATCfg.NumThetaDirs * maxnumofactions)) {
SBPL_ERROR("ERROR: nonuniform number of actions is not supported "
"(maxnumofactions=%d while motprims=%d thetas=%d\n",
maxnumofactions, (unsigned int)motionprimitiveV->size(), EnvNAVXYTHETALATCfg.NumThetaDirs);
throw new SBPL_Exception();
}
//now compute replanning data
ComputeReplanningData();
SBPL_PRINTF("done pre-computing action data based on motion primitives\n");
}
void EnvironmentNAVXYTHETALATTICE::DeprecatedPrecomputeActions()
{
SBPL_PRINTF("Use of DeprecatedPrecomputeActions() is deprecated and probably doesn't work!\n");
//construct list of actions
SBPL_PRINTF("Pre-computing action data using the motion primitives for a 3D kinematic planning...\n");
EnvNAVXYTHETALATCfg.ActionsV = new EnvNAVXYTHETALATAction_t*[EnvNAVXYTHETALATCfg.NumThetaDirs];
EnvNAVXYTHETALATCfg.PredActionsV = new vector<EnvNAVXYTHETALATAction_t*> [EnvNAVXYTHETALATCfg.NumThetaDirs];
vector<sbpl_2Dcell_t> footprint;
//iterate over source angles
for (int tind = 0; tind < EnvNAVXYTHETALATCfg.NumThetaDirs; tind++) {
SBPL_PRINTF("processing angle %d\n", tind);
EnvNAVXYTHETALATCfg.ActionsV[tind] = new EnvNAVXYTHETALATAction_t[EnvNAVXYTHETALATCfg.actionwidth];
//compute sourcepose
sbpl_xy_theta_pt_t sourcepose;
sourcepose.x = DISCXY2CONT(0, EnvNAVXYTHETALATCfg.cellsize_m);
sourcepose.y = DISCXY2CONT(0, EnvNAVXYTHETALATCfg.cellsize_m);
sourcepose.theta = DiscTheta2Cont(tind, EnvNAVXYTHETALATCfg.NumThetaDirs);
//the construction assumes that the robot first turns and then goes along this new theta
int aind = 0;
for (; aind < 3; aind++) {
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].aind = aind;
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].starttheta = tind;
//-1,0,1
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].endtheta = (tind + aind - 1) % EnvNAVXYTHETALATCfg.NumThetaDirs;
double angle = DiscTheta2Cont(EnvNAVXYTHETALATCfg.ActionsV[tind][aind].endtheta,
EnvNAVXYTHETALATCfg.NumThetaDirs);
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].dX = (int)(cos(angle) + 0.5 * (cos(angle) > 0 ? 1 : -1));
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].dY = (int)(sin(angle) + 0.5 * (sin(angle) > 0 ? 1 : -1));
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].cost = (int)(ceil(NAVXYTHETALAT_COSTMULT_MTOMM
* EnvNAVXYTHETALATCfg.cellsize_m / EnvNAVXYTHETALATCfg.nominalvel_mpersecs
* sqrt((double)(EnvNAVXYTHETALATCfg.ActionsV[tind][aind].dX
* EnvNAVXYTHETALATCfg.ActionsV[tind][aind].dX + EnvNAVXYTHETALATCfg.ActionsV[tind][aind].dY
* EnvNAVXYTHETALATCfg.ActionsV[tind][aind].dY))));
//compute intersecting cells
sbpl_xy_theta_pt_t pose;
pose.x = DISCXY2CONT(EnvNAVXYTHETALATCfg.ActionsV[tind][aind].dX, EnvNAVXYTHETALATCfg.cellsize_m);
pose.y = DISCXY2CONT(EnvNAVXYTHETALATCfg.ActionsV[tind][aind].dY, EnvNAVXYTHETALATCfg.cellsize_m);
pose.theta = angle;
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].intermptV.clear();
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].intersectingcellsV.clear();
get_2d_footprint_cells(EnvNAVXYTHETALATCfg.FootprintPolygon,
&EnvNAVXYTHETALATCfg.ActionsV[tind][aind].intersectingcellsV, pose,
EnvNAVXYTHETALATCfg.cellsize_m);
RemoveSourceFootprint(sourcepose, &EnvNAVXYTHETALATCfg.ActionsV[tind][aind].intersectingcellsV);
#if DEBUG
SBPL_PRINTF("action tind=%d aind=%d: endtheta=%d (%f) dX=%d dY=%d cost=%d\n",
tind, aind, EnvNAVXYTHETALATCfg.ActionsV[tind][aind].endtheta, angle,
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].dX, EnvNAVXYTHETALATCfg.ActionsV[tind][aind].dY,
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].cost);
#endif
//add to the list of backward actions
int targettheta = EnvNAVXYTHETALATCfg.ActionsV[tind][aind].endtheta;
if (targettheta < 0) targettheta = targettheta + EnvNAVXYTHETALATCfg.NumThetaDirs;
EnvNAVXYTHETALATCfg.PredActionsV[targettheta].push_back(&(EnvNAVXYTHETALATCfg.ActionsV[tind][aind]));
}
//decrease and increase angle without movement
aind = 3;
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].aind = aind;
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].starttheta = tind;
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].endtheta = tind - 1;
if (EnvNAVXYTHETALATCfg.ActionsV[tind][aind].endtheta < 0)
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].endtheta += EnvNAVXYTHETALATCfg.NumThetaDirs;
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].dX = 0;
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].dY = 0;
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].cost = (int)(NAVXYTHETALAT_COSTMULT_MTOMM *
EnvNAVXYTHETALATCfg.timetoturn45degsinplace_secs);
//compute intersecting cells
sbpl_xy_theta_pt_t pose;
pose.x = DISCXY2CONT(EnvNAVXYTHETALATCfg.ActionsV[tind][aind].dX, EnvNAVXYTHETALATCfg.cellsize_m);
pose.y = DISCXY2CONT(EnvNAVXYTHETALATCfg.ActionsV[tind][aind].dY, EnvNAVXYTHETALATCfg.cellsize_m);
pose.theta =
DiscTheta2Cont(EnvNAVXYTHETALATCfg.ActionsV[tind][aind].endtheta, EnvNAVXYTHETALATCfg.NumThetaDirs);
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].intermptV.clear();
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].intersectingcellsV.clear();
get_2d_footprint_cells(EnvNAVXYTHETALATCfg.FootprintPolygon,
&EnvNAVXYTHETALATCfg.ActionsV[tind][aind].intersectingcellsV, pose,
EnvNAVXYTHETALATCfg.cellsize_m);
RemoveSourceFootprint(sourcepose, &EnvNAVXYTHETALATCfg.ActionsV[tind][aind].intersectingcellsV);
#if DEBUG
SBPL_PRINTF("action tind=%d aind=%d: endtheta=%d (%f) dX=%d dY=%d cost=%d\n",
tind, aind, EnvNAVXYTHETALATCfg.ActionsV[tind][aind].endtheta,
DiscTheta2Cont(EnvNAVXYTHETALATCfg.ActionsV[tind][aind].endtheta, EnvNAVXYTHETALATCfg.NumThetaDirs),
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].dX, EnvNAVXYTHETALATCfg.ActionsV[tind][aind].dY,
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].cost);
#endif
//add to the list of backward actions
int targettheta = EnvNAVXYTHETALATCfg.ActionsV[tind][aind].endtheta;
if (targettheta < 0) targettheta = targettheta + EnvNAVXYTHETALATCfg.NumThetaDirs;
EnvNAVXYTHETALATCfg.PredActionsV[targettheta].push_back(&(EnvNAVXYTHETALATCfg.ActionsV[tind][aind]));
aind = 4;
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].aind = aind;
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].starttheta = tind;
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].endtheta = (tind + 1) % EnvNAVXYTHETALATCfg.NumThetaDirs;
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].dX = 0;
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].dY = 0;
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].cost = (int)(NAVXYTHETALAT_COSTMULT_MTOMM *
EnvNAVXYTHETALATCfg.timetoturn45degsinplace_secs);
//compute intersecting cells
pose.x = DISCXY2CONT(EnvNAVXYTHETALATCfg.ActionsV[tind][aind].dX, EnvNAVXYTHETALATCfg.cellsize_m);
pose.y = DISCXY2CONT(EnvNAVXYTHETALATCfg.ActionsV[tind][aind].dY, EnvNAVXYTHETALATCfg.cellsize_m);
pose.theta =
DiscTheta2Cont(EnvNAVXYTHETALATCfg.ActionsV[tind][aind].endtheta, EnvNAVXYTHETALATCfg.NumThetaDirs);
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].intermptV.clear();
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].intersectingcellsV.clear();
get_2d_footprint_cells(EnvNAVXYTHETALATCfg.FootprintPolygon,
&EnvNAVXYTHETALATCfg.ActionsV[tind][aind].intersectingcellsV, pose,
EnvNAVXYTHETALATCfg.cellsize_m);
RemoveSourceFootprint(sourcepose, &EnvNAVXYTHETALATCfg.ActionsV[tind][aind].intersectingcellsV);
#if DEBUG
SBPL_PRINTF("action tind=%d aind=%d: endtheta=%d (%f) dX=%d dY=%d cost=%d\n",
tind, aind, EnvNAVXYTHETALATCfg.ActionsV[tind][aind].endtheta, DiscTheta2Cont(EnvNAVXYTHETALATCfg.ActionsV[tind][aind].endtheta, EnvNAVXYTHETALATCfg.NumThetaDirs),
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].dX, EnvNAVXYTHETALATCfg.ActionsV[tind][aind].dY,
EnvNAVXYTHETALATCfg.ActionsV[tind][aind].cost);
#endif
//add to the list of backward actions
targettheta = EnvNAVXYTHETALATCfg.ActionsV[tind][aind].endtheta;
if (targettheta < 0) targettheta = targettheta + EnvNAVXYTHETALATCfg.NumThetaDirs;
EnvNAVXYTHETALATCfg.PredActionsV[targettheta].push_back(&(EnvNAVXYTHETALATCfg.ActionsV[tind][aind]));
}
//now compute replanning data
ComputeReplanningData();
SBPL_PRINTF("done pre-computing action data\n");
}
void EnvironmentNAVXYTHETALATTICE::InitializeEnvConfig(vector<SBPL_xytheta_mprimitive>* motionprimitiveV)
{
//aditional to configuration file initialization of EnvNAVXYTHETALATCfg if necessary
//dXY dirs
EnvNAVXYTHETALATCfg.dXY[0][0] = -1;
EnvNAVXYTHETALATCfg.dXY[0][1] = -1;
EnvNAVXYTHETALATCfg.dXY[1][0] = -1;
EnvNAVXYTHETALATCfg.dXY[1][1] = 0;
EnvNAVXYTHETALATCfg.dXY[2][0] = -1;
EnvNAVXYTHETALATCfg.dXY[2][1] = 1;
EnvNAVXYTHETALATCfg.dXY[3][0] = 0;
EnvNAVXYTHETALATCfg.dXY[3][1] = -1;
EnvNAVXYTHETALATCfg.dXY[4][0] = 0;
EnvNAVXYTHETALATCfg.dXY[4][1] = 1;
EnvNAVXYTHETALATCfg.dXY[5][0] = 1;
EnvNAVXYTHETALATCfg.dXY[5][1] = -1;
EnvNAVXYTHETALATCfg.dXY[6][0] = 1;
EnvNAVXYTHETALATCfg.dXY[6][1] = 0;
EnvNAVXYTHETALATCfg.dXY[7][0] = 1;
EnvNAVXYTHETALATCfg.dXY[7][1] = 1;
sbpl_xy_theta_pt_t temppose;
temppose.x = 0.0;
temppose.y = 0.0;
temppose.theta = 0.0;
vector<sbpl_2Dcell_t> footprint;
get_2d_footprint_cells(EnvNAVXYTHETALATCfg.FootprintPolygon, &footprint, temppose, EnvNAVXYTHETALATCfg.cellsize_m);
SBPL_PRINTF("number of cells in footprint of the robot = %d\n", (unsigned int)footprint.size());
for (vector<sbpl_2Dcell_t>::iterator it = footprint.begin(); it != footprint.end(); ++it) {
SBPL_PRINTF("Footprint cell at (%d, %d)\n", it->x, it->y);
}
#if DEBUG
SBPL_FPRINTF(fDeb, "footprint cells (size=%d):\n", (int)footprint.size());
for(int i = 0; i < (int) footprint.size(); i++)
{
SBPL_FPRINTF(fDeb, "%d %d (cont: %.3f %.3f)\n", footprint.at(i).x, footprint.at(i).y,
DISCXY2CONT(footprint.at(i).x, EnvNAVXYTHETALATCfg.cellsize_m),
DISCXY2CONT(footprint.at(i).y, EnvNAVXYTHETALATCfg.cellsize_m));
}
#endif
if (motionprimitiveV == NULL)
DeprecatedPrecomputeActions();
else
PrecomputeActionswithCompleteMotionPrimitive(motionprimitiveV);
}
bool EnvironmentNAVXYTHETALATTICE::IsValidCell(int X, int Y)
{
return (X >= 0 && X < EnvNAVXYTHETALATCfg.EnvWidth_c && Y >= 0 && Y < EnvNAVXYTHETALATCfg.EnvHeight_c &&
EnvNAVXYTHETALATCfg.Grid2D[X][Y] < EnvNAVXYTHETALATCfg.obsthresh);
}
bool EnvironmentNAVXYTHETALATTICE::IsWithinMapCell(int X, int Y)
{
return (X >= 0 && X < EnvNAVXYTHETALATCfg.EnvWidth_c && Y >= 0 && Y < EnvNAVXYTHETALATCfg.EnvHeight_c);
}
bool EnvironmentNAVXYTHETALATTICE::IsValidConfiguration(int X, int Y, int Theta)
{
vector<sbpl_2Dcell_t> footprint;
sbpl_xy_theta_pt_t pose;
//compute continuous pose
pose.x = DISCXY2CONT(X, EnvNAVXYTHETALATCfg.cellsize_m);
pose.y = DISCXY2CONT(Y, EnvNAVXYTHETALATCfg.cellsize_m);
pose.theta = DiscTheta2Cont(Theta, EnvNAVXYTHETALATCfg.NumThetaDirs);
//compute footprint cells
get_2d_footprint_cells(EnvNAVXYTHETALATCfg.FootprintPolygon, &footprint, pose, EnvNAVXYTHETALATCfg.cellsize_m);
//iterate over all footprint cells
for (int find = 0; find < (int)footprint.size(); find++) {
int x = footprint.at(find).x;
int y = footprint.at(find).y;
if (x < 0 || x >= EnvNAVXYTHETALATCfg.EnvWidth_c || y < 0 || y >= EnvNAVXYTHETALATCfg.EnvHeight_c ||
EnvNAVXYTHETALATCfg.Grid2D[x][y] >= EnvNAVXYTHETALATCfg.obsthresh)
{
return false;
}
}
return true;
}
int EnvironmentNAVXYTHETALATTICE::GetActionCost(int SourceX, int SourceY, int SourceTheta,
EnvNAVXYTHETALATAction_t* action)
{
sbpl_2Dcell_t cell;
sbpl_xy_theta_cell_t interm3Dcell;
int i;
//TODO - go over bounding box (minpt and maxpt) to test validity and skip
//testing boundaries below, also order intersect cells so that the four
//farthest pts go first
if (!IsValidCell(SourceX, SourceY)) return INFINITECOST;
if (!IsValidCell(SourceX + action->dX, SourceY + action->dY)) return INFINITECOST;
if (EnvNAVXYTHETALATCfg.Grid2D[SourceX + action->dX][SourceY + action->dY] >=
EnvNAVXYTHETALATCfg.cost_inscribed_thresh)
{
return INFINITECOST;
}
//need to iterate over discretized center cells and compute cost based on them
unsigned char maxcellcost = 0;
for (i = 0; i < (int)action->interm3DcellsV.size(); i++) {
interm3Dcell = action->interm3DcellsV.at(i);
interm3Dcell.x = interm3Dcell.x + SourceX;
interm3Dcell.y = interm3Dcell.y + SourceY;
if (interm3Dcell.x < 0 || interm3Dcell.x >= EnvNAVXYTHETALATCfg.EnvWidth_c || interm3Dcell.y < 0
|| interm3Dcell.y >= EnvNAVXYTHETALATCfg.EnvHeight_c) return INFINITECOST;
maxcellcost = __max(maxcellcost, EnvNAVXYTHETALATCfg.Grid2D[interm3Dcell.x][interm3Dcell.y]);
//check that the robot is NOT in the cell at which there is no valid orientation
if (maxcellcost >= EnvNAVXYTHETALATCfg.cost_inscribed_thresh) return INFINITECOST;
}
//check collisions that for the particular footprint orientation along the action
if (EnvNAVXYTHETALATCfg.FootprintPolygon.size() > 1 && (int)maxcellcost >=
EnvNAVXYTHETALATCfg.cost_possibly_circumscribed_thresh)
{
checks++;
for (i = 0; i < (int)action->intersectingcellsV.size(); i++) {
//get the cell in the map
cell = action->intersectingcellsV.at(i);
cell.x = cell.x + SourceX;
cell.y = cell.y + SourceY;
//check validity
if (!IsValidCell(cell.x, cell.y)) return INFINITECOST;
//if(EnvNAVXYTHETALATCfg.Grid2D[cell.x][cell.y] > currentmaxcost)
////cost computation changed: cost = max(cost of centers of the
//robot along action)
// currentmaxcost = EnvNAVXYTHETALATCfg.Grid2D[cell.x][cell.y];
// //intersecting cells are only used for collision checking
}
}
//to ensure consistency of h2D:
maxcellcost = __max(maxcellcost, EnvNAVXYTHETALATCfg.Grid2D[SourceX][SourceY]);
int currentmaxcost =
(int)__max(maxcellcost, EnvNAVXYTHETALATCfg.Grid2D[SourceX + action->dX][SourceY + action->dY]);
return action->cost * (currentmaxcost + 1); //use cell cost as multiplicative factor
}
double EnvironmentNAVXYTHETALATTICE::EuclideanDistance_m(int X1, int Y1, int X2, int Y2)
{
int sqdist = ((X1 - X2) * (X1 - X2) + (Y1 - Y2) * (Y1 - Y2));
return EnvNAVXYTHETALATCfg.cellsize_m * sqrt((double)sqdist);
}
//calculates a set of cells that correspond to the specified footprint
//adds points to it (does not clear it beforehand)
void EnvironmentNAVXYTHETALATTICE::CalculateFootprintForPose(sbpl_xy_theta_pt_t pose, vector<sbpl_2Dcell_t>* footprint,
const vector<sbpl_2Dpt_t>& FootprintPolygon)
{
int pind;
#if DEBUG
// SBPL_PRINTF("---Calculating Footprint for Pose: %f %f %f---\n",
// pose.x, pose.y, pose.theta);
#endif
//handle special case where footprint is just a point
if (FootprintPolygon.size() <= 1) {
sbpl_2Dcell_t cell;
cell.x = CONTXY2DISC(pose.x, EnvNAVXYTHETALATCfg.cellsize_m);
cell.y = CONTXY2DISC(pose.y, EnvNAVXYTHETALATCfg.cellsize_m);
for (pind = 0; pind < (int)footprint->size(); pind++) {
if (cell.x == footprint->at(pind).x && cell.y == footprint->at(pind).y) break;
}
if (pind == (int)footprint->size()) footprint->push_back(cell);
return;
}
vector<sbpl_2Dpt_t> bounding_polygon;
unsigned int find;
double max_x = -INFINITECOST, min_x = INFINITECOST, max_y = -INFINITECOST, min_y = INFINITECOST;
sbpl_2Dpt_t pt(0, 0);
for (find = 0; find < FootprintPolygon.size(); find++) {
//rotate and translate the corner of the robot
pt = FootprintPolygon[find];
//rotate and translate the point
sbpl_2Dpt_t corner;
corner.x = cos(pose.theta) * pt.x - sin(pose.theta) * pt.y + pose.x;
corner.y = sin(pose.theta) * pt.x + cos(pose.theta) * pt.y + pose.y;
bounding_polygon.push_back(corner);
#if DEBUG
// SBPL_PRINTF("Pt: %f %f, Corner: %f %f\n", pt.x, pt.y, corner.x, corner.y);
#endif
if (corner.x < min_x || find == 0) {
min_x = corner.x;
}
if (corner.x > max_x || find == 0) {
max_x = corner.x;
}
if (corner.y < min_y || find == 0) {
min_y = corner.y;
}
if (corner.y > max_y || find == 0) {
max_y = corner.y;
}
}
#if DEBUG
// SBPL_PRINTF("Footprint bounding box: %f %f %f %f\n", min_x, max_x, min_y, max_y);
#endif
//initialize previous values to something that will fail the if condition during the first iteration in the for loop
int prev_discrete_x = CONTXY2DISC(pt.x, EnvNAVXYTHETALATCfg.cellsize_m) + 1;
int prev_discrete_y = CONTXY2DISC(pt.y, EnvNAVXYTHETALATCfg.cellsize_m) + 1;
int prev_inside = 0;
int discrete_x;
int discrete_y;
for (double x = min_x; x <= max_x; x += EnvNAVXYTHETALATCfg.cellsize_m / 3) {
for (double y = min_y; y <= max_y; y += EnvNAVXYTHETALATCfg.cellsize_m / 3) {
pt.x = x;
pt.y = y;
discrete_x = CONTXY2DISC(pt.x, EnvNAVXYTHETALATCfg.cellsize_m);
discrete_y = CONTXY2DISC(pt.y, EnvNAVXYTHETALATCfg.cellsize_m);
//see if we just tested this point
if (discrete_x != prev_discrete_x || discrete_y != prev_discrete_y || prev_inside == 0) {
#if DEBUG
// SBPL_PRINTF("Testing point: %f %f Discrete: %d %d\n", pt.x, pt.y, discrete_x, discrete_y);
#endif
if (IsInsideFootprint(pt, &bounding_polygon)) {
//convert to a grid point
#if DEBUG
// SBPL_PRINTF("Pt Inside %f %f\n", pt.x, pt.y);
#endif
sbpl_2Dcell_t cell;
cell.x = discrete_x;
cell.y = discrete_y;
//insert point if not there already
int pind = 0;
for (pind = 0; pind < (int)footprint->size(); pind++) {
if (cell.x == footprint->at(pind).x && cell.y == footprint->at(pind).y) break;
}
if (pind == (int)footprint->size()) footprint->push_back(cell);
prev_inside = 1;
#if DEBUG
// SBPL_PRINTF("Added pt to footprint: %f %f\n", pt.x, pt.y);
#endif
}
else {
prev_inside = 0;
}
}
else {
#if DEBUG
//SBPL_PRINTF("Skipping pt: %f %f\n", pt.x, pt.y);
#endif
}
prev_discrete_x = discrete_x;
prev_discrete_y = discrete_y;
}//over x_min...x_max
}
}
//calculates a set of cells that correspond to the footprint of the base
//adds points to it (does not clear it beforehand)
void EnvironmentNAVXYTHETALATTICE::CalculateFootprintForPose(sbpl_xy_theta_pt_t pose, vector<sbpl_2Dcell_t>* footprint)
{
CalculateFootprintForPose(pose, footprint, EnvNAVXYTHETALATCfg.FootprintPolygon);
}
//removes a set of cells that correspond to the specified footprint at the sourcepose
//adds points to it (does not clear it beforehand)
void EnvironmentNAVXYTHETALATTICE::RemoveSourceFootprint(sbpl_xy_theta_pt_t sourcepose,
vector<sbpl_2Dcell_t>* footprint,
const vector<sbpl_2Dpt_t>& FootprintPolygon)
{
vector<sbpl_2Dcell_t> sourcefootprint;
//compute source footprint
get_2d_footprint_cells(FootprintPolygon, &sourcefootprint, sourcepose, EnvNAVXYTHETALATCfg.cellsize_m);
//now remove the source cells from the footprint
for (int sind = 0; sind < (int)sourcefootprint.size(); sind++) {
for (int find = 0; find < (int)footprint->size(); find++) {
if (sourcefootprint.at(sind).x == footprint->at(find).x && sourcefootprint.at(sind).y
== footprint->at(find).y) {
footprint->erase(footprint->begin() + find);
break;
}
}//over footprint
}//over source
}
//removes a set of cells that correspond to the footprint of the base at the sourcepose
//adds points to it (does not clear it beforehand)
void EnvironmentNAVXYTHETALATTICE::RemoveSourceFootprint(sbpl_xy_theta_pt_t sourcepose,
vector<sbpl_2Dcell_t>* footprint)
{
RemoveSourceFootprint(sourcepose, footprint, EnvNAVXYTHETALATCfg.FootprintPolygon);
}
//------------------------------------------------------------------------------
//------------------------------Heuristic computation--------------------------
void EnvironmentNAVXYTHETALATTICE::EnsureHeuristicsUpdated(bool bGoalHeuristics)
{
if (bNeedtoRecomputeStartHeuristics && !bGoalHeuristics) {
grid2Dsearchfromstart->search(EnvNAVXYTHETALATCfg.Grid2D, EnvNAVXYTHETALATCfg.cost_inscribed_thresh,
EnvNAVXYTHETALATCfg.StartX_c, EnvNAVXYTHETALATCfg.StartY_c,
EnvNAVXYTHETALATCfg.EndX_c, EnvNAVXYTHETALATCfg.EndY_c,
SBPL_2DGRIDSEARCH_TERM_CONDITION_TWOTIMESOPTPATH);
bNeedtoRecomputeStartHeuristics = false;
SBPL_PRINTF("2dsolcost_infullunits=%d\n",
(int)(grid2Dsearchfromstart->getlowerboundoncostfromstart_inmm(EnvNAVXYTHETALATCfg.EndX_c,
EnvNAVXYTHETALATCfg.EndY_c) /
EnvNAVXYTHETALATCfg.nominalvel_mpersecs));
}
if (bNeedtoRecomputeGoalHeuristics && bGoalHeuristics) {
grid2Dsearchfromgoal->search(EnvNAVXYTHETALATCfg.Grid2D, EnvNAVXYTHETALATCfg.cost_inscribed_thresh,
EnvNAVXYTHETALATCfg.EndX_c, EnvNAVXYTHETALATCfg.EndY_c,
EnvNAVXYTHETALATCfg.StartX_c, EnvNAVXYTHETALATCfg.StartY_c,
SBPL_2DGRIDSEARCH_TERM_CONDITION_TWOTIMESOPTPATH);
bNeedtoRecomputeGoalHeuristics = false;
SBPL_PRINTF("2dsolcost_infullunits=%d\n",
(int)(grid2Dsearchfromgoal->getlowerboundoncostfromstart_inmm(EnvNAVXYTHETALATCfg.StartX_c,
EnvNAVXYTHETALATCfg.StartY_c) /
EnvNAVXYTHETALATCfg.nominalvel_mpersecs));
}
}
void EnvironmentNAVXYTHETALATTICE::ComputeHeuristicValues()
{
//whatever necessary pre-computation of heuristic values is done here
SBPL_PRINTF("Precomputing heuristics...\n");
//allocated 2D grid searches
grid2Dsearchfromstart = new SBPL2DGridSearch(EnvNAVXYTHETALATCfg.EnvWidth_c, EnvNAVXYTHETALATCfg.EnvHeight_c,
(float)EnvNAVXYTHETALATCfg.cellsize_m);
grid2Dsearchfromgoal = new SBPL2DGridSearch(EnvNAVXYTHETALATCfg.EnvWidth_c, EnvNAVXYTHETALATCfg.EnvHeight_c,
(float)EnvNAVXYTHETALATCfg.cellsize_m);
//set OPEN type to sliding buckets
grid2Dsearchfromstart->setOPENdatastructure(SBPL_2DGRIDSEARCH_OPENTYPE_SLIDINGBUCKETS);
grid2Dsearchfromgoal->setOPENdatastructure(SBPL_2DGRIDSEARCH_OPENTYPE_SLIDINGBUCKETS);
SBPL_PRINTF("done\n");
}
//------------debugging functions---------------------------------------------
bool EnvironmentNAVXYTHETALATTICE::CheckQuant(FILE* fOut)
{
for (double theta = -10; theta < 10; theta += 2.0 * PI_CONST / EnvNAVXYTHETALATCfg.NumThetaDirs * 0.01) {
int nTheta = ContTheta2Disc(theta, EnvNAVXYTHETALATCfg.NumThetaDirs);
double newTheta = DiscTheta2Cont(nTheta, EnvNAVXYTHETALATCfg.NumThetaDirs);
int nnewTheta = ContTheta2Disc(newTheta, EnvNAVXYTHETALATCfg.NumThetaDirs);
SBPL_FPRINTF(fOut, "theta=%f(%f)->%d->%f->%d\n", theta, theta * 180 / PI_CONST, nTheta, newTheta, nnewTheta);
if (nTheta != nnewTheta) {
SBPL_ERROR("ERROR: invalid quantization\n");
return false;
}
}
return true;
}
//-----------------------------------------------------------------------------
//-----------interface with outside functions-----------------------------------
bool EnvironmentNAVXYTHETALATTICE::InitializeEnv(const char* sEnvFile, const vector<sbpl_2Dpt_t>& perimeterptsV,
const char* sMotPrimFile)
{
EnvNAVXYTHETALATCfg.FootprintPolygon = perimeterptsV;
FILE* fCfg = fopen(sEnvFile, "r");
if (fCfg == NULL) {
SBPL_ERROR("ERROR: unable to open %s\n", sEnvFile);
throw new SBPL_Exception();
}
ReadConfiguration(fCfg);
fclose(fCfg);
if (sMotPrimFile != NULL) {
FILE* fMotPrim = fopen(sMotPrimFile, "r");
if (fMotPrim == NULL) {
SBPL_ERROR("ERROR: unable to open %s\n", sMotPrimFile);
throw new SBPL_Exception();
}
if (ReadMotionPrimitives(fMotPrim) == false) {
SBPL_ERROR("ERROR: failed to read in motion primitive file\n");
throw new SBPL_Exception();
}
InitGeneral(&EnvNAVXYTHETALATCfg.mprimV);
fclose(fMotPrim);
}
else
InitGeneral( NULL);
SBPL_PRINTF("size of env: %d by %d\n", EnvNAVXYTHETALATCfg.EnvWidth_c, EnvNAVXYTHETALATCfg.EnvHeight_c);
return true;
}
bool EnvironmentNAVXYTHETALATTICE::InitializeEnv(const char* sEnvFile)
{
FILE* fCfg = fopen(sEnvFile, "r");
if (fCfg == NULL) {
SBPL_ERROR("ERROR: unable to open %s\n", sEnvFile);
throw new SBPL_Exception();
}
ReadConfiguration(fCfg);
fclose(fCfg);
InitGeneral( NULL);
return true;
}
bool EnvironmentNAVXYTHETALATTICE::InitializeEnv(int width, int height, const vector<sbpl_2Dpt_t> & perimeterptsV,
double cellsize_m, double nominalvel_mpersecs,
double timetoturn45degsinplace_secs, unsigned char obsthresh,
const char* sMotPrimFile, EnvNAVXYTHETALAT_InitParms params)
{
EnvNAVXYTHETALATCfg.NumThetaDirs = params.numThetas;
return InitializeEnv(width, height, params.mapdata, params.startx, params.starty, params.starttheta, params.goalx,
params.goaly, params.goaltheta, params.goaltol_x, params.goaltol_y, params.goaltol_theta,
perimeterptsV, cellsize_m, nominalvel_mpersecs, timetoturn45degsinplace_secs, obsthresh,
sMotPrimFile);
}
bool EnvironmentNAVXYTHETALATTICE::InitializeEnv(int width, int height, const unsigned char* mapdata, double startx,
double starty, double starttheta, double goalx, double goaly,
double goaltheta, double goaltol_x, double goaltol_y,
double goaltol_theta, const vector<sbpl_2Dpt_t> & perimeterptsV,
double cellsize_m, double nominalvel_mpersecs,
double timetoturn45degsinplace_secs, unsigned char obsthresh,
const char* sMotPrimFile)
{
SBPL_PRINTF("env: initialize with width=%d height=%d start=%.3f %.3f %.3f "
"goalx=%.3f %.3f %.3f cellsize=%.3f nomvel=%.3f timetoturn=%.3f, obsthresh=%d\n",
width, height, startx, starty, starttheta, goalx, goaly, goaltheta, cellsize_m, nominalvel_mpersecs,
timetoturn45degsinplace_secs, obsthresh);
SBPL_PRINTF("NOTE: goaltol parameters currently unused\n");
SBPL_PRINTF("perimeter has size=%d\n", (unsigned int)perimeterptsV.size());
for (int i = 0; i < (int)perimeterptsV.size(); i++) {
SBPL_PRINTF("perimeter(%d) = %.4f %.4f\n", i, perimeterptsV.at(i).x, perimeterptsV.at(i).y);
}
EnvNAVXYTHETALATCfg.obsthresh = obsthresh;
//TODO - need to set the tolerance as well
SetConfiguration(width, height, mapdata, CONTXY2DISC(startx, cellsize_m), CONTXY2DISC(starty, cellsize_m),
ContTheta2Disc(starttheta, EnvNAVXYTHETALATCfg.NumThetaDirs), CONTXY2DISC(goalx, cellsize_m),
CONTXY2DISC(goaly, cellsize_m), ContTheta2Disc(goaltheta, EnvNAVXYTHETALATCfg.NumThetaDirs),
cellsize_m, nominalvel_mpersecs, timetoturn45degsinplace_secs, perimeterptsV);
if (sMotPrimFile != NULL) {
FILE* fMotPrim = fopen(sMotPrimFile, "r");
if (fMotPrim == NULL) {
SBPL_ERROR("ERROR: unable to open %s\n", sMotPrimFile);
throw new SBPL_Exception();
}
if (ReadMotionPrimitives(fMotPrim) == false) {
SBPL_ERROR("ERROR: failed to read in motion primitive file\n");
throw new SBPL_Exception();
}
fclose(fMotPrim);
}
if (EnvNAVXYTHETALATCfg.mprimV.size() != 0) {
InitGeneral(&EnvNAVXYTHETALATCfg.mprimV);
}
else
InitGeneral( NULL);
return true;
}
bool EnvironmentNAVXYTHETALATTICE::InitGeneral(vector<SBPL_xytheta_mprimitive>* motionprimitiveV)
{
//Initialize other parameters of the environment
InitializeEnvConfig(motionprimitiveV);
//initialize Environment
InitializeEnvironment();
//pre-compute heuristics
ComputeHeuristicValues();
return true;
}
bool EnvironmentNAVXYTHETALATTICE::InitializeMDPCfg(MDPConfig *MDPCfg)
{
//initialize MDPCfg with the start and goal ids
MDPCfg->goalstateid = EnvNAVXYTHETALAT.goalstateid;
MDPCfg->startstateid = EnvNAVXYTHETALAT.startstateid;
return true;
}
void EnvironmentNAVXYTHETALATTICE::PrintHeuristicValues()
{
#ifndef ROS
const char* heur = "heur.txt";
#endif
FILE* fHeur = SBPL_FOPEN(heur, "w");
if (fHeur == NULL) {
SBPL_ERROR("ERROR: could not open debug file to write heuristic\n");
throw new SBPL_Exception();
}
SBPL2DGridSearch* grid2Dsearch = NULL;
for (int i = 0; i < 2; i++) {
if (i == 0 && grid2Dsearchfromstart != NULL) {
grid2Dsearch = grid2Dsearchfromstart;
SBPL_FPRINTF(fHeur, "start heuristics:\n");
}
else if (i == 1 && grid2Dsearchfromgoal != NULL) {
grid2Dsearch = grid2Dsearchfromgoal;
SBPL_FPRINTF(fHeur, "goal heuristics:\n");
}
else
continue;
for (int y = 0; y < EnvNAVXYTHETALATCfg.EnvHeight_c; y++) {
for (int x = 0; x < EnvNAVXYTHETALATCfg.EnvWidth_c; x++) {
if (grid2Dsearch->getlowerboundoncostfromstart_inmm(x, y) < INFINITECOST)
SBPL_FPRINTF(fHeur, "%5d ", grid2Dsearch->getlowerboundoncostfromstart_inmm(x, y));
else
SBPL_FPRINTF(fHeur, "XXXXX ");
}
SBPL_FPRINTF(fHeur, "\n");
}
}
SBPL_FCLOSE(fHeur);
}
void EnvironmentNAVXYTHETALATTICE::SetAllPreds(CMDPSTATE* state)
{
//implement this if the planner needs access to predecessors
SBPL_ERROR("ERROR in EnvNAVXYTHETALAT... function: SetAllPreds is undefined\n");
throw new SBPL_Exception();
}
void EnvironmentNAVXYTHETALATTICE::GetSuccs(int SourceStateID, vector<int>* SuccIDV, vector<int>* CostV)
{
GetSuccs(SourceStateID, SuccIDV, CostV, NULL);
}
void EnvironmentNAVXYTHETALATTICE::GetLazySuccs(int SourceStateID, std::vector<int>* SuccIDV, std::vector<int>* CostV, std::vector<bool>* isTrueCost){
GetLazySuccs(SourceStateID, SuccIDV, CostV, isTrueCost, NULL);
}
void EnvironmentNAVXYTHETALATTICE::GetSuccsWithUniqueIds(int SourceStateID, std::vector<int>* SuccIDV, std::vector<int>* CostV){
GetSuccsWithUniqueIds(SourceStateID, SuccIDV, CostV, NULL);
}
void EnvironmentNAVXYTHETALATTICE::GetLazySuccsWithUniqueIds(int SourceStateID, std::vector<int>* SuccIDV, std::vector<int>* CostV, std::vector<bool>* isTrueCost){
GetLazySuccsWithUniqueIds(SourceStateID, SuccIDV, CostV, isTrueCost, NULL);
}
const EnvNAVXYTHETALATConfig_t* EnvironmentNAVXYTHETALATTICE::GetEnvNavConfig()
{
return &EnvNAVXYTHETALATCfg;
}
bool EnvironmentNAVXYTHETALATTICE::UpdateCost(int x, int y, unsigned char newcost)
{
#if DEBUG
//SBPL_FPRINTF(fDeb, "Cost updated for cell %d %d from old cost=%d to new cost=%d\n", x,y,EnvNAVXYTHETALATCfg.Grid2D[x][y], newcost);
#endif
EnvNAVXYTHETALATCfg.Grid2D[x][y] = newcost;
bNeedtoRecomputeStartHeuristics = true;
bNeedtoRecomputeGoalHeuristics = true;
return true;
}
bool EnvironmentNAVXYTHETALATTICE::SetMap(const unsigned char* mapdata)
{
int xind = -1, yind = -1;
for (xind = 0; xind < EnvNAVXYTHETALATCfg.EnvWidth_c; xind++) {
for (yind = 0; yind < EnvNAVXYTHETALATCfg.EnvHeight_c; yind++) {
EnvNAVXYTHETALATCfg.Grid2D[xind][yind] = mapdata[xind + yind * EnvNAVXYTHETALATCfg.EnvWidth_c];
}
}
bNeedtoRecomputeStartHeuristics = true;
bNeedtoRecomputeGoalHeuristics = true;
return true;
}
void EnvironmentNAVXYTHETALATTICE::PrintEnv_Config(FILE* fOut)
{
//implement this if the planner needs to print out EnvNAVXYTHETALAT. configuration
SBPL_ERROR("ERROR in EnvNAVXYTHETALAT... function: PrintEnv_Config is undefined\n");
throw new SBPL_Exception();
}
void EnvironmentNAVXYTHETALATTICE::PrintTimeStat(FILE* fOut)
{
#if TIME_DEBUG
SBPL_FPRINTF(fOut, "time3_addallout = %f secs, time_gethash = %f secs, time_createhash = %f secs, "
"time_getsuccs = %f\n",
time3_addallout/(double)CLOCKS_PER_SEC, time_gethash/(double)CLOCKS_PER_SEC,
time_createhash/(double)CLOCKS_PER_SEC, time_getsuccs/(double)CLOCKS_PER_SEC);
#endif
}
bool EnvironmentNAVXYTHETALATTICE::IsObstacle(int x, int y)
{
#if DEBUG
SBPL_FPRINTF(fDeb, "Status of cell %d %d is queried. Its cost=%d\n", x,y,EnvNAVXYTHETALATCfg.Grid2D[x][y]);
#endif
return (EnvNAVXYTHETALATCfg.Grid2D[x][y] >= EnvNAVXYTHETALATCfg.obsthresh);
}
void EnvironmentNAVXYTHETALATTICE::GetEnvParms(int *size_x, int *size_y, int* num_thetas, double* startx,
double* starty, double*starttheta, double* goalx, double* goaly,
double* goaltheta, double* cellsize_m, double* nominalvel_mpersecs,
double* timetoturn45degsinplace_secs, unsigned char* obsthresh, vector<
SBPL_xytheta_mprimitive>* mprimitiveV)
{
*num_thetas = EnvNAVXYTHETALATCfg.NumThetaDirs;
GetEnvParms(size_x, size_y, startx, starty, starttheta, goalx, goaly, goaltheta, cellsize_m, nominalvel_mpersecs,
timetoturn45degsinplace_secs, obsthresh, mprimitiveV);
}
void EnvironmentNAVXYTHETALATTICE::GetEnvParms(int *size_x, int *size_y, double* startx, double* starty,
double*starttheta, double* goalx, double* goaly, double* goaltheta,
double* cellsize_m, double* nominalvel_mpersecs,
double* timetoturn45degsinplace_secs, unsigned char* obsthresh,
vector<SBPL_xytheta_mprimitive>* mprimitiveV)
{
*size_x = EnvNAVXYTHETALATCfg.EnvWidth_c;
*size_y = EnvNAVXYTHETALATCfg.EnvHeight_c;
*startx = DISCXY2CONT(EnvNAVXYTHETALATCfg.StartX_c, EnvNAVXYTHETALATCfg.cellsize_m);
*starty = DISCXY2CONT(EnvNAVXYTHETALATCfg.StartY_c, EnvNAVXYTHETALATCfg.cellsize_m);
*starttheta = DiscTheta2Cont(EnvNAVXYTHETALATCfg.StartTheta, EnvNAVXYTHETALATCfg.NumThetaDirs);
*goalx = DISCXY2CONT(EnvNAVXYTHETALATCfg.EndX_c, EnvNAVXYTHETALATCfg.cellsize_m);
*goaly = DISCXY2CONT(EnvNAVXYTHETALATCfg.EndY_c, EnvNAVXYTHETALATCfg.cellsize_m);
*goaltheta = DiscTheta2Cont(EnvNAVXYTHETALATCfg.EndTheta, EnvNAVXYTHETALATCfg.NumThetaDirs);
*cellsize_m = EnvNAVXYTHETALATCfg.cellsize_m;
*nominalvel_mpersecs = EnvNAVXYTHETALATCfg.nominalvel_mpersecs;
*timetoturn45degsinplace_secs = EnvNAVXYTHETALATCfg.timetoturn45degsinplace_secs;
*obsthresh = EnvNAVXYTHETALATCfg.obsthresh;
*mprimitiveV = EnvNAVXYTHETALATCfg.mprimV;
}
bool EnvironmentNAVXYTHETALATTICE::PoseContToDisc(double px, double py, double pth, int &ix, int &iy, int &ith) const
{
ix = CONTXY2DISC(px, EnvNAVXYTHETALATCfg.cellsize_m);
iy = CONTXY2DISC(py, EnvNAVXYTHETALATCfg.cellsize_m);
ith = ContTheta2Disc(pth, EnvNAVXYTHETALATCfg.NumThetaDirs); // ContTheta2Disc() normalizes the angle
return (pth >= -2 * PI_CONST) && (pth <= 2 * PI_CONST) && (ix >= 0) && (ix < EnvNAVXYTHETALATCfg.EnvWidth_c) &&
(iy >= 0) && (iy < EnvNAVXYTHETALATCfg.EnvHeight_c);
}
bool EnvironmentNAVXYTHETALATTICE::PoseDiscToCont(int ix, int iy, int ith, double &px, double &py, double &pth) const
{
px = DISCXY2CONT(ix, EnvNAVXYTHETALATCfg.cellsize_m);
py = DISCXY2CONT(iy, EnvNAVXYTHETALATCfg.cellsize_m);
pth = normalizeAngle(DiscTheta2Cont(ith, EnvNAVXYTHETALATCfg.NumThetaDirs));
return (ith >= 0) && (ith < EnvNAVXYTHETALATCfg.NumThetaDirs) && (ix >= 0) &&
(ix < EnvNAVXYTHETALATCfg.EnvWidth_c) && (iy >= 0) && (iy < EnvNAVXYTHETALATCfg.EnvHeight_c);
}
unsigned char EnvironmentNAVXYTHETALATTICE::GetMapCost(int x, int y)
{
return EnvNAVXYTHETALATCfg.Grid2D[x][y];
}
bool EnvironmentNAVXYTHETALATTICE::SetEnvParameter(const char* parameter, int value)
{
if (EnvNAVXYTHETALAT.bInitialized == true) {
SBPL_ERROR("ERROR: all parameters must be set before initialization of the environment\n");
return false;
}
SBPL_PRINTF("setting parameter %s to %d\n", parameter, value);
if (strcmp(parameter, "cost_inscribed_thresh") == 0) {
if (value < 0 || value > 255) {
SBPL_ERROR("ERROR: invalid value %d for parameter %s\n", value, parameter);
return false;
}
EnvNAVXYTHETALATCfg.cost_inscribed_thresh = (unsigned char)value;
}
else if (strcmp(parameter, "cost_possibly_circumscribed_thresh") == 0) {
if (value < 0 || value > 255) {
SBPL_ERROR("ERROR: invalid value %d for parameter %s\n", value, parameter);
return false;
}
EnvNAVXYTHETALATCfg.cost_possibly_circumscribed_thresh = value;
}
else if (strcmp(parameter, "cost_obsthresh") == 0) {
if (value < 0 || value > 255) {
SBPL_ERROR("ERROR: invalid value %d for parameter %s\n", value, parameter);
return false;
}
EnvNAVXYTHETALATCfg.obsthresh = (unsigned char)value;
}
else {
SBPL_ERROR("ERROR: invalid parameter %s\n", parameter);
return false;
}
return true;
}
int EnvironmentNAVXYTHETALATTICE::GetEnvParameter(const char* parameter)
{
if (strcmp(parameter, "cost_inscribed_thresh") == 0) {
return (int)EnvNAVXYTHETALATCfg.cost_inscribed_thresh;
}
else if (strcmp(parameter, "cost_possibly_circumscribed_thresh") == 0) {
return (int)EnvNAVXYTHETALATCfg.cost_possibly_circumscribed_thresh;
}
else if (strcmp(parameter, "cost_obsthresh") == 0) {
return (int)EnvNAVXYTHETALATCfg.obsthresh;
}
else {
SBPL_ERROR("ERROR: invalid parameter %s\n", parameter);
throw new SBPL_Exception();
}
}
//------------------------------------------------------------------------------
//-----------------XYTHETA Enivornment (child) class---------------------------
EnvironmentNAVXYTHETALAT::~EnvironmentNAVXYTHETALAT()
{
SBPL_PRINTF("destroying XYTHETALAT\n");
//delete the states themselves first
for (int i = 0; i < (int)StateID2CoordTable.size(); i++) {
delete StateID2CoordTable.at(i);
StateID2CoordTable.at(i) = NULL;
}
StateID2CoordTable.clear();
//delete hashtable
if (Coord2StateIDHashTable != NULL) {
delete[] Coord2StateIDHashTable;
Coord2StateIDHashTable = NULL;
}
if (Coord2StateIDHashTable_lookup != NULL) {
delete[] Coord2StateIDHashTable_lookup;
Coord2StateIDHashTable_lookup = NULL;
}
}
void EnvironmentNAVXYTHETALAT::GetCoordFromState(int stateID, int& x, int& y, int& theta) const
{
EnvNAVXYTHETALATHashEntry_t* HashEntry = StateID2CoordTable[stateID];
x = HashEntry->X;
y = HashEntry->Y;
theta = HashEntry->Theta;
}
int EnvironmentNAVXYTHETALAT::GetStateFromCoord(int x, int y, int theta)
{
EnvNAVXYTHETALATHashEntry_t* OutHashEntry;
if ((OutHashEntry = (this->*GetHashEntry)(x, y, theta)) == NULL) {
//have to create a new entry
OutHashEntry = (this->*CreateNewHashEntry)(x, y, theta);
}
return OutHashEntry->stateID;
}
void EnvironmentNAVXYTHETALAT::ConvertStateIDPathintoXYThetaPath(vector<int>* stateIDPath,
vector<sbpl_xy_theta_pt_t>* xythetaPath)
{
vector<EnvNAVXYTHETALATAction_t*> actionV;
vector<int> CostV;
vector<int> SuccIDV;
int targetx_c, targety_c, targettheta_c;
int sourcex_c, sourcey_c, sourcetheta_c;
SBPL_PRINTF("checks=%ld\n", checks);
xythetaPath->clear();
#if DEBUG
SBPL_FPRINTF(fDeb, "converting stateid path into coordinates:\n");
#endif
for (int pind = 0; pind < (int)(stateIDPath->size()) - 1; pind++) {
int sourceID = stateIDPath->at(pind);
int targetID = stateIDPath->at(pind + 1);
#if DEBUG
GetCoordFromState(sourceID, sourcex_c, sourcey_c, sourcetheta_c);
#endif
//get successors and pick the target via the cheapest action
SuccIDV.clear();
CostV.clear();
actionV.clear();
GetSuccs(sourceID, &SuccIDV, &CostV, &actionV);
int bestcost = INFINITECOST;
int bestsind = -1;
#if DEBUG
GetCoordFromState(sourceID, sourcex_c, sourcey_c, sourcetheta_c);
GetCoordFromState(targetID, targetx_c, targety_c, targettheta_c);
SBPL_FPRINTF(fDeb, "looking for %d %d %d -> %d %d %d (numofsuccs=%d)\n", sourcex_c, sourcey_c, sourcetheta_c,
targetx_c, targety_c, targettheta_c, (int)SuccIDV.size());
#endif
for (int sind = 0; sind < (int)SuccIDV.size(); sind++) {
#if DEBUG
int x_c, y_c, theta_c;
GetCoordFromState(SuccIDV[sind], x_c, y_c, theta_c);
SBPL_FPRINTF(fDeb, "succ: %d %d %d\n", x_c, y_c, theta_c);
#endif
if (SuccIDV[sind] == targetID && CostV[sind] <= bestcost) {
bestcost = CostV[sind];
bestsind = sind;
}
}
if (bestsind == -1) {
SBPL_ERROR("ERROR: successor not found for transition:\n");
GetCoordFromState(sourceID, sourcex_c, sourcey_c, sourcetheta_c);
GetCoordFromState(targetID, targetx_c, targety_c, targettheta_c);
SBPL_PRINTF("%d %d %d -> %d %d %d\n", sourcex_c, sourcey_c, sourcetheta_c, targetx_c, targety_c,
targettheta_c);
throw new SBPL_Exception();
}
//now push in the actual path
int sourcex_c, sourcey_c, sourcetheta_c;
GetCoordFromState(sourceID, sourcex_c, sourcey_c, sourcetheta_c);
double sourcex, sourcey;
sourcex = DISCXY2CONT(sourcex_c, EnvNAVXYTHETALATCfg.cellsize_m);
sourcey = DISCXY2CONT(sourcey_c, EnvNAVXYTHETALATCfg.cellsize_m);
//TODO - when there are no motion primitives we should still print source state
for (int ipind = 0; ipind < ((int)actionV[bestsind]->intermptV.size()) - 1; ipind++) {
//translate appropriately
sbpl_xy_theta_pt_t intermpt = actionV[bestsind]->intermptV[ipind];
intermpt.x += sourcex;
intermpt.y += sourcey;
#if DEBUG
int nx = CONTXY2DISC(intermpt.x, EnvNAVXYTHETALATCfg.cellsize_m);
int ny = CONTXY2DISC(intermpt.y, EnvNAVXYTHETALATCfg.cellsize_m);
SBPL_FPRINTF(fDeb, "%.3f %.3f %.3f (%d %d %d cost=%d) ",
intermpt.x, intermpt.y, intermpt.theta,
nx, ny,
ContTheta2Disc(intermpt.theta, EnvNAVXYTHETALATCfg.NumThetaDirs), EnvNAVXYTHETALATCfg.Grid2D[nx][ny]);
if(ipind == 0) SBPL_FPRINTF(fDeb, "first (heur=%d)\n", GetStartHeuristic(sourceID));
else SBPL_FPRINTF(fDeb, "\n");
#endif
//store
xythetaPath->push_back(intermpt);
}
}
}
//returns the stateid if success, and -1 otherwise
int EnvironmentNAVXYTHETALAT::SetGoal(double x_m, double y_m, double theta_rad)
{
int x = CONTXY2DISC(x_m, EnvNAVXYTHETALATCfg.cellsize_m);
int y = CONTXY2DISC(y_m, EnvNAVXYTHETALATCfg.cellsize_m);
int theta = ContTheta2Disc(theta_rad, EnvNAVXYTHETALATCfg.NumThetaDirs);
SBPL_PRINTF("env: setting goal to %.3f %.3f %.3f (%d %d %d)\n", x_m, y_m, theta_rad, x, y, theta);
if (!IsWithinMapCell(x, y)) {
SBPL_ERROR("ERROR: trying to set a goal cell %d %d that is outside of map\n", x, y);
return -1;
}
if (!IsValidConfiguration(x, y, theta)) {
SBPL_PRINTF("WARNING: goal configuration is invalid\n");
}
EnvNAVXYTHETALATHashEntry_t* OutHashEntry;
if ((OutHashEntry = (this->*GetHashEntry)(x, y, theta)) == NULL) {
//have to create a new entry
OutHashEntry = (this->*CreateNewHashEntry)(x, y, theta);
}
//need to recompute start heuristics?
if (EnvNAVXYTHETALAT.goalstateid != OutHashEntry->stateID) {
bNeedtoRecomputeStartHeuristics = true; //because termination condition may not plan all the way to the new goal
bNeedtoRecomputeGoalHeuristics = true; //because goal heuristics change
}
EnvNAVXYTHETALAT.goalstateid = OutHashEntry->stateID;
EnvNAVXYTHETALATCfg.EndX_c = x;
EnvNAVXYTHETALATCfg.EndY_c = y;
EnvNAVXYTHETALATCfg.EndTheta = theta;
return EnvNAVXYTHETALAT.goalstateid;
}
//returns the stateid if success, and -1 otherwise
int EnvironmentNAVXYTHETALAT::SetStart(double x_m, double y_m, double theta_rad)
{
int x = CONTXY2DISC(x_m, EnvNAVXYTHETALATCfg.cellsize_m);
int y = CONTXY2DISC(y_m, EnvNAVXYTHETALATCfg.cellsize_m);
int theta = ContTheta2Disc(theta_rad, EnvNAVXYTHETALATCfg.NumThetaDirs);
if (!IsWithinMapCell(x, y)) {
SBPL_ERROR("ERROR: trying to set a start cell %d %d that is outside of map\n", x, y);
return -1;
}
SBPL_PRINTF("env: setting start to %.3f %.3f %.3f (%d %d %d)\n", x_m, y_m, theta_rad, x, y, theta);
if (!IsValidConfiguration(x, y, theta)) {
SBPL_PRINTF("WARNING: start configuration %d %d %d is invalid\n", x, y, theta);
}
EnvNAVXYTHETALATHashEntry_t* OutHashEntry;
if ((OutHashEntry = (this->*GetHashEntry)(x, y, theta)) == NULL) {
//have to create a new entry
OutHashEntry = (this->*CreateNewHashEntry)(x, y, theta);
}
//need to recompute start heuristics?
if (EnvNAVXYTHETALAT.startstateid != OutHashEntry->stateID) {
bNeedtoRecomputeStartHeuristics = true;
//because termination condition can be not all states TODO - make it dependent on term. condition
bNeedtoRecomputeGoalHeuristics = true;
}
//set start
EnvNAVXYTHETALAT.startstateid = OutHashEntry->stateID;
EnvNAVXYTHETALATCfg.StartX_c = x;
EnvNAVXYTHETALATCfg.StartY_c = y;
EnvNAVXYTHETALATCfg.StartTheta = theta;
return EnvNAVXYTHETALAT.startstateid;
}
void EnvironmentNAVXYTHETALAT::PrintState(int stateID, bool bVerbose, FILE* fOut /*=NULL*/)
{
#if DEBUG
if(stateID >= (int)StateID2CoordTable.size())
{
SBPL_ERROR("ERROR in EnvNAVXYTHETALAT... function: stateID illegal (2)\n");
throw new SBPL_Exception();
}
#endif
if (fOut == NULL) fOut = stdout;
EnvNAVXYTHETALATHashEntry_t* HashEntry = StateID2CoordTable[stateID];
if (stateID == EnvNAVXYTHETALAT.goalstateid && bVerbose) {
SBPL_FPRINTF(fOut, "the state is a goal state\n");
}
if (bVerbose)
SBPL_FPRINTF(fOut, "X=%d Y=%d Theta=%d\n", HashEntry->X, HashEntry->Y, HashEntry->Theta);
else
SBPL_FPRINTF(fOut, "%.3f %.3f %.3f\n", DISCXY2CONT(HashEntry->X, EnvNAVXYTHETALATCfg.cellsize_m),
DISCXY2CONT(HashEntry->Y, EnvNAVXYTHETALATCfg.cellsize_m),
DiscTheta2Cont(HashEntry->Theta, EnvNAVXYTHETALATCfg.NumThetaDirs));
}
EnvNAVXYTHETALATHashEntry_t* EnvironmentNAVXYTHETALAT::GetHashEntry_lookup(int X, int Y, int Theta)
{
if (X < 0 || X >= EnvNAVXYTHETALATCfg.EnvWidth_c || Y < 0 || Y >= EnvNAVXYTHETALATCfg.EnvHeight_c || Theta < 0 ||
Theta >= EnvNAVXYTHETALATCfg.NumThetaDirs) return NULL;
int index = XYTHETA2INDEX(X,Y,Theta);
return Coord2StateIDHashTable_lookup[index];
}
EnvNAVXYTHETALATHashEntry_t* EnvironmentNAVXYTHETALAT::GetHashEntry_hash(int X, int Y, int Theta)
{
#if TIME_DEBUG
clock_t currenttime = clock();
#endif
int binid = GETHASHBIN(X, Y, Theta);
#if DEBUG
if ((int)Coord2StateIDHashTable[binid].size() > 5)
{
SBPL_FPRINTF(fDeb, "WARNING: Hash table has a bin %d (X=%d Y=%d) of size %d\n",
binid, X, Y, (int)Coord2StateIDHashTable[binid].size());
PrintHashTableHist(fDeb);
}
#endif
//iterate over the states in the bin and select the perfect match
vector<EnvNAVXYTHETALATHashEntry_t*>* binV = &Coord2StateIDHashTable[binid];
for (int ind = 0; ind < (int)binV->size(); ind++) {
EnvNAVXYTHETALATHashEntry_t* hashentry = binV->at(ind);
if (hashentry->X == X && hashentry->Y == Y && hashentry->Theta == Theta) {
#if TIME_DEBUG
time_gethash += clock()-currenttime;
#endif
return hashentry;
}
}
#if TIME_DEBUG
time_gethash += clock()-currenttime;
#endif
return NULL;
}
EnvNAVXYTHETALATHashEntry_t* EnvironmentNAVXYTHETALAT::CreateNewHashEntry_lookup(int X, int Y, int Theta)
{
int i;
#if TIME_DEBUG
clock_t currenttime = clock();
#endif
EnvNAVXYTHETALATHashEntry_t* HashEntry = new EnvNAVXYTHETALATHashEntry_t;
HashEntry->X = X;
HashEntry->Y = Y;
HashEntry->Theta = Theta;
HashEntry->iteration = 0;
HashEntry->stateID = StateID2CoordTable.size();
//insert into the tables
StateID2CoordTable.push_back(HashEntry);
int index = XYTHETA2INDEX(X,Y,Theta);
#if DEBUG
if(Coord2StateIDHashTable_lookup[index] != NULL)
{
SBPL_ERROR("ERROR: creating hash entry for non-NULL hashentry\n");
throw new SBPL_Exception();
}
#endif
Coord2StateIDHashTable_lookup[index] = HashEntry;
//insert into and initialize the mappings
int* entry = new int[NUMOFINDICES_STATEID2IND];
StateID2IndexMapping.push_back(entry);
for (i = 0; i < NUMOFINDICES_STATEID2IND; i++) {
StateID2IndexMapping[HashEntry->stateID][i] = -1;
}
if (HashEntry->stateID != (int)StateID2IndexMapping.size() - 1) {
SBPL_ERROR("ERROR in Env... function: last state has incorrect stateID\n");
throw new SBPL_Exception();
}
#if TIME_DEBUG
time_createhash += clock()-currenttime;
#endif
return HashEntry;
}
EnvNAVXYTHETALATHashEntry_t* EnvironmentNAVXYTHETALAT::CreateNewHashEntry_hash(int X, int Y, int Theta)
{
int i;
#if TIME_DEBUG
clock_t currenttime = clock();
#endif
EnvNAVXYTHETALATHashEntry_t* HashEntry = new EnvNAVXYTHETALATHashEntry_t;
HashEntry->X = X;
HashEntry->Y = Y;
HashEntry->Theta = Theta;
HashEntry->iteration = 0;
HashEntry->stateID = StateID2CoordTable.size();
//insert into the tables
StateID2CoordTable.push_back(HashEntry);
//get the hash table bin
i = GETHASHBIN(HashEntry->X, HashEntry->Y, HashEntry->Theta);
//insert the entry into the bin
Coord2StateIDHashTable[i].push_back(HashEntry);
//insert into and initialize the mappings
int* entry = new int[NUMOFINDICES_STATEID2IND];
StateID2IndexMapping.push_back(entry);
for (i = 0; i < NUMOFINDICES_STATEID2IND; i++) {
StateID2IndexMapping[HashEntry->stateID][i] = -1;
}
if (HashEntry->stateID != (int)StateID2IndexMapping.size() - 1) {
SBPL_ERROR("ERROR in Env... function: last state has incorrect stateID\n");
throw new SBPL_Exception();
}
#if TIME_DEBUG
time_createhash += clock()-currenttime;
#endif
return HashEntry;
}
void EnvironmentNAVXYTHETALAT::GetSuccs(int SourceStateID, vector<int>* SuccIDV, vector<int>* CostV, vector<
EnvNAVXYTHETALATAction_t*>* actionV /*=NULL*/)
{
int aind;
#if TIME_DEBUG
clock_t currenttime = clock();
#endif
//clear the successor array
SuccIDV->clear();
CostV->clear();
SuccIDV->reserve(EnvNAVXYTHETALATCfg.actionwidth);
CostV->reserve(EnvNAVXYTHETALATCfg.actionwidth);
if (actionV != NULL) {
actionV->clear();
actionV->reserve(EnvNAVXYTHETALATCfg.actionwidth);
}
//goal state should be absorbing
if (SourceStateID == EnvNAVXYTHETALAT.goalstateid) return;
//get X, Y for the state
EnvNAVXYTHETALATHashEntry_t* HashEntry = StateID2CoordTable[SourceStateID];
//iterate through actions
for (aind = 0; aind < EnvNAVXYTHETALATCfg.actionwidth; aind++) {
EnvNAVXYTHETALATAction_t* nav3daction = &EnvNAVXYTHETALATCfg.ActionsV[(unsigned int)HashEntry->Theta][aind];
int newX = HashEntry->X + nav3daction->dX;
int newY = HashEntry->Y + nav3daction->dY;
int newTheta = NORMALIZEDISCTHETA(nav3daction->endtheta, EnvNAVXYTHETALATCfg.NumThetaDirs);
//skip the invalid cells
if (!IsValidCell(newX, newY)) continue;
//get cost
int cost = GetActionCost(HashEntry->X, HashEntry->Y, HashEntry->Theta, nav3daction);
if (cost >= INFINITECOST) continue;
EnvNAVXYTHETALATHashEntry_t* OutHashEntry;
if ((OutHashEntry = (this->*GetHashEntry)(newX, newY, newTheta)) == NULL) {
//have to create a new entry
OutHashEntry = (this->*CreateNewHashEntry)(newX, newY, newTheta);
}
SuccIDV->push_back(OutHashEntry->stateID);
CostV->push_back(cost);
if (actionV != NULL) actionV->push_back(nav3daction);
}
#if TIME_DEBUG
time_getsuccs += clock()-currenttime;
#endif
}
void EnvironmentNAVXYTHETALAT::GetPreds(int TargetStateID, vector<int>* PredIDV, vector<int>* CostV)
{
//TODO- to support tolerance, need:
// a) generate preds for goal state based on all possible goal state variable settings,
// b) change goal check condition in gethashentry c) change
// getpredsofchangedcells and getsuccsofchangedcells functions
int aind;
#if TIME_DEBUG
clock_t currenttime = clock();
#endif
//get X, Y for the state
EnvNAVXYTHETALATHashEntry_t* HashEntry = StateID2CoordTable[TargetStateID];
//clear the successor array
PredIDV->clear();
CostV->clear();
PredIDV->reserve(EnvNAVXYTHETALATCfg.PredActionsV[(unsigned int)HashEntry->Theta].size());
CostV->reserve(EnvNAVXYTHETALATCfg.PredActionsV[(unsigned int)HashEntry->Theta].size());
//iterate through actions
vector<EnvNAVXYTHETALATAction_t*>* actionsV = &EnvNAVXYTHETALATCfg.PredActionsV[(unsigned int)HashEntry->Theta];
for (aind = 0; aind < (int)EnvNAVXYTHETALATCfg.PredActionsV[(unsigned int)HashEntry->Theta].size(); aind++) {
EnvNAVXYTHETALATAction_t* nav3daction = actionsV->at(aind);
int predX = HashEntry->X - nav3daction->dX;
int predY = HashEntry->Y - nav3daction->dY;
int predTheta = nav3daction->starttheta;
//skip the invalid cells
if (!IsValidCell(predX, predY)) continue;
//get cost
int cost = GetActionCost(predX, predY, predTheta, nav3daction);
if (cost >= INFINITECOST) continue;
EnvNAVXYTHETALATHashEntry_t* OutHashEntry;
if ((OutHashEntry = (this->*GetHashEntry)(predX, predY, predTheta)) == NULL) {
//have to create a new entry
OutHashEntry = (this->*CreateNewHashEntry)(predX, predY, predTheta);
}
PredIDV->push_back(OutHashEntry->stateID);
CostV->push_back(cost);
}
#if TIME_DEBUG
time_getsuccs += clock()-currenttime;
#endif
}
void EnvironmentNAVXYTHETALAT::SetAllActionsandAllOutcomes(CMDPSTATE* state)
{
int cost;
#if DEBUG
if(state->StateID >= (int)StateID2CoordTable.size())
{
SBPL_ERROR("ERROR in Env... function: stateID illegal\n");
throw new SBPL_Exception();
}
if((int)state->Actions.size() != 0)
{
SBPL_ERROR("ERROR in Env_setAllActionsandAllOutcomes: actions already exist for the state\n");
throw new SBPL_Exception();
}
#endif
//goal state should be absorbing
if (state->StateID == EnvNAVXYTHETALAT.goalstateid) return;
//get X, Y for the state
EnvNAVXYTHETALATHashEntry_t* HashEntry = StateID2CoordTable[state->StateID];
//iterate through actions
for (int aind = 0; aind < EnvNAVXYTHETALATCfg.actionwidth; aind++) {
EnvNAVXYTHETALATAction_t* nav3daction = &EnvNAVXYTHETALATCfg.ActionsV[(unsigned int)HashEntry->Theta][aind];
int newX = HashEntry->X + nav3daction->dX;
int newY = HashEntry->Y + nav3daction->dY;
int newTheta = NORMALIZEDISCTHETA(nav3daction->endtheta, EnvNAVXYTHETALATCfg.NumThetaDirs);
//skip the invalid cells
if (!IsValidCell(newX, newY)) continue;
//get cost
cost = GetActionCost(HashEntry->X, HashEntry->Y, HashEntry->Theta, nav3daction);
if (cost >= INFINITECOST) continue;
//add the action
CMDPACTION* action = state->AddAction(aind);
#if TIME_DEBUG
clock_t currenttime = clock();
#endif
EnvNAVXYTHETALATHashEntry_t* OutHashEntry;
if ((OutHashEntry = (this->*GetHashEntry)(newX, newY, newTheta)) == NULL) {
//have to create a new entry
OutHashEntry = (this->*CreateNewHashEntry)(newX, newY, newTheta);
}
action->AddOutcome(OutHashEntry->stateID, cost, 1.0);
#if TIME_DEBUG
time3_addallout += clock()-currenttime;
#endif
}
}
void EnvironmentNAVXYTHETALAT::GetPredsofChangedEdges(vector<nav2dcell_t> const * changedcellsV,
vector<int> *preds_of_changededgesIDV)
{
nav2dcell_t cell;
sbpl_xy_theta_cell_t affectedcell;
EnvNAVXYTHETALATHashEntry_t* affectedHashEntry;
//increment iteration for processing savings
iteration++;
for (int i = 0; i < (int)changedcellsV->size(); i++) {
cell = changedcellsV->at(i);
//now iterate over all states that could potentially be affected
for (int sind = 0; sind < (int)affectedpredstatesV.size(); sind++) {
affectedcell = affectedpredstatesV.at(sind);
//translate to correct for the offset
affectedcell.x = affectedcell.x + cell.x;
affectedcell.y = affectedcell.y + cell.y;
//insert only if it was actually generated
affectedHashEntry = (this->*GetHashEntry)(affectedcell.x, affectedcell.y, affectedcell.theta);
if (affectedHashEntry != NULL && affectedHashEntry->iteration < iteration) {
preds_of_changededgesIDV->push_back(affectedHashEntry->stateID);
affectedHashEntry->iteration = iteration; //mark as already inserted
}
}
}
}
void EnvironmentNAVXYTHETALAT::GetSuccsofChangedEdges(vector<nav2dcell_t> const * changedcellsV,
vector<int> *succs_of_changededgesIDV)
{
nav2dcell_t cell;
sbpl_xy_theta_cell_t affectedcell;
EnvNAVXYTHETALATHashEntry_t* affectedHashEntry;
SBPL_ERROR("ERROR: getsuccs is not supported currently\n");
throw new SBPL_Exception();
//increment iteration for processing savings
iteration++;
//TODO - check
for (int i = 0; i < (int)changedcellsV->size(); i++) {
cell = changedcellsV->at(i);
//now iterate over all states that could potentially be affected
for (int sind = 0; sind < (int)affectedsuccstatesV.size(); sind++) {
affectedcell = affectedsuccstatesV.at(sind);
//translate to correct for the offset
affectedcell.x = affectedcell.x + cell.x;
affectedcell.y = affectedcell.y + cell.y;
//insert only if it was actually generated
affectedHashEntry = (this->*GetHashEntry)(affectedcell.x, affectedcell.y, affectedcell.theta);
if (affectedHashEntry != NULL && affectedHashEntry->iteration < iteration) {
succs_of_changededgesIDV->push_back(affectedHashEntry->stateID);
affectedHashEntry->iteration = iteration; //mark as already inserted
}
}
}
}
void EnvironmentNAVXYTHETALAT::InitializeEnvironment()
{
EnvNAVXYTHETALATHashEntry_t* HashEntry;
int maxsize = EnvNAVXYTHETALATCfg.EnvWidth_c * EnvNAVXYTHETALATCfg.EnvHeight_c * EnvNAVXYTHETALATCfg.NumThetaDirs;
if (maxsize <= SBPL_XYTHETALAT_MAXSTATESFORLOOKUP) {
SBPL_PRINTF("environment stores states in lookup table\n");
Coord2StateIDHashTable_lookup = new EnvNAVXYTHETALATHashEntry_t*[maxsize];
for (int i = 0; i < maxsize; i++)
Coord2StateIDHashTable_lookup[i] = NULL;
GetHashEntry = &EnvironmentNAVXYTHETALAT::GetHashEntry_lookup;
CreateNewHashEntry = &EnvironmentNAVXYTHETALAT::CreateNewHashEntry_lookup;
//not using hash table
HashTableSize = 0;
Coord2StateIDHashTable = NULL;
}
else {
SBPL_PRINTF("environment stores states in hashtable\n");
//initialize the map from Coord to StateID
HashTableSize = 4 * 1024 * 1024; //should be power of two
Coord2StateIDHashTable = new vector<EnvNAVXYTHETALATHashEntry_t*> [HashTableSize];
GetHashEntry = &EnvironmentNAVXYTHETALAT::GetHashEntry_hash;
CreateNewHashEntry = &EnvironmentNAVXYTHETALAT::CreateNewHashEntry_hash;
//not using hash
Coord2StateIDHashTable_lookup = NULL;
}
//initialize the map from StateID to Coord
StateID2CoordTable.clear();
//create start state
if ((HashEntry = (this->*GetHashEntry)(EnvNAVXYTHETALATCfg.StartX_c, EnvNAVXYTHETALATCfg.StartY_c,
EnvNAVXYTHETALATCfg.StartTheta)) == NULL) {
//have to create a new entry
HashEntry = (this->*CreateNewHashEntry)(EnvNAVXYTHETALATCfg.StartX_c, EnvNAVXYTHETALATCfg.StartY_c,
EnvNAVXYTHETALATCfg.StartTheta);
}
EnvNAVXYTHETALAT.startstateid = HashEntry->stateID;
//create goal state
if ((HashEntry = (this->*GetHashEntry)(EnvNAVXYTHETALATCfg.EndX_c, EnvNAVXYTHETALATCfg.EndY_c,
EnvNAVXYTHETALATCfg.EndTheta)) == NULL) {
//have to create a new entry
HashEntry = (this->*CreateNewHashEntry)(EnvNAVXYTHETALATCfg.EndX_c, EnvNAVXYTHETALATCfg.EndY_c,
EnvNAVXYTHETALATCfg.EndTheta);
}
EnvNAVXYTHETALAT.goalstateid = HashEntry->stateID;
//initialized
EnvNAVXYTHETALAT.bInitialized = true;
}
//examples of hash functions: map state coordinates onto a hash value
//#define GETHASHBIN(X, Y) (Y*WIDTH_Y+X)
//here we have state coord: <X1, X2, X3, X4>
unsigned int EnvironmentNAVXYTHETALAT::GETHASHBIN(unsigned int X1, unsigned int X2, unsigned int Theta)
{
return inthash(inthash(X1) + (inthash(X2) << 1) + (inthash(Theta) << 2)) & (HashTableSize - 1);
}
void EnvironmentNAVXYTHETALAT::PrintHashTableHist(FILE* fOut)
{
int s0 = 0, s1 = 0, s50 = 0, s100 = 0, s200 = 0, s300 = 0, slarge = 0;
for (int j = 0; j < HashTableSize; j++) {
if ((int)Coord2StateIDHashTable[j].size() == 0)
s0++;
else if ((int)Coord2StateIDHashTable[j].size() < 5)
s1++;
else if ((int)Coord2StateIDHashTable[j].size() < 25)
s50++;
else if ((int)Coord2StateIDHashTable[j].size() < 50)
s100++;
else if ((int)Coord2StateIDHashTable[j].size() < 100)
s200++;
else if ((int)Coord2StateIDHashTable[j].size() < 400)
s300++;
else
slarge++;
}
SBPL_FPRINTF(fOut, "hash table histogram: 0:%d, <5:%d, <25:%d, <50:%d, <100:%d, <400:%d, >400:%d\n", s0, s1, s50,
s100, s200, s300, slarge);
}
int EnvironmentNAVXYTHETALAT::GetFromToHeuristic(int FromStateID, int ToStateID)
{
#if USE_HEUR==0
return 0;
#endif
#if DEBUG
if(FromStateID >= (int)StateID2CoordTable.size()
|| ToStateID >= (int)StateID2CoordTable.size())
{
SBPL_ERROR("ERROR in EnvNAVXYTHETALAT... function: stateID illegal\n");
throw new SBPL_Exception();
}
#endif
//get X, Y for the state
EnvNAVXYTHETALATHashEntry_t* FromHashEntry = StateID2CoordTable[FromStateID];
EnvNAVXYTHETALATHashEntry_t* ToHashEntry = StateID2CoordTable[ToStateID];
//TODO - check if one of the gridsearches already computed and then use it.
return (int)(NAVXYTHETALAT_COSTMULT_MTOMM * EuclideanDistance_m(FromHashEntry->X, FromHashEntry->Y, ToHashEntry->X,
ToHashEntry->Y) /
EnvNAVXYTHETALATCfg.nominalvel_mpersecs);
}
int EnvironmentNAVXYTHETALAT::GetGoalHeuristic(int stateID)
{
#if USE_HEUR==0
return 0;
#endif
#if DEBUG
if (stateID >= (int)StateID2CoordTable.size()) {
SBPL_ERROR("ERROR in EnvNAVXYTHETALAT... function: stateID illegal\n");
throw new SBPL_Exception();
}
#endif
EnvNAVXYTHETALATHashEntry_t* HashEntry = StateID2CoordTable[stateID];
//computes distances from start state that is grid2D, so it is EndX_c EndY_c
int h2D = grid2Dsearchfromgoal->getlowerboundoncostfromstart_inmm(HashEntry->X, HashEntry->Y);
int hEuclid = (int)(NAVXYTHETALAT_COSTMULT_MTOMM * EuclideanDistance_m(HashEntry->X, HashEntry->Y,
EnvNAVXYTHETALATCfg.EndX_c,
EnvNAVXYTHETALATCfg.EndY_c));
//define this function if it is used in the planner (heuristic backward search would use it)
return (int)(((double)__max(h2D, hEuclid)) / EnvNAVXYTHETALATCfg.nominalvel_mpersecs);
}
int EnvironmentNAVXYTHETALAT::GetStartHeuristic(int stateID)
{
#if USE_HEUR==0
return 0;
#endif
#if DEBUG
if (stateID >= (int)StateID2CoordTable.size()) {
SBPL_ERROR("ERROR in EnvNAVXYTHETALAT... function: stateID illegal\n");
throw new SBPL_Exception();
}
#endif
EnvNAVXYTHETALATHashEntry_t* HashEntry = StateID2CoordTable[stateID];
int h2D = grid2Dsearchfromstart->getlowerboundoncostfromstart_inmm(HashEntry->X, HashEntry->Y);
int hEuclid = (int)(NAVXYTHETALAT_COSTMULT_MTOMM * EuclideanDistance_m(EnvNAVXYTHETALATCfg.StartX_c,
EnvNAVXYTHETALATCfg.StartY_c, HashEntry->X,
HashEntry->Y));
//define this function if it is used in the planner (heuristic backward search would use it)
return (int)(((double)__max(h2D, hEuclid)) / EnvNAVXYTHETALATCfg.nominalvel_mpersecs);
}
int EnvironmentNAVXYTHETALAT::SizeofCreatedEnv()
{
return (int)StateID2CoordTable.size();
}
//------------------------------------------------------------------------------
void EnvironmentNAVXYTHETALAT::GetLazySuccs(int SourceStateID, std::vector<int>* SuccIDV, std::vector<int>* CostV, std::vector<bool>* isTrueCost,
std::vector<EnvNAVXYTHETALATAction_t*>* actionV /*=NULL*/)
{
int aind;
#if TIME_DEBUG
clock_t currenttime = clock();
#endif
//clear the successor array
SuccIDV->clear();
CostV->clear();
SuccIDV->reserve(EnvNAVXYTHETALATCfg.actionwidth);
CostV->reserve(EnvNAVXYTHETALATCfg.actionwidth);
isTrueCost->reserve(EnvNAVXYTHETALATCfg.actionwidth);
if (actionV != NULL) {
actionV->clear();
actionV->reserve(EnvNAVXYTHETALATCfg.actionwidth);
}
//goal state should be absorbing
if (SourceStateID == EnvNAVXYTHETALAT.goalstateid) return;
//get X, Y for the state
EnvNAVXYTHETALATHashEntry_t* HashEntry = StateID2CoordTable[SourceStateID];
//iterate through actions
for (aind = 0; aind < EnvNAVXYTHETALATCfg.actionwidth; aind++) {
EnvNAVXYTHETALATAction_t* nav3daction = &EnvNAVXYTHETALATCfg.ActionsV[(unsigned int)HashEntry->Theta][aind];
int newX = HashEntry->X + nav3daction->dX;
int newY = HashEntry->Y + nav3daction->dY;
int newTheta = NORMALIZEDISCTHETA(nav3daction->endtheta, EnvNAVXYTHETALATCfg.NumThetaDirs);
//skip the invalid cells
if (!IsValidCell(newX, newY)) continue;
if(!actionV){//if we are supposed to return the action, then don't do lazy
EnvNAVXYTHETALATHashEntry_t* OutHashEntry;
if((OutHashEntry = (this->*GetHashEntry)(newX, newY, newTheta)) == NULL)
OutHashEntry = (this->*CreateNewHashEntry)(newX, newY, newTheta);
SuccIDV->push_back(OutHashEntry->stateID);
CostV->push_back(nav3daction->cost);
isTrueCost->push_back(false);
continue;
}
//get cost
int cost = GetActionCost(HashEntry->X, HashEntry->Y, HashEntry->Theta, nav3daction);
if (cost >= INFINITECOST) continue;
EnvNAVXYTHETALATHashEntry_t* OutHashEntry;
if ((OutHashEntry = (this->*GetHashEntry)(newX, newY, newTheta)) == NULL) {
//have to create a new entry
OutHashEntry = (this->*CreateNewHashEntry)(newX, newY, newTheta);
}
SuccIDV->push_back(OutHashEntry->stateID);
CostV->push_back(cost);
isTrueCost->push_back(true);
if (actionV != NULL) actionV->push_back(nav3daction);
}
#if TIME_DEBUG
time_getsuccs += clock()-currenttime;
#endif
}
int EnvironmentNAVXYTHETALAT::GetTrueCost(int parentID, int childID){
EnvNAVXYTHETALATHashEntry_t* fromHash = StateID2CoordTable[parentID];
EnvNAVXYTHETALATHashEntry_t* toHash = StateID2CoordTable[childID];
for(int i=0; i<EnvNAVXYTHETALATCfg.actionwidth; i++){
EnvNAVXYTHETALATAction_t* nav3daction = &EnvNAVXYTHETALATCfg.ActionsV[(unsigned int)fromHash->Theta][i];
int newX = fromHash->X + nav3daction->dX;
int newY = fromHash->Y + nav3daction->dY;
int newTheta = NORMALIZEDISCTHETA(nav3daction->endtheta, EnvNAVXYTHETALATCfg.NumThetaDirs);
//skip the invalid cells
if(!IsValidCell(newX, newY))
continue;
EnvNAVXYTHETALATHashEntry_t* hash;
if((hash = (this->*GetHashEntry)(newX, newY, newTheta)) == NULL)
continue;
if(hash->stateID != toHash->stateID)
continue;
//get cost
int cost = GetActionCost(fromHash->X, fromHash->Y, fromHash->Theta, nav3daction);
if(cost >= INFINITECOST)
return -1;
return cost;
}
printf("this should never happen! we didn't find the state we need to get the true cost for!\n");
throw new SBPL_Exception();
return -1;
}
void EnvironmentNAVXYTHETALAT::GetSuccsWithUniqueIds(int SourceStateID, std::vector<int>* SuccIDV, std::vector<int>* CostV,
std::vector<EnvNAVXYTHETALATAction_t*>* actionV /*=NULL*/){
GetSuccs(SourceStateID, SuccIDV, CostV, actionV);
}
void EnvironmentNAVXYTHETALAT::GetLazySuccsWithUniqueIds(int SourceStateID, std::vector<int>* SuccIDV, std::vector<int>* CostV, std::vector<bool>* isTrueCost,
std::vector<EnvNAVXYTHETALATAction_t*>* actionV /*=NULL*/){
GetLazySuccs(SourceStateID, SuccIDV, CostV, isTrueCost, actionV);
}
bool EnvironmentNAVXYTHETALAT::isGoal(int id){
return EnvNAVXYTHETALAT.goalstateid == id;
}
//void EnvironmentNAVXYTHETALAT::GetPreds(int TargetStateID, std::vector<int>* PredIDV, std::vector<int>* CostV, std::vector<bool>* isTrueCost);
//void EnvironmentNAVXYTHETALAT::GetPredsWithUniqueIds(int TargetStateID, std::vector<int>* PredIDV, std::vector<int>* CostV);
//void EnvironmentNAVXYTHETALAT::GetPredsWithUniqueIds(int TargetStateID, std::vector<int>* PredIDV, std::vector<int>* CostV, std::vector<bool>* isTrueCost);
| [
"venkatrn@andrew.cmu.edu"
] | venkatrn@andrew.cmu.edu |
833d49454295e165d53debdf744832305d5548b5 | 2ef6a773dd5288e6526b70e484fb0ec0104529f4 | /poj.org/3654/4218559_AC_32MS_504K.cc | 87786a89144b1086a4ad3dc9cad0714ca5e46181 | [] | no_license | thebeet/online_judge_solution | f09426be6b28f157b1e5fd796c2eef99fb9978d8 | 7e8c25ff2e1f42cc9835e9cc7e25869a9dbbc0a1 | refs/heads/master | 2023-08-31T15:19:26.619898 | 2023-08-28T10:51:24 | 2023-08-28T10:51:24 | 60,448,261 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,101 | cc | /*
* PKU3654::Electronic_Document_Security.cpp
*
* Created on: Oct 9, 2008 7:09:04 PM
* Author: TheBeet
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <map>
using namespace std;
int main()
{
string inp;
int ti(0);
while ((cin >> inp), inp != "#")
{
cout << ++ti << ":";
map<char, map<char, bool> > ans;
map<char, string> ansstr;
string token;
ans.clear();
ansstr.clear();
int pos;
while (inp.size() > 0)
{
string op;
if ((pos = inp.find(',')) == inp.npos)
{
token = inp;
inp = "";
}
else
{
token = inp.substr(0, pos);
inp = inp.substr(pos + 1, inp.size() - pos - 1);
}
string left, right;
if ((pos = token.find('-')) != token.npos)
{
left = token.substr(0, pos);
right = token.substr(pos + 1, token.size() - pos - 1);
op = "-";
for (int i = 0; i < left.size(); ++i)
{
for (int j = 0; j < right.size(); ++j)
{
ans[left[i]].erase(right[j]);
}
}
}
else if ((pos = token.find('+')) != token.npos)
{
left = token.substr(0, pos);
right = token.substr(pos + 1, token.size() - pos - 1);
op = "+";
for (int i = 0; i < left.size(); ++i)
{
for (int j = 0; j < right.size(); ++j)
{
ans[left[i]][right[j]] = true;
}
}
}
else if ((pos = token.find('=')) != token.npos)
{
left = token.substr(0, pos);
right = token.substr(pos + 1, token.size() - pos - 1);
op = "=";
map<char, bool> newans;
for (int j = 0; j < right.size(); ++j)
{
newans[right[j]] = true;
}
for (int i = 0; i < left.size(); ++i)
{
ans[left[i]] = newans;
}
}
// cerr << left << " " << op << " " << right << endl;
}
char pre = '\0';
for (char a = 'A'; a <= 'Z'; ++a)
{
if (ans[a].size() == 0)
{
continue;
}
else
{
if (pre != '\0')
{
for (char b = 'a'; b <= 'z'; ++b)
{
if (ans[a][b])
{
ansstr[a].push_back(b);
}
}
if (ansstr[a] == ansstr[pre])
{
cout << a;
}
else
{
cout << ansstr[pre] << a;
}
pre = a;
}
else
{
pre = a;
for (char b = 'a'; b <= 'z'; ++b)
{
if (ans[a][b])
{
ansstr[a].push_back(b);
}
}
cout << a;
}
}
}
if (pre != '\0')
{
cout << ansstr[pre];
}
cout << endl;
}
return 0;
}
| [
"项光特"
] | 项光特 |
696cdd218ae5a086d67eecd5855d90b5e9a0baed | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/squid/gumtree/squid_new_hunk_1137.cpp | c048007cf7b72362cee5b15d4869c81e29776bb9 | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 973 | cpp |
#endif
debugs(0, DBG_IMPORTANT, "Rotate log file " << lf->path);
/* Rotate numbers 0 through N up one */
for (int16_t i = nRotate; i > 1;) {
--i;
snprintf(from, MAXPATHLEN, "%s.%d", realpath, i - 1);
snprintf(to, MAXPATHLEN, "%s.%d", realpath, i);
xrename(from, to);
}
/* Rotate the current log to .0 */
logfileFlush(lf);
file_close(ll->fd); /* always close */
if (nRotate > 0) {
snprintf(to, MAXPATHLEN, "%s.%d", realpath, 0);
xrename(realpath, to);
}
/* Reopen the log. It may have been renamed "manually" */
ll->fd = file_open(realpath, O_WRONLY | O_CREAT | O_TEXT);
if (DISK_ERROR == ll->fd && lf->flags.fatal) {
int xerrno = errno;
debugs(50, DBG_CRITICAL, MYNAME << "ERROR: " << lf->path << ": " << xstrerr(xerrno));
fatalf("Cannot open %s: %s", lf->path, xstrerr(xerrno));
}
}
static void
logfile_mod_stdio_close(Logfile * lf)
{
| [
"993273596@qq.com"
] | 993273596@qq.com |
f57281a4e1de71a14be3205d0f2661e6a7629759 | 2e7c251c97dda8031dbda355e1bc36cb8bc1a9ea | /Simp/Simp/Src/File.cpp | 8b112e7698d6e2dad3a364b7be6e6bfc0d06b76a | [] | no_license | 15831944/studies | 98677ed4bf173c4a1647f2fde2d98f9debe0f072 | 5347e517318b921aa799e11d310527be273be3fd | refs/heads/master | 2023-06-12T17:00:01.774021 | 2021-07-09T09:38:12 | 2021-07-09T09:38:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 114 | cpp | // File.cpp
//
#include "StdAfx.h"
#include <Simp/File.h>
static const _TCHAR* THIS_FILE = _T(__FILE__);
| [
"breaker.zy@gmail.com"
] | breaker.zy@gmail.com |
f1adfa1197e6fe9aa9ca1f74ece4a61cd3bd4967 | c7a3e4cd224ea63c3e05746a7ff827c27e6d411f | /majorityelement.cpp | 50d9baa9d463873a7685dd377d4682e010f36f8b | [] | no_license | Vikky357/Preparation | d06b56e3af34413e56a5a23a69bfc03e52f66912 | 696453e283627c339c71ba003838bad3dcfa31b0 | refs/heads/master | 2023-04-25T03:37:11.015019 | 2021-05-12T18:13:39 | 2021-05-12T18:13:39 | 270,175,289 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 924 | cpp | /*
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
Example 1:
Input: [3,2,3]
Output: 3
Example 2:
Input: [2,2,1,1,1,2,2]
Output: 2
*/
class Solution {
public:
int majorityElement(vector<int>& nums) {
int size=nums.size();
int index=0,count=1;
for(int i=1;i<size;i++)
{
if(nums[index]==nums[i])
count++;
else
count--;
if(!count)
{
index=i;
count=1;
}
}
return nums[index];
/*count=0;
for(int i=0;i<size;i++)
if(nums[index]==nums[i])
count++;
if(count>size/2)
return nums[index];*/
}
};
| [
"noreply@github.com"
] | Vikky357.noreply@github.com |
83a60dcfb63ee749b550abf2cef6f55c93ee21e8 | 366bc36559793ddd4ac3979f040e72dd0e2a266b | /urg_process/src/penetration_voxel_map/accident_predictor_for_penetration_voxel_map_test.h | 7d5c2a33b53079561b3d609a47fc2b29af7d3f3a | [] | no_license | seniorcar-team/seniorcar-program-ishikawa-ws | a1467b9750b455f9aa471fc2e2492ea0cd069afd | 9782a8ac33475fa60a027812b3073e69c22628a3 | refs/heads/master | 2022-02-01T21:17:31.736878 | 2019-07-31T10:06:29 | 2019-07-31T10:06:29 | 108,623,719 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,446 | h | #ifndef __ACCIDENT_PREDICTOR_H_INCLUDED__
#define __ACCIDENT_PREDICTOR_H_INCLUDED__
#include "penetration_voxel_map.h"
#include "../parameter/seniorcar_param.h"
//#include "geometry_msgs/Pose.h"
//#include <tf/transform_listener.h>
#include "ultimate_seniorcar/SeniorcarState.h"
//#include <tf/transform_datatypes.h>
#include <math.h>
//#include <algorithm>
//#include "geometry_msgs/PoseArray.h"
#include <visualization_msgs/Marker.h>
#include <stdlib.h> // rand, srand関数
#include <time.h> // time関数
/*
各種パラメータ
*/
const float CALCULATE_DISTANCE_STEP = 0.2; // 何m刻みで領域を評価するのか
const float CALCULATE_DISTANCE_LENGTH = 3.6; // 何m先までの領域を検出するのか
const float CALCULATE_STEER_DEG_STEP = 5.0; // 操舵角度何度ごとに計算を行うか
const float MAX_STEER_DEG_CHANGE = 30.0; // 今の操舵角度から何度変化するところまで計算するか
const float TIME_STEP_RESOLUTION = 0.25; // 矢印一個につき何秒刻みとするか
const int PATH_POINT_NUM = int( CALCULATE_DISTANCE_LENGTH / CALCULATE_DISTANCE_STEP ) + 1; // 1つの経路を何個の点で表現するか
const int DEG_CALCULTE_NUM = int( MAX_STEER_DEG_CHANGE * 2.0 / CALCULATE_STEER_DEG_STEP ) + 1; // 何個の経路を生成するか
const int CALC_LOOP_NUM = 1; // 1つの予測通過点に対し何回計算するか
const float SENIORCAR_DRIVABLE_PITCH_ANGLE_THRESHOLD = 10.0 * 3.14 / 180;
const float DANGER_ANGLE = 0.25; // 走れない角度
const float DANGER_Y_ZMP = SENIORCAR_HARF_TREAD_LENGTH*2 - 0.1; // ここまでZMPが来るとまずい閾値
const float MIN_VHEICLE_VELOCITY = 0.5; //考慮する車両の最低速度
const float RAD_TO_DEG = 180.0 / M_PI;
const float NOT_SET = -100;
/*
タイヤの位置を格納するための型
*/
typedef struct{
float vehicle_pose[3]; // 車両原点位置位置(x,y,th)
float tire_pos[4][4]; // 車輪位置座標((x,y,z,th)*4)
float tire_height_probability_density[4][MAP_SIZE_Z*2]; // 車輪高さを確率密度分布で表したいときのやつ
float calculated_roll_angle; // 車輪位置から計算された車両の傾き
float calculated_pitch_angle;
} CalculatedVehicleState;
typedef struct{
float steer_angle[DEG_CALCULTE_NUM];
float max_distance_to_go[DEG_CALCULTE_NUM];
} PredictResult;
enum ObjectMapStatus{
UNKNOWN = 0,
OBJECT = 1,
ROAD = 2,
};
enum TireIndexNumber{
FRONT_LEFT = 0,
FRONT_RIGHT = 1,
BACK_LEFT = 2,
BACK_RIGHT = 3,
};
/*
セニアカーの転倒転落リスクをHeightMapを元に算出するためのクラス
*/
class AccidentPredictor : public PenetrationVoxelMap
{
public:
AccidentPredictor(float pos_x,float pos_y,float pos_z);
/*
領域を走行可能か走行不可農家に識別する
一旦全部不可能として根本から計算していく感じ??
*/
void predictAccident(float pos_x,float pos_y,float pos_z,float roll,float pitch,float yaw,float vehicle_velocity);
/*
外部プログラムから結果を参照する用
*/
PredictResult returnPredictResult();
/*
可視化関連
*/
void returnCalculatedVehicleState(visualization_msgs::Marker *triangles);
private:
vector < vector < vector <float> > > predicted_path; // 走行領域 predict_path[DEG_CALCULATE_NUM][PATH_POINT_NUM][3]
vector < CalculatedVehicleState > calculated_state_array;
float now_pos_z;
vector < vector <float> > tire_calculation_point; // [x0,y0,z0],[x1,y1,z1],[x2,y2,z2]...
vector < vector <int> > tire_calculation_index; // [x0,y0,z0],[x1,y1,z1],[x2,y2,z2]...
float C_f,C_b,C_a; // ロール角計算用 φ= C_f * ⊿h_f + C_b * ⊿h_b + C_a * a_y
void generatePath(float pos_x,float pos_y,float yaw,float vehicle_velocity); // 予想経路更新
void returnTirePositionAtGivenPose(CalculatedVehicleState *return_tire_pos,vector<float> pose);
void calculateSlopeOfVehicle(CalculatedVehicleState *predicted_state);
/*
vehicle stateにおけるy方向の最大のZMP位置の絶対値を返す
*/
float calculateZMP(CalculatedVehicleState vehicle_state,float vehicle_velocity,float steer_angle_deg);
/*
四輪の中で閾値以上に高さが離れている車輪があれば転落判定を返す
*/
bool isFall(CalculatedVehicleState vehicle_state);
/*
前輪の接地高さが前のステップから段差高さ以上に高くなっていると走行できない判定
*/
bool isCollisionByTirePos(CalculatedVehicleState state_now,CalculatedVehicleState state_old);
double returnTireHeightAtGivenPositionAndPose(double x_pos,double y_pos,double tire_theta);
// 車輪の高さを確率密度関数で計算するやつ
void calculateTireHeightProbabilityDensity(CalculatedVehicleState *return_tire_height);
// 車輪の高さを確率密度関数を基にランダムサンプリングしてtire_pos[Z]に代入する
void randomSamplingTireHeighrByPropanilityDensity(CalculatedVehicleState *return_tire_height);
// 車輪の高さを確率密度関数の中で最も確率が高い高さをtire_pos[Z]に代入する
void mostLikelyTireHeightByPropanilityDensity(CalculatedVehicleState *return_tire_height);
/*
テスト用
*/
void printCalculatedState(CalculatedVehicleState state);
void printTireHeightPropabilityDensity();
void printFrontLeftTirePropabilityDensity();
void printPredictedVehicleAngle();
};
#endif | [
"noreply@github.com"
] | seniorcar-team.noreply@github.com |
5915aa2637c42c4f8e0c1b49a9524cc4d2545745 | e5922a33275ce4f56aa2679c0f6b318b4a960831 | /leetcode/NoTest/NO-62.cpp | 538a2b8b9b06c65915db5781d0b1d1fc6c0667e2 | [] | no_license | shengzhemi/MyPratice | d4d03d8d865b1642ab5b5a02d316b290dfc5a56d | 013fda7928d4ffd933e0ba3fd7396a008a3b85e3 | refs/heads/master | 2021-05-14T19:42:27.311792 | 2020-09-02T23:01:23 | 2020-09-02T23:01:23 | 115,431,823 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 439 | cpp | class Solution {
public:
int uniquePaths(int m, int n) {
if (m == 0 || n == 0) {
return 0;
}
int a[101] = {0};
a[1] = 1;
for (int i = 1; i <= m; i++) {
int last = 0;
for (int j = 1; j <= n; j++) {
int current = last + a[j];
last = current;
a[j] = current;
}
}
return a[n];
}
};
| [
"shengzhemi@foxmail.com"
] | shengzhemi@foxmail.com |
317f823d51344382aaa5632e691f0e775e142ce1 | 60e1416d08834036e7ca9cb1adb36635f7ada57e | /libpmf-1.41/util.cpp | 274ea1338ef6e00301c3d40541da5d974ef7b3cb | [
"BSD-3-Clause"
] | permissive | DavidMcDonald1993/atp | d8b807a71b14e97b90979310301103a2fcdb66ab | baa7ba751b7be7306f624043989bf3ecde3148d4 | refs/heads/master | 2020-09-12T15:03:59.448968 | 2020-06-08T10:11:20 | 2020-06-08T10:11:20 | 222,460,966 | 1 | 0 | BSD-3-Clause | 2019-11-18T13:54:31 | 2019-11-18T13:54:31 | null | UTF-8 | C++ | false | false | 5,621 | cpp | #include "util.h"
#define MALLOC(type, size) (type*)malloc(sizeof(type)*(size))
// load utility for CCS RCS
void load(const char* srcdir, smat_t &R, testset_t &T, bool with_weights){
// add testing later
char filename[1024], buf[1024];
sprintf(filename,"%s/meta",srcdir);
FILE *fp = fopen(filename,"r");
long m, n, nnz;
fscanf(fp, "%ld %ld", &m, &n);
fscanf(fp, "%ld %s", &nnz, buf);
sprintf(filename,"%s/%s", srcdir, buf);
R.load(m, n, nnz, filename, with_weights);
if(fscanf(fp, "%ld %s", &nnz, buf)!= EOF){
sprintf(filename,"%s/%s", srcdir, buf);
T.load(m, n, nnz, filename);
}
fclose(fp);
//double bias = R.get_global_mean(); R.remove_bias(bias); T.remove_bias(bias);
return ;
}
// Save a mat_t A to a file in row_major order.
// row_major = true: A is stored in row_major order,
// row_major = false: A is stored in col_major order.
void save_mat_t(mat_t A, FILE *fp, bool row_major){
if (fp == NULL)
fprintf(stderr, "output stream is not valid.\n");
long m = row_major? A.size(): A[0].size();
long n = row_major? A[0].size(): A.size();
fwrite(&m, sizeof(long), 1, fp);
fwrite(&n, sizeof(long), 1, fp);
vec_t buf(m*n);
if (row_major) {
size_t idx = 0;
for(size_t i = 0; i < m; ++i)
for(size_t j = 0; j < n; ++j)
buf[idx++] = A[i][j];
} else {
size_t idx = 0;
for(size_t i = 0; i < m; ++i)
for(size_t j = 0; j < n; ++j)
buf[idx++] = A[j][i];
}
fwrite(&buf[0], sizeof(double), m*n, fp);
}
// Load a matrix from a file and return a mat_t matrix
// row_major = true: the returned A is stored in row_major order,
// row_major = false: the returened A is stored in col_major order.
mat_t load_mat_t(FILE *fp, bool row_major){
if (fp == NULL)
fprintf(stderr, "input stream is not valid.\n");
long m, n;
fread(&m, sizeof(long), 1, fp);
fread(&n, sizeof(long), 1, fp);
vec_t buf(m*n);
fread(&buf[0], sizeof(double), m*n, fp);
mat_t A;
if (row_major) {
A = mat_t(m, vec_t(n));
size_t idx = 0;
for(size_t i = 0; i < m; ++i)
for(size_t j = 0; j < n; ++j)
A[i][j] = buf[idx++];
} else {
A = mat_t(n, vec_t(m));
size_t idx = 0;
for(size_t i = 0; i < m; ++i)
for(size_t j = 0; j < n; ++j)
A[j][i] = buf[idx++];
}
return A;
}
void initial(mat_t &X, long n, long k){
X = mat_t(n, vec_t(k));
srand48(0L);
for(long i = 0; i < n; ++i){
for(long j = 0; j < k; ++j)
X[i][j] = 0.1*drand48(); //-1;
//X[i][j] = 0; //-1;
}
}
void initial_col(mat_t &X, long k, long n){
X = mat_t(k, vec_t(n));
srand48(0L);
for(long i = 0; i < n; ++i)
for(long j = 0; j < k; ++j)
X[j][i] = 0.1*drand48();
}
double dot(const vec_t &a, const vec_t &b){
double ret = 0;
#pragma omp parallel for
for(int i = a.size()-1; i >=0; --i)
ret+=a[i]*b[i];
return ret;
}
double dot(const mat_t &W, const int i, const mat_t &H, const int j){
int k = W.size();
double ret = 0;
for(int t = 0; t < k; ++t)
ret+=W[t][i]*H[t][j];
return ret;
}
double dot(const mat_t &W, const int i, const vec_t &H_j){
int k = H_j.size();
double ret = 0;
for(int t = 0; t < k; ++t)
ret+=W[t][i]*H_j[t];
return ret;
}
double norm(const vec_t &a){
double ret = 0;
for(int i = a.size()-1; i >=0; --i)
ret+=a[i]*a[i];
return ret;
}
double norm(const mat_t &M) {
double reg = 0;
for(int i = M.size()-1; i>=0; --i) reg += norm(M[i]);
return reg;
}
double calloss(const smat_t &R, const mat_t &W, const mat_t &H){
double loss = 0;
int k = H.size();
for(long c = 0; c < R.cols; ++c){
for(long idx = R.col_ptr[c]; idx < R.col_ptr[c+1]; ++idx){
double diff = - R.val[idx];
diff += dot(W[R.row_idx[idx]], H[c]);
loss += diff*diff;
}
}
return loss;
}
double calobj(const smat_t &R, const mat_t &W, const mat_t &H, const double lambda, bool iscol){
double loss = 0;
int k = iscol?H.size():0;
vec_t Hc(k);
for(long c = 0; c < R.cols; ++c){
if(iscol)
for(int t=0;t<k;++t) Hc[t] = H[t][c];
for(long idx = R.col_ptr[c]; idx < R.col_ptr[c+1]; ++idx){
double diff = - R.val[idx];
if(iscol)
diff += dot(W, R.row_idx[idx], Hc);
else
diff += dot(W[R.row_idx[idx]], H[c]);
loss += (R.with_weights? R.weight[idx] : 1.0) * diff*diff;
}
}
double reg = 0;
if(iscol) {
for(int t=0;t<k;++t) {
for(long r=0;r<R.rows;++r) reg += W[t][r]*W[t][r]*R.nnz_of_row(r);
for(long c=0;c<R.cols;++c) reg += H[t][c]*H[t][c]*R.nnz_of_col(c);
}
} else {
for(long r=0;r<R.rows;++r) reg += R.nnz_of_row(r)*norm(W[r]);
for(long c=0;c<R.cols;++c) reg += R.nnz_of_col(c)*norm(H[c]);
}
reg *= lambda;
return loss + reg;
}
double calrmse(testset_t &testset, const mat_t &W, const mat_t &H, bool iscol){
size_t nnz = testset.nnz;
double rmse = 0, err;
for(size_t idx = 0; idx < nnz; ++idx){
err = -testset[idx].v;
if(iscol)
err += dot(W, testset[idx].i, H, testset[idx].j);
else
err += dot(W[testset[idx].i], H[testset[idx].j]);
rmse += err*err;
}
return sqrt(rmse/nnz);
}
double calrmse_r1(testset_t &testset, vec_t &Wt, vec_t &Ht){
size_t nnz = testset.nnz;
double rmse = 0, err;
#pragma omp parallel for reduction(+:rmse)
for(size_t idx = 0; idx < nnz; ++idx){
testset[idx].v -= Wt[testset[idx].i]*Ht[testset[idx].j];
rmse += testset[idx].v*testset[idx].v;
}
return sqrt(rmse/nnz);
}
double calrmse_r1(testset_t &testset, vec_t &Wt, vec_t &Ht, vec_t &oldWt, vec_t &oldHt){
size_t nnz = testset.nnz;
double rmse = 0, err;
#pragma omp parallel for reduction(+:rmse)
for(size_t idx = 0; idx < nnz; ++idx){
testset[idx].v -= Wt[testset[idx].i]*Ht[testset[idx].j] - oldWt[testset[idx].i]*oldHt[testset[idx].j];
rmse += testset[idx].v*testset[idx].v;
}
return sqrt(rmse/nnz);
}
| [
"sjk2412@163.com"
] | sjk2412@163.com |
1bd3de6ac3851eeb065847b86c10ed69716f9a31 | c40b3a302218d020820f5d557e3f21e6b09a9974 | /src/components/MCWiFi/MCWiFi.cpp | 4231a5aad33c00bf228e3d7774408da6df5342f9 | [] | no_license | manugildev/modular-cubes-embedded | f231aa55ec31c74b28ec20ff5899aaa35e7c2086 | 29eeb15bc633ff3e8a47503520978e8a500abeac | refs/heads/master | 2021-03-19T17:28:20.078397 | 2019-11-05T22:29:26 | 2019-11-05T22:29:26 | 85,623,916 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,990 | cpp | #include <ESP8266WiFi.h>
#include <components/MCWiFi/MCWiFi.h>
#include <configuration/Configuration.h>
#include <data/ModularCube.h>
void MCWiFi::setup() {
pinMode(2, OUTPUT); // Just to blink whenever is connecting
maxDevicesPerAP = 4;
String mssid = String(String(CUBES_WIFI_SSID) + "_M");
String wifiName = generateSSID();
String connectTo = getConnectTo(wifiName);
if (wifiName == mssid) {
createWiFiAP(wifiName.c_str());
Cube.setMaster(true);
if (connectToWiFi(connectTo.c_str(), WIFI_PASSWORD, 10000))
Cube.setWlan(connectTo);
WiFi.mode(WIFI_AP_STA);
IPAddress ip = WiFi.softAPIP();
Cube.setLocalIP(String(ip[3]));
} else {
if (connectToWiFi(connectTo.c_str(), "", 10000))
Cube.setWlan(connectTo);
WiFi.mode(WIFI_STA);
IPAddress ip = WiFi.localIP();
Cube.setLocalIP(String(ip[3]));
}
Cube.setAPName(wifiName);
Cube.setConnectionMode(WiFi.getMode());
}
void MCWiFi::loop() {
if (!WiFi.isConnected()) {
Serial.println("Disconnected: Rebooting...");
Cube.reboot();
}
}
// Connect to any wifi
bool MCWiFi::connectToWiFi(const char *ssid, const char *pass, int wait) {
WiFi.begin(ssid, pass);
Serial.printf("\nConnecting to %s ", ssid);
int tries = 0;
int maxTries = (wait / 100) + 1;
// We try to connect for X times, if it doesn't work we just stop
while (tries < maxTries) {
if (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
digitalWrite(2, LOW);
delay(50);
digitalWrite(2, HIGH);
delay(50);
tries++;
} else if (WiFi.status() == WL_CONNECTED) {
Serial.printf("\nConnected to %s\n", ssid);
Serial.print("Local IP: ");
Serial.println(WiFi.localIP());
return true;
} else if (WiFi.status() == WL_CONNECT_FAILED) {
digitalWrite(2, LOW);
Serial.printf("\nConnection to %s failed.\n", ssid);
}
}
digitalWrite(2, LOW);
Serial.printf("\nConnection to %s failed.\n", ssid);
return false;
}
// Checks if the wifi passed in the parameters exist, returns true or false
bool MCWiFi::checkIfWiFiExists(const char *ssid, int wait) {
Serial.printf("Trying to find %s...\n", ssid);
int tries = 0;
int maxTries = (wait / 10) + 1;
// We set the WiFi to Station Mode and Disconnect from any other WiFi
WiFi.mode(WIFI_STA);
WiFi.disconnect();
while (tries < maxTries) {
int n = WiFi.scanNetworks();
Serial.printf("%i - %i network(s) found. ", tries, n);
for (int i = 0; i < n; i++) {
if (WiFi.SSID(i) == ssid) {
return true;
}
}
Serial.printf("%s Not found.\n", ssid);
delay(10);
tries++;
}
Serial.printf("After %i tries %s could not be found.\n", tries, ssid);
return false;
}
// Creates WiFi Hotspot
bool MCWiFi::createWiFiAP(const char *ssid, const char *pass) {
Serial.printf("Starting Access Point: %s\n", ssid);
WiFi.softAP(ssid, pass);
String ip = WiFi.softAPIP().toString();
Serial.printf("AP IP adress: %s", ip.c_str());
}
// Algorithm that generates an ssid name for the current cube based on the cubes
// that are already around
String MCWiFi::generateSSID() {
const char *mssid = String(String(CUBES_WIFI_SSID) + "_M").c_str();
String smssid = String(String(CUBES_WIFI_SSID) + "_M");
if (!checkIfWiFiExists(mssid)) {
Cube.setMaster(true);
return mssid;
} else {
WiFi.mode(WIFI_STA);
WiFi.disconnect();
int n = WiFi.scanNetworks();
int maxNumber = 0;
Serial.printf("%i network(s) found. \n", n);
// This bucle should return the maximum index of the network
for (int i = 0; i < n; i++) {
String curr_ssid = WiFi.SSID(i);
if (curr_ssid.startsWith(CUBES_WIFI_SSID) && curr_ssid != smssid) {
int number = curr_ssid.substring(curr_ssid.indexOf("_") + 1).toInt();
Serial.printf("Number found %i\n", number);
if (number > maxNumber) {
maxNumber = number;
}
}
}
String previous = "";
if (maxNumber == 0) {
return String(String(CUBES_WIFI_SSID) + "_0001");
} else {
char buffer[4] = "";
sprintf(buffer, "%04d", maxNumber);
previous = buffer;
}
// Generate the SSID based on the number
String nT = previous;
char nA[nT.length() + 1];
strcpy(nA, nT.c_str());
// Reverse to work with it
const size_t len = strlen(nA);
for (size_t i = 0; i < len / 2; i++)
std::swap(nA[i], nA[len - i - 1]);
// TODO: Make this so it can fill the gaps
for (int i = 0; i < strlen(nA); i++) {
int tN = nA[i] - '0'; // Convert char to int
if (tN >= maxDevicesPerAP) {
nA[i] = '1';
} else {
nA[i] = (tN + 1) + '0';
break;
}
}
previous = String(nA);
// Reverse the string to return final string
for (size_t i = 0; i < len / 2; i++)
std::swap(nA[i], nA[len - i - 1]);
String next = String(nA);
return String(String(CUBES_WIFI_SSID) + "_" + next);
}
}
// Gets the name of the network this cube should be connecting to, based on the
// name that the generateSSID algorithm generated
String MCWiFi::getConnectTo(String apssid) {
String mssid = String(String(CUBES_WIFI_SSID) + "_M");
if (apssid == mssid) {
return WIFI_SSID;
} else {
int start = apssid.indexOf("_") + 1;
int end = apssid.length();
int number = apssid.substring(start, end).toInt();
// If the nodes are primary
if (number > 0 && number <= maxDevicesPerAP)
return mssid;
// If the nodes are not primary
char buffer[4] = "";
String snum = String(number);
int finalNum = snum.substring(0, snum.length() - 1).toInt();
sprintf(buffer, "%04d", finalNum);
return String(String(CUBES_WIFI_SSID) + "_" + buffer);
}
}
String MCWiFi::ipAdressToString(const IPAddress &ipAddress) {
return String(ipAddress[0]) + String(".") + String(ipAddress[1]) +
String(".") + String(ipAddress[2]) + String(".") +
String(ipAddress[3]);
}
MCWiFi MC_WiFi;
| [
"madtriangl3@gmail.com"
] | madtriangl3@gmail.com |
833b2a7cfab10a67277da2702a8d3b4928958669 | 999049ae2313712363c8229d04f4efc9ac167b61 | /Round366/A.cpp | 755917904385f9c4b032b9e1fd9f07e34e93569c | [] | no_license | XiaoXiaoLui/CodeForces | fa2f254c2adedf759019622598912d53d9bdfa18 | 1c4b12450a3b8be958fd81d98acb03dcfed2220d | refs/heads/master | 2021-01-11T02:09:09.927403 | 2016-10-13T16:36:50 | 2016-10-13T16:36:50 | 70,825,476 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 588 | cpp | #include <iostream>
#include <cstdio>
#include <vector>
#include <set>
#include <map>
#include <algorithm>
#include <string>
#include <cmath>
#include <cstring>
#include <queue>
using namespace std;
#define pii pair<int, int>
#define mp make_pair<int, int>
typedef long long ll;
int main()
{
string str;
int n, i;
scanf("%d", &n);
n--;
str = "I hate ";
for (i = 0; i < n; i++)
{
if (i & 1)
{
str += "that I hate ";
}
else
{
str += "that I love ";
}
}
str += "it";
printf("%s\n", str.c_str());
return 0;
} | [
"980821718@qq.com"
] | 980821718@qq.com |
169203431d9e61121f214a3d67687b64da7fadc5 | 651991951dd36e42b6b97ee9f6dcd0e632ef7f9f | /Player.h | 778647661a2556110401b92a7b90decf827d28d5 | [] | no_license | omeressa/Cpp-Ex7 | 7e67c786b55b8b9a6a03b0fa5e69e7da5d9a95c8 | ad8d01a06026b8819f2bdbcb08e95619140f21a4 | refs/heads/master | 2020-03-18T01:30:45.465066 | 2018-05-20T11:46:59 | 2018-05-20T11:46:59 | 134,145,276 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 506 | h |
#pragma once
#include "Board.h"
#include <string>
#include <exception>
class Player {
public:
char myChar;
Player(){}
Player(char c){
if (c=='O' || c== 'X')
myChar=c;
else{
throw IllegalCharException(c);
}
}
void setChar(char c) {
myChar = c;
}
char getChar(){
return myChar;
}
virtual const string name() const =0;
virtual const Coordinate play(const Board& board)=0 ;
};
| [
"noreply@github.com"
] | omeressa.noreply@github.com |
8ed4dc0fd5e2250127107b02ea8ad7f61aa48699 | 7a6e2a3492b6e237a70b12d75fd05b7a77472af3 | /cplus/expression/prac_4.32.cpp | a8e900cd19721847e4ef7839df673ce4aa04a29f | [] | no_license | timtingwei/prac | e44b7e4634a931d36ed7e09770447f5dba5f25e6 | ae77fa781934226ab1e22d6aba6dba152dd15bfe | refs/heads/master | 2020-05-21T17:53:07.144037 | 2017-10-10T14:55:52 | 2017-10-10T14:55:52 | 63,440,125 | 3 | 0 | null | null | null | null | GB18030 | C++ | false | false | 643 | cpp | #include <iostream>
#include <vector>
#include <string>
using std::cin; using std::cout; using std::endl;
using std::vector;
using std::string;
int prac_432()
{
//解释下面循环含义
constexpr int size = 5;
int ia[size] = { 1,2,3,4,5 };
//初始化 指针ptr指向数组ia的首元素,ix初始化为0;当ix值和size相等或 ptr指向尾元素的后一位,循环停止;每进行一次循环,ix+1,ptr+1,表达式返回+1后的ptr
for (int *ptr = ia, ix = 0; ix != size && ptr != ia + size; ++ix, ++ptr)
cout << ix << " " << (*ptr) << endl;
/*
输出:
0 1
1 2
2 3
3 4
4 5
*/
system("pause");
return 0;
} | [
"timtingwei@hotmail.com"
] | timtingwei@hotmail.com |
67c0045d1c4b394eebddcfe121f785cea2a2abe2 | d4f6dc94f10e4e0f230be917160d0e850f5ba86f | /server/base/test/ThreadPool_test.cc | 586efa6a6737f677c9a42adaff2d25a113470348 | [] | no_license | zxm1990/TcpServer | 10ff877e898bfdea8d60d368edac809a8fe9afd5 | cdc7007132d8c896b57ae31291fc9321eafc4494 | refs/heads/master | 2021-01-13T17:13:11.327049 | 2017-05-14T01:09:15 | 2017-05-14T01:09:15 | 81,882,115 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,161 | cc | #include <server/base/ThreadPool.h>
#include <server/base/CountDownLatch.h>
#include <server/base/CurrentThread.h>
#include <server/base/Logging.h>
#include <boost/bind.hpp>
#include <stdio.h>
void print()
{
printf("tid=%d\n", server::CurrentThread::tid());
}
void printString(const std::string& str)
{
LOG_INFO << str;
usleep(100*1000);
}
void test(int maxSize)
{
LOG_WARN << "Test ThreadPool with max queue size = " << maxSize;
server::ThreadPool pool("MainThreadPool");
pool.setMaxQueueSize(maxSize);
//创建5个线程的线程池
pool.start(5);
LOG_WARN << "Adding";
pool.run(print);
pool.run(print);
for (int i = 0; i < 100; ++i)
{
char buf[32];
snprintf(buf, sizeof buf, "task %d", i);
pool.run(boost::bind(printString, std::string(buf)));
}
LOG_WARN << "Done";
server::CountDownLatch latch(1);
pool.run(boost::bind(&server::CountDownLatch::countDown, &latch));
latch.wait();
pool.stop();
}
int main()
{
//server::Logger loger(__FILE__, __LINE__, server::Logger::TRACE, __func__);
//loger.setLogLevel(server::Logger::TRACE);
//test(0);
//test(1);
test(5);
//test(10);
//test(50);
}
| [
"hejunjian2012@163.com"
] | hejunjian2012@163.com |
4b6fbb07ec672fab32c56c91f5f2086887e49315 | 6f26f3bfea63412ff871883c6e8ad4308e31fa91 | /Character/Player.h | 22d0b191a7810b923500b1651b0ad809526ab6fa | [] | no_license | Turupawn/STGD | 6820abfc8a535ef0cc36dee2ad671134c2f93d7a | ba8c2bfd84776515f42bdf3ca4bb1323d57bef25 | refs/heads/master | 2020-06-02T04:12:53.083006 | 2014-04-08T16:01:47 | 2014-04-08T16:01:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,042 | h | #ifndef PLAYER_H
#define PLAYER_H
#include <map>
#include <list>
#include <vector>
#include "TinyXml/tinyxml.h"
#include "RosalilaGraphics/RosalilaGraphics.h"
#include "RosalilaSound/RosalilaSound.h"
#include "RosalilaInputs/RosalilaInputs.h"
#include "../Spells/Bullet.h"
#include "../Spells/Pattern.h"
#include "Character.h"
class Player : public Character
{
Image*life_bar;
//Slow bar variables
Image*slow_bar;
int slow_decrement;
int slow_increment;
int slow_cooldown_increment;
bool slow_in_cooldown;
int slow_bar_x;
int slow_bar_y;
int slow_bar_rect_offset_x;
int slow_bar_rect_offset_y;
int slow_bar_rect_height;
int slow_bar_rect_width;
Color slow_bar_color;
Color slow_bar_cooldown_color;
public:
bool raped;
int cont_release_rape;
bool unbind_right_press;
Player(Sound* sonido,RosalilaGraphics* painter,Receiver* receiver,std::string name);
void logic(int stage_velocity);
void inputControl();
void render();
void loadPlayerFromXML();
};
#endif
| [
"antares_43@hotmail.com"
] | antares_43@hotmail.com |
9929f137f0d9cdd51a6e8a85d39d74ba5be6ffba | 2905dedf5abea272613faccda8786aebd54ceede | /прогр 9.4.cpp | dbd14ca6344a536f77c3645cd6e38df07908bf86 | [] | no_license | SofaProkopeva/9 | 6a67ad157bfc647872b9fcf40db59c58fa4aee40 | 1cc4959641ed888c1852496e9ba6fe3eadfe7bc9 | refs/heads/master | 2020-10-01T20:26:24.167174 | 2019-12-12T13:56:16 | 2019-12-12T13:56:16 | 227,618,834 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,956 | cpp | #include <iostream>
using namespace std;
int main()
{
setlocale(LC_ALL, "Russian");
int a, s, d, e, o;
cout << "Введите число (100 - 999)" << endl;
cin >> a;
s = a / 100;
o = a % 100;
d = o / 10;
e = o % 10;
if (s == 1)
cout << "сто ";
if (s == 2)
cout << "двести ";
if (s == 3)
cout << "триста ";
if (s == 4)
cout << "четыреста ";
if (s == 5)
cout << "пятьсот ";
if (s == 6)
cout << "шестьсот ";
if (s == 7)
cout << "семьсот ";
if (s == 8)
cout << "восемьсот ";
if (s == 9)
cout << "девятьсот ";
if (d == 1)
{
if (e == 0)
cout << "десять ";
if (e == 1)
cout << "одиннадцать ";
if (e == 2)
cout << "двенадцать ";
if (e == 3)
cout << "тринадцать ";
if (e == 4)
cout << "четырнадцать ";
if (e == 5)
cout << "пятнадцать ";
if (e == 6)
cout << "шестнадцать ";
if (e == 7)
cout << "семнадцать ";
if (e == 8)
cout << "восемнадцать ";
if (e == 9)
cout << "девятнадцать ";
}
if (d == 2)
cout << "двадцать ";
if (d == 3)
cout << "тридцать ";
if (d == 4)
cout << "сорок ";
if (d == 5)
cout << "пятьдесят ";
if (d == 6)
cout << "шестьдесят";
if (d == 7)
cout << "семьдесят ";
if (d == 8)
cout << "восемьдесят ";
if (d == 9)
cout << "девяносто ";
if (d != 1)
{
if (e == 1)
cout << "один";
if (e == 2)
cout << "два";
if (e == 3)
cout << "три";
if (e == 4)
cout << "четыре";
if (e == 5)
cout << "пять";
if (e == 6)
cout << "шесть";
if (e == 7)
cout << "семь";
if (e == 8)
cout << "восемь";
if (e == 9)
cout << "девять";
}
}
| [
"noreply@github.com"
] | SofaProkopeva.noreply@github.com |
db095801a03755cf4fa04b12bcac9fcc7e019bc4 | b3ad4d576ef130245216bd6174d18225f491cd3a | /dreamhack-io/Memory_Corruption_C++/BOF/container-6.cpp | 6e2839f9b1748c3702e67a122fd674241954fa0f | [] | no_license | dnsdudrla97/pwn | fed44b09d1c1d12c1325401d85713ed0f403e22b | 72532e531b2cb98fb254fce5cd55889f483475a6 | refs/heads/master | 2023-02-02T18:15:29.476146 | 2020-12-22T05:41:06 | 2020-12-22T05:41:06 | 277,975,117 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 371 | cpp | // g++ -o container-6 container-6.cpp -std=c++11
#include <iostream>
#include <vector>
void f(const std::vector<int> &c) {
for(auto i = c.begin(), e = i + c.size(); i != e; ++i) {
std::cout << *i << std::endl;
}
}
int main(void) {
std::vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
v.push_back(5);
f(v);
}
| [
"dnsdudrla97@naver.com"
] | dnsdudrla97@naver.com |
591323805b1115014d4cb1d7afca5340e43ce8ab | 83bacfbdb7ad17cbc2fc897b3460de1a6726a3b1 | /third_party/WebKit/Source/core/svg/properties/SVGAnimatedProperty.cpp | 802d8a7698d3d91a052b9064fc58cbc4e0242ade | [
"Apache-2.0",
"BSD-2-Clause",
"LGPL-2.1-only",
"LGPL-2.0-only",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"GPL-1.0-or-later",
"GPL-2.0-only",
"LicenseRef-scancode-other-copyleft"
] | permissive | cool2528/miniblink49 | d909e39012f2c5d8ab658dc2a8b314ad0050d8ea | 7f646289d8074f098cf1244adc87b95e34ab87a8 | refs/heads/master | 2020-06-05T03:18:43.211372 | 2019-06-01T08:57:37 | 2019-06-01T08:59:56 | 192,294,645 | 2 | 0 | Apache-2.0 | 2019-06-17T07:16:28 | 2019-06-17T07:16:27 | null | UTF-8 | C++ | false | false | 2,526 | cpp | /*
* Copyright (C) 2013 Google 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 Google Inc. 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.
*/
#include "config.h"
#include "core/svg/properties/SVGAnimatedProperty.h"
#include "core/svg/SVGElement.h"
namespace blink {
SVGAnimatedPropertyBase::SVGAnimatedPropertyBase(AnimatedPropertyType type, SVGElement* contextElement, const QualifiedName& attributeName)
: m_type(type)
, m_isReadOnly(false)
, m_contextElement(contextElement)
, m_attributeName(attributeName)
{
ASSERT(m_contextElement);
ASSERT(m_attributeName != QualifiedName::null());
}
SVGAnimatedPropertyBase::~SVGAnimatedPropertyBase()
{
}
void SVGAnimatedPropertyBase::animationEnded()
{
synchronizeAttribute();
}
void SVGAnimatedPropertyBase::synchronizeAttribute()
{
AtomicString value(currentValueBase()->valueAsString());
m_contextElement->setSynchronizedLazyAttribute(m_attributeName, value);
}
bool SVGAnimatedPropertyBase::isSpecified() const
{
return isAnimating() || contextElement()->hasAttribute(attributeName());
}
} // namespace blink
| [
"22249030@qq.com"
] | 22249030@qq.com |
291514ec055f00ad4269325f2e551b7d70b64672 | a9ba52226f0f2f40b123aaa3a7ed798006d0f2a3 | /宝箱(Zombie's Treasure Chest, Shanghai 2011, UVa 12325)/main.cpp | 8441cc9fbda66a44c1aa8e067f3b6ab16546a8ec | [] | no_license | Wu0409/NOIP_solution | 21dd9048ec45d7386c67050c75ecb2c9381b97fb | 23815f3863c483966e7ec062c1b2cab383da0b49 | refs/heads/master | 2023-08-08T01:39:50.919380 | 2020-03-30T14:22:35 | 2020-03-30T14:22:35 | 235,752,069 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,700 | cpp | //书本P210
//考察:
//QUESTION:宝箱
//备注:这个写法在数字很小,而n很大时,枚举量太大
#include <iostream>
#include <vector>
#include <map>
using namespace std;
//体积 - 价值
int s1 = 34,v1 = 34; //option1
int s2 = 5, v2 = 3; //option2
int current_max = 0; //当前最优解
vector <int> ans;
int all_value(vector <int> result){
int value = 0;
for(int i = 0;i < result.size();i++){
result[i] == 1 ? value += v1 : value += v2;
}
return value;
}
void solution(int leftover,vector <int> result){
if(leftover < 0) return;
int minimum = min(s1,s2); int maximum = max(s1,s2);
int opt_min,opt_max;
minimum == s1? opt_min = 1,opt_max = 2 : opt_min = 2,opt_max = 1;
if(leftover < minimum){ //装不下任何东西
int all_v = all_value(result);
if(all_v > current_max){ //找到更好的解
current_max = all_v;
ans = result; //放入答案
}
return;
}
if(leftover >= minimum){
if(leftover < maximum){ //只能选择小的价值的
result.push_back(opt_min);
solution(leftover - minimum,result);
}
if(leftover >= maximum){
result.push_back(opt_min);
solution(leftover - minimum,result);
result.pop_back();
result.push_back(opt_max);
solution(leftover - maximum,result);
result.pop_back();
}
}
}
int main() {
vector <int> result;
solution(100,result);
//输出结果
for(int i:ans){
cout<<i<<" ";
}
cout<<endl;
cout<<"总价值:"<<all_value(ans)<<endl;
return 0;
}
| [
"872093177@qq.com"
] | 872093177@qq.com |
34ebb13c39440b191a15c41d6a57627ff796dfbf | 363cbc43dad2f8a3cb08ca343b95c1d08f6c60c6 | /analysis/macro/ReweightPU.cpp | 1b29fcdf3fab0dae6cb43cae56d1d33015bd593e | [] | no_license | DebabrataBhowmik/MonoHiggsToGG | 45af4363928b48d51ae50210a18a1bb19eb909c5 | b22984b06d3b1f767dcf15796c66f07581bf39f0 | refs/heads/master | 2022-01-26T02:30:39.866888 | 2019-04-02T09:50:26 | 2019-04-02T09:50:26 | 179,046,566 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 7,367 | cpp | #include "ReweightPU.hh"
ReweightPU::ReweightPU(const TString MC, const TString Data, const Double_t lumi, const Int_t nBins, const TString indir, const TString outdir, const TString type) {
// save samples for PU weighting
fMCName = MC;
fDataName = Data;
fInDir = indir;
std::cout << "Comparing " << fMCName.Data() << " vs. " << fDataName.Data() <<std::endl;
// save lumi
fLumi = lumi;
// set nBins for nvtx distribution
fNBins = nBins+1;
fMin = -0.5;
fMax = Double_t(nBins)+0.5;
// std::cout << "lumi " << lumi << " nbins " << nBins << std::endl;
// set outputs
fOutDir = outdir;
MakeOutDirectory(outdir);
fOutType = type;
// Initialize output TH1D's for data
fOutDataNvtx = new TH1D("nvtx_data","",fNBins,fMin,fMax);
fOutDataNvtx->Sumw2();
// Initialize outputs for MC
fOutMCNvtx = new TH1D("nvtx_mc","",fNBins,fMin,fMax);
fOutMCNvtx->Sumw2();
// Intialize Ratio Hist
fOutDataOverMCNvtx = new TH1D("nvtx_dataOverMC","",fNBins,fMin,fMax);
fOutDataOverMCNvtx->Sumw2();
// Initialize Output root file to be used by other macros ... eventually could integrate... no need now
fOutFile = new TFile(Form("%s/PURW_MC.root",fOutDir.Data()),"RECREATE");
}
ReweightPU::~ReweightPU() {
//delete hists
delete fOutDataNvtx;
delete fOutMCNvtx;
delete fOutDataOverMCNvtx;
//delete
delete fOutFile;
}
DblVec ReweightPU::GetPUWeights() {
DblVec puweights; // return weights
// get vtx distribution for data first
// files + trees + tmp hist for data
TString filename = Form("%s%s.root",fInDir.Data(),fDataName.Data());
TFile * fileData = TFile::Open(filename.Data());
CheckValidFile(fileData,filename);
TTree * treeData = (TTree*)fileData->Get("DiPhotonTree");
CheckValidTree(treeData,"DiPhotonTree",filename);
TH1D * tmpnvtxData = new TH1D("tmpnvtxData","",fNBins,fMin,fMax);
tmpnvtxData->Sumw2();
// fill each input data nvtx
std::cout << "Reading data nvtx: " << filename.Data() << std::endl;
treeData->Draw("nvtx>>tmpnvtxData");
// add input data hist to total data hist
fOutDataNvtx->Add(tmpnvtxData);
//tmpnvtxData->Draw();
//fOutDataNvtx->Draw();
fOutDataNvtx->Print();
// delete objects
delete tmpnvtxData;
delete treeData;
delete fileData;
// get vtx distribution for mc second
// files + trees for mc + tmp hists
filename = Form("%s%s.root",fInDir.Data(),fMCName.Data());
TFile * fileMC = TFile::Open(filename.Data());
CheckValidFile(fileMC,filename);
TTree * treeMC = (TTree*)fileMC->Get("DiPhotonTree");
CheckValidTree(treeMC,"DiPhotonTree",filename);
TH1D * tmpnvtxMC = new TH1D("tmpnvtxMC","",fNBins,fMin,fMax);
tmpnvtxMC->Sumw2();
// fill each input mc nvtx
std::cout << "Reading MC nvtx: " << filename.Data() << std::endl;
treeMC->Draw("nvtx>>tmpnvtxMC");
// add input mc hist to total mc hist
fOutMCNvtx->Add(tmpnvtxMC);
fOutMCNvtx->Print();
// delete objects
delete tmpnvtxMC;
delete treeMC;
delete fileMC;
// Set line colors
fOutDataNvtx->SetLineColor(kRed);
fOutMCNvtx->SetLineColor(kBlue);
// use these for scaling and rescaling
const Double_t int_DataNvtx = fOutDataNvtx->Integral();
const Double_t int_MCNvtx = fOutMCNvtx->Integral();
//std::cout << "DataNvtx = " << int_DataNvtx << " MCNvtx = " << int_MCNvtx << std::endl;
TCanvas * c0 = new TCanvas(); // Draw before reweighting --> unscaled
c0->cd();
c0->SetTitle("Before PU Reweighting Unnormalized");
// draw and save in output directory --> appended by what selection we used for this pu reweight
fOutDataNvtx->Draw("PE");
fOutMCNvtx->Draw("HIST SAME");
CMSLumi(c0,0,fLumi);
c0->SetLogy(1); // save log
c0->SaveAs(Form("%snvtx_%s_beforePURW_unnorm_log.%s",fOutDir.Data(),fMCName.Data(),fOutType.Data()));
c0->SetLogy(0); // save lin
c0->SaveAs(Form("%snvtx_%s_beforePURW_unnorm.%s",fOutDir.Data(),fMCName.Data(),fOutType.Data()));
/////////////////////////////////////////////
// SCALE HERE TO GET REWEIGHTING //
/////////////////////////////////////////////
// scale to unit area to not bias against data
fOutDataNvtx->Scale(1.0/int_DataNvtx);
fOutMCNvtx->Scale(1.0/int_MCNvtx);
// Draw before reweighting -- scaled
TCanvas * c1 = new TCanvas();
c1->cd();
c1->SetTitle("Before PU Reweighting Normalized");
// draw and save in output directory --> appended by what selection we used for this pu reweight
fOutDataNvtx->Draw("PE");
fOutMCNvtx->Draw("HIST SAME");
CMSLumi(c1,0,fLumi);
c1->SetLogy(1); // save log
c1->SaveAs(Form("%snvtx_%s_beforePURW_norm_log.%s",fOutDir.Data(),fMCName.Data(),fOutType.Data()));
c1->SetLogy(0); // save lin
c1->SaveAs(Form("%snvtx_%s_beforePURW_norm.%s",fOutDir.Data(),fMCName.Data(),fOutType.Data()));
/////////////////////////////////////////////
// DIVIDE HERE TO GET REWEIGHTING //
/////////////////////////////////////////////
// copy fOutDataNvtx to save output of reweights properly
for (Int_t ibin = 1; ibin <= fNBins; ibin++) {
fOutDataOverMCNvtx->SetBinContent(ibin,fOutDataNvtx->GetBinContent(ibin));
}
// divide Data/MC after copy, now this original hist will be used for reweighting
fOutDataOverMCNvtx->Divide(fOutMCNvtx);
/////////////////////////////////////////////
// STORE HERE TO USE REWEIGHTING //
/////////////////////////////////////////////
// push back reweights and then scale MC to demonstrate that it works
for (Int_t ibin = 1; ibin <= fNBins; ibin++) {
// push back reweights
puweights.push_back(fOutDataOverMCNvtx->GetBinContent(ibin));
// scale MC appropriately
Double_t tmp = fOutMCNvtx->GetBinContent(ibin);
fOutMCNvtx->SetBinContent(ibin,puweights[ibin-1]*tmp);
}
fOutFile->cd();
fOutDataOverMCNvtx->Write();
TCanvas * c = new TCanvas();
fOutDataOverMCNvtx->Draw("PE");
CMSLumi(c,0,fLumi);
c->SetLogy(1);
c->SaveAs(Form("%spurw_%s_log.%s",fOutDir.Data(),fMCName.Data(),fOutType.Data()));
c->SetLogy(0);
c->SaveAs(Form("%spurw_%s.%s",fOutDir.Data(),fMCName.Data(),fOutType.Data()));
// Draw after reweighting
TCanvas * c2 = new TCanvas();
c2->cd();
c2->SetTitle("After PU Reweighting Normalized");
// draw output and save it, see comment above about selection
fOutDataNvtx->Draw("PE");
fOutMCNvtx->Draw("HIST SAME");
CMSLumi(c2,0,fLumi);
c2->SetLogy(1); // save log
c2->SaveAs(Form("%snvtx_%s_afterPURW_norm_log.%s",fOutDir.Data(),fMCName.Data(),fOutType.Data()));
c2->SetLogy(0); // save lin
c2->SaveAs(Form("%snvtx_%s_afterPURW_norm.%s",fOutDir.Data(),fMCName.Data(),fOutType.Data()));
TCanvas * c3 = new TCanvas(); // Draw before reweighting --> unscaled
c3->cd();
c3->SetTitle("After PU Reweighting Unnormalized");
// now that the reweighting is applied, see total events again
fOutDataNvtx->Scale(int_DataNvtx);
fOutMCNvtx->Scale(int_MCNvtx);
fOutDataNvtx->Draw("PE");
fOutMCNvtx->Draw("HIST SAME");
CMSLumi(c3,0,fLumi);
c3->SetLogy(1); // save log
c3->SaveAs(Form("%snvtx_%s_afterPURW_unnorm_log.%s",fOutDir.Data(),fMCName.Data(),fOutType.Data()));
c3->SetLogy(0); // save lin
c3->SaveAs(Form("%snvtx_%s_afterPURW_unnorm.%s",fOutDir.Data(),fMCName.Data(),fOutType.Data()));
delete c0;
delete c1;
delete c2;
delete c3;
return puweights;
}
| [
"mez34@cornell.edu"
] | mez34@cornell.edu |
3a69889fd8c967b7ceec98e284c8dd21023f6e3c | 0d839be7ab1554d4632a1723afbfb286be6a6601 | /main.cpp | 46dcda86c858eff92b337393cbfc08c04910cb5f | [] | no_license | arager1/Cards | be220dc75c77acc06987bf4f2d8cdc77ce0bed19 | 2ec08c55dd138c27aab16957943442a8235e9077 | refs/heads/master | 2021-07-08T11:42:34.086977 | 2017-10-04T14:03:17 | 2017-10-04T14:03:17 | 105,773,863 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 244 | cpp | #include "Pokergame.h"
#include <iostream>
int main(){
Pokergame game;
game.addPlayer("Alec", 10000);
game.addPlayer("Nick", 10000);
game.addPlayer("Danielle", 10000);
game.addPlayer("Logan", 10000);
game.deal(7);
game.print();
}
| [
"arager@umich.edu"
] | arager@umich.edu |
3b8ee3ccb7d199b7726edb33e821310b545d2bae | 0a5f9a707ea8f5e8fe0cc5d0d631dfb9dadcdb90 | /CGUITexturedSkin.cpp | 114449f10fcdd921f76bf23452d71ad76c535e53 | [] | no_license | q4a/dakar2011 | 8adda624d997fb2d22066bcbd6d799a0604045c7 | 7f0049d132eac5bb147e860ca33d27bf03dd80c7 | refs/heads/master | 2021-04-03T20:12:54.458317 | 2010-12-22T13:01:14 | 2010-12-22T13:01:14 | 248,392,928 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 29,771 | cpp | #include "CGUITexturedSkin.h"
using namespace irr;
using namespace core;
using namespace video;
using namespace io;
using namespace gui;
namespace irr {
namespace gui {
CGUITexturedSkin::CGUITexturedSkin(IGUIEnvironment * pEnv, irr::io::IFileSystem * ifs)
{
pGuiEnv = pEnv;
pGuiEnv->grab();
pVideo = pEnv->getVideoDriver();
pVideo->grab();
pFileSystem = ifs;
pFileSystem->grab();
SpriteBank = 0;
pSkinTexture = 0;
pSkinImage = 0;
IGUIFont* builtinfont = pEnv->getBuiltInFont();
IGUIFontBitmap* bitfont = 0;
if (builtinfont && builtinfont->getType() == EGFT_BITMAP)
bitfont = (IGUIFontBitmap*)builtinfont;
if (bitfont)
setSpriteBank( bitfont->getSpriteBank() );
for (u32 i=0; i<EGDF_COUNT; ++i)
fonts[i] = 0;
colors[EGDC_3D_DARK_SHADOW] = video::SColor(101,50,50,50);
colors[EGDC_3D_SHADOW] = video::SColor(101,130,130,130);
colors[EGDC_3D_FACE] = video::SColor(101,210,210,210);
colors[EGDC_3D_HIGH_LIGHT] = video::SColor(101,255,255,255);
colors[EGDC_3D_LIGHT] = video::SColor(101,210,210,210);
colors[EGDC_ACTIVE_BORDER] = video::SColor(101,16,14,115);
colors[EGDC_ACTIVE_CAPTION] = video::SColor(200,255,255,255);
colors[EGDC_APP_WORKSPACE] = video::SColor(101,100,100,100);
colors[EGDC_BUTTON_TEXT] = video::SColor(240,10,10,10);
colors[EGDC_GRAY_TEXT] = video::SColor(240,130,130,130);
colors[EGDC_HIGH_LIGHT] = video::SColor(101,8,36,107);
colors[EGDC_HIGH_LIGHT_TEXT] = video::SColor(240,255,255,255);
colors[EGDC_INACTIVE_BORDER] = video::SColor(101,165,165,165);
colors[EGDC_INACTIVE_CAPTION] = video::SColor(101,210,210,210);
colors[EGDC_TOOLTIP] = video::SColor(200,0,0,0);
colors[EGDC_TOOLTIP_BACKGROUND]= video::SColor(200,255,255,225);
colors[EGDC_SCROLLBAR] = video::SColor(101,230,230,230);
colors[EGDC_WINDOW] = video::SColor(101,255,255,255);
colors[EGDC_WINDOW_SYMBOL] = video::SColor(200,10,10,10);
colors[EGDC_ICON] = video::SColor(200,255,255,255);
colors[EGDC_ICON_HIGH_LIGHT] = video::SColor(200,8,36,107);
sizes[EGDS_SCROLLBAR_SIZE] = 14;
sizes[EGDS_MENU_HEIGHT] = 30;
sizes[EGDS_WINDOW_BUTTON_WIDTH] = 15;
sizes[EGDS_CHECK_BOX_WIDTH] = 18;
sizes[EGDS_MESSAGE_BOX_WIDTH] = 500;
sizes[EGDS_MESSAGE_BOX_HEIGHT] = 200;
sizes[EGDS_BUTTON_WIDTH] = 80;
sizes[EGDS_BUTTON_HEIGHT] = 30;
sizes[EGDS_TEXT_DISTANCE_X] = 2;
sizes[EGDS_TEXT_DISTANCE_Y] = 0;
texts[EGDT_MSG_BOX_OK] = L"OK";
texts[EGDT_MSG_BOX_CANCEL] = L"Cancel";
texts[EGDT_MSG_BOX_YES] = L"Yes";
texts[EGDT_MSG_BOX_NO] = L"No";
texts[EGDT_WINDOW_CLOSE] = L"Close";
texts[EGDT_WINDOW_RESTORE] = L"Restore";
texts[EGDT_WINDOW_MINIMIZE] = L"Minimize";
texts[EGDT_WINDOW_MAXIMIZE] = L"Maximize";
icons[EGDI_WINDOW_MAXIMIZE] = 225;
icons[EGDI_WINDOW_RESTORE] = 226;
icons[EGDI_WINDOW_CLOSE] = 227;
icons[EGDI_WINDOW_MINIMIZE] = 228;
icons[EGDI_CURSOR_UP] = 229;
icons[EGDI_CURSOR_DOWN] = 230;
icons[EGDI_CURSOR_LEFT] = 231;
icons[EGDI_CURSOR_RIGHT] = 232;
icons[EGDI_MENU_MORE] = 232;
icons[EGDI_CHECK_BOX_CHECKED] = 0;
icons[EGDI_DROP_DOWN] = 234;
icons[EGDI_SMALL_CURSOR_UP] = 235;
icons[EGDI_SMALL_CURSOR_DOWN] = 236;
icons[EGDI_RADIO_BUTTON_CHECKED] = 237;
icons[EGDI_MORE_LEFT] = 238;
icons[EGDI_MORE_RIGHT] = 239;
icons[EGDI_MORE_UP] = 240;
icons[EGDI_MORE_DOWN] = 241;
icons[EGDI_WINDOW_RESIZE] = 242;
icons[EGDI_EXPAND] = 243;
icons[EGDI_COLLAPSE] = 244;
icons[EGDI_FILE] = 245;
icons[EGDI_DIRECTORY] = 246;
}
CGUITexturedSkin::~CGUITexturedSkin()
{
for (u32 i=0; i<EGDF_COUNT; ++i)
{
if (fonts[i])
fonts[i]->drop();
}
if (SpriteBank)
SpriteBank->drop();
if ( pSkinTexture )
{
pSkinTexture->drop();
pSkinTexture = 0;
}
if ( pSkinImage )
{
pSkinImage->drop();
pSkinImage = 0;
}
pGuiEnv->drop();
pVideo->drop();
pFileSystem->drop();
}
// Protected helper functions...
bool CGUITexturedSkin::readSkinXml( const c8 * guiSkinXmlFile )
{
IXMLReaderUTF8 * pXml = pFileSystem->createXMLReaderUTF8( guiSkinXmlFile );
if ( !pXml )
{
return false;
}
skinFilename = guiSkinXmlFile;
while ( pXml->read() )
{
if ( EXN_ELEMENT == pXml->getNodeType() )
{
if ( isNodeName( pXml, "guiskin" ) )
{
skinName = pXml->getAttributeValue( "name" );
skinTextureFilename = pXml->getAttributeValue( "texture" );
}
else if ( isNodeName( pXml, "buttonNormal" ) ) // Normal button
{
core::array< c8 * > nodeList;
nodeList.push_back( "left" );
nodeList.push_back( "middle" );
nodeList.push_back( "right" );
nodeList.push_back( "imageCoord" );
s32 texCoordIndex = ESTC_ENUM_INVALID;
s32 nodeDepth = 0;
for ( s32 findResult = findInterestedSubNode( pXml, nodeList, nodeDepth );
findResult != -1;
findResult = findInterestedSubNode( pXml, nodeList, nodeDepth ) )
{
switch ( findResult )
{
case 0:
texCoordIndex = ESTC_BUTTON_NORMAL_LEFT;
break;
case 1:
texCoordIndex = ESTC_BUTTON_NORMAL_MIDDLE;
break;
case 2:
texCoordIndex = ESTC_BUTTON_NORMAL_RIGHT;
break;
case 3:
if ( ESTC_ENUM_INVALID != texCoordIndex )
{
skinTexCoords[texCoordIndex] = decodeImageCoord( pXml );
}
break;
}
}
}
else if ( isNodeName( pXml, "buttonPressed" ) ) // Pressed button
{
core::array< c8 * > nodeList;
nodeList.push_back( "left" );
nodeList.push_back( "middle" );
nodeList.push_back( "right" );
nodeList.push_back( "imageCoord" );
s32 texCoordIndex = ESTC_ENUM_INVALID;
s32 nodeDepth = 0;
for ( s32 findResult = findInterestedSubNode( pXml, nodeList, nodeDepth );
findResult != -1;
findResult = findInterestedSubNode( pXml, nodeList, nodeDepth ) )
{
switch ( findResult )
{
case 0:
texCoordIndex = ESTC_BUTTON_PRESSED_LEFT;
break;
case 1:
texCoordIndex = ESTC_BUTTON_PRESSED_MIDDLE;
break;
case 2:
texCoordIndex = ESTC_BUTTON_PRESSED_RIGHT;
break;
case 3:
if ( ESTC_ENUM_INVALID != texCoordIndex )
{
skinTexCoords[texCoordIndex] = decodeImageCoord( pXml );
}
break;
}
}
}
else if ( isNodeName( pXml, "checkBox" ) ) // Tab button
{
core::array< c8 * > nodeList;
nodeList.push_back( "unchecked" );
nodeList.push_back( "checked" );
nodeList.push_back( "imageCoord" );
s32 checkBoxType = ESTC_CHECK_BOX_UNCHECKED;
s32 nodeDepth = 0;
for ( s32 findResult = findInterestedSubNode( pXml, nodeList, nodeDepth );
findResult != -1;
findResult = findInterestedSubNode( pXml, nodeList, nodeDepth ) )
{
switch ( findResult )
{
case 0:
checkBoxType = ESTC_CHECK_BOX_UNCHECKED;
break;
case 1:
checkBoxType = ESTC_CHECK_BOX_CHECKED;
break;
case 2:
skinTexCoords[checkBoxType] = decodeImageCoord( pXml );
break;
}
}
}
else if ( isNodeName( pXml, "menuPane" ) ) // Menu pane
{
core::array< c8 * > nodeList;
nodeList.push_back( "imageCoord" );
s32 nodeDepth = 0;
for ( s32 findResult = findInterestedSubNode( pXml, nodeList, nodeDepth );
findResult != -1;
findResult = findInterestedSubNode( pXml, nodeList, nodeDepth ) )
{
if ( 0 == findResult )
{
skinTexCoords[ESTC_MENU_PANE] = decodeImageCoord( pXml );
}
}
}
else if ( isNodeName( pXml, "sunkenPane" ) ) // Sunken pane
{
core::array< c8 * > nodeList;
nodeList.push_back( "imageCoord" );
s32 nodeDepth = 0;
for ( s32 findResult = findInterestedSubNode( pXml, nodeList, nodeDepth );
findResult != -1;
findResult = findInterestedSubNode( pXml, nodeList, nodeDepth ) )
{
if ( 0 == findResult )
{
skinTexCoords[ESTC_SUNKEN_PANE] = decodeImageCoord( pXml );
}
}
}
else if ( isNodeName( pXml, "tabBody" ) ) // Tab body
{
core::array< c8 * > nodeList;
nodeList.push_back( "imageCoord" );
s32 nodeDepth = 0;
for ( s32 findResult = findInterestedSubNode( pXml, nodeList, nodeDepth );
findResult != -1;
findResult = findInterestedSubNode( pXml, nodeList, nodeDepth ) )
{
if ( 0 == findResult )
{
skinTexCoords[ESTC_TAB_BODY] = decodeImageCoord( pXml );
}
}
}
else if ( isNodeName( pXml, "tabButton" ) ) // Tab button
{
core::array< c8 * > nodeList;
nodeList.push_back( "active" );
nodeList.push_back( "inactive" );
nodeList.push_back( "imageCoord" );
s32 buttonType = ESTC_TAB_BUTTON_ACTIVE;
s32 nodeDepth = 0;
for ( s32 findResult = findInterestedSubNode( pXml, nodeList, nodeDepth );
findResult != -1;
findResult = findInterestedSubNode( pXml, nodeList, nodeDepth ) )
{
switch ( findResult )
{
case 0:
buttonType = ESTC_TAB_BUTTON_ACTIVE;
break;
case 1:
buttonType = ESTC_TAB_BUTTON_INACTIVE;
break;
case 2:
skinTexCoords[buttonType] = decodeImageCoord( pXml );
break;
}
}
}
else if ( isNodeName( pXml, "toolBar" ) ) // Toolbar
{
core::array< c8 * > nodeList;
nodeList.push_back( "left" );
nodeList.push_back( "middle" );
nodeList.push_back( "right" );
nodeList.push_back( "imageCoord" );
s32 texCoordIndex = ESTC_ENUM_INVALID;
s32 nodeDepth = 0;
for ( s32 findResult = findInterestedSubNode( pXml, nodeList, nodeDepth );
findResult != -1;
findResult = findInterestedSubNode( pXml, nodeList, nodeDepth ) )
{
switch ( findResult )
{
case 0:
texCoordIndex = ESTC_TOOLBAR_LEFT;
break;
case 1:
texCoordIndex = ESTC_TOOLBAR_MIDDLE;
break;
case 2:
texCoordIndex = ESTC_TOOLBAR_RIGHT;
break;
case 3:
if ( ESTC_ENUM_INVALID != texCoordIndex )
{
skinTexCoords[texCoordIndex] = decodeImageCoord( pXml );
}
break;
}
}
}
else if ( isNodeName( pXml, "window" ) ) // Window
{
core::array< c8 * > nodeList;
nodeList.push_back( "upperLeftCorner" );
nodeList.push_back( "upperRightCorner" );
nodeList.push_back( "lowerLeftCorner" );
nodeList.push_back( "lowerRightCorner" );
nodeList.push_back( "upperEdge" );
nodeList.push_back( "lowerEdge" );
nodeList.push_back( "leftEdge" );
nodeList.push_back( "rightEdge" );
nodeList.push_back( "interior" );
nodeList.push_back( "titleBar" );
nodeList.push_back( "imageCoord" );
s32 texCoordIndex = ESTC_ENUM_INVALID;
s32 nodeDepth = 0;
for ( s32 findResult = findInterestedSubNode( pXml, nodeList, nodeDepth );
findResult != -1;
findResult = findInterestedSubNode( pXml, nodeList, nodeDepth ) )
{
switch ( findResult )
{
case 0:
texCoordIndex = ESTC_WINDOW_UPPER_LEFT_CORNER;
break;
case 1:
texCoordIndex = ESTC_WINDOW_UPPER_RIGHT_CORNER;
break;
case 2:
texCoordIndex = ESTC_WINDOW_LOWER_LEFT_CORNER;
break;
case 3:
texCoordIndex = ESTC_WINDOW_LOWER_RIGHT_CORNER;
break;
case 4:
texCoordIndex = ESTC_WINDOW_UPPER_EDGE;
break;
case 5:
texCoordIndex = ESTC_WINDOW_LOWER_EDGE;
break;
case 6:
texCoordIndex = ESTC_WINDOW_LEFT_EDGE;
break;
case 7:
texCoordIndex = ESTC_WINDOW_RIGHT_EDGE;
break;
case 8:
texCoordIndex = ESTC_WINDOW_INTERIOR;
tileWindowInterior = stringc( pXml->getAttributeValue( "tile" ) ).equals_ignore_case( stringc( "true" ) );
break;
case 9:
texCoordIndex = ESTC_WINDOW_TITLEBAR;
break;
case 10:
if ( ESTC_ENUM_INVALID != texCoordIndex )
{
skinTexCoords[texCoordIndex] = decodeImageCoord( pXml );
}
break;
}
}
}
}
} // end while pXml->read()
// Drop the Xml reader to free it
pXml->drop();
return true;
}
bool CGUITexturedSkin::isNodeName( IXMLReaderUTF8 * pXml, const c8 * pNodeName )
{
// do case insensitive string compare with current node name
if ( stringc( pNodeName ).equals_ignore_case( stringc( pXml->getNodeName() ) ) )
{
return true;
}
return false;
}
s32 CGUITexturedSkin::findInterestedSubNode( IXMLReaderUTF8 * pXml, core::array< c8 * > nodeList, s32 & currNodeDepth )
{
bool done = false;
while ( pXml->read() && !done )
{
if ( EXN_ELEMENT == pXml->getNodeType() )
{
currNodeDepth++;
for ( u32 i = 0; i < nodeList.size(); i++ )
{
if ( isNodeName( pXml, nodeList[i] ) )
{
return (s32)i;
}
}
}
else if ( EXN_ELEMENT_END == pXml->getNodeType() )
{
currNodeDepth--;
if ( currNodeDepth < 0 )
{
done = true;
}
}
}
return -1;
}
core::rect<s32> CGUITexturedSkin::decodeImageCoord( IXMLReaderUTF8 * pXml )
{
core::rect<s32> returnRect;
const c8 * pCoordStr = 0;
s32 index = 0;
s32 tempValue = 0;
// This stores number of coordinate values converted
s32 numCoordObtained = 0;
if ( pXml->read() && EXN_TEXT == pXml->getNodeType() )
{
pCoordStr = pXml->getNodeData();
}
else
{
return returnRect;
}
while ( pCoordStr[index] != 0 )
{
if ( pCoordStr[index] >= '0' && pCoordStr[index] <= '9' )
{
tempValue *= 10;
tempValue += (s32) (pCoordStr[index] - '0');
}
else if ( pCoordStr[index] == ',' )
{
switch ( numCoordObtained )
{
case 0:
returnRect.UpperLeftCorner.X = tempValue;
numCoordObtained++;
break;
case 1:
returnRect.UpperLeftCorner.Y = tempValue;
numCoordObtained++;
break;
case 2:
returnRect.LowerRightCorner.X = tempValue;
numCoordObtained++;
break;
case 3:
returnRect.LowerRightCorner.Y = tempValue;
numCoordObtained++;
break;
}
tempValue = 0;
}
if ( pCoordStr[index+1] == 0 )
{
// This will return the number when the end of string is reached
returnRect.LowerRightCorner.Y = tempValue;
numCoordObtained++;
}
index++;
}
return returnRect;
}
// Public function...
bool CGUITexturedSkin::setSkin( const c8 * guiSkinXmlFile )
{
if ( !readSkinXml( guiSkinXmlFile ) )
{
// fail to load or parse xml file
return false;
}
if ( pSkinTexture )
{
// release existing skin texture
pSkinTexture->drop();
pSkinTexture = 0;
}
pSkinTexture = pVideo->getTexture( skinTextureFilename.c_str() );
if ( !pSkinTexture )
{
// fail to load texture
return false;
}
pSkinTexture->grab();
if ( pSkinImage )
{
// release existing skin image
pSkinImage->drop();
pSkinImage = 0;
}
pSkinImage = pVideo->createImageFromFile( skinTextureFilename.c_str() );
if ( !pSkinImage )
{
return false;
}
return true;
}
void CGUITexturedSkin::draw3DButtonPanePressed(IGUIElement*element, const core::rect<s32> &rect, const core::rect<s32> *clip)
{
// Draw the left side
core::rect<s32> buttonPressedLeft = skinTexCoords[ESTC_BUTTON_PRESSED_LEFT];
f32 leftHtRatio = (f32)rect.getHeight() / buttonPressedLeft.getHeight();
core::rect<s32> leftDestRect = rect;
s32 leftWidth = (s32)(buttonPressedLeft.getWidth() * leftHtRatio);
leftDestRect.LowerRightCorner.X = rect.UpperLeftCorner.X + (leftWidth<=rect.getWidth()?leftWidth:rect.getWidth());
pVideo->draw2DImage(pSkinTexture,leftDestRect,buttonPressedLeft,0,0,true);
// Draw the right side
core::rect<s32> buttonPressedRight = skinTexCoords[ESTC_BUTTON_PRESSED_RIGHT];
f32 rightHtRatio = (f32)rect.getHeight() / buttonPressedRight.getHeight();
core::rect<s32> rightDestRect = rect;
s32 rightWidth = (s32)(buttonPressedRight.getWidth() * rightHtRatio);
rightDestRect.UpperLeftCorner.X = rect.LowerRightCorner.X - (rightWidth<=rect.getWidth()?rightWidth:rect.getWidth());
pVideo->draw2DImage(pSkinTexture,rightDestRect,buttonPressedRight,0,0,true);
// Draw the middle
core::rect<s32> buttonPressedMiddle = skinTexCoords[ESTC_BUTTON_PRESSED_MIDDLE];
core::rect<s32> middleDestRect = rect;
middleDestRect.UpperLeftCorner.X = leftDestRect.LowerRightCorner.X;
middleDestRect.LowerRightCorner.X = rightDestRect.UpperLeftCorner.X;
pVideo->draw2DImage(pSkinTexture,middleDestRect,buttonPressedMiddle,0,0,true);
}
void CGUITexturedSkin::draw3DButtonPaneStandard(IGUIElement *element, const core::rect<s32> &rect, const core::rect<s32> *clip)
{
// Draw the left side
core::rect<s32> buttonNormalLeft = skinTexCoords[ESTC_BUTTON_NORMAL_LEFT];
f32 leftHtRatio = (f32)rect.getHeight() / buttonNormalLeft.getHeight();
core::rect<s32> leftDestRect = rect;
s32 leftWidth = (s32)(buttonNormalLeft.getWidth() * leftHtRatio);
leftDestRect.LowerRightCorner.X = rect.UpperLeftCorner.X + (leftWidth<=rect.getWidth()?leftWidth:rect.getWidth());
pVideo->draw2DImage(pSkinTexture,leftDestRect,buttonNormalLeft,0,0,true);
// Draw the right side
core::rect<s32> buttonNormalRight = skinTexCoords[ESTC_BUTTON_NORMAL_RIGHT];
f32 rightHtRatio = (f32)rect.getHeight() / buttonNormalRight.getHeight();
core::rect<s32> rightDestRect = rect;
s32 rightWidth = (s32)(buttonNormalRight.getWidth() * rightHtRatio);
rightDestRect.UpperLeftCorner.X = rect.LowerRightCorner.X - (rightWidth<=rect.getWidth()?rightWidth:rect.getWidth());
pVideo->draw2DImage(pSkinTexture,rightDestRect,buttonNormalRight,0,0,true);
// Draw the middle
core::rect<s32> buttonNormalMiddle = skinTexCoords[ESTC_BUTTON_NORMAL_MIDDLE];
core::rect<s32> middleDestRect = rect;
middleDestRect.UpperLeftCorner.X = leftDestRect.LowerRightCorner.X;
middleDestRect.LowerRightCorner.X = rightDestRect.UpperLeftCorner.X;
pVideo->draw2DImage(pSkinTexture,middleDestRect,buttonNormalMiddle,0,0,true);
}
void CGUITexturedSkin::draw3DMenuPane(IGUIElement *element, const core::rect<s32> &rect, const core::rect<s32> *clip)
{
core::rect<s32> menuPane = skinTexCoords[ESTC_MENU_PANE];
pVideo->draw2DImage(pSkinTexture,rect,menuPane,0,0,true);
}
void CGUITexturedSkin::draw3DSunkenPane(IGUIElement *element, video::SColor bgcolor, bool flat, bool fillBackGround, const core::rect<s32> &rect, const core::rect<s32> *clip)
{
s32 type = ESTC_SUNKEN_PANE;
if ( EGUIET_CHECK_BOX == element->getType() )
{
if ( ( (IGUICheckBox*)element)->isChecked() )
{
type = ESTC_CHECK_BOX_CHECKED;
}
else
{
type = ESTC_CHECK_BOX_UNCHECKED;
}
}
core::rect<s32> sunkenPane = skinTexCoords[type];
pVideo->draw2DImage(pSkinTexture,rect,sunkenPane,0,0,true);
}
void CGUITexturedSkin::draw3DTabBody(IGUIElement *element, bool border, bool background, const core::rect<s32> &rect, const core::rect<s32> *clip
, s32 tabHeight, gui::EGUI_ALIGNMENT alignment)
{
core::rect<s32> tabBody = skinTexCoords[ESTC_TAB_BODY];
core::rect<s32> destRect = rect;
destRect.UpperLeftCorner.Y += getSize(EGDS_BUTTON_HEIGHT);
pVideo->draw2DImage(pSkinTexture,destRect,tabBody,0,0,true);
}
void CGUITexturedSkin::draw3DTabButton(IGUIElement *element, bool active, const core::rect<s32> &rect, const core::rect<s32> *clip, gui::EGUI_ALIGNMENT alignment)
{
s32 buttonType = active ? ESTC_TAB_BUTTON_ACTIVE : ESTC_TAB_BUTTON_INACTIVE;
core::rect<s32> tabButton = skinTexCoords[buttonType];
pVideo->draw2DImage(pSkinTexture,rect,tabButton,0,0,true);
}
void CGUITexturedSkin::draw3DToolBar(IGUIElement *element, const core::rect<s32> &rect, const core::rect<s32> *clip)
{
// Draw the left side
core::rect<s32> toolBarLeft = skinTexCoords[ESTC_TOOLBAR_LEFT];
f32 leftHtRatio = (f32)rect.getHeight() / toolBarLeft.getHeight();
core::rect<s32> leftDestRect = rect;
s32 leftWidth = (s32)(toolBarLeft.getWidth() * leftHtRatio);
leftDestRect.LowerRightCorner.X = rect.UpperLeftCorner.X + (leftWidth<=rect.getWidth()?leftWidth:rect.getWidth());
pVideo->draw2DImage(pSkinTexture,leftDestRect,toolBarLeft,0,0,true);
// Draw the right side
core::rect<s32> toolBarRight = skinTexCoords[ESTC_TOOLBAR_RIGHT];
f32 rightHtRatio = (f32)rect.getHeight() / toolBarRight.getHeight();
core::rect<s32> rightDestRect = rect;
s32 rightWidth = (s32)(toolBarRight.getWidth() * rightHtRatio);
rightDestRect.UpperLeftCorner.X = rect.LowerRightCorner.X - (rightWidth<=rect.getWidth()?rightWidth:rect.getWidth());
pVideo->draw2DImage(pSkinTexture,rightDestRect,toolBarRight,0,0,true);
// Draw the middle
core::rect<s32> toolBarMiddle = skinTexCoords[ESTC_TOOLBAR_MIDDLE];
core::rect<s32> middleDestRect = rect;
middleDestRect.UpperLeftCorner.X = leftDestRect.LowerRightCorner.X;
middleDestRect.LowerRightCorner.X = rightDestRect.UpperLeftCorner.X;
pVideo->draw2DImage(pSkinTexture,middleDestRect,toolBarMiddle,0,0,true);
}
core::rect< s32 > CGUITexturedSkin::draw3DWindowBackground(IGUIElement *element, bool drawTitleBar, video::SColor titleBarColor, const core::rect< s32 > &rect, const core::rect< s32 > *clip, core::rect<s32>* checkClientArea
)
{
// Draw top left corner
core::rect<s32> topLeftCorner = skinTexCoords[ESTC_WINDOW_UPPER_LEFT_CORNER];
core::rect<s32> topLeftCornerDest = rect;
topLeftCornerDest.LowerRightCorner.X = topLeftCornerDest.UpperLeftCorner.X + topLeftCorner.getWidth();
topLeftCornerDest.LowerRightCorner.Y = topLeftCornerDest.UpperLeftCorner.Y + topLeftCorner.getHeight();
pVideo->draw2DImage(pSkinTexture,topLeftCornerDest,topLeftCorner,0,0,true);
// Draw top right corner
core::rect<s32> topRightCorner = skinTexCoords[ESTC_WINDOW_UPPER_RIGHT_CORNER];
core::rect<s32> topRightCornerDest = rect;
topRightCornerDest.UpperLeftCorner.X = rect.LowerRightCorner.X - topRightCorner.getWidth();
topRightCornerDest.LowerRightCorner.Y = rect.UpperLeftCorner.Y + topRightCorner.getHeight();
pVideo->draw2DImage(pSkinTexture,topRightCornerDest,topRightCorner,0,0,true);
// Draw bottom left corner
core::rect<s32> bottomLeftCorner = skinTexCoords[ESTC_WINDOW_LOWER_LEFT_CORNER];
core::rect<s32> bottomLeftCornerDest = rect;
bottomLeftCornerDest.LowerRightCorner.X = rect.UpperLeftCorner.X + bottomLeftCorner.getWidth();
bottomLeftCornerDest.UpperLeftCorner.Y = rect.LowerRightCorner.Y - bottomLeftCorner.getHeight();
pVideo->draw2DImage(pSkinTexture,bottomLeftCornerDest,bottomLeftCorner,0,0,true);
// Draw top right corner
core::rect<s32> bottomRightCorner = skinTexCoords[ESTC_WINDOW_LOWER_RIGHT_CORNER];
core::rect<s32> bottomRightCornerDest = rect;
bottomRightCornerDest.UpperLeftCorner.X = rect.LowerRightCorner.X - bottomRightCorner.getWidth();
bottomRightCornerDest.UpperLeftCorner.Y = rect.LowerRightCorner.Y - bottomRightCorner.getHeight();
pVideo->draw2DImage(pSkinTexture,bottomRightCornerDest,bottomRightCorner,0,0,true);
// Draw top edge
core::rect<s32> topEdge = skinTexCoords[ESTC_WINDOW_UPPER_EDGE];
core::rect<s32> topEdgeDest = rect;
topEdgeDest.UpperLeftCorner.X = rect.UpperLeftCorner.X + topLeftCorner.getWidth();
topEdgeDest.LowerRightCorner.X = rect.LowerRightCorner.X - topRightCorner.getWidth();
topEdgeDest.LowerRightCorner.Y = rect.UpperLeftCorner.Y + topEdge.getHeight();
pVideo->draw2DImage(pSkinTexture,topEdgeDest,topEdge,0,0,true);
// Draw bottom edge
core::rect<s32> bottomEdge = skinTexCoords[ESTC_WINDOW_LOWER_EDGE];
core::rect<s32> bottomEdgeDest = rect;
bottomEdgeDest.UpperLeftCorner.X = rect.UpperLeftCorner.X + bottomLeftCorner.getWidth();
bottomEdgeDest.UpperLeftCorner.Y = rect.LowerRightCorner.Y - bottomEdge.getHeight();
bottomEdgeDest.LowerRightCorner.X = rect.LowerRightCorner.X - bottomRightCorner.getWidth();
pVideo->draw2DImage(pSkinTexture,bottomEdgeDest,bottomEdge,0,0,true);
// Draw left edge
core::rect<s32> leftEdge = skinTexCoords[ESTC_WINDOW_LEFT_EDGE];
core::rect<s32> leftEdgeDest = rect;
leftEdgeDest.UpperLeftCorner.Y = rect.UpperLeftCorner.Y + topLeftCorner.getHeight();
leftEdgeDest.LowerRightCorner.X = rect.UpperLeftCorner.X + leftEdge.getWidth();
leftEdgeDest.LowerRightCorner.Y = rect.LowerRightCorner.Y - bottomLeftCorner.getHeight();
pVideo->draw2DImage(pSkinTexture,leftEdgeDest,leftEdge,0,0,true);
// Draw right edge
core::rect<s32> rightEdge = skinTexCoords[ESTC_WINDOW_RIGHT_EDGE];
core::rect<s32> rightEdgeDest = rect;
rightEdgeDest.UpperLeftCorner.X = rect.LowerRightCorner.X - rightEdge.getWidth();
rightEdgeDest.UpperLeftCorner.Y = rect.UpperLeftCorner.Y + topRightCorner.getHeight();
rightEdgeDest.LowerRightCorner.Y = rect.LowerRightCorner.Y - bottomRightCorner.getHeight();
pVideo->draw2DImage(pSkinTexture,rightEdgeDest,rightEdge,0,0,true);
// Draw interior
core::rect<s32> interior = skinTexCoords[ESTC_WINDOW_INTERIOR];
core::rect<s32> interiorDest = rect;
interiorDest.UpperLeftCorner.X = rect.UpperLeftCorner.X + leftEdge.getWidth();
interiorDest.UpperLeftCorner.Y = rect.UpperLeftCorner.Y + topEdge.getHeight();
interiorDest.LowerRightCorner.X = rect.LowerRightCorner.X - rightEdge.getWidth();
interiorDest.LowerRightCorner.Y = rect.LowerRightCorner.Y - bottomEdge.getHeight();
pVideo->draw2DImage(pSkinTexture,interiorDest,interior,0,0,true);
if (drawTitleBar)
{
// Draw title bar
core::rect<s32> titleBar = skinTexCoords[ESTC_WINDOW_TITLEBAR];
core::rect<s32> titleBarDest = rect;
titleBarDest.UpperLeftCorner.X = rect.UpperLeftCorner.X + 3;
titleBarDest.UpperLeftCorner.Y = rect.UpperLeftCorner.Y + 3;
titleBarDest.LowerRightCorner.X = rect.UpperLeftCorner.X + titleBar.getWidth();
titleBarDest.LowerRightCorner.Y = rect.UpperLeftCorner.Y + titleBar.getHeight();
pVideo->draw2DImage(pSkinTexture,titleBarDest,titleBar,0,0,true);
return titleBarDest;
}
return rect;
}
SColor CGUITexturedSkin::getColor(EGUI_DEFAULT_COLOR color) const
{
if ((u32)color < EGDC_COUNT)
return colors[color];
else
return video::SColor();
}
void CGUITexturedSkin::setColor(EGUI_DEFAULT_COLOR which, SColor newColor)
{
if ((u32)which < EGDC_COUNT)
colors[which] = newColor;
if ( 0 == which )
{
SetSkinAlpha( newColor.getAlpha() );
}
}
s32 CGUITexturedSkin::getSize(EGUI_DEFAULT_SIZE size) const
{
if ((u32)size < EGDS_COUNT)
return sizes[size];
else
return 0;
}
void CGUITexturedSkin::setSize(EGUI_DEFAULT_SIZE which, s32 size)
{
if ((u32)which < EGDS_COUNT)
sizes[which] = size;
}
const wchar_t * CGUITexturedSkin::getDefaultText(EGUI_DEFAULT_TEXT text) const
{
if ((u32)text < EGDT_COUNT)
return texts[text].c_str();
else
return texts[0].c_str();
}
void CGUITexturedSkin::setDefaultText(EGUI_DEFAULT_TEXT which, const wchar_t *newText)
{
if ((u32)which < EGDT_COUNT)
texts[which] = newText;
}
IGUIFont * CGUITexturedSkin::getFont(EGUI_DEFAULT_FONT which) const
{
if (((u32)which < EGDS_COUNT) && fonts[which])
return fonts[which];
else
return fonts[EGDF_DEFAULT];
}
void CGUITexturedSkin::setFont(IGUIFont *font, EGUI_DEFAULT_FONT which)
{
if ((u32)which >= EGDS_COUNT)
return;
if (fonts[which])
fonts[which]->drop();
fonts[which] = font;
if (fonts[which])
fonts[which]->grab();
}
IGUISpriteBank* CGUITexturedSkin::getSpriteBank() const
{
return SpriteBank;
}
void CGUITexturedSkin::setSpriteBank(IGUISpriteBank* bank)
{
if (SpriteBank)
SpriteBank->drop();
if (bank)
bank->grab();
SpriteBank = bank;
}
u32 CGUITexturedSkin::getIcon(EGUI_DEFAULT_ICON icon) const
{
if ((u32)icon < EGDI_COUNT)
return icons[icon];
else
return 0;
}
void CGUITexturedSkin::setIcon(EGUI_DEFAULT_ICON icon, u32 index)
{
if ((u32)icon < EGDI_COUNT)
icons[icon] = index;
}
void CGUITexturedSkin::drawIcon(IGUIElement* element, EGUI_DEFAULT_ICON icon,
const core::position2di position,
u32 starttime, u32 currenttime,
bool loop, const core::rect<s32>* clip)
{
if (!SpriteBank)
return;
SpriteBank->draw2DSprite(icons[icon], position, clip,
video::SColor(255,0,0,0), starttime, currenttime, loop, true);
}
void CGUITexturedSkin::draw2DRectangle(IGUIElement* element,
const video::SColor &color, const core::rect<s32>& pos,
const core::rect<s32>* clip)
{
pVideo->draw2DRectangle(color, pos, clip);
}
void CGUITexturedSkin::serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options) const
{
out->addString( "SkinFilename", skinFilename.c_str() );
}
void CGUITexturedSkin::deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options)
{
irr::core::stringc file = in->getAttributeAsString( "SkinFilename" );
setSkin( file.c_str() );
}
void CGUITexturedSkin::SetSkinAlpha( u32 a )
{
if ( !pSkinImage || !pSkinTexture )
{
return;
}
if ( ECF_A8R8G8B8 != pSkinImage->getColorFormat() || ECF_A8R8G8B8 != pSkinTexture->getColorFormat() )
{
// Working with 32 bit colour format only for now
return;
}
irr::core::dimension2d<u32> imageSize = pSkinImage->getDimension();
irr::u32 pixelMask = pSkinImage->getRedMask() | pSkinImage->getGreenMask() | pSkinImage->getBlueMask();
irr::u32 alphaBits = (a << 24 | a << 16 | a << 8 | a) & pSkinImage->getAlphaMask();
irr::u32 imagePitch = pSkinImage->getPitch();
irr::u32 texturePitch = pSkinTexture->getPitch();
irr::u32 imagePixelSize = pSkinImage->getBytesPerPixel();
irr::u32 texturePixelSize = imagePixelSize;
irr::u8 * pImageData = (irr::u8 *) pSkinImage->lock();
irr::u8 * pTextureData = (irr::u8 *) pSkinTexture->lock();
for ( irr::s32 y = 0; y < imageSize.Height; ++y )
{
for ( irr::s32 x = 0; x < imageSize.Width; ++x )
{
irr::u32 * pImagePixel = (irr::u32*)pImageData;
irr::u32 * pTexturePixel = (irr::u32*)pTextureData;
if ( (*pImagePixel & pSkinImage->getAlphaMask()) != 0 )
{
*pTexturePixel = (*pImagePixel & pixelMask) | alphaBits;
}
pImageData += imagePixelSize;
pTextureData += texturePixelSize;
}
// Somehow incrementing the pointer by pitch results in out of bounds memory access, while not using it works fine
//pImageData += imagePitch;
//pTextureData += texturePitch;
}
pSkinImage->unlock();
pSkinTexture->unlock();
}
} // end namespace gui
} // end namespace irr
| [
"btuska@0b255d0d-b62e-4858-a3ea-23bff437c660"
] | btuska@0b255d0d-b62e-4858-a3ea-23bff437c660 |
73e336babba1f12e7db2dc29adbb6b1dee7f34c3 | 0d99bcb8b8717008c1ec9b080c6c86c2b1710eee | /날씨/build/Android/Preview2/app/src/main/include/Fuse.Controls.Fallbac-8b30b373.h | 2ae77006ddfc9fa34cfa5a3be1f4b3d585f485c8 | [] | no_license | shj4849/Fuse | 526d92bc49a0a2d8087beece987b1701dc35cccc | 447f49f96f9dadf203f5f91e8a1d67f19d8ecc04 | refs/heads/master | 2021-05-15T23:08:09.523726 | 2017-12-21T05:28:53 | 2017-12-21T05:28:53 | 106,758,124 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,006 | h | // This file was generated based on C:/Users/t2/AppData/Local/Fusetools/Packages/Fuse.Controls.Primitives/1.4.0/TextControls/FallbackTextRenderer/WordWrapInfo.uno.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Uno.Object.h>
namespace g{namespace Fuse{namespace Controls{namespace FallbackTextRenderer{struct DefaultTextRenderer;}}}}
namespace g{namespace Fuse{namespace Controls{namespace FallbackTextRenderer{struct WordWrapInfo;}}}}
namespace g{
namespace Fuse{
namespace Controls{
namespace FallbackTextRenderer{
// internal sealed class WordWrapInfo :5
// {
uType* WordWrapInfo_typeof();
void WordWrapInfo__ctor__fn(WordWrapInfo* __this, ::g::Fuse::Controls::FallbackTextRenderer::DefaultTextRenderer* textRenderer, bool* isEnabled, float* wrapWidth, float* fontSize, float* lineHeight, float* lineSpacing, float* absoluteZoom);
void WordWrapInfo__Equals_fn(WordWrapInfo* __this, uObject* obj, bool* __retval);
void WordWrapInfo__GetHashCode_fn(WordWrapInfo* __this, int* __retval);
void WordWrapInfo__New1_fn(::g::Fuse::Controls::FallbackTextRenderer::DefaultTextRenderer* textRenderer, bool* isEnabled, float* wrapWidth, float* fontSize, float* lineHeight, float* lineSpacing, float* absoluteZoom, WordWrapInfo** __retval);
struct WordWrapInfo : uObject
{
uStrong< ::g::Fuse::Controls::FallbackTextRenderer::DefaultTextRenderer*> TextRenderer;
bool IsEnabled;
float WrapWidth;
float FontSize;
float LineHeight;
float LineSpacing;
float AbsoluteZoom;
void ctor_(::g::Fuse::Controls::FallbackTextRenderer::DefaultTextRenderer* textRenderer, bool isEnabled, float wrapWidth, float fontSize, float lineHeight, float lineSpacing, float absoluteZoom);
static WordWrapInfo* New1(::g::Fuse::Controls::FallbackTextRenderer::DefaultTextRenderer* textRenderer, bool isEnabled, float wrapWidth, float fontSize, float lineHeight, float lineSpacing, float absoluteZoom);
};
// }
}}}} // ::g::Fuse::Controls::FallbackTextRenderer
| [
"shj4849@naver.com"
] | shj4849@naver.com |
cf9fafd3a3d0007ec599ec4da96a542b5ab6348f | 6b0ca4ece69cb52c30228395d8201137028605eb | /cpp/911-920/Online Election.cpp | 5ff3c1a0b2f737471c1618806f78543ee91d92ee | [
"MIT"
] | permissive | gzc/leetcode | d8245071199e1b6321856ba0ddbdef5acfb5b2ac | 1a604df1e86c9775b8db364bfb3a5462ed96e9d0 | refs/heads/master | 2022-02-04T00:12:19.448204 | 2022-01-30T03:08:14 | 2022-01-30T03:08:14 | 32,258,529 | 178 | 68 | MIT | 2021-03-28T16:50:18 | 2015-03-15T12:04:59 | C++ | UTF-8 | C++ | false | false | 658 | cpp | class TopVotedCandidate {
public:
map<int, int> m;
TopVotedCandidate(vector<int> persons, vector<int> times) {
int n = persons.size(), lead = -1;
unordered_map<int, int> count;
for (int i = 0; i < n; ++i) m[times[i]] = persons[i];
for (auto it : m) {
if (++count[it.second] >= count[lead])lead = it.second;
m[it.first] = lead;
}
}
int q(int t) {
return (--m.upper_bound(t))-> second;
}
};
/**
* Your TopVotedCandidate object will be instantiated and called as such:
* TopVotedCandidate obj = new TopVotedCandidate(persons, times);
* int param_1 = obj.q(t);
*/
| [
"noreply@github.com"
] | gzc.noreply@github.com |
50f07db97abfe301bed5a4d5fc05cfca4d5b0270 | 933b95b8f6b640d5c4456ac573d4e74898f6c8f2 | /mediapipe/examples/desktop/demo_run_graph_main_gpu.cc | 687a704ebeeb190dc94cd0f94e979df726f3977e | [
"Apache-2.0"
] | permissive | lukereichold/mediapipe | 03e8a602cf98bddb9e1a60c73149312d96f88c86 | 1cc2e6f549119054130d9e9a02012a7221da5992 | refs/heads/master | 2020-10-02T06:08:13.571951 | 2019-12-13T00:02:22 | 2019-12-13T00:02:22 | 227,718,415 | 1 | 0 | Apache-2.0 | 2019-12-12T23:57:41 | 2019-12-12T23:57:40 | null | UTF-8 | C++ | false | false | 7,985 | cc | // Copyright 2019 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.
//
// An example of sending OpenCV webcam frames into a MediaPipe graph.
// This example requires a linux computer and a GPU with EGL support drivers.
#include "mediapipe/framework/calculator_framework.h"
#include "mediapipe/framework/formats/image_frame.h"
#include "mediapipe/framework/formats/image_frame_opencv.h"
#include "mediapipe/framework/port/commandlineflags.h"
#include "mediapipe/framework/port/file_helpers.h"
#include "mediapipe/framework/port/opencv_highgui_inc.h"
#include "mediapipe/framework/port/opencv_imgproc_inc.h"
#include "mediapipe/framework/port/opencv_video_inc.h"
#include "mediapipe/framework/port/parse_text_proto.h"
#include "mediapipe/framework/port/status.h"
#include "mediapipe/gpu/gl_calculator_helper.h"
#include "mediapipe/gpu/gpu_buffer.h"
#include "mediapipe/gpu/gpu_shared_data_internal.h"
constexpr char kInputStream[] = "input_video";
constexpr char kOutputStream[] = "output_video";
constexpr char kWindowName[] = "MediaPipe";
DEFINE_string(
calculator_graph_config_file, "",
"Name of file containing text format CalculatorGraphConfig proto.");
DEFINE_string(input_video_path, "",
"Full path of video to load. "
"If not provided, attempt to use a webcam.");
DEFINE_string(output_video_path, "",
"Full path of where to save result (.mp4 only). "
"If not provided, show result in a window.");
::mediapipe::Status RunMPPGraph() {
std::string calculator_graph_config_contents;
MP_RETURN_IF_ERROR(mediapipe::file::GetContents(
FLAGS_calculator_graph_config_file, &calculator_graph_config_contents));
LOG(INFO) << "Get calculator graph config contents: "
<< calculator_graph_config_contents;
mediapipe::CalculatorGraphConfig config =
mediapipe::ParseTextProtoOrDie<mediapipe::CalculatorGraphConfig>(
calculator_graph_config_contents);
LOG(INFO) << "Initialize the calculator graph.";
mediapipe::CalculatorGraph graph;
MP_RETURN_IF_ERROR(graph.Initialize(config));
LOG(INFO) << "Initialize the GPU.";
ASSIGN_OR_RETURN(auto gpu_resources, mediapipe::GpuResources::Create());
MP_RETURN_IF_ERROR(graph.SetGpuResources(std::move(gpu_resources)));
mediapipe::GlCalculatorHelper gpu_helper;
gpu_helper.InitializeForTest(graph.GetGpuResources().get());
LOG(INFO) << "Initialize the camera or load the video.";
cv::VideoCapture capture;
const bool load_video = !FLAGS_input_video_path.empty();
if (load_video) {
capture.open(FLAGS_input_video_path);
} else {
capture.open(0);
}
RET_CHECK(capture.isOpened());
cv::VideoWriter writer;
const bool save_video = !FLAGS_output_video_path.empty();
if (save_video) {
LOG(INFO) << "Prepare video writer.";
cv::Mat test_frame;
capture.read(test_frame); // Consume first frame.
capture.set(cv::CAP_PROP_POS_AVI_RATIO, 0); // Rewind to beginning.
writer.open(FLAGS_output_video_path,
mediapipe::fourcc('a', 'v', 'c', '1'), // .mp4
capture.get(cv::CAP_PROP_FPS), test_frame.size());
RET_CHECK(writer.isOpened());
} else {
cv::namedWindow(kWindowName, /*flags=WINDOW_AUTOSIZE*/ 1);
#if (CV_MAJOR_VERSION >= 3) && (CV_MINOR_VERSION >= 2)
capture.set(cv::CAP_PROP_FRAME_WIDTH, 640);
capture.set(cv::CAP_PROP_FRAME_HEIGHT, 480);
capture.set(cv::CAP_PROP_FPS, 30);
#endif
}
LOG(INFO) << "Start running the calculator graph.";
ASSIGN_OR_RETURN(mediapipe::OutputStreamPoller poller,
graph.AddOutputStreamPoller(kOutputStream));
MP_RETURN_IF_ERROR(graph.StartRun({}));
LOG(INFO) << "Start grabbing and processing frames.";
size_t frame_timestamp = 0;
bool grab_frames = true;
while (grab_frames) {
// Capture opencv camera or video frame.
cv::Mat camera_frame_raw;
capture >> camera_frame_raw;
if (camera_frame_raw.empty()) break; // End of video.
cv::Mat camera_frame;
cv::cvtColor(camera_frame_raw, camera_frame, cv::COLOR_BGR2RGB);
if (!load_video) {
cv::flip(camera_frame, camera_frame, /*flipcode=HORIZONTAL*/ 1);
}
// Wrap Mat into an ImageFrame.
auto input_frame = absl::make_unique<mediapipe::ImageFrame>(
mediapipe::ImageFormat::SRGB, camera_frame.cols, camera_frame.rows,
mediapipe::ImageFrame::kGlDefaultAlignmentBoundary);
cv::Mat input_frame_mat = mediapipe::formats::MatView(input_frame.get());
camera_frame.copyTo(input_frame_mat);
// Prepare and add graph input packet.
MP_RETURN_IF_ERROR(
gpu_helper.RunInGlContext([&input_frame, &frame_timestamp, &graph,
&gpu_helper]() -> ::mediapipe::Status {
// Convert ImageFrame to GpuBuffer.
auto texture = gpu_helper.CreateSourceTexture(*input_frame.get());
auto gpu_frame = texture.GetFrame<mediapipe::GpuBuffer>();
glFlush();
texture.Release();
// Send GPU image packet into the graph.
MP_RETURN_IF_ERROR(graph.AddPacketToInputStream(
kInputStream, mediapipe::Adopt(gpu_frame.release())
.At(mediapipe::Timestamp(frame_timestamp++))));
return ::mediapipe::OkStatus();
}));
// Get the graph result packet, or stop if that fails.
mediapipe::Packet packet;
if (!poller.Next(&packet)) break;
std::unique_ptr<mediapipe::ImageFrame> output_frame;
// Convert GpuBuffer to ImageFrame.
MP_RETURN_IF_ERROR(gpu_helper.RunInGlContext(
[&packet, &output_frame, &gpu_helper]() -> ::mediapipe::Status {
auto& gpu_frame = packet.Get<mediapipe::GpuBuffer>();
auto texture = gpu_helper.CreateSourceTexture(gpu_frame);
output_frame = absl::make_unique<mediapipe::ImageFrame>(
mediapipe::ImageFormatForGpuBufferFormat(gpu_frame.format()),
gpu_frame.width(), gpu_frame.height(),
mediapipe::ImageFrame::kGlDefaultAlignmentBoundary);
gpu_helper.BindFramebuffer(texture);
const auto info =
mediapipe::GlTextureInfoForGpuBufferFormat(gpu_frame.format(), 0);
glReadPixels(0, 0, texture.width(), texture.height(), info.gl_format,
info.gl_type, output_frame->MutablePixelData());
glFlush();
texture.Release();
return ::mediapipe::OkStatus();
}));
// Convert back to opencv for display or saving.
cv::Mat output_frame_mat = mediapipe::formats::MatView(output_frame.get());
cv::cvtColor(output_frame_mat, output_frame_mat, cv::COLOR_RGB2BGR);
if (save_video) {
writer.write(output_frame_mat);
} else {
cv::imshow(kWindowName, output_frame_mat);
// Press any key to exit.
const int pressed_key = cv::waitKey(5);
if (pressed_key >= 0 && pressed_key != 255) grab_frames = false;
}
}
LOG(INFO) << "Shutting down.";
if (writer.isOpened()) writer.release();
MP_RETURN_IF_ERROR(graph.CloseInputStream(kInputStream));
return graph.WaitUntilDone();
}
int main(int argc, char** argv) {
google::InitGoogleLogging(argv[0]);
gflags::ParseCommandLineFlags(&argc, &argv, true);
::mediapipe::Status run_status = RunMPPGraph();
if (!run_status.ok()) {
LOG(ERROR) << "Failed to run the graph: " << run_status.message();
} else {
LOG(INFO) << "Success!";
}
return 0;
}
| [
"jqtang@google.com"
] | jqtang@google.com |
1385d1148d0aee800eca1087c879b8ab8cc134a0 | 0f5f4d0c33e752a35fc71a7762ad7aa904d16c27 | /dcmdata/libsrc/dcmetinf.cxx | b7a34a87b567402513519331c65ea5739f01c029 | [
"LicenseRef-scancode-warranty-disclaimer",
"IJG",
"BSD-4.3TAHOE",
"LicenseRef-scancode-other-permissive",
"xlock",
"OFFIS",
"BSD-3-Clause",
"JasPer-2.0"
] | permissive | trabs/DCMTK | 158b945f3740806d6a128d7f4d0a059997d3bacb | d6c163e4c2dcf1831c2efa20aa7752d15b61e67e | refs/heads/master | 2021-01-18T06:18:08.748952 | 2010-03-09T21:36:11 | 2010-06-14T08:19:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 30,644 | cxx | /*
*
* Copyright (C) 1994-2009, OFFIS
*
* This software and supporting documentation were developed by
*
* Kuratorium OFFIS e.V.
* Healthcare Information and Communication Systems
* Escherweg 2
* D-26121 Oldenburg, Germany
*
* THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND OFFIS MAKES NO WARRANTY
* REGARDING THE SOFTWARE, ITS PERFORMANCE, ITS MERCHANTABILITY OR
* FITNESS FOR ANY PARTICULAR USE, FREEDOM FROM ANY COMPUTER DISEASES OR
* ITS CONFORMITY TO ANY SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND
* PERFORMANCE OF THE SOFTWARE IS WITH THE USER.
*
* Module: dcmdata
*
* Author: Gerd Ehlers, Andreas Barth
*
* Purpose: Implementation of class DcmMetaInfo
*
* Last Update: $Author: joergr $
* Update Date: $Date: 2009-11-13 13:11:21 $
* CVS/RCS Revision: $Revision: 1.50 $
* Status: $State: Exp $
*
* CVS/RCS Log at end of file
*
*/
#include "dcmtk/config/osconfig.h" /* make sure OS specific configuration is included first */
#define INCLUDE_CSTDLIB
#define INCLUDE_CSTRING
#include "dcmtk/ofstd/ofstdinc.h"
#include "dcmtk/ofstd/ofstream.h"
#include "dcmtk/ofstd/ofstd.h"
#include "dcmtk/dcmdata/dcmetinf.h"
#include "dcmtk/dcmdata/dcitem.h"
#include "dcmtk/dcmdata/dcxfer.h"
#include "dcmtk/dcmdata/dcvrul.h"
#include "dcmtk/dcmdata/dcdeftag.h"
#include "dcmtk/ofstd/ofdefine.h"
#include "dcmtk/dcmdata/dcistrma.h" /* for class DcmInputStream */
#include "dcmtk/dcmdata/dcostrma.h" /* for class DcmOutputStream */
const Uint32 DCM_GroupLengthElementLength = 12;
// ********************************
DcmMetaInfo::DcmMetaInfo()
: DcmItem(ItemTag),
preambleUsed(OFFalse),
fPreambleTransferState(ERW_init),
Xfer(META_HEADER_DEFAULT_TRANSFERSYNTAX)
{
setPreamble();
}
DcmMetaInfo::DcmMetaInfo(const DcmMetaInfo &old)
: DcmItem(old),
preambleUsed(old.preambleUsed),
fPreambleTransferState(ERW_init),
Xfer(old.Xfer)
{
memcpy(filePreamble, old.filePreamble, 128);
}
DcmMetaInfo& DcmMetaInfo::operator=(const DcmMetaInfo& obj)
{
if (this != &obj)
{
// copy parent's member variables
DcmItem::operator=(obj);
// copy DcmMetaInfo's member variables
preambleUsed = obj.preambleUsed;
fPreambleTransferState = obj.fPreambleTransferState;
Xfer = obj.Xfer;
memcpy(filePreamble, obj.filePreamble, 128);
}
return *this;
}
OFCondition DcmMetaInfo::copyFrom(const DcmObject& rhs)
{
if (this != &rhs)
{
if (rhs.ident() != ident()) return EC_IllegalCall;
*this = (DcmMetaInfo&) rhs;
}
return EC_Normal;
}
DcmMetaInfo::~DcmMetaInfo()
{
}
// ********************************
DcmEVR DcmMetaInfo::ident() const
{
return EVR_metainfo;
}
E_TransferSyntax DcmMetaInfo::getOriginalXfer() const
{
return Xfer;
}
void DcmMetaInfo::removeInvalidGroups()
{
DcmStack stack;
DcmObject *object = NULL;
/* iterate over all elements */
while (nextObject(stack, OFTrue).good())
{
object = stack.top();
/* delete invalid elements */
if (object->getTag().getGroup() != 0x0002)
{
stack.pop();
/* remove element from meta information header and free memory */
delete OFstatic_cast(DcmItem *, stack.top())->remove(object);
}
}
}
// ********************************
void DcmMetaInfo::print(STD_NAMESPACE ostream&out,
const size_t flags,
const int level,
const char *pixelFileName,
size_t *pixelCounter)
{
out << OFendl;
printNestingLevel(out, flags, level);
out << "# Dicom-Meta-Information-Header" << OFendl;
printNestingLevel(out, flags, level);
out << "# Used TransferSyntax: " << DcmXfer(Xfer).getXferName();
out << OFendl;
if (!elementList->empty())
{
DcmObject *dO;
elementList->seek(ELP_first);
do {
dO = elementList->get();
dO->print(out, flags, level + 1, pixelFileName, pixelCounter);
} while (elementList->seek(ELP_next));
}
}
// ********************************
OFCondition DcmMetaInfo::writeXML(STD_NAMESPACE ostream&out,
const size_t flags)
{
OFString xmlString;
DcmXfer xfer(Xfer);
/* XML start tag for "meta-header" */
out << "<meta-header xfer=\"" << xfer.getXferID() << "\"";
out << " name=\"" << OFStandard::convertToMarkupString(xfer.getXferName(), xmlString) << "\">" << OFendl;
if (!elementList->empty())
{
/* write content of all children */
DcmObject *dO;
elementList->seek(ELP_first);
do
{
dO = elementList->get();
dO->writeXML(out, flags);
} while (elementList->seek(ELP_next));
}
/* XML end tag for "meta-header" */
out << "</meta-header>" << OFendl;
/* always report success */
return EC_Normal;
}
// ********************************
void DcmMetaInfo::setPreamble()
{
memzero(filePreamble, sizeof(filePreamble));
preambleUsed = OFFalse;
}
// ********************************
OFBool DcmMetaInfo::checkAndReadPreamble(DcmInputStream &inStream,
E_TransferSyntax &newxfer)
{
if (fPreambleTransferState == ERW_init)
{
inStream.mark();
fPreambleTransferState = ERW_inWork;
}
OFBool retval = OFFalse;
if (fPreambleTransferState == ERW_inWork)
{
const Uint32 preambleLen = DCM_PreambleLen + DCM_MagicLen;
const Uint32 readLen = preambleLen - getTransferredBytes();
if (readLen > 0)
incTransferredBytes(OFstatic_cast(Uint32, inStream.read(&filePreamble[getTransferredBytes()], readLen)));
if (inStream.eos() && getTransferredBytes() != preambleLen)
{ // file too short, no preamble
inStream.putback();
DCMDATA_TRACE("DcmMetaInfo::checkAndReadPreamble() No Preamble available: File too short ("
<< preambleLen << ") < " << DCM_PreambleLen + DCM_MagicLen << " bytes");
retval = OFFalse;
this -> setPreamble();
fPreambleTransferState = ERW_ready;
}
else if (getTransferredBytes() == preambleLen) // check Preamble and Dicom Prefix
{ // set prefix to appropriate position
char *prefix = filePreamble + DCM_PreambleLen;
if (memcmp(prefix, DCM_Magic, DCM_MagicLen) == 0)
{
retval = OFTrue; // Preamble present
// inStream.UnsetPutbackMark(); // not needed anymore with new stream architecture
} else { // no Preamble
retval = OFFalse;
this -> setPreamble();
inStream.putback();
}
fPreambleTransferState = ERW_ready;
} else
errorFlag = EC_StreamNotifyClient;
}
if (fPreambleTransferState == ERW_ready)
{
E_TransferSyntax tmpxfer = checkTransferSyntax(inStream);
DcmXfer tmpxferSyn(tmpxfer);
DcmXfer xferSyn(newxfer);
if ((tmpxferSyn.isExplicitVR() && xferSyn.isImplicitVR()) ||
(tmpxferSyn.isImplicitVR() && xferSyn.isExplicitVR()) ||
xferSyn.getXfer() == EXS_Unknown)
{
newxfer = tmpxferSyn.getXfer(); // use determined xfer
if (xferSyn.getXfer() != EXS_Unknown)
DCMDATA_WARN("DcmMetaInfo: TransferSyntax of MetaInfo is other than expected");
} else
newxfer = xferSyn.getXfer();
}
if (retval == OFTrue)
{
DCMDATA_TRACE("DcmMetaInfo::checkAndReadPreamble() Preamble = 0x"
<< STD_NAMESPACE hex << STD_NAMESPACE setfill('0')
<< STD_NAMESPACE setw(4) << OFstatic_cast(Uint32, *filePreamble));
} else
DCMDATA_TRACE("DcmMetaInfo::checkAndReadPreamble() No Preambel found");
DCMDATA_TRACE("DcmMetaInfo::checkAndReadPreamble() TransferSyntax = " << DcmXfer(newxfer).getXferName());
return retval;
} // DcmMetaInfo::checkAndReadPreamble
// ********************************
OFBool DcmMetaInfo::nextTagIsMeta(DcmInputStream &inStream)
{
char testbytes[2];
inStream.mark();
inStream.read(testbytes, 2);
inStream.putback();
// check for group 0x0002 only
return (testbytes[0] == 0x02 && testbytes[1] == 0x00) || (testbytes[0] == 0x00 && testbytes[1] == 0x02);
}
// ********************************
Uint32 DcmMetaInfo::calcElementLength(const E_TransferSyntax /*xfer*/,
const E_EncodingType enctype)
{
Uint32 metaLength = DcmItem::getLength(META_HEADER_DEFAULT_TRANSFERSYNTAX, enctype);
metaLength += DCM_PreambleLen + DCM_MagicLen;
return metaLength;
}
// ********************************
OFCondition DcmMetaInfo::readGroupLength(DcmInputStream &inStream,
const E_TransferSyntax xfer,
const DcmTagKey &xtag,
const E_GrpLenEncoding glenc,
Uint32 &headerLen,
Uint32 &bytesRead,
const Uint32 maxReadLength)
{
OFCondition l_error = EC_TagNotFound;
E_TransferSyntax newxfer = xfer;
bytesRead = 0;
headerLen = 0;
if (nextTagIsMeta(inStream))
{
DcmTag newTag;
Uint32 newValueLength = 0;
Uint32 bytes_tagAndLen = 0;
l_error = DcmItem::readTagAndLength(inStream, newxfer, newTag, newValueLength, bytes_tagAndLen);
bytesRead += bytes_tagAndLen;
if (l_error.good() && !inStream.good())
l_error = inStream.status();
if (l_error.good())
{
l_error = DcmItem::readSubElement(inStream, newTag, newValueLength, newxfer, glenc, maxReadLength);
bytesRead += newValueLength;
if (l_error.good() && newTag.getXTag() == xtag && elementList->get() != NULL && newValueLength > 0)
{
l_error = (OFstatic_cast(DcmUnsignedLong *, elementList->get()))->getUint32(headerLen);
DCMDATA_TRACE("DcmMetaInfo::readGroupLength() Group Length of File Meta Header = " << headerLen + bytesRead);
} else {
l_error = EC_CorruptedData;
DCMDATA_WARN("DcmMetaInfo: No Group Length available in Meta Information Header");
}
}
}
DCMDATA_TRACE("DcmMetaInfo::readGroupLength() returns error = " << l_error.text());
return l_error;
}
// ********************************
OFCondition DcmMetaInfo::read(DcmInputStream &inStream,
const E_TransferSyntax xfer,
const E_GrpLenEncoding glenc,
const Uint32 maxReadLength)
{
if (fPreambleTransferState == ERW_notInitialized || getTransferState() == ERW_notInitialized)
errorFlag = EC_IllegalCall;
else
{
Xfer = xfer;
E_TransferSyntax newxfer = xfer;
/* figure out if the stream reported an error */
errorFlag = inStream.status();
if (errorFlag.good() && inStream.eos())
errorFlag = EC_EndOfStream;
else if (errorFlag.good() && getTransferState() != ERW_ready)
{
if (getTransferState() == ERW_init && fPreambleTransferState != ERW_ready)
{
if (xfer == EXS_Unknown)
preambleUsed = checkAndReadPreamble(inStream, newxfer);
else
newxfer = xfer;
if (fPreambleTransferState == ERW_ready)
{
Xfer = newxfer; // store parameter transfer syntax
setTransferState(ERW_inWork);
setTransferredBytes(0);
fStartPosition = inStream.tell();
setLengthField(0);
}
}
if (getTransferState() == ERW_inWork && getLengthField() == 0)
{
if (inStream.avail() < DCM_GroupLengthElementLength)
errorFlag = EC_StreamNotifyClient;
else
{
Uint32 headerLength = 0;
Uint32 bytesRead = 0;
errorFlag = readGroupLength(inStream, newxfer, DCM_FileMetaInformationGroupLength, glenc,
headerLength, bytesRead, maxReadLength);
setTransferredBytes(bytesRead);
if (errorFlag.good())
{
/* FileMetaInformationGroupLength (0002,0000) is present but should be ignored */
if (dcmIgnoreFileMetaInformationGroupLength.get())
{
DCMDATA_WARN("DcmMetaInfo: Ignoring Group Length of Meta Information Header");
setLengthField(DCM_UndefinedLength);
} else
setLengthField(headerLength + getTransferredBytes());
} else
setLengthField(DCM_UndefinedLength);
}
}
#ifdef REJECT_FILE_IF_META_GROUP_LENGTH_ABSENT
// this is the old behaviour up to DCMTK 3.5.3: fail with EC_CorruptedData error code
// if the file meta header group length (0002,0000) is absent.
if (getTransferState() == ERW_inWork && getLengthField() != 0 && errorFlag.good())
{
#else
// new behaviour: accept file without meta header group length, determine end of
// meta header based on heuristic that checks for group 0002 tags.
if (getTransferState() == ERW_inWork && getLengthField() != 0 && (errorFlag.good() ||
((errorFlag == EC_CorruptedData) && (getLengthField() == DCM_UndefinedLength))))
{
/* start with "no error" in order to handle meta-header with only one data element */
errorFlag = EC_Normal;
#endif
while (inStream.good() && !inStream.eos() &&
((getLengthField() < DCM_UndefinedLength && getTransferredBytes() < getLengthField()) ||
(getLengthField() == DCM_UndefinedLength && nextTagIsMeta(inStream)) ||
!lastElementComplete))
{
DcmTag newTag;
Uint32 newValueLength = 0;
Uint32 bytes_tagAndLen = 0;
if (lastElementComplete)
{
errorFlag = DcmItem::readTagAndLength(inStream, newxfer, newTag, newValueLength, bytes_tagAndLen);
incTransferredBytes(bytes_tagAndLen);
if (errorFlag != EC_Normal)
break; // terminate while loop
lastElementComplete = OFFalse;
errorFlag = DcmItem::readSubElement(inStream, newTag, newValueLength, newxfer, glenc, maxReadLength);
if (errorFlag.good())
lastElementComplete = OFTrue;
/* check for valid meta-header elements */
if (newTag.getGroup() != 0x0002)
DCMDATA_WARN("DcmMetaInfo: Invalid Element " << newTag << " found in Meta Information Header");
} else {
errorFlag = elementList->get()->read(inStream, xfer, glenc, maxReadLength);
if (errorFlag.good())
lastElementComplete = OFTrue;
}
setTransferredBytes(OFstatic_cast(Uint32, inStream.tell() - fStartPosition));
if (errorFlag.bad())
break; // terminate while loop
} //while
}
if (errorFlag == EC_TagNotFound || errorFlag == EC_EndOfStream)
{
errorFlag = EC_Normal; // there is no meta header
Xfer = EXS_Unknown;
} else if (errorFlag == EC_ItemEnd)
errorFlag = EC_Normal;
if (errorFlag.good())
{
if (getLengthField() != DCM_UndefinedLength && getTransferredBytes() != getLengthField())
DCMDATA_WARN("DcmMetaInfo: Group Length of Meta Information Header has incorrect value");
setTransferState(ERW_ready); // MetaInfo is complete
}
}
}
return errorFlag;
} // DcmMetaInfo::read()
// ********************************
void DcmMetaInfo::transferInit()
{
DcmItem::transferInit();
fPreambleTransferState = ERW_init;
}
// ********************************
void DcmMetaInfo::transferEnd()
{
DcmItem::transferEnd();
fPreambleTransferState = ERW_notInitialized;
}
// ********************************
OFCondition DcmMetaInfo::write(
DcmOutputStream &outStream,
const E_TransferSyntax /*oxfer*/,
const E_EncodingType enctype,
DcmWriteCache *wcache)
/*
* This function writes all data elements which make up the meta header to the stream.
* For a specification of the elements that make up the meta header see DICOM standard
* (year 2000) part 10, section 7.1)) or the corresponding section in a later version of
* the standard).
*
* Parameters:
* outStream - [inout] The stream that the information will be written to.
* oxfer - [in] The transfer syntax which shall be used. (is not necessary since the meta header
* shall always be encoded in the explicit VR little endian transfer syntax)
* enctype - [in] Encoding type for sequences. Specifies how sequences will be handled.
*/
{
/* if the transfer state of this is not initialized, this is an illegal call */
if (getTransferState() == ERW_notInitialized)
errorFlag = EC_IllegalCall;
else
{
/* if this is not an illegal call, do something */
/* determine the (default) transfer syntax which shall be used (always explicit VR little endian) */
E_TransferSyntax outxfer = META_HEADER_DEFAULT_TRANSFERSYNTAX;
/* check if the stream reported an error so far */
errorFlag = outStream.status();
/* if the stream did not report any error and the transfer state is ERW_ready, */
/* go ahead and write the meta header information to the out stream */
if (errorFlag.good() && getTransferState() != ERW_ready)
{
/* if some particular conditions are met we need to write the file preamble (128 byte wide) and */
/* the DICOM prefix "DICM" to the stream. Always check if there is enough space in the stream and */
/* set the transfer state of certain elements to indicate that they have already been written. */
if (getTransferState() == ERW_init)
{
if (preambleUsed || !elementList->empty())
{
if (fPreambleTransferState == ERW_init)
{
incTransferredBytes(OFstatic_cast(Uint32, outStream.write(&filePreamble[getTransferredBytes()],
DCM_PreambleLen - getTransferredBytes())));
if (getTransferredBytes() != DCM_PreambleLen)
errorFlag = EC_StreamNotifyClient;
else
fPreambleTransferState = ERW_inWork;
}
if (fPreambleTransferState == ERW_inWork && outStream.avail() >= 4)
{
outStream.write(DCM_Magic, 4);
fPreambleTransferState = ERW_ready;
setTransferState(ERW_inWork);
elementList->seek(ELP_first);
} else
errorFlag = EC_StreamNotifyClient;
}
}
/* if the file premable and the DICOM prefix have been written, go */
/* ahead and write the meta header's data elements to the stream. */
/* (note that at this point elementList->get() should never be NULL, */
/* but lets play the game safe here...) */
if (!elementList->empty() && (getTransferState() == ERW_inWork) && (elementList->get() != NULL))
{
DcmObject *dO;
/* iterate over the list of data elements and write them to the stream */
do {
dO = elementList->get();
errorFlag = dO->write(outStream, outxfer, enctype, wcache);
} while (errorFlag.good() && elementList->seek(ELP_next));
}
/* if the error flag equals ok and the transfer state equals ERW_inWork, all data elements of the meta */
/* header have been written to the stream. Indicate this by setting the transfer state to ERW_ready */
if (errorFlag.good() && getTransferState() == ERW_inWork)
setTransferState(ERW_ready);
}
}
/* return result value */
return errorFlag;
}
/*
** CVS/RCS Log:
** $Log: dcmetinf.cc,v $
** Revision 1.50 2009-11-13 13:11:21 joergr
** Fixed minor issues in log output.
**
** Revision 1.49 2009-11-04 09:58:10 uli
** Switched to logging mechanism provided by the "new" oflog module
**
** Revision 1.48 2009-09-28 13:30:59 joergr
** Moved general purpose definition file from module dcmdata to ofstd, and
** added new defines in order to make the usage easier.
**
** Revision 1.47 2009-08-25 12:54:57 joergr
** Added new methods which remove all data elements with an invalid group number
** from the meta information header, dataset and/or fileformat.
**
** Revision 1.46 2009-06-04 16:58:24 joergr
** Added new parsing flag that allows for ignoring the value of File Meta
** Information Group Length (0002,0000).
** Report a warning on all data elements in the meta-header which have an
** incorrect group number, i.e. everything but 0x0002.
**
** Revision 1.45 2009-03-02 11:16:36 joergr
** Moved variable definition.
**
** Revision 1.44 2009-03-02 11:15:18 joergr
** Fixed issue with incorrectly encoded file meta information header consisting
** of one data element only (e.g. TransferSyntaxUID).
**
** Revision 1.43 2009-02-04 17:57:19 joergr
** Fixes various type mismatches reported by MSVC introduced with OFFile class.
**
** Revision 1.42 2008-07-17 10:31:31 onken
** Implemented copyFrom() method for complete DcmObject class hierarchy, which
** permits setting an instance's value from an existing object. Implemented
** assignment operator where necessary.
**
** Revision 1.41 2008-04-30 12:38:42 meichel
** Fixed compile errors due to changes in attribute tag names
**
** Revision 1.40 2007/11/29 14:30:21 meichel
** Write methods now handle large raw data elements (such as pixel data)
** without loading everything into memory. This allows very large images to
** be sent over a network connection, or to be copied without ever being
** fully in memory.
**
** Revision 1.39 2007/06/29 14:17:49 meichel
** Code clean-up: Most member variables in module dcmdata are now private,
** not protected anymore.
**
** Revision 1.38 2006/08/15 15:49:54 meichel
** Updated all code in module dcmdata to correctly compile when
** all standard C++ classes remain in namespace std.
**
** Revision 1.37 2005/12/08 15:41:18 meichel
** Changed include path schema for all DCMTK header files
**
** Revision 1.36 2005/11/28 15:53:13 meichel
** Renamed macros in dcdebug.h
**
** Revision 1.35 2005/11/07 16:59:26 meichel
** Cleaned up some copy constructors in the DcmObject hierarchy.
**
** Revision 1.34 2005/05/26 11:51:12 meichel
** Now reading DICOM files in which the meta header group length attribute
** (0002,0000) is absent, based on a heuristic that checks for group 0002
** attribute tags. New behaviour can be disabled by compiling with the macro
** REJECT_FILE_IF_META_GROUP_LENGTH_ABSENT defined.
**
** Revision 1.33 2004/02/04 16:35:00 joergr
** Adapted type casts to new-style typecast operators defined in ofcast.h.
** Removed acknowledgements with e-mail addresses from CVS log.
**
** Revision 1.32 2003/10/15 16:55:43 meichel
** Updated error messages for parse errors
**
** Revision 1.31 2002/12/06 12:59:39 joergr
** Enhanced "print()" function by re-working the implementation and replacing
** the boolean "showFullData" parameter by a more general integer flag.
** Made source code formatting more consistent with other modules/files.
** Replaced some German comments by English translations.
**
** Revision 1.30 2002/11/27 12:06:49 meichel
** Adapted module dcmdata to use of new header file ofstdinc.h
**
** Revision 1.29 2002/08/27 16:55:51 meichel
** Initial release of new DICOM I/O stream classes that add support for stream
** compression (deflated little endian explicit VR transfer syntax)
**
** Revision 1.28 2002/04/25 10:17:19 joergr
** Added support for XML output of DICOM objects.
**
** Revision 1.27 2002/04/16 13:43:18 joergr
** Added configurable support for C++ ANSI standard includes (e.g. streams).
**
** Revision 1.26 2001/11/01 14:55:40 wilkens
** Added lots of comments.
**
** Revision 1.25 2001/09/26 15:49:30 meichel
** Modified debug messages, required by OFCondition
**
** Revision 1.24 2001/09/25 17:19:51 meichel
** Adapted dcmdata to class OFCondition
**
** Revision 1.23 2001/06/01 15:49:06 meichel
** Updated copyright header
**
** Revision 1.22 2001/05/10 12:46:52 meichel
** Fixed minor bug in DcmMetaInfo::transferEnd()
**
** Revision 1.21 2001/05/03 08:15:22 meichel
** Fixed bug in dcmdata sequence handling code that could lead to application
** failure in rare cases during parsing of a correct DICOM dataset.
**
** Revision 1.20 2000/04/14 15:55:06 meichel
** Dcmdata library code now consistently uses ofConsole for error output.
**
** Revision 1.19 2000/03/08 16:26:38 meichel
** Updated copyright header.
**
** Revision 1.18 2000/03/03 14:05:35 meichel
** Implemented library support for redirecting error messages into memory
** instead of printing them to stdout/stderr for GUI applications.
**
** Revision 1.17 2000/02/23 15:11:56 meichel
** Corrected macro for Borland C++ Builder 4 workaround.
**
** Revision 1.16 2000/02/10 10:52:20 joergr
** Added new feature to dcmdump (enhanced print method of dcmdata): write
** pixel data/item value fields to raw files.
**
** Revision 1.15 2000/02/01 10:12:08 meichel
** Avoiding to include <stdlib.h> as extern "C" on Borland C++ Builder 4,
** workaround for bug in compiler header files.
**
** Revision 1.14 1999/03/31 09:25:33 meichel
** Updated copyright header in module dcmdata
**
** Revision 1.13 1998/07/15 15:52:02 joergr
** Removed several compiler warnings reported by gcc 2.8.1 with
** additional options, e.g. missing copy constructors and assignment
** operators, initialization of member variables in the body of a
** constructor instead of the member initialization list, hiding of
** methods by use of identical names, uninitialized member variables,
** missing const declaration of char pointers. Replaced tabs by spaces.
**
** Revision 1.12 1997/07/21 08:25:28 andreas
** - Replace all boolean types (BOOLEAN, CTNBOOLEAN, DICOM_BOOL, BOOL)
** with one unique boolean type OFBool.
**
** Revision 1.11 1997/07/03 15:10:00 andreas
** - removed debugging functions Bdebug() and Edebug() since
** they write a static array and are not very useful at all.
** Cdebug and Vdebug are merged since they have the same semantics.
** The debugging functions in dcmdata changed their interfaces
** (see dcmdata/include/dcdebug.h)
**
** Revision 1.10 1997/05/16 08:23:54 andreas
** - Revised handling of GroupLength elements and support of
** DataSetTrailingPadding elements. The enumeratio E_GrpLenEncoding
** got additional enumeration values (for a description see dctypes.h).
** addGroupLength and removeGroupLength methods are replaced by
** computeGroupLengthAndPadding. To support Padding, the parameters of
** element and sequence write functions changed.
** - Added a new method calcElementLength to calculate the length of an
** element, item or sequence. For elements it returns the length of
** tag, length field, vr field, and value length, for item and
** sequences it returns the length of the whole item. sequence including
** the Delimitation tag (if appropriate). It can never return
** UndefinedLength.
**
** Revision 1.9 1997/04/18 08:17:18 andreas
** - The put/get-methods for all VRs did not conform to the C++-Standard
** draft. Some Compilers (e.g. SUN-C++ Compiler, Metroworks
** CodeWarrier, etc.) create many warnings concerning the hiding of
** overloaded get methods in all derived classes of DcmElement.
** So the interface of all value representation classes in the
** library are changed rapidly, e.g.
** OFCondition get(Uint16 & value, const unsigned long pos);
** becomes
** OFCondition getUint16(Uint16 & value, const unsigned long pos);
** All (retired) "returntype get(...)" methods are deleted.
** For more information see dcmdata/include/dcelem.h
**
** Revision 1.8 1996/08/05 08:46:13 andreas
** new print routine with additional parameters:
** - print into files
** - fix output length for elements
** corrected error in search routine with parameter ESM_fromStackTop
**
** Revision 1.7 1996/07/31 13:14:31 andreas
** - Minor corrections: error code for swapping to or from byteorder unknown
** correct read of dataset in fileformat
**
** Revision 1.6 1996/04/27 14:04:56 hewett
** Eliminated compiler warnings when compiling without -DDEBUG. Very
** minor corrections, mostly unused parameters and uninitialized variables.
**
** Revision 1.5 1996/01/29 13:38:27 andreas
** - new put method for every VR to put value as a string
** - better and unique print methods
**
** Revision 1.4 1996/01/09 11:06:47 andreas
** New Support for Visual C++
** Correct problems with inconsistent const declarations
** Correct error in reading Item Delimitation Elements
**
** Revision 1.3 1996/01/05 13:27:39 andreas
** - changed to support new streaming facilities
** - unique read/write methods for file and block transfer
** - more cleanups
**
*/
| [
"jchris.fillionr@kitware.com"
] | jchris.fillionr@kitware.com |
580b53d1d7a59ff0df255d46b39daab24143aac6 | ffcc6e8c4fe677b0e4ccd87abe1da6f7db2d3dea | /noaaParser/Data_Block.h | bd1da5d657c73cdad471c47d45a6b4ff9df17920 | [] | no_license | jrober/NOAAparser | 271152134cb76974e618f1dca742d0374273da60 | 4119a7e70df8ae81192e1462d15a4922ccc20e86 | refs/heads/master | 2020-07-27T06:15:17.922291 | 2019-09-24T22:00:14 | 2019-09-24T22:00:14 | 208,898,440 | 0 | 0 | null | 2019-09-24T22:00:15 | 2019-09-16T21:09:03 | C++ | UTF-8 | C++ | false | false | 397 | h | #pragma once
#include "Data_Record.h"
#include "Header.h"
#include<vector>
class Data_Block
{
private:
vector<Data_Record> dr;
Header header;
public:
// default constructor
Data_Block() {};
// initialization constructor
Data_Block(Header headerIn, vector<Data_Record> drIN) {
dr = drIN;
header = headerIn;
};
void coutData_Block();
void fileOut(ofstream& os);
};
| [
"justinrobertsdw@gmail.com"
] | justinrobertsdw@gmail.com |
6184adc0bf35d1101ab51d13fbb1d7d4b94a7228 | bae10b03c0b051a4e1b8a2110a3ad7fb3d33c84c | /G4beamline-3.06-source/g4bl/UNUSED/OLD/BLQtToolBar.cc | 8d6830654b4b8a194dbb0606297087b29bc62160 | [] | no_license | QUASAR-Group/Codes | a99e78e745e7e491cfb214030e168e489416fcbd | 5d81c48c653d9cb409d941ab7234b913a123f1cc | refs/heads/master | 2020-03-22T18:02:59.507670 | 2019-05-10T14:47:41 | 2019-05-10T14:47:41 | 140,433,391 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,197 | cc | // BLQtToolBar.cc
#ifdef G4BL_VISUAL
#ifdef G4BL_GUI
#include <QAction>
#include "G4UImanager.hh"
#include "G4VViewer.hh"
#include "G4Scene.hh"
#include "G4ViewParameters.hh"
#include "BLQtToolBar.h"
#include "BLVisManager.hh"
BLQtToolBar::BLQtToolBar() : QToolBar(), axesVisible(false)
{
nEv = new QLineEdit("1");
nEv->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred);
nEv->setToolTip("Number of events per run.");
//nEv->setMinimumWidth(40);
//QSizePolicy sp = nEv->sizePolicy();
//sp.setHorizontalStretch(1);
//nEv->setSizePolicy(sp);
addWidget(nEv);
QAction *a = addAction("Start Run");
connect(a, SIGNAL(triggered()), this, SLOT(run()));
a->setToolTip("Start a run with the above number of events; draw them.");
addSeparator();
a = addAction("Home");
connect(a, SIGNAL(triggered()), this, SLOT(home()));
a->setToolTip("Restore the viewer to Home position.");
a = addAction("Set Home");
connect(a, SIGNAL(triggered()), this, SLOT(setHome()));
a->setToolTip("Set the Home position to the current view.");
addSeparator();
a = addAction("Top View");
connect(a, SIGNAL(triggered()), this, SLOT(setViewpoint()));
a->setToolTip("Show system viewed from top (+y).");
a = addAction("Left View");
connect(a, SIGNAL(triggered()), this, SLOT(setViewpoint()));
a->setToolTip("Show system viewed from left side (+x).");
a = addAction("Right View");
connect(a, SIGNAL(triggered()), this, SLOT(setViewpoint()));
a->setToolTip("Show system viewed from right side (-x).");
a = addAction("Front View");
connect(a, SIGNAL(triggered()), this, SLOT(setViewpoint()));
a->setToolTip("Show system viewed from front (+z).");
a = addAction("Rear View");
connect(a, SIGNAL(triggered()), this, SLOT(setViewpoint()));
a->setToolTip("Show system viewed from rear (-z).");
a = addAction("Bottom View");
connect(a, SIGNAL(triggered()), this, SLOT(setViewpoint()));
a->setToolTip("Show system viewed from bottom (-y).");
addSeparator();
a = addAction("Show Axes");
connect(a, SIGNAL(triggered()), this, SLOT(showAxes()));
a->setToolTip("Display (Red,Green,Blue) Axes at the origin.");
getHomeCommands();
}
void BLQtToolBar::run()
{
int n = nEv->text().toInt();
QString cmd("/run/beamOn "+QString::number(n));
G4UImanager::GetUIpointer()->ApplyCommand(qPrintable(cmd));
}
void BLQtToolBar::home()
{
Q_FOREACH(QString s, homeCommands) {
G4UImanager::GetUIpointer()->ApplyCommand(qPrintable(s));
}
}
void BLQtToolBar::setHome()
{
getHomeCommands();
}
void BLQtToolBar::setViewpoint()
{
QAction *a = dynamic_cast<QAction*>(sender());
if(a != 0) {
QString text = a->text();
QStringList cmds;
// make it unlikely new viewpoint is along up vector
cmds << "/vis/viewer/set/upVector 0.315 -.823 .51";
if(text.startsWith("Front"))
cmds << "/vis/viewer/set/viewpointVector 0 0 1"
<< "/vis/viewer/set/upVector 0 1 0";
else if(text.startsWith("Rear"))
cmds << "/vis/viewer/set/viewpointVector 0 0 -1"
<< "/vis/viewer/set/upVector 0 1 0";
else if(text.startsWith("Top"))
cmds << "/vis/viewer/set/viewpointVector 0 1 0"
<< "/vis/viewer/set/upVector 1 0 0";
else if(text.startsWith("Bottom"))
cmds << "/vis/viewer/set/viewpointVector 0 -1 0"
<< "/vis/viewer/set/upVector -1 0 0";
else if(text.startsWith("Left"))
cmds << "/vis/viewer/set/viewpointVector 1 0 0"
<< "/vis/viewer/set/upVector 0 1 0";
else if(text.startsWith("Right"))
cmds << "/vis/viewer/set/viewpointVector -1 0 0"
<< "/vis/viewer/set/upVector 0 1 0";
Q_FOREACH(QString s, cmds) {
G4UImanager::GetUIpointer()->ApplyCommand(qPrintable(s));
}
}
}
void BLQtToolBar::showAxes()
{
G4UImanager::GetUIpointer()->ApplyCommand("/vis/scene/add/axes");
}
void BLQtToolBar::getHomeCommands()
{
G4Point3D p = BLVisManager::getObject()->GetCurrentScene()
->GetStandardTargetPoint();
G4VViewer *viewer = BLVisManager::getObject()->GetCurrentViewer();
const G4ViewParameters ¶m = viewer->GetViewParameters();
G4String s = param.CameraAndLightingCommands(p).c_str();
homeCommands = QString(s.c_str()).split("\n");
}
#endif // G4BL_GUI
#else // !G4BL_VISUAL
int dummy_g4bltoolbar=0;
#endif // G4BL_VISUAL
| [
"volodymyr.rodin@gmail.com"
] | volodymyr.rodin@gmail.com |
7a6a0b1445b8507c105554b023f1ba3f4e87e08e | c5c4b8c6231c55df710c3bd680a4395fe8ff2d63 | /include/gphyx/PhysicsManagerT.h | d13a25eb89b3059a8098bb425fff938823dd9088 | [] | no_license | grynca/gphyx | 19ccbe77140e69f13e64b37287be3eb95e9a68ce | 6793e753d8703a91d2fb7ebe0b9397d8caa9166d | refs/heads/master | 2021-04-26T22:14:07.885065 | 2018-03-06T09:07:42 | 2018-03-06T09:07:42 | 124,048,791 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,684 | h | #ifndef PHYSICSMANAGERT_H
#define PHYSICSMANAGERT_H
#include "gphyx_config.h"
#include "joints.h"
#include "maths/shapes/Shape.h"
#include "maths/shapes/OverlapHelper.h"
#include "types/containers/PolyPool.h"
namespace grynca {
// keeps internal copy of Speeds for better cache coherence
// (in hash map with key BodyIdT - Hasher<BodyIdT> must be available)
template <typename Derived/*CRTP*/, typename BodiesPairHandler>
class PhysicsManagerT : private SAPManagerC<Derived, gphyx::SAPDomain> {
public:
typedef SAPManagerC<Derived, gphyx::SAPDomain> Base;
typedef PolyPool<JointTypes::getTypesCount(), Joint, Derived> JointsPool;
typedef ObjFunc<void()> OverlapCbFunc;
PhysicsManagerT(f32 updates_per_sec = 60);
Base& accSAP();
BodiesPairHandler& accBPH();
void setUPS(f32 updates_per_sec);
f32 getUpdatesPerSec()const;
f32 getUpdateDt()const;
void addCollider(Collider& coll, const Transform& tr, Index body_id);
void removeCollider(Collider& coll);
void moveCollider(const Collider& coll, const Vec2& move_vec);
void updateCollider(const Collider& coll, const Transform& tr);
// calculates tentative velocity
void updateVelocity(Body& b, Speed& spd_io);
void updateContacts();
void solve();
void updateTransform(const Speed& spd, Transform& tr_io);
Vec2 updateTransform2(const Speed& spd, Transform& tr_io); // returns move vector which caller can use for moving with collider
u32 getContactsCount()const;
// Joints
template <typename JointType, typename... InitArgs>
JointType& addJoint(Index body_id1, Index body_id2, InitArgs&&... args);
void removeJoint(Index id);
template <typename JointType>
const JointType& getJoint(Index id)const;
template <typename JointType>
JointType& accJoint(Index id);
const Joint& getJoint(Index id)const;
Joint& accJoint(Index id);
// OverlapCallbacks
template <typename Functor>
void setBeginOverlapCb(u32 group1_id, u32 group2_id);
template <typename Functor>
void setOnOverlapCb(u32 group1_id, u32 group2_id);
template <typename Functor>
void setEndOverlapCb(u32 group1_id, u32 group2_id);
// setting for multiple groups specified with mask
template <typename Functor>
void setBeginOverlapCbs(u32 group1_id, CollisionGroupsMask groups2_mask);
template <typename Functor>
void setOnOverlapCbs(u32 group1_id, CollisionGroupsMask groups2_mask);
template <typename Functor>
void setEndOverlapCbs(u32 group1_id, CollisionGroupsMask groups2_mask);
void clear();
std::string getOverlapCallbacksDebugString()const;
// in case you want to call it yourself (e.g. do some custom handling + default)
void defaultPhysicalOverlap();
protected:
friend class SAPManagerBase<gphyx::SAPDomain>;
struct PreStepJoints_ {
template <typename TP, typename T>
static void f(Derived& pm);
};
struct StepJoints_ {
template <typename TP, typename T>
static void f(Derived& pm, bool& small);
};
// overriden from base
bool beforeBoxesOverlap_(gphyx::SAPBox&, gphyx::SAPBox&);
void afterBoxesOverlap_(gphyx::SAPBox&, gphyx::SAPBox&);
Derived& getAsD_();
void initCallbacks_();
OverlapCbFunc& accCbs_(OverlapCbFunc* cbs_arr, u32 row, u32 col);
template <typename OnSpeedFunc>
void solveInner_(const OnSpeedFunc& osf);
void getSpeedsFromBph_(u32 &spdA_id_out, u32 &spdB_id_out);
ARect transformBound_(const Collider& coll, const Transform& tr);
f32 ups_, dt_;
BodiesPairHandler bph_;
OverlapHelper ohlp_;
gphyx::SpeedsHashMapT speeds_;
// overlap callbacks
OverlapCbFunc begin_op_cbs_[GPHYX_MAX_CGROUPS*GPHYX_MAX_CGROUPS];
OverlapCbFunc on_op_cbs_[GPHYX_MAX_CGROUPS*GPHYX_MAX_CGROUPS];
OverlapCbFunc end_op_cbs_[GPHYX_MAX_CGROUPS*GPHYX_MAX_CGROUPS];
// contact joints (last only 1 tick)
fast_vector<ContactJoint<1> > contacts1_;
fast_vector<ContactJoint<2> > contacts2_;
// persistant joints
JointsPool joints_;
};
template <typename BodiesPairHandler>
class PhysicsManagerSimpleT : public PhysicsManagerT<PhysicsManagerSimpleT<BodiesPairHandler>, BodiesPairHandler> {};
}
#undef PMT
#include "PhysicsManagerT.inl"
#endif //PHYSICSMANAGERT_H
| [
"grynca@gmail.com"
] | grynca@gmail.com |
8153d0369ee4a2363c60807dbc36024d69b5514d | 90beaf6c9e091f5aaa40c3b24bff498a0ed5055a | /compiler/lib/Dialect/Linalg/Transforms/BufferizableOpInterfaceImpl.cpp | 97731c607074e565378f95051560e69014fdb775 | [
"Apache-2.0",
"NCSA",
"LicenseRef-scancode-generic-cla",
"LLVM-exception",
"BSD-2-Clause",
"MIT"
] | permissive | bytedance/byteir | cf1d9bc27ec8e9f7ea92ff449cbedf470f90115c | 0e7673074c9d9a299717bb3379cb774c9921f72c | refs/heads/main | 2023-08-31T04:42:44.536710 | 2023-08-30T20:14:22 | 2023-08-30T20:14:22 | 598,267,148 | 208 | 16 | NOASSERTION | 2023-09-13T21:50:19 | 2023-02-06T18:51:31 | MLIR | UTF-8 | C++ | false | false | 7,711 | cpp | //===- BufferizableOpInterfaceImpl.cpp - Impl. of BufferizableOpInterface -===//
//
// Copyright 2022 ByteDance Ltd. and/or its affiliates. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// 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.
//
//===----------------------------------------------------------------------===//
// Some code from Linalg/Transforms/BufferizableOpInterfaceImpl.cpp of LLVM
// Original license:
//
// 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
//
//===----------------------------------------------------------------------===//
#include "byteir/Dialect/Linalg/Transforms/BufferizableOpInterfaceImpl.h"
#include "byteir/Dialect/Linalg/IR/LinalgExtOps.h"
#include "mlir/Dialect/Bufferization/IR/BufferizableOpInterface.h"
#include "mlir/Dialect/Bufferization/IR/Bufferization.h"
#include "mlir/Dialect/Linalg/IR/Linalg.h"
#include "mlir/Dialect/MemRef/IR/MemRef.h"
#include "mlir/Dialect/Tensor/IR/Tensor.h"
#include "mlir/IR/Dialect.h"
#include "mlir/IR/Operation.h"
#include "mlir/Interfaces/DestinationStyleOpInterface.h"
using namespace mlir;
using namespace linalg;
using namespace linalg_ext;
using namespace mlir::bufferization;
namespace {
/// Generic conversion for any DestinationStyleOpInterface on tensors.
static LogicalResult
bufferizeDestinationStyleOpInterface(RewriterBase &rewriter,
DestinationStyleOpInterface op,
const BufferizationOptions &options) {
// Take a guard before anything else.
OpBuilder::InsertionGuard g(rewriter);
rewriter.setInsertionPoint(op);
// Nothing to do. This op is already bufferized.
if (op.hasBufferSemantics())
return success();
// Ensure op has only tensors. Allow mixed tensor-buffer mode on a per-need
// basis.
if (!op.hasTensorSemantics())
return op->emitError() << "op does not have tensor semantics";
// New input operands for the cloned op.
SmallVector<Value> newInputBuffers;
newInputBuffers.reserve(op.getNumDpsInputs());
for (OpOperand *opOperand : op.getDpsInputOperands()) {
if (op.isScalar(opOperand)) {
newInputBuffers.push_back(opOperand->get());
continue;
}
FailureOr<Value> buffer = getBuffer(rewriter, opOperand->get(), options);
if (failed(buffer))
return failure();
newInputBuffers.push_back(*buffer);
}
// New output operands for the cloned op.
SmallVector<Value> newOutputBuffers;
llvm::DenseSet<Value> visited;
for (OpResult opResult : op->getOpResults()) {
OpOperand *opOperand = op.getDpsInitOperand(opResult.getResultNumber());
FailureOr<Value> resultBuffer =
getBuffer(rewriter, opOperand->get(), options);
if (failed(resultBuffer))
return failure();
newOutputBuffers.push_back(*resultBuffer);
}
// Merge input/output operands.
SmallVector<Value> newOperands = newInputBuffers;
newOperands.append(newOutputBuffers.begin(), newOutputBuffers.end());
// Set insertion point now that potential alloc/dealloc are introduced.
rewriter.setInsertionPoint(op);
// Clone the op, but use the new operands. Move the existing block into the
// new op. Since the new op does not have any tensor results, it does not
// return anything.
auto newOp = cast<DestinationStyleOpInterface>(cloneWithoutRegions(
rewriter, op, /*newResultTypes=*/TypeRange{}, newOperands));
if (op->getNumRegions() == 1) {
rewriter.inlineRegionBefore(op->getRegion(0), newOp->getRegion(0),
newOp->getRegion(0).begin());
}
// Replace the results of the old op with the new output buffers.
replaceOpWithBufferizedValues(rewriter, op, newOutputBuffers);
return success();
}
/// Helper structure that iterates over all LinalgOps in `OpTys` and registers
/// the `BufferizableOpInterface` with each of them.
template <typename... Ops> struct LinalgExtOpInterfaceHelper {
static void registerOpInterface(MLIRContext *ctx) {
(Ops::template attachInterface<LinalgExtBufferizableOpInterface<Ops>>(*ctx),
...);
}
};
} // namespace
namespace mlir::linalg_ext {
bool LinalgExtBufferizableOpInterfaceImpl::bufferizesToMemoryRead(
Operation *op, OpOperand &opOperand,
const AnalysisState & /* state*/) const {
// Operand is read if it is used in the computation.
if (auto linalgExtOp = dyn_cast<linalg_ext::LinalgExtOp>(op)) {
return linalgExtOp.isOperandRead(opOperand.getOperandNumber());
} else if (auto linalgOp = dyn_cast<linalg::LinalgOp>(op)) {
return linalgOp.payloadUsesValueFromOperand(&opOperand);
}
return false;
}
bool LinalgExtBufferizableOpInterfaceImpl::bufferizesToMemoryWrite(
Operation *op, OpOperand &opOperand, const AnalysisState &state) const {
// Operand is written to if it has an aliasing OpResult.
auto bufferizableOp = cast<BufferizableOpInterface>(op);
return bufferizableOp.getAliasingOpResults(opOperand, state)
.getNumAliases() != 0;
}
bufferization::AliasingOpOperandList
LinalgExtBufferizableOpInterfaceImpl::getAliasingOpOperands(
Operation *op, OpResult opResult, const AnalysisState &) const {
auto genericOp = cast<DestinationStyleOpInterface>(op);
// The i-th OpResult may alias with the i-th "out" tensor.
return {{genericOp.getDpsInitOperand(opResult.getResultNumber()),
BufferRelation::Equivalent}};
}
bufferization::AliasingOpResultList
LinalgExtBufferizableOpInterfaceImpl::getAliasingOpResults(
Operation *op, OpOperand &opOperand, const AnalysisState &) const {
auto genericOp = cast<DestinationStyleOpInterface>(op);
// The i-th "out" tensor may alias with the i-th OpResult.
if (genericOp.isDpsInit(&opOperand))
return {
{genericOp.getTiedOpResult(&opOperand), BufferRelation::Equivalent}};
return {};
}
BufferRelation LinalgExtBufferizableOpInterfaceImpl::bufferRelation(
Operation *op, OpResult opResult, const AnalysisState &state) const {
return BufferRelation::Equivalent;
}
LogicalResult LinalgExtBufferizableOpInterfaceImpl::bufferize(
Operation *op, RewriterBase &rewriter,
const BufferizationOptions &options) const {
return bufferizeDestinationStyleOpInterface(
rewriter, cast<DestinationStyleOpInterface>(op), options);
}
} // namespace mlir::linalg_ext
void mlir::linalg_ext::registerBufferizableOpInterfaceExternalModels(
DialectRegistry ®istry) {
registry.addExtension(
+[](MLIRContext *ctx, linalg_ext::LinalgExtDialect *dialect) {
// Register all Linalg structured ops. `LinalgOp` is an interface and it
// is not possible to attach an external interface to an existing
// interface. Therefore, attach the `BufferizableOpInterface` to all ops
// one-by-one.
LinalgExtOpInterfaceHelper<
#define GET_OP_LIST
#include "byteir/Dialect/Linalg/IR/LinalgExtOps.cpp.inc"
>::registerOpInterface(ctx);
});
}
| [
"noreply@github.com"
] | bytedance.noreply@github.com |
e90df3f822d57689fc7980ecd98bfe9bf527a75d | fc73264e6a2632dc229962e2e55e8f7e51af646a | /solid/system/socketaddress.hpp | 53f86f0d765584876af5b293953df4527967d41e | [
"BSL-1.0"
] | permissive | zodsoft/solidframe | 8b259b208bda99bd85029664d92a05a0f254420c | 136e913027cd94a54bff3dee4b0a6673f2123a7f | refs/heads/master | 2021-01-12T23:59:56.403982 | 2016-12-22T09:50:52 | 2016-12-22T09:50:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,766 | hpp | // solid/system/socketaddress.hpp
//
// Copyright (c) 2007, 2008 Valentin Palade (vipalade @ gmail . com)
//
// This file is part of SolidFrame framework.
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt.
//
#ifndef SYSTEM_SOCKETADDRESS_HPP
#define SYSTEM_SOCKETADDRESS_HPP
#ifndef SOLID_ON_WINDOWS
#include <sys/un.h>
#include <arpa/inet.h>
#endif
#include <ostream>
#include <array>
#include "solid/system/common.hpp"
#include "solid/system/socketinfo.hpp"
#if defined(SOLID_USE_CPP11) && !defined(USHAREDBACKEND)
#include <memory>
#elif defined(UBOOSTSHAREDPTR) && !defined(USHAREDBACKEND)
#include "boost/shared_ptr.hpp"
#else
#include "solid/system/sharedbackend.hpp"
#endif
#ifndef SOLID_HAS_NO_INLINES
#include "solid/system/cassert.hpp"
#include "solid/system/debug.hpp"
#endif
namespace solid{
class SocketDevice;
//struct sockaddr_in;
//struct sockaddr_in6;
//==================================================================
//! An interator for POSIX addrinfo (see man getaddrinfo)
/*!
Usually it will hold all data needed for creating and connecting
a socket. Use ResolverData::begin() to get started.
*/
struct ResolveIterator{
ResolveIterator();
ResolveIterator& next();
int family()const;
int type()const;
int protocol()const;
size_t size()const;
sockaddr* sockAddr()const;
operator bool()const;
ResolveIterator &operator++();
bool operator==(const ResolveIterator &_rrit)const;
private:
friend struct ResolveData;
ResolveIterator(addrinfo *_pa);
const addrinfo *paddr;
};
//==================================================================
struct DirectResoveInfo{
enum FlagsE{
#ifndef SOLID_ON_WINDOWS
CannonName = AI_CANONNAME,
All = AI_ALL,
AddrConfig = AI_ADDRCONFIG,
V4Mapped = AI_V4MAPPED,
NumericHost = AI_NUMERICHOST,
NumericService = AI_NUMERICSERV,
#else
CannonName,
All,
AddrConfig,
V4Mapped,
NumericHost,
NumericService,
#endif
Numeric = NumericHost | NumericService,
};
};
//! A shared pointer for POSIX addrinfo (see man getaddrinfo)
/*!
Use synchronous_resolve to create ResolveData objects.
*/
struct ResolveData{
typedef ResolveIterator const_iterator;
ResolveData();
ResolveData(addrinfo *_pai);
ResolveData(const ResolveData &_rai);
~ResolveData();
//! Get an iterator to he first resolved ip address
const_iterator begin()const;
const_iterator end()const;
//! Check if the returned list of ip addresses is empty
bool empty()const;
void clear();
ResolveData& operator=(const ResolveData &_rrd);
private:
static void delete_addrinfo(void *_pv);
#if defined(SOLID_USE_CPP11) && !defined(USHAREDBACKEND)
typedef std::shared_ptr<addrinfo> AddrInfoSharedPtrT;
AddrInfoSharedPtrT aiptr;
#elif defined(UBOOSTSHAREDPTR) && !defined(USHAREDBACKEND)
typedef boost::shared_ptr<addrinfo> AddrInfoSharedPtrT;
AddrInfoSharedPtrT aiptr;
#else
SharedStub *pss;
#endif
};
ResolveData synchronous_resolve(const char *_node, const char *_service);
ResolveData synchronous_resolve(
const char *_node,
const char *_service,
int _flags,
int _family = -1,
int _type = -1,
int _proto = -1
);
ResolveData synchronous_resolve(const char *_node, int _port);
ResolveData synchronous_resolve(
const char *_node,
int _port,
int _flags,
int _family = -1,
int _type = -1,
int _proto = -1
);
struct SocketAddressStub;
struct ReverseResolveInfo{
enum FlagsE{
#ifndef SOLID_ON_WINDOWS
NameRequest = NI_NAMEREQD,
Datagram = NI_DGRAM,
NoFQDN = NI_NOFQDN,
NumericHost = NI_NUMERICHOST,
NumericService = NI_NUMERICSERV,
#else
NameRequest,
Datagram,
NoFQDN,
NumericHost,
NumericService,
#endif
Numeric = NumericHost | NumericService,
};
};
bool synchronous_resolve(std::string &_rhost, std::string &_rserv, const SocketAddressStub &_rsa, int _flags = 0);
//==================================================================
struct SocketAddress;
struct SocketAddressInet;
struct SocketAddressInet4;
struct SocketAddressInet6;
struct SocketAddressLocal;
#ifdef SOLID_ON_WINDOWS
typedef int socklen_t;
#endif
//! A pair of a sockaddr pointer and a size
/*!
It is a commodity structure, it will not allocate data
for sockaddr pointer nor it will delete it. Use this
structure with SocketAddress and ResolveIterator
*/
struct SocketAddressStub{
SocketAddressStub(sockaddr *_pa = nullptr, size_t _sz = 0);
SocketAddressStub(const ResolveIterator &_it);
SocketAddressStub(const SocketAddress &_rsa);
SocketAddressStub(const SocketAddressInet &_rsa);
SocketAddressStub(const SocketAddressInet4 &_rsa);
SocketAddressStub(const SocketAddressInet6 &_rsa);
SocketAddressStub(const SocketAddressLocal &_rsa);
SocketAddressStub& operator=(const ResolveIterator &_it);
SocketAddressStub& operator=(const SocketAddress &_rsa);
SocketAddressStub& operator=(const SocketAddressInet &_rsa);
SocketAddressStub& operator=(const SocketAddressInet4 &_rsa);
SocketAddressStub& operator=(const SocketAddressInet6 &_rsa);
SocketAddressStub& operator=(const SocketAddressLocal &_rsa);
operator const sockaddr*()const;
void clear();
SocketInfo::Family family()const;
bool isInet4()const;
bool isInet6()const;
bool isLocal()const;
socklen_t size()const;
int port()const;
const sockaddr *sockAddr()const;
private:
const sockaddr *addr;
socklen_t sz;
};
//==================================================================
//! Holds a generic socket address
/*!
On unix it can be either: inet_v4, inet_v6 or unix/local address
*/
struct SocketAddress{
private:
union AddrUnion{
sockaddr addr;
sockaddr_in inaddr4;
sockaddr_in6 inaddr6;
#ifndef SOLID_ON_WINDOWS
sockaddr_un localaddr;
#endif
};
public:
enum {Capacity = sizeof(AddrUnion)};
SocketAddress();
SocketAddress(const SocketAddressStub &);
SocketAddress(const char* _addr, int _port);
SocketAddress(const char* _path);
SocketAddress& operator=(const SocketAddressStub &);
SocketInfo::Family family()const;
bool isInet4()const;
bool isInet6()const;
bool isLocal()const;
bool isLoopback()const;
bool isInvalid()const;
bool empty()const;
const socklen_t& size()const;
const sockaddr* sockAddr()const;
operator const sockaddr*()const;
bool operator<(const SocketAddress &_raddr)const;
bool operator==(const SocketAddress &_raddr)const;
void address(const char*_str);
const in_addr& address4()const;
const in6_addr& address6()const;
int port()const;
bool port(int _port);
void clear();
size_t hash()const;
size_t addressHash()const;
void path(const char*_pth);
const char* path()const;
private:
friend class SocketDevice;
operator sockaddr*();
sockaddr* sockAddr();
AddrUnion d;
socklen_t sz;
};
//==================================================================
struct SocketAddressInet{
private:
union AddrUnion{
sockaddr addr;
sockaddr_in inaddr4;
sockaddr_in6 inaddr6;
};
public:
enum {Capacity = sizeof(AddrUnion)};
typedef std::array<uint8_t, 4> DataArray4T;
typedef std::array<uint8_t, 16> DataArray6T;
SocketAddressInet();
SocketAddressInet(const SocketAddressStub &);
SocketAddressInet(const char* _addr, int _port = 0);
SocketAddressInet& operator=(const SocketAddressStub &);
SocketInfo::Family family()const;
bool isInet4()const;
bool isInet6()const;
bool isLoopback()const;
bool isInvalid()const;
bool empty()const;
const socklen_t& size()const;
const sockaddr* sockAddr()const;
operator const sockaddr*()const;
bool toBinary(DataArray4T &_bin, uint16_t &_port)const;
bool toBinary(DataArray6T &_bin, uint16_t &_port)const;
void fromBinary(const DataArray4T &_bin, uint16_t _port = 0);
void fromBinary(const DataArray6T &_bin, uint16_t _port = 0);
bool operator<(const SocketAddressInet &_raddr)const;
bool operator==(const SocketAddressInet &_raddr)const;
void address(const char*_str);
const in_addr& address4()const;
const in6_addr& address6()const;
int port()const;
bool port(int _port);
void clear();
size_t hash()const;
size_t addressHash()const;
private:
friend class SocketDevice;
operator sockaddr*();
sockaddr* sockAddr();
AddrUnion d;
socklen_t sz;
};
//==================================================================
struct SocketAddressInet4{
private:
union AddrUnion{
sockaddr addr;
sockaddr_in inaddr4;
};
public:
enum {Capacity = sizeof(AddrUnion)};
typedef std::array<uint8_t, 4> DataArrayT;
SocketAddressInet4();
SocketAddressInet4(const SocketAddressStub &);
SocketAddressInet4(const char* _addr, int _port = 0);
SocketAddressInet4(uint32_t _addr, int _port);
SocketAddressInet4(const DataArrayT &_addr, int _port = 0);
//SocketAddressInet4& operator=(const ResolveIterator &);
SocketAddressInet4& operator=(const SocketAddressStub &);
SocketInfo::Family family()const;
bool isInet4()const;
bool isLoopback()const;
bool isInvalid()const;
socklen_t size()const;
const sockaddr* sockAddr()const;
//operator sockaddr*(){return sockAddr();}
operator const sockaddr*()const;
void toBinary(DataArrayT &_bin, uint16_t &_port)const;
void toUInt(uint32_t &_addr, uint16_t &_port)const;
void fromBinary(const DataArrayT &_bin, uint16_t _port = 0);
void fromUInt(uint32_t _addr, uint16_t _port = 0);
bool operator<(const SocketAddressInet4 &_raddr)const;
bool operator==(const SocketAddressInet4 &_raddr)const;
void address(const char*_str);
const in_addr& address()const;
int port()const;
void port(int _port);
void clear();
size_t hash()const;
size_t addressHash()const;
private:
friend class SocketDevice;
operator sockaddr*();
sockaddr* sockAddr();
AddrUnion d;
};
//==================================================================
struct SocketAddressInet6{
private:
union AddrUnion{
sockaddr addr;
sockaddr_in6 inaddr6;
};
public:
enum {Capacity = sizeof(AddrUnion)};
typedef std::array<uint8_t, 16> DataArrayT;
SocketAddressInet6();
SocketAddressInet6(const SocketAddressStub &);
SocketAddressInet6(const char* _addr, int _port = 0);
SocketAddressInet6(const DataArrayT &_addr, int _port = 0);
SocketAddressInet6& operator=(const SocketAddressStub &);
SocketInfo::Family family()const;
bool isInet6()const;
bool isLoopback()const;
bool isInvalid()const;
bool empty()const;
socklen_t size()const;
const sockaddr* sockAddr()const;
operator const sockaddr*()const;
void toBinary(DataArrayT &_bin, uint16_t &_port)const;
void fromBinary(const DataArrayT &_bin, uint16_t _port = 0);
bool operator<(const SocketAddressInet6 &_raddr)const;
bool operator==(const SocketAddressInet6 &_raddr)const;
void address(const char*_str);
const in6_addr& address()const;
int port()const;
void port(int _port);
void clear();
size_t hash()const;
size_t addressHash()const;
private:
friend class SocketDevice;
operator sockaddr*();
sockaddr* sockAddr();
AddrUnion d;
};
//==================================================================
bool operator<(const in_addr &_inaddr1, const in_addr &_inaddr2);
bool operator==(const in_addr &_inaddr1, const in_addr &_inaddr2);
bool operator<(const in6_addr &_inaddr1, const in6_addr &_inaddr2);
bool operator==(const in6_addr &_inaddr1, const in6_addr &_inaddr2);
size_t in_addr_hash(const in_addr &_inaddr);
size_t in_addr_hash(const in6_addr &_inaddr);
std::ostream& operator<<(std::ostream& _ros, const SocketAddressInet4& _rsa);
std::ostream& operator<<(std::ostream& _ros, const SocketAddressInet& _rsa);
std::ostream& operator<<(std::ostream& _ros, const SocketAddress& _rsa);
//==================================================================
#ifndef SOLID_ON_WINDOWS
struct SocketAddressLocal{
private:
union AddrUnion{
sockaddr addr;
sockaddr_un localaddr;
};
public:
enum {Capacity = sizeof(AddrUnion)};
SocketAddressLocal();
SocketAddressLocal(const char* _path);
SocketAddressLocal& operator=(const SocketAddressStub &);
SocketInfo::Family family()const;
bool empty()const;
const socklen_t& size()const;
const sockaddr* sockAddr()const;
operator const sockaddr*()const;
bool operator<(const SocketAddressLocal &_raddr)const;
bool operator==(const SocketAddressLocal &_raddr)const;
void clear();
size_t hash()const;
size_t addressHash()const;
void path(const char*_pth);
const char* path()const;
private:
friend class SocketDevice;
operator sockaddr*();
sockaddr* sockAddr();
AddrUnion d;
socklen_t sz;
};
#endif
//==================================================================
#ifndef SOLID_HAS_NO_INLINES
#include "solid/system/socketaddress.ipp"
#endif
//==================================================================
}//namespace solid
#endif
| [
"vipalade@gmail.com"
] | vipalade@gmail.com |
d63a959664866c84dade07e89eb2023d64a4c0d0 | a01851ad710157c72e2a122a1f7735639f6db225 | /L921. Minimum Add to Make Parentheses Valid.cpp | e536c312d18ac7168d6e3bb4991854591f32f776 | [] | no_license | we-are-kicking-lhx/xinxinalgorithm | 9089629b210a5a0e199f374c74afc24742644f03 | e988e3bca6438af6933378f374afb2627a5708fe | refs/heads/master | 2021-06-27T10:50:22.979162 | 2020-11-23T07:01:23 | 2020-11-23T07:01:23 | 173,912,054 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 382 | cpp | class Solution
{
public:
int minAddToMakeValid(string S)
{
int n = 0, r = 0;
for (int i = 0; i < S.size(); i++)
{
if (S[i] == '(')
r++;
else
{
if (r != 0)
r--;
else
n++;
}
}
return n + r;
}
}; | [
"1917089423@qq.com"
] | 1917089423@qq.com |
78248540162ac681b330e2fb6ff550e2ec68d342 | 8f8ae70775eda42f71d0e6354b9caba4576f3310 | /firefoamcases/cases/singleBox/constant/LESProperties | 8f3596985f84227fd8eaa161347ebcd7ffdda033 | [] | no_license | hong27/myFireFoamCases | 6070bb35781717b58bdec2f1a35be79077ce8111 | 8709c8aa7f1aa1718f3fbf0c7cdc7b284f531c57 | refs/heads/master | 2020-06-14T01:38:28.073535 | 2019-07-02T12:03:25 | 2019-07-02T12:03:25 | 194,851,906 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,955 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: dev |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class dictionary;
location "constant";
object LESProperties;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
LESModel oneEqEddy;
//LESModel WALE;
//delta vanDriest;
delta cubeRootVol;
turbulence on;
printCoeffs on;
WALECoeffs
{
cw 0.5;
}
oneEqEddyCoeffs
{
ck 0.03;
Prt 1;
}
cubeRootVolCoeffs
{
deltaCoeff 1;
}
PrandtlCoeffs
{
delta cubeRootVol;
cubeRootVolCoeffs
{
deltaCoeff 1;
}
smoothCoeffs
{
delta cubeRootVol;
cubeRootVolCoeffs
{
deltaCoeff 1;
}
maxDeltaRatio 1.1;
}
Cdelta 0.158;
}
vanDriestCoeffs
{
delta cubeRootVol;
cubeRootVolCoeffs
{
deltaCoeff 1;
}
smoothCoeffs
{
delta cubeRootVol;
cubeRootVolCoeffs
{
deltaCoeff 1;
}
maxDeltaRatio 1.1;
}
Aplus 26;
Cdelta 0.158;
}
smoothCoeffs
{
delta cubeRootVol;
cubeRootVolCoeffs
{
deltaCoeff 1;
}
maxDeltaRatio 1.1;
}
// ************************************************************************* //
| [
"linjianhongljh@gmail.com"
] | linjianhongljh@gmail.com | |
700f3ead5c13fc61207d2c4b3cf23d7406940a7c | 6c5fb5b74be518a5103b812f3b648c4eab8f99d5 | /competitive_programming/chapter3_greedy_involving_sorting/uva11100.cc | 27eb5624a04c3085d0dd0bede47c4fc3d1db76dc | [] | no_license | thyagostall/competitive | 1bfc44232773693edbfb59526650f47622d69791 | db5ed16ae0ef745fc407f6baabb0df2e505eb85e | refs/heads/master | 2021-01-22T06:44:35.390582 | 2018-10-03T03:56:14 | 2018-10-03T03:56:14 | 81,784,040 | 0 | 0 | null | 2017-06-17T17:11:15 | 2017-02-13T04:14:27 | C++ | UTF-8 | C++ | false | false | 1,765 | cc | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
ostream &operator<<(ostream &out, const vector<int> &v);
ostream &operator<<(ostream &out, const vector<vector<int>> &v);
vector<vector<int>> compute_bags(vector<int> &bag_sizes);
int compute_bag_qty(vector<int> &bag_sizes);
int main()
{
int bag_qty, case_num = 0;
while (cin >> bag_qty && bag_qty) {
vector<int> bag_sizes(bag_qty, 0);
for (int i = 0; i < bag_qty; i++) {
cin >> bag_sizes[i];
}
if (case_num++) cout << endl;
vector<vector<int>> bags = compute_bags(bag_sizes);
cout << bags.size() << endl;
cout << bags;
}
}
ostream &operator<<(ostream &out, const vector<int> &v)
{
for (int i = 0; i < v.size(); i++) {
if (i) out << " ";
out << v[i];
}
return out;
}
ostream &operator<<(ostream &out, const vector<vector<int>> &v)
{
for (int i = 0; i < v.size(); i++) {
out << v[i] << endl;
}
return out;
}
vector<vector<int>> compute_bags(vector<int> &bag_sizes)
{
vector<vector<int>> bags;
sort(bag_sizes.begin(), bag_sizes.end());
int bag_qty = compute_bag_qty(bag_sizes);
for (int i = 0; i < bag_qty; i++) {
vector<int> bag;
for (int j = i; j < bag_sizes.size(); j += bag_qty) {
bag.push_back(bag_sizes[j]);
}
bags.push_back(bag);
}
return bags;
}
int compute_bag_qty(vector<int> &bag_sizes)
{
int bag_qty = 1, current_streak = 1;
for (int i = 1; i < bag_sizes.size(); i++) {
if (bag_sizes[i] == bag_sizes[i - 1]) {
bag_qty = max(++current_streak, bag_qty);
} else {
current_streak = 1;
}
}
return bag_qty;
}
| [
"thstall@gmail.com"
] | thstall@gmail.com |
08046449bcd5ba2554d9eaa2080a6281144e2167 | 5c675c06498225ae57662796f252eb0a9ec48947 | /graphicmap.cpp | 73a64afde1a6c0ae4ea6d2c2bc4f8326c59189e4 | [] | no_license | aminrd/SharifWars | 86e5bc1b095c71c37b95d32a48b5a7aac55b89c3 | 30b4ac1c1c9410b3737675392c93ceb0295634a3 | refs/heads/master | 2020-04-06T20:10:46.685075 | 2019-08-20T17:32:12 | 2019-08-20T17:32:12 | 157,764,302 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,523 | cpp | #include "graphicmap.h"
#include <QPainter>
#include <gameobject.h>
#include <QHeaderView>
#include <QScrollBar>
#include "map.h"
#include "player.h"
#include "gameobject.h"
GraphicMap::GraphicMap(QTableWidget* _table, Map* _map, QWidget* parent){
map=_map;
maptable=_table;
}
void GraphicMap::paintEvent(QPaintEvent* event){
QWidget::paintEvent(event);
QPainter p(this);
int width_block=this->width()/map->GetColcount();
int height_block=this->height()/map->GetRowcount();
int start_height=this->height()- (height_block*map->GetRowcount());
start_height/=2;
int start_width=this->width()- (width_block*map->GetColcount());
start_width/=2;
for(int i=0; i<map->GetRowcount(); i++)
for(int j=0; j<map->GetColcount(); j++){
int number=0;//number of game object in the block
vector <GameObject*> temp_checker;
temp_checker=map->getBlock(i,j)->getObjects();
number=0;
//-----------------------------------------------------------------show empty block
if(map->getBlock(i,j)->getEmpty()==true) { //show empty block
p.setBrush(QColor(20,80,20,220));
}
else{
Player s;
int id=temp_checker[number]->getPlayer()->getPlayerID();
switch(id){
case -1:
p.setBrush(QColor(200,200,200,220));
break;
case 1:
p.setBrush(QColor(80,20,20,220));
break;
case 2:
p.setBrush(QColor(20,20,80,220));
break;
case 3:
p.setBrush(QColor(80,80,20,220));
break;
case 4:
p.setBrush(QColor(80,20,80,220));
break;
case 5:
p.setBrush(QColor(20,80,80,220));
break;
}
}
p.setPen(Qt::NoPen);
p.drawRect(j*width_block+start_width,i*height_block+start_height,width_block,height_block);
}
p.setBrush(Qt::NoBrush);
p.setPen(Qt::blue);
p.drawRect(start_width+maptable->horizontalScrollBar()->value()*width_block , start_height+maptable->verticalScrollBar()->value()*height_block , width_block*47, height_block*18);
}
| [
"aghaee@cs.ubc.ca"
] | aghaee@cs.ubc.ca |
76fdeb34332eaf2115e27c3e0343729e190e93f0 | 81464366d3d2ab91a6600be8646d0856d413d8be | /Sum_on_right_side.cpp | 19ad21245feb1460671142c5725faf4835ddb4c5 | [] | no_license | SunnyJaiswal5297/Basic_c_programs | 08f289d04817f81222ceaacd7362e47fbae2935e | a2fd6168ce4ff075be6488c172200da21058dd93 | refs/heads/master | 2022-12-03T09:53:35.189234 | 2020-07-28T17:17:17 | 2020-07-28T17:17:17 | 283,201,986 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 671 | cpp | #include<iostream>
#include<time.h>
using namespace std;
int main()
{
clock_t start=clock();
int t;
cin>>t;
while(t--)
{
int n,i,j;
cin>>n;
int arr[n],b[n];
for(i=0;i<n;i++)
{
cin>>arr[i];
b[i]=0;
}
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(arr[i]>arr[j])
{
b[i]++;
}
}
}
for(i=0;i<n;i++)
cout<<b[i]<<" ";
cout<<"\n";
}
cout<<((clock()-start)/CLOCKS_PER_SEC);
return 0;
} | [
"s2jaiswal.sj@gmail.com"
] | s2jaiswal.sj@gmail.com |
5e5758d8f9f1e65e6255f1ee142804ab51b59f0e | 4cdd282955b32e41705c1dc3c077e7625af740ef | /main.cpp | ad4fd81644adc0e3151caaa631050a9fb90afb98 | [] | no_license | Makgalemela/Checkers-Game | bb096deb33a60a67ada3ed2af9551c0497a5c3c8 | 3131543446ff828258fce82a615c9101ca852fda | refs/heads/master | 2023-02-13T06:59:28.921853 | 2021-01-01T14:46:49 | 2021-01-01T14:46:49 | 322,437,680 | 0 | 0 | null | 2021-01-10T10:15:58 | 2020-12-17T23:31:49 | C++ | UTF-8 | C++ | false | false | 1,028 | cpp |
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cstdlib>
#include <time.h>
#include <string>
#include "checkers.h"
using namespace std;
///The function read the board sizes and feed them to the game engine
vector<int> boardSizes(){
int temp_size = 0;
ifstream inFile;
inFile.open("input.txt");
vector<int> arrSizes;
while (inFile.is_open() && inFile>>temp_size){
if(temp_size%2 ==0){
if(temp_size >5){
if(temp_size <13){
arrSizes.push_back(temp_size);
}
}
}
}
return arrSizes;
}
int main()
{
srand(time(NULL));
vector<int> boardsize(boardSizes());
for(int i = 0 ; i < boardsize.size(); i++){
checkers c(boardsize.at(i));
c.startGame();
while(c.startNewGame()==false){
c.randomiser();
c.secondAlgorithm();
}
c.finalScore();
c.writeHistory(" ");
}
return 0;
}
| [
"gugurachelmvelase102@gmail.com"
] | gugurachelmvelase102@gmail.com |
ace1f5777dc271c732c973f417d7005cfe8214f9 | 1834c0796ee324243f550357c67d8bcd7c94de17 | /SDK/TCF_WBP_Item_Death_structs.hpp | e095b66b73560bb94b5189140b0a3de04928bd36 | [] | no_license | DarkCodez/TCF-SDK | ce41cc7dab47c98b382ad0f87696780fab9898d2 | 134a694d3f0a42ea149a811750fcc945437a70cc | refs/heads/master | 2023-08-25T20:54:04.496383 | 2021-10-25T11:26:18 | 2021-10-25T11:26:18 | 423,337,506 | 1 | 0 | null | 2021-11-01T04:31:21 | 2021-11-01T04:31:20 | null | UTF-8 | C++ | false | false | 290 | hpp | #pragma once
// The Cycle Frontier (1.X) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "TCF_Basic.hpp"
#include "TCF_ScreenSystem_classes.hpp"
#include "TCF_UMG_classes.hpp"
#include "TCF_Prospect_classes.hpp"
namespace SDK
{
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"30532128+pubgsdk@users.noreply.github.com"
] | 30532128+pubgsdk@users.noreply.github.com |
0ae32cafdc3d2bf431ef71945806ee9920995739 | 309d7e225969cacc90b9c812a9226c2386651d2b | /sources/core/inc/TimerController.class.hpp | 0d09a069a9ecaec3903c0f379478c0db9671a59a | [] | no_license | Hadrien-Estela/Gbmu | a62350e532c7f63a4f9ca6202694c787705ec323 | cc61e80867ee6bff00d186b3e7007af50e403bd3 | refs/heads/master | 2021-09-28T21:04:03.284880 | 2018-11-20T15:54:15 | 2018-11-20T15:54:15 | 117,264,806 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,820 | hpp | // ************************************************************************** //
// //
// ::: :::::::: //
// TimerController.class.hpp :+: :+: :+: //
// +:+ +:+ +:+ //
// By: hestela <hestela@student.42.fr> +#+ +:+ +#+ //
// +#+#+#+#+#+ +#+ //
// Created: 2016/01/01 14:06:59 by hestela #+# #+# //
// Updated: 2016/01/01 14:06:59 by hestela ### ########.fr //
// //
// ************************************************************************** //
#ifndef TIMERCONTROLLER_CLASS_HPP
# define TIMERCONTROLLER_CLASS_HPP
# include <iostream>
# include <fstream>
# include "Cpu.class.hpp"
# include "SerialIO.class.hpp"
# include "Defines.hpp"
/*
************************* USED REGISTERS ************************
-- DIV Register (Divider Register) [0xFF04]
This register is incremented 16384 (~16779 on SGB) times a second.
Writing any value sets it to $00.
-- TIMA Register (Timer counter) [0xFF05]
This timer is incremented by a clock frequency specified by the TAC register ($FF07).
The timer generates an interrupt when it overflows.
-- TMA Register (Timer Modulo) [0xFF06]
When the TIMA overflows, this data will be loaded.
-- TAC Register (Timer Control) [0xFF07]
BIT 2: Timer Stop. ( 0 = Stop | 1 = start )
BITS 0-1: Input Clock Select
00: 4. 096 KHz
01: 262. 144 Khz
10: 65. 536 KHz
11: 16. 384 KHz
*/
namespace Gbmu
{
class TimerController
{
private:
enum InputClock // values of Bits 01 of TAC register in cycles
{
Clock_00 = 1024,
Clock_01 = 16,
Clock_10 = 64,
Clock_11 = 256
};
private:
Cpu* _cpu; // get a pointer to the Cpu ( the parent )
struct SerialIO::IORegisters* _IOREGS; // get a pointer to the IO registers
size_t _cyclesTIMA; // Cycle counter for TIMA
size_t _cyclesDIV; // Cycle counter for DIV
public:
TimerController( Cpu* cpu );
virtual ~TimerController( void );
void reset ( void );
void update ( uint8_t const& cycles );
void onWriteDIV ( void );
void onWriteTAC ( uint8_t const& value );
void saveState ( std::fstream& file );
void loadState ( std::fstream& file );
private:
bool timerStarted ( void ) const;
size_t InputClock ( void ) const;
};
}
#else
namespace Gbmu
{
class TimerController;
}
#endif // !TIMERCONTROLLER_CLASS_HPP
| [
"hadrienestela@gmail.com"
] | hadrienestela@gmail.com |
c7864cad8799cce9a427e8517375e76358e0b6bb | 3a8b30c331b4e0e6f81cb7823e98ee667b3b2180 | /QSW/wov/ribbonemitter.h | ab78e8308b37607d5f6ef0d16346a5b24e75933f | [
"MIT"
] | permissive | sidsukana/QSpellWork | 2f67ed88267731eacdef693651b3740facc85d2e | d25a76935e506d347c862442f891dab6dab12380 | refs/heads/qsw-2.0 | 2022-07-11T05:05:55.445428 | 2022-06-27T11:50:17 | 2022-06-27T11:50:17 | 16,616,945 | 20 | 23 | MIT | 2022-06-27T11:50:28 | 2014-02-07T14:30:18 | C++ | UTF-8 | C++ | false | false | 1,274 | h | #ifndef RIBBON_EMITTER_H
#define RIBBON_EMITTER_H
#include <QObject>
#include <QOpenGLShaderProgram>
#include <QOpenGLBuffer>
#include <QOpenGLFunctions>
#include "m2structures.h"
#include "animatedvalue.h"
#include "mvp.h"
#include "particleemitter.h"
struct Ribbon
{
QVector3D position;
QVector3D up;
};
class RibbonEmitter : public QObject
{
Q_OBJECT
public:
RibbonEmitter(const M2RibbonEmitter &emitter, const quint32 *sequences, const QByteArray &data, QOpenGLFunctions* funcs);
void update(quint32 animation, quint32 time, QMatrix4x4 boneMatrix);
void render(QOpenGLShaderProgram *program, MVP viewProjection);
qint32 getBoneId() const;
qint32 getTextureId() const;
private:
void initialize();
qint32 m_bone;
QVector3D m_position;
QList<qint32> m_textures;
QList<qint32> m_blending;
AnimatedValue<QVector3D> m_color;
AnimatedValue<qint16> m_opacity;
AnimatedValue<float> m_above;
AnimatedValue<float> m_below;
float m_segments;
float m_length;
float m_angle;
QList<Ribbon> m_ribbons;
ParticleVertex *m_vertices;
QOpenGLBuffer *m_vertexBuffer;
bool m_initialized;
QOpenGLFunctions* m_funcs;
};
#endif
| [
"pgsilent@gmail.com"
] | pgsilent@gmail.com |
e1437c5ff3af4e2c0dcc1f622ee2889a620c0fcf | 33691f66e73fdfe7d90caebf51bc39b60ffd8a38 | /UserInterface/GeneratedFiles/Debug/moc_DrawController.cpp | e5e6633f7a39e8f296eecded6d18cd4a221e341b | [] | no_license | Frenor/CCCP | 9bc494dc5ed0bc049dc71a3735897ea33e663bbf | 91994c73af62aa6f3c1b7a812ee1ae6f8092a30a | refs/heads/master | 2020-05-07T09:23:06.667397 | 2014-11-24T16:30:43 | 2014-11-24T16:30:43 | 25,698,291 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,414 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'DrawController.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.3.2)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../DrawController.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'DrawController.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.3.2. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
struct qt_meta_stringdata_DrawController_t {
QByteArrayData data[13];
char stringdata[156];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_DrawController_t, stringdata) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_DrawController_t qt_meta_stringdata_DrawController = {
{
QT_MOC_LITERAL(0, 0, 14),
QT_MOC_LITERAL(1, 15, 15),
QT_MOC_LITERAL(2, 31, 0),
QT_MOC_LITERAL(3, 32, 7),
QT_MOC_LITERAL(4, 40, 5),
QT_MOC_LITERAL(5, 46, 8),
QT_MOC_LITERAL(6, 55, 10),
QT_MOC_LITERAL(7, 66, 9),
QT_MOC_LITERAL(8, 76, 9),
QT_MOC_LITERAL(9, 86, 11),
QT_MOC_LITERAL(10, 98, 12),
QT_MOC_LITERAL(11, 111, 25),
QT_MOC_LITERAL(12, 137, 18)
},
"DrawController\0setActiveEntity\0\0Entity*\0"
"reset\0setModel\0DrawModel*\0DrawModel\0"
"doneEvent\0cancelEvent\0actorClicked\0"
"vtkSmartPointer<vtkActor>\0actorDoubleClicked"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_DrawController[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
7, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: name, argc, parameters, tag, flags
1, 1, 49, 2, 0x0a /* Public */,
4, 0, 52, 2, 0x0a /* Public */,
5, 1, 53, 2, 0x0a /* Public */,
8, 0, 56, 2, 0x0a /* Public */,
9, 0, 57, 2, 0x0a /* Public */,
10, 1, 58, 2, 0x0a /* Public */,
12, 1, 61, 2, 0x0a /* Public */,
// slots: parameters
QMetaType::Void, 0x80000000 | 3, 2,
QMetaType::Void,
QMetaType::Void, 0x80000000 | 6, 7,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void, 0x80000000 | 11, 2,
QMetaType::Void, 0x80000000 | 11, 2,
0 // eod
};
void DrawController::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
DrawController *_t = static_cast<DrawController *>(_o);
switch (_id) {
case 0: _t->setActiveEntity((*reinterpret_cast< Entity*(*)>(_a[1]))); break;
case 1: _t->reset(); break;
case 2: _t->setModel((*reinterpret_cast< DrawModel*(*)>(_a[1]))); break;
case 3: _t->doneEvent(); break;
case 4: _t->cancelEvent(); break;
case 5: _t->actorClicked((*reinterpret_cast< vtkSmartPointer<vtkActor>(*)>(_a[1]))); break;
case 6: _t->actorDoubleClicked((*reinterpret_cast< vtkSmartPointer<vtkActor>(*)>(_a[1]))); break;
default: ;
}
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
switch (_id) {
default: *reinterpret_cast<int*>(_a[0]) = -1; break;
case 0:
switch (*reinterpret_cast<int*>(_a[1])) {
default: *reinterpret_cast<int*>(_a[0]) = -1; break;
case 0:
*reinterpret_cast<int*>(_a[0]) = qRegisterMetaType< Entity* >(); break;
}
break;
case 2:
switch (*reinterpret_cast<int*>(_a[1])) {
default: *reinterpret_cast<int*>(_a[0]) = -1; break;
case 0:
*reinterpret_cast<int*>(_a[0]) = qRegisterMetaType< DrawModel* >(); break;
}
break;
}
}
}
const QMetaObject DrawController::staticMetaObject = {
{ &GraphicController::staticMetaObject, qt_meta_stringdata_DrawController.data,
qt_meta_data_DrawController, qt_static_metacall, 0, 0}
};
const QMetaObject *DrawController::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *DrawController::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_DrawController.stringdata))
return static_cast<void*>(const_cast< DrawController*>(this));
return GraphicController::qt_metacast(_clname);
}
int DrawController::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = GraphicController::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 7)
qt_static_metacall(this, _c, _id, _a);
_id -= 7;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 7)
qt_static_metacall(this, _c, _id, _a);
_id -= 7;
}
return _id;
}
QT_END_MOC_NAMESPACE
| [
"fredrik@nordmoen.com"
] | fredrik@nordmoen.com |
9068580d40fd09204699ab35eb9f16d5d239729f | a8597563c1349d1ff2820cfc528d3d8d05b74bc7 | /Webkit-owb/generated_sources/WebCore/JSHTMLAppletElement.cpp | 387d2350b2bddbc88c5e2f3821e5686878eaa7f9 | [] | no_license | lentinic/EAWebKit | 68f8288b96d3b629f0466e94287ece37820a322d | 132ee635f9cd4cfce92ad4da823c83d54b95e993 | refs/heads/master | 2021-01-15T22:09:35.942573 | 2011-06-28T16:41:01 | 2011-06-28T16:41:01 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 10,094 | cpp | /*
This file is part of the WebKit open source project.
This file has been generated by generate-bindings.pl. DO NOT MODIFY!
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
/*
* This file was modified by Electronic Arts Inc Copyright © 2009
*/
#include "config.h"
#include "JSHTMLAppletElement.h"
#include <wtf/GetPtr.h>
#include "AtomicString.h"
#include "HTMLAppletElement.h"
#include "JSHTMLAppletElementCustom.h"
#include "KURL.h"
using namespace KJS;
namespace WebCore {
/* Hash table */
static const HashTableValue JSHTMLAppletElementTableValues[13] =
{
{ "align", (intptr_t)JSHTMLAppletElement::AlignAttrNum, DontDelete, 0 },
{ "alt", (intptr_t)JSHTMLAppletElement::AltAttrNum, DontDelete, 0 },
{ "archive", (intptr_t)JSHTMLAppletElement::ArchiveAttrNum, DontDelete, 0 },
{ "code", (intptr_t)JSHTMLAppletElement::CodeAttrNum, DontDelete, 0 },
{ "codeBase", (intptr_t)JSHTMLAppletElement::CodeBaseAttrNum, DontDelete, 0 },
{ "height", (intptr_t)JSHTMLAppletElement::HeightAttrNum, DontDelete, 0 },
{ "hspace", (intptr_t)JSHTMLAppletElement::HspaceAttrNum, DontDelete, 0 },
{ "name", (intptr_t)JSHTMLAppletElement::NameAttrNum, DontDelete, 0 },
{ "object", (intptr_t)JSHTMLAppletElement::ObjectAttrNum, DontDelete, 0 },
{ "vspace", (intptr_t)JSHTMLAppletElement::VspaceAttrNum, DontDelete, 0 },
{ "width", (intptr_t)JSHTMLAppletElement::WidthAttrNum, DontDelete, 0 },
{ "constructor", (intptr_t)JSHTMLAppletElement::ConstructorAttrNum, DontEnum, 0 },
{ 0, 0, 0, 0 }
};
static const HashTable JSHTMLAppletElementTable = { 127, JSHTMLAppletElementTableValues, 0 };
/* Hash table for constructor */
static const HashTableValue JSHTMLAppletElementConstructorTableValues[1] =
{
{ 0, 0, 0, 0 }
};
static const HashTable JSHTMLAppletElementConstructorTable = { 0, JSHTMLAppletElementConstructorTableValues, 0 };
class JSHTMLAppletElementConstructor : public DOMObject {
public:
JSHTMLAppletElementConstructor(ExecState* exec)
: DOMObject(exec->lexicalGlobalObject()->objectPrototype())
{
putDirect(exec->propertyNames().prototype, JSHTMLAppletElementPrototype::self(exec), None);
}
virtual bool getOwnPropertySlot(ExecState*, const Identifier&, PropertySlot&);
JSValue* getValueProperty(ExecState*, int token) const;
virtual const ClassInfo* classInfo() const { return &s_info; }
static const ClassInfo s_info;
virtual bool implementsHasInstance() const { return true; }
};
const ClassInfo JSHTMLAppletElementConstructor::s_info = { "HTMLAppletElementConstructor", 0, &JSHTMLAppletElementConstructorTable, 0 };
bool JSHTMLAppletElementConstructor::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot)
{
return getStaticValueSlot<JSHTMLAppletElementConstructor, DOMObject>(exec, &JSHTMLAppletElementConstructorTable, this, propertyName, slot);
}
JSValue* JSHTMLAppletElementConstructor::getValueProperty(ExecState* exec, int token) const
{
// The token is the numeric value of its associated constant
return jsNumber(exec, token);
}
/* Hash table for prototype */
static const HashTableValue JSHTMLAppletElementPrototypeTableValues[1] =
{
{ 0, 0, 0, 0 }
};
static const HashTable JSHTMLAppletElementPrototypeTable = { 0, JSHTMLAppletElementPrototypeTableValues, 0 };
const ClassInfo JSHTMLAppletElementPrototype::s_info = { "HTMLAppletElementPrototype", 0, &JSHTMLAppletElementPrototypeTable, 0 };
JSObject* JSHTMLAppletElementPrototype::self(ExecState* exec)
{
// Changed by Paul Pedriana (1/2009), as the static new was creating a memory leak. If this gets called a lot then we can consider making it a static pointer that's freed on shutdown.
const Identifier prototypeIdentifier(exec, "[[JSHTMLAppletElement.prototype]]");
return KJS::cacheGlobalObject<JSHTMLAppletElementPrototype>(exec, prototypeIdentifier);
}
const ClassInfo JSHTMLAppletElement::s_info = { "HTMLAppletElement", &JSHTMLElement::s_info, &JSHTMLAppletElementTable , 0 };
JSHTMLAppletElement::JSHTMLAppletElement(JSObject* prototype, HTMLAppletElement* impl)
: JSHTMLElement(prototype, impl)
{
}
bool JSHTMLAppletElement::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot)
{
if (canGetItemsForName(exec, static_cast<HTMLAppletElement*>(impl()), propertyName)) {
slot.setCustom(this, nameGetter);
return true;
}
if (customGetOwnPropertySlot(exec, propertyName, slot))
return true;
return getStaticValueSlot<JSHTMLAppletElement, Base>(exec, &JSHTMLAppletElementTable, this, propertyName, slot);
}
JSValue* JSHTMLAppletElement::getValueProperty(ExecState* exec, int token) const
{
switch (token) {
case AlignAttrNum: {
HTMLAppletElement* imp = static_cast<HTMLAppletElement*>(impl());
return jsString(exec, imp->align());
}
case AltAttrNum: {
HTMLAppletElement* imp = static_cast<HTMLAppletElement*>(impl());
return jsString(exec, imp->alt());
}
case ArchiveAttrNum: {
HTMLAppletElement* imp = static_cast<HTMLAppletElement*>(impl());
return jsString(exec, imp->archive());
}
case CodeAttrNum: {
HTMLAppletElement* imp = static_cast<HTMLAppletElement*>(impl());
return jsString(exec, imp->code());
}
case CodeBaseAttrNum: {
HTMLAppletElement* imp = static_cast<HTMLAppletElement*>(impl());
return jsString(exec, imp->codeBase());
}
case HeightAttrNum: {
HTMLAppletElement* imp = static_cast<HTMLAppletElement*>(impl());
return jsString(exec, imp->height());
}
case HspaceAttrNum: {
HTMLAppletElement* imp = static_cast<HTMLAppletElement*>(impl());
return jsString(exec, imp->hspace());
}
case NameAttrNum: {
HTMLAppletElement* imp = static_cast<HTMLAppletElement*>(impl());
return jsString(exec, imp->name());
}
case ObjectAttrNum: {
HTMLAppletElement* imp = static_cast<HTMLAppletElement*>(impl());
return jsString(exec, imp->object());
}
case VspaceAttrNum: {
HTMLAppletElement* imp = static_cast<HTMLAppletElement*>(impl());
return jsString(exec, imp->vspace());
}
case WidthAttrNum: {
HTMLAppletElement* imp = static_cast<HTMLAppletElement*>(impl());
return jsString(exec, imp->width());
}
case ConstructorAttrNum:
return getConstructor(exec);
}
return 0;
}
void JSHTMLAppletElement::put(ExecState* exec, const Identifier& propertyName, JSValue* value)
{
if (customPut(exec, propertyName, value))
return;
lookupPut<JSHTMLAppletElement, Base>(exec, propertyName, value, &JSHTMLAppletElementTable, this);
}
void JSHTMLAppletElement::putValueProperty(ExecState* exec, int token, JSValue* value)
{
switch (token) {
case AlignAttrNum: {
HTMLAppletElement* imp = static_cast<HTMLAppletElement*>(impl());
imp->setAlign(valueToStringWithNullCheck(exec, value));
break;
}
case AltAttrNum: {
HTMLAppletElement* imp = static_cast<HTMLAppletElement*>(impl());
imp->setAlt(valueToStringWithNullCheck(exec, value));
break;
}
case ArchiveAttrNum: {
HTMLAppletElement* imp = static_cast<HTMLAppletElement*>(impl());
imp->setArchive(valueToStringWithNullCheck(exec, value));
break;
}
case CodeAttrNum: {
HTMLAppletElement* imp = static_cast<HTMLAppletElement*>(impl());
imp->setCode(valueToStringWithNullCheck(exec, value));
break;
}
case CodeBaseAttrNum: {
HTMLAppletElement* imp = static_cast<HTMLAppletElement*>(impl());
imp->setCodeBase(valueToStringWithNullCheck(exec, value));
break;
}
case HeightAttrNum: {
HTMLAppletElement* imp = static_cast<HTMLAppletElement*>(impl());
imp->setHeight(valueToStringWithNullCheck(exec, value));
break;
}
case HspaceAttrNum: {
HTMLAppletElement* imp = static_cast<HTMLAppletElement*>(impl());
imp->setHspace(valueToStringWithNullCheck(exec, value));
break;
}
case NameAttrNum: {
HTMLAppletElement* imp = static_cast<HTMLAppletElement*>(impl());
imp->setName(valueToStringWithNullCheck(exec, value));
break;
}
case ObjectAttrNum: {
HTMLAppletElement* imp = static_cast<HTMLAppletElement*>(impl());
imp->setObject(valueToStringWithNullCheck(exec, value));
break;
}
case VspaceAttrNum: {
HTMLAppletElement* imp = static_cast<HTMLAppletElement*>(impl());
imp->setVspace(valueToStringWithNullCheck(exec, value));
break;
}
case WidthAttrNum: {
HTMLAppletElement* imp = static_cast<HTMLAppletElement*>(impl());
imp->setWidth(valueToStringWithNullCheck(exec, value));
break;
}
}
}
JSValue* JSHTMLAppletElement::getConstructor(ExecState* exec)
{
// Changed by Paul Pedriana (1/2009), as the static new was creating a memory leak. If this gets called a lot then we can consider making it a static pointer that's freed on shutdown.
const Identifier constructorIdentifier(exec, "[[HTMLAppletElement.constructor]]");
return KJS::cacheGlobalObject<JSHTMLAppletElementConstructor>(exec, constructorIdentifier);
}
}
| [
"nanashi4129@gmail.com"
] | nanashi4129@gmail.com |
e5f87b560a41ce450969c05f4695a3963c212881 | 103eca6c82eec3bd5fa3a9d28fa65446564e4bd4 | /abcdsat_p21/parallel/LocalThread.h | dc9b69dbf17865eaa8261f13b9056b78314b8a48 | [] | no_license | jingchaochen/abcdsat_p21 | c0df8973e8fa9232da5dab12b8a1c2f0518a505c | cb5e67aaa2669aa3c111596656e4168d79219268 | refs/heads/main | 2023-04-10T11:16:07.528238 | 2021-04-20T08:20:56 | 2021-04-20T08:20:56 | 359,734,474 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,286 | h |
#ifndef LocalThread_H
#define LocalThread_H
#include "core/SolverTypes.h"
#include "core/Solver.h"
#include "simp/SimpSolver.h"
#include "parallel/SharedInfo.h"
namespace abcdSAT {
class LocalThread : public SimpSolver {
friend class MainThread;
friend class SharedInfo;
protected :
int thn; // internal thread number(due to incomplete types)
SharedInfo *sharedinfo;
pthread_cond_t *pcfinished; // condition variable that says that a thread as finished
pthread_cond_t *pClonefinished;
public:
LocalThread* copysolver;
LocalThread(){}
LocalThread(const LocalThread &s);
~LocalThread();
virtual Clone* clone() const { return new LocalThread(*this); }
int threadNumber () const {return thn;}
void setThreadNumber (int i) {thn = i;}
void reportProgress();
int nextUnit;
int nextBin;
virtual bool panicModeIsEnabled();
virtual bool OtherSolverFinished();
virtual void terminate_signal (lbool status);
virtual void cloneSolver ();
virtual void part_UNSAT_signal ();
virtual bool parallelExportUnitClause (Lit unitLit);
virtual void parallelExportBinClause(Lit p, Lit q);
virtual Lit getUnit();
virtual void getbin(Lit & p, Lit & q);
};
}
#endif // LocalThread_H
| [
"noreply@github.com"
] | jingchaochen.noreply@github.com |
0c7903d97b801e391b007fe046db1de07164bd5a | ff5b427352226fc308b8f10ebce3f563c51cf9bd | /Algorithms/Strings/Sherlock and Anagrams.cpp | ccd351ab48f989cd523280c2b3f29964ec903602 | [] | no_license | davidffa/HackerRank-Cpp | 622520cab05764abde301ce44e2a8730aa28e83c | 9bcbbcea8a66811d182915eedfb6965d7907ea01 | refs/heads/master | 2022-11-05T11:00:42.827861 | 2020-06-21T20:45:42 | 2020-06-21T20:45:42 | 272,500,629 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 526 | cpp | #include <bits/stdc++.h>
using namespace std;
void solve() {
string s;
cin >> s;
int ans=0;
map<vector<int>, int> mp;
for (int i=1; i<=s.length(); i++) {
for (int j=0; j<s.length()&&j+i<=s.length(); j++) {
string s1= s.substr(j, i);
vector<int> v(26, 0);
for (char c : s1) ++v[c-'a'];
++mp[v];
}
}
for (auto p : mp) {
ans += p.second*(p.second-1)/2;
}
cout << ans << "\n";
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int t;
cin >> t;
while (t--) {
solve();
}
return 0;
}
| [
"davidfilipeamorim@gmail.com"
] | davidfilipeamorim@gmail.com |
20c31a6cded7b078a69fc90cb7b5c4098bc00cfb | 0cdbd51c06a8385f928bcaea7ae58da5d5d635fa | /W07 - Exam2 Review/Operator-overloading/Rational.cpp | 8548b9c671ed9cd87b923032f7f3800cf421f82f | [] | no_license | yilin2548/UIndy-CSCI-156-50 | dc6f155d410570833d39e27891a38c3a84f81568 | 852065df15ab3d0352c1c481dc018636e9cef484 | refs/heads/master | 2021-05-05T10:17:41.195367 | 2018-04-30T19:53:49 | 2018-04-30T19:53:49 | 117,909,544 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,155 | cpp | // Name: Yilin Liu-Leitke
// Date: 2/15/18
// Desc: Implementation of the Rational class.
// iostream is not neccassary because cout is not used.
#include <sstream>
// Be sure to include the .h file!
#include "Rational.h"
using namespace std;
// Default constructor
Rational::Rational(){
numerator = 1;
denominator = 1;
}
// Overloaded constructor
Rational::Rational(const int &top, const int &bottom){
numerator = top;
denominator = bottom;
}
// Setters
void Rational::setNumerator(const int &top){
numerator = top;
}
void Rational::setDenominator(const int &bottom){
denominator = bottom;
}
// Getters
int Rational::getNumerator() const{
return numerator;
}
int Rational::getDenominator() const{
return denominator;
}
// Print
string Rational::print() const{
stringstream s;
s << numerator << "/" << denominator;
return s.str();
}
// multBy(int)
void Rational::multBy(const int &n){
numerator = numerator * n;
}
// addBy(int)
void Rational::addBy(const int &n){
numerator += denominator * n;
}
// mult(Rational)
Rational Rational::mult(const Rational &other) const{
// Rational ret;
// ret.numerator = numerator * other.numerator;
// ret.denominator = denominator * other.denominator;
// return ret;
// Or you can do the following one line:
return Rational(numerator * other.numerator, denominator * other.denominator);
}
// add(Rational)
Rational Rational::add(const Rational &other) const{
Rational ret;
ret.numerator = numerator * other.denominator + other.numerator * denominator;
ret.denominator = denominator * other.denominator;
return ret;
}
// isEqualTo(Rational)
bool Rational::isEqualTo(const Rational &other) const{
int ltop = numerator * other.denominator;
int rtop = other.numerator * denominator;
return ltop == rtop;
}
// isGreaterThan(Rational)
bool Rational::isGreaterThan(const Rational &other) const{
int ltop = numerator * other.denominator;
int rtop = other.numerator * denominator;
return ltop > rtop;
}
// isGreaterOrEqualTo
bool Rational::isGreaterOrEqualTo(const Rational &other) const{
return isEqualTo(other) || isGreaterThan(other);
}
// operator overloading
Rational Rational::operator+(const Rational &rhs) const{
return add(rhs);
}
Rational Rational::operator-(const Rational &rhs) const{
Rational ret;
ret.numerator = numerator * rhs.denominator - rhs.numerator * denominator;
ret.denominator = denominator * rhs.denominator;
return ret;
// return add(negate(rhs));
}
Rational Rational::operator*(const Rational &rhs) const{
return mult(rhs);
}
Rational Rational::operator/(const Rational &rhs) const{
return mult(Rational(rhs.denominator, rhs.numerator));
// return mult(invert(rhs));
}
bool Rational::operator<(const Rational &rhs) const{
return !isGreaterOrEqualTo(rhs);
}
bool Rational::operator>(const Rational &rhs) const{
return isGreaterThan(rhs);
}
bool Rational::operator==(const Rational &rhs) const{
return isEqualTo(rhs);
}
ostream& operator<<(ostream &o, const Rational &r){
o << r.print();
return o;
} | [
"yilin2548@gmail.com"
] | yilin2548@gmail.com |
e2af09d4ce19a1e26cde2d0c86922ceb643dacf5 | ac68ee4921c4a3fe613ecf5207b4e09bb3e9aef7 | /day-04/day4.cpp | cb40809f88b1bbcce2b64781cfb1e7cc4a4c4332 | [
"MIT"
] | permissive | WhoSoup/aoc2019 | 33f000c483c61f684fec616047e6a9026e6dd013 | 90f68bb555e93d41a9ffc8e84bcda4548d41d26c | refs/heads/master | 2020-09-22T09:21:36.452539 | 2019-12-22T11:55:26 | 2019-12-22T11:55:26 | 225,135,836 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 907 | cpp | #include <iostream>
#include <vector>
std::pair<bool,bool> valid(int pw) {
bool repeat = false;
bool repeat2 = false;
int run = 0;
int prev = 10; // going reverse, so higher than 9
while (pw > 0) {
int r = pw % 10;
if (prev < r) {
return std::pair<bool,bool>{false,false};
}
if (prev == r) {
repeat = true;
run++;
} else {
if (run == 1) {
repeat2 = true;
}
run = 0;
}
pw /= 10;
prev = r;
}
return std::pair<bool,bool>{repeat, repeat2 || run == 1};
}
int main() {
int start = 353096, end = 843212;
int v = 0, v2 = 0;
for (int i = start; i <= end; i++) {
auto p = valid(i);
if (p.first) v++;
if (p.second) v2++;
}
std::cout << v << std::endl;
std::cout << v2 << std::endl;
} | [
"who.soup@gmail.com"
] | who.soup@gmail.com |
cad0289820035fbfeb4c4031f41bae3f9e5f0ff3 | 5168d97461d4335784082f88ba2f90d3dee71769 | /Coding Questions/2-D Array/Class Questions/AvgFilter.cpp | 95287f4ce07dda8fdd874af57d92d84e6edab083 | [] | no_license | parasjain929/Karma | eb4021397f085cbc24a08b2651d2d20103047484 | 7e52e7f5698f8a6e15684800ee336ae24dae8c36 | refs/heads/master | 2020-06-01T23:27:10.785809 | 2019-07-05T08:57:04 | 2019-07-05T08:57:04 | 190,964,636 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 634 | cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
int i,j,temp,n,x,y;
cin>>n;
int a[n][n];
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
cin>>a[i][j];
}
for(i=1;i<n-1;i++)
{
temp=0;
for(j=1;j<n-1;j++)
{
for(x=-1;x<=1;x++)
{
for(y=-1;y<=1;y++)
{
temp+=a[i+x][j+y];
}
}
a[i][j]=temp/9;
}
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{cout<<a[i][n];
}
cout<<endl;}
}
| [
"parasjain929@gmail.com"
] | parasjain929@gmail.com |
a8750460986afff6527e7deebba25ee6f0894d23 | c27b97c85778eaf84a5d1b36c5f52687bbeb705a | /C++/1004.cpp | a4ff41b615013c6aee21277b58fa4aa40951ca20 | [] | no_license | ongss/coding | c7d158caba72a5f795aca87821543d5d1a0afd14 | 679adbac41b03b88f47c568967e7dc99eaf22b67 | refs/heads/master | 2021-04-29T14:01:32.823293 | 2018-02-16T15:12:21 | 2018-02-16T15:12:21 | 121,764,614 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,432 | cpp | #include<stdio.h>
int main()
{
int a,b,cnt=0,d,e,i,j,k=0,l,clas,n=0,stn;
scanf("%d %d",&a,&b);
int cls[1000]={0},std[1000]={0},line[1000]={0},nwline[1000]={0},clsline[1000];
for(i=0;i<b;i++)
{
scanf("%d %d",&cls[i],&std[i]);
}
for(i=0;;i++)
{
scanf("%c",&b);
if(b=='E')
{
scanf("%d",&line[k]);
for(j=0;j<b;j++)
{
if(line[k]==std[j])
{
clsline[k]=cls[j];
k++;
}
if(clsline[j]!=clsline[j+1]&&clsline[j+1]!=0)
{
clas=clsline[j+1];
stn=line[j+1];
for(e=k-1;e>=0;e--)
{
if(clas==clsline[e])
{
for(d=k-e-1;d>0;d--)
{
line[d+1]=line[d];
clsline[d+1]=clsline[d];
}
clsline[e]=clas;
line[e]=stn;
}
}
}
}
}
if(b=='D') cnt++;
if(b=='X') break;
}
/*for(i=0;i<k;i++)
{
for(j=0;j<k;j++)
{
if(clsline[j]!=0)
{
clas=clsline[j];
break;
}
}
for(j=0;j<k;j++)
{
if(clas==clsline[j])
{
nwline[n]=line[j];
clsline[j]=0;
n++;
}
}
}*/
for(i=0;i<k;i++)
{
printf("%d ",line[i]);
//printf("%d" ,clsline[i]);
}
scanf(" ");
}
| [
"ong54321@hotmail.com"
] | ong54321@hotmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.