blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
264
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
85
| license_type
stringclasses 2
values | repo_name
stringlengths 5
140
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 905
values | visit_date
timestamp[us]date 2015-08-09 11:21:18
2023-09-06 10:45:07
| revision_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-17 19:19:19
| committer_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-06 06:22:19
| github_id
int64 3.89k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us]date 2012-06-07 00:51:45
2023-09-14 21:58:39
⌀ | gha_created_at
timestamp[us]date 2008-03-27 23:40:48
2023-08-21 23:17:38
⌀ | gha_language
stringclasses 141
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
10.4M
| extension
stringclasses 115
values | content
stringlengths 3
10.4M
| authors
sequencelengths 1
1
| author_id
stringlengths 0
158
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
27f02a4be29763da3b57ccdae801db8ae07498a9 | f7897a7e0aa643ecb9ee082bfeee2aa6a910236a | /443c_fc.cpp | c97f3040aa40ca47bec2aed0873ba6c856e4d7f9 | [] | no_license | ranasl62/UVA_SOLVE | c245100b7de723c8651f1ea8dae875328da17cf9 | 8b12c1402e17d7004cc337ac3a6934d141813a7c | refs/heads/master | 2020-05-21T07:44:02.826934 | 2018-08-16T16:57:23 | 2018-08-16T16:57:23 | 69,553,543 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 923 | cpp | #include<bits/stdc++.h>
using namespace std;
#define mx INT_MAX
int main()
{
int a,b;
long long n;
string c;
pair<string,int>l;
vector< pair<string,int> >x;
cin>>n;
cin>>c>>b;
l=make_pair(c,b);
a=b;
x.push_back(l);
for( int i=1; i<n; i++)
{
cin>>c>>b;
if(c[0]=='|' && (a|b)!=a)
{
l=make_pair(c,b);
x.push_back(l);
a=a|b;
}
else if(c[0]=='^' && (a^b)!=a)
{
l=make_pair(c,b);
x.push_back(l);
a=a^b;
}
else if (c[0]=='&' && (a&b)!=a)
{
l=make_pair(c,b);
x.push_back(l);
a=a&b;
}
if(a==0)
{
x.clear();
}
}
cout<<x.size()<<endl;
for(int i=0; i<x.size(); i++)
{
cout<<x[i].first<< " "<<x[i].second<<endl;
}
return 0;
}
| [
"[email protected]"
] | |
ca598a72ed75b20995269e978805bff33c79babb | 9bc7ef3e15c9c61d66b72a02f102cfd9f726cb15 | /main.cpp | e691df1443c77df0a02737e3d6d40af932763065 | [] | no_license | jhlandman/programming_principals_cpp | c3e9bebaa56fa482df0a52879227afa89983dfcc | 68cd4056464493dc99b716d39458d070b07dbc9e | refs/heads/master | 2022-11-12T23:35:20.381059 | 2020-06-30T08:38:53 | 2020-06-30T08:38:53 | 275,918,941 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 547 | cpp | /***********************************************
** Author: Jayson Landman
** Description: cpp exercises programming
principals and practice
***********************************************/
#include <iostream>
class Bad_area{};
int area(int length, int width) {
if (length <=0 || width <= 0) throw Bad_area{};
return length * width;
}
int main() try {
int x = -1;
int y = 2;
int z = 4;
//int area1 = area(x, y);
int area2 = area(y, z);
} catch (Bad_area) {
std::cout << "Oops! bad arguments to area()\n";
} | [
"[email protected]"
] | |
787c34e9d233bc7ed309c71c39ddee5a05c416c0 | 43a2fbc77f5cea2487c05c7679a30e15db9a3a50 | /Cpp/Internal (Offsets Only)/SDK/wld_bush_cluster_04_d_parameters.h | 6f65c9a388af58ca8d0f6687db448f9879e188a9 | [] | no_license | zH4x/SoT-Insider-SDK | 57e2e05ede34ca1fd90fc5904cf7a79f0259085c | 6bff738a1b701c34656546e333b7e59c98c63ad7 | refs/heads/main | 2023-06-09T23:10:32.929216 | 2021-07-07T01:34:27 | 2021-07-07T01:34:27 | 383,638,719 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 549 | h | #pragma once
// Name: SoT-Insider, Version: 1.102.2382.0
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Parameters
//---------------------------------------------------------------------------
// Function wld_bush_cluster_04_d.wld_bush_cluster_04_d_C.UserConstructionScript
struct Awld_bush_cluster_04_d_C_UserConstructionScript_Params
{
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"[email protected]"
] | |
18b56354e186eb756a31204921270d0050af71ed | f74f835ec8c156cc72d288500b1a5a16b9c8c62b | /Controller/src/LSST/M1M3/SS/Threads/IThread.h | 99ff878fc367e42a6d91adcba923e6a80abb6c46 | [] | no_license | AmmarNoman/ts_m1m3support | 44176bfdfad790a46aa722fe27c5e48a6243d5d6 | 1bb88ae2d754ce19c0c4efc7a20243c06fba9ac0 | refs/heads/master | 2021-05-22T18:30:53.085262 | 2018-07-30T23:00:30 | 2018-07-30T23:00:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 496 | h | /*
* IThread.h
*
* Created on: Sep 28, 2017
* Author: ccontaxis
*/
#ifndef ITHREAD_H_
#define ITHREAD_H_
namespace LSST {
namespace M1M3 {
namespace SS {
/*!
* Interface used to represent a task that needs to run
* on its own thread.
*/
class IThread {
public:
virtual ~IThread();
/*!
* Run the task.
*/
virtual void run();
/*!
* Stop the task.
*/
virtual void stop();
};
} /* namespace SS */
} /* namespace M1M3 */
} /* namespace LSST */
#endif /* ITHREAD_H_ */
| [
"[email protected]"
] | |
f8ff73414f4f3f9a666d92fc56cb7423ecbe1230 | 7bea4a44a587ea6d83ead8fdae18c58bf77d4f90 | /tests/super_simple_test.cpp | 094d87a08e123d1e1a31c49100411f59a2f8c019 | [
"MIT"
] | permissive | fraguela/depspawn | 1f461b7440f199ab9e83b4b7eb47c966b8df9043 | 434057dd1cdc4ac0ee4fb0d7269df601e4f865a5 | refs/heads/master | 2023-02-24T19:48:32.866889 | 2023-02-19T18:36:57 | 2023-02-19T18:36:57 | 49,231,704 | 10 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,168 | cpp | /*
DepSpawn: Data Dependent Spawn library
Copyright (C) 2012-2023 Carlos H. Gonzalez, Basilio B. Fraguela. Universidade da Coruna
Distributed under the MIT License. (See accompanying file LICENSE)
*/
///
/// \author Carlos H. Gonzalez <[email protected]>
/// \author Basilio B. Fraguela <[email protected]>
///
#include <iostream>
#include <chrono>
#include "depspawn/depspawn.h"
#include "common_io.cpp" // This is only for serializing parallel prints
using namespace depspawn;
std::chrono::time_point<std::chrono::high_resolution_clock> t0;
void f(int &i) {
LOG("f begin: " << std::chrono::duration<double>(std::chrono::high_resolution_clock::now() - t0).count());
i = 10;
LOG("f finish: " << std::chrono::duration<double>(std::chrono::high_resolution_clock::now() - t0).count() << " with i=" << i);
}
int main()
{ int i = 0;
t0 = std::chrono::high_resolution_clock::now();
spawn(f, i);
LOG("post-spawn");
wait_for_all();
std::cout << "Final i=" << i << std::endl;
const bool test_ok = (i == 10);
std::cout << "TEST " << (test_ok ? "SUCCESSFUL" : "UNSUCCESSFUL") << std::endl;
return !test_ok;
}
| [
"[email protected]"
] | |
be7cc38ab046929303bba38caa30adb35d46d388 | 89aada6240c98ff52b8ae3d85a645dc127e43492 | /code/include/FileManager/ProgressWidget.h | 8951f65431bd7d38fc08271daa77ac820fcc493b | [
"Apache-2.0"
] | permissive | TheodorusWare/Archivarius | 3d68deed166eeca1fa34c859d2799c29a206588e | c7bc89a2faaadc37bb65c24fc2e978c915edd582 | refs/heads/master | 2021-01-03T16:12:58.460949 | 2020-05-07T20:47:37 | 2020-05-07T20:47:37 | 240,146,060 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,772 | h | /*
Copyright (C) 2018-2020 Theodorus Software
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef _TAH_GuiProgressWidget_h_
#define _TAH_GuiProgressWidget_h_
#include <Common/Config.h>
#include <Common/Vector2i.h>
#include <Common/Timer.h>
#include <Widget/Window.h>
#include <Widget/Label.h>
#include <Widget/Progressbar.h>
namespace tas
{
class ProgressWidget
{
public:
/** Interface */
Window * mWindow;
Label * mLabels[8];
Progressbar * mProgressbar;
Timer mTimer;
Vector2i mWindowPos;
Vector2i mWindowSize;
Array<half> mCommands; /// commands
String mFileName;
String mBuffer; /// string buffer
bool mReturn; /// dialog return value, 1 ok, 0 cancel
bool mClose;
byte mType; /// encode 0, decode 1, test 2
static ProgressWidget* mPtr;
public:
ProgressWidget();
~ProgressWidget();
/** Return nil after pressed cancel
Type encode 0, decode 1 */
bool create(byte type);
bool createItems();
bool initialise();
bool operationCancel();
bool closeWindow();
int callback(Widget* widget, uint message, uint_t param);
void idle();
void commands();
void keyboard();
void onButtons(uint id);
void setCommand(half cmd);
/** Archive callback. */
int eventCallback(wint* data);
/** Singleton. */
static ProgressWidget* ptr();
};
}
#endif | [
"[email protected]"
] | |
a44dd4abdd232390a4ee9b4a45695b6d31d5d977 | 60defd73359a391d70f83e599ffb7531b6af70ba | /Shizuku.Flow/Command/Parameter/ModelSpacePointParameter.h | af17bfb99cb97fc6cff74d0f3155c56516d1970d | [
"MIT"
] | permissive | blackoffee/Shizuku | 88b5473faf64b815f5d4d462a68419a4079eb117 | dde4c4f437ca271181d59a78da2815dee01800eb | refs/heads/master | 2022-10-01T17:04:46.845471 | 2020-06-08T13:28:30 | 2020-06-08T13:28:30 | 74,714,522 | 21 | 4 | MIT | 2019-02-06T03:56:16 | 2016-11-25T01:04:35 | C++ | UTF-8 | C++ | false | false | 475 | h | #pragma once
#include "Shizuku.Core/Types/Point.h"
#ifdef SHIZUKU_FLOW_EXPORTS
#define FLOW_API __declspec(dllexport)
#else
#define FLOW_API __declspec(dllimport)
#endif
namespace Shizuku{ namespace Flow{ namespace Command{
struct FLOW_API ModelSpacePointParameter
{
Shizuku::Core::Types::Point<float> Position;
ModelSpacePointParameter();
ModelSpacePointParameter(const Shizuku::Core::Types::Point<float>& p_pos);
};
} } }
| [
"[email protected]"
] | |
b2c9a63a37481975b859c923d9899c90510da63c | a86860b29300a89e731085d0ee85202b6aadffe3 | /cclient/src/geom.h | 64b3e18158a22e6fef3fb383e72f9741238c1c0f | [] | no_license | davdar/project-apricot | 0f71cec930af1e220ab23dcc0800fa25d7ebfd1f | 641812c649da63a639d335578d6613f386d1f59a | refs/heads/master | 2016-09-05T10:10:09.052972 | 2013-03-16T12:58:50 | 2013-03-16T12:58:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 303 | h | #ifndef _GEOM_H
#define _GEOM_H
#include "vector.h"
namespace geom {
inline bool intersectPointRect(const Vector2 &point, const Vector2 &rectP1, const Vector2 &rectP2){
return point[0] >= rectP1[0] &&
point[0] < rectP2[0] &&
point[1] < rectP1[1] &&
point[1] < rectP2[1];
}
}
#endif | [
"[email protected]"
] | |
c6b9860f966252060ba284c075306bb190caa8f0 | a72a1357a977739ed487d5369318e76c4c38d845 | /4_21/4_21/test.cpp | 943ed65bd3cf0dafd1fbed811059b0851672798a | [] | no_license | Asupi/C_plusplus | eb7f1cb54e4d3337d283dd1b76ce92bf56f8589a | 03b414bcae58cc1a4d94db2c70e3092b35d51385 | refs/heads/master | 2022-01-18T07:21:58.031202 | 2019-07-21T10:00:28 | 2019-07-21T10:00:28 | 173,754,377 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 931 | cpp | #define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
//class Car
//{
//public:
// virtual void Drive() = 0;
//};
//class Benz :public Car
//{
//public:
// virtual void Drive()
// {
// cout << "Benz-舒适" << endl;
// }
//};
//class BMW :public Car
//{
//public:
// virtual void Drive()
// {
// cout << "BMW-操控" << endl;
// }
//};
//void Test()
//{
// Car* pBenz = new Benz;
// pBenz->Drive();
//
// Car* pBMW = new BMW;
// pBMW->Drive();
//}
//final修饰基类的虚函数不能被派生类重写
class Car
{
public:
virtual void Drive()final{}
};
class Benz :public Car
{
public:
virtual void Drive()
{
cout << "Benz-舒适" << endl;
}
};
class Car
{
public:
virtual void Drive(){}
};
//override 修饰派生类虚函数强制完成重写,如果没有重写就会编译报错
class Benz :public Car
{
public:
virtual void Drive()override
{
cout << "Benz-舒适" << endl;
}
}; | [
"[email protected]"
] | |
925abb48966e013e7af82d734dd963d236507fd5 | fb1ae6bf81d7d560ae029ac6353edfec0f1b524a | /GenData/src/ITokenizer.h | 4a886669bd05c981c0c1b687e5f9fa74279d7d77 | [] | no_license | jerry2yu/geo | cf48e9bd75b77380689adb60896cc990623158a0 | a079a3253989faf6d2b98f014deb7e101bbf1e81 | refs/heads/master | 2021-06-01T10:34:29.617884 | 2019-10-10T00:34:11 | 2019-10-10T00:34:11 | 4,357,610 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 587 | h | #ifndef ITOKENIZER_H_
#define ITOKENIZER_H_
#include "IToken.h"
#include "vector.h"
/**
* Interface of tokenizers
* April 15, 2006. Zheyuan Yu
*/
class ITokenizer
{
public:
ITokenizer();
virtual ~ITokenizer();
/**
* Parses a text file into tokens, and save them into vector of pointers of tokens
* @param fileName - name of the text file to be parsed
* @param tokens - pointer to the vector of parsed token pointers
* @return true if parsing succeeded, otherwise false
*/
virtual bool parse( const char * fileName, vector<IToken*> * tokens ) = 0;
};
#endif
| [
"[email protected]"
] | |
fd48b83a931e20f31c35454515e6b41c892fc707 | fc20269ab21f0152a7221bdfe94b19ed9f7d9db7 | /cs_162/assignments/hw4/code2/empty.hpp | 0573b58e7df0a88a1a51d11d9f81af3014c44909 | [] | no_license | john-waczak/homeworkRepo | f92ae6f088ac0e568cd5f0104f132900131305cb | bb95598159501ccee6d6c0677595f8091e4b49ed | refs/heads/master | 2021-01-12T07:23:45.275138 | 2019-06-20T13:56:14 | 2019-06-20T13:56:14 | 76,935,269 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 164 | hpp | #ifndef EMPTY_H
#define EMPTY_H
#include "event.hpp"
class Empty : public Event{
public:
Empty();
~Empty();
void percept();
void encounter();
};
#endif
| [
"[email protected]"
] | |
0ac6d06f9521e60981948e2267bcb5840c20769c | 0bbe6b0e6cb38e29fbf4f56c1a9a1ac8ccaab610 | /rushhour/rushhour_results_result.cpp | 53373fdbc472651501b043661bbe6d7747cfe139 | [
"Apache-2.0"
] | permissive | nwbruce/rushhour | 06547232c8ef3df3efedd5f6eeac83c00bf606f4 | d1d378f1c68a1fea3cb096c67301d7d882d79fcf | refs/heads/master | 2021-03-31T01:53:31.805240 | 2018-04-07T19:05:06 | 2018-04-07T19:05:06 | 124,663,476 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 644 | cpp | #include <rushhour_results_result.h>
namespace rushhour {
namespace results {
Result::Result(const std::chrono::steady_clock::time_point& start,
const std::chrono::steady_clock::time_point& end, bool succeeded)
: start_(start), end_(end), succeeded_(succeeded) {}
std::chrono::nanoseconds Result::elapsed() const { return end_ - start_; }
bool Result::succeeded() const { return succeeded_; }
const std::chrono::steady_clock::time_point& Result::started() const {
return start_;
}
const std::chrono::steady_clock::time_point& Result::ended() const {
return end_;
}
} // namespace results
} // namespace rushhour
| [
"[email protected]"
] | |
91696816f9d20a65c74bf9e27805b51ef63e45c7 | 23e4d01a65ad6620c80f36d92c228aece4ceedeb | /Classes/SettingLayer.cpp | dd1346ef4ab7216824764ef7dcc518ed4959cf9c | [
"MIT"
] | permissive | AndyZhou3087/hllm-v2 | 697e9e04ccd30e6499522a4eb82c2579ccbc4842 | d7c32031b5b6723a3919f87d63e0064251bffdd2 | refs/heads/master | 2021-01-22T10:46:45.946598 | 2017-02-16T01:35:24 | 2017-02-16T01:35:24 | 82,035,544 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 8,695 | cpp | #include "SettingLayer.h"
#include "SoundManager.h"
#include "GlobalData.h"
#include "HintBox.h"
#include "CommonLayer.h"
#include "LoadingScene.h"
#include "WaitingProgress.h"
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
#include <jni.h>
#include "platform/android/jni/JniHelper.h"
#endif
int SettingLayer::setChangelogin = LOGIN_NONE;
SettingLayer::SettingLayer()
{
setChangelogin = LOGIN_NONE;
}
SettingLayer::~SettingLayer()
{
setChangelogin = LOGIN_NONE;
}
bool SettingLayer::init()
{
if (!Layer::init())
{
return false;
}
LayerColor* color = LayerColor::create(Color4B(11, 32, 22, 192));
this->addChild(color);
Node * layer = CSLoader::createNode("settingLayer.csb");
addChild(layer);
_musicBtn = (cocos2d::ui::Button*)layer->getChildByName("settingmusicbtn");
_musicBtn->addTouchEventListener(CC_CALLBACK_2(SettingLayer::musicOption, this));
_musicoff = (cocos2d::ui::Widget*)layer->getChildByName("settingmusicoff");
bool musicon = UserDefault::getInstance()->getBoolForKey("ismusicon", true);
_musicoff->setVisible(!musicon);
_musicBtn->setBright(musicon);
_soundBtn = (cocos2d::ui::Button*)layer->getChildByName("settingsoundbtn");
_soundBtn->addTouchEventListener(CC_CALLBACK_2(SettingLayer::soundOption, this));
_soundoff = (cocos2d::ui::Widget*)layer->getChildByName("settingsoundoff");
bool soundon = UserDefault::getInstance()->getBoolForKey("issoundon", true);
_soundoff->setVisible(!soundon);
_soundBtn->setBright(soundon);
cocos2d::ui::EditBox* editName = cocos2d::ui::EditBox::create(Size(200, 32), cocos2d::ui::Scale9Sprite::createWithSpriteFrameName("blank.png"));
editName->setAnchorPoint(Vec2(0, 0.5));
editName->setPosition(Point(183, 635));
editName->setFontColor(Color3B::WHITE);
editName->setPlaceHolder("请输入昵称:(回车键确认输入,返回关闭)");
editName->setPlaceholderFontColor(Color3B::WHITE);
editName->setMaxLength(14);
editName->setTag(0);
editName->setText(GlobalData::getMyName().c_str());
//editName->setReturnType(EditBox::KeyboardReturnType::DONE);
editName->setDelegate(this);
layer->addChild(editName);
cocos2d::ui::Widget* motifyBtn = (cocos2d::ui::Widget*)layer->getChildByName("settingmotifybtn");
motifyBtn->addTouchEventListener(CC_CALLBACK_2(SettingLayer::motifyName, this));
cocos2d::ui::Text* myid = (cocos2d::ui::Text*)layer->getChildByName("idtext");
if (GlobalData::getMyID().compare(0, 2, "loc", 0, 2) == 0)
myid->setString(CommonFuncs::gbk2utf("请检查网络"));
else
myid->setString("ID:" + GlobalData::getMyID());
cocos2d::ui::Widget* closeBtn = (cocos2d::ui::Widget*)layer->getChildByName("close");
closeBtn->addTouchEventListener(CC_CALLBACK_2(SettingLayer::close, this));
cocos2d::ui::Widget* qqloginbtn = (cocos2d::ui::Widget*)layer->getChildByName("loginqqbtn");
qqloginbtn->setTag(LOGIN_QQ);
qqloginbtn->addTouchEventListener(CC_CALLBACK_2(SettingLayer::login, this));
cocos2d::ui::Widget* wxloginbtn = (cocos2d::ui::Widget*)layer->getChildByName("loginwxbtn");
wxloginbtn->setTag(LOGIN_WX);
wxloginbtn->addTouchEventListener(CC_CALLBACK_2(SettingLayer::login, this));
#ifndef THIRDLOGIN
qqloginbtn->setVisible(false);
wxloginbtn->setVisible(false);
_musicBtn->setPosition(qqloginbtn->getPosition());
_musicoff->setPosition(_musicBtn->getPosition());
_soundBtn->setPosition(wxloginbtn->getPosition());
_soundoff->setPosition(_soundBtn->getPosition());
#endif
auto listener = EventListenerTouchOneByOne::create();
listener->onTouchBegan = [=](Touch *touch, Event *event)
{
return true;
};
listener->setSwallowTouches(true);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
layer->setAnchorPoint(Vec2(0.5f, 0.5f));
layer->setPosition(Vec2(270, 480));
layer->setScale(0.1f);
layer->runAction(Speed::create(EaseSineIn::create(ScaleTo::create(0.5f, 1)), 2));
_myhead = (cocos2d::ui::ImageView*)layer->getChildByName("head");
cocos2d::ui::Widget* settingheadbox = (cocos2d::ui::Widget*)layer->getChildByName("settingheadbox");
int logintype = GlobalData::getLoginType();
if (logintype > 0)
{
std::string headimgname = "qhead00.png";
if (logintype == 2)
headimgname = "wxhead00.png";
string path = FileUtils::getInstance()->getWritablePath() + headimgname;
bool isHasfile = FileUtils::getInstance()->isFileExist(path);
if (isHasfile)
{
_myhead->loadTexture(path, cocos2d::ui::TextureResType::LOCAL);
_myhead->setContentSize(Size(78,78));
_myhead->setPosition(Vec2(settingheadbox->getPositionX() - 1, settingheadbox->getPositionY() + 1));
settingheadbox->setLocalZOrder(1);
}
editName->setEnabled(false);
motifyBtn->setVisible(false);
}
else
{
editName->setEnabled(true);
motifyBtn->setVisible(true);
}
return true;
}
void SettingLayer::login(cocos2d::Ref *pSender, cocos2d::ui::Widget::TouchEventType type)
{
CommonLayer::Action(pSender, type);
cocos2d::ui::Widget* nodebtn = (cocos2d::ui::Widget*)pSender;
int tag = nodebtn->getTag();
if (type == ui::Widget::TouchEventType::ENDED)
{
setChangelogin = tag;
WaitingProgress* waitbox = WaitingProgress::create("数据加载中...");
Director::getInstance()->getRunningScene()->addChild(waitbox, 10000, "waitbox");
LoadingScene::login(tag);
}
}
void SettingLayer::musicOption(cocos2d::Ref *pSender, cocos2d::ui::Widget::TouchEventType type)
{
if (type == ui::Widget::TouchEventType::ENDED)
{
SoundManager::sharedManager()->playSound(SoundManager::SOUND_ID_BUTTON);
if (!_musicoff->isVisible())
{
SoundManager::sharedManager()->setIsMusicOn(false);
_musicoff->setVisible(true);
SoundManager::sharedManager()->pauseBackMusic();
UserDefault::getInstance()->setBoolForKey("ismusicon", false);
_musicBtn->setBright(false);
}
else
{
SoundManager::sharedManager()->setIsMusicOn(true);
_musicoff->setVisible(false);
if (SoundManager::sharedManager()->getMusicPlayed())
SoundManager::sharedManager()->resumeBackMusic();
else
SoundManager::sharedManager()->playBackMusic("sound/bg.mp3");
UserDefault::getInstance()->setBoolForKey("ismusicon", true);
_musicBtn->setBright(true);
}
}
}
void SettingLayer::soundOption(cocos2d::Ref *pSender, cocos2d::ui::Widget::TouchEventType type)
{
if (type == ui::Widget::TouchEventType::ENDED)
{
SoundManager::sharedManager()->playSound(SoundManager::SOUND_ID_BUTTON);
if (!_soundoff->isVisible())
{
SoundManager::sharedManager()->setIsSoundOn(false);
_soundoff->setVisible(true);
UserDefault::getInstance()->setBoolForKey("issoundon", false);
_soundBtn->setBright(false);
}
else
{
SoundManager::sharedManager()->setIsSoundOn(true);
_soundoff->setVisible(false);
UserDefault::getInstance()->setBoolForKey("issoundon", true);
_soundBtn->setBright(true);
SoundManager::sharedManager()->playSound(SoundManager::SOUND_ID_BUTTON);
}
}
}
void SettingLayer::close(cocos2d::Ref *pSender, cocos2d::ui::Widget::TouchEventType type)
{
CommonLayer::Action(pSender, type);
if (type == ui::Widget::TouchEventType::ENDED)
{
this->removeFromParentAndCleanup(true);
}
}
void SettingLayer::motifyName(cocos2d::Ref *pSender, cocos2d::ui::Widget::TouchEventType type)
{
CommonLayer::Action(pSender, type);
}
void SettingLayer::textFiledEvent(cocos2d::Ref *pSender, cocos2d::ui::TextField::EventType eventtype)
{
switch (eventtype)
{
case cocos2d::ui::TextField::EventType::ATTACH_WITH_IME:
break;
case cocos2d::ui::TextField::EventType::INSERT_TEXT:
break;
case cocos2d::ui::TextField::EventType::DETACH_WITH_IME:
break;
case cocos2d::ui::TextField::EventType::DELETE_BACKWARD:
break;
default:
break;
}
}
void SettingLayer::editBoxEditingDidBegin(cocos2d::ui::EditBox* editBox)
{
}
void SettingLayer::editBoxEditingDidEnd(cocos2d::ui::EditBox* editBox)
{
if (editBox->getTag() == 0)
{
std::string myname = GlobalData::getMyName();
if (myname.compare(editBox->getText()) != 0)
{
int ret = 0;
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
char p_str[64] = { 0 };
sprintf(p_str, "%s", editBox->getText());
JniMethodInfo methodInfo;
if (JniHelper::getStaticMethodInfo(methodInfo, "com/kuxx/hllm/hllm", "isSensitiveWord", "(Ljava/lang/String;)I"))
{
jstring str1 = methodInfo.env->NewStringUTF(p_str);
ret = methodInfo.env->CallStaticIntMethod(methodInfo.classID, methodInfo.methodID, str1);
}
#endif
if (ret == 0)
GlobalData::setMyName(editBox->getText());
else
{
editBox->setText(myname.c_str());
}
}
}
}
void SettingLayer::editBoxTextChanged(cocos2d::ui::EditBox* editBox, const std::string &text)
{
}
void SettingLayer::editBoxReturn(cocos2d::ui::EditBox *editBox)
{
}
| [
"jian zhou"
] | jian zhou |
4f64eb3531e2d26cce738bbf9ea8a7f7fbd0dd50 | 531e753cf9e9378799078da5852264db088e9781 | /inc/MessageRequestGetHandler.h | 272c4a1423701b483041a924c80b659eaa43a1fe | [] | no_license | Yhgenomics/meloton-cli | b4d21abcd86e6d78edf3873dfc1a02bcafeb0bc9 | 2f9acb0f1464b139335d3f4bb265e75e9c60aff9 | refs/heads/master | 2016-08-12T09:18:00.042388 | 2016-03-01T08:20:00 | 2016-03-01T08:20:00 | 49,190,905 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 561 | h | /* * * * * * * * * * * * * * * *
* YHGenomics Inc.
* Author : yang shubo
* Date : 2016-01-13
* Description: handler for MessageRequestGet
* * * * * * * * * * * * * * * */
#ifndef MESSAGEREQUESTGET_HANDLER_
#define MESSAGEREQUESTGET_HANDLER_
#include <string>
#include <memory>
#include <MRT.h>
#include <ProtocolSession.h>
#include <google/protobuf/message.h>
#include <MessageRequestGet.pb.h>
static int MessageRequestGetHandler( ProtocolSession * session , uptr<MessageRequestGet> msg )
{
return 0;
}
#endif
// !MESSAGEREQUESTGET_HANDLER_
| [
"[email protected]"
] | |
7bda6839de0006ce7c2db06599bc4c3b909db802 | 2cc63e61904c0b821b88687cbc7c20f4ffeb28cb | /2147 - Galopeira.cpp | 8b99dac40ee53f6497149fa3142ec5071e9d975c | [] | no_license | lawrencesilva/URI | 47557fbb007ccbfb00150d2cd503e8ab9bd0973a | 1db51a14e7072099351e205abb691b191fb7d681 | refs/heads/master | 2020-03-24T02:08:58.630761 | 2018-07-26T11:12:00 | 2018-07-26T11:12:00 | 142,364,470 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 423 | cpp | #include <iostream>
#include <cmath>
#include <string>
#include <iomanip>
using namespace std;
int main() {
double guarda;
string palavra;
int vezes, contador = 0;
cin >> vezes;
while(vezes > 0) {
cin >> palavra;
for(int i = 0; palavra[i] != '\0'; i++ ) {
contador++;
}
guarda = contador;
cout << fixed << setprecision(2) << guarda / 100 << endl;
contador = 0;
vezes--;
}
return 0;
} | [
"[email protected]"
] | |
b9069574e5812985ad8732c7bf8117fde46600dd | cd470ad61c4dbbd37ff004785fd6d75980987fe9 | /互测2021/day12/C/C.cpp | b9477f52bfb2c995f82c35ca1a2b0c22da832dd3 | [] | no_license | AutumnKite/Codes | d67c3770687f3d68f17a06775c79285edc59a96d | 31b7fc457bf8858424172bc3580389badab62269 | refs/heads/master | 2023-02-17T21:33:04.604104 | 2023-02-17T05:38:57 | 2023-02-17T05:38:57 | 202,944,952 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 9,871 | cpp | #include <bits/stdc++.h>
const long long INF = std::numeric_limits<long long>::max();
int pcnt;
int V[200000];
class convex {
public:
struct line {
long long k, b;
line(long long _k = 0, long long _b = 0) : k(_k), b(_b) {}
long long get(const int &x) const {
return k * V[x] + b;
}
};
protected:
const int n;
struct node {
line v;
node *ls, *rs;
node(line _v) : v(_v), ls(nullptr), rs(nullptr) {}
};
node *rt;
void insert(node *&u, int l, int r, line v) {
if (u == nullptr) {
u = new node(v);
return;
}
if (v.get(l) <= u->v.get(l) && v.get(r) <= u->v.get(r)) {
u->v = v;
return;
}
if (v.get(l) >= u->v.get(l) && v.get(r) >= u->v.get(r)) {
return;
}
int mid = (l + r) >> 1;
if (v.get(mid) < u->v.get(mid)) {
std::swap(u->v, v);
}
if (v.get(l) < u->v.get(l)) {
insert(u->ls, l, mid, v);
} else {
insert(u->rs, mid + 1, r, v);
}
}
void merge(node *&u, node *&v, int l, int r) {
if (u == nullptr) {
std::swap(u, v);
return;
}
if (v == nullptr) {
return;
}
int mid = (l + r) >> 1;
merge(u->ls, v->ls, l, mid);
merge(u->rs, v->rs, mid + 1, r);
insert(u, l, r, v->v);
delete v;
v = nullptr;
}
long long query(node *u, int l, int r, int x) {
if (u == nullptr) {
return INF;
}
int mid = (l + r) >> 1;
if (x <= mid) {
return std::min(query(u->ls, l, mid, x), u->v.get(x));
} else {
return std::min(query(u->rs, mid + 1, r, x), u->v.get(x));
}
}
void clear(node *u) {
if (u == nullptr) {
return;
}
clear(u->ls);
clear(u->rs);
delete u;
}
public:
convex(int _n) : n(_n), rt(nullptr) {}
void insert(const line &v) {
insert(rt, 0, n - 1, v);
}
void merge(convex &c) {
merge(rt, c.rt, 0, n - 1);
}
long long query(int x) {
return query(rt, 0, n - 1, x);
}
void clear() {
clear(rt);
rt = nullptr;
}
convex &operator=(const convex &rhs) {
clear();
rt = rhs.rt;
return *this;
}
};
class segment_tree {
protected:
static int enlarge(int n) {
int res = 1;
while (res < n) {
res <<= 1;
}
return res;
}
int n, en, idx;
std::vector<convex> a;
std::vector<std::vector<std::pair<int, int>>> Q;
std::vector<convex> T;
void insert(int u, int l, int r, int x, const convex::line &v) {
T[u].insert(v);
if (l + 1 == r) {
return;
}
int mid = (l + r + 1) >> 1;
if (x < mid) {
insert(u << 1, l, mid, x, v);
} else {
insert(u << 1 | 1, mid, r, x, v);
}
}
void add_query(int u, int l, int r, int L, int R, int x, int id) {
if (L <= l && r <= R) {
Q[u].emplace_back(x, id);
return;
}
int mid = (l + r + 1) >> 1;
if (L < mid) {
add_query(u << 1, l, mid, L, R, x, id);
}
if (R > mid) {
add_query(u << 1 | 1, mid, r, L, R, x, id);
}
}
std::vector<long long> ans;
void get_ans(int u, int l, int r) {
if (l + 1 == r) {
T[u].merge(a[l]);
} else {
int mid = (l + r + 1) >> 1;
get_ans(u << 1, l, mid);
get_ans(u << 1 | 1, mid, r);
T[u].merge(T[u << 1]);
T[u].merge(T[u << 1 | 1]);
}
for (auto [x, id] : Q[u]) {
ans[id] = std::min(ans[id], T[u].query(x));
}
}
public:
segment_tree(int _n, int _m)
: n(_n), en(enlarge(n) << 1), idx(0), a(n, convex(_m)),
Q(en), T(en, convex(_m)) {}
void insert(int x, const convex::line &v) {
a[x].insert(v);
}
void add_query(int l, int r, int x) {
add_query(1, 0, n, l, r, x, idx++);
}
std::vector<long long> get_ans() {
ans.assign(idx, INF);
get_ans(1, 0, n);
T[1].clear();
return ans;
}
};
class tree {
public:
struct query {
int u, x, id;
query(int _u, int _x, int _id) : u(_u), x(_x), id(_id) {}
};
std::vector<query> Q;
protected:
int n, rt, dfn_idx;
std::vector<int> a;
std::vector<std::vector<std::pair<int, long long>>> E;
std::vector<int> fa, dep, sz, son, top, dfn;
std::vector<long long> dis;
std::vector<std::vector<int>> lt;
int idx;
std::vector<std::vector<int>> Q1, Q2, Q3, Q4;
std::vector<int> c1, c2, c3, c4;
void dfs1(int u) {
sz[u] = 1;
son[u] = -1;
for (auto [v, w] : E[u]) {
if (v != fa[u]) {
fa[v] = u;
dep[v] = dep[u] + 1;
dis[v] = dis[u] + w;
dfs1(v);
sz[u] += sz[v];
if (son[u] == -1 || sz[v] > sz[son[u]]) {
son[u] = v;
}
}
}
}
void dfs2(int u, int tp) {
dfn[u] = dfn_idx++;
top[u] = tp;
if (son[u] != -1) {
dfs2(son[u], tp);
}
for (auto [v, w] : E[u]) {
if (v != fa[u] && v != son[u]) {
dfs2(v, v);
}
}
}
std::vector<long long> sum;
std::vector<long long> ans;
void upd(int id, long long s) {
ans[id] = std::min(ans[id], s);
}
std::vector<convex> con;
void dfs3(int u, convex &now1, convex &now2) {
for (int v : lt[u]) {
now1.insert(convex::line(a[v], 2 * dis[v] - 2 * dis[u]));
now2.insert(convex::line(a[v], 2 * dis[v] - 4 * dis[u]));
}
for (auto i : Q1[u]) {
upd(Q[i].id, now1.query(Q[i].x));
}
for (auto i : Q3[u]) {
upd(Q[i].id, now2.query(Q[i].x) + 2 * dis[Q[i].u]);
}
if (son[u] != -1) {
dfs3(son[u], now1, now2);
}
now1.clear(), now2.clear();
for (auto [v, w] : E[u]) {
if (v != fa[u] && v != son[u]) {
dfs3(v, now1, now2);
now1.clear(), now2.clear();
}
}
con[u].insert(convex::line(a[u], 2 * dis[u]));
for (auto [v, w] : E[u]) {
if (v != fa[u]) {
con[u].merge(con[v]);
}
}
for (auto i : Q3[u]) {
upd(Q[i].id, con[u].query(Q[i].x) - 4 * dis[u] + 2 * dis[Q[i].u]);
}
for (auto i : Q1[u]) {
upd(Q[i].id, con[u].query(Q[i].x) - 2 * dis[u]);
}
for (auto i : Q4[u]) {
upd(Q[i].id, con[u].query(Q[i].x) - 2 * dis[u]);
}
}
public:
tree(std::vector<int> _a, int _rt)
: n(_a.size()), rt(_rt), dfn_idx(0), a(_a), E(n),
fa(n), dep(n), sz(n), son(n), top(n), dfn(n), dis(n), lt(n),
idx(0), Q1(n), Q2(n), Q3(n), Q4(n), c1(n), c2(n), c3(n), c4(n) {}
void add_edge(int u, int v, long long w) {
E[u].emplace_back(v, w);
E[v].emplace_back(u, w);
}
void build() {
fa[rt] = -1;
dep[rt] = 0;
dis[rt] = 0;
dfs1(rt);
dfs2(rt, rt);
for (int u = 0; u < n; ++u) {
lt[u].reserve(sz[u] - (son[u] == -1 ? 0 : sz[son[u]]));
}
for (int u = 0; u < n; ++u) {
for (int v = u; v != -1; v = fa[top[v]]) {
lt[v].push_back(u);
}
}
}
int LCA(int u, int v) {
while (top[u] != top[v]) {
if (dep[top[u]] < dep[top[v]]) {
std::swap(u, v);
}
u = fa[top[u]];
}
return dep[u] < dep[v] ? u : v;
}
void add_query(int u, int v, int x) {
V[pcnt++] = x;
int z = LCA(u, v);
sum.emplace_back(dis[u] + dis[v] - 2 * dis[z]);
Q.emplace_back(u, x, idx);
Q.emplace_back(v, x, idx);
Q.emplace_back(z, x, idx);
for (int p = u; p != -1; p = fa[top[p]]) {
if (top[p] == top[z]) {
++c2[p];
++c4[p];
break;
}
++c1[p];
}
for (int p = v; p != -1; p = fa[top[p]]) {
if (top[p] == top[z]) {
++c2[p];
++c4[p];
break;
}
++c1[p];
}
for (int p = z; p != -1; p = fa[top[p]]) {
++c3[p];
}
++idx;
}
std::vector<long long> get_ans() {
std::sort(V, V + pcnt);
pcnt = std::unique(V, V + pcnt) - V;
ans.assign(idx, INF);
segment_tree T(n, pcnt);
for (int u = 0; u < n; ++u) {
for (int v : lt[u]) {
T.insert(dfn[u], convex::line(a[v], 2 * dis[v] - 2 * dis[u]));
}
}
for (int i = 0; i < n; ++i) {
Q1[i].reserve(c1[i]);
Q2[i].reserve(c2[i]);
Q3[i].reserve(c3[i]);
Q4[i].reserve(c4[i]);
}
for (int i = 0; i < (int)Q.size(); i += 3) {
int tmp = std::lower_bound(V, V + pcnt, Q[i].x) - V;
Q[i].x = Q[i + 1].x = Q[i + 2].x = tmp;
int u = Q[i].u, v = Q[i + 1].u, z = Q[i + 2].u;
for (int p = u; p != -1; p = fa[top[p]]) {
if (top[p] == top[z]) {
Q2[p].emplace_back(i + 2);
Q4[p].emplace_back(i);
break;
}
Q1[p].emplace_back(i);
}
for (int p = v; p != -1; p = fa[top[p]]) {
if (top[p] == top[z]) {
Q2[p].emplace_back(i + 2);
Q4[p].emplace_back(i + 1);
break;
}
Q1[p].emplace_back(i + 1);
}
for (int p = z; p != -1; p = fa[top[p]]) {
Q3[p].emplace_back(i + 2);
}
}
for (int u = 0; u < n; ++u) {
for (auto i : Q2[u]) {
T.add_query(dfn[Q[i].u], dfn[u] + 1, Q[i].x);
}
}
auto tans = T.get_ans();
auto it = tans.begin();
for (int u = 0; u < n; ++u) {
for (auto i : Q2[u]) {
upd(Q[i].id, *it);
++it;
}
}
con.assign(n, convex(pcnt));
convex tmp1(pcnt), tmp2(pcnt);
dfs3(rt, tmp1, tmp2);
con[0].clear();
for (int i = 0; i < idx; ++i) {
ans[i] += sum[i];
}
return ans;
}
};
int main() {
std::ios_base::sync_with_stdio(false);
std::cin.tie(0);
int n, m, q;
std::cin >> n >> m >> q;
std::vector<int> a(n);
for (int i = 0; i < n; ++i) {
std::cin >> a[i];
}
tree T(a, 0);
for (int i = 0; i < n - 1; ++i) {
int u, v;
long long w;
std::cin >> u >> v >> w;
--u, --v;
T.add_edge(u, v, w);
}
T.build();
for (int i = 0; i < q; ++i) {
long long x, y;
std::cin >> x >> y;
--x, --y;
T.add_query(x % n, y % n, abs(x / n - y / n));
}
auto ans = T.get_ans();
for (int i = 0; i < q; ++i) {
std::cout << ans[i] << "\n";
}
}
| [
"[email protected]"
] | |
8af267f144a9acd161064559861e9e73340aa16b | 3106e8e7d458a077fbaa7b9a08e5a1c9c2b63d30 | /trust/service.cpp | 29675e5b02c9acf47a38b2a641eb05faa0c6ffe7 | [] | no_license | schwabe93/android_device_oneplus_sdm845-common | f0dd6107640de5e0ea632a0d270b30ddca5da793 | bd7229da3c29419e70ba293bd63d0c8d1c8edad4 | refs/heads/lineage-16.0 | 2020-06-11T23:21:37.099203 | 2019-06-17T17:34:04 | 2019-06-17T17:34:04 | 194,119,465 | 2 | 1 | null | 2019-06-29T15:32:45 | 2019-06-27T15:24:08 | C++ | UTF-8 | C++ | false | false | 1,929 | cpp | /*
* Copyright (C) 2019 The LineageOS Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define LOG_TAG "[email protected]"
#include <android-base/logging.h>
#include <binder/ProcessState.h>
#include <hidl/HidlTransportSupport.h>
#include "UsbRestrict.h"
using android::OK;
using android::sp;
using android::status_t;
// libhwbinder:
using android::hardware::configureRpcThreadpool;
using android::hardware::joinRpcThreadpool;
using ::vendor::lineage::trust::V1_0::IUsbRestrict;
using ::vendor::lineage::trust::V1_0::implementation::UsbRestrict;
int main() {
sp<IUsbRestrict> usbRestrict;
status_t status;
LOG(INFO) << "Trust HAL service is starting.";
usbRestrict = new UsbRestrict();
if (usbRestrict == nullptr) {
LOG(ERROR) << "Can not create an instance of Trust HAL UsbRestricted Iface, exiting.";
goto shutdown;
}
configureRpcThreadpool(1, true /*callerWillJoin*/);
status = usbRestrict->registerAsService();
if (status != OK) {
LOG(ERROR) << "Could not register service for Trust HAL UsbRestricted Iface (" << status
<< ").";
}
LOG(INFO) << "Trust HAL service is ready.";
joinRpcThreadpool();
// Should not pass this line
shutdown:
// In normal operation, we don't expect the thread pool to shutdown
LOG(ERROR) << "Trust HAL service is shutting down.";
return 1;
}
| [
"[email protected]"
] | |
c89ecc88dd5cf910b6e68343f3358d6c575259ea | 75a6ecde3327a88a8facbd62e38be682044429ea | /median.cpp | 53f629782c81d9a2f8fd13b0972c42936ef321e3 | [] | no_license | surop1/spoj | 1aa29fe3870111b5e543032168088f1de372e748 | b2b15071a6e70a6923a97d475000a30917956d05 | refs/heads/master | 2023-03-31T20:53:31.086414 | 2021-04-13T09:55:23 | 2021-04-13T09:55:23 | 339,306,820 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 929 | cpp | double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
if (nums1.size()>nums2.size()) return findMedianSortedArrays(nums2, nums1);
int X=nums1.size(), Y=nums2.size();
int s=0, e=X;
while (s<=e){
int px = (s+e)/2;
int py = (X+Y+1)/2-px;
int maxLeftX = px==0? INT_MIN: nums1[px-1];
int maxLeftY = py==0? INT_MIN: nums2[py-1];
int minRightX = px==X? INT_MAX: nums1[px];
int minRightY = py==Y? INT_MAX: nums2[py];
if (maxLeftX <= minRightY && maxLeftY <= minRightX){
if ((X+Y)%2==0){
return (double)(min(minRightX, minRightY)+max(maxLeftX, maxLeftY))/2.0;
}
return max(maxLeftX, maxLeftY);
}
else if (maxLeftX > minRightY) e=px-1;
else s=px+1;
}
return 1.0;
}
| [
"[email protected]"
] | |
ae02f018dc3c225208479a638428dc2d47806f33 | abc963c15bc10cb413e23626fa71cfbbb4f7b42e | /samples/Properties/main.cpp | 4c715fa3013e0c1bc45a780d2f9bff2962c52f9b | [] | no_license | zetsumi/Flyff-Engine | d78707bea3c345c7f94826fb1054e1c14a0a0792 | 8bcecb1e1708ad46950e28dcd7022906e0e201ec | refs/heads/master | 2023-05-01T15:34:34.783839 | 2023-04-17T19:28:28 | 2023-04-17T19:28:28 | 226,941,886 | 4 | 1 | null | 2023-04-17T19:28:29 | 2019-12-09T18:41:12 | C++ | UTF-8 | C++ | false | false | 1,073 | cpp | #include <iostream>
#include <ctime>
#include <io/file/reader.hpp>
#pragma warning( disable: 4251 )
bool sample_project();
void propitem_without_project();
void propctrl_without_project();
bool load_text_json();
bool propitem_load_from_file(fe::LOADER_MODE mode);
bool propctrl_load_from_file(fe::LOADER_MODE mode);
bool propskill_load_from_file(fe::LOADER_MODE mode);
bool propkarma_load_from_file(fe::LOADER_MODE mode);
int main()
{
std::srand(static_cast<std::uint32_t>(std::time(nullptr)));
sample_project();
//load_text_json();
//propitem_without_project();
//propitem_load_from_file(fe::LOADER_MODE::JSON);
//propitem_load_from_file(fe::LOADER_MODE::XML);
//propctrl_without_project();
//propctrl_load_from_file(fe::LOADER_MODE::JSON);
//propctrl_load_from_file(fe::LOADER_MODE::XML);
//propskill_load_from_file(fe::LOADER_MODE::XML);
//propskill_load_from_file(fe::LOADER_MODE::JSON);
//propkarma_load_from_file(fe::LOADER_MODE::XML);
//propkarma_load_from_file(fe::LOADER_MODE::JSON);
return 0;
} | [
"[email protected]"
] | |
b784c1a916f9abf1115838ef280291160bc88e7a | 1461d854afde6abea7b08824cbc6e345ff8c1e48 | /src/mruset.h | 1a07e3f2f7a8d52e665c228db0f0c06d250b9cfc | [
"MIT"
] | permissive | Nanotoken/nanotoken | 5442bdba9b0030575f0d6db608dce79a4338c8f2 | 08127376fe24b0244229f0d2965e08cebd8617f7 | refs/heads/master | 2021-01-09T09:01:22.686297 | 2014-04-21T16:36:21 | 2014-04-21T16:36:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,178 | h | // Copyright (c) 2012 The Bitcoin developers
// Copyright (c) 2012 Litecoin Developers
// Copyright (c) 2013 nanotoken Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_MRUSET_H
#define BITCOIN_MRUSET_H
#include <set>
#include <deque>
/** STL-like set container that only keeps the most recent N elements. */
template <typename T> class mruset
{
public:
typedef T key_type;
typedef T value_type;
typedef typename std::set<T>::iterator iterator;
typedef typename std::set<T>::const_iterator const_iterator;
typedef typename std::set<T>::size_type size_type;
protected:
std::set<T> set;
std::deque<T> queue;
size_type nMaxSize;
public:
mruset(size_type nMaxSizeIn = 0) { nMaxSize = nMaxSizeIn; }
iterator begin() const { return set.begin(); }
iterator end() const { return set.end(); }
size_type size() const { return set.size(); }
bool empty() const { return set.empty(); }
iterator find(const key_type& k) const { return set.find(k); }
size_type count(const key_type& k) const { return set.count(k); }
bool inline friend operator==(const mruset<T>& a, const mruset<T>& b) { return a.set == b.set; }
bool inline friend operator==(const mruset<T>& a, const std::set<T>& b) { return a.set == b; }
bool inline friend operator<(const mruset<T>& a, const mruset<T>& b) { return a.set < b.set; }
std::pair<iterator, bool> insert(const key_type& x)
{
std::pair<iterator, bool> ret = set.insert(x);
if (ret.second)
{
if (nMaxSize && queue.size() == nMaxSize)
{
set.erase(queue.front());
queue.pop_front();
}
queue.push_back(x);
}
return ret;
}
size_type max_size() const { return nMaxSize; }
size_type max_size(size_type s)
{
if (s)
while (queue.size() > s)
{
set.erase(queue.front());
queue.pop_front();
}
nMaxSize = s;
return nMaxSize;
}
};
#endif
| [
"[email protected]"
] | |
d669a7174829b4bac75505cdb3b758ac44a3a6a4 | 0a5645154953b0a09d3f78753a1711aaa76928ff | /common/c/nbservices/src/map/layermanager/BubbleListenerInterface.h | cef6c15174d07ff3e3e3a51042472c096ed3be02 | [] | no_license | GENIVI/navigation-next | 3a6f26063350ac8862b4d0e2e9d3522f6f249328 | cb8f7ec5ec4c78ef57aa573315b75960b2a5dd36 | refs/heads/master | 2023-08-04T17:44:45.239062 | 2023-07-25T19:22:19 | 2023-07-25T19:22:19 | 116,230,587 | 17 | 11 | null | 2018-05-18T20:00:38 | 2018-01-04T07:43:22 | C++ | UTF-8 | C++ | false | false | 4,989 | h | /*
Copyright (c) 2018, TeleCommunication Systems, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the TeleCommunication Systems, 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 TELECOMMUNICATION SYSTEMS, INC.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.
*/
/*!--------------------------------------------------------------------------
@file BubblelistenerInterface.h
@defgroup nbmap
*/
/*
(C) Copyright 2011 by TeleCommunication Systems, Inc.
The information contained herein is confidential, proprietary
to TeleCommunication Systems, Inc., and considered a trade secret as
defined in section 499C of the penal code of the State of
California. Use of this information by anyone other than
authorized employees of TeleCommunication Systems, is granted only
under a written non-disclosure agreement, expressly
prescribing the scope and manner of such use.
---------------------------------------------------------------------------*/
/*! @{ */
#ifndef __BUBBLE_LISTENER__
#define __BUBBLE_LISTENER__
#include "smartpointer.h"
#include <string>
namespace nbmap
{
class BubblelistenerInterface
{
public:
/*! Callback function called when the pin is selected or the selected pin is moved from the outside to the screen
This function is called in the render thread.
@return None
*/
virtual void NotifyShowBubble(shared_ptr<std::string> pinId, float x, float y, bool orientation) = 0;
/*! Callback function called when the pin is unselected or the selected pin is moved outside the screen
This function is called in the render thread.
@return None
*/
virtual void NotifyHideBubble(shared_ptr<std::string> pinId) = 0;
/*! Callback function called when position of selected pin is changed
This function is called in the render thread.
@return None
*/
virtual void NotifyUpdateBubble(shared_ptr<std::string> pinId, float x, float y, bool orientation) = 0;
/*! Callback function called to show location bubble.
This function is called in the render thread.
@return None
*/
virtual void NotifyShowLocationBubble(float x, float y, bool orientation,
float latitude, float longitude) = 0;
/*! Callback function called to hide location bubble.
This function is called in the render thread.
@return None
*/
virtual void NotifyHideLocationBubble() = 0;
/*! Callback function called when position of location disk changes
This function is called in the render thread.
@return None
*/
virtual void NotifyUpdateLocationBubble(float x, float y, bool orientation,
float latitude, float longitude) = 0;
/*! Callback function called when the static poi is selected or the selected static poi is moved from the outside to the screen
This function is called in the render thread.
@return None
*/
virtual void NotifyShowStaticPoiBubble(float x, float y, bool orientation) = 0;
/*! Callback function called when the static poi is unselected or the selected static poi is moved outside the screen
This function is called in the render thread.
@return None
*/
virtual void NotifyHideStaticPoiBubble() = 0;
/*! Callback function called when position of selected static poi is changed
This function is called in the render thread.
@return None
*/
virtual void NotifyUpdateStaticPoiBubble(float x, float y, bool orientation) = 0;
};
}; // namespace nbmap
#endif
/*! @} */
| [
"[email protected]"
] | |
51ad347777436dfbfd4269b9a91f23a1aeb1aef1 | 3df5eb732be98513ac4bfa96321a9289725b8ee5 | /SRC/MISSMAN/NODEREV.CPP | a636f796fd4c3e052327fdd57113d73af32196f6 | [] | no_license | PythonicFortran/mig_src | 505f797c12b44d52f69892b408343f7cc496385d | 7adf5e68c56f1bfbc79430064df39e36a4e665b6 | refs/heads/master | 2021-05-29T11:52:29.183612 | 2015-08-06T23:27:59 | 2015-08-06T23:27:59 | null | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 89,839 | cpp | /*
MiG Alley
Copyright (C) 1998, 1999, 2000, 2001 Empire Interactive (Europe) Ltd,
677 High Road, North Finchley, London N12 0DA
Please see the document licence.doc for the full licence agreement
2. LICENCE
2.1
Subject to the provisions of this Agreement we now grant to you the
following rights in respect of the Source Code:
2.1.1
the non-exclusive right to Exploit the Source Code and Executable
Code on any medium; and
2.1.2
the non-exclusive right to create and distribute Derivative Works.
2.2
Subject to the provisions of this Agreement we now grant you the
following rights in respect of the Object Code:
2.2.1
the non-exclusive right to Exploit the Object Code on the same
terms and conditions set out in clause 3, provided that any
distribution is done so on the terms of this Agreement and is
accompanied by the Source Code and Executable Code (as
applicable).
3. GENERAL OBLIGATIONS
3.1
In consideration of the licence granted in clause 2.1 you now agree:
3.1.1
that when you distribute the Source Code or Executable Code or
any Derivative Works to Recipients you will also include the
terms of this Agreement;
3.1.2
that when you make the Source Code, Executable Code or any
Derivative Works ("Materials") available to download, you will
ensure that Recipients must accept the terms of this Agreement
before being allowed to download such Materials;
3.1.3
that by Exploiting the Source Code or Executable Code you may
not impose any further restrictions on a Recipient's subsequent
Exploitation of the Source Code or Executable Code other than
those contained in the terms and conditions of this Agreement;
3.1.4
not (and not to allow any third party) to profit or make any
charge for the Source Code, or Executable Code, any
Exploitation of the Source Code or Executable Code, or for any
Derivative Works;
3.1.5
not to place any restrictions on the operability of the Source
Code;
3.1.6
to attach prominent notices to any Derivative Works stating
that you have changed the Source Code or Executable Code and to
include the details anddate of such change; and
3.1.7
not to Exploit the Source Code or Executable Code otherwise than
as expressly permitted by this Agreement.
questions about this file may be asked at http://www.simhq.com/
*/
//------------------------------------------------------------------------------
//Filename noderev.cpp
//System
//Author R. Hyde
//Date Thu 6 Mar 1997
//Description
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//
//In 3d/debrief:
//
//On killing mobiles allocate storesdestroyed to launching SupplyRoutes
//
// Need: BlueAcAtAirfield(UniqueID af)
// RedAcAtAirfield(UniqueID af)
//
//
//Logic to handle salients:
// one route front cannot be radically different from the others
//Need to be able to distiguish if something is dead
//
//Use:
// consecutive_days_attacked
// stores_destroyed
// totalstores_destroyed
// recommision_time (Implement code ProcessStoresArrival)
//
//What needs to be done about campaign win/loss?
// Same for every campaign?
//What should we do about first node. at present we just max stores everyday
//
//Routines that need discussion:
// FindModifiedSupplies()
// called for frontline only
// used when?
// ProcessAirFields()
// test may have to change in light of frontline change
// do we loose a/c: RemoveLostAc();
// and kill it on transfer to other side: KillItem ();
// WithDrawSupplies(SupplyNode* node)
// launch some battle fields to indicate withdrawal
// messages to player
//
//Not Used:
// UpdateBf()
//
//Traffic along a whole route should be modified by attacks on big marshalling yards
// Use TodaysMobiles and Currmobiles
// Whatabout splitAB splitBC
//for each supply line
//determine TodaysTrains using MaxTrains and status of
// AssociatedMarshallingYard[2]
//Battle Field launches
//Each InterNode structure has the potential to launch mobiles. These will only
//be seen in the game when an individual field exceeds the normal maximum.
//This is to indicate movement during the day.
//Normal movements occurred at night.
//
//We should generally see movement then just behind the lines.
//
//In addition:
// we will place aircraft on the active airfields
// front line activity will be launched for FRONTLINE node
//
//Other things to consider:
//
// Activity on nodes and supplyroutes should generate messages
//
//
// If Player selects close support mission, he will be directed to battlefield
// targets by radio and FAC. When out of ammo he returns and may be told he
// needs to go out immediately to finish the job.
//
//MiG model
// how many MiGs are launched each day and where
//
//
//Messages:
//
// Ground forces say they need an attack on something to help them.
// Red artillery needs to be taken out
// to help defence
// to help attack
//
#include "dosdefs.h" //RJS 30Aug96
//#include "stdafx.h"
#include "myerror.h" //DAW 26/04/99
#define F_BATTLE //RJS 30Aug96
#include "files.g" //RJS 30Aug96
#include "math.h"
#include "worldinc.h"
#include "text.h"
#include "missman2.h"
#include "node.h"
//#include "briefing.h" //PD 15Mar96
#include "mymath.h"
#include "..\mfc\resource.h"
#include "persons2.h"
MATHABLE(SupplyPriority);
//컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴
//Procedure FindModifiedSupplies
//Author R. Hyde
//Date Thu 6 Mar 1997
//
//Description
//
//Inputs
//
//Returns
//
//------------------------------------------------------------------------------
SWord SupplyTree::FindModifiedSupplies(SupplyNode* node)
{
SWord retval;
retval = node->currentstores;
return (retval);
}
//컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴
//Procedure BlueAcAtAirfield
//Author R. Hyde
//Date Tue 11 Mar 1997
//
//Description
//
//Inputs
//
//Returns
//
//------------------------------------------------------------------------------
SWord SupplyTree::BlueAcAtAirfield(UniqueID af)
{
SWord count = 0;
for (int squad = 0; squad < 5; squad++)
{
if (airfieldinfo[MMC.squad[squad].airfieldindex].airfield == af)
count += MMC.squad[squad].ac_total_avail;
}
return (count);
}
//컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴
//Procedure RedAcAtAirfield
//Author R. Hyde
//Date Tue 11 Mar 1997
//
//Description
//
//Inputs
//
//Returns
//
//------------------------------------------------------------------------------
SWord SupplyTree::RedAcAtAirfield(UniqueID af)
{
SWord count;
AirFieldInfo* afptr=FindAirfieldForItem(af);
count = afptr->activeac;
return (count);
}
//컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴
//Procedure PopulateRedAfs
//Author R. Hyde
//Date //RDH 13/02/99
//
//Description
//
//Inputs
//
//Returns
//
//------------------------------------------------------------------------------
void SupplyTree::PopulateRedAfs()
{
//DEADCODE RDH 19/06/99 //clr out activeac
//DEADCODE RDH 19/06/99 SWord i = 0;
//DEADCODE RDH 19/06/99 while (airfieldinfo[i].nationality != NAT_ALIGN)
//DEADCODE RDH 19/06/99 {
//DEADCODE RDH 19/06/99 airfieldinfo[i].activeac = 0;
//DEADCODE RDH 19/06/99 i++;
//DEADCODE RDH 19/06/99 }
UniqueID af;
SWord i = 0;
if (Miss_Man.currcampaignnum != MissMan::F86_CAMPAIGN) //RDH 14/06/99
{//don't want MiGs on red airfelds below Yalu in F86 campaign //RDH 14/06/99 //RDH 14/06/99
int afnum = MMC.migsquad[1].ac_total_avail/20;
int acnum = MMC.migsquad[1].ac_total_avail;
int popac;
if (afnum > 2)
afnum = 2;
for (i = 0; i <= afnum;i++)
{
popac = acnum;
if (popac > 20)
popac = 20;
if (popac > 0)
af = FindRedAfToPopulate(popac); //store as a negative number
acnum = acnum - popac;
}
}
//clr out old activeac
i = 0;
while (airfieldinfo[i].nationality != NAT_ALIGN)
{
if (airfieldinfo[i].activeac < 0)
airfieldinfo[i].activeac = -airfieldinfo[i].activeac;
else
airfieldinfo[i].activeac = 0;
i++;
}
}
//컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴
//Procedure FindRedAfToPopulate
//Author R. Hyde
//Date Thu 6 Mar 1997
//
//Description
//
//Inputs
//
//Returns
//
//------------------------------------------------------------------------------
UniqueID SupplyTree::FindRedAfToPopulate(int acnum)
{
//find a red airfield that fits the bill to populate
//populate it with acnum aircraft
SupplyNode* currnode;
currnode = WestRoute.frontline->route[0]->supplier;
COORDS3D& frontline=
Persons2::ConvertPtrUID(WestRoute.frontline->associated_item)->World;
while (currnode != NULL)
{
for (int i=0;i <3;i++)
{
AirFieldInfo* af=FindAirfieldForItem(currnode->airfield[i]);
if (af)
{
COORDS3D& afworld=
Persons2::ConvertPtrUID(af->airfield)->World;
if ( (af->attackstats.damagelevel < 90)
&& (af->activeac >= 0)
&& ((afworld.Z - frontline.Z) > 5000000) //airfield > 50km north of frontlibe
)
{
if (af->activeac == 0)
MMC.DisDayEntry(Debrief::TARGUID, af->airfield, Debrief::T_Airfield01_H);
af->activeac =-acnum;
return(af->airfield);
}
}
}
currnode = currnode->route[0]->supplier;
}
return(UID_Null);
}
void SupplyTree::MoveSquadron(int squad)
{
int af = 0;
while ( (airfieldinfo[af].nationality!=NAT_ALIGN)
)
{
if ( ( ( (airfieldinfo[af].type < AFT_JET)
&& (squad != SQ_F51)
)
||
(airfieldinfo[af].type > AFT_JET)
)
&&
(FindFreeSlots(af) >= 1)
&&
(airfieldinfo[af].nationality == NAT_BLUE)
)
{
MMC.squad[squad].movetoairfieldindex = -1;
MMC.DisDayEntry(Debrief::DISCARDTARGUID,
airfieldinfo[MMC.squad[squad].airfieldindex].airfield,
Debrief::T_Airfield02_H); //RDH 18/04/99
MMC.squad[squad].airfieldindex = af;
break;
}
af++;
}
}
int SupplyTree::FindFreeSlots(int afnum)
{
int free =0;
for (int i=0;i<PILOTABLE_SQUADRONS;i++)
{
if ( ( (MMC.squad[i].airfieldindex == afnum)
&& (MMC.squad[i].movetoairfieldindex == -1)
)
|| ( (MMC.squad[i].movetoairfieldindex == afnum)
)
)
free++;
}
free = SupplyTree::airfieldinfo[afnum].capacity - free;
return (free);
}
void SupplyTree::MoveAnyBlueAc(int curraf)
{
for (int i=0;i<PILOTABLE_SQUADRONS;i++)
{
if ( ( (MMC.squad[i].airfieldindex == curraf)
&& (MMC.squad[i].movetoairfieldindex == -1)
)
|| ( (MMC.squad[i].movetoairfieldindex == curraf)
)
)
MoveSquadron(i);
}
}
//컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴
//Procedure ProcessAirFields
//Author R. Hyde
//Date Thu 6 Mar 1997
//
//Description
//
//Inputs
//
//Returns
//
//------------------------------------------------------------------------------
void SupplyTree::ProcessAirFields()
{
SWord i = 0;
PopulateRedAfs();
while (airfieldinfo[i].nationality != NAT_ALIGN)
{
if (airfieldinfo[i].nationality == NAT_BLUE)
{
if ( (airfieldinfo[i].northnodes[0]->status == BEHINDREDLINES)
&& (airfieldinfo[i].northnodes[1]->status == BEHINDREDLINES)
)
{
MMC.DisDayEntry(Debrief::DISCARDTARGUID, airfieldinfo[i].airfield, Debrief::T_AF01_H);
airfieldinfo[i].nationality = NAT_RED;
airfieldinfo[i].days = 0;
MoveAnyBlueAc(i); //RDH 10/03/99
}elseif ( (airfieldinfo[i].northnodes[0]->status == BEHINDREDLINES)
|| (airfieldinfo[i].northnodes[1]->status == BEHINDREDLINES)
|| (airfieldinfo[i].northnodes[0]->status == FRONTLINE)
|| (airfieldinfo[i].northnodes[1]->status == FRONTLINE)
)
{
if ( (airfieldinfo[i].northnodes[0]->supplyline->initiative == REDATTACKING)
|| (airfieldinfo[i].northnodes[1]->supplyline->initiative == REDATTACKING)
)
airfieldinfo[i].days++;
if (airfieldinfo[i].days == 1)
MMC.DisDayEntry(Debrief::DISCARDTARGUID, airfieldinfo[i].airfield, Debrief::T_AF00_H);
elseif (BlueAcAtAirfield(airfieldinfo[i].airfield) != 0)
MMC.DisDayEntry(Debrief::DISCARDTARGUID, airfieldinfo[i].airfield, Debrief::T_AF00_H);
}else
{
airfieldinfo[i].days = 0;
}
}else
{
if ( (airfieldinfo[i].northnodes[0]->status == BEHINDBLUELINES)
&& (airfieldinfo[i].northnodes[1]->status == BEHINDBLUELINES)
)
{
MMC.DisDayEntry(Debrief::DISCARDTARGUID, airfieldinfo[i].airfield, Debrief::T_AF02_H);
airfieldinfo[i].nationality = NAT_BLUE;
airfieldinfo[i].days = 0;
}elseif ( (airfieldinfo[i].southnodes[0]->status == BEHINDBLUELINES)
|| (airfieldinfo[i].southnodes[1]->status == BEHINDBLUELINES)
|| (airfieldinfo[i].northnodes[0]->status == FRONTLINE)
|| (airfieldinfo[i].northnodes[1]->status == FRONTLINE)
)
{
if ( (airfieldinfo[i].northnodes[0]->supplyline->initiative == BLUEATTACKING)
|| (airfieldinfo[i].northnodes[1]->supplyline->initiative == BLUEATTACKING)
)
airfieldinfo[i].days++;
if (airfieldinfo[i].days == 1)
MMC.DisDayEntry(Debrief::DISCARDTARGUID, airfieldinfo[i].airfield, Debrief::T_Airfield04_H);
elseif (RedAcAtAirfield(airfieldinfo[i].airfield) != 0)
MMC.DisDayEntry(Debrief::DISCARDTARGUID, airfieldinfo[i].airfield, Debrief::T_Airfield05_H);
}else
{
airfieldinfo[i].days = 0;
}
}
i++;
}
}
//컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴
//Procedure RetreatOneNode
//Author R. Hyde
//Date 12/1/99
//
//Description
//
//Inputs
//
//Returns
//
//------------------------------------------------------------------------------
void SupplyTree::RetreatOneNode()
{
for (int front=0;front<3;front++)
if (supplylines[front]->frontline->type==BATTLEFIELD)
RetreatOneNode(supplylines[front]);
}
//컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴
//Procedure RetreatOneNode
//Author R. Hyde
//Date Tue 11 Mar 1997
//
//Description
//
//Inputs
//
//Returns
//
//------------------------------------------------------------------------------
void SupplyTree::RetreatOneNode(SupplyLine* SL)
{
//DEADCODE RDH 24/03/99 if (SL->frontline->route[0]->supplier == &N1_7_Pyongyang)
//DEADCODE RDH 24/03/99 MMC.specialeventbits |= CAMPAIGNWONENTEREDPYONGYANG;
//DEADCODE RDH 24/03/99 else
//DEADCODE RDH 24/03/99 SL->frontline = SL->frontline->route[0]->supplier;
//N1_6_Sukchon is one above
//last battlefield
SL->ExitBf();
SL->frontline = SL->frontline->route[0]->supplier;
SL->initiative=BLUEINITIATIVE;
}
//컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴
//Procedure GenerateSupplyDIS
//Author R. Hyde
//Date //RDH 09/03/99
//
//Description
//
//Inputs
//
//Returns
//
//------------------------------------------------------------------------------
void SupplyTree::GenerateSupplyDIS()
{
SupplyNode* currnode = CurrDisNode;
do
{
NodeType type;
if (currnode)
type = currnode->type;
if ( (currnode->type == LASTONE)
)
currnode = FirstNode;
else
currnode = currnode->next;
if ( (currnode->associated_town != NULL)
&& (currnode->maxstorestonnes > STORES_INITALMEDIUMSETTLEMENT)
&& ((3 * currnode->currentstores) > (currnode->maxstorestonnes * 4))
)
{
MMC.DisDayEntry(Debrief::DISCARDTARGUID, currnode->associated_town, Debrief::T_Supply00_H);
break;
}
}while (currnode != CurrDisNode);
CurrDisNode = currnode;
FrontLineSupplyDIS(&WestRoute);
FrontLineSupplyDIS(&CentralRoute);
FrontLineSupplyDIS(&EastRoute);
}
//컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴
//Procedure FrontLineSupplyDIS
//Author R. Hyde
//Date //RDH 09/03/99
//
//Description
//
//Inputs
//
//Returns
//
//------------------------------------------------------------------------------
void SupplyTree::FrontLineSupplyDIS(SupplyLine* SL)
{
if (SL->frontline->currentstores < STORES_TOSUPPORTASSAULT)
MMC.DisDayEntry(Debrief::DISCARDTARGUID, SL->frontline->associated_item, Debrief::T_Supply01_H);
else
MMC.DisDayEntry(Debrief::DISCARDTARGUID, SL->frontline->associated_item, Debrief::T_Supply02_H);
if (SL->frontline->status != FRONTLINE)
{
if (SL->frontline->currentstores > STORES_TOPREPAREASSAULT)
MMC.DisDayEntry(Debrief::TARGUID, SL->frontline->associated_item, Debrief::T_Army00_H);
else if (SL->frontline->currentstores < STORES_BLUEPREPAREATTACK)
MMC.DisDayEntry(Debrief::TARGUID, SL->frontline->associated_item, Debrief::T_Army05_H);
}
}
static const int forcenames[3][2][TeamDef::MAXFORCETYPES]=
{ //TROOPSONLY,MORTAR,MORTARTRUCK,TANKS,ARTILLARY
{/*WR*/ {IDS_L_WR_TROOPS,IDS_L_WR_MORTAR,IDS_L_WR_MORTARTRUCK,IDS_WR_TANKS,IDS_WR_ARTILLARY},
/*WB*/ {IDS_L_WB_TROOPS,IDS_L_WB_MORTAR,IDS_L_WB_MORTARTRUCK,IDS_WB_TANKS,IDS_WB_ARTILLARY}},
{/*CR*/ {IDS_L_CR_TROOPS,IDS_L_CR_MORTAR,IDS_L_CR_MORTARTRUCK,IDS_CR_TANKS,IDS_CR_ARTILLARY},
/*CB*/ {IDS_L_CB_TROOPS,IDS_L_CB_MORTAR,IDS_L_CB_MORTARTRUCK,IDS_CB_TANKS,IDS_CB_ARTILLARY}},
{/*ER*/ {IDS_L_ER_TROOPS,IDS_L_ER_MORTAR,IDS_L_ER_MORTARTRUCK,IDS_ER_TANKS,IDS_ER_ARTILLARY},
/*EB*/ {IDS_L_EB_TROOPS,IDS_L_EB_MORTAR,IDS_L_EB_MORTARTRUCK,IDS_EB_TANKS,IDS_EB_ARTILLARY}},
};
//컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴
//Procedure InitiateBf
//Author R. Hyde
//Date Thu 6 Mar 1997
//
//Description
//
//Inputs
//
//Returns
//
//------------------------------------------------------------------------------
void SupplyLine::InitiateBf()
{
int slnum;
if (this==&SupplyTree::WestRoute)
slnum=0;
else
if (this==&SupplyTree::CentralRoute)
slnum=1;
else
////if (this==&SupplyTree::EastRoute)
slnum=2;
if (slnum!=2) //JIM 10/06/99
if (initiative==REDATTACKING)
{
MMC.DisDayEntry(Debrief::TARGUID,frontline->associated_item,frontline->bluefrontBF->startdis);
if (groundbattle.LoadBattleNodes(frontline->bluefrontBF->nodetree))
{
groundbattle.NewSetupFirstDay(forcenames[slnum][0],forcenames[slnum][1],frontline->maxstorestonnes*0.50,frontline->currentstores);
groundbattle.NextAttackDecisions();
}
}
else
{
MMC.DisDayEntry(Debrief::TARGUID,frontline->associated_item,frontline->redfrontBF->startdis);
frontline->currentstores+=frontline->maxstorestonnes*0.30;//DAW 02Sep99
if (groundbattle.LoadBattleNodes(frontline->redfrontBF->nodetree))
{
groundbattle.NewSetupFirstDay(forcenames[slnum][1],forcenames[slnum][0],frontline->currentstores,frontline->maxstorestonnes*0.50);
groundbattle.NextAttackDecisions();
}
}
}
void SupplyLine::ExitBf()
{
for (int t=0;t<groundbattle.MAXTEAMS;t++)
groundbattle.teamlist[t].strength=0;
groundbattle.usednodes=0;
groundbattle.usedteams=0;
}
//DEADCODE JIM 18/05/99 //컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴
//DEADCODE JIM 18/05/99 //Procedure UpdateBf
//DEADCODE JIM 18/05/99 //Author R. Hyde
//DEADCODE JIM 18/05/99 //Date Thu 6 Mar 1997
//DEADCODE JIM 18/05/99 //
//DEADCODE JIM 18/05/99 //Description
//DEADCODE JIM 18/05/99 //
//DEADCODE JIM 18/05/99 //Inputs
//DEADCODE JIM 18/05/99 //
//DEADCODE JIM 18/05/99 //Returns
//DEADCODE JIM 18/05/99 //
//DEADCODE JIM 18/05/99 //------------------------------------------------------------------------------
//DEADCODE JIM 18/05/99 void SupplyTree::UpdateBf()
//DEADCODE JIM 18/05/99 {
//DEADCODE JIM 18/05/99
//DEADCODE JIM 18/05/99 }
//DEADCODE JIM 18/05/99
//컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴
//Procedure WithDrawSupplies
//Author R. Hyde
//Date Tue 11 Mar 1997
//
//Description
//
//Inputs
//
//Returns
//
//------------------------------------------------------------------------------
void SupplyTree::WithDrawSupplies(SupplyNode* node)
{
//launch some battle fields to indicate withdrawal
//messages to player
//
for (int route=0;route<3;route++)
if (node->route[route] && node->route[route]->suppliee)
if (node->currentstores/5>node->route[route]->maxcapacitysummer)
node->route[route]->supplier->currentstores+=node->route[route]->maxcapacitysummer;
else
node->route[route]->supplier->currentstores+=node->currentstores/5;
node->currentstores=0;
}
//컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴
//Procedure StoreLaunchPossible
//Author R. Hyde
//Date Tue 11 Mar 1997
//
//Description
//
//Inputs
//
//Returns
//
//------------------------------------------------------------------------------
SWord SupplyTree::StoreLaunchPossible(SupplyRoute* currroute)
{
SWord capacity = currroute->maxcapacitysummer;
capacity -= currroute->storeslaunched;
return (capacity);
}
//컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴
//Procedure SupplyNode
//Author R. Hyde
//Date Tue 11 Mar 1997
//
//Description
//
//Inputs
//
//Returns
//
//------------------------------------------------------------------------------
void SupplyTree::SupplyThisNode(SupplyNode* node,SWord priority,SWord requirement)
{
SWord i = 0,storelaunchrequest;
SupplyRoute* currroute;
while ( (i < NUM_OF_SUPPLYROUTES)
&& (requirement != 0)
)
{
currroute = node->route[i];
while ( (currroute != NULL)
&& (requirement != 0)
)
{
if ( (currroute->status == SR_ACTIVE)
&& (!currroute->associated_brdg || currroute->attackstats.damagelevel<90)
)
{
if (currroute->supplier->currentstores > 0) //RDH 14/05/99
{
if (currroute->supplier->currentstores < requirement)
storelaunchrequest = currroute->supplier->currentstores;
else
storelaunchrequest = requirement;
if ((StoreLaunchPossible(currroute)) < storelaunchrequest)
storelaunchrequest = StoreLaunchPossible(currroute);
if (storelaunchrequest < 0)
storelaunchrequest = 0;
if (storelaunchrequest == 0)
MMC.DisDayEntry(Debrief::DISCARDTARGUID, currroute->supplier->associated_item, Debrief::T_Supply02_H);
currroute->supplier->priority =
(SupplyPriority)(currroute->supplier->priority+
priority*storelaunchrequest/requirement);
requirement -= storelaunchrequest;
currroute->supplier->currentstores -= storelaunchrequest;
currroute->storeslaunched += storelaunchrequest;
}else
currroute->supplier->priority = (SupplyPriority)priority;
}
currroute = currroute->alternateroute;
};
i++;
}
//DeadCode DAW 21May99 if (requirement > 0)
node->serviced = TRUE; //perhaps unsuccessfully
}
//컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴
//Procedure AdvanceOneNode
//Author R. Hyde
//Date 12/1/99
//
//Description
//
//Inputs
//
//Returns
//
//------------------------------------------------------------------------------
void SupplyTree::AdvanceOneNode()
{
for (int front=0;front<3;front++)
if (supplylines[front]->frontline->type==BATTLEFIELD)
AdvanceOneNode(supplylines[front]);
}
//컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴
//Procedure AdvanceOneNode
//Author R. Hyde
//Date Tue 11 Mar 1997
//
//Description
//
//Inputs
//
//Returns
//
//------------------------------------------------------------------------------
void SupplyTree::AdvanceOneNode(SupplyLine* SL)
{
//DEADCODE RDH 24/03/99 if (SL->frontline->route[0]->suppliee == &N3_1_Taejon)
//DEADCODE RDH 24/03/99 MMC.specialeventbits |= CAMPAIGNLOSTTAEJONOVERRUN;
//DEADCODE RDH 24/03/99 else
//DEADCODE RDH 24/03/99 SL->frontline = SL->frontline->forward->suppliee;
//N3_3_Chonan is behind blue's last battlefield
SL->ExitBf();
SL->frontline = SL->frontline->forward->suppliee;
SL->initiative=REDINITIATIVE;
}
//컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴
//Procedure StoresUsage
//Author R. Hyde
//Date Mon 17 Mar 1997
//
//Description
//
//Inputs
//
//Returns
//
//------------------------------------------------------------------------------
SWord SupplyTree::StoresUsage (SupplyLine* SL,SupplyNode* node)
{
SWord retval;
if (node == SL->frontline)
{
return -(30+(node->attackstats.damagelevel*node->maxstorestonnes/400));
}else
{
retval = 0;
}
return (retval);
}
//////////////////////////////////////////////////////////////////////
//
// Function: AllFrontOnBattleNodes
// Date: 29/06/99
// Author: JIM
//
//Description: Checks all front are on battle nodes.
// If non-zero checks they are on same battle nodes
//
//////////////////////////////////////////////////////////////////////
bool SupplyTree::AllFrontOnBattleNodes(int frontnum)
{
if ( WestRoute.frontline->type==NOCONTEST
|| CentralRoute.frontline->type==NOCONTEST
|| EastRoute.frontline->type==NOCONTEST
)
return false;
if (frontnum)
if ( WestRoute.frontline->redfrontBF->frontnum!=frontnum
|| CentralRoute.frontline->redfrontBF->frontnum!=frontnum
|| EastRoute.frontline->redfrontBF->frontnum!=frontnum
)
return false;
return true;
}
//컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴
//Procedure ProcessFrontLineRequest
//Author R. Hyde
//Date Tue 11 Mar 1997
//
//Description
//
//Inputs
//
//Returns
//
//------------------------------------------------------------------------------
void SupplyTree::ProcessFrontLineRequest (SupplyLine* SL)
{
SWord supplies;
SWord requirement;
supplies = FindModifiedSupplies(SL->frontline);
requirement = SL->frontline->maxstorestonnes - SL->frontline->currentstores
- StoresUsage (SL,SL->frontline);
if (Miss_Man.currcampaignnum!=Miss_Man.F51_CAMPAIGN)
SL->FACActive=(Math_Lib.rnd()>20000);
else
SL->FACActive=true;
switch (SL->initiative)
{
case BLUEINITIATIVE:
{
switch (SL->frontline->type)
{
case NOCONTEST:
{
if (supplies < SL->frontline->maxstorestonnes*0.05)
RetreatOneNode(SL);
else
WithDrawSupplies(SL->frontline);
break;
}
case BATTLEFIELD:
{
SupplyThisNode(SL->frontline,SP_HIGH,requirement);
if (supplies > (3*SL->frontline->maxstorestonnes/4))
{
SL->initiative = REDINITIATIVE;
}else
if (supplies < (2*SL->frontline->maxstorestonnes/4))
if (AllFrontOnBattleNodes())
{
SL->initiative = BLUEATTACKING;
SL->InitiateBf();
}
break;
}
}
break;
}
case REDINITIATIVE:
{
switch (SL->frontline->type)
{
case NOCONTEST:
{
if (supplies >= SL->frontline->maxstorestonnes*0.2)
AdvanceOneNode(SL);
else
{ //Nasty cheet. I don't want to take all day about the advancement or it will go wrong!
supplies=SL->frontline->maxstorestonnes*0.21; //DAW 26/06/99
SupplyThisNode(SL->frontline,SP_HIGH,requirement);
}
break;
}
case BATTLEFIELD:
{
if (supplies >= SL->frontline->maxstorestonnes*0.95)
{
if (AllFrontOnBattleNodes())
{
SL->initiative = REDATTACKING;
SL->InitiateBf();
}
}
else
if(supplies < (STORES_TODISCOURAGEBLUEATTACK*0.8+SL->frontline->maxstorestonnes*0.3))
{
SL->initiative = BLUEINITIATIVE;
}
requirement = STORES_TOSUPPORTASSAULT;
SupplyThisNode(SL->frontline,SP_HIGH,requirement);
break;
}
}
break;
}
case BLUEATTACKING:
{
switch (SL->frontline->type)
{
case NOCONTEST:
{
SL->initiative = BLUEINITIATIVE;
break;
}
case BATTLEFIELD:
{
//DEADCODE JIM 19/06/99 ALL THESE CONDITIONS HANDLED INSIDE GROUND BATTLE PROCESSING
//DEADCODE JIM 19/06/99 // if (supplies > (3*SL->frontline->maxstorestonnes/4))
//DEADCODE JIM 19/06/99 // { THIS IS NOW BLUELOST
//DEADCODE JIM 19/06/99 // SL->initiative = REDATTACKING;
//DEADCODE JIM 19/06/99 // if (Math_Lib.rnd(2))
//DEADCODE JIM 19/06/99 // MMC.DisDayEntry(Debrief::TARGUID, SL->frontline->associated_item, Debrief::T_Army04_H);
//DEADCODE JIM 19/06/99 // else
//DEADCODE JIM 19/06/99 // MMC.DisDayEntry(Debrief::TARGUID, SL->frontline->associated_item, Debrief::T_Army07_H);
//DEADCODE JIM 19/06/99 // }elseif (supplies <(SL->frontline->maxstorestonnes/4))
//DEADCODE JIM 19/06/99 // { THIS IS NOW BLUEWON
//DEADCODE JIM 19/06/99 // if (SL!=&EastRoute) //JIM 10/06/99
//DEADCODE JIM 19/06/99 // {
//DEADCODE JIM 19/06/99 // MMC.DisDayEntry(Debrief::TARGUID, SL->frontline->associated_item, SL->frontline->bluefrontBF->advancedis);
//DEADCODE JIM 19/06/99 // RetreatOneNode();
//DEADCODE JIM 19/06/99 // SL->initiative = BLUEINITIATIVE;
//DEADCODE JIM 19/06/99 // }
//DEADCODE JIM 19/06/99 // }
//DEADCODE JIM 19/06/99 if (supplies<STORES_TODISCOURAGEBLUEATTACK)
//DEADCODE JIM 19/06/99 {
//DEADCODE JIM 19/06/99 if (SL!=&EastRoute)
//DEADCODE JIM 19/06/99 SL->initiative=BLUEWON;
//DEADCODE JIM 19/06/99 }
//DEADCODE JIM 19/06/99 else
{
SupplyThisNode(SL->frontline,SP_HIGH,requirement);
}
break;
}
}
break;
}
case BLUELOST:
{
if (Math_Lib.rnd(2))
MMC.DisDayEntry(Debrief::TARGUID, SL->frontline->associated_item, Debrief::T_Army04_H);
else
MMC.DisDayEntry(Debrief::TARGUID, SL->frontline->associated_item, Debrief::T_Army07_H);
SL->ExitBf();
SL->initiative=REDINITIATIVE;
}
break;
case REDATTACKING:
{
switch (SL->frontline->type)
{
case NOCONTEST:
{
SL->initiative = REDINITIATIVE;
break;
}
case BATTLEFIELD:
{
//DEADCODE JIM 19/06/99 ALL THESE CONDITIONS HANDLED INSIDE GROUND BATTLE PROCESSING
//DEADCODE JIM 19/06/99 // if (supplies >= SL->frontline->maxstorestonnes)
//DEADCODE JIM 19/06/99 // { THIS IS NOW REDWON
//DEADCODE JIM 19/06/99 // if (SL!=&EastRoute) //JIM 10/06/99
//DEADCODE JIM 19/06/99 // {
//DEADCODE JIM 19/06/99 // MMC.DisDayEntry(Debrief::TARGUID, SL->frontline->associated_item, SL->frontline->redfrontBF->advancedis);
//DEADCODE JIM 19/06/99 // AdvanceOneNode();
//DEADCODE JIM 19/06/99 // SL->initiative = REDINITIATIVE;
//DEADCODE JIM 19/06/99 // SupplyThisNode(SL->frontline,SP_HIGH,requirement);
//DEADCODE JIM 19/06/99 // }
//DEADCODE JIM 19/06/99 // }
//DEADCODE JIM 19/06/99 // elseif (supplies > (SL->frontline->maxstorestonnes/4))
//DEADCODE JIM 19/06/99 if (supplies<STORES_TODISCOURAGEBLUEATTACK)
//DEADCODE JIM 19/06/99 {
//DEADCODE JIM 19/06/99 if (SL!=&EastRoute)
//DEADCODE JIM 19/06/99 SL->initiative = REDLOST;
//DEADCODE JIM 19/06/99 }
//DEADCODE JIM 19/06/99 else
{
//DEADCODE JIM 18/05/99 UpdateBf();
SupplyThisNode(SL->frontline,SP_HIGH,requirement);
}
//DEADCODE JIM 19/06/99 // else
//DEADCODE JIM 19/06/99 // {
//DEADCODE JIM 19/06/99 // SL->ExitBf();
//DEADCODE JIM 19/06/99 // SL->initiative = BLUEINITIATIVE;
//DEADCODE JIM 19/06/99 // if (Math_Lib.rnd(2))
//DEADCODE JIM 19/06/99 // MMC.DisDayEntry(Debrief::TARGUID, SL->frontline->associated_item, Debrief::T_Army02_H);
//DEADCODE JIM 19/06/99 // else
//DEADCODE JIM 19/06/99 // MMC.DisDayEntry(Debrief::TARGUID, SL->frontline->associated_item, Debrief::T_Army03_H);
//DEADCODE JIM 19/06/99 //DEADCODE JIM 18/05/99 RetreatOneNode();
//DEADCODE JIM 19/06/99 // }
break;
}
}
break;
}
case REDLOST:
{
if (Math_Lib.rnd(2))
MMC.DisDayEntry(Debrief::TARGUID, SL->frontline->associated_item, Debrief::T_Army02_H);
else
MMC.DisDayEntry(Debrief::TARGUID, SL->frontline->associated_item, Debrief::T_Army03_H);
SL->ExitBf();
SL->initiative=BLUEINITIATIVE;
}
break;
case REDWON:
{ //not handled here!
}
break;
case BLUEWON:
{ //not handled here!
}
break;
}
//DEADCODE JIM 10/06/99 SL->groundbattle.NextAttackDecisions();
}
//컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴
//Procedure ProcessFrontLineRequests
//Author R. Hyde
//Date Thu 6 Mar 1997
//
//Description
//
//Inputs
//
//Returns
//
//------------------------------------------------------------------------------
void SupplyTree::ProcessFrontLineRequests ()
{
ProcessFrontLineRequest (&WestRoute);
ProcessFrontLineRequest (&EastRoute);
ProcessFrontLineRequest (&CentralRoute);
if (WestRoute.initiative==REDWON || EastRoute.initiative==REDWON || CentralRoute.initiative==REDWON)
{
for (int fr=0;fr<3;fr++)
if (supplylines[fr]->initiative==REDWON)
MMC.DisDayEntry(Debrief::TARGUID, supplylines[fr]->frontline->associated_item, supplylines[fr]->frontline->bluefrontBF->advancedis);
AdvanceOneNode();
}
else
if (WestRoute.initiative==BLUEWON || EastRoute.initiative==BLUEWON || CentralRoute.initiative==BLUEWON)
{
for (int fr=0;fr<3;fr++)
if (supplylines[fr]->initiative==BLUEWON)
MMC.DisDayEntry(Debrief::TARGUID, supplylines[fr]->frontline->associated_item, supplylines[fr]->frontline->redfrontBF->advancedis);
RetreatOneNode();
}
}
//컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴
//Procedure SupplyHPNodes
//Author R. Hyde
//Date Thu 6 Mar 1997
//
//Description
//
//Inputs
//
//Returns
//
//------------------------------------------------------------------------------
void SupplyTree::SupplyHPNodes ()
{
SupplyPriority priority;
SupplyNode* currnode;
SupplyNode* hp_node=NULL;
SWord requirement;
do
{
priority = SP_NONE;
currnode = &N0_0_Dangdong;
while (currnode->next->type != LASTONE)
{
if ( (currnode->serviced == FALSE)
&& (currnode->status!=BEHINDBLUELINES) //don't supply blue nodes
&& (currnode->priority > priority)
&& ( currnode->status!=FRONTLINE //don't supply blue advance nodes
|| currnode->type!=NOCONTEST //JIM 29/06/99
|| currnode->supplyline->initiative!=BLUEINITIATIVE
)
)
{
priority = currnode->priority;
hp_node = currnode;
}
currnode = currnode->next;
};
if (priority != SP_NONE)
{
requirement = hp_node->maxstorestonnes -
hp_node->currentstores;
SupplyThisNode(hp_node,(SWord) priority,requirement);
}
}
while (priority != SP_NONE);
}
//컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴
//Procedure ResetPriorityAndServicedFlag
//Author R. Hyde
//Date Wed 12 Mar 1997
//
//Description
//
//Inputs
//
//Returns
//
//------------------------------------------------------------------------------
void SupplyTree::ResetPriorityAndServicedFlag()
{
SupplyNode* currnode;
currnode = &N0_0_Dangdong;
while (currnode->next->type != LASTONE)
{
if (currnode->currentstores == currnode->maxstorestonnes)
{
currnode->priority = SP_NONE;
}
currnode->serviced = FALSE;
currnode = currnode->next;
}
}
//컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴
//Procedure ProcessStoresDestroyed
//Author R. Hyde
//Date //RDH 25/05/99
//
//Description
// On starting a mission put last store_destroyed in
// stores_destroyed_today and then zero
//
// store_destroyed can then be used for stores destroyed on mission
// stores_destroyed_today is used in node review at the end of the day
// stores_destroyed needs to be retained because it is used in debrief
//Inputs
//
//Returns
//
//------------------------------------------------------------------------------
void SupplyTree::ProcessStoresDestroyed ()
{
SupplyRoute* currroute;
currroute= &R0_0_1Rail0;
while (currroute->next->status != SR_LASTONE)
{
currroute->stores_destroyed_today += currroute->stores_destroyed;
currroute->stores_destroyed = 0;
currroute = currroute->next;
}
for (int front=0;front<3;front++)
for (int t=0;t<supplylines[front]->groundbattle.usedteams;t++)
{
supplylines[front]->groundbattle.teamlist[t].lastlosses=0;
supplylines[front]->groundbattle.teamlist[t].lastlostforces=0;
}
}
//컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴
//Procedure ProcessStoresArrival
//Author R. Hyde
//Date Wed 12 Mar 1997
//
//Description
//
//Inputs
//
//Returns
//
//------------------------------------------------------------------------------
void SupplyTree::ProcessStoresArrival ()
{
SWord storagespace,availablestores;
SupplyRoute* currroute;
currroute= &R0_0_1Rail0;
while (currroute->next->status != SR_LASTONE)
{
if (currroute->suppliee)
{
storagespace = currroute->suppliee->maxstorestonnes -
currroute->suppliee->currentstores;
//DEADCODE DAW 25/06/99 - StoresUsage (currroute->suppliee->supplyline,currroute->suppliee);
if (storagespace <= 0)
{
currroute->suppliee->currentstores = currroute->suppliee->maxstorestonnes;
//DEADCODE DAW 25/06/99 - StoresUsage (currroute->suppliee->supplyline,currroute->suppliee);
}else
{
availablestores = (currroute->storeslaunched
- currroute->stores_destroyed_today);
if (availablestores > storagespace)
availablestores = storagespace;
currroute->suppliee->priority = (SupplyPriority)
(currroute->suppliee->priority*(storagespace - availablestores)/
storagespace);
//if damagelevel high and stores added then storing in damaged wh
if ( (currroute->suppliee->currentstores == 0)
&& (currroute->suppliee->attackstats.damagelevel > 60) //RDH 17/06/99
&& (availablestores > 0 )
)
MMC.DisDayEntry(Debrief::TARGUID, currroute->suppliee->associated_item, Debrief::T_USE_DAMAGED_WH_H);
currroute->suppliee->currentstores += availablestores;
if (currroute->suppliee->currentstores > ((96 * STORES_MAXSUPPLY) / 128))
MMC.DisDayEntry(Debrief::DISCARDTARGUID, currroute->suppliee->associated_item, Debrief::T_Supply00_H);
}
currroute->totalstores_destroyed += currroute->stores_destroyed_today;
//inc aaalevel if (currroute->stores_destroyed != 0)
// currroute->consecutive_days_attacked++;
// else
// currroute->consecutive_days_attacked = 0;
currroute->stores_destroyed_today =
currroute->storeslaunched = 0;
if (currroute->recommision_time <= MMC.debrief.currlogday)
currroute->status = SR_ACTIVE;
if (currroute->totalstores_destroyed > STORES_NO_TO_DESTROY_TO_REST_ROUTE)
{
currroute->totalstores_destroyed = 0;
currroute->recommision_time = MMC.debrief.currlogday + 5;
currroute->status = SR_RESTING;
}
//TempCode RDH 12Mar97 if (currroute->recommision_time < Time)
//TempCode RDH 12Mar97 status = SR_ACTIVE;
//TempCode RDH 12Mar97 if (currroute->totalstores_destroyed > STORES_NO_TO_DESTROY_TO_REST_ROUTE)
//TempCode RDH 12Mar97 {
//TempCode RDH 12Mar97 currroute->totalstores_destroyed = 0;
//TempCode RDH 12Mar97 currroute->recommision_time = Time + 5days;
//TempCode RDH 12Mar97 currroute->status = SR_RESTING;
//TempCode RDH 12Mar97 }
}
currroute = currroute->next;
}
}
//컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴
//Procedure FrontLineStoresUsage
//Author R. Hyde
//Date Wed 12 Mar 1997
//
//Description
//
//Inputs
//
//Returns
//
//------------------------------------------------------------------------------
void SupplyTree::FrontLineStoresUsage (SupplyLine* SL)
{
SL->frontline->currentstores += StoresUsage (SL,SL->frontline);
if (SL->frontline->currentstores < 0)
SL->frontline->currentstores = 0;
}
//컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴
//Procedure ResetFirstSupplyNode
//Author R. Hyde
//Date Thu 13 Mar 1997
//
//Description
//
//Inputs
//
//Returns
//
//------------------------------------------------------------------------------
void SupplyTree::ResetFirstSupplyNode (SupplyLine* SL)
{
SL->firstnode->currentstores = SL->firstnode->maxstorestonnes;
SL->firstnode->serviced = TRUE;
}
//컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴
//Procedure ProcessPreviousDaysSupplies
//Author R. Hyde
//Date Wed 12 Mar 1997
//
//Description
//
//Inputs
//
//Returns
//
//------------------------------------------------------------------------------
void SupplyTree::ProcessPreviousDaysSupplies()
{
ResetPriorityAndServicedFlag();
FrontLineStoresUsage (&WestRoute);
FrontLineStoresUsage (&CentralRoute);
FrontLineStoresUsage (&EastRoute);
ProcessStoresArrival ();
ResetFirstSupplyNode (&WestRoute);
ResetFirstSupplyNode (&CentralRoute);
ResetFirstSupplyNode (&EastRoute);
}
//컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴
//Procedure UpDateAttacksStructure()
//Author R. Hyde
//Date 7/1/99
//
//Description
//
//Inputs
//
//Returns
//
//------------------------------------------------------------------------------
Attacks* SupplyTree::GetAttacks(UniqueID uid)
{
SupplyTree::Supply2UID rel;
SupplyNode* node=SupplyTree::FindSupplyNodeForItem(uid,&rel);
return GetAttacks(uid,node,rel);
}
Attacks* SupplyTree::GetAttacks(UniqueID uid,SupplyNode* node,SupplyTree::Supply2UID rel)
{
Attacks* att=NULL;
if (node)
switch (rel)
{ //S2U_NOTHERE=0,S2U_MAIN,S2U_AF0,S2U_AF1,S2U_AF2,S2U_ROUTE0,S2U_ROUTE1,S2U_ROUTE2
case S2U_MAIN:
{
if (uid==node->associated_item)
att = &node->attackstats;
else
att = &node->attackstown;
break;
}
case S2U_ROUTE0:
case S2U_ROUTE1:
case S2U_ROUTE2:
{
att = &FindBridge(uid,
node->route[rel-SupplyTree::S2U_ROUTE0])->attackstats;
break;
}
case S2U_AF0:
case S2U_AF1:
case S2U_AF2:
{
AirFieldInfo* af = SupplyTree::FindAirfieldForItem(uid);
att=&af->attackstats;
break;
}
}
return att;
}
void SupplyTree::UpDateAttacksStructure()
{
for (int i=0;i<Profile::MAX_PACKS;i++)
{
if (Todays_Packages.pack[i][0][0].uid)
{
SupplyTree::Supply2UID rel;
SupplyNode* node=SupplyTree::FindSupplyNodeForItem(Todays_Packages.pack[i].packagetarget,&rel);
Attacks* att;
if (node)
{
att=GetAttacks(Todays_Packages.pack[i].packagetarget,node,rel);
//0, 32 92 152 212 255
enum {aaalevelcut=100,aaaleveldelta=60};
if (att->aaalevel < 32)
att->aaalevel = 32;
else if (att->aaalevel > 195)
att->aaalevel = 255;
else
if (att->aaalevel > aaalevelcut)
att->aaalevel += aaaleveldelta;
else
{ //if any 1 node goes through 150 then test all nodes to get message
att->aaalevel += aaaleveldelta;
if (att->aaalevel > aaalevelcut)
switch (rel)
{
case S2U_MAIN:
{ //check all nodes
for (SupplyNode* node=FirstNode;node->next!=node;node=node->next)
if (node->attackstats.aaalevel<aaalevelcut)
break;
if (node->next==node)
MMC.DisDayEntry(Debrief::TARGUID,Todays_Packages.pack[i].packagetarget,Debrief::D_Flak01_H); break;
}
break;
case S2U_ROUTE0:
case S2U_ROUTE1:
case S2U_ROUTE2:
{ //routes: check all rail or road as appropriate
SupplyRoute* route=FindBridge(Todays_Packages.pack[i].packagetarget,node->route[rel-SupplyTree::S2U_ROUTE0]);
int wagonsize=0;
if (route->associated_brdg)
for (route=FirstRoute;route->next!=route;route=route->next)
{
if (route->associated_brdg && route->attackstats.aaalevel<aaalevelcut)
break;
}
else
{
wagonsize=route->storespermobile;
for (route=FirstRoute;route->next!=route;route=route->next)
{
if (!route->associated_brdg && route->storespermobile==wagonsize && route->attackstats.aaalevel<aaalevelcut)
break;
}
}
if (route->next==route)
switch (wagonsize)
{
case 0: MMC.DisDayEntry(Debrief::TARGUID,Todays_Packages.pack[i].packagetarget,Debrief::D_Flak03_H); break;
case STORES_TRUCK: MMC.DisDayEntry(Debrief::TARGUID,Todays_Packages.pack[i].packagetarget,Debrief::D_Flak02_H); break;
case STORES_TRAIN: MMC.DisDayEntry(Debrief::TARGUID,Todays_Packages.pack[i].packagetarget,Debrief::D_Flak00_H); break;
}
}
break;
case S2U_AF0:
case S2U_AF1:
case S2U_AF2:
{ //check all red airfields
AirFieldInfo* af = SupplyTree::FindAirfieldForItem(Todays_Packages.pack[i].packagetarget);
att=&af->attackstats;
}
break;
}
}
att->daylasthit = MMC.debrief.currlogday+1; //0 indicates never hit
att->actypelasthit = Todays_Packages.pack[i][0][0].squadron;
}
}
}
}
//컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴
//Procedure DestroyedStores
//Author R. Hyde
//Date //RDH 27/05/99
//
//Description
//
//Inputs
//
//Returns
//
//------------------------------------------------------------------------------
int SupplyTree::DestroyedStores(SupplyNode* node)
{
int destroyedstores;
int tokens = node->attackstats.tokensinmw + node->attackstats.tokensinbf;
if (tokens <= 0)
destroyedstores = 0;
else
{
destroyedstores = node->currentstores * node->attackstats.damagedtokens;
destroyedstores = destroyedstores/tokens;
}
return (destroyedstores);
}
//컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴
//Procedure RemoveDestroyedStores
//Author R. Hyde
//Date //RDH 27/05/99
//
//Description
//
//Inputs
//
//Returns
//
//------------------------------------------------------------------------------
void SupplyTree::RemoveDestroyedStores()
{
SupplyNode* currnode;
currnode = &N0_0_Dangdong;
while (currnode->next->type != LASTONE)
{
currnode->currentstores -= DestroyedStores(currnode);
if (currnode->currentstores < 0) //RDH 22/06/99
currnode->currentstores = 0; //RDH 22/06/99
currnode = currnode->next;
}
}
//컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴
//Procedure NodeReview
//Author R. Hyde
//Date Mon 10 Mar 1997
//
//Description
//
//Inputs
//
//Returns
//
//------------------------------------------------------------------------------
void SupplyTree::NodeReview ()
{
ProcessPreviousDaysSupplies();
ProcessFrontLineRequests();
SupplyHPNodes();
//DEADCODE RDH 23/03/99 ProcessAirFields();
GenerateSupplyDIS();
}
//higher value are higher priority. Mul by 10 to give full priority.
//컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴
//Procedure NodeReview
//Author R. Hyde
//Date Mon 10 Mar 1997
//
//Description
//
//Inputs
//
//Returns
//
//------------------------------------------------------------------------------
bool SupplyTree::ChkSpringOffensiveOver()
{
if ( (WestRoute.frontline == &N1_6_Sukchon)
|| (WestRoute.frontline == &N3_3_Chonan)
|| (CentralRoute.frontline == &N1_29_Kangdong)
|| (CentralRoute.frontline == &N3_5_Chechon)
|| (EastRoute.frontline == &N1_20_Kowon)
|| (EastRoute.frontline == &N2_28_Samchok)
)
return (true);
else
return (false);
}
//컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴
//Procedure NodeReview
//Author R. Hyde
//Date Mon 10 Mar 1997
//
//Description
//
//Inputs
//
//Returns
//
//------------------------------------------------------------------------------
int SupplyTree::FindBattleIndex()
{
SupplyRoute* currroute;
int index = 1;
if (WestRoute.frontline == &N1_6_Sukchon)
index = 0;
else if (WestRoute.frontline == &N3_3_Chonan)
index = 7;
else
{
int count = 0;
SupplyNode* currnode = WestRoute.firstnode;
while ( (count < 80)
&& (currnode->forward != NULL)
&& (WestRoute.frontline != currnode)
)
{
if (currnode->type == BATTLEFIELD)
index++;
currroute = currnode->forward;
currnode = currroute->suppliee;
count++;
}
}
return(index);
}
enum ConflictDecisionPercents
{
MAX_DEAD=5, //force between 0..5% of army faced may as well be wiped
MAX_ALWAYS_WITHDRAW=20, //force between 5 and 20% will always withdraw
EXTRA_HURT_DEFENDERS=25,
MIN_FORWARD_TO_ATTACK=40, //won't move forward to attack next occ pos until got 40% their strength or better
MAX_RND_WITHDRAW_REINFORCE=40, //force between 20 and 40% will either wait for reinforcements or withdraw
MAX_ALWAYS_REINFORCE=60, //force between 40 and 70% of opp strength will always wait
MAX_RND_REINFORCE_ATTACK=90, //force between 70 and 90 may wait or go for it
MAX_SEND_REINFORCE=95, //won't send extra reinforcements above this fig
MAX_ATTACK_DONTSPLIT=400, //force over 4* can send reinforcements to others
/// MAX_ALWAYS_ATTACK=2000 //inverse of 5% - bigger force just goes for it
};
enum { PLAYER_PROPORTION_ATTACKER=45, //bigger means less player effect
PLAYER_PROPORTION_DEFENDER=35, //Holder gets applied as well.
PLAYER_PROPORTION_RETREAT=25,
PLAYER_PROPORTION_CONVOY=35,
PLAYER_PROPORTION_HOLDER=55,
ATTACK_PROPORTION_AUTO=20, //bigger means less ground battle effect
STORES_TO_TROOPS_INITIAL=8, //average - info only
STORES_TO_REDTROOPS_REINFORCE=3,
MAXSTORES_TO_BLUETROOPS_REINFORCE=8,
STORES_TROOPS_PER_PERIOD=140, //bigger means less stores used
OVERWHELMING_TROOPS_PROPORTION_WIN=20
};
inline bool SameSide(TeamDef* us,TeamDef* them) //BOTH MUST BE NON-NULL!
{ return (us->team==them->team); }
inline int CalcChanceMods(TeamDef* attacker,SuperBattleNode::IntraLink* attackpos,
TeamDef* defender,SuperBattleNode* defendpos)
{
int advmod=attackpos->TerrainAdvantage();
if (!(defendpos->flanks.nonlinks&defendpos->flanks.NOT_ML))
if (defendpos->flanks.leftnode->occupier)
if (SameSide(defender,defendpos->flanks.leftnode->occupier))
advmod+=10;
else
advmod-=10;
if (!(defendpos->flanks.nonlinks&defendpos->flanks.NOT_MR))
if (defendpos->flanks.rightnode->occupier)
if (SameSide(defender,defendpos->flanks.rightnode->occupier))
advmod+=10;
else
advmod-=10;
if (attacker->forcetype==attacker->TROOPSONLY)
advmod+=10;
if (attacker->forcetype==attacker->ARTILLARY)
advmod+=10;
if (defender->forcetype==defender->TROOPSONLY)
advmod-=10;
if (defender->forcetype==defender->ARTILLARY)
advmod-=20;
//Additional modifiers required for:
// distant artillary
return advmod;
}
inline int CalcAttackChance(TeamDef* attacker,SuperBattleNode::IntraLink* attackpos,
TeamDef* defender,SuperBattleNode* defendpos)
{
int advantage=attacker->strength*100/defender->strength;
int advmod=CalcChanceMods(attacker,attackpos,defender,defendpos);
return advantage+advmod;
}
inline int CalcDefendChance(TeamDef* attacker,SuperBattleNode::IntraLink* attackpos,
TeamDef* defender,SuperBattleNode* defendpos)
{
int advantage=defender->strength*100/attacker->strength;
int advmod=CalcChanceMods(attacker,attackpos,defender,defendpos);
return advantage-advmod;
}
bool Better(int h,int l)
{
if (l==h)
return (Math_Lib.rnd(2)==0);
else
return (h>l);
}
inline void MergeForces(TeamDef* benefitters,TeamDef* dissolvers)
{
if (benefitters->forcetype==TeamDef::TROOPSONLY
|| ( dissolvers->forcetype!=TeamDef::TROOPSONLY
&& dissolvers->strength>benefitters->strength
) )
benefitters->forcetype=dissolvers->forcetype;
benefitters->strength+=dissolvers->strength;
benefitters->lastlosses+=dissolvers->lastlosses;
benefitters->lastlostforces+=dissolvers->lastlostforces;
dissolvers->strength=-1;
}
bool BattleStruct::NextAttackDecision(TeamDef* us)
{ //returns true if force disbanded!
typedef TeamDef T;
T::Action decision=T::STAY_HERE;
T::Action nameddecision=T::STAY_HERE;
int routenum=0;
UniqueID teleloc=us->location;
UniqueID nextloc=us->location;
us->DiagnosticOutput("NextMove a");
SuperBattleNode* nextnode=us->node;
//this team is on team->node
SuperBattleNode* node=us->node;
TeamDef* them;
SuperBattleNode::IntraLink *fwd=&node->in,*back=&node->out;
us->namedaction=TeamDef::STAY_HERE; //in case nothing better gets set...
us->advantagepriority=us->strength/10;
if (us->team==T::HOME)
{ fwd=&node->out;back=&node->in; }
if (node)
if (node->occupier==us) //main node
{
if ((them=fwd->occupier)!=NULL)
if (SameSide(us,them))
{ //silly case: force in front will have to come back and merge with us
decision=T::STAY_HERE;
}
else
{ //enemy force ahead. Either defend or pull back
int attackadvantage=CalcDefendChance(them,fwd,us,node);
us->advantagepriority=attackadvantage;
if (attackadvantage<MAX_DEAD)
decision=T::LOSE_FORCE;
else if (attackadvantage<MAX_ALWAYS_WITHDRAW)
nameddecision=decision=T::RETREAT;
else if (attackadvantage<MAX_RND_WITHDRAW_REINFORCE && Math_Lib.rnd(2))
nameddecision=decision=T::RETREAT;
else if (attackadvantage<MAX_ATTACK_DONTSPLIT)
decision=T::STAY_HERE,nameddecision=T::DEFEND_ATTACK;
else
{ //can send some troops to other locations
decision=T::STAY_HERE,nameddecision=T::DEFEND_ATTACK; //NOT HANDLING SPLITS YET!
}
if (decision==T::RETREAT)
{ //may not be able to retreat - then stay here!
if (back->occupier)
if (SameSide(us,back->occupier))
{
nextloc=teleloc=back->uid;
decision=T::MERGE_FORCE;
}
else
decision=T::STAY_HERE,nameddecision=T::DEFEND_ATTACK;
else
if (us->team==T::HOME)
if (!node->innode)
decision=T::STAY_HERE,nameddecision=T::DEFEND_ATTACK;
else
{
SuperBattleNode::IntraLink* back2=&node->innode->out;
if (back2->occupier && !SameSide(us,back2->occupier))
decision=T::STAY_HERE,nameddecision=T::DEFEND_ATTACK;
else
{
decision=T::RETREAT;
teleloc=back->uid;
nextloc=back2->uid;
nextnode=node->innode;
}
}
else //away
if (!node->firstoutnode)
decision=T::STAY_HERE,nameddecision=T::DEFEND_ATTACK;
else
{
SuperBattleNode* backnode=node->firstoutnode;
decision=T::STAY_HERE,nameddecision=T::DEFEND_ATTACK;
while (backnode && backnode->innode==node)
{
SuperBattleNode::IntraLink* back2=&backnode->in;
if (!back2->occupier || SameSide(us,back2->occupier))
{
nameddecision=decision=T::RETREAT;
teleloc=back->uid;
nextloc=back2->uid;
nextnode=backnode;
break;
}
backnode=backnode->flanks.rightnode;
}
}
}
} //end of defending against attack
else
{ //next node not occupied
//SPECIAL RULES TO KEEP ARTILLARY BACK1 NODE NOT IMPLEMENTED!
//need to choose best route to go down
SuperBattleNode* fwdnode;
SuperBattleNode* fwdnodenotnull;
SuperBattleNode::IntraLink* fwd2;
if (us->team==T::HOME)
{
fwdnode=node->firstoutnode;
fwd2=&fwdnode->in;
}
else
{
fwdnode=node->innode;
fwd2=&fwdnode->out;
}
int currroute=0;
enum {REENFORCENONEED=50,STAYBAD=100,TAKEEMPTYPRI=150,ATTACKENEMYPRI=300,
ATTACKENEMYWAITREINFORCEPRI=301, //want to attack enemy, but can't move forward until ready to attack!
REINFORCEATT=200,REINFORCEDEFEND=250};
int bestsofar=0;
while (fwdnode)
{
if (fwd2->occupier)
if (SameSide(us,fwd2->occupier))
{ //REINFORCE option
if (fwdnode->occupier && !SameSide(us,fwdnode->occupier))
{ //ongoing conflict. Do they need help?
int attackchance=MAX_SEND_REINFORCE-CalcAttackChance(fwd2->occupier,fwd2,fwdnode->occupier,fwdnode);
if (attackchance>0)
attackchance+=REINFORCEATT;
else
attackchance=REENFORCENONEED;
if (Better(attackchance,bestsofar))
{
bestsofar=attackchance;
decision=T::MOVE_FORWARD;
nameddecision=T::MOVE_REINFORCE;
routenum=currroute;
}
}
}
else
{ //Can't go here- enemy occupied position
if (Better(STAYBAD,bestsofar))
{ //but must defend my current spot against them??
bestsofar=STAYBAD;
nameddecision=decision=T::STAY_HERE;
routenum=currroute;
}
}
else if (fwdnode->occupier)
if (SameSide(us,fwdnode->occupier))
{ //REINFORCE option
SuperBattleNode::IntraLink* fwd2fwd=&fwdnode->out;
if (fwd2fwd==fwd2) fwd2fwd=&fwdnode->in;
if (fwd2fwd->occupier && !SameSide(us,fwd2fwd->occupier))
{ //ongoing conflict. Do they need help?
int attackchance=MAX_SEND_REINFORCE-CalcDefendChance(fwd2fwd->occupier,fwd2fwd,fwdnode->occupier,fwdnode);
if (attackchance>0)
attackchance+=REINFORCEATT;
else
attackchance=REENFORCENONEED;
if (Better(attackchance,bestsofar))
{
bestsofar=attackchance;
decision=T::MOVE_FORWARD;
nameddecision=T::MOVE_REINFORCE;
routenum=currroute;
}
}
}
else
{ //Enemy node - consider attacking
int attackchance=CalcAttackChance(us,fwd2,fwdnode->occupier,fwdnode);
//check if there is a wait reinforce battlefield... otherwise must wait here!
if (attackchance>MIN_FORWARD_TO_ATTACK)
if ( attackchance>MAX_ALWAYS_REINFORCE
|| ( (us->team==T::HOME && fwdnode->in.waitreinforcehere)
|| (us->team==T::AWAY && fwdnode->out.waitreinforcehere)
) )
{
if (Better(ATTACKENEMYPRI,bestsofar))
{
bestsofar=ATTACKENEMYPRI;
decision=T::MOVE_FORWARD;
nameddecision=T::MOVE_TOATTACK;
routenum=currroute;
us->advantagepriority=attackchance;
}
}
else
if (Better(ATTACKENEMYWAITREINFORCEPRI,bestsofar))
{
bestsofar=ATTACKENEMYWAITREINFORCEPRI;
nameddecision=T::WAIT_REINFORCE;
decision=T::STAY_HERE;
us->advantagepriority=attackchance;
}
}
else
{ //move forward to take vacant node
if (Better(TAKEEMPTYPRI,bestsofar))
{
bestsofar=TAKEEMPTYPRI;
nameddecision=decision=T::MOVE_FORWARD;
routenum=currroute;
}
}
currroute++;
if (us->team==T::AWAY)
fwdnode=NULL;
else
{
fwdnode=fwdnode->flanks.rightnode;
if (fwdnode)
if (fwdnode->innode!=node)
fwdnode=NULL;
else
fwd2=&fwdnode->in;
}
} //end while all alternate routes
//OK.. so now we know... move forward or stay here?
if (decision==T::MOVE_FORWARD)
if (us->team==T::HOME)
{
nextnode=node->firstoutnode;
while (routenum--)
nextnode=nextnode->flanks.rightnode;
teleloc=node->out.uid;
nextloc=nextnode->in.uid;
}
else
{
teleloc=node->in.uid;
nextnode=node->innode;
nextloc=nextnode->out.uid;
}
}
} //end of cental occupation
else
if (fwd->occupier==us)
{ //IF WE ARE ON FORWARD NODE THEN MUST BE RETREATING
//What are we retreating into?
if (node->occupier)
if (SameSide(us,node->occupier))
{ //merge into holding force
nextloc=teleloc=node->mainuid;
decision=T::MERGE_FORCE;
}
else
{ //fight past holding force
nextloc=back->uid;
if (fwd->retreatfromhere)
nameddecision=decision=T::RETREAT_UNDER_FIRE;
else
{
decision=T::TELEPORT;
nameddecision=T::STAY_HERE;
teleloc=back->uid;
}
}
else
{ //take node for 1 round... should have happened already...
decision=T::TELEPORT;
nameddecision=T::STAY_HERE;
teleloc=node->mainuid;
nextloc=node->mainuid;
}
}
else
if (back->occupier==us)
{ //If we are on back node then we should consider attacking
//other situation is if we have retreated through last node.
if (node->occupier)
if (SameSide(us,node->occupier))
{ //merge into holding force
nextloc=teleloc=node->mainuid;
decision=T::MERGE_FORCE;
}
else
{ //enemy force on main spot. Now what?
int attackadvantage=CalcAttackChance(us,back,node->occupier,node);
if (attackadvantage<MAX_DEAD)
decision=T::LOSE_FORCE;
else if (attackadvantage<MAX_ALWAYS_WITHDRAW)
nameddecision=decision=T::RETREAT;
else if (attackadvantage<MAX_RND_WITHDRAW_REINFORCE && Math_Lib.rnd(2))
nameddecision=decision=T::RETREAT;
else if (attackadvantage<MAX_ALWAYS_REINFORCE)
decision=T::STAY_HERE,nameddecision=T::WAIT_REINFORCE;
else if (attackadvantage<MAX_RND_REINFORCE_ATTACK && Math_Lib.rnd(2))
decision=T::STAY_HERE,nameddecision=T::WAIT_REINFORCE;
else if (attackadvantage<MAX_ATTACK_DONTSPLIT)
nameddecision=decision=T::ATTACK;
else
nameddecision=decision=T::ATTACK;
if (decision==T::STAY_HERE && !back->waitreinforcehere)
nameddecision=decision=T::RETREAT; //If can't stay here then go back
if (decision==T::RETREAT)
{
if (us->team==T::HOME)
if (!node->innode)
decision=T::STAY_HERE,nameddecision=T::WAIT_REINFORCE;
else
{
SuperBattleNode::IntraLink* back2=&node->innode->out;
if (back2->occupier && !SameSide(us,back2->occupier))
decision=T::STAY_HERE,nameddecision=T::WAIT_REINFORCE;
else
{
decision=T::TELEPORT;
nameddecision=T::STAY_HERE;
teleloc=back->uid;
nextloc=back2->uid;
nextnode=node->innode;
}
}
else //away
if (!node->firstoutnode)
decision=T::STAY_HERE,nameddecision=T::WAIT_REINFORCE;
else
{
SuperBattleNode* backnode=node->firstoutnode;
decision=T::STAY_HERE,nameddecision=T::WAIT_REINFORCE;
while (backnode && backnode->innode==node)
{
SuperBattleNode::IntraLink* back2=&backnode->in;
if (!back2->occupier || SameSide(us,back2->occupier))
{
decision=T::RETREAT;
teleloc=back->uid;
nextloc=back2->uid;
nextnode=backnode;
break;
}
backnode=backnode->flanks.rightnode;
}
}
}
if (decision==T::STAY_HERE && !back->waitreinforcehere)
nameddecision=decision=T::ATTACK; //if can't go back and can't stay here then attack!
if (decision==T::ATTACK)
nextloc=node->mainuid;
}
else
if (fwd->uid) //not end of tree!!!
{ //main node empty! Lets take it!
decision=T::TELEPORT;
teleloc=node->mainuid;
nextloc=node->mainuid;
}
}
else
{ //new force needs injecting... CAN'T DO IT HERE!
}
//OK that's made some decisions... now need to set in stone.
//first, the losers
if (decision==T::MERGE_FORCE)
{ //if merge forces, then inherit better weaponry
TeamDef* targ=node->occupier;
if (node->in.uid==teleloc)
targ=node->in.occupier;
if (node->out.uid==teleloc)
targ=node->out.occupier;
MergeForces(targ,us);
return false;
}
if (decision==T::LOSE_FORCE)
{
us->strength=-1;
return false;
}
//now the winners.
//stop others travelling our route
//by setting us up as occupier
if (decision==T::TELEPORT)
decision=T::STAY_HERE;
//DEADCODE DAW 15/06/99 us->lastlosses=0;
us->action=decision;
us->namedaction=nameddecision;
if (teleloc!=us->location)
{
us->location=teleloc;
if (node->mainuid==teleloc)
node->occupier=us;
else
if (node->in.uid==teleloc)
node->in.occupier=us;
else
if (node->out.uid==teleloc)
node->out.occupier=us;
}
if (nextloc!=teleloc)
{
us->nextlocation=nextloc;
us->nextnode=nextnode;
if (nextnode->mainuid==nextloc && !node->occupier)
nextnode->occupier=us;
else
if (nextnode->in.uid==nextloc && !node->in.occupier)
nextnode->in.occupier=us;
else
if (nextnode->out.uid==nextloc && !node->out.occupier)
nextnode->out.occupier=us;
}
us->DiagnosticOutput("NextMove b");
return true;
}
bool BattleStruct::PostAttackDecision(TeamDef* us)
{ //THIS ROUTINE RESOLVES CONFLICTS ONLY!!
//returns true if force disbanded!
typedef TeamDef T;
SuperBattleNode* node=us->node;
TeamDef* them;
SuperBattleNode::IntraLink *fwd=&node->in,*back=&node->out;
if (us->team==T::HOME)
{ fwd=&node->out;back=&node->in; }
switch (us->action)
{
case T::ATTACK: //inner to main
{ //calc losses due to fighting on both sides
//did we wipe them out? Did they move out?
us->DiagnosticOutput("PostAttack a");
assert (back->occupier==us);
if ((them=node->occupier)!=NULL)
if (SameSide(us,them))
{ //should not happen!!! Merge
MergeForces(them,us);
back->occupier=NULL;
return false;
}
else
{ //ho hum. The enemy are still there.
//losses due to player
them->lastlostforces+=them->strength*(them->lastlosses)/PLAYER_PROPORTION_ATTACKER;
them->strength-=them->strength*(them->lastlosses)/PLAYER_PROPORTION_ATTACKER;
us->lastlostforces=us->strength*(us->lastlosses)/PLAYER_PROPORTION_DEFENDER;
us->strength-=us->strength*(us->lastlosses)/PLAYER_PROPORTION_DEFENDER;
//they are fighting so lose 10% off both forces using opposite strengths
them->strength-=us->strength/ATTACK_PROPORTION_AUTO;
us->strength-=them->strength/ATTACK_PROPORTION_AUTO;
//compare percentages to get extra losses
int advantage=CalcAttackChance(us,back,them,node)+Math_Lib.rnd(20);
if (advantage<100)
{
if (advantage>0)
us->strength=us->strength*advantage/100;
else
us->strength==1;
advantage=CalcAttackChance(us,back,them,node)+Math_Lib.rnd(20);
if (advantage<MAX_DEAD)
{ //ourforce is removed
us->strength=-1;
back->occupier=NULL;
return false;
}
}
else
{
advantage=CalcDefendChance(us,back,them,node)+Math_Lib.rnd(20);
if (advantage<EXTRA_HURT_DEFENDERS)
{
if (advantage>0)
them->strength=them->strength*advantage/EXTRA_HURT_DEFENDERS;
else
them->strength=-1;
advantage=CalcDefendChance(us,back,them,node)+Math_Lib.rnd(20);
if (advantage<MAX_DEAD)
{ //they die. We move onto their hill.
us->location=node->mainuid;
us->nextlocation=UID_NULL;
node->occupier=us;
back->occupier=NULL;
them->strength=-1;
them->action=T::LOSE_FORCE;
}
}
//nothing much else happens if no-one has advantage
}
}
else
{ //they moved out! We get node
//(note: If they moved out they were teleported to the out point and then transported)
us->nextnode=NULL;
us->location=node->mainuid;
node->occupier=us;
back->occupier=NULL;
us->nextlocation=UID_NULL;
}
//DEADCODE DAW 15/06/99 us->lastlosses=0;
//DEADCODE JIM 18/06/99 us->action=T::STAY_HERE;
}
us->DiagnosticOutput("PostAttack a");
break;
case T::RETREAT_UNDER_FIRE: //outer to inner - could merge or take main if empty
{
us->DiagnosticOutput("PostAttack a");
assert (fwd->occupier==us);
//calc losses due to fighting
if ((them=node->occupier)!=NULL)
if (SameSide(us,them))
{ //retreated past our own troops. Should not happen!
MergeForces(them,us);
fwd->occupier=NULL;
return false;
}
else
{ //did they wipe us out?
int advantage=CalcAttackChance(us,fwd,them,node);
us->lastlostforces+=us->strength*(us->lastlosses)/PLAYER_PROPORTION_RETREAT;
us->strength-=us->strength*(us->lastlosses)/PLAYER_PROPORTION_RETREAT;
us->strength=us->strength*advantage/200; //tunable to ensure high losses even if advantage
advantage=CalcAttackChance(us,fwd,them,node);
if (advantage<MAX_DEAD)
{ //ourforce is removed
us->strength=-1;
fwd->occupier=NULL;
return false;
}
if ((them=back->occupier)!=NULL)
{
assert (SameSide(us,them)); //must be our side - merge for counter //DAW 23/06/99
MergeForces(them,us);
fwd->occupier=NULL;
return false;
}
us->nextnode=NULL; //otherwise we take the inner point with remaining force
us->location=back->uid;
us->nextlocation=UID_NULL;
back->occupier=us;
fwd->occupier=NULL;
}
else
{ //they moved out! We take node!
//(note: If they moved out they were teleported to the in point and then transported)
us->nextnode=NULL;
us->location=node->mainuid;
us->nextlocation=UID_NULL;
node->occupier=us;
fwd->occupier=NULL;
}
//DEADCODE DAW 15/06/99 us->lastlosses=0;
//DEADCODE JIM 18/06/99 us->action=T::STAY_HERE;
us->DiagnosticOutput("PostAttack a");
}
break;
default:;
// case RETREAT, //down road - could merge
// case MOVE_FORWARD: //up road - could merge
// case TELEPORT:
// case STAY_HERE: //main or inner
// LOSE_FORCE,
// MERGE_FORCE,
}
return true;
}
bool BattleStruct::PostMoveDecision(TeamDef* us)
{
//returns true if force disbanded!
typedef TeamDef T;
SuperBattleNode* node=us->node;
assert(node);
TeamDef* them;
if (us->action==T::MOVE_FORWARD || us->action==T::RETREAT)
{
us->DiagnosticOutput("PostMove a");
//DEADCODE DAW 26/04/99 #pragma warnmsg("Indentation troubles.")
us->lastlostforces+=us->strength*(us->lastlosses)/PLAYER_PROPORTION_CONVOY;
us->strength-=us->strength*(us->lastlosses)/PLAYER_PROPORTION_CONVOY;
assert(node!=us->nextnode);
if ( (us->team==T::HOME)==(us->action==T::MOVE_FORWARD) )
{
assert(node->out.occupier==us)
node->out.occupier=NULL;
}
else
{
assert(node->in.occupier==us);
node->in.occupier=NULL;
}
node=us->nextnode;
assert(node);
us->node=us->nextnode;
us->nextnode=NULL;
us->location=us->nextlocation;
us->nextlocation=UID_NULL;
//need to check if should move to main node or merge here or at main node
SuperBattleNode::IntraLink *back=&node->out;
if ( (us->team==T::HOME)==(us->action==T::MOVE_FORWARD) )
back=&node->in;
assert (back->uid==us->location || node->mainuid==us->location);
if ((them=back->occupier)!=NULL && them!=us)
{
assert (SameSide(us,them))
MergeForces(them,us);
return false;
}
else
if ((them=node->occupier)!=NULL)
if (SameSide(us,them))
{
MergeForces(them,us);
return false;
}
else
{ //set up to attack them
back->occupier=us;
us->location=back->uid;
}
else
{
us->location=node->mainuid;
node->occupier=us;
}
us->DiagnosticOutput("PostMove b");
}
else
if (us->action==T::STAY_HERE)
{
us->DiagnosticOutput("PostMove a");
us->lastlostforces+=us->strength*(us->lastlosses)/PLAYER_PROPORTION_HOLDER;
us->strength-=us->strength*(us->lastlosses)/PLAYER_PROPORTION_HOLDER;
}
//else others already covered.
return true;
}
bool BattleStruct::NextAttackDecisions()
{
assert(usednodes || !usedteams);
LinkTeams();
for (int i=0;i<usedteams;i++)
if (!teamlist[i].location)
{ //new force needs injecting!
SuperBattleNode* node=NULL;
if (teamlist[i].team==TeamDef::HOME)
{
node=homenodes; //have to go in here!
}
else
{
SuperBattleNode* trynode=awaynodes;
int score=-10000; //JIM 01/06/99
enum {EMPTY=40,OCCSAME=30,OCCDIFF=10,NOTANKS=20};
while (trynode)
{
if (!trynode->occupier)
if (!(trynode->out.terrain&SuperBattleNode::IntraLink::TANKSLOST))
{
if (Better(NOTANKS,score)) //any route flagged no tanks is poor
{ //as trucks will get stopped too!
score=NOTANKS;
node=trynode;
}
}
else
{
if (Better(EMPTY,score)) //usable empty square is best
{
score=EMPTY;
node=trynode;
}
}
else
if (trynode->occupier->forcetype==teamlist[i].forcetype)
{ //consider merging with same force type
if (Better(OCCSAME-trynode->occupier->strength/100,score))
{
score=OCCSAME-trynode->occupier->strength/100;
node=trynode;
}
}
else
{ //consider merging with diff force type
if (Better(OCCDIFF-trynode->occupier->strength/100,score))
{
score=OCCDIFF-trynode->occupier->strength/100;
node=trynode;
}
}
trynode=trynode->flanks.rightnode;
}
}
//so teleport new force to selected node...
if (!node->occupier)
{ //can teleport there
teamlist[i].action=TeamDef::STAY_HERE;
teamlist[i].namedaction=TeamDef::NEW_FORCE;
teamlist[i].advantagepriority=teamlist[i].strength/10;
teamlist[i].location=node->mainuid;
teamlist[i].node=node;
node->occupier=teamlist+i;
}
else
{
teamlist[i].action=TeamDef::MERGE_FORCE;
MergeForces(node->occupier,&teamlist[i]);
node->occupier->namedaction=TeamDef::NEW_FORCE;
node->occupier->advantagepriority=node->occupier->strength/10;
}
teamlist[i].DiagnosticOutput("NewForce");
}
else
NextAttackDecision(teamlist+i);
int teamdif=0; //compaction factor
for ( i=0;i<usedteams;i++)
if (teamlist[i].strength<=0)
teamdif++;
else
if (teamdif)
teamlist[i-teamdif]=teamlist[i];
usedteams-=teamdif;
for (i=usedteams;i<MAXTEAMS;i++)
teamlist[i].strength=0;
LinkTeams();
return true; //probably return false if end of battle
}
bool BattleStruct::PostAttackDecisions()
{
assert(usednodes || !usedteams);
LinkTeams();
for (int i=0;i<usedteams;i++)
if (teamlist[i].location)
PostAttackDecision(teamlist+i);
int teamdif=0; //compaction factor
for ( i=0;i<usedteams;i++)
if (teamlist[i].strength<=0)
teamdif++;
else
if (teamdif)
teamlist[i-teamdif]=teamlist[i];
usedteams-=teamdif;
for (i=usedteams;i<MAXTEAMS;i++)
teamlist[i].strength=0;
LinkTeams();
for ( i=0;i<usedteams;i++)
if (teamlist[i].location)
PostMoveDecision(teamlist+i);
teamdif=0; //compaction factor
for ( i=0;i<usedteams;i++)
if (teamlist[i].strength<=0)
teamdif++;
else
if (teamdif)
teamlist[i-teamdif]=teamlist[i];
usedteams-=teamdif;
for (i=usedteams;i<MAXTEAMS;i++)
teamlist[i].strength=0;
LinkTeams();
return true; //probably return false if end of battle
}
void SupplyLine::NextAttackReports()
{
TeamDef::Team blueteam=TeamDef::AWAY;
if (initiative==REDATTACKING)
blueteam=TeamDef::HOME;
else
return;
for (int i=0;i<groundbattle.usedteams;i++)
if (groundbattle.teamlist[i].team==blueteam)
{
if (groundbattle.teamlist[i].advantagepriority<MAX_RND_WITHDRAW_REINFORCE)
if (groundbattle.teamlist[i].action==TeamDef::STAY_HERE)
MMC.DisDayEntry(Debrief::DISCARDTARGUID,frontline->associated_item, Debrief::T_FAC01_H);
if ( groundbattle.teamlist[i].node
&& groundbattle.teamlist[i].node->flanks.leftnode==NULL
&& groundbattle.teamlist[i].node->flanks.rightnode!=NULL
)
{
SuperBattleNode* n;
bool someonemovedup=false;
for (n=groundbattle.teamlist[i].node;n;n=n->flanks.rightnode)
{
breakif (!n->occupier || n->occupier->team!=blueteam); //stop on any gap or red
if (n->occupier->action!=TeamDef::STAY_HERE)
someonemovedup=true;
}
if (!n && someonemovedup)
MMC.DisDayEntry(Debrief::DISCARDTARGUID,frontline->associated_item, Debrief::T_FAC03_H);
}
if (blueteam==TeamDef::HOME)
{
SuperBattleNode* n=NULL;
for (n=groundbattle.teamlist[i].node->innode;n;n=n->innode)
breakif(n->occupier && n->occupier->team!=blueteam); //stop on red only
if (n)
if (n->occupier->action==TeamDef::STAY_HERE)
MMC.DisDayEntry(Debrief::DISCARDTARGUID,frontline->associated_item, Debrief::T_FAC04_H);
else
MMC.DisDayEntry(Debrief::DISCARDTARGUID,frontline->associated_item, Debrief::T_Army01_H);
}
}
else
{
}
}
void SupplyLine::PostAttackReports()
{
if (initiative!=REDATTACKING && initiative!=BLUEATTACKING)
return;
if (!groundbattle.usednodes)
return; //JIM 11/06/99
TeamDef::Team blueteam=TeamDef::AWAY;
int bluestoresinuse=0; //10 troops = 1 stores
int redstoresinuse=0;
if (initiative==REDATTACKING)
blueteam=TeamDef::HOME;
//DeadCode DAW 27Jun99 else
//DeadCode DAW 27Jun99 return;
for (int i=0;i<groundbattle.usedteams;i++)
{
if (groundbattle.teamlist[i].team==blueteam)
{
bluestoresinuse+=groundbattle.teamlist[i].strength;
if (groundbattle.teamlist[i].lastlosses>5)
MMC.DisDayEntry(Debrief::DISCARDTARGUID,frontline->associated_item, Debrief::T_FAC02_H);
}
else
{
redstoresinuse+=groundbattle.teamlist[i].strength;
if (groundbattle.teamlist[i].lastlosses>8)
MMC.DisDayEntry(Debrief::DISCARDTARGUID,frontline->associated_item, Debrief::T_FAC00_H);
}
if ( groundbattle.teamlist[i].team==TeamDef::HOME)
{
if (!groundbattle.teamlist[i].node->firstoutnode
&& groundbattle.teamlist[i].node->occupier==&groundbattle.teamlist[i]
)
if (initiative==REDATTACKING)
initiative=REDLOST;
else
if (initiative==BLUEATTACKING)
initiative=BLUELOST;
}
else
if ( groundbattle.teamlist[i].team==TeamDef::AWAY)
{
if ( !groundbattle.teamlist[i].node->innode
&& groundbattle.teamlist[i].node->occupier==&groundbattle.teamlist[i]
)
if (initiative==REDATTACKING)
initiative=REDWON;
else
if (initiative==BLUEATTACKING)
initiative=BLUEWON;
}
}
DiagnosticOutput(0,"Supplies");
if (frontline->currentstores-redstoresinuse/STORES_TROOPS_PER_PERIOD>0)
frontline->currentstores-=redstoresinuse/STORES_TROOPS_PER_PERIOD;
else
{
frontline->currentstores=STORES_STANDARDSUPPLY;
if (initiative==REDATTACKING)
initiative=REDLOST;
else
if (initiative==BLUEATTACKING)
initiative=BLUEWON;
}
if (redstoresinuse>OVERWHELMING_TROOPS_PROPORTION_WIN*bluestoresinuse)
if (initiative==REDATTACKING)
initiative=REDWON;
else
if (initiative==BLUEATTACKING)
initiative=BLUELOST;
if (bluestoresinuse>OVERWHELMING_TROOPS_PROPORTION_WIN*redstoresinuse)
if (initiative==REDATTACKING)
initiative=REDLOST;
else
if (initiative==BLUEATTACKING)
initiative=BLUEWON;
int slnum;
if (initiative!=REDATTACKING && initiative!=BLUEATTACKING)
ExitBf();
if (this==&SupplyTree::WestRoute)
slnum=0;
else
if (this==&SupplyTree::CentralRoute)
slnum=1;
else
////if (this==&SupplyTree::EastRoute)
slnum=2;
DiagnosticOutput(0,"Remaining");
if (frontline->currentstores>STORES_TOINITIATEASSAULT) //400
if (Math_Lib.rnd(2))
{ //inject extra red force
TeamDef* team=groundbattle.teamlist+groundbattle.usedteams++;
team->strength=frontline->currentstores/STORES_TO_REDTROOPS_REINFORCE;
int forcetype=Math_Lib.rnd(5);
team->team=(blueteam==TeamDef::AWAY)?TeamDef::HOME:TeamDef::AWAY;
team->forcename=forcenames[slnum][1][forcetype]+Math_Lib.rnd(5);
team->forcetype=TeamDef::ForceType(forcetype);
team->action=TeamDef::STAY_HERE;
team->namedaction=TeamDef::NEW_FORCE;
team->location=UID_NULL;
team->nextlocation=UID_NULL;
team->lastlosses=0;
team->lastlostforces=0;
team->node=NULL;
team->nextnode=NULL;
}
if (Math_Lib.rnd(2)==0)
{ //inject extra blue force
TeamDef* team=groundbattle.teamlist+groundbattle.usedteams++;
team->strength=frontline->maxstorestonnes/MAXSTORES_TO_BLUETROOPS_REINFORCE;
int forcetype=Math_Lib.rnd(5);
team->team=blueteam;
team->forcename=forcenames[slnum][0][forcetype]+Math_Lib.rnd(5);
team->forcetype=TeamDef::ForceType(forcetype);
team->action=TeamDef::STAY_HERE;
team->namedaction=TeamDef::NEW_FORCE;
team->location=UID_NULL;
team->nextlocation=UID_NULL;
team->lastlosses=0;
team->lastlostforces=0;
team->node=NULL;
team->nextnode=NULL;
}
}
bool BattleStruct::BattleField(int teamnum,FileNum& fil,UniqueID& src,UniqueID& trg,int& mainforce,int& extraforce)
{ //return true if outward from src
fil=FIL_NULL;
TeamDef* us=teamlist+teamnum;
if (us->strength==0)
return false;
typedef TeamDef T;
SuperBattleNode* node=us->node;
mainforce=us->strength/80;
extraforce=0;
if (mainforce>10)
{
extraforce=mainforce-10;
if (extraforce>6)
extraforce=6;
mainforce=10;
}
if (us->team==T::HOME)
switch(us->action)
{
case T::MERGE_FORCE://should never happen
case T::LOSE_FORCE: //should never happen
case T::TELEPORT: //should never happen
case T::STAY_HERE:
if (node->occupier==us)
{
fil=node->out.defendmain;
src=node->mainuid;
trg=node->out.uid;
return true;
}
else
{ assert (node->in.occupier==us);
fil=node->in.waitreinforcehere;
src=node->in.uid;
trg=node->mainuid;
return true;
}
case T::MOVE_FORWARD:
{
fil=us->nextnode->innerlink.homeapproach;
src=node->out.uid;
trg=us->nextnode->in.uid;
return true;
}
case T::ATTACK:
{
fil=node->in.attackmain;
src=node->in.uid;
trg=node->mainuid;
//in this case, extraforce represents flanking...
if (!( ( (node->flanks.nonlinks&SuperBattleNode::FlankLink::NOT_ML)
|| (!node->flanks.leftnode->occupier)
|| SameSide(us,node->flanks.leftnode->occupier)
)
&& ( (node->flanks.nonlinks&SuperBattleNode::FlankLink::NOT_MR)
|| (!node->flanks.rightnode->occupier)
|| SameSide(us,node->flanks.rightnode->occupier)
)) )
extraforce=0;
return true;
}
case T::RETREAT:
{
fil=node->innerlink.homeretreat;
src=node->in.uid;
trg=us->nextnode->out.uid;
return false;
}
case T::RETREAT_UNDER_FIRE:
{
fil=node->out.retreatfromhere;
src=node->out.uid;
trg=node->in.uid;
return false;
}
}
else
switch(us->action)
{
case T::MERGE_FORCE://should never happen
case T::LOSE_FORCE: //should never happen
case T::TELEPORT: //should never happen
case T::STAY_HERE:
if (node->occupier==us)
{
fil=node->in.defendmain;
src=node->mainuid;
trg=node->in.uid;
return false;
}
else
{ assert (node->out.occupier==us);
fil=node->out.waitreinforcehere;
src=node->out.uid;
trg=node->mainuid;
return false;
}
case T::MOVE_FORWARD:
{
fil=node->innerlink.awayapproach;
src=node->in.uid;
trg=us->nextnode->out.uid;
return false;
}
case T::ATTACK:
{
fil=node->out.attackmain;
src=node->out.uid;
trg=node->mainuid;
//in this case, extraforce represents flanking...
if (!( ( (node->flanks.nonlinks&SuperBattleNode::FlankLink::NOT_ML)
|| (!node->flanks.leftnode->occupier)
|| SameSide(us,node->flanks.leftnode->occupier)
)
&& ( (node->flanks.nonlinks&SuperBattleNode::FlankLink::NOT_MR)
|| (!node->flanks.rightnode->occupier)
|| SameSide(us,node->flanks.rightnode->occupier)
)) )
extraforce=0;
return false;
}
case T::RETREAT:
{
fil=us->nextnode->innerlink.awayretreat;
src=node->out.uid;
trg=us->nextnode->in.uid;
return true;
}
case T::RETREAT_UNDER_FIRE:
{
fil=node->in.retreatfromhere;
src=node->in.uid;
trg=node->out.uid;
return true;
}
}
fil=FIL_NULL;
return true;
}
//static bool Sh(UWord& v) {v>>=1;return ((v&1)!=0);}
bool BattleStruct::NewSetupFirstDay(const int* hometeamnames,const int* awayteamnames,int homestrength,int awaystrength)
{
LinkBattleNodes();
SuperBattleNode* away=awaynodes;
int awaynodecount=0;
while (away)
{
awaynodecount++;
away=away->flanks.rightnode;
}
int homenodecount=homestrength/(awaynodecount+1);
awaynodecount=awaystrength/(awaynodecount+1);
int homeskip=Math_Lib.rnd(20); //this node left undefended, but 'cos rnd is high,,,
away=awaynodes;
TeamDef *team=teamlist;
for (away=awaynodes;away;away=away->flanks.rightnode)
{ //set up attackers:
int forcetype=away->out.terrain&15;
if ((away->out.terrain&32768)==0)
forcetype=Math_Lib.rnd(13)/3;
team->strength=awaynodecount*4+Math_Lib.rnd(5); //STORES_TO_TROOPS_INITIAL
awaystrength-=team->strength/STORES_TO_TROOPS_INITIAL;
team->team=team->AWAY;
team->forcename=awayteamnames[forcetype]+Math_Lib.rnd(5);
team->forcetype=TeamDef::ForceType(forcetype);
team->action=TeamDef::STAY_HERE;
team->location=away->mainuid;
team->nextlocation=UID_NULL;
team->lastlosses=0;
team->lastlostforces=0;
team->node=away;
team->nextnode=away;
away->occupier=team;
team++;
//set up defenders
if (homestrength>0)
if (!away->innode->occupier) //DAW 26/04/99
{
forcetype=(away->out.terrain>>8)&15;
if ((away->out.terrain&32768)==0)
forcetype=Math_Lib.rnd(13)/3;
team->strength=homenodecount*4+Math_Lib.rnd(5); //STORES_TO_TROOPS_INITIAL
homestrength-=team->strength/STORES_TO_TROOPS_INITIAL;
team->team=team->HOME;
team->forcename=awayteamnames[forcetype]+Math_Lib.rnd(5);
team->forcetype=TeamDef::ForceType(forcetype);
team->action=TeamDef::STAY_HERE;
team->location=away->innerlink.uid;
team->nextlocation=UID_NULL;
team->lastlosses=0;
team->lastlostforces=0;
team->node=away->innode;
team->nextnode=away->innode;
away->innode->occupier=team;
team++;
}
else
{ //double team this defensive position!
away->innode->occupier->strength+=homenodecount*5;
homestrength-=homenodecount*5/10;
}
}
LinkTeams();
return true;
}
TeamDef* BattleStruct::FindTeamAtLocation(UniqueID u)
{
for (int team=usedteams-1;team>=0;team--)
if (teamlist[team].location==u)
return teamlist+team;
return NULL;
}
void SupplyTree::SetNodeNationalities(UniqueID eastfront,UniqueID centralfront,UniqueID westfront,int deltastrength)
{
//first set all nodes to Blue
for (SupplyNode* node=FirstNode;node->next!=node;node=node->next)
{
node->status=BEHINDBLUELINES;
// node->attackstats.aaalevel=0;
}
node=FindSupplyNodeForNodeItem(eastfront);
EastRoute.frontline=node;
node->status=FRONTLINE;
if (deltastrength)
{
node->currentstores+=deltastrength;
if (node->currentstores>node->maxstorestonnes)
node->currentstores=node->maxstorestonnes;
if (node->currentstores<node->maxstorestonnes/2)
node->currentstores=node->maxstorestonnes/2;
}
node=FindSupplyNodeForNodeItem(centralfront);
CentralRoute.frontline=node;
node->status=FRONTLINE;
if (deltastrength)
{
node->currentstores+=deltastrength;
if (node->currentstores>node->maxstorestonnes)
node->currentstores=node->maxstorestonnes;
if (node->currentstores<node->maxstorestonnes/2)
node->currentstores=node->maxstorestonnes/2;
}
node=FindSupplyNodeForNodeItem(westfront);
WestRoute.frontline=node;
node->status=FRONTLINE;
if (deltastrength)
{
node->currentstores+=deltastrength;
if (node->currentstores>node->maxstorestonnes)
node->currentstores=node->maxstorestonnes;
if (node->currentstores<node->maxstorestonnes/2)
node->currentstores=node->maxstorestonnes/2;
}
if (deltastrength>0)
{
EastRoute.initiative=REDINITIATIVE;
EastRoute.initiative=BLUEINITIATIVE;
WestRoute.initiative=REDINITIATIVE;
}
if (deltastrength<0)
{
WestRoute.initiative=BLUEINITIATIVE;
CentralRoute.initiative=REDINITIATIVE;
CentralRoute.initiative=BLUEINITIATIVE;
}
SupplyRoute* route;
int routeind;
bool gotone=true;
while(gotone)
for (gotone=false,node=FirstNode;node->next!=node;node=node->next)
if (node->status!=BEHINDBLUELINES)
for (routeind=0;route=node->route[routeind],routeind<3;routeind++)
if (route && route->supplier->status==BEHINDBLUELINES)
{
gotone=true;
route->supplier->status=BEHINDREDLINES;
if (route->supplier->attackstats.aaalevel<80)
route->supplier->attackstats.aaalevel=80;
if (route->attackstats.aaalevel<80)
route->attackstats.aaalevel=80;
}
for (route=FirstRoute;route->next!=route;route=route->next)
if (route->suppliee->status==BEHINDREDLINES)
if (route->attackstats.aaalevel<60)
route->attackstats.aaalevel=60;
for (int af=0;airfieldinfo[af].nationality!=NAT_ALIGN;af++)
if ( airfieldinfo[af].northnodes[0]->status==BEHINDBLUELINES
&& ( !airfieldinfo[af].northnodes[1]
|| airfieldinfo[af].northnodes[1]->status==BEHINDBLUELINES
) )
{
airfieldinfo[af].nationality=NAT_BLUE;
airfieldinfo[af].attackstats.aaalevel=0;
}
else
if ( airfieldinfo[af].southnodes[0]->status==BEHINDREDLINES
&& ( !airfieldinfo[af].southnodes[1]
|| airfieldinfo[af].southnodes[1]->status==BEHINDREDLINES
) )
{
airfieldinfo[af].nationality=NAT_RED;
airfieldinfo[af].attackstats.aaalevel=60;
}
else
airfieldinfo[af].nationality=NAT_AMBER;
}
| [
"[email protected]"
] | |
592ab6be4d46226b53c4a3ffc18b036c8c565da3 | 58c2ebd2d359ef2f2a821dd6ad26c84d8fea3784 | /CoreESP8266/libraries/ESP8266WiFi/src/WiFiClientSecure.h | 79f634e6792b4b8d97f6ea6768df9d13162e9ae3 | [] | no_license | Raise3D/Reprap-Raise3D-E2-Series | 3e30cb944b2e2c1928cd7dfae38ad4e10d650bf3 | d29dfac429d7f541021320d914bd74d86e5c7757 | refs/heads/master | 2023-03-28T00:01:02.203536 | 2021-03-12T07:11:49 | 2021-03-12T07:11:49 | 307,570,206 | 5 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 3,084 | h | /*
WiFiClientSecure.h - Variant of WiFiClient with TLS support
Copyright (c) 2015 Ivan Grokhotkov. All rights reserved.
This file is part of the esp8266 core for Arduino environment.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef wificlientsecure_h
#define wificlientsecure_h
#include "WiFiClient.h"
#include "include/ssl.h"
class SSLContext;
class WiFiClientSecure : public WiFiClient {
public:
WiFiClientSecure();
~WiFiClientSecure() override;
int connect(IPAddress ip, uint16_t port) override;
int connect(const String host, uint16_t port) override;
int connect(const char* name, uint16_t port) override;
bool verify(const char* fingerprint, const char* domain_name);
bool verifyCertChain(const char* domain_name);
uint8_t connected() override;
size_t write(const uint8_t *buf, size_t size) override;
size_t write_P(PGM_P buf, size_t size) override;
int read(uint8_t *buf, size_t size) override;
int available() override;
int read() override;
int peek() override;
size_t peekBytes(uint8_t *buffer, size_t length) override;
void stop() override;
bool setCACert(const uint8_t* pk, size_t size);
bool setCertificate(const uint8_t* pk, size_t size);
bool setPrivateKey(const uint8_t* pk, size_t size);
bool setCACert_P(PGM_VOID_P pk, size_t size);
bool setCertificate_P(PGM_VOID_P pk, size_t size);
bool setPrivateKey_P(PGM_VOID_P pk, size_t size);
bool loadCACert(Stream& stream, size_t size);
bool loadCertificate(Stream& stream, size_t size);
bool loadPrivateKey(Stream& stream, size_t size);
void allowSelfSignedCerts();
template<typename TFile>
bool loadCertificate(TFile& file) {
return loadCertificate(file, file.size());
}
template<typename TFile>
bool loadPrivateKey(TFile& file) {
return loadPrivateKey(file, file.size());
}
template<typename TFile>
bool loadCACert(TFile& file) {
return loadCACert(file, file.size());
}
friend class WiFiServerSecure; // Needs access to custom constructor below
protected:
// Only called by WiFiServerSecure
WiFiClientSecure(ClientContext* client, bool usePMEM, const uint8_t *rsakey, int rsakeyLen, const uint8_t *cert, int certLen);
protected:
void _initSSLContext();
int _connectSSL(const char* hostName);
bool _verifyDN(const char* name);
std::shared_ptr<SSLContext> _ssl = nullptr;
};
#endif //wificlientsecure_h
| [
"[email protected]"
] | |
f38bc15a1c80a1e81054114c984d4d18d832bc68 | 26d3df4594960f2d12d4c674310e87e70c2b3389 | /sprout/numeric/dft/fit/dft.hpp | 8e5121de178fdd7a6097915a60d6661d2d71f9d7 | [
"BSL-1.0"
] | permissive | VD-15/Sprout | e2ff06c2ec6515ea70dee0d410955db8cd1d9dc9 | f85f3de543353e746f5c1440e909488592b37ae7 | refs/heads/master | 2022-12-22T05:05:15.528416 | 2020-09-28T13:40:42 | 2020-09-28T13:40:42 | 298,625,230 | 0 | 0 | null | 2020-09-25T16:29:32 | 2020-09-25T16:29:32 | null | UTF-8 | C++ | false | false | 2,154 | hpp | /*=============================================================================
Copyright (c) 2011-2019 Bolero MURAKAMI
https://github.com/bolero-MURAKAMI/Sprout
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 SPROUT_NUMERIC_DFT_FIT_DFT_HPP
#define SPROUT_NUMERIC_DFT_FIT_DFT_HPP
#include <sprout/config.hpp>
#include <sprout/iterator/distance.hpp>
#include <sprout/container/traits.hpp>
#include <sprout/container/functions.hpp>
#include <sprout/numeric/dft/fixed/dft.hpp>
#include <sprout/algorithm/fit/results.hpp>
#include <sprout/sub_array/sub_array.hpp>
#include <sprout/sub_array/sub.hpp>
#include <sprout/pit/pit.hpp>
namespace sprout {
namespace fit {
namespace detail {
template<typename ForwardIterator, typename Result>
inline SPROUT_CONSTEXPR typename sprout::fit::results::algorithm<Result>::type
dft_impl(
ForwardIterator const& first, ForwardIterator const& last, Result const& result,
typename sprout::container_traits<Result>::difference_type offset
)
{
return sprout::sub_copy(
sprout::get_internal(sprout::fixed::dft(first, last, result)),
offset,
offset + sprout::fit_size(result, sprout::distance(first, last))
);
}
} // namespace detail
//
// dft
//
template<typename ForwardIterator, typename Result>
inline SPROUT_CONSTEXPR typename sprout::fit::results::algorithm<Result>::type
dft(ForwardIterator first, ForwardIterator last, Result const& result) {
return sprout::fit::detail::dft_impl(first, last, result, sprout::internal_begin_offset(result));
}
template<typename Result, typename ForwardIterator>
inline SPROUT_CONSTEXPR typename sprout::fixed::results::algorithm<Result>::type
dft(ForwardIterator first, ForwardIterator last) {
return sprout::fit::dft(first, last, sprout::pit<Result>());
}
} // namespace fit
} // namespace sprout
#endif // #ifndef SPROUT_NUMERIC_DFT_FIT_DFT_HPP
| [
"[email protected]"
] | |
7a97dbc5ea8a42c4315bd382fd2c1dfdf1da422d | 89dedd7f3c7acc81d12e2bcb2e716f9af9e5fa04 | /third_party/WebKit/Source/platform/DragImage.cpp | 93726fe852eba917efa24cb21e3bbd3e42fb69cb | [
"BSD-3-Clause",
"LGPL-2.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-1.0-or-later",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft",
"MIT",
"Apache-2.0"
] | permissive | bino7/chromium | 8d26f84a1b6e38a73d1b97fea6057c634eff68cb | 4666a6bb6fdcb1114afecf77bdaa239d9787b752 | refs/heads/master | 2022-12-22T14:31:53.913081 | 2016-09-06T10:05:11 | 2016-09-06T10:05:11 | 67,410,510 | 1 | 3 | BSD-3-Clause | 2022-12-17T03:08:52 | 2016-09-05T10:11:59 | null | UTF-8 | C++ | false | false | 11,166 | cpp | /*
* Copyright (C) 2007 Apple 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:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "platform/DragImage.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "platform/fonts/Font.h"
#include "platform/fonts/FontCache.h"
#include "platform/fonts/FontDescription.h"
#include "platform/fonts/FontMetrics.h"
#include "platform/geometry/FloatPoint.h"
#include "platform/geometry/FloatRect.h"
#include "platform/geometry/IntPoint.h"
#include "platform/graphics/BitmapImage.h"
#include "platform/graphics/Color.h"
#include "platform/graphics/GraphicsContext.h"
#include "platform/graphics/Image.h"
#include "platform/graphics/ImageBuffer.h"
#include "platform/graphics/paint/DrawingRecorder.h"
#include "platform/graphics/paint/SkPictureBuilder.h"
#include "platform/text/BidiTextRun.h"
#include "platform/text/StringTruncator.h"
#include "platform/text/TextRun.h"
#include "platform/transforms/AffineTransform.h"
#include "platform/weborigin/KURL.h"
#include "skia/ext/image_operations.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkImage.h"
#include "third_party/skia/include/core/SkMatrix.h"
#include "third_party/skia/include/core/SkSurface.h"
#include "wtf/PtrUtil.h"
#include "wtf/RefPtr.h"
#include "wtf/text/WTFString.h"
#include <algorithm>
#include <memory>
namespace blink {
namespace {
const float kDragLabelBorderX = 4;
// Keep border_y in synch with DragController::LinkDragBorderInset.
const float kDragLabelBorderY = 2;
const float kLabelBorderYOffset = 2;
const float kMaxDragLabelWidth = 300;
const float kMaxDragLabelStringWidth = (kMaxDragLabelWidth - 2 * kDragLabelBorderX);
const float kDragLinkLabelFontSize = 11;
const float kDragLinkUrlFontSize = 10;
} // anonymous namespace
sk_sp<SkImage> DragImage::resizeAndOrientImage(sk_sp<SkImage> image, ImageOrientation orientation,
FloatSize imageScale, float opacity, InterpolationQuality interpolationQuality)
{
IntSize size(image->width(), image->height());
size.scale(imageScale.width(), imageScale.height());
AffineTransform transform;
if (orientation != DefaultImageOrientation) {
if (orientation.usesWidthAsHeight())
size = size.transposedSize();
transform *= orientation.transformFromDefault(FloatSize(size));
}
transform.scaleNonUniform(imageScale.width(), imageScale.height());
if (size.isEmpty())
return nullptr;
if (transform.isIdentity() && opacity == 1) {
// Nothing to adjust, just use the original.
ASSERT(image->width() == size.width());
ASSERT(image->height() == size.height());
return image;
}
sk_sp<SkSurface> surface = SkSurface::MakeRasterN32Premul(size.width(), size.height());
if (!surface)
return nullptr;
SkPaint paint;
ASSERT(opacity >= 0 && opacity <= 1);
paint.setAlpha(opacity * 255);
paint.setFilterQuality(interpolationQuality == InterpolationNone
? kNone_SkFilterQuality : kHigh_SkFilterQuality);
SkCanvas* canvas = surface->getCanvas();
canvas->concat(affineTransformToSkMatrix(transform));
canvas->drawImage(image, 0, 0, &paint);
return surface->makeImageSnapshot();
}
FloatSize DragImage::clampedImageScale(const IntSize& imageSize, const IntSize& size,
const IntSize& maxSize)
{
// Non-uniform scaling for size mapping.
FloatSize imageScale(
static_cast<float>(size.width()) / imageSize.width(),
static_cast<float>(size.height()) / imageSize.height());
// Uniform scaling for clamping.
const float clampScaleX = size.width() > maxSize.width()
? static_cast<float>(maxSize.width()) / size.width() : 1;
const float clampScaleY = size.height() > maxSize.height()
? static_cast<float>(maxSize.height()) / size.height() : 1;
imageScale.scale(std::min(clampScaleX, clampScaleY));
return imageScale;
}
std::unique_ptr<DragImage> DragImage::create(Image* image,
RespectImageOrientationEnum shouldRespectImageOrientation, float deviceScaleFactor,
InterpolationQuality interpolationQuality, float opacity, FloatSize imageScale)
{
if (!image)
return nullptr;
sk_sp<SkImage> skImage = image->imageForCurrentFrame();
if (!skImage)
return nullptr;
ImageOrientation orientation;
if (shouldRespectImageOrientation == RespectImageOrientation && image->isBitmapImage())
orientation = toBitmapImage(image)->currentFrameOrientation();
SkBitmap bm;
sk_sp<SkImage> resizedImage =
resizeAndOrientImage(std::move(skImage), orientation, imageScale, opacity, interpolationQuality);
if (!resizedImage || !resizedImage->asLegacyBitmap(&bm, SkImage::kRO_LegacyBitmapMode))
return nullptr;
return wrapUnique(new DragImage(bm, deviceScaleFactor, interpolationQuality));
}
static Font deriveDragLabelFont(int size, FontWeight fontWeight, const FontDescription& systemFont)
{
FontDescription description = systemFont;
description.setWeight(fontWeight);
description.setSpecifiedSize(size);
description.setComputedSize(size);
Font result(description);
result.update(nullptr);
return result;
}
std::unique_ptr<DragImage> DragImage::create(const KURL& url, const String& inLabel, const FontDescription& systemFont, float deviceScaleFactor)
{
const Font labelFont = deriveDragLabelFont(kDragLinkLabelFontSize, FontWeightBold, systemFont);
const Font urlFont = deriveDragLabelFont(kDragLinkUrlFontSize, FontWeightNormal, systemFont);
FontCachePurgePreventer fontCachePurgePreventer;
bool drawURLString = true;
bool clipURLString = false;
bool clipLabelString = false;
float maxDragLabelStringWidthDIP = kMaxDragLabelStringWidth / deviceScaleFactor;
String urlString = url.getString();
String label = inLabel.stripWhiteSpace();
if (label.isEmpty()) {
drawURLString = false;
label = urlString;
}
// First step is drawing the link drag image width.
TextRun labelRun(label.impl());
TextRun urlRun(urlString.impl());
IntSize labelSize(labelFont.width(labelRun), labelFont.getFontMetrics().ascent() + labelFont.getFontMetrics().descent());
if (labelSize.width() > maxDragLabelStringWidthDIP) {
labelSize.setWidth(maxDragLabelStringWidthDIP);
clipLabelString = true;
}
IntSize urlStringSize;
IntSize imageSize(labelSize.width() + kDragLabelBorderX * 2, labelSize.height() + kDragLabelBorderY * 2);
if (drawURLString) {
urlStringSize.setWidth(urlFont.width(urlRun));
urlStringSize.setHeight(urlFont.getFontMetrics().ascent() + urlFont.getFontMetrics().descent());
imageSize.setHeight(imageSize.height() + urlStringSize.height());
if (urlStringSize.width() > maxDragLabelStringWidthDIP) {
imageSize.setWidth(maxDragLabelStringWidthDIP);
clipURLString = true;
} else
imageSize.setWidth(std::max(labelSize.width(), urlStringSize.width()) + kDragLabelBorderX * 2);
}
// We now know how big the image needs to be, so we create and
// fill the background
IntSize scaledImageSize = imageSize;
scaledImageSize.scale(deviceScaleFactor);
std::unique_ptr<ImageBuffer> buffer(ImageBuffer::create(scaledImageSize));
if (!buffer)
return nullptr;
buffer->canvas()->scale(deviceScaleFactor, deviceScaleFactor);
const float DragLabelRadius = 5;
IntRect rect(IntPoint(), imageSize);
SkPaint backgroundPaint;
backgroundPaint.setColor(SkColorSetRGB(140, 140, 140));
SkRRect rrect;
rrect.setRectXY(SkRect::MakeWH(imageSize.width(), imageSize.height()), DragLabelRadius, DragLabelRadius);
buffer->canvas()->drawRRect(rrect, backgroundPaint);
// Draw the text
SkPaint textPaint;
if (drawURLString) {
if (clipURLString)
urlString = StringTruncator::centerTruncate(urlString, imageSize.width() - (kDragLabelBorderX * 2.0f), urlFont);
IntPoint textPos(kDragLabelBorderX, imageSize.height() - (kLabelBorderYOffset + urlFont.getFontMetrics().descent()));
TextRun textRun(urlString);
urlFont.drawText(buffer->canvas(), TextRunPaintInfo(textRun), textPos, deviceScaleFactor, textPaint);
}
if (clipLabelString)
label = StringTruncator::rightTruncate(label, imageSize.width() - (kDragLabelBorderX * 2.0f), labelFont);
bool hasStrongDirectionality;
TextRun textRun = textRunWithDirectionality(label, &hasStrongDirectionality);
IntPoint textPos(kDragLabelBorderX, kDragLabelBorderY + labelFont.getFontDescription().computedPixelSize());
if (hasStrongDirectionality && textRun.direction() == RTL) {
float textWidth = labelFont.width(textRun);
int availableWidth = imageSize.width() - kDragLabelBorderX * 2;
textPos.setX(availableWidth - ceilf(textWidth));
}
labelFont.drawBidiText(buffer->canvas(), TextRunPaintInfo(textRun), FloatPoint(textPos), Font::DoNotPaintIfFontNotReady, deviceScaleFactor, textPaint);
RefPtr<Image> image = buffer->newImageSnapshot();
return DragImage::create(image.get(), DoNotRespectImageOrientation, deviceScaleFactor);
}
DragImage::DragImage(const SkBitmap& bitmap, float resolutionScale, InterpolationQuality interpolationQuality)
: m_bitmap(bitmap)
, m_resolutionScale(resolutionScale)
, m_interpolationQuality(interpolationQuality)
{
}
DragImage::~DragImage()
{
}
void DragImage::scale(float scaleX, float scaleY)
{
skia::ImageOperations::ResizeMethod resizeMethod = m_interpolationQuality == InterpolationNone ? skia::ImageOperations::RESIZE_BOX : skia::ImageOperations::RESIZE_LANCZOS3;
int imageWidth = scaleX * m_bitmap.width();
int imageHeight = scaleY * m_bitmap.height();
m_bitmap = skia::ImageOperations::Resize(m_bitmap, resizeMethod, imageWidth, imageHeight);
}
} // namespace blink
| [
"[email protected]"
] | |
cfe7a2c4014b02d0bb06b7e3e91bf4ac0c9c474a | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/mutt/gumtree/mutt_old_hunk_131.cpp | de9862b12ec64b3334e4a50716eb1773870544d9 | [] | 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 | 467 | cpp | #define CURHDR Context->hdrs[Context->v2r[menu->current]]
#define OLDHDR Context->hdrs[Context->v2r[menu->oldcurrent]]
#define UNREAD(h) mutt_thread_contains_unread (Context, h)
extern size_t UngetCount;
void index_make_entry (char *s, size_t l, MUTTMENU *menu, int num)
{
format_flag flag = M_FORMAT_MAKEPRINT | M_FORMAT_ARROWCURSOR | M_FORMAT_INDEX;
int edgemsgno, reverse = Sort & SORT_REVERSE;
HEADER *h = Context->hdrs[Context->v2r[num]];
THREAD *tmp;
| [
"[email protected]"
] | |
d51ba7d67b94914b8364f048a460d556c557922b | 35be95e5e4ef306a1203a173bed12599f62db7b6 | /SlimDXc_Jun2010(VC++2008)/source/direct3d11/StreamOutputElement11.cpp | 4354ca236d8bd22d13fa8b078bff868493340ece | [
"MIT"
] | permissive | Orz5566/RandomTest | dd0ec2eb7a0db3993409c2a647658a175a3b4027 | 2884f99d29dda603c646d464a60d7bce3346b74d | refs/heads/master | 2021-09-06T01:10:29.460192 | 2018-02-01T06:56:53 | 2018-02-01T06:56:53 | 118,869,777 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,560 | cpp | /*
* Copyright (c) 2007-2012 SlimDX Group
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "stdafx.h"
#include "Direct3D11Exception.h"
#include "Device11.h"
#include "StreamOutputElement11.h"
using namespace System;
using namespace System::Runtime::InteropServices;
namespace SlimDX
{
namespace Direct3D11
{
StreamOutputElement::StreamOutputElement( int stream, String^ name, int index, int startComponent, int componentCount, int outputSlot )
{
Stream = stream;
SemanticName = name;
SemanticIndex = index;
StartComponent = startComponent;
ComponentCount = componentCount;
OutputSlot = outputSlot;
}
D3D11_SO_DECLARATION_ENTRY StreamOutputElement::CreateNativeVersion()
{
D3D11_SO_DECLARATION_ENTRY native;
native.Stream = Stream;
native.SemanticName = Utilities::AllocateNativeString( SemanticName );
native.SemanticIndex = SemanticIndex;
native.StartComponent = static_cast<BYTE>(StartComponent);
native.ComponentCount = static_cast<BYTE>(ComponentCount);
native.OutputSlot = static_cast<BYTE>(OutputSlot);
return native;
}
bool StreamOutputElement::operator == ( StreamOutputElement left, StreamOutputElement right )
{
return StreamOutputElement::Equals( left, right );
}
bool StreamOutputElement::operator != ( StreamOutputElement left, StreamOutputElement right )
{
return !StreamOutputElement::Equals( left, right );
}
int StreamOutputElement::GetHashCode()
{
return SemanticName->GetHashCode() + SemanticIndex.GetHashCode() + StartComponent.GetHashCode()
+ OutputSlot.GetHashCode() + ComponentCount.GetHashCode()
+ Stream.GetHashCode();
}
bool StreamOutputElement::Equals( Object^ value )
{
if( value == nullptr )
return false;
if( value->GetType() != GetType() )
return false;
return Equals( safe_cast<StreamOutputElement>( value ) );
}
bool StreamOutputElement::Equals( StreamOutputElement value )
{
return ( SemanticName == value.SemanticName && SemanticIndex == value.SemanticIndex && StartComponent == value.StartComponent
&& OutputSlot == value.OutputSlot && ComponentCount == value.ComponentCount
&& Stream == value.Stream );
}
bool StreamOutputElement::Equals( StreamOutputElement% value1, StreamOutputElement% value2 )
{
return ( value1.SemanticName == value2.SemanticName && value1.SemanticIndex == value2.SemanticIndex && value1.StartComponent == value2.StartComponent
&& value1.OutputSlot == value2.OutputSlot && value1.ComponentCount == value2.ComponentCount
&& value1.Stream == value2.Stream );
}
}
}
| [
"[email protected]"
] | |
58824523ccfc2e6e0434e21d234aabbd077cadeb | 7d8a941a21174bf6c97447f01686d9de874e7efd | /src/Console/Commands/GenerateCommand.hpp | af378ca2bb01a1da75bea4fae3d2b8016a0d925c | [
"Apache-2.0"
] | permissive | zephir-lang/zephirc | 397710746e24a5b91f226e5fd127761b3d93090a | 2b8f77d7822121b6a8d5657d720f795fcc8f72ba | refs/heads/master | 2020-08-09T05:52:49.309369 | 2020-01-21T09:28:09 | 2020-01-21T09:28:09 | 214,012,252 | 7 | 1 | Apache-2.0 | 2020-01-21T09:28:10 | 2019-10-09T20:00:42 | C++ | UTF-8 | C++ | false | false | 1,495 | hpp | // This file is part of the Zephir.
//
// (c) Phalcon Team <[email protected]>
//
// For the full copyright and license information, please view
// the LICENSE file that was distributed with this source code.
/// \file GenerateCommand.hpp
/// \brief Provides GenerateOptions, GenerateOptionsPtr and GenerateCommand.
#ifndef ZEPHIR_CLI_COMMANDS_GENERATE_HPP_
#define ZEPHIR_CLI_COMMANDS_GENERATE_HPP_
#include <memory>
#include <string>
#include "AbstractCommand.hpp"
namespace zephir::console::commands {
/// \brief Collection of all options of GenerateCommand subcommand.
struct GenerateOptions {
/// Used backend to generate extension.
std::string backend{""};
};
/// \brief A type definition for a unique pointer to a GenerateOptions instance.
using GenerateOptionsPtr = std::unique_ptr<GenerateOptions>;
/// \brief Generates C code from the Zephir code without compiling it.
/// \sa AbstractCommand
class GenerateCommand : public AbstractCommand {
public:
/// \brief Construct GenerateCommand object with a given name.
///
/// \param name The name of the command
explicit GenerateCommand(std::string name);
/// \brief Configures the GenerateCommand command.
///
/// \param app A `CLI::App` instance
void Setup(std::shared_ptr<CLI::App> app) override;
/// \brief Executes GenerateCommand command.
void Execute() override;
private:
GenerateOptionsPtr options_;
};
} // namespace zephir::console::commands
#endif // ZEPHIR_CLI_COMMANDS_GENERATE_HPP_
| [
"[email protected]"
] | |
9f3121eb1aa87acbad89d978d72590b3ce60a0f1 | 2eb446d49123a21799e54a249c85f3b6a530e482 | /bsnes/fc/cartridge/board/nes-nrom.cpp | 0cdbc5cd14d75a60327af10cacf5b1dd10a5ba2b | [] | no_license | nelsonnan/BSNES-Core | 38dc43e28d9342311e6d4698125e1d4db31e61e7 | 4d86bfa2c2cab624b2c1d0de65a2a72fa9933ab9 | refs/heads/master | 2021-01-16T22:17:20.326557 | 2014-02-08T22:23:07 | 2014-02-08T22:23:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,024 | cpp | //NES-NROM-128
//NES-NROM-256
struct NES_NROM : Board {
struct Settings {
bool mirror; //0 = horizontal, 1 = vertical
} settings;
uint8 prg_read(unsigned addr) {
if(addr & 0x8000) return prgrom.read(addr);
return cpu.mdr();
}
void prg_write(unsigned addr, uint8 data) {
}
uint8 chr_read(unsigned addr) {
if(addr & 0x2000) {
if(settings.mirror == 0) addr = ((addr & 0x0800) >> 1) | (addr & 0x03ff);
return ppu.ciram_read(addr & 0x07ff);
}
if(chrram.size) return chrram.read(addr);
return chrrom.read(addr);
}
void chr_write(unsigned addr, uint8 data) {
if(addr & 0x2000) {
if(settings.mirror == 0) addr = ((addr & 0x0800) >> 1) | (addr & 0x03ff);
return ppu.ciram_write(addr & 0x07ff, data);
}
if(chrram.size) return chrram.write(addr, data);
}
void serialize(serializer &s) {
Board::serialize(s);
}
NES_NROM(XML::Document &document, const stream &memory) : Board(document, memory) {
settings.mirror = document["cartridge"]["mirror"]["mode"].data == "vertical" ? 1 : 0;
}
};
| [
"[email protected]"
] | |
a6820e9d4f70a4fb91c048f4b0cba924dec7f12b | ccf3c834556738c9819718989eec76428481a280 | /SteppingMotoerTest_dv32u/L6470_commands.ino | 103fe5801ef9dbbe7be88212f4c34042bb673036 | [] | no_license | BirdAndEarth/Arduino | 14d3eed8bb59fc3a70b6477ce54652b4980b9dbb | b199c2433c5da69e614d4e08cc9e2782ccfa6a10 | refs/heads/master | 2021-05-02T12:38:20.369836 | 2017-06-22T08:11:19 | 2017-06-22T08:11:19 | 43,566,590 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 10,214 | ino | /*ver 1.00 2013/4/24*/
/*L6470 コントロール コマンド
引数-----------------------
dia 1:正転 0:逆転,
spd (20bit)(0.015*spd[step/s])
pos (22bit)
n_step (22bit)
act 1:絶対座標をマーク 0:絶対座標リセット
mssec ミリ秒
val 各レジスタに書き込む値
---------------------------
L6470_run(dia,spd); //指定した回転方向に連続回転
L6470_stepclock(dia); //指定した回転方向にstepピンのクロックで回転
L6470_move(dia,n_step); //指定方向に指定数ステップする
L6470_goto(pos); //指定座標に移動
L6470_gotodia(dia,pos); //回転方向を指定して指定座標に移動
L6470_gountil(act,dia,spd); //指定した回転方向に指定した速度で回転し、スイッチのONで急停止と座標処理
L6470_relesesw(act,dia); //スイッチがOFFに戻るまで最低速度で回転し、停止と座標処理
L6470_gohome(); //座標原点に移動
L6470_gomark(); //マーク座標に移動
L6470_resetpos(); //絶対座標リセット
L6470_resetdevice(); //L6470リセット
L6470_softstop(); //回転停止、保持トルクあり
L6470_hardstop(); //回転急停止、保持トルクあり
L6470_softhiz(); //回転停止、保持トルクなし
L6470_hardhiz(); //回転急停止、保持トルクなし
L6470_getstatus(); //statusレジスタの値を返す (L6470_getparam_status();と同じ)
L6470_busydelay(msec); //busyフラグがHIGHになってから、指定ミリ秒待つ。
レジスタ書き込みコマンド
L6470_setparam_abspos(val); //default 0x000000 (22bit)
L6470_setparam_elpos(val); //default 0x000 (2+7bit)
L6470_setparam_mark(val); //default 0x000000 (22bit)
//L6470_spped //read onry (20bit)
L6470_setparam_acc(val); //default 0x08A (12bit) (14.55*val+14.55[step/s^2])
L6470_setparam_dec(val); //default 0x08A (12bit) (14.55*val+14.55[step/s^2])
L6470_setparam_maxspeed(val); //default 0x041 (10bit) (15.25*val+15.25[step/s])
L6470_setparam_minspeed(val); //default 0x000 (1+12bit) (0.238*val+[step/s])
L6470_setparam_fsspd(val); //default 0x027 (10bit) (15.25*val+7.63[step/s])
L6470_setparam_kvalhold(val); //default 0x29 (8bit) (Vs[V]*val/256)
L6470_setparam_kvalrun(val); //default 0x29 (8bit) (Vs[V]*val/256)
L6470_setparam_kvalacc(val); //default 0x29 (8bit) (Vs[V]*val/256)
L6470_setparam_kvaldec(val); //default 0x29 (8bit) (Vs[V]*val/256)
L6470_setparam_intspd(val); //default 0x0408 (14bit) (0.238*val[step/s])
L6470_setparam_stslp(val); //default 0x19 (8bit) (0.000015*val)
L6470_setparam_fnslpacc(val); //default 0x29 (8bit) (0.000015*val)
L6470_setparam_fnslpdec(val); //default 0x29 (8bit) (0.000015*val)
L6470_setparam_ktherm(val); //default 0x0 (4bit) (0.03125*val+1)
//L6470_adcout //read onry (5bit)
L6470_setparam_ocdth(val); //default 0x8 (4bit) (375*val+375[mV])
L6470_setparam_stallth(val); //default 0x40 (7bit) (31.25*val+31.25[mV])
L6470_setparam_stepmood(val); //default 0x07 (1+3+1+3bit)
L6470_setparam_alareen(val); //default 0xff (1+1+1+1+1+1+1+1bit)
L6470_setparam_config(val); //default 0x2e88 (3+3+2+1+1+1+1+1+3bit)
//L6470_status //read onry (16bit)
レジスタ読み込みコマンド(返り値 long型)
L6470_getparam_abspos();
L6470_getparam_elpos();
L6470_getparam_mark();
L6470_getparam_speed();
L6470_getparam_acc();
L6470_getparam_dec();
L6470_getparam_maxspeed();
L6470_getparam_minspeed();
L6470_getparam_fsspd();
L6470_getparam_kvalhold();
L6470_getparam_kvalrun();
L6470_getparam_kvalacc();
L6470_getparam_kvaldec();
L6470_getparam_intspd();
L6470_getparam_stslp();
L6470_getparam_fnslpacc();
L6470_getparam_fnslpdec();
L6470_getparam_ktherm();
L6470_getparam_adcout();
L6470_getparam_ocdth();
L6470_getparam_stallth();
L6470_getparam_stepmood();
L6470_getparam_alareen();
L6470_getparam_config();
L6470_getparam_status();
*/
void L6470_setparam_abspos(long val){L6470_transfer(0x01,3,val);}
void L6470_setparam_elpos(long val){L6470_transfer(0x02,2,val);}
void L6470_setparam_mark(long val){L6470_transfer(0x03,3,val);}
void L6470_setparam_acc(long val){L6470_transfer(0x05,2,val);}
void L6470_setparam_dec(long val){L6470_transfer(0x06,2,val);}
void L6470_setparam_maxspeed(long val){L6470_transfer(0x07,2,val);}
void L6470_setparam_minspeed(long val){L6470_transfer(0x08,2,val);}
void L6470_setparam_fsspd(long val){L6470_transfer(0x15,2,val);}
void L6470_setparam_kvalhold(long val){L6470_transfer(0x09,1,val);}
void L6470_setparam_kvalrun(long val){L6470_transfer(0x0a,1,val);}
void L6470_setparam_kvalacc(long val){L6470_transfer(0x0b,1,val);}
void L6470_setparam_kvaldec(long val){L6470_transfer(0x0c,1,val);}
void L6470_setparam_intspd(long val){L6470_transfer(0x0d,2,val);}
void L6470_setparam_stslp(long val){L6470_transfer(0x0e,1,val);}
void L6470_setparam_fnslpacc(long val){L6470_transfer(0x0f,1,val);}
void L6470_setparam_fnslpdec(long val){L6470_transfer(0x10,1,val);}
void L6470_setparam_ktherm(long val){L6470_transfer(0x11,1,val);}
void L6470_setparam_ocdth(long val){L6470_transfer(0x13,1,val);}
void L6470_setparam_stallth(long val){L6470_transfer(0x14,1,val);}
void L6470_setparam_stepmood(long val){L6470_transfer(0x16,1,val);}
void L6470_setparam_alareen(long val){L6470_transfer(0x17,1,val);}
void L6470_setparam_config(long val){L6470_transfer(0x18,2,val);}
long L6470_getparam_abspos(){return L6470_getparam(0x01,3);}
long L6470_getparam_elpos(){return L6470_getparam(0x02,2);}
long L6470_getparam_mark(){return L6470_getparam(0x03,3);}
long L6470_getparam_speed(){return L6470_getparam(0x04,3);}
long L6470_getparam_acc(){return L6470_getparam(0x05,2);}
long L6470_getparam_dec(){return L6470_getparam(0x06,2);}
long L6470_getparam_maxspeed(){return L6470_getparam(0x07,2);}
long L6470_getparam_minspeed(){return L6470_getparam(0x08,2);}
long L6470_getparam_fsspd(){return L6470_getparam(0x15,2);}
long L6470_getparam_kvalhold(){return L6470_getparam(0x09,1);}
long L6470_getparam_kvalrun(){return L6470_getparam(0x0a,1);}
long L6470_getparam_kvalacc(){return L6470_getparam(0x0b,1);}
long L6470_getparam_kvaldec(){return L6470_getparam(0x0c,1);}
long L6470_getparam_intspd(){return L6470_getparam(0x0d,2);}
long L6470_getparam_stslp(){return L6470_getparam(0x0e,1);}
long L6470_getparam_fnslpacc(){return L6470_getparam(0x0f,1);}
long L6470_getparam_fnslpdec(){return L6470_getparam(0x10,1);}
long L6470_getparam_ktherm(){return L6470_getparam(0x11,1);}
long L6470_getparam_adcout(){return L6470_getparam(0x12,1);}
long L6470_getparam_ocdth(){return L6470_getparam(0x13,1);}
long L6470_getparam_stallth(){return L6470_getparam(0x14,1);}
long L6470_getparam_stepmood(){return L6470_getparam(0x16,1);}
long L6470_getparam_alareen(){return L6470_getparam(0x17,1);}
long L6470_getparam_config(){return L6470_getparam(0x18,2);}
long L6470_getparam_status(){return L6470_getparam(0x19,2);}
void L6470_run(int dia,long spd){
if(dia==1)
L6470_transfer(0x51,3,spd);
else
L6470_transfer(0x50,3,spd);
}
void L6470_stepclock(int dia){
if(dia==1)
L6470_transfer(0x59,0,0);
else
L6470_transfer(0x58,0,0);
}
void L6470_move(int dia,long n_step){
if(dia==1)
L6470_transfer(0x41,3,n_step);
else
L6470_transfer(0x40,3,n_step);
}
void L6470_goto(long pos){
L6470_transfer(0x60,3,pos);
}
void L6470_gotodia(int dia,int pos){
if(dia==1)
L6470_transfer(0x69,3,pos);
else
L6470_transfer(0x68,3,pos);
}
void L6470_gountil(int act,int dia,long spd){
if(act==1)
if(dia==1)
L6470_transfer(0x8b,3,spd);
else
L6470_transfer(0x8a,3,spd);
else
if(dia==1)
L6470_transfer(0x83,3,spd);
else
L6470_transfer(0x82,3,spd);
}
void L6470_relesesw(int act,int dia){
if(act==1)
if(dia==1)
L6470_transfer(0x9b,0,0);
else
L6470_transfer(0x9a,0,0);
else
if(dia==1)
L6470_transfer(0x93,0,0);
else
L6470_transfer(0x92,0,0);
}
void L6470_gohome(){
L6470_transfer(0x70,0,0);
}
void L6470_gomark(){
L6470_transfer(0x78,0,0);
}
void L6470_resetpos(){
L6470_transfer(0xd8,0,0);
}
void L6470_resetdevice(){
L6470_send_u(0x00);//nop命令
L6470_send_u(0x00);
L6470_send_u(0x00);
L6470_send_u(0x00);
L6470_send_u(0xc0);
}
void L6470_softstop(){
L6470_transfer(0xb0,0,0);
}
void L6470_hardstop(){
L6470_transfer(0xb8,0,0);
}
void L6470_softhiz(){
L6470_transfer(0xa0,0,0);
}
void L6470_hardhiz(){
L6470_transfer(0xa8,0,0);
}
long L6470_getstatus(){
long val=0;
L6470_send_u(0xd0);
for(int i=0;i<=1;i++){
val = val << 8;
digitalWrite(PIN_SPI_SS, LOW); // ~SSイネーブル。
val = val | SPI.transfer(0x00); // アドレスもしくはデータ送信。
digitalWrite(PIN_SPI_SS, HIGH); // ~SSディスエーブル
}
return val;
}
void L6470_transfer(int add,int bytes,long val){
int data[3];
L6470_send(add);
for(int i=0;i<=bytes-1;i++){
data[i] = val & 0xff;
val = val >> 8;
}
if(bytes==3){
L6470_send(data[2]);
}
if(bytes>=2){
L6470_send(data[1]);
}
if(bytes>=1){
L6470_send(data[0]);
}
}
void L6470_send(unsigned char add_or_val){
while(!digitalRead(PIN_BUSY)){
} //BESYが解除されるまで待機
digitalWrite(PIN_SPI_SS, LOW); // ~SSイネーブル。
SPI.transfer(add_or_val); // アドレスもしくはデータ送信。
digitalWrite(PIN_SPI_SS, HIGH); // ~SSディスエーブル。
}
void L6470_send_u(unsigned char add_or_val){//busyを確認せず送信するため用
digitalWrite(PIN_SPI_SS, LOW); // ~SSイネーブル。
SPI.transfer(add_or_val); // アドレスもしくはデータ送信。
digitalWrite(PIN_SPI_SS, HIGH); // ~SSディスエーブル。
}
void L6470_busydelay(long time){//BESYが解除されるまで待機
while(!digitalRead(PIN_BUSY)){
}
delay(time);
}
long L6470_getparam(int add,int bytes){
long val=0;
int send_add = add | 0x20;
L6470_send_u(send_add);
for(int i=0;i<=bytes-1;i++){
val = val << 8;
digitalWrite(PIN_SPI_SS, LOW); // ~SSイネーブル。
val = val | SPI.transfer(0x00); // アドレスもしくはデータ送信。
digitalWrite(PIN_SPI_SS, HIGH); // ~SSディスエーブル
}
return val;
}
| [
"[email protected]"
] | |
a295514490a6056e191d36dd2506028218d9b2dd | fc3c7d3b0c89906ce37589e7b37870ecc357e83e | /homework7/observable.h | 31e193951ea94030e29f4fa75506004c15b24f82 | [] | no_license | gromakovski/clone_repo | 283b633716a66b8742955ce09f653bc7f4ff5375 | cfdb081411c95a705425645ded61bb186046b96d | refs/heads/master | 2020-09-07T16:51:58.960893 | 2019-11-10T21:24:34 | 2019-11-10T21:24:34 | 220,851,558 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 448 | h | #ifndef OBSERVABLE_H
#define OBSERVABLE_H
#include <vector>
#include "observer.h"
class Observable {
public:
void addObserver(Observer *observer) { _observers.push_back(observer); }
void notifyUpdate(std::string data, std::time_t time = 0) {
int size = _observers.size();
for (int i = 0; i < size; i++) {
_observers[i]->update(data, time);
}
}
private:
std::vector<Observer *> _observers;
};
#endif // OBSERVABLE_H
| [
"gromakovski"
] | gromakovski |
d782cf3b44f3aa5db028504b812be965a3d1de84 | fc84b697c8584300cafbef4ade7ccf1618074d97 | /deprecated.h | 1c3774b7858371ab9e2e64dcc9f6a8de1d99290d | [] | no_license | orebas/GyroAveraging | 43808614f05e94da0d74151aa6504d00b67707e9 | 564fd34c7bdb74711cb098a5e4407e497b62bbfe | refs/heads/master | 2021-06-28T08:10:48.916197 | 2021-03-19T02:06:22 | 2021-03-19T02:06:22 | 226,803,821 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 68,435 | h |
void testInterpImprovement();
template <int rhocount, int xcount, int ycount, class RealT = double>
class GyroAveragingGrid {
public:
typedef Array3d<rhocount, xcount, ycount, RealT> fullgrid;
typedef Array4d<rhocount, xcount, ycount, 4, RealT> fullgridInterp;
typedef Array4d<rhocount, xcount, ycount, 4, RealT>
derivsGrid; // at each rho,x,y calculate [f,f_x,f_y,f_xy]
typedef Array4d<rhocount, xcount, ycount, 16, RealT> bicubicParameterGrid;
typedef Eigen::SparseMatrix<RealT, Eigen::RowMajor> SpM;
typedef Eigen::Triplet<RealT> SpT;
private:
std::vector<RealT> rhoset;
std::vector<RealT> xset;
std::vector<RealT> yset;
fullgrid gridValues; // input values of f
fullgrid almostExactGA; // stores value of GA calculated as trapezoid rule
// on input f
fullgrid truncatedAlmostExactGA; // above, except f hard truncated to 0
// outside grid
fullgrid trapezoidInterp; // GA calculated as trapezoid rule on
// interpolated, truncated f
fullgrid bicubicInterp;
fullgrid fastGALTResult;
fullgrid BCResult;
fullgrid
analytic_averages; // stores value of expected GA computed analytically
fullgridInterp
interpParameters; // will store the bilinear interp parameters.
bicubicParameterGrid bicubicParameters;
SpM LTOffsetTensor;
SpM BCOffsetTensor;
SpM FDTensor; // finite difference tensor, used to populate derivs from
// gridValues
derivsGrid derivs;
void csvPrinter(const fullgrid &m, int rho) {
for (int j = 0; j < xcount; j++) {
for (int k = 0; k < ycount; k++) {
std::cout << m(rho, j, k) << ",";
}
std::cout << std::endl;
}
}
void testInterpImprovement();
void csvPrinterDiff(const fullgrid &m, const fullgrid &n, int rho) {
for (int j = 0; j < xcount; j++) {
for (int k = 0; k < ycount; k++) {
std::cout << m(rho, j, k) - n(rho, j, k) << ",";
}
std::cout << std::endl;
}
}
void clearGrid(fullgrid &m) {
for (auto i = 0; i < rhocount; i++) {
for (auto j = 0; j < xcount; j++)
for (auto k = 0; k < ycount; k++) {
m(i, j, k) = 0;
}
}
}
RealT RMSNorm(const fullgrid &m, int rho) {
RealT result = 0;
for (int j = 0; j < xcount; j++)
for (int k = 0; k < ycount; k++)
result += m(rho, j, k) * m(rho, j, k);
return std::sqrt(result / (xcount * ycount));
}
RealT maxNorm(const fullgrid &m, int rho) {
RealT result = 0;
for (int j = 0; j < xcount; j++)
for (int k = 0; k < ycount; k++)
result = std::max(result, std::abs(m(rho, j, k)));
return result;
}
RealT RMSNormDiff(const fullgrid &m1, const fullgrid &m2, int rho) {
RealT result = 0;
for (int j = 0; j < xcount; j++)
for (int k = 0; k < ycount; k++) {
RealT t = m1(rho, j, k) - m2(rho, j, k);
result += t * t;
}
return std::sqrt(result / (xcount * ycount));
}
RealT maxNormDiff(const fullgrid &m1, const fullgrid &m2, int rho) {
RealT result = 0;
for (int j = 0; j < xcount; j++)
for (int k = 0; k < ycount; k++) {
RealT t = m1(rho, j, k) - m2(rho, j, k);
result = std::max(result, std::abs(t));
}
return result;
}
// below fills a grid, given a function of rho, x, and y
template <typename TFunc>
void fill(fullgrid &m, TFunc f) {
#pragma omp parallel for
for (auto i = 0; i < rhocount; i++) {
for (auto j = 0; j < xcount; j++)
for (auto k = 0; k < ycount; k++) {
m(i, j, k) = f(rhoset[i], xset[j], yset[k]);
}
}
}
// below fills a grid, given a function of i,j,k
template <typename TFunc>
void fillbyindex(fullgrid &m, TFunc f) {
#pragma omp parallel for
for (int i = 0; i < rhocount; i++)
for (int j = 0; j < xcount; j++)
for (int k = 0; k < ycount; k++) {
m(i, j, k) = f(i, j, k);
}
}
template <typename TFunc1>
void fillAlmostExactGA(fullgrid &m, TFunc1 f) {
fillbyindex(
m,
[&](int i, int j, int k)
-> RealT { // adaptive trapezoid rule on actual input function.
RealT xc = xset[j];
RealT yc = yset[k];
if (rhoset[i] == 0) return f(i, xc, yc);
auto new_f = [&](RealT x) -> RealT {
return f(rhoset[i], xc + rhoset[i] * std::sin(x),
yc - rhoset[i] * std::cos(x));
};
RealT result =
GSLIntegrate(0.0, 2 * pi, new_f) / (2 * pi);
return result;
});
}
template <typename TFunc1>
void fillTruncatedAlmostExactGA(fullgrid &m, TFunc1 f) {
fillbyindex(m, [&](int i, int j, int k) -> RealT {
RealT xc = xset[j];
RealT yc = yset[k];
if (rhoset[i] == 0) return f(i, xc, yc);
auto new_f = [&](RealT x) -> RealT {
RealT ex = xc + rhoset[i] * std::sin(x);
RealT why = yc - rhoset[i] * std::cos(x);
if ((ex < xset[0]) || (ex > xset.back())) return 0;
if ((why < yset[0]) || (why > yset.back())) return 0;
return f(rhoset[i], ex, why);
};
RealT result = GSLIntegrate(0.0, 2 * pi, new_f) / (2 * pi);
return result;
});
}
template <typename TFunc1>
void fillTrapezoidInterp(
fullgrid &m, TFunc1 f) { // this calls interp2d. gridValues must be
// filled, but we don't need setupInterpGrid.
fillbyindex(m, [&](int i, int j, int k) -> RealT {
RealT xc = xset[j];
RealT yc = yset[k];
if (rhoset[i] == 0) return f(rhoset[i], xc, yc);
auto new_f = [&](RealT x) -> RealT {
return interp2d(i, xc + rhoset[i] * std::sin(x),
yc - rhoset[i] * std::cos(x));
};
RealT result = GSLIntegrate(0.0, 2 * pi, new_f) / (2 * pi);
return result;
});
}
// below requires the bicubic parameter grid to be populated.
void fillBicubicInterp(fullgrid &m) {
fillbyindex(m, [&](int i, int j, int k) -> RealT {
RealT xc = xset[j];
RealT yc = yset[k];
if (rhoset[i] == 0) return gridValues(i, j, k);
auto new_f = [&](RealT x) -> RealT {
return interpNaiveBicubic(i, xc + rhoset[i] * std::sin(x),
yc - rhoset[i] * std::cos(x));
};
RealT result = GSLIntegrate(0.0, 2 * pi, new_f) / (2 * pi);
return result;
});
}
public:
GyroAveragingGrid(const std::vector<RealT> &rhos,
const std::vector<RealT> &xes,
const std::vector<RealT> &yies)
: rhoset(rhos), xset(xes), yset(yies) {
assert(rhocount == rhos.size());
assert(xcount == xes.size());
assert(ycount == yies.size());
std::sort(xset.begin(), xset.end());
std::sort(yset.begin(), yset.end());
std::sort(rhoset.begin(), rhoset.end());
}
void interpIndexSearch(const RealT x, const RealT y, int &xindex,
int &yindex);
inline void integrand(const RealT rho, const RealT xc, const RealT yc,
const RealT gamma, RealT &xn, RealT &yn) {
xn = xc + rho * std::sin(gamma);
yn = yc - rho * std::cos(gamma);
}
void setupInterpGrid();
void setupDerivsGrid(); // make accuracy a variable later
void setupBicubicGrid();
// void setupBicubicGrid2();
void assembleFastGACalc(void);
void assembleFastBCCalc(void);
void fastLTCalcOffset();
void fastBCCalcOffset();
std::array<RealT, 4> arcIntegral(RealT rho, RealT xc, RealT yc, RealT s0,
RealT s1);
// std::array<RealT, 16> arcIntegralBicubic(RealT rho, RealT xc, RealT yc,
// RealT s0, RealT s1);
template <typename TFunc1, typename TFunc2>
void GyroAveragingTestSuite(TFunc1 f, TFunc2 analytic);
template <typename TFunc1, typename TFunc2>
void compactErrorAnalysis(TFunc1 f, TFunc2 analytic);
template <typename TFunc1, typename TFunc2>
void GPUTestSuite(TFunc1 f, TFunc2 analytic);
template <typename TFunc1, typename TFunc2>
void GPUTestSuiteBC(TFunc1 f, TFunc2 analytic);
template <typename TFunc1, typename TFunc2>
void InterpErrorAnalysis(TFunc1 f, TFunc2 analytic);
template <typename TFunc1, typename TFunc2>
void errorAnalysis(TFunc1 f, TFunc2 analytic);
template <typename TFunc1, typename TFunc2, typename TFunc3,
typename TFunc4>
void derivsErrorAnalysis(TFunc1 f, TFunc2 f_x, TFunc3 f_y, TFunc4 f_xy);
RealT interp2d(int rhoindex, const RealT x, const RealT y);
RealT interpNaiveBicubic(int rhoindex, const RealT x, const RealT y);
RealT interpNaiveBicubic2(int rhoindex, const RealT x, const RealT y);
friend void testInterpImprovement();
};
template <class RealT = double>
struct indexedPoint {
RealT xvalue = 0;
RealT yvalue = 0;
RealT s = 0; // from 0 to 2*Pi only please.
indexedPoint(RealT x = 0, RealT y = 0, RealT row = 0)
: xvalue(x), yvalue(y), s(row) {}
};
template <typename TFunc1, typename TFunc2, class RealT = double>
void interpAnalysis(const gridDomain<RealT> &g, TFunc1 f, TFunc2 analytic);
template <typename TFunc1, typename TFunc2, class RealT = double>
void errorAnalysis(const gridDomain<RealT> &g, TFunc1 f, TFunc2 analytic);
template <int i, typename TFunc1, typename TFunc2, class RealT = double>
void interpAnalysisInnerLoop(const gridDomain<RealT> &g, TFunc1 f,
TFunc2 analytic);
template <int i, typename TFunc1, typename TFunc2, class RealT = double>
void errorAnalysisInnerLoop(const gridDomain<RealT> &g, TFunc1 f,
TFunc2 analytic);
template <typename TFunc1, typename TFunc2, typename TFunc3, typename TFunc4,
class RealT = double>
void derivTest(const gridDomain<RealT> &g, TFunc1 f, TFunc2 f_x, TFunc3 f_y,
TFunc4 f_xy);
template <class RealT = double>
void inline arcIntegralBicubic(std::array<RealT, 16> &coeffs, RealT rho,
RealT xc, RealT yc, RealT s0, RealT s1);
template <class RealT = double>
void testArcIntegralBicubic();
/* setupInterpGrid is going to fill a 4d array with the A,B,C,D coefficients
such that for each i,j,k with j,k not on the top or right edge for every x,y
inside the box xset[j],xset[j+1],yset[k],yset[k+1] interp2d(i,x,y,etc) =
A+Bx+Cy+Dxy (approx)
*/
template <int rhocount, int xcount, int ycount, class RealT>
void GyroAveragingGrid<rhocount, xcount, ycount, RealT>::setupInterpGrid() {
// using namespace Eigen;
for (int i = 0; i < rhocount; i++) {
interpParameters(i, xcount - 1, ycount - 1, 0) =
0; // we set the top-right grid points to 0
interpParameters(i, xcount - 1, ycount - 1, 1) =
0; // so we can point to them later.
interpParameters(i, xcount - 1, ycount - 1, 2) =
0; // otherwise the right and top edges are not used.
interpParameters(i, xcount - 1, ycount - 1, 3) = 0;
for (int j = 0; j < xcount - 1; j++)
for (int k = 0; k < ycount - 1; k++) {
RealT Q11 = gridValues(i, j, k), Q12 = gridValues(i, j + 1, k),
Q21 = gridValues(i, j, k + 1),
Q22 = gridValues(i, j + 1, k + 1);
RealT x = xset[j], a = xset[j + 1], y = yset[k],
b = yset[k + 1];
RealT denom = (a - x) * (b - y);
interpParameters(i, j, k, 0) =
(a * b * Q11 - a * y * Q12 - b * x * Q21 + x * y * Q22) /
denom;
interpParameters(i, j, k, 1) =
(-b * Q11 + y * Q12 + b * Q21 - y * Q22) / denom;
interpParameters(i, j, k, 2) =
(-a * Q11 + a * Q12 + x * Q21 - x * Q22) / denom;
interpParameters(i, j, k, 3) = (Q11 - Q12 - Q21 + Q22) / denom;
}
}
}
// Using an existing derivs grid, the below computes bicubic interpolation
// parameters.
// 16 parameters per patch, and the bicubic is of the form a_{ij} x^i y^j for 0
// \leq x,y \leq 3
template <int rhocount, int xcount, int ycount, class RealT>
void GyroAveragingGrid<rhocount, xcount, ycount, RealT>::setupBicubicGrid() {
using namespace Eigen;
bicubicParameterGrid &b = bicubicParameters;
derivsGrid &d = derivs;
for (int i = 0; i < rhocount; i++) {
// we explicitly rely on parameters being initialized to 0, including
// the top and right sides.
for (int j = 0; j < xcount - 1; j++)
for (int k = 0; k < ycount - 1; k++) {
RealT x0 = xset[j], x1 = xset[j + 1];
RealT y0 = yset[k], y1 = yset[k + 1];
Matrix<RealT, 4, 4> X, Y, RHS, A, temp1, temp2;
RHS << d(i, j, k, 0), d(i, j, k + 1, 0), d(i, j, k, 2),
d(i, j, k + 1, 2), d(i, j + 1, k, 0), d(i, j + 1, k + 1, 0),
d(i, j + 1, k, 2), d(i, j + 1, k + 1, 2), d(i, j, k, 1),
d(i, j, k + 1, 1), d(i, j, k, 3), d(i, j, k + 1, 3),
d(i, j + 1, k, 1), d(i, j + 1, k + 1, 1), d(i, j + 1, k, 3),
d(i, j + 1, k + 1, 3);
X << 1, x0, x0 * x0, x0 * x0 * x0, 1, x1, x1 * x1, x1 * x1 * x1,
0, 1, 2 * x0, 3 * x0 * x0, 0, 1, 2 * x1, 3 * x1 * x1;
Y << 1, 1, 0, 0, y0, y1, 1, 1, y0 * y0, y1 * y1, 2 * y0, 2 * y1,
y0 * y0 * y0, y1 * y1 * y1, 3 * y0 * y0, 3 * y1 * y1;
// temp1 = X.fullPivLu().inverse(); //this line crashes on my
// home machine without optimization turned on. temp2 =
// Y.fullPivLu().inverse(); // we should take out the Eigen
// dependency methinks. TODO
A = X.inverse() * RHS * Y.inverse();
for (int t = 0; t < 16; ++t) b(i, j, k, t) = A(t % 4, t / 4);
}
}
}
// setupDerivsGrid assumes the values of f are already in gridValues
// then populates derivs with vectors of the form [f,f_x,f_y, f_xy]
// we are using finite difference
// the below is a linear transform, and we will hopefully get it into a (sparse)
// matrix soon. the below uses 5-point stencils (including at edges) for f_x and
// f_y 16-point stencils for f_xy where derivatives are available
// 4-point stencils for f_xy one row or column from edges
// f_xy at edges is hardcoded to 0.
template <int rhocount, int xcount, int ycount, class RealT>
void GyroAveragingGrid<rhocount, xcount, ycount, RealT>::setupDerivsGrid() {
RealT ydenom = yset[1] - yset[0];
RealT xdenom = xset[1] - xset[0];
fullgrid &g = gridValues;
for (int i = 0; i < rhocount; i++) {
for (int j = 0; j < xcount; j++) {
for (int k = 0; k < ycount; k++) {
derivs(i, j, k, 0) = g(i, j, k);
}
}
for (int k = 0; k < ycount; k++) {
derivs(i, 0, k, 1) = 0;
derivs(i, xcount - 1, k, 1) = 0;
derivs(i, 1, k, 1) =
(-3.0 * g(i, 0, k) + -10.0 * g(i, 1, k) + 18 * g(i, 2, k) +
-6 * g(i, 3, k) + 1 * g(i, 4, k)) /
(12.0 * xdenom);
derivs(i, xcount - 2, k, 1) =
(3.0 * g(i, xcount - 1, k) + 10.0 * g(i, xcount - 2, k) +
-18.0 * g(i, xcount - 3, k) + 6.0 * g(i, xcount - 4, k) +
-1.0 * g(i, xcount - 5, k)) /
(12.0 * xdenom);
for (int j = 2; j <= xcount - 3; j++)
derivs(i, j, k, 1) =
(1.0 * g(i, j - 2, k) + -8.0 * g(i, j - 1, k) +
0.0 * g(i, j, k) + 8.0 * g(i, j + 1, k) +
-1.0 * g(i, j + 2, k)) /
(12.0 * xdenom);
}
for (int j = 0; j < xcount; j++) {
derivs(i, j, 0, 2) = 0;
derivs(i, j, ycount - 1, 2) = 0;
derivs(i, j, 1, 2) =
(-3.0 * g(i, j, 0) + -10.0 * g(i, j, 1) + 18.0 * g(i, j, 2) +
-6.0 * g(i, j, 3) + 1.0 * g(i, j, 4)) /
(12.0 * ydenom);
derivs(i, j, ycount - 2, 2) =
(3.0 * g(i, j, ycount - 1) + 10.0 * g(i, j, ycount - 2) +
-18.0 * g(i, j, ycount - 3) + 6.0 * g(i, j, ycount - 4) +
-1 * g(i, j, ycount - 5)) /
(12.0 * ydenom);
for (int k = 2; k < ycount - 3; k++) {
derivs(i, j, k, 2) =
(1.0 * g(i, j, k - 2) + -8.0 * g(i, j, k - 1) +
0.0 * g(i, j, k) + 8.0 * g(i, j, k + 1) +
-1.0 * g(i, j, k + 2)) /
(12.0 * ydenom);
}
};
for (int j = 2; j < xcount - 2; ++j) {
for (int k = 2; k < ycount - 2; ++k) {
derivs(i, j, k, 3) =
(8 * (g(i, j + 1, k - 2) + g(i, j + 2, k - 1) +
g(i, j - 2, k + 1) + g(i, j - 1, k + 2)) +
-8 * (g(i, j - 1, k - 2) + g(i, j - 2, k - 1) +
g(i, j + 1, k + 2) + g(i, j + 2, k + 1)) +
-1 * (g(i, j + 2, k - 2) + g(i, j - 2, k + 2) -
g(i, j - 2, k - 2) - g(i, j + 2, k + 2)) +
64 * (g(i, j - 1, k - 1) + g(i, j + 1, k + 1) -
g(i, j + 1, k - 1) - g(i, j - 1, k + 1))) /
(144 * xdenom * ydenom);
}
}
for (int j = 1; j < xcount - 1; j++) {
derivs(i, j, 1, 3) = (g(i, j - 1, 0) + g(i, j + 1, 1 + 1) -
g(i, j + 1, 1 - 1) - g(i, j - 1, 1 + 1)) /
(4 * xdenom * ydenom);
derivs(i, j, ycount - 2, 3) =
(g(i, j - 1, ycount - 2 - 1) + g(i, j + 1, ycount - 2 + 1) -
g(i, j + 1, ycount - 2 - 1) - g(i, j - 1, ycount - 2 + 1)) /
(4 * xdenom * ydenom);
}
for (int k = 1; k < ycount - 1; k++) {
derivs(i, 1, k, 3) = (g(i, 1 - 1, k - 1) + g(i, 1 + 1, k + 1) -
g(i, 1 + 1, k - 1) - g(i, 1 - 1, k + 1)) /
(4 * xdenom * ydenom);
derivs(i, xcount - 2, k, 3) =
(g(i, xcount - 2 - 1, k - 1) + g(i, xcount - 2 + 1, k + 1) -
g(i, xcount - 2 + 1, k - 1) - g(i, xcount - 2 - 1, k + 1)) /
(4 * xdenom * ydenom);
}
}
}
// arcIntegral computes the analytic integral of a bilinear function over an arc
// of a circle the circle is centered at xc,yc with radius rho, and the function
// is determined by a previously setup interp grid.
template <int rhocount, int xcount, int ycount, class RealT>
std::array<RealT, 4> GyroAveragingGrid<rhocount, xcount, ycount,
RealT>::arcIntegral(RealT rho, RealT xc,
RealT yc, RealT s0,
RealT s1) {
std::array<RealT, 4> coeffs;
RealT coss1 = std::cos(s1), coss0 = std::cos(s0), sins0 = std::sin(s0),
sins1 = std::sin(s1);
coeffs[0] = s1 - s0;
coeffs[1] = (s1 * xc - rho * coss1) - (s0 * xc - rho * coss0);
coeffs[2] = (s1 * yc - rho * sins1) - (s0 * yc - rho * sins0);
coeffs[3] = (s1 * xc * yc - rho * yc * coss1 - rho * xc * sins1 +
rho * rho * coss1 * coss1 / 2.0) -
(s0 * xc * yc - rho * yc * coss0 - rho * xc * sins0 +
rho * rho * coss0 * coss0 / 2.0);
return coeffs;
}
// add handling for rho =0.
template <int rhocount, int xcount, int ycount, class RealT>
void GyroAveragingGrid<rhocount, xcount, ycount, RealT>::assembleFastGACalc(
void) {
std::vector<std::vector<SpT>> TripletVecVec(rhocount);
#pragma omp parallel for
for (auto i = 0; i < rhocount; i++) {
for (auto j = 0; j < xcount; j++)
for (auto k = 0; k < ycount; k++) {
std::vector<indexedPoint<RealT>> intersections;
RealT rho = rhoset[i];
RealT xc = xset[j];
RealT yc = yset[k];
RealT xmin = xset[0], xmax = xset.back();
RealT ymin = yset[0], ymax = yset.back();
std::vector<RealT> xIntersections, yIntersections;
// these two loops calculate all potential intersection points
// between GA circle and the grid.
for (auto v : xset)
if (std::abs(v - xc) <= rho) {
RealT deltax = v - xc;
RealT deltay = std::sqrt(rho * rho - deltax * deltax);
if ((yc + deltay >= ymin) && (yc + deltay <= ymax))
intersections.push_back(
indexedPoint<RealT>(v, yc + deltay, 0));
if ((yc - deltay >= ymin) && (yc - deltay <= ymax))
intersections.push_back(
indexedPoint<RealT>(v, yc - deltay, 0));
}
for (auto v : yset)
if (std::abs(v - yc) <= rho) {
RealT deltay = v - yc;
RealT deltax = std::sqrt(rho * rho - deltay * deltay);
if ((xc + deltax >= xmin) && (xc + deltax <= xmax))
intersections.push_back(
indexedPoint<RealT>(xc + deltax, v, 0));
if ((xc - deltax >= xmin) && (xc - deltax <= xmax))
intersections.push_back(
indexedPoint<RealT>(xc - deltax, v, 0));
}
for (auto &v : intersections) {
v.s = std::atan2(v.xvalue - xc, yc - v.yvalue);
if (v.s < 0) v.s += 2 * pi;
assert((0 <= v.s) && (v.s < 2 * pi));
assert((xc + std::sin(v.s) * rho) - v.xvalue < 1e-10);
assert((yc - std::cos(v.s) * rho) - v.yvalue < 1e-10);
}
indexedPoint<RealT> temp;
temp.s = 0;
intersections.push_back(temp);
temp.s = 2 * pi;
intersections.push_back(temp);
std::sort(intersections.begin(), intersections.end(),
[](indexedPoint<RealT> a, indexedPoint<RealT> b) {
return a.s < b.s;
});
assert(intersections.size() > 0);
assert(intersections[0].s == 0);
assert(intersections.back().s == (2 * pi));
for (size_t p = 0; p < intersections.size() - 1; p++) {
RealT s0 = intersections[p].s, s1 = intersections[p + 1].s;
RealT xmid, ymid;
std::array<RealT, 4> coeffs;
int xInterpIndex = 0, yInterpIndex = 0;
if (s1 - s0 < 1e-12)
continue; // if two of our points are equal or very
// close to one another, we make the arc
// larger. this will probably happen for s=0
// and s=pi/2, but doesn't cost us anything.
integrand(rho, xc, yc, (s0 + s1) / 2, xmid,
ymid); // this just calculates into (xmid,ymid)
// the point half through the arc.
coeffs = arcIntegral(rho, xc, yc, s0, s1);
interpIndexSearch(xmid, ymid, xInterpIndex, yInterpIndex);
// begin look-thru code
if (!((xInterpIndex == (xcount - 1)) &&
(yInterpIndex == (ycount - 1)))) {
RealT x = xset[xInterpIndex],
a = xset[xInterpIndex + 1];
RealT y = yset[yInterpIndex],
b = yset[yInterpIndex + 1];
RealT c1 = coeffs[0] / (2 * pi);
RealT c2 = coeffs[1] / (2 * pi);
RealT c3 = coeffs[2] / (2 * pi);
RealT c4 = coeffs[3] / (2 * pi);
RealT denom = (a - x) * (b - y);
std::array<int, 4> LTSources({0, 0, 0, 0}),
LTTargets({0, 0, 0, 0});
std::array<RealT, 4> LTCoeffs({0, 0, 0, 0});
LTSources[0] =
&(gridValues(i, xInterpIndex, yInterpIndex)) -
&(gridValues(0, 0, 0));
LTSources[1] =
&(gridValues(i, xInterpIndex + 1, yInterpIndex)) -
&(gridValues(0, 0, 0));
LTSources[2] =
&(gridValues(i, xInterpIndex, yInterpIndex + 1)) -
&(gridValues(0, 0, 0));
LTSources[3] = &(gridValues(i, xInterpIndex + 1,
yInterpIndex + 1)) -
&(gridValues(0, 0, 0));
LTTargets[0] =
&(fastGALTResult(i, j, k)) -
&(fastGALTResult(0, 0,
0)); // eh these are all the same,
// delete the extras.
LTTargets[1] = &(fastGALTResult(i, j, k)) -
&(fastGALTResult(0, 0, 0));
LTTargets[2] = &(fastGALTResult(i, j, k)) -
&(fastGALTResult(0, 0, 0));
LTTargets[3] = &(fastGALTResult(i, j, k)) -
&(fastGALTResult(0, 0, 0));
LTCoeffs[0] = (c1 * a * b - b * c2 - a * c3 + c4) /
denom; // coeff of Q11
LTCoeffs[1] = (-c4 - c1 * a * y + a * c3 + y * c2) /
denom; // etc
LTCoeffs[2] =
(b * c2 - c1 * b * x + x * c3 - c4) / denom;
LTCoeffs[3] =
(c1 * x * y - y * c2 - x * c3 + c4) / denom;
for (int l = 0; l < 4; l++) {
TripletVecVec[i].emplace_back(
SpT(LTTargets[l], LTSources[l], LTCoeffs[l]));
}
}
}
}
}
std::vector<SpT> Triplets;
for (int i = 0; i < rhocount; i++) {
for (auto iter = TripletVecVec[i].begin();
iter != TripletVecVec[i].end(); ++iter) {
Triplets.emplace_back(*iter);
}
}
LTOffsetTensor.resize(rhocount * xcount * ycount,
rhocount * xcount * ycount);
LTOffsetTensor.setFromTriplets(Triplets.begin(), Triplets.end());
// std::cout << "Number of RealT products needed for LT calc: " <<
// LTOffsetTensor.nonZeros() << " and rough memory usage is " <<
// LTOffsetTensor.nonZeros() * (sizeof(RealT) + sizeof(long)) << std::endl;
}
template <int rhocount, int xcount, int ycount, class RealT>
void GyroAveragingGrid<rhocount, xcount, ycount, RealT>::assembleFastBCCalc(
void) { // bicubic version of the above.
std::vector<std::vector<SpT>> TripletVecVec(rhocount);
#pragma omp parallel for
for (auto i = 0; i < rhocount; i++) {
for (auto j = 0; j < xcount; j++)
for (auto k = 0; k < ycount; k++) {
std::vector<indexedPoint<RealT>> intersections;
RealT rho = rhoset[i];
RealT xc = xset[j];
RealT yc = yset[k];
RealT xmin = xset[0], xmax = xset.back();
RealT ymin = yset[0], ymax = yset.back();
std::vector<RealT> xIntersections, yIntersections;
// these two loops calculate all potential intersection points
// between GA circle and the grid.
for (auto v : xset)
if (std::abs(v - xc) <= rho) {
RealT deltax = v - xc;
RealT deltay = std::sqrt(rho * rho - deltax * deltax);
if ((yc + deltay >= ymin) && (yc + deltay <= ymax))
intersections.push_back(
indexedPoint<RealT>(v, yc + deltay, 0));
if ((yc - deltay >= ymin) && (yc - deltay <= ymax))
intersections.push_back(
indexedPoint<RealT>(v, yc - deltay, 0));
}
for (auto v : yset)
if (std::abs(v - yc) <= rho) {
RealT deltay = v - yc;
RealT deltax = std::sqrt(rho * rho - deltay * deltay);
if ((xc + deltax >= xmin) && (xc + deltax <= xmax))
intersections.push_back(
indexedPoint<RealT>(xc + deltax, v, 0));
if ((xc - deltax >= xmin) && (xc - deltax <= xmax))
intersections.push_back(
indexedPoint<RealT>(xc - deltax, v, 0));
}
for (auto &v : intersections) {
v.s = std::atan2(v.xvalue - xc, yc - v.yvalue);
if (v.s < 0) v.s += 2 * pi;
assert((0 <= v.s) && (v.s < 2 * pi));
assert((xc + std::sin(v.s) * rho) - v.xvalue < 1e-10);
assert((yc - std::cos(v.s) * rho) - v.yvalue < 1e-10);
}
indexedPoint<RealT> temp;
temp.s = 0;
intersections.push_back(temp);
temp.s = 2 * pi;
intersections.push_back(temp);
std::sort(intersections.begin(), intersections.end(),
[](indexedPoint<RealT> a, indexedPoint<RealT> b) {
return a.s < b.s;
});
assert(intersections.size() > 0);
assert(intersections[0].s == 0);
assert(intersections.back().s == (2 * pi));
for (size_t p = 0; p < intersections.size() - 1; p++) {
RealT s0 = intersections[p].s, s1 = intersections[p + 1].s;
RealT xmid, ymid;
std::array<RealT, 16> coeffs;
int xInterpIndex = 0, yInterpIndex = 0;
if (s1 - s0 <
1e-12) // TODO MAGIC NUMBER (here and another place )
continue; // if two of our points are equal or very
// close to one another, we make the arc
// larger. this will probably happen for s=0
// and s=pi/2, but doesn't cost us anything.
integrand(rho, xc, yc, (s0 + s1) / 2, xmid,
ymid); // this just calculates into (xmid,ymid)
// the point half through the arc.
arcIntegralBicubic(coeffs, rho, xc, yc, s0, s1);
interpIndexSearch(xmid, ymid, xInterpIndex, yInterpIndex);
// begin look-thru code
if (!((xInterpIndex == (xcount - 1)) &&
(yInterpIndex == (ycount - 1)))) {
std::array<int, 16> LTSources, LTTargets;
std::array<RealT, 16> LTCoeffs;
for (int l = 0; l < 16; l++) {
LTSources[l] =
&(bicubicParameters(i, xInterpIndex,
yInterpIndex, l)) -
&(bicubicParameters(0, 0, 0, 0));
LTTargets[l] =
&(BCResult(i, j, k)) - &(BCResult(0, 0, 0));
LTCoeffs[l] = coeffs[l] / (2.0 * pi);
TripletVecVec[i].emplace_back(
SpT(LTTargets[l], LTSources[l], LTCoeffs[l]));
}
}
}
}
}
std::vector<SpT> Triplets;
for (int i = 0; i < rhocount; i++) {
for (auto iter = TripletVecVec[i].begin();
iter != TripletVecVec[i].end(); ++iter) {
SpT lto(*iter);
Triplets.emplace_back(*iter);
}
}
BCOffsetTensor.resize(rhocount * xcount * ycount,
rhocount * xcount * ycount * 16);
BCOffsetTensor.setFromTriplets(Triplets.begin(), Triplets.end());
// std::cout << "Number of RealT products needed for BC calc: " <<
// BCOffsetTensor.nonZeros() << " and rough memory usage is " <<
// BCOffsetTensor.nonZeros() * (sizeof(RealT) + sizeof(long)) << std::endl;
}
template <int rhocount, int xcount, int ycount, class RealT>
void GyroAveragingGrid<rhocount, xcount, ycount, RealT>::fastLTCalcOffset() {
clearGrid(fastGALTResult);
Eigen::Map<Eigen::Matrix<RealT, rhocount * xcount * ycount, 1>> source(
gridValues.data.data());
Eigen::Map<Eigen::Matrix<RealT, rhocount * xcount * ycount, 1>> target(
fastGALTResult.data.data());
target = LTOffsetTensor * source;
}
template <int rhocount, int xcount, int ycount, class RealT>
void GyroAveragingGrid<rhocount, xcount, ycount, RealT>::fastBCCalcOffset() {
clearGrid(BCResult);
Eigen::Map<Eigen::Matrix<RealT, rhocount * xcount * ycount * 16, 1>> source(
bicubicParameters.data.data());
Eigen::Map<Eigen::Matrix<RealT, rhocount * xcount * ycount, 1>> target(
BCResult.data.data());
target = BCOffsetTensor * source;
}
template <int rhocount, int xcount, int ycount, class RealT>
template <typename TFunc1, typename TFunc2>
void GyroAveragingGrid<rhocount, xcount, ycount, RealT>::GPUTestSuite(
TFunc1 f, TFunc2 analytic) {
// boost::timer::auto_cpu_timer t;
SpM &cpu_sparse_matrix = LTOffsetTensor;
viennacl::compressed_matrix<RealT> vcl_sparse_matrix(
xcount * ycount * rhocount, xcount * ycount * rhocount);
// t.start();
viennacl::copy(cpu_sparse_matrix, vcl_sparse_matrix);
viennacl::backend::finish();
// t.report();
std::cout
<< "That was the time to create the CPU matrix and copy it once to GPU."
<< std::endl;
// t.start();
viennacl::compressed_matrix<RealT, 1> vcl_compressed_matrix_1(
xcount * ycount * rhocount, xcount * ycount * rhocount);
viennacl::compressed_matrix<RealT, 4> vcl_compressed_matrix_4(
xcount * ycount * rhocount, xcount * ycount * rhocount);
viennacl::compressed_matrix<RealT, 8> vcl_compressed_matrix_8(
xcount * ycount * rhocount, xcount * ycount * rhocount);
// viennacl::coordinate_matrix<RealT> vcl_coordinate_matrix_128(xcount *
// ycount * rhocount, xcount * ycount * rhocount);
// viennacl::ell_matrix<RealT, 1> vcl_ell_matrix_1();
// viennacl::hyb_matrix<RealT, 1> vcl_hyb_matrix_1();
// viennacl::sliced_ell_matrix<RealT> vcl_sliced_ell_matrix_1(xcount *
// ycount * rhocount, xcount * ycount * rhocount);
viennacl::vector<RealT> gpu_source(gridValues.data.size());
viennacl::vector<RealT> gpu_target(gridValues.data.size());
copy(gridValues.data.begin(), gridValues.data.end(), gpu_source.begin());
copy(gridValues.data.begin(), gridValues.data.end(), gpu_target.begin());
// we are going to compute each product once and then sync, to compile all
// kernels. this will feel like a ~1 second delay in user space.
viennacl::copy(cpu_sparse_matrix, vcl_compressed_matrix_1);
viennacl::copy(cpu_sparse_matrix, vcl_compressed_matrix_4);
viennacl::copy(cpu_sparse_matrix, vcl_compressed_matrix_8);
// viennacl::copy(cpu_sparse_matrix, vcl_coordinate_matrix_128);
// viennacl::copy(cpu_sparse_matrix,vcl_ell_matrix_1);
// viennacl::copy(ublas_matrix,vcl_hyb_matrix_1);
// viennacl::copy(cpu_sparse_matrix, vcl_sliced_ell_matrix_1);
viennacl::backend::finish();
// t.report();
// t.start();
std::cout << "That was the time to copy everything onto the GPU."
<< std::endl;
fullgrid cpu_results[8];
gpu_target = viennacl::linalg::prod(vcl_sparse_matrix, gpu_source);
viennacl::backend::finish();
gpu_target = viennacl::linalg::prod(vcl_compressed_matrix_1, gpu_source);
viennacl::copy(gpu_target.begin(), gpu_target.end(),
cpu_results[0].data.begin());
gpu_target = viennacl::linalg::prod(vcl_compressed_matrix_4, gpu_source);
gpu_target = viennacl::linalg::prod(vcl_compressed_matrix_8, gpu_source);
// gpu_target = viennacl::linalg::prod(vcl_coordinate_matrix_128,
// gpu_source); gpu_target =
// viennacl::linalg::prod(vcl_ell_matrix_1,gpu_source); gpu_target =
// viennacl::linalg::prod(vcl_hyb_matrix_1,gpu_source); gpu_target =
// viennacl::linalg::prod(vcl_sliced_ell_matrix_1, gpu_source);
viennacl::backend::finish();
viennacl::copy(gpu_target.begin(), gpu_target.end(),
cpu_results[0].data.begin());
viennacl::backend::finish();
// t.report();
std::cout << "That was the time to do all of the products, and copy the "
"result back twice."
<< std::endl;
constexpr int gputimes = 1;
// At this point everything has been done once. We start benchmarking. We
// are going to include cost of vectors transfers back and forth.
// t.start();
for (int count = 0; count < gputimes; ++count) {
copy(gridValues.data.begin(), gridValues.data.end(),
gpu_source.begin());
viennacl::backend::finish();
gpu_target = viennacl::linalg::prod(vcl_sparse_matrix, gpu_source);
viennacl::backend::finish();
viennacl::copy(gpu_target.begin(), gpu_target.end(),
cpu_results[0].data.begin());
viennacl::backend::finish();
}
// t.report();
std::cout << "That was the full cycle time to do " << gputimes
<< " products using default sparse matrix." << std::endl;
// t.start();
for (int count = 0; count < gputimes; ++count) {
copy(gridValues.data.begin(), gridValues.data.end(),
gpu_source.begin());
viennacl::backend::finish();
gpu_target =
viennacl::linalg::prod(vcl_compressed_matrix_1, gpu_source);
viennacl::backend::finish();
viennacl::copy(gpu_target.begin(), gpu_target.end(),
cpu_results[1].data.begin());
viennacl::backend::finish();
}
// t.report();
std::cout << "That was the full cycle time to do " << gputimes
<< " products using compressed_matrix_1 matrix." << std::endl;
// t.start();
for (int count = 0; count < gputimes; ++count) {
copy(gridValues.data.begin(), gridValues.data.end(),
gpu_source.begin());
viennacl::backend::finish();
gpu_target =
viennacl::linalg::prod(vcl_compressed_matrix_4, gpu_source);
viennacl::backend::finish();
viennacl::copy(gpu_target.begin(), gpu_target.end(),
cpu_results[2].data.begin());
viennacl::backend::finish();
}
// t.report();
std::cout << "That was the full cycle time to do " << gputimes
<< " products using compressed_matrix_4 matrix." << std::endl;
// t.start();
for (int count = 0; count < gputimes; ++count) {
copy(gridValues.data.begin(), gridValues.data.end(),
gpu_source.begin());
viennacl::backend::finish();
gpu_target =
viennacl::linalg::prod(vcl_compressed_matrix_8, gpu_source);
viennacl::backend::finish();
viennacl::copy(gpu_target.begin(), gpu_target.end(),
cpu_results[3].data.begin());
viennacl::backend::finish();
}
// t.report();
std::cout << "That was the full cycle time to do " << gputimes
<< " products using compressed_matrix_8 matrix." << std::endl;
/* t.start();
for (int count = 0; count < gputimes; ++count) {
copy(gridValues.data.begin(), gridValues.data.end(),
gpu_source.begin()); viennacl::backend::finish(); gpu_target =
viennacl::linalg::prod(vcl_coordinate_matrix_128, gpu_source);
viennacl::backend::finish();
viennacl::copy(gpu_target.begin(), gpu_target.end(),
cpu_results[4].data.begin()); viennacl::backend::finish();
}
t.report();
*/
// std::cout << "That was the full cycle time to do " << gputimes * 0 << "
// products using coordinate_matrix_128 matrix." << std::endl;
/*t.start();
for (int count = 0; count < gputimes; ++count) {
copy(gridValues.data.begin(), gridValues.data.end(),
gpu_source.begin()); viennacl::backend::finish(); gpu_target =
viennacl::linalg::prod(vcl_sliced_ell_matrix_1, gpu_source);
viennacl::backend::finish();
viennacl::copy(gpu_target.begin(), gpu_target.end(),
cpu_results[4].data.begin()); viennacl::backend::finish();
}
t.report();
std::cout << "That was the full cycle time to do " << gputimes << " products
using sliced_ell_matrix_1 matrix." << std::endl;
*/
std::cout << "Next we report errors for each GPU calc (in above order) vs "
"CPU dot-product calc. Here we only report maxabs norm"
<< std::endl;
for (int i = 0; i < rhocount; i++) {
std::cout.precision(5);
std::cout << std::fixed << rhoset[i] << std::scientific << std::setw(15)
<< maxNormDiff(fastGALTResult, cpu_results[0], i) << "\t"
<< maxNormDiff(fastGALTResult, cpu_results[1], i) << "\t"
<< maxNormDiff(fastGALTResult, cpu_results[2], i) << "\t"
<< maxNormDiff(fastGALTResult, cpu_results[3], i)
<< std::endl;
}
// end ViennaCL calc
}
template <int rhocount, int xcount, int ycount, class RealT>
template <typename TFunc1, typename TFunc2>
void GyroAveragingGrid<rhocount, xcount, ycount, RealT>::GPUTestSuiteBC(
TFunc1 f, TFunc2 analytic) {
// TODO the below cheats and doesn't yet recompute derivs/params. Need to
// add that and benchmark.
std::cout << "Beginning GPU test of BC calc.\n";
// boost::timer::auto_cpu_timer t;
viennacl::compressed_matrix<RealT> vcl_sparse_matrix(
xcount * ycount * rhocount, xcount * ycount * rhocount * 16);
// t.start();
SpM &cpu_sparse_matrix = BCOffsetTensor;
viennacl::copy(cpu_sparse_matrix, vcl_sparse_matrix);
viennacl::backend::finish();
// t.report();
std::cout
<< "That was the time to create the CPU matrix and copy it once to GPU."
<< std::endl;
// t.start();
viennacl::backend::finish();
viennacl::compressed_matrix<RealT, 1> vcl_compressed_matrix_1(
xcount * ycount * rhocount, xcount * ycount * rhocount * 16);
viennacl::compressed_matrix<RealT, 4> vcl_compressed_matrix_4(
xcount * ycount * rhocount, xcount * ycount * rhocount * 16);
viennacl::compressed_matrix<RealT, 8> vcl_compressed_matrix_8(
xcount * ycount * rhocount, xcount * ycount * rhocount * 16);
// viennacl::coordinate_matrix<RealT> vcl_coordinate_matrix_128(xcount *
// ycount * rhocount, xcount * ycount * rhocount * 16);
// viennacl::ell_matrix<RealT, 1> vcl_ell_matrix_1();
// viennacl::hyb_matrix<RealT, 1> vcl_hyb_matrix_1();
// viennacl::sliced_ell_matrix<RealT> vcl_sliced_ell_matrix_1(xcount *
// ycount * rhocount, xcount * ycount * rhocount *16);
viennacl::vector<RealT> gpu_source(bicubicParameters.data.size());
viennacl::vector<RealT> gpu_target(BCResult.data.size());
copy(cpu_sparse_matrix,
vcl_sparse_matrix); // default alignment, benchmark different options.
copy(bicubicParameters.data.begin(), bicubicParameters.data.end(),
gpu_source.begin());
viennacl::backend::finish();
copy(gridValues.data.begin(), gridValues.data.end(),
gpu_target.begin()); // this is garbage data, I just want to make sure
// it's allocated.
// we are going to compute each product once and then sync, to compile all
// kernels. this will feel like a ~1 second delay in user space.
viennacl::copy(cpu_sparse_matrix, vcl_compressed_matrix_1);
viennacl::copy(cpu_sparse_matrix, vcl_compressed_matrix_4);
viennacl::copy(cpu_sparse_matrix, vcl_compressed_matrix_8);
// viennacl::copy(cpu_sparse_matrix, vcl_coordinate_matrix_128);
// viennacl::copy(cpu_sparse_matrix,vcl_ell_matrix_1);
// viennacl::copy(ublas_matrix,vcl_hyb_matrix_1);
// viennacl::copy(cpu_sparse_matrix, vcl_sliced_ell_matrix_1);
viennacl::backend::finish();
// t.report();
// t.start();
std::cout << "That was the time to copy everything onto the GPU."
<< std::endl;
fullgrid cpu_results[8];
gpu_target = viennacl::linalg::prod(vcl_sparse_matrix, gpu_source);
viennacl::backend::finish();
gpu_target = viennacl::linalg::prod(vcl_compressed_matrix_1, gpu_source);
viennacl::copy(gpu_target.begin(), gpu_target.end(),
cpu_results[0].data.begin());
gpu_target = viennacl::linalg::prod(vcl_compressed_matrix_4, gpu_source);
gpu_target = viennacl::linalg::prod(vcl_compressed_matrix_8, gpu_source);
// gpu_target = viennacl::linalg::prod(vcl_coordinate_matrix_128,
// gpu_source); gpu_target =
// viennacl::linalg::prod(vcl_ell_matrix_1,gpu_source); gpu_target =
// viennacl::linalg::prod(vcl_hyb_matrix_1,gpu_source); gpu_target =
// viennacl::linalg::prod(vcl_sliced_ell_matrix_1, gpu_source);
viennacl::backend::finish();
viennacl::copy(gpu_target.begin(), gpu_target.end(),
cpu_results[0].data.begin());
viennacl::backend::finish();
// t.report();
std::cout << "That was the time to do all of the products, and copy the "
"result back."
<< std::endl;
constexpr int gputimes = 1;
// At this point everything has been done once. We start benchmarking. We
// are going to include cost of vectors transfers back and forth.
// t.start();
for (int count = 0; count < gputimes; ++count) {
copy(bicubicParameters.data.begin(), bicubicParameters.data.end(),
gpu_source.begin());
viennacl::backend::finish();
gpu_target = viennacl::linalg::prod(vcl_sparse_matrix, gpu_source);
viennacl::backend::finish();
viennacl::copy(gpu_target.begin(), gpu_target.end(),
cpu_results[0].data.begin());
viennacl::backend::finish();
}
// t.report();
std::cout << "That was the full cycle time to do " << gputimes
<< " products using default sparse matrix." << std::endl;
// t.start();
for (int count = 0; count < gputimes; ++count) {
copy(bicubicParameters.data.begin(), bicubicParameters.data.end(),
gpu_source.begin());
viennacl::backend::finish();
gpu_target =
viennacl::linalg::prod(vcl_compressed_matrix_1, gpu_source);
viennacl::backend::finish();
viennacl::copy(gpu_target.begin(), gpu_target.end(),
cpu_results[1].data.begin());
viennacl::backend::finish();
}
// t.report();
std::cout << "That was the full cycle time to do " << gputimes
<< " products using compressed_matrix_1 matrix." << std::endl;
// t.start();
for (int count = 0; count < gputimes; ++count) {
copy(bicubicParameters.data.begin(), bicubicParameters.data.end(),
gpu_source.begin());
viennacl::backend::finish();
gpu_target =
viennacl::linalg::prod(vcl_compressed_matrix_4, gpu_source);
viennacl::backend::finish();
viennacl::copy(gpu_target.begin(), gpu_target.end(),
cpu_results[2].data.begin());
viennacl::backend::finish();
}
// t.report();
std::cout << "That was the full cycle time to do " << gputimes
<< " products using compressed_matrix_4 matrix." << std::endl;
// t.start();
for (int count = 0; count < gputimes; ++count) {
copy(bicubicParameters.data.begin(), bicubicParameters.data.end(),
gpu_source.begin());
viennacl::backend::finish();
gpu_target =
viennacl::linalg::prod(vcl_compressed_matrix_8, gpu_source);
viennacl::backend::finish();
viennacl::copy(gpu_target.begin(), gpu_target.end(),
cpu_results[3].data.begin());
viennacl::backend::finish();
}
// t.report();
std::cout << "That was the full cycle time to do " << gputimes
<< " products using compressed_matrix_8 matrix." << std::endl;
// t.start();
/* for(int count =0; count<gputimes;++count){
copy(bicubicParameters.data.begin(),bicubicParameters.data.end(),gpu_source.begin());
viennacl::backend::finish();
gpu_target = viennacl::linalg::prod(vcl_coordinate_matrix_128,gpu_source);
viennacl::backend::finish();
viennacl::copy(gpu_target.begin(),gpu_target.end(),cpu_results[4].data.begin());
viennacl::backend::finish();
}
t.report();*/
// std::cout << "That was the full cycle time to do " << gputimes * 0 << "
// products using coordinate_matrix_128 matrix." << std::endl;
// t.start();
/*for (int count = 0; count < gputimes; ++count) {
copy(bicubicParameters.data.begin(), bicubicParameters.data.end(),
gpu_source.begin()); viennacl::backend::finish(); gpu_target =
viennacl::linalg::prod(vcl_sliced_ell_matrix_1, gpu_source);
viennacl::backend::finish();
viennacl::copy(gpu_target.begin(), gpu_target.end(),
cpu_results[4].data.begin()); viennacl::backend::finish();
}*/
// t.report();
// std::cout << "That was the full cycle time to do " << gputimes << "
// products using sliced_ell_matrix_1 matrix." << std::endl;
// t.start();
for (int count = 0; count < gputimes; ++count) {
setupDerivsGrid();
setupBicubicGrid();
copy(bicubicParameters.data.begin(), bicubicParameters.data.end(),
gpu_source.begin());
viennacl::backend::finish();
gpu_target = viennacl::linalg::prod(vcl_sparse_matrix, gpu_source);
viennacl::backend::finish();
viennacl::copy(gpu_target.begin(), gpu_target.end(),
cpu_results[0].data.begin());
viennacl::backend::finish();
}
// t.report();
std::cout << "That was the full cycle time to do " << gputimes
<< " products using default sparse matrix, and recalculated "
"derivatives and BC parameters."
<< std::endl;
std::cout << "Next we report errors for each GPU calc (in above order) vs "
"CPU dot-product calc. Here we only report maxabs norm"
<< std::endl;
for (int i = 0; i < rhocount; i++) {
std::cout.precision(5);
std::cout << std::fixed << rhoset[i] << std::scientific << std::setw(15)
<< maxNormDiff(BCResult, cpu_results[0], i) << "\t"
<< maxNormDiff(BCResult, cpu_results[1], i) << "\t"
<< maxNormDiff(BCResult, cpu_results[2], i) << "\t"
<< maxNormDiff(BCResult, cpu_results[3], i) << std::endl;
}
}
/* Run test suite. We expect the test suite to:
1) Calculate the gyroaverage transform of f, using f on a full grid, at each
grid point 2) above, using f but truncating it to be 0 outside of our grid
3) above, using bilinear interp of f (explicitly only gridpoint valuations
are allowed) and we trapezoid rule the interp-ed, truncated function (vs (2),
only interp error introduced) 4) fast dot-product calc: see
AssembleFastGACalc for details We report evolution of errorand sample timings.
*/
template <int rhocount, int xcount, int ycount, class RealT>
template <typename TFunc1, typename TFunc2>
void GyroAveragingGrid<rhocount, xcount, ycount, RealT>::GyroAveragingTestSuite(
TFunc1 f, TFunc2 analytic) {
// boost::timer::auto_cpu_timer t;
fill(gridValues,
f); // This is the base grid of values we will interpolate.
// t.start();
fill(analytic_averages, analytic); // analytic formula for gyroaverages
// t.report();
std::cout
<< "That was the time required to calculate analytic gyroaverages.\n";
setupInterpGrid();
// t.start();
fillAlmostExactGA(almostExactGA, f);
// t.report();
std::cout << "That was the time required to calculate gyroaverages from "
"the definition, with the trapezoid rule.\n";
// t.start();
fillTruncatedAlmostExactGA(truncatedAlmostExactGA, f);
// t.report();
std::cout << "That was the time required to calculate gryoaverages by def "
"(as above), except we hard truncated f() to 0 off-grid.\n";
// t.start();
fillTrapezoidInterp(trapezoidInterp, f);
// t.report();
std::cout << "That was the time required to calc gyroaverages by def, "
"replacing f() by its bilinear interpolant."
<< std::endl;
// t.start();
assembleFastGACalc();
// t.report();
std::cout << "That was the time required to assemble the sparse matrix in "
"the fast-GA dot product calculation."
<< std::endl;
// t.start();
setupDerivsGrid();
// t.report();
// t.start();
setupBicubicGrid();
// t.report();
// t.start();
assembleFastBCCalc();
// t.report();
std::cout << "That was the time required to assemble the sparse matrix in "
"the fast-BC dot product calculation."
<< std::endl;
// t.start();
int times = 1;
for (int counter = 0; counter < times; counter++) {
fastLTCalcOffset();
}
// t.report();
std::cout << "The was the time require to run LT gyroaverage calc " << times
<< " times. \n " << std::endl;
// t.start();
for (int counter = 0; counter < times; counter++) {
setupDerivsGrid();
setupBicubicGrid();
fastBCCalcOffset();
}
// t.report();
std::cout << "The was the time require to run BC gyroaverage calc " << times
<< " times. \n " << std::endl;
GPUTestSuite(f, analytic);
setupDerivsGrid();
setupBicubicGrid();
fullgrid bicubicResults;
fillBicubicInterp(bicubicResults);
GPUTestSuiteBC(f, analytic);
std::cout << "Below are some summary statistics for various grid. Under "
"each header is a pair of values. The first is the RMS of a "
"matrix, the second is the max absolute entry in a matrix.\n";
std::cout
<< "rho Input Grid Analytic Estimates "
" Trapezoid Rule Trap Rule truncation "
" Trapezoid rule of bilin interp Fast dot-product GA\n";
for (int i = 0; i < rhocount; i++) {
std::cout.precision(5);
std::cout << std::fixed << rhoset[i] << std::scientific << std::setw(15)
<< RMSNorm(gridValues, i) << "\t" << maxNorm(gridValues, i)
<< "\t" << RMSNorm(analytic_averages, i) << "\t"
<< maxNorm(analytic_averages, i) << "\t"
<< RMSNorm(almostExactGA, i) << "\t"
<< maxNorm(almostExactGA, i) << "\t"
<< RMSNorm(truncatedAlmostExactGA, i) << "\t"
<< maxNorm(truncatedAlmostExactGA, i) << "\t"
<< RMSNorm(trapezoidInterp, i) << "\t"
<< maxNorm(trapezoidInterp, i) << "\t"
<< RMSNorm(fastGALTResult, i) << "\t"
<< maxNorm(fastGALTResult, i) << "\t"
<< RMSNorm(bicubicResults, i) << "\t"
<< maxNorm(bicubicResults, i) << "\t" << RMSNorm(BCResult, i)
<< "\t" << maxNorm(BCResult, i) << "\n";
}
std::cout << "Diffs:\n";
std::cout << "rho Analytic vs Quadrature Error due to "
"truncation Error due to interp Analytic "
"vs interp interp vs DP bicub trap vs "
"analytic bicubic DP vs analytic \n";
for (int i = 0; i < rhocount; i++) {
std::cout.precision(5);
std::cout << std::fixed << rhoset[i] << std::scientific << std::setw(15)
<< RMSNormDiff(analytic_averages, almostExactGA, i) << "\t"
<< maxNormDiff(analytic_averages, almostExactGA, i) << "\t"
<< RMSNormDiff(almostExactGA, truncatedAlmostExactGA, i)
<< "\t"
<< maxNormDiff(almostExactGA, truncatedAlmostExactGA, i)
<< "\t"
<< RMSNormDiff(truncatedAlmostExactGA, trapezoidInterp, i)
<< "\t"
<< maxNormDiff(truncatedAlmostExactGA, trapezoidInterp, i)
<< "\t" << RMSNormDiff(analytic_averages, trapezoidInterp, i)
<< "\t" << maxNormDiff(analytic_averages, trapezoidInterp, i)
<< "\t" << RMSNormDiff(trapezoidInterp, fastGALTResult, i)
<< "\t" << maxNormDiff(trapezoidInterp, fastGALTResult, i)
<< "\t" << RMSNormDiff(bicubicResults, analytic_averages, i)
<< "\t" << maxNormDiff(bicubicResults, analytic_averages, i)
<< "\t" << RMSNormDiff(BCResult, analytic_averages, i) << "\t"
<< maxNormDiff(BCResult, analytic_averages, i) << "\n";
// << RMSNormDiff(fastGALTResult, cpu_results[0], i) << "\t"
// << maxNormDiff(fastGALTResult, cpu_results[0], i) << "\n";
//<< RMSNormDiff(fastGALTResult, fastGACalcResultOffset, i) << "\t"
//<< maxNormDiff(fastGALTResult, fastGACalcResultOffset, i) << "\n";
}
};
template <int rhocount, int xcount, int ycount, class RealT>
template <typename TFunc1, typename TFunc2>
void GyroAveragingGrid<rhocount, xcount, ycount, RealT>::compactErrorAnalysis(
TFunc1 f, TFunc2 analytic) {
fill(gridValues, f); // This is the base grid of values we will
// interpolate.
fill(analytic_averages, analytic); // analytic formula for gyroaverages
setupInterpGrid();
fillAlmostExactGA(almostExactGA, f);
fillTruncatedAlmostExactGA(truncatedAlmostExactGA, f);
fillTrapezoidInterp(trapezoidInterp, f);
assembleFastGACalc();
setupDerivsGrid();
setupBicubicGrid();
assembleFastBCCalc();
fastLTCalcOffset();
fastBCCalcOffset();
fullgrid bicubicResults;
fillBicubicInterp(bicubicResults);
for (int i = 0; i < rhocount; i++) {
std::cout.precision(5);
std::cout << std::fixed << xcount << std::scientific << std::setw(15)
<< RMSNorm(gridValues, i) << "\t" << maxNorm(gridValues, i)
<< "\t" << RMSNorm(analytic_averages, i) << "\t"
<< maxNorm(analytic_averages, i) << "\t"
<< RMSNorm(fastGALTResult, i) << "\t"
<< maxNorm(fastGALTResult, i) << "\t" << RMSNorm(BCResult, i)
<< "\t" << maxNorm(BCResult, i) << "\t"
<< maxNormDiff(fastGALTResult, analytic_averages, i) /
maxNorm(analytic_averages, i)
<< "\t"
<< maxNormDiff(BCResult, analytic_averages, i) /
maxNorm(analytic_averages, i)
<< "\n";
}
}
// below function returns the indices referring to lower left point of the grid
// box containing (x,y) it is not (yet) efficient. In particular, we should
// probably explicitly assume equispaced grids and use that fact.
template <int rhocount, int xcount, int ycount, class RealT>
void GyroAveragingGrid<rhocount, xcount, ycount, RealT>::interpIndexSearch(
const RealT x, const RealT y, int &xindex, int &yindex) {
if ((x < xset[0]) || (y < yset[0]) || (x > xset.back()) ||
(y > yset.back())) {
xindex = xcount - 1; // the top right corner should have zeros.
yindex = ycount - 1;
return;
}
xindex = std::upper_bound(xset.begin(), xset.end(), x) - xset.begin() - 1;
yindex = std::upper_bound(yset.begin(), yset.end(), y) - yset.begin() - 1;
xindex = std::min(std::max(xindex, 0), xcount - 2);
yindex = std::min(ycount - 2, std::max(yindex, 0));
assert((xset[xindex]) <= x && (xset[xindex + 1] >= x));
assert((yset[yindex]) <= y && (yset[yindex + 1] >= y));
}
template <int rhocount, int xcount, int ycount, class RealT>
RealT GyroAveragingGrid<rhocount, xcount, ycount, RealT>::interp2d(
int rhoindex, const RealT x, const RealT y) {
assert((rhoindex >= 0) && (rhoindex < rhocount));
if ((x <= xset[0]) || (y <= yset[0]) || (x >= xset.back()) ||
(y >= yset.back()))
return 0;
int xindex = 0, yindex = 0;
interpIndexSearch(x, y, xindex, yindex);
RealT result = BilinearInterpolation<RealT>(
gridValues(rhoindex, xindex, yindex),
gridValues(rhoindex, xindex + 1, yindex),
gridValues(rhoindex, xindex, yindex + 1),
gridValues(rhoindex, xindex + 1, yindex + 1), xset[xindex],
xset[xindex + 1], yset[yindex], yset[yindex + 1], x, y);
return result;
}
// Below returns bicubic interp f(x,y), in the dumb way. We should do
// multivariate horners method soon.
template <int rhocount, int xcount, int ycount, class RealT>
RealT GyroAveragingGrid<rhocount, xcount, ycount, RealT>::interpNaiveBicubic(
int rhoindex, const RealT x, const RealT y) {
assert((rhoindex >= 0) && (rhoindex < rhocount));
if ((x <= xset[0]) || (y <= yset[0]) || (x >= xset.back()) ||
(y >= yset.back()))
return 0;
int xindex = 0, yindex = 0;
RealT result = 0;
interpIndexSearch(x, y, xindex, yindex);
RealT xns[4] = {1, x, x * x, x * x * x};
RealT yns[4] = {1, y, y * y, y * y * y};
for (int i = 0; i <= 3; ++i)
for (int j = 0; j <= 3; ++j) {
result += bicubicParameters(rhoindex, xindex, yindex, j * 4 + i) *
xns[i] * yns[j];
}
return result;
}
template <int rhocount, int xcount, int ycount, class RealT>
template <typename TFunc1, typename TFunc2, typename TFunc3, typename TFunc4>
void GyroAveragingGrid<rhocount, xcount, ycount, RealT>::derivsErrorAnalysis(
TFunc1 f, TFunc2 f_x, TFunc3 f_y, TFunc4 f_xy) {
std::cout << "Starting derivative accuracy check:\n";
fill(gridValues, f);
setupInterpGrid();
setupDerivsGrid();
fullgrid analytic[4];
fullgrid numeric[4];
for (int i = 0; i < rhocount; i++)
for (int j = 0; j < xcount; j++)
for (int k = 0; k < ycount; k++) {
analytic[0](i, j, k) = f(rhoset[i], xset[j], yset[k]);
numeric[0](i, j, k) = derivs(i, j, k, 0);
analytic[1](i, j, k) = f_x(rhoset[i], xset[j], yset[k]);
numeric[1](i, j, k) = derivs(i, j, k, 1);
analytic[2](i, j, k) = f_y(rhoset[i], xset[j], yset[k]);
numeric[2](i, j, k) = derivs(i, j, k, 2);
analytic[3](i, j, k) = f_xy(rhoset[i], xset[j], yset[k]);
numeric[3](i, j, k) = derivs(i, j, k, 3);
}
for (int l = 0; l < 4; l++) {
csvPrinter(analytic[l], 1);
std::cout << std::endl;
csvPrinter(numeric[l], 1);
std::cout << std::endl;
}
for (int i = 0; i < rhocount; i++) {
std::cout.precision(5);
std::cout << std::fixed << rhoset[i] << std::scientific << std::setw(15)
<< RMSNormDiff(analytic[0], numeric[0], i) << "\t"
<< maxNormDiff(analytic[0], numeric[0], i) << "\t"
<< RMSNormDiff(analytic[1], numeric[1], i) << "\t"
<< maxNormDiff(analytic[1], numeric[1], i) << "\t"
<< RMSNormDiff(analytic[2], numeric[2], i) << "\t"
<< maxNormDiff(analytic[2], numeric[2], i) << "\n";
}
}
template <int rhocount, int xcount, int ycount, class RealT>
template <typename TFunc1, typename TFunc2>
void GyroAveragingGrid<rhocount, xcount, ycount, RealT>::InterpErrorAnalysis(
TFunc1 f, TFunc2 analytic) {
fill(gridValues, f); // This is the base grid of values we will
// interpolate.
fill(analytic_averages, analytic); // analytic formula for gyroaverages
fullgrid bicubictest;
setupInterpGrid();
setupDerivsGrid();
setupBicubicGrid();
for (auto i = 0; i < rhocount; i++)
for (auto j = 0; j < xcount; j++)
for (auto k = 0; k < ycount; k++) {
bicubictest(i, j, k) = interpNaiveBicubic(i, xset[j], yset[k]);
}
fillAlmostExactGA(almostExactGA, f);
fillTruncatedAlmostExactGA(truncatedAlmostExactGA, f);
fillTrapezoidInterp(trapezoidInterp, f);
fillBicubicInterp(bicubicInterp);
std::cout << "There were " << trapezoidInterp.data.size() << " entries. \n";
std::cout << "Diffs:\n";
std::cout
<< "rho Analytic vs Quadrature Error due to truncation "
" Error due to interp Analytic vs interp "
" interp vs dot-product GA GPU vs CPU\n";
for (int i = 0; i < rhocount; i++) {
std::cout.precision(5);
std::cout << std::fixed << rhoset[i] << std::scientific << std::setw(15)
<< RMSNormDiff(analytic_averages, almostExactGA, i) << "\t"
<< maxNormDiff(analytic_averages, almostExactGA, i) << "\t"
<< RMSNormDiff(almostExactGA, truncatedAlmostExactGA, i)
<< "\t"
<< maxNormDiff(almostExactGA, truncatedAlmostExactGA, i)
<< "\t"
<< RMSNormDiff(truncatedAlmostExactGA, trapezoidInterp, i)
<< "\t"
<< maxNormDiff(truncatedAlmostExactGA, trapezoidInterp, i)
<< "\t" << RMSNormDiff(analytic_averages, trapezoidInterp, i)
<< "\t" << maxNormDiff(analytic_averages, trapezoidInterp, i)
<< "\t"
<< RMSNormDiff(truncatedAlmostExactGA, bicubicInterp, i)
<< "\t"
<< maxNormDiff(truncatedAlmostExactGA, bicubicInterp, i)
<< "\n";
}
}
// below function is for testing and will be refactored later. | [
"[email protected]"
] | |
b7d74b9926c3533cfcff05980827de500b5c3fa9 | 5d4f80445645f0771d5bed3aebeac2c7c1d4210b | /gui/widget/calibrations/EndStopCalibrationWidget.cpp | 7ad0d6794d2c6610616ee175c0c2e01578edba61 | [] | no_license | Kaldie/GeRoBot | ac9f3699dbfd91111d2e60b939d82046f4636fdc | b7ad01d62df52995f5c82298b06113b0a26f79ce | refs/heads/master | 2020-12-24T16:15:57.102544 | 2017-03-21T13:23:56 | 2017-03-21T13:23:56 | 25,439,362 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,813 | cpp | // Copyright Ruud Cools [2017]
#include <macroHeader.h>
#include "./EndStopCalibrationWidget.h"
#include <QWidget>
#include <BaseCalibration.h>
#include <QTimer>
#include <QLineEdit>
#include <BaseJoint.h>
#include <EndStop.h>
#include <thread>
#include <EndStopCalibration.h>
EndStopCalibrationWidget::EndStopCalibrationWidget(const std::shared_ptr<BaseCalibration>& i_calibration,
QWidget* i_parent)
: CalibrationWidget(i_calibration, i_parent),
m_timer(std::make_shared<QTimer>(this)) {
if (i_calibration->getType() != BaseCalibration::EndStopCalibration) {
LOG_ERROR("Did not recieve the proper calibration!");
}
initialise();
}
void EndStopCalibrationWidget::initialise() {
connect(m_timer.get(), &QTimer::timeout,
this, &EndStopCalibrationWidget::updateJointInfo);
createAdditionalUIElements();
}
void EndStopCalibrationWidget::createAdditionalUIElements() {
// layout box for property label line edit combinations
// add joint position info
QHBoxLayout* hBox = new QHBoxLayout();
hBox->addWidget(new QLabel("Estimated Joint Position: "));
m_jointPosition = new QLineEdit();
m_jointPosition->setReadOnly(true);
hBox->addWidget(m_jointPosition);
calibrationLayout->addLayout(hBox);
// add joint movement per step info
hBox = new QHBoxLayout();
hBox->addWidget(new QLabel("Estimated Joint Movement per Step: "));
m_jointMovementPerStep = new QLineEdit();
m_jointMovementPerStep->setReadOnly(true);
hBox->addWidget(m_jointMovementPerStep);
// add the joint position
calibrationLayout->addLayout(hBox);
updateJointInfo();
// add end stop indicators as we have some
int i = 1;
QLineEdit* tmpLineEdit;
for (const auto& endStop : m_calibration->getJoint()->getEndStops()) {
hBox = new QHBoxLayout();
hBox->addWidget(new QLabel
(QString("EndStop %1 position:").arg(i)));
tmpLineEdit = new QLineEdit(QString::number(endStop->getPosition()));
tmpLineEdit->setReadOnly(true);
hBox->addWidget(tmpLineEdit);
calibrationLayout->addLayout(hBox);
++i;
}
}
void EndStopCalibrationWidget::updateJointInfo() {
LOG_DEBUG("Update joint info");
std::shared_ptr<BaseJoint> joint(m_calibration->getJoint());
m_jointPosition->setText(QString::number(joint->getPosition()));
m_jointMovementPerStep->setText(QString::number(joint->getMovementPerStep()));
}
void EndStopCalibrationWidget::executeCalibration() {
setEnabled(false);
connect(m_timer.get(),&QTimer::timeout,
this, &EndStopCalibrationWidget::evaluateCurrentCalibration);
std::thread endStopCalibrationThread(&EndStopCalibration::execute,
std::static_pointer_cast<EndStopCalibration>(m_calibration));
endStopCalibrationThread.detach();
m_timer->start(300);
}
void EndStopCalibrationWidget::evaluateCurrentCalibration() {
notifyCurrentState();
if (std::static_pointer_cast<EndStopCalibration>(m_calibration)->getState() ==
EndStopCalibration::Finished) {
LOG_DEBUG("Done execute calibration");
m_timer->stop();
setEnabled(true);
emit updateCalibrationOutText();
}
}
void EndStopCalibrationWidget::notifyCurrentState() {
std::string currentStateString;
switch (std::static_pointer_cast<EndStopCalibration>(m_calibration)->getState()) {
case EndStopCalibration::Idle:
currentStateString = "Idle";
break;
case EndStopCalibration::Moving:
currentStateString = "Moving";
break;
case EndStopCalibration::Sending:
currentStateString = "Sending";
break;
case EndStopCalibration::Calculating:
currentStateString = "Calculating";
break;
case EndStopCalibration::Finished:
currentStateString = "Finished";
default:
currentStateString = "Unknown";\
}
outputEdit->setPlainText(QString::fromStdString("Current state is: " + currentStateString));
}
| [
"[email protected]"
] | |
6cd169d4b1acfed6d306b9d7bf9ac06317bc06fc | 4bc5a7778610f297c2a7ddc9077cfde7890e8659 | /practica_9/practica_9/Window.cpp | 4ff0b9d86d08dbd267a10df32154acd1f70ce503 | [
"MIT"
] | permissive | ValdrST/lab_computacion_grafica | ed16550e2dbb7214fa2871a70aee66a86bfd89be | 5971e7a57acafd9df93463da533e756608cde066 | refs/heads/master | 2020-12-31T08:49:22.566800 | 2020-04-21T23:22:53 | 2020-04-21T23:22:53 | 238,956,166 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,841 | cpp | #include "Window.h"
Window::Window()
{
width = 800;
height = 600;
for (size_t i = 0; i < 1024; i++)
{
keys[i] = 0;
}
}
Window::Window(GLint windowWidth, GLint windowHeight)
{
width = windowWidth;
height = windowHeight;
muevex = 2.0f;
for (size_t i = 0; i < 1024; i++)
{
keys[i] = 0;
}
}
int Window::Initialise()
{
//Inicializaci�n de GLFW
if (!glfwInit())
{
printf("Fall� inicializar GLFW");
glfwTerminate();
return 1;
}
//Asignando variables de GLFW y propiedades de ventana
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5);
//para solo usar el core profile de OpenGL y no tener retrocompatibilidad
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
//CREAR VENTANA
mainWindow = glfwCreateWindow(width, height, "Proyecto Alameda", NULL, NULL);
if (!mainWindow)
{
printf("Fallo en crearse la ventana con GLFW");
glfwTerminate();
return 1;
}
//Obtener tama�o de Buffer
glfwGetFramebufferSize(mainWindow, &bufferWidth, &bufferHeight);
//asignar el contexto
glfwMakeContextCurrent(mainWindow);
//MANEJAR TECLADO y MOUSE
createCallbacks();
//permitir nuevas extensiones
glewExperimental = GL_TRUE;
if (glewInit() != GLEW_OK)
{
printf("Fall� inicializaci�n de GLEW");
glfwDestroyWindow(mainWindow);
glfwTerminate();
return 1;
}
glEnable(GL_DEPTH_TEST); //HABILITAR BUFFER DE PROFUNDIDAD
// Asignar valores de la ventana y coordenadas
//Asignar Viewport
glViewport(0, 0, bufferWidth, bufferHeight);
//Callback para detectar que se est� usando la ventana
glfwSetWindowUserPointer(mainWindow, this);
return 0;
}
void Window::createCallbacks()
{
glfwSetKeyCallback(mainWindow, ManejaTeclado);
glfwSetCursorPosCallback(mainWindow, ManejaMouse);
}
GLfloat Window::getXChange()
{
GLfloat theChange = xChange;
xChange = 0.0f;
return theChange;
}
GLfloat Window::getYChange()
{
GLfloat theChange = yChange;
yChange = 0.0f;
return theChange;
}
void Window::ManejaTeclado(GLFWwindow* window, int key, int code, int action, int mode)
{
Window* theWindow = static_cast<Window*>(glfwGetWindowUserPointer(window));
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
{
glfwSetWindowShouldClose(window, GL_TRUE);
}
if (key == GLFW_KEY_K)
{
theWindow-> muevex -= 0.10;
}
if (key == GLFW_KEY_SEMICOLON)
{
theWindow-> muevex += 0.10;
}
if (key == GLFW_KEY_L)
{
theWindow-> muevez -= 0.10;
}
if (key == GLFW_KEY_O)
{
theWindow-> muevez += 0.10;
}
if (key == GLFW_KEY_I)
{
theWindow-> muevey -= 0.10;
}
if (key == GLFW_KEY_P)
{
theWindow-> muevey += 0.10;
}
if (key == GLFW_KEY_F)
{
if(action == GLFW_RELEASE){
if(theWindow-> statusLight == true)
theWindow-> statusLight = false;
else
theWindow-> statusLight = true;
}
}
if (key >= 0 && key < 1024)
{
if (action == GLFW_PRESS)
{
theWindow->keys[key] = true;
printf("se presiono la tecla %d'\n", key);
}
else if (action == GLFW_RELEASE)
{
theWindow->keys[key] = false;
printf("se solto la tecla %d'\n", key);
}
}
}
void Window::ManejaMouse(GLFWwindow* window, double xPos, double yPos)
{
Window* theWindow = static_cast<Window*>(glfwGetWindowUserPointer(window));
if (theWindow->mouseFirstMoved)
{
theWindow->lastX = xPos;
theWindow->lastY = yPos;
theWindow->mouseFirstMoved = false;
}
theWindow->xChange = xPos - theWindow->lastX;
theWindow->yChange = theWindow->lastY - yPos;
theWindow->lastX = xPos;
theWindow->lastY = yPos;
}
Window::~Window()
{
glfwDestroyWindow(mainWindow);
glfwTerminate();
}
| [
"[email protected]"
] | |
e4cc96c29af17b25652ab21120f7683525d069da | 756594a30f68e178f6b1b2572422097c4318834c | /gcl/md5.cpp | 50be9d9ac1a5d0c2784598a53fd02dab1b4603b9 | [] | no_license | fcoulombe/gcl | cc8a980b5d5f3635b3faa8e0abbfab0464230dc8 | 43070441f8d670afdb8a9255987e2851200e615b | refs/heads/master | 2021-01-01T19:47:09.825629 | 2015-03-13T21:44:45 | 2015-03-13T21:44:45 | 2,240,567 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,063 | cpp | /*
Copyright (C) 1999, 2000, 2002 Aladdin Enterprises. All rights reserved.
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
L. Peter Deutsch
[email protected]
*/
/* $Id: md5.c,v 1.6 2002/04/13 19:20:28 lpd Exp $ */
/*
Independent implementation of MD5 (RFC 1321).
This code implements the MD5 Algorithm defined in RFC 1321, whose
text is available at
http://www.ietf.org/rfc/rfc1321.txt
The code is derived from the text of the RFC, including the test suite
(section A.5) but excluding the rest of Appendix A. It does not include
any code or documentation that is identified in the RFC as being
copyrighted.
The original and principal author of md5.c is L. Peter Deutsch
<[email protected]>. Other authors are noted in the change history
that follows (in reverse chronological order):
2002-04-13 lpd Clarified derivation from RFC 1321; now handles byte order
either statically or dynamically; added missing #include <string.h>
in library.
2002-03-11 lpd Corrected argument list for main(), and added int return
type, in test program and T value program.
2002-02-21 lpd Added missing #include <stdio.h> in test program.
2000-07-03 lpd Patched to eliminate warnings about "constant is
unsigned in ANSI C, signed in traditional"; made test program
self-checking.
1999-11-04 lpd Edited comments slightly for automatic TOC extraction.
1999-10-18 lpd Fixed typo in header comment (ansi2knr rather than md5).
1999-05-03 lpd Original version.
*/
#include "md5.h"
#include <string.h>
#undef BYTE_ORDER /* 1 = big-endian, -1 = little-endian, 0 = unknown */
#ifdef ARCH_IS_BIG_ENDIAN
# define BYTE_ORDER (ARCH_IS_BIG_ENDIAN ? 1 : -1)
#else
# define BYTE_ORDER 0
#endif
#define T_MASK ((md5_word_t)~0)
#define T1 /* 0xd76aa478 */ (T_MASK ^ 0x28955b87)
#define T2 /* 0xe8c7b756 */ (T_MASK ^ 0x173848a9)
#define T3 0x242070db
#define T4 /* 0xc1bdceee */ (T_MASK ^ 0x3e423111)
#define T5 /* 0xf57c0faf */ (T_MASK ^ 0x0a83f050)
#define T6 0x4787c62a
#define T7 /* 0xa8304613 */ (T_MASK ^ 0x57cfb9ec)
#define T8 /* 0xfd469501 */ (T_MASK ^ 0x02b96afe)
#define T9 0x698098d8
#define T10 /* 0x8b44f7af */ (T_MASK ^ 0x74bb0850)
#define T11 /* 0xffff5bb1 */ (T_MASK ^ 0x0000a44e)
#define T12 /* 0x895cd7be */ (T_MASK ^ 0x76a32841)
#define T13 0x6b901122
#define T14 /* 0xfd987193 */ (T_MASK ^ 0x02678e6c)
#define T15 /* 0xa679438e */ (T_MASK ^ 0x5986bc71)
#define T16 0x49b40821
#define T17 /* 0xf61e2562 */ (T_MASK ^ 0x09e1da9d)
#define T18 /* 0xc040b340 */ (T_MASK ^ 0x3fbf4cbf)
#define T19 0x265e5a51
#define T20 /* 0xe9b6c7aa */ (T_MASK ^ 0x16493855)
#define T21 /* 0xd62f105d */ (T_MASK ^ 0x29d0efa2)
#define T22 0x02441453
#define T23 /* 0xd8a1e681 */ (T_MASK ^ 0x275e197e)
#define T24 /* 0xe7d3fbc8 */ (T_MASK ^ 0x182c0437)
#define T25 0x21e1cde6
#define T26 /* 0xc33707d6 */ (T_MASK ^ 0x3cc8f829)
#define T27 /* 0xf4d50d87 */ (T_MASK ^ 0x0b2af278)
#define T28 0x455a14ed
#define T29 /* 0xa9e3e905 */ (T_MASK ^ 0x561c16fa)
#define T30 /* 0xfcefa3f8 */ (T_MASK ^ 0x03105c07)
#define T31 0x676f02d9
#define T32 /* 0x8d2a4c8a */ (T_MASK ^ 0x72d5b375)
#define T33 /* 0xfffa3942 */ (T_MASK ^ 0x0005c6bd)
#define T34 /* 0x8771f681 */ (T_MASK ^ 0x788e097e)
#define T35 0x6d9d6122
#define T36 /* 0xfde5380c */ (T_MASK ^ 0x021ac7f3)
#define T37 /* 0xa4beea44 */ (T_MASK ^ 0x5b4115bb)
#define T38 0x4bdecfa9
#define T39 /* 0xf6bb4b60 */ (T_MASK ^ 0x0944b49f)
#define T40 /* 0xbebfbc70 */ (T_MASK ^ 0x4140438f)
#define T41 0x289b7ec6
#define T42 /* 0xeaa127fa */ (T_MASK ^ 0x155ed805)
#define T43 /* 0xd4ef3085 */ (T_MASK ^ 0x2b10cf7a)
#define T44 0x04881d05
#define T45 /* 0xd9d4d039 */ (T_MASK ^ 0x262b2fc6)
#define T46 /* 0xe6db99e5 */ (T_MASK ^ 0x1924661a)
#define T47 0x1fa27cf8
#define T48 /* 0xc4ac5665 */ (T_MASK ^ 0x3b53a99a)
#define T49 /* 0xf4292244 */ (T_MASK ^ 0x0bd6ddbb)
#define T50 0x432aff97
#define T51 /* 0xab9423a7 */ (T_MASK ^ 0x546bdc58)
#define T52 /* 0xfc93a039 */ (T_MASK ^ 0x036c5fc6)
#define T53 0x655b59c3
#define T54 /* 0x8f0ccc92 */ (T_MASK ^ 0x70f3336d)
#define T55 /* 0xffeff47d */ (T_MASK ^ 0x00100b82)
#define T56 /* 0x85845dd1 */ (T_MASK ^ 0x7a7ba22e)
#define T57 0x6fa87e4f
#define T58 /* 0xfe2ce6e0 */ (T_MASK ^ 0x01d3191f)
#define T59 /* 0xa3014314 */ (T_MASK ^ 0x5cfebceb)
#define T60 0x4e0811a1
#define T61 /* 0xf7537e82 */ (T_MASK ^ 0x08ac817d)
#define T62 /* 0xbd3af235 */ (T_MASK ^ 0x42c50dca)
#define T63 0x2ad7d2bb
#define T64 /* 0xeb86d391 */ (T_MASK ^ 0x14792c6e)
static void
md5_process(md5_state_t *pms, const md5_byte_t *data /*[64]*/)
{
md5_word_t
a = pms->abcd[0], b = pms->abcd[1],
c = pms->abcd[2], d = pms->abcd[3];
md5_word_t t;
#if BYTE_ORDER > 0
/* Define storage only for big-endian CPUs. */
md5_word_t X[16];
#else
/* Define storage for little-endian or both types of CPUs. */
md5_word_t xbuf[16];
const md5_word_t *X;
#endif
{
#if BYTE_ORDER == 0
/*
* Determine dynamically whether this is a big-endian or
* little-endian machine, since we can use a more efficient
* algorithm on the latter.
*/
static const int w = 1;
if (*((const md5_byte_t *)&w)) /* dynamic little-endian */
#endif
#if BYTE_ORDER <= 0 /* little-endian */
{
/*
* On little-endian machines, we can process properly aligned
* data without copying it.
*/
if (!((data - (const md5_byte_t *)0) & 3)) {
/* data are properly aligned */
X = (const md5_word_t *)data;
} else {
/* not aligned */
memcpy(xbuf, data, 64);
X = xbuf;
}
}
#endif
#if BYTE_ORDER == 0
else /* dynamic big-endian */
#endif
#if BYTE_ORDER >= 0 /* big-endian */
{
/*
* On big-endian machines, we must arrange the bytes in the
* right order.
*/
const md5_byte_t *xp = data;
int i;
# if BYTE_ORDER == 0
X = xbuf; /* (dynamic only) */
# else
# define xbuf X /* (static only) */
# endif
for (i = 0; i < 16; ++i, xp += 4)
xbuf[i] = xp[0] + (xp[1] << 8) + (xp[2] << 16) + (xp[3] << 24);
}
#endif
}
#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32 - (n))))
/* Round 1. */
/* Let [abcd k s i] denote the operation
a = b + ((a + F(b,c,d) + X[k] + T[i]) <<< s). */
#define F(x, y, z) (((x) & (y)) | (~(x) & (z)))
#define SET(a, b, c, d, k, s, Ti)\
t = a + F(b,c,d) + X[k] + Ti;\
a = ROTATE_LEFT(t, s) + b
/* Do the following 16 operations. */
SET(a, b, c, d, 0, 7, T1);
SET(d, a, b, c, 1, 12, T2);
SET(c, d, a, b, 2, 17, T3);
SET(b, c, d, a, 3, 22, T4);
SET(a, b, c, d, 4, 7, T5);
SET(d, a, b, c, 5, 12, T6);
SET(c, d, a, b, 6, 17, T7);
SET(b, c, d, a, 7, 22, T8);
SET(a, b, c, d, 8, 7, T9);
SET(d, a, b, c, 9, 12, T10);
SET(c, d, a, b, 10, 17, T11);
SET(b, c, d, a, 11, 22, T12);
SET(a, b, c, d, 12, 7, T13);
SET(d, a, b, c, 13, 12, T14);
SET(c, d, a, b, 14, 17, T15);
SET(b, c, d, a, 15, 22, T16);
#undef SET
/* Round 2. */
/* Let [abcd k s i] denote the operation
a = b + ((a + G(b,c,d) + X[k] + T[i]) <<< s). */
#define G(x, y, z) (((x) & (z)) | ((y) & ~(z)))
#define SET(a, b, c, d, k, s, Ti)\
t = a + G(b,c,d) + X[k] + Ti;\
a = ROTATE_LEFT(t, s) + b
/* Do the following 16 operations. */
SET(a, b, c, d, 1, 5, T17);
SET(d, a, b, c, 6, 9, T18);
SET(c, d, a, b, 11, 14, T19);
SET(b, c, d, a, 0, 20, T20);
SET(a, b, c, d, 5, 5, T21);
SET(d, a, b, c, 10, 9, T22);
SET(c, d, a, b, 15, 14, T23);
SET(b, c, d, a, 4, 20, T24);
SET(a, b, c, d, 9, 5, T25);
SET(d, a, b, c, 14, 9, T26);
SET(c, d, a, b, 3, 14, T27);
SET(b, c, d, a, 8, 20, T28);
SET(a, b, c, d, 13, 5, T29);
SET(d, a, b, c, 2, 9, T30);
SET(c, d, a, b, 7, 14, T31);
SET(b, c, d, a, 12, 20, T32);
#undef SET
/* Round 3. */
/* Let [abcd k s t] denote the operation
a = b + ((a + H(b,c,d) + X[k] + T[i]) <<< s). */
#define H(x, y, z) ((x) ^ (y) ^ (z))
#define SET(a, b, c, d, k, s, Ti)\
t = a + H(b,c,d) + X[k] + Ti;\
a = ROTATE_LEFT(t, s) + b
/* Do the following 16 operations. */
SET(a, b, c, d, 5, 4, T33);
SET(d, a, b, c, 8, 11, T34);
SET(c, d, a, b, 11, 16, T35);
SET(b, c, d, a, 14, 23, T36);
SET(a, b, c, d, 1, 4, T37);
SET(d, a, b, c, 4, 11, T38);
SET(c, d, a, b, 7, 16, T39);
SET(b, c, d, a, 10, 23, T40);
SET(a, b, c, d, 13, 4, T41);
SET(d, a, b, c, 0, 11, T42);
SET(c, d, a, b, 3, 16, T43);
SET(b, c, d, a, 6, 23, T44);
SET(a, b, c, d, 9, 4, T45);
SET(d, a, b, c, 12, 11, T46);
SET(c, d, a, b, 15, 16, T47);
SET(b, c, d, a, 2, 23, T48);
#undef SET
/* Round 4. */
/* Let [abcd k s t] denote the operation
a = b + ((a + I(b,c,d) + X[k] + T[i]) <<< s). */
#define I(x, y, z) ((y) ^ ((x) | ~(z)))
#define SET(a, b, c, d, k, s, Ti)\
t = a + I(b,c,d) + X[k] + Ti;\
a = ROTATE_LEFT(t, s) + b
/* Do the following 16 operations. */
SET(a, b, c, d, 0, 6, T49);
SET(d, a, b, c, 7, 10, T50);
SET(c, d, a, b, 14, 15, T51);
SET(b, c, d, a, 5, 21, T52);
SET(a, b, c, d, 12, 6, T53);
SET(d, a, b, c, 3, 10, T54);
SET(c, d, a, b, 10, 15, T55);
SET(b, c, d, a, 1, 21, T56);
SET(a, b, c, d, 8, 6, T57);
SET(d, a, b, c, 15, 10, T58);
SET(c, d, a, b, 6, 15, T59);
SET(b, c, d, a, 13, 21, T60);
SET(a, b, c, d, 4, 6, T61);
SET(d, a, b, c, 11, 10, T62);
SET(c, d, a, b, 2, 15, T63);
SET(b, c, d, a, 9, 21, T64);
#undef SET
/* Then perform the following additions. (That is increment each
of the four registers by the value it had before this block
was started.) */
pms->abcd[0] += a;
pms->abcd[1] += b;
pms->abcd[2] += c;
pms->abcd[3] += d;
}
void
md5_init(md5_state_t *pms)
{
pms->count[0] = pms->count[1] = 0;
pms->abcd[0] = 0x67452301;
pms->abcd[1] = /*0xefcdab89*/ T_MASK ^ 0x10325476;
pms->abcd[2] = /*0x98badcfe*/ T_MASK ^ 0x67452301;
pms->abcd[3] = 0x10325476;
}
void
md5_append(md5_state_t *pms, const md5_byte_t *data, int nbytes)
{
const md5_byte_t *p = data;
int left = nbytes;
int offset = (pms->count[0] >> 3) & 63;
md5_word_t nbits = (md5_word_t)(nbytes << 3);
if (nbytes <= 0)
return;
/* Update the message length. */
pms->count[1] += nbytes >> 29;
pms->count[0] += nbits;
if (pms->count[0] < nbits)
pms->count[1]++;
/* Process an initial partial block. */
if (offset) {
int copy = (offset + nbytes > 64 ? 64 - offset : nbytes);
memcpy(pms->buf + offset, p, copy);
if (offset + copy < 64)
return;
p += copy;
left -= copy;
md5_process(pms, pms->buf);
}
/* Process full blocks. */
for (; left >= 64; p += 64, left -= 64)
md5_process(pms, p);
/* Process a final partial block. */
if (left)
memcpy(pms->buf, p, left);
}
void
md5_finish(md5_state_t *pms, md5_byte_t digest[16])
{
static const md5_byte_t pad[64] = {
0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
md5_byte_t data[8];
int i;
/* Save the length before padding. */
for (i = 0; i < 8; ++i)
data[i] = (md5_byte_t)(pms->count[i >> 2] >> ((i & 3) << 3));
/* Pad to 56 bytes mod 64. */
md5_append(pms, pad, ((55 - (pms->count[0] >> 3)) & 63) + 1);
/* Append the length. */
md5_append(pms, data, 8);
for (i = 0; i < 16; ++i)
digest[i] = (md5_byte_t)(pms->abcd[i >> 2] >> ((i & 3) << 3));
}
| [
"[email protected]"
] | |
32fb35727debcf9152d2c499b18eb20566336929 | e0089e71e523e4dd46bc1040498ee51c713f31f7 | /simulation/g4simulation/g4eval/DSTEmulator.h | b55d7e7b5afbe2ebc78fa1a80826ff511baaad7d | [] | no_license | johnlajoie/coresoftware | d66ba3c4c6af6380061dff630e84b6a75bc28d02 | 57a393eade7a5edad8fb6a602d730845ae2143d4 | refs/heads/master | 2022-01-03T04:11:51.631461 | 2021-12-19T12:29:43 | 2021-12-19T12:29:43 | 38,701,802 | 0 | 0 | null | 2015-07-07T16:52:39 | 2015-07-07T16:52:38 | null | UTF-8 | C++ | false | false | 2,713 | h | #ifndef G4EVAL_DSTEMULATOR_H
#define G4EVAL_DSTEMULATOR_H
/*!
* \file TrackEvaluation.h
* \author Hugo Pereira Da Costa <[email protected]>
*/
#include <fun4all/SubsysReco.h>
#include <trackbase/TrkrDefs.h>
#include <trackbase/ActsSurfaceMaps.h>
#include <trackbase/ActsTrackingGeometry.h>
#include <map>
#include <set>
#include <string>
#include <vector>
class PHG4Hit;
class PHG4HitContainer;
class PHG4Particle;
class PHG4TruthInfoContainer;
class SvtxTrack;
class SvtxTrackMap;
class TrackEvaluationContainerv1;
class TrkrCluster;
class TrkrClusterContainer;
class TrkrClusterHitAssoc;
class TrkrHitSetContainer;
class TrkrHitTruthAssoc;
class TFile;
class TNtuple;
class DSTEmulator : public SubsysReco
{
public:
//! constructor
DSTEmulator( const std::string& = "DSTEmulator",
const std::string &filename = "DSTana.root" );
//! global initialization
int Init(PHCompositeNode*) override;
//! run initialization
int InitRun(PHCompositeNode*) override;
//! event processing
int process_event(PHCompositeNode*) override;
//! end of processing
int End(PHCompositeNode*) override;
private:
//! load nodes
int load_nodes( PHCompositeNode* );
//! evaluate tracks
void evaluate_tracks();
float compress_dx(float in_val);
float compress_dy(float in_val);
// get geant hits associated to a cluster
using G4HitSet = std::set<PHG4Hit*>;
G4HitSet find_g4hits( TrkrDefs::cluskey ) const;
//! get G4Particle id of max contributor to a given track
std::pair<int,int> get_max_contributor( SvtxTrack* ) const;
//! get embedded id for given g4track
int get_embed(PHG4Particle*) const;
//! evaluation node
TrackEvaluationContainerv1* m_container = nullptr;
//! hits
TrkrHitSetContainer* m_hitsetcontainer = nullptr;
//! clusters
TrkrClusterContainer* m_cluster_map = nullptr;
//! cluster to hit association
TrkrClusterHitAssoc* m_cluster_hit_map = nullptr;
//! hit to truth association
TrkrHitTruthAssoc* m_hit_truth_map = nullptr;
//! tracks
SvtxTrackMap* m_track_map = nullptr;
//!@name geant4 hits
//@{
PHG4HitContainer* m_g4hits_tpc = nullptr;
PHG4HitContainer* m_g4hits_intt = nullptr;
PHG4HitContainer* m_g4hits_mvtx = nullptr;
PHG4HitContainer* m_g4hits_micromegas = nullptr;
//@}
//! truth information
PHG4TruthInfoContainer* m_g4truthinfo = nullptr;
// map cluster keys to g4hits
using G4HitMap = std::map<TrkrDefs::cluskey,G4HitSet>;
mutable G4HitMap m_g4hit_map;
ActsSurfaceMaps *m_surfMaps = nullptr;
ActsTrackingGeometry *m_tGeometry = nullptr;
TNtuple *_dst_data;
// output file
std::string _filename;
TFile *_tfile;
};
#endif // G4EVAL_DSTEMULATOR_H
| [
"[email protected]"
] | |
321a68ec3852237e259d36104a3f3ec262dde4cb | bb5fb7a64f08cc9e05114c5a6f25e6025891b3f8 | /notes/ObjectRelationships.cpp | 3ec896bcd03e84c76955451a147b16fdee8bf00f | [] | no_license | meenurathi/CppNotes | ac8ac2f67dcfe6c15a10e5d59efe10e9e815e858 | 1baedcb2500e8ae24236983dd201e64ac6d87e71 | refs/heads/master | 2023-02-11T19:47:50.111992 | 2021-01-14T03:15:12 | 2021-01-14T03:15:12 | 324,540,184 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,358 | cpp | //Relationships:
/*
Terminology:
object--> parentcontains part/component
1)Object Composition :"has-a" /"part-of"
process of building complex objts from simpler ones
e.g struct & car are composite types
sub types
---composition
---aggregation */
/*>>>>>>Composition
To qualify as a composition, an object and a part must have the following relationship:
The part (member) is part of the object (class)
The part (member) can only belong to one object (class) at a time
single owner
The part (member) has its existence managed by the object (class)
death relationship
The part (member) does not know about the existence of the object (class)
unidirectional relationship, because the body knows about the heart, but not the other way around
--
> A composition may defer creation of some parts until they are needed. For example, a string class may not create a dynamic array of characters until the user assigns the string some data to hold.
> A composition may opt to use a part that has been given to it as input rather than create the part itself.
> A composition may delegate destruction of its parts to some other object (e.g. to a garbage collection routine).
The key point here is that the composition should manage its parts without the user of the composition needing to manage anything.
That task should either be the storage and manipulation of some kind of data (e.g. Point2D, std::string), OR the coordination of subclasses (e.g. Creature). Ideally not both.
*/
/* >>>>> Aggregation "has-a"
To qualify as an aggregation, a whole object and its parts must have the following relationship:
The part (member) is part of the object (class) (SAME AS COMPOSITION)
part-whole relationship
The part (member) can belong to more than one object (class) at a time (opposite of Composition)
stores as reference or pointer , which are provided during construction or by member functions
The part (member) does not have its existence managed by the object (class) (opposite of Composition)
Part may exist before creating containing object or may persist after containing obj destruction
The part (member) does not know about the existence of the object (class) (SAME AS COMPOSTION)
unidirection relationship
*/
/*
Compositions: e.g body - heart (heart cannot exist without body}
Typically use normal member variables
Can use pointer members if the class handles object allocation/deallocation itself
Responsible for creation/destruction of parts
Aggregations: e.g bag-pebble, car-engine (engine can exist without car)
Typically use pointer or reference members that point to or reference objects that live outside the scope of the aggregate class
Not responsible for creating/destroying parts
>this can cause memory leak, if part objt is not destroyed by external identity
>so, composition should be pereferred over aggregation
Note: It is worth noting that the concepts of composition and aggregation are not mutually exclusive, and can be mixed freely within the same class.
*/
//....... reference_wrapper
/*
1) std::reference_wrapper lives in the <functional> header.
2) When you create your std::reference_wrapper wrapped object, the object can’t be an anonymous object
(since anonymous objects have expression scope would leave the reference dangling).
>allow us to create vector of references
3) When you want to get your object back out of std::reference_wrapper, you use the get() member function.
The good news is that you don’t really need to understand how it works to use it. All you need to know are three things:
*/
#include <functional> // std::reference_wrapper
#include <iostream>
#include <vector>
#include <string>
int main1()
{
std::string tom{ "Tom" };
std::string berta{ "Berta" };
//std::vector<const std::string&> names {tom, berta}; //illegal
//List elements cannot be references because references have to be initialized and cannot be reassigned
// Vector of const references to std::string
std::vector<std::reference_wrapper<std::string>> names {tom, berta};
std::string james{"james"};
names.push_back(james);
for(auto name: names){
name.get()+=" Bean";
}
for(auto name: names)
std::cout<<name.get()<<", ";
return 0;
}
/*
Would you be more likely to implement the following as a composition or an aggregation?
a) A ball that has a color
b) An employer that is employing multiple people
c) The departments in a university
d) Your age
e) A bag of marbles
ans:
a) Composition: Color is an intrinsic property of a ball.
b) Aggregation: An employer doesn’t start with any employees and hopefully doesn’t destroy all its employees when it goes bankrupt.
c) Composition: Departments can’t exist in absence of a university.
d) Composition: Your age is an intrinsic property of you.
e) Aggregation: The bag and the marbles inside have independent existences.
*/
//e.g.
#include <functional> // std::reference_wrapper
#include <iostream>
#include <string>
#include <vector>
class Teacher
{
private:
std::string m_name{};
public:
Teacher(const std::string& name)
: m_name{ name }{ }
const std::string& getName() const { return m_name; }
};
class Department
{
private:
std::vector<std::reference_wrapper<const Teacher>> m_teachers{};
public:
// Pass by regular reference. The user of the Department class shouldn't care
// about how it's implemented.
void add(const Teacher& teacher)
{
m_teachers.push_back(teacher);
}
friend std::ostream& operator<<(std::ostream& out, const Department& department)
{
out << "Department: ";
for (const auto& teacher : department.m_teachers)
{
out << teacher.get().getName() << ' ';
}
out << '\n';
return out;
}
};
int main2()
{
// Create a teacher outside the scope of the Department
Teacher t1{ "Bob" };
Teacher t2{ "Frank" };
Teacher t3{ "Beth" };
{
// Create a department and add some Teachers to it
Department department{}; // create an empty Department
department.add(t1);
department.add(t2);
department.add(t3);
std::cout << department;
} // department goes out of scope here and is destroyed
std::cout << t1.getName() << " still exists!\n";
std::cout << t2.getName() << " still exists!\n";
std::cout << t3.getName() << " still exists!\n";
return 0;
}
//Association : relationship between two unrelated objects
//"uses-a " relationship
/*
To qualify as an association, an object and another object must have the following relationship:
The associated object (member) is otherwise unrelated to the object (class)
The associated object (member) can belong to more than one object (class) at a time
The associated object (member) does not have its existence managed by the object (class)
The associated object (member) may or may not know about the existence of the object (class)
>unidirection (preferred)/ bidirectional relationship(shoulb be avoided)
eg. dr patient rleationship >> dr uses patient to earn money, patient uses dr for health
Associations may be implemented via pointer or reference, or by a more indirect means (such as holding the index or key of the associated object).
*/
#include<string>
#include<vector>
class Patient;
class Doctor{
std::string m_name{};
std::vector<std::reference_wrapper<const Patient>> m_patient;
public:
Doctor(const std::string &name):m_name(name){};
void addPatient( Patient & patient);
const std::string & getName()const {
return m_name;
}
friend std::ostream& operator<<(std::ostream &out, const Doctor &doctor);
};
class Patient{
std::string m_name{};
std::vector<std::reference_wrapper<const Doctor>> m_doctor{};
public:
Patient(const std::string & name):m_name{name}{};
void addDoctor(const Doctor & dr){
m_doctor.push_back(dr);
}
const std::string &getName()const {
return m_name;
}
friend std::ostream& operator<<(std::ostream &out, const Patient &patient);
};
void Doctor::addPatient( Patient & patient){
m_patient.push_back(patient);
patient.addDoctor(*this);
}
std::ostream& operator<<(std::ostream &out, const Doctor &doctor)
{
if (doctor.m_patient.empty())
{
out << doctor.m_name << " has no patients right now";
return out;
}
out << doctor.m_name << " is seeing patients: ";
for (const auto& patient : doctor.m_patient)
out << patient.get().getName() << ", ";
return out;
}
std::ostream& operator<<(std::ostream &out, const Patient &patient)
{
if (patient.m_doctor.empty())
{
out << patient.getName() << " has no doctors right now";
return out;
}
out << patient.m_name << " is seeing doctors: ";
for (const auto& doctor : patient.m_doctor)
out << doctor.get().getName() << ", ";
return out;
}
int main()
{
// Create a Patient outside the scope of the Doctor
Patient dave{ "Dave" };
Patient frank{ "Frank" };
Patient betsy{ "Betsy" };
Doctor james{ "James" };
Doctor scott{ "Scott" };
james.addPatient(dave);
scott.addPatient(dave);
scott.addPatient(betsy);
std::cout << james << '\n';
std::cout << scott << '\n';
std::cout << dave << '\n';
std::cout << frank << '\n';
std::cout << betsy << '\n';
return 0;
}
//.. Reflexive association
//objects may have a relationship with other objects of the same type.
#include <string>
class Course
{
private:
std::string m_name;
const Course *m_prerequisite;//reflexive relationship
public:
Course(const std::string &name, const Course *prerequisite = nullptr):
m_name{ name }, m_prerequisite{ prerequisite } { }
};
//This can lead to a chain of associations (a course has a prerequisite, which has a prerequisite, etc…)
//Associations can be indirect :
/* Any kind of data that allows you to link two objects together suffices.
a Driver class can have a unidirectional association with a Car USING CARID ,without actually including a Car pointer or reference member . using cardid it can search in carLot for getting car of the carid */
/*
Composition vs aggregation vs association vs dependecy summary
Property Composition Aggregation Association Dependency
Relationship type Whole/part Whole/part Otherwise unrelated Otherwise unrelated
Members can belong to multiple classes No Yes Yes Yes
Members existence managed by class Yes No No No Directionality Unidirectional Unidirectional Unidirectional Unidirectional
or bidirectional or bidirectional
Relationship verb Part-of Has-a Uses-a Depends-on
*/ | [
"[email protected]"
] | |
1bb653e86a2fd5ad94400d12395b799857147149 | e912095f4db6d464b7f75cf3aa3d654bd3d56fac | /39_FuntionTemplateswithMultipleParameter.cpp | 92aa674a14afcd8b9c025f8556224701541013ac | [] | no_license | dr-poco/Cpp_tutorials | 0dc87b737da65f0908de5d73c4e44be85a626e68 | b99167eb14fdbffbde27053e17ad10e4105b3d61 | refs/heads/master | 2023-06-17T22:59:57.309850 | 2021-07-15T01:38:15 | 2021-07-15T01:38:15 | 386,126,407 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 314 | cpp | #include <iostream>
#include <string>
using namespace std;
//Here datatype may be of any type, one int and another one float.
template <class first, class second>
first Max(first a, second b)
{
return (a > b ? a : b);
}
int main()
{
float x = 36.35466;
int y = 48;
cout << Max(x, y) << endl;
}
| [
"[email protected]"
] | |
dad17258a6edc9572c476ce9b2ce09ee6a49245f | 981d3bc3b62d8be02657c3d385c751efebf993a4 | /flowbench/BenchCallback.actor.cpp | a7c7fd207e04913e878af9da54907b9c313fed0c | [
"Apache-2.0"
] | permissive | TheBenCollins/foundationdb | d2b22f3b63525e3ec9ea6475c79630abe4701cc2 | e6950abae6914dab989ec00a4b4b648bb9d8af52 | refs/heads/master | 2022-06-20T01:04:35.104630 | 2022-03-05T01:09:06 | 2022-03-09T19:48:08 | 146,839,943 | 0 | 0 | Apache-2.0 | 2018-08-31T04:01:42 | 2018-08-31T04:01:42 | null | UTF-8 | C++ | false | false | 2,315 | cpp | /*
* BenchCallback.actor.cpp
*
* This source file is part of the FoundationDB open source project
*
* Copyright 2013-2020 Apple Inc. and the FoundationDB project authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "benchmark/benchmark.h"
#include <vector>
#include "fdbclient/FDBTypes.h"
#include "flow/flow.h"
#include "flow/ThreadHelper.actor.h"
#include "flow/actorcompiler.h" // This must be the last #include.
ACTOR template <size_t Size>
static Future<Void> increment(Future<Void> f, uint32_t* sum) {
state std::array<uint8_t, Size> arr;
wait(f);
benchmark::DoNotOptimize(arr);
++(*sum);
return Void();
}
ACTOR template <size_t Size>
static Future<Void> benchCallbackActor(benchmark::State* benchState) {
state size_t actorCount = benchState->range(0);
state uint32_t sum;
while (benchState->KeepRunning()) {
sum = 0;
Promise<Void> trigger;
std::vector<Future<Void>> futures;
futures.reserve(actorCount);
for (int i = 0; i < actorCount; ++i) {
futures.push_back(increment<Size>(trigger.getFuture(), &sum));
}
trigger.send(Void());
wait(waitForAll(futures));
benchmark::DoNotOptimize(sum);
}
benchState->SetItemsProcessed(actorCount * static_cast<long>(benchState->iterations()));
benchState->SetBytesProcessed(actorCount * Size * static_cast<long>(benchState->iterations()));
return Void();
}
template <size_t Size>
static void bench_callback(benchmark::State& benchState) {
onMainThread([&benchState]() { return benchCallbackActor<Size>(&benchState); }).blockUntilReady();
}
BENCHMARK_TEMPLATE(bench_callback, 1)->Range(1, 1 << 8)->ReportAggregatesOnly(true);
BENCHMARK_TEMPLATE(bench_callback, 32)->Range(1, 1 << 8)->ReportAggregatesOnly(true);
BENCHMARK_TEMPLATE(bench_callback, 1024)->Range(1, 1 << 8)->ReportAggregatesOnly(true);
| [
"[email protected]"
] | |
3b0a93c36c3e36c136b4420034d1a4141c0082a7 | 444fc1019dc18a005ca8b1d80f34353d5435fe24 | /CS.cpp/data_structure/tree/binary_tree_test.cpp | 53cecac177bc63c341f0bb029b8848a109692787 | [] | no_license | adan830/CS.cpp | e177775faa2ddfc1bb20ccf94e7a1657d89c0f69 | 6b49417f4fd840328ae3552b422b2865f05ba77a | refs/heads/master | 2021-01-15T11:34:46.641918 | 2016-03-07T11:12:37 | 2016-03-07T11:12:37 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 7,915 | cpp | #include "binary_tree.h"
#include <queue>
#include <memory>
#include "algorithm.h"
NS_BEGIN(elloop)
template <typename T>
typename TreeHelper<T>::Tree* TreeHelper<T>::createBinaryTreeUsingLevelOrder(ValueList items) {
// init a queue.
// while index < items.size, new a tree node. and enqueue it's left and right child.
// while the queue is not empty, pop and create node with items[index]
auto nodesCount = items.size();
if (0 == nodesCount) {
return nullptr;
}
// create a tree.
auto tree = new Tree();
auto node = &(tree->root_);
std::queue<Node** > childQueue;
childQueue.push(node);
size_t index(0);
while (index < nodesCount) {
node = childQueue.front();
(*node) = new Node(items[index++]);
childQueue.push(&((*node)->left_));
childQueue.push(&((*node)->right_));
childQueue.pop();
}
return tree;
}
template <typename T>
typename TreeHelper<T>::Tree* TreeHelper<T>::createBinaryTreeUsingPreAndInOrder(
ValueList preOrder, ValueList inOrder) {
if (preOrder.empty() ||
inOrder.empty() ||
inOrder.size() != preOrder.size()) {
return nullptr;
}
Tree * tree = new Tree();
tree->setRoot(createBinaryTreeUsingPreAndInOrder(preOrder, 0, preOrder.size() - 1,
inOrder, 0, inOrder.size() - 1));
return tree;
}
template <typename T>
typename TreeHelper<T>::Node* TreeHelper<T>::createBinaryTreeUsingPreAndInOrder(
ValueList preOrder, size_t indexPl, size_t indexPr,
ValueList inOrder, size_t indexIl, size_t indexIr) {
if (indexPr < indexPl) {
return nullptr;
}
if (indexIr < indexIl) {
return nullptr;
}
T value = preOrder[indexPl];
Node* root = new Node(value);
// 取出多少个元素用来构造子树:到中序序列里面去找根在第几个。
size_t count(0);
while ((indexIl + count <= indexIr) && (value != inOrder[indexIl + count])) {
++count;
}
// 用count个元素来构建左子树,剩下的去构建右子树.
root->setLeft(createBinaryTreeUsingPreAndInOrder(preOrder, indexPl + 1, indexPl + count,
inOrder, indexIl, indexIl + count - 1));
root->setRight(createBinaryTreeUsingPreAndInOrder(preOrder, indexPl + count + 1, indexPr,
inOrder, indexIl + count + 1, indexIr));
return root;
}
template <typename T>
void TreeHelper<T>::printBinaryTree(const Node * root, size_t indent, size_t inc) {
if (nullptr == root) {
return;
}
printBinaryTree(root->right_, indent + inc, inc);
for (size_t i = 0; i < indent; ++i) {
p(" ");
}
pln(root->value_);
printBinaryTree(root->left_, indent + inc, inc);
}
template <typename T>
void TreeHelper<T>::releaseBinaryTree(Tree* tree) {
changeBinaryTree(tree, [](Node * & node) {
delete node;
node = nullptr;
});
}
template <typename T>
void TreeHelper<T>::changeBinaryTree(Tree* tree, typename Tree::visitor visit) {
tree->postOrder(visit);
}
template <typename T>
size_t TreeHelper<T>::getBinaryTreeLeafCount(const Tree* tree) {
size_t leafCount(0);
countBinaryTreeLeaf(tree->root(), leafCount);
return leafCount;
}
template <typename T>
void TreeHelper<T>::countBinaryTreeLeaf(const Node* node, size_t & count) {
if (node != nullptr) {
if (node->left() == nullptr && node->right() == nullptr) {
++count;
return;
}
countBinaryTreeLeaf(node->left(), count);
countBinaryTreeLeaf(node->right(), count);
}
}
template <typename T>
size_t TreeHelper<T>::getTreeHeight(const Node* node) {
size_t lHeight(0);
size_t rHeight(0);
size_t height(0);
if (nullptr == node) {
height = 0;
}
else {
lHeight = getTreeHeight(node->left());
rHeight = getTreeHeight(node->right());
height = max(lHeight, rHeight) + 1;
}
return height;
}
template <typename T>
typename TreeHelper<T>::Tree* TreeHelper<T>::copyTree(const Tree* tree) {
if (tree != nullptr) {
Tree* treeCopy = new Tree();
treeCopy->root_ = copySubTree(tree->root());
return treeCopy;
}
return nullptr;
}
template <typename T>
typename TreeHelper<T>::Node * TreeHelper<T>::copySubTree(const Node* node) {
if (nullptr == node) {
return nullptr;
}
Node* left = copySubTree(node->left());
Node* right = copySubTree(node->right());
return new Node(node->value(), left, right);
}
template <typename T>
void TreeHelper<T>::logTreeInfo(const Tree* tree) {
LOGD("height: %d, leaf count: %d\n", getTreeHeight(tree->root()),
getBinaryTreeLeafCount(tree));
}
//---------------------- begin of new test ----------------------
BEGIN_TEST(BinaryTreeTest, CreateTreeLevelOrder, @@);
return;
pcln("only a root node");
BinaryTree<int> tree(new BinaryTreeNode<int>(1000));
TreeHelper<int>::printBinaryTree(tree.root(), 0);
TreeHelper<int>::releaseBinaryTree(&tree);
pcln("bigger tree");
std::vector<int> nodesInLevelOrder{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
std::shared_ptr<BinaryTree<int>> pTree(TreeHelper<int>::createBinaryTreeUsingLevelOrder(nodesInLevelOrder));
//auto pTree = TreeHelper<int>::createBinaryTreeUsingLevelOrder(nodesInLevelOrder);
TreeHelper<int>::printBinaryTree(pTree->root(), 0);
cr;
// add 10 to every node's value
TreeHelper<int>::changeBinaryTree(pTree.get(), [](BinaryTreeNode<int>* & node) {
node->setValue(node->value() + 10);
});
TreeHelper<int>::printBinaryTree(pTree->root(), 0);
psln(TreeHelper<int>::getBinaryTreeLeafCount(pTree.get()));
psln(TreeHelper<int>::getTreeHeight(pTree->root()));
// copy tree.
std::shared_ptr<BinaryTree<int>> copy(TreeHelper<int>::copyTree(pTree.get()));
EXPECT_TRUE(copy != nullptr);
TreeHelper<int>::releaseBinaryTree(pTree.get());
EXPECT_EQ(0, TreeHelper<int>::getBinaryTreeLeafCount(pTree.get()));
EXPECT_EQ(0, TreeHelper<int>::getTreeHeight(pTree->root()));
EXPECT_EQ(nullptr, pTree->root());
// shared_ptr auto delete.
//delete pTree;
// pTree is dead.
// now the copy tree is still alive.
psln(TreeHelper<int>::getBinaryTreeLeafCount(copy.get()));
psln(TreeHelper<int>::getTreeHeight(copy->root()));
TreeHelper<int>::printBinaryTree(copy->root(), 0);
TreeHelper<int>::releaseBinaryTree(copy.get());
EXPECT_EQ(0, TreeHelper<int>::getBinaryTreeLeafCount(copy.get()));
EXPECT_EQ(0, TreeHelper<int>::getTreeHeight(copy->root()));
EXPECT_EQ(nullptr, copy->root());
//delete copy;
END_TEST;
//---------------------- begin of new test ----------------------
BEGIN_TEST(BinaryTreeTest, CreateTreePreInOrder, @@);
return;
std::vector<char> preOrder{ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I' };
std::vector<char> inOrder{ 'B', 'C', 'A', 'E', 'D', 'G', 'H', 'F', 'I' };
// create tree using preOrder and inOrder sequences.
BinaryTree<char> * tree = TreeHelper<char>::createBinaryTreeUsingPreAndInOrder(preOrder, inOrder);
pln("original input preOrder nodes:");
printArrayLikeContainer(preOrder);
auto printFunc = [](const BinaryTreeNode<char>* node) { p(node->value()); };
pln("use tree's preOrder iteration");
tree->preOrder(printFunc);
pln("\nand the non recursive version");
tree->preOrderNonRecursive(printFunc);
cr;
pln("original input inOrder nodes:");
printContainerNormally(inOrder);
pln("use tree's inOrder iteration");
tree->inOrder(printFunc);
pln("\nand the non recursive version");
tree->inOrderNonRecursive(printFunc);
cr;
pln("use tree's postOrder iteration");
tree->postOrder(printFunc);
cr;
pcln("Tree Construct Result:");
TreeHelper<char>::logTreeInfo(tree);
TreeHelper<char>::printBinaryTree(tree->root(), 0);
cr;
TreeHelper<char>::releaseBinaryTree(tree);
EXPECT_EQ(nullptr, tree->root());
EXPECT_EQ(0, TreeHelper<char>::getBinaryTreeLeafCount(tree));
EXPECT_EQ(0, TreeHelper<char>::getTreeHeight(tree->root()));
delete tree;
END_TEST;
NS_END(elloop) | [
"[email protected]"
] | |
608de55c2610d715a64495091b3a20300a75907a | 3c9d64d2af8cf3d5b83c7393b4ddfeba468a94f7 | /third/blobs/blob.h | 933fda8b69b26c9ca70ef86081eb38fa443b90ee | [] | no_license | kod3r/cv | 0ff9f31b9b926a6f61f7e422bc69f0303a8a2de4 | 9e769c90693005b76c8a7d5305002a1feb07f096 | refs/heads/master | 2021-01-18T10:55:32.764921 | 2009-08-10T17:32:19 | 2009-08-10T17:32:19 | null | 0 | 0 | null | null | null | null | ISO-8859-2 | C++ | false | false | 4,484 | h | /************************************************************************
Blob.h
FUNCIONALITAT: Definició de la classe CBlob
AUTOR: Inspecta S.L.
MODIFICACIONS (Modificació, Autor, Data):
FUNCTIONALITY: Definition of the CBlob class and some helper classes to perform
some calculations on it
AUTHOR: Inspecta S.L.
MODIFICATIONS (Modification, Author, Date):
**************************************************************************/
//! Disable warnings referred to 255 character truncation for the std:map
//#pragma warning( disable : 4786 )
#ifndef CBLOB_INSPECTA_INCLUDED
#define CBLOB_INSPECTA_INCLUDED
#include <opencv/cxcore.h>
//#include "BlobLibraryConfiguration.h"
#include "blob_contour.h"
#ifdef BLOB_OBJECT_FACTORY
//! Object factory pattern implementation
#include "..\inspecta\DesignPatterns\ObjectFactory.h"
#endif
//! Type of labelled images
typedef unsigned int t_labelType;
//! Blob class
class CBlob
{
typedef std::list<CBlobContour> t_contourList;
public:
CBlob();
CBlob( t_labelType id, CvPoint startPoint, CvSize originalImageSize );
~CBlob();
//! Copy constructor
CBlob( const CBlob &src );
CBlob( const CBlob *src );
//! Operador d'assignació
//! Assigment operator
CBlob& operator=(const CBlob &src );
//! Adds a new internal contour to the blob
void AddInternalContour( const CBlobContour &newContour );
//! Retrieves contour in Freeman's chain code
CBlobContour *GetExternalContour()
{
return &m_externalContour;
}
//! Retrieves blob storage
CvMemStorage *GetStorage()
{
return m_storage;
}
//! Get label ID
t_labelType GetID()
{
return m_id;
}
//! > 0 for extern blobs, 0 if not
int Exterior( IplImage *mask, bool xBorder = true, bool yBorder = true );
//! Compute blob's area
double Area();
//! Compute blob's perimeter
double Perimeter();
//! Compute blob's moment (p,q up to MAX_CALCULATED_MOMENTS)
double Moment(int p, int q);
//! Compute extern perimeter
double ExternPerimeter( IplImage *mask, bool xBorder = true, bool yBorder = true );
//! Get mean grey color
double Mean( IplImage *image );
//! Get standard deviation grey color
double StdDev( IplImage *image );
//! Indica si el blob estŕ buit ( no té cap info associada )
//! Shows if the blob has associated information
bool IsEmpty();
//! Retorna el poligon convex del blob
//! Calculates the convex hull of the blob
t_PointList GetConvexHull();
//! Pinta l'interior d'un blob d'un color determinat
//! Paints the blob in an image
void FillBlob( IplImage *imatge, CvScalar color, int offsetX = 0, int offsetY = 0 );
//! Join a blob to current one (add's contour
void JoinBlob( CBlob *blob );
//! Get bounding box
CvRect GetBoundingBox();
//! Get bounding ellipse
CvBox2D GetEllipse();
//! Minimun X
double MinX()
{
return GetBoundingBox().x;
}
//! Minimun Y
double MinY()
{
return GetBoundingBox().y;
}
//! Maximun X
double MaxX()
{
return GetBoundingBox().x + GetBoundingBox().width;
}
//! Maximun Y
double MaxY()
{
return GetBoundingBox().y + GetBoundingBox().height;
}
private:
//! Deallocates all contours
void ClearContours();
//////////////////////////////////////////////////////////////////////////
// Blob contours
//////////////////////////////////////////////////////////////////////////
//! Contour storage memory
CvMemStorage *m_storage;
//! External contour of the blob (crack codes)
CBlobContour m_externalContour;
//! Internal contours (crack codes)
t_contourList m_internalContours;
//////////////////////////////////////////////////////////////////////////
// Blob features
//////////////////////////////////////////////////////////////////////////
//! Label number
t_labelType m_id;
//! Area
double m_area;
//! Perimeter
double m_perimeter;
//! Extern perimeter from blob
double m_externPerimeter;
//! Mean gray color
double m_meanGray;
//! Standard deviation from gray color blob distribution
double m_stdDevGray;
//! Bounding box
CvRect m_boundingBox;
//! Bounding ellipse
CvBox2D m_ellipse;
//! Sizes from image where blob is extracted
CvSize m_originalImageSize;
};
#endif //CBLOB_INSPECTA_INCLUDED
| [
"[email protected]"
] | |
ffead13a3f6d0e130f143c10b031969c55c4e789 | 26ad4cc35496d364b31396e43a863aee08ef2636 | /SDK/SoT_BP_msc_hurdygurdy_skl_01_a_ItemDesc_functions.cpp | 08094d652c86cb3003ee35890084da9cca9e44cd | [] | no_license | cw100/SoT-SDK | ddb9b19ce6ae623299b2b02dee51c29581537ba1 | 3e6f12384c8e21ed83ef56f00030ca0506d297fb | refs/heads/master | 2020-05-05T12:09:55.938323 | 2019-03-20T14:11:57 | 2019-03-20T14:11:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 372 | cpp | // Sea of Thieves (1.4) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "SoT_BP_msc_hurdygurdy_skl_01_a_ItemDesc_classes.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Functions
//---------------------------------------------------------------------------
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"[email protected]"
] | |
391bfad28e6b5a890680a62696015619a3af45a3 | 5e0422794380a8f3bf06d0c37ac2354f4b91fefb | /cheat/test_any.h | 3258790a0599fc236dfbf7507175b4c43241cd9b | [] | no_license | OrAlien/fastnetwork | 1d8fb757b855b1f23cc844cda4d8dc7a568bc38e | 792d28d8b5829c227aebe8378f60db17de4d6f14 | refs/heads/master | 2021-05-28T20:30:24.031458 | 2010-06-02T14:30:04 | 2010-06-02T14:30:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,274 | h | #pragma once
#include "test_fixture.h"
#include <boost/any.hpp>
using namespace boost;
class test_any :
public test_fixture
{
public:
test_any(void);
~test_any(void);
public:
void test() {
string_copy s( "abc" );
string_copy & r = s;
cout << "s addr: " << &s << endl;
cout << "r addr: " << &r << endl;
cout << "to any." << endl;
any a = &s;
cout << "changing..." << endl;
s.set( "def" );
any b = a;
try {
string_copy * c = any_cast<string_copy*>( b );
cout << "c addr: " << c << endl;
cout << c->get() << " has been casted." << endl;
cout << "source is: " << s.get() << endl;
} catch( const bad_any_cast & ) {
cerr << "any cast failed." << endl;
}
}
private:
class string_copy {
public:
string_copy( const string & s ) {
cout << "construct" << endl;
set( s );
}
string_copy( const string_copy & r ) {
cout << "copy" << endl;
set( r.s );
}
void set( const string & s ) {
cout << "change" << endl;
this->s = s;
}
string_copy & operator=( const string_copy& rhs ) {
cout << "assign" << endl;
set( rhs.s );
return *this;
}
const string & get() const {
return s;
}
private:
string s;
};
};
| [
"everwanna@8b0bd7a0-72c1-11de-90d8-1fdda9445408"
] | everwanna@8b0bd7a0-72c1-11de-90d8-1fdda9445408 |
7dc242f8679f894efebc6669a9a0e03f252c4cac | 1d928c3f90d4a0a9a3919a804597aa0a4aab19a3 | /c++/JUCE/2017/4/juce_OpenGL_win32.h | 77f747b25cc2e1cd910d0db72c5968b0bae9a978 | [] | no_license | rosoareslv/SED99 | d8b2ff5811e7f0ffc59be066a5a0349a92cbb845 | a062c118f12b93172e31e8ca115ce3f871b64461 | refs/heads/main | 2023-02-22T21:59:02.703005 | 2021-01-28T19:40:51 | 2021-01-28T19:40:51 | 306,497,459 | 1 | 1 | null | 2020-11-24T20:56:18 | 2020-10-23T01:18:07 | null | UTF-8 | C++ | false | false | 10,802 | h | /*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2017 - ROLI Ltd.
JUCE is an open source library subject to commercial or open-source
licensing.
By using JUCE, you agree to the terms of both the JUCE 5 End-User License
Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
27th April 2017).
End User License Agreement: www.juce.com/juce-5-licence
Privacy Policy: www.juce.com/juce-5-privacy-policy
Or: You may also use this code under the terms of the GPL v3 (see
www.gnu.org/licenses).
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
DISCLAIMED.
==============================================================================
*/
extern ComponentPeer* createNonRepaintingEmbeddedWindowsPeer (Component&, void* parent);
//==============================================================================
class OpenGLContext::NativeContext
{
public:
NativeContext (Component& component,
const OpenGLPixelFormat& pixelFormat,
void* contextToShareWith,
bool /*useMultisampling*/,
OpenGLVersion)
: context (nullptr)
{
dummyComponent = new DummyComponent (*this);
createNativeWindow (component);
PIXELFORMATDESCRIPTOR pfd;
initialisePixelFormatDescriptor (pfd, pixelFormat);
const int pixFormat = ChoosePixelFormat (dc, &pfd);
if (pixFormat != 0)
SetPixelFormat (dc, pixFormat, &pfd);
renderContext = wglCreateContext (dc);
if (renderContext != 0)
{
makeActive();
initialiseGLExtensions();
const int wglFormat = wglChoosePixelFormatExtension (pixelFormat);
deactivateCurrentContext();
if (wglFormat != pixFormat && wglFormat != 0)
{
// can't change the pixel format of a window, so need to delete the
// old one and create a new one..
releaseDC();
nativeWindow = nullptr;
createNativeWindow (component);
if (SetPixelFormat (dc, wglFormat, &pfd))
{
deleteRenderContext();
renderContext = wglCreateContext (dc);
}
}
if (contextToShareWith != nullptr)
wglShareLists ((HGLRC) contextToShareWith, renderContext);
component.getTopLevelComponent()->repaint();
component.repaint();
}
}
~NativeContext()
{
deleteRenderContext();
releaseDC();
}
void initialiseOnRenderThread (OpenGLContext& c) { context = &c; }
void shutdownOnRenderThread() { deactivateCurrentContext(); context = nullptr; }
static void deactivateCurrentContext() { wglMakeCurrent (0, 0); }
bool makeActive() const noexcept { return isActive() || wglMakeCurrent (dc, renderContext) != FALSE; }
bool isActive() const noexcept { return wglGetCurrentContext() == renderContext; }
void swapBuffers() const noexcept { SwapBuffers (dc); }
bool setSwapInterval (int numFramesPerSwap)
{
jassert (isActive()); // this can only be called when the context is active..
return wglSwapIntervalEXT != nullptr && wglSwapIntervalEXT (numFramesPerSwap) != FALSE;
}
int getSwapInterval() const
{
jassert (isActive()); // this can only be called when the context is active..
return wglGetSwapIntervalEXT != nullptr ? wglGetSwapIntervalEXT() : 0;
}
void updateWindowPosition (const Rectangle<int>& bounds)
{
if (nativeWindow != nullptr)
SetWindowPos ((HWND) nativeWindow->getNativeHandle(), 0,
bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight(),
SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
}
bool createdOk() const noexcept { return getRawContext() != nullptr; }
void* getRawContext() const noexcept { return renderContext; }
unsigned int getFrameBufferID() const noexcept { return 0; }
void triggerRepaint()
{
if (context != nullptr)
context->triggerRepaint();
}
struct Locker { Locker (NativeContext&) {} };
private:
struct DummyComponent : public Component
{
DummyComponent (NativeContext& c) : context (c) {}
// The windowing code will call this when a paint callback happens
void handleCommandMessage (int) override { context.triggerRepaint(); }
NativeContext& context;
};
ScopedPointer<DummyComponent> dummyComponent;
ScopedPointer<ComponentPeer> nativeWindow;
HGLRC renderContext;
HDC dc;
OpenGLContext* context;
#define JUCE_DECLARE_WGL_EXTENSION_FUNCTION(name, returnType, params) \
typedef returnType (__stdcall *type_ ## name) params; type_ ## name name;
JUCE_DECLARE_WGL_EXTENSION_FUNCTION (wglChoosePixelFormatARB, BOOL, (HDC, const int*, const FLOAT*, UINT, int*, UINT*))
JUCE_DECLARE_WGL_EXTENSION_FUNCTION (wglSwapIntervalEXT, BOOL, (int))
JUCE_DECLARE_WGL_EXTENSION_FUNCTION (wglGetSwapIntervalEXT, int, ())
#undef JUCE_DECLARE_WGL_EXTENSION_FUNCTION
void initialiseGLExtensions()
{
#define JUCE_INIT_WGL_FUNCTION(name) name = (type_ ## name) OpenGLHelpers::getExtensionFunction (#name);
JUCE_INIT_WGL_FUNCTION (wglChoosePixelFormatARB);
JUCE_INIT_WGL_FUNCTION (wglSwapIntervalEXT);
JUCE_INIT_WGL_FUNCTION (wglGetSwapIntervalEXT);
#undef JUCE_INIT_WGL_FUNCTION
}
void createNativeWindow (Component& component)
{
Component* topComp = component.getTopLevelComponent();
nativeWindow = createNonRepaintingEmbeddedWindowsPeer (*dummyComponent, topComp->getWindowHandle());
if (ComponentPeer* peer = topComp->getPeer())
updateWindowPosition (peer->getAreaCoveredBy (component));
nativeWindow->setVisible (true);
dc = GetDC ((HWND) nativeWindow->getNativeHandle());
}
void deleteRenderContext()
{
if (renderContext != 0)
{
wglDeleteContext (renderContext);
renderContext = 0;
}
}
void releaseDC()
{
ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
}
static void initialisePixelFormatDescriptor (PIXELFORMATDESCRIPTOR& pfd, const OpenGLPixelFormat& pixelFormat)
{
zerostruct (pfd);
pfd.nSize = sizeof (pfd);
pfd.nVersion = 1;
pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.iLayerType = PFD_MAIN_PLANE;
pfd.cColorBits = (BYTE) (pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits);
pfd.cRedBits = (BYTE) pixelFormat.redBits;
pfd.cGreenBits = (BYTE) pixelFormat.greenBits;
pfd.cBlueBits = (BYTE) pixelFormat.blueBits;
pfd.cAlphaBits = (BYTE) pixelFormat.alphaBits;
pfd.cDepthBits = (BYTE) pixelFormat.depthBufferBits;
pfd.cStencilBits = (BYTE) pixelFormat.stencilBufferBits;
pfd.cAccumBits = (BYTE) (pixelFormat.accumulationBufferRedBits + pixelFormat.accumulationBufferGreenBits
+ pixelFormat.accumulationBufferBlueBits + pixelFormat.accumulationBufferAlphaBits);
pfd.cAccumRedBits = (BYTE) pixelFormat.accumulationBufferRedBits;
pfd.cAccumGreenBits = (BYTE) pixelFormat.accumulationBufferGreenBits;
pfd.cAccumBlueBits = (BYTE) pixelFormat.accumulationBufferBlueBits;
pfd.cAccumAlphaBits = (BYTE) pixelFormat.accumulationBufferAlphaBits;
}
int wglChoosePixelFormatExtension (const OpenGLPixelFormat& pixelFormat) const
{
int format = 0;
if (wglChoosePixelFormatARB != nullptr)
{
int atts[64];
int n = 0;
atts[n++] = WGL_DRAW_TO_WINDOW_ARB; atts[n++] = GL_TRUE;
atts[n++] = WGL_SUPPORT_OPENGL_ARB; atts[n++] = GL_TRUE;
atts[n++] = WGL_DOUBLE_BUFFER_ARB; atts[n++] = GL_TRUE;
atts[n++] = WGL_PIXEL_TYPE_ARB; atts[n++] = WGL_TYPE_RGBA_ARB;
atts[n++] = WGL_ACCELERATION_ARB;
atts[n++] = WGL_FULL_ACCELERATION_ARB;
atts[n++] = WGL_COLOR_BITS_ARB; atts[n++] = pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits;
atts[n++] = WGL_RED_BITS_ARB; atts[n++] = pixelFormat.redBits;
atts[n++] = WGL_GREEN_BITS_ARB; atts[n++] = pixelFormat.greenBits;
atts[n++] = WGL_BLUE_BITS_ARB; atts[n++] = pixelFormat.blueBits;
atts[n++] = WGL_ALPHA_BITS_ARB; atts[n++] = pixelFormat.alphaBits;
atts[n++] = WGL_DEPTH_BITS_ARB; atts[n++] = pixelFormat.depthBufferBits;
atts[n++] = WGL_STENCIL_BITS_ARB; atts[n++] = pixelFormat.stencilBufferBits;
atts[n++] = WGL_ACCUM_RED_BITS_ARB; atts[n++] = pixelFormat.accumulationBufferRedBits;
atts[n++] = WGL_ACCUM_GREEN_BITS_ARB; atts[n++] = pixelFormat.accumulationBufferGreenBits;
atts[n++] = WGL_ACCUM_BLUE_BITS_ARB; atts[n++] = pixelFormat.accumulationBufferBlueBits;
atts[n++] = WGL_ACCUM_ALPHA_BITS_ARB; atts[n++] = pixelFormat.accumulationBufferAlphaBits;
if (pixelFormat.multisamplingLevel > 0
&& OpenGLHelpers::isExtensionSupported ("GL_ARB_multisample"))
{
atts[n++] = WGL_SAMPLE_BUFFERS_ARB;
atts[n++] = 1;
atts[n++] = WGL_SAMPLES_ARB;
atts[n++] = pixelFormat.multisamplingLevel;
}
atts[n++] = 0;
jassert (n <= numElementsInArray (atts));
UINT formatsCount = 0;
wglChoosePixelFormatARB (dc, atts, nullptr, 1, &format, &formatsCount);
}
return format;
}
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NativeContext)
};
//==============================================================================
bool OpenGLHelpers::isContextActive()
{
return wglGetCurrentContext() != 0;
}
| [
"[email protected]"
] | |
64833a6b1bcf6707a1eaffa1df0aeac5ac76ec2e | 1f11cdf6c6432c4d997b82c8cd8bc6b210e3a5f6 | /MAXSUMSU/Thao-Solved/maxsumsu.cpp | f9bce96627d01477a6d001f74cb94c3304e78afc | [] | no_license | BUW-Comp-Prog-Project/WS_19 | 6cb394bb838e5acc66f0ac40e22f591a23163b9a | c8eba3f5276ae479784756a94f6828ddb2dfcf0d | refs/heads/master | 2020-09-04T11:40:30.235164 | 2020-04-23T19:41:43 | 2020-04-23T19:41:43 | 219,722,585 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 599 | cpp | #include <iostream>
#include <string.h>
#include <limits>
#define ll long long
using namespace std;
ll inf = numeric_limits<long int>::min();
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
ll cases;
cin >> cases;
while (cases--)
{
ll n;
cin >> n;
ll seq[n], mem[n];
ll max_sum = inf;
mem[0] = 0;
for (ll i=0; i<n; i++)
{
cin >> seq[i];
if (i == 0)
{
mem[i] = seq[i];
}
else
{
mem[i] = max(seq[i], seq[i] + mem[i-1]);
}
if (max_sum < mem[i])
{
max_sum = mem[i];
}
}
cout << max_sum << "\n";
}
return 0;
}
| [
"[email protected]"
] | |
968897c08dc37db3b1d6cf95b26c0c84fbe91c06 | b55c605606c5085078b0cabde489e6b281025ab8 | /app/src/main/jni/jnilibsvm/libsvm/svm-predict.cpp | 4f9af2ce028f96b2bd1cdc200f0d7f0514d9daab | [
"BSD-3-Clause"
] | permissive | TangWeicheng/facerecognizer-master | ce1c5b6432e668fe089b699fbc6a30d727735991 | a9374c8d0f60f0e5520a2b99f2e4feec8abdcce5 | refs/heads/master | 2020-03-21T15:04:59.299957 | 2018-06-26T06:29:45 | 2018-06-26T06:29:45 | 138,693,443 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,553 | cpp | #include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include "../common.h"
#include "svm-predict.h"
#include "svm.h"
namespace svmpredict {
int print_null(const char *s,...) {return 0;}
//static int (*info)(const char *fmt,...) = &printf;
//static void (*info)(const char *fmt,...) = &debug;
struct svm_node *x;
int max_nr_attr = 64;
struct svm_model* model;
int predict_probability=0;
static char *line = NULL;
static int max_line_len;
static char* readline(FILE *input)
{
int len;
if(fgets(line,max_line_len,input) == NULL)
return NULL;
while(strrchr(line,'\n') == NULL)
{
max_line_len *= 2;
line = (char *) realloc(line,max_line_len);
len = (int) strlen(line);
if(fgets(line+len,max_line_len-len,input) == NULL)
break;
}
return line;
}
void exit_input_error(int line_num)
{
debug("Wrong input format at line %d\n", line_num);
exit(1);
}
void predict(float *input, int len, int *index, double *prob)
{
int svm_type=svm_get_svm_type(model);
int nr_class=svm_get_nr_class(model);
double *prob_estimates=NULL;
int j;
if(predict_probability)
{
if (svm_type==NU_SVR || svm_type==EPSILON_SVR)
debug("Prob. model for test data: target value = predicted value + z,\nz: Laplace distribution e^(-|z|/sigma)/(2sigma),sigma=%g\n",svm_get_svr_probability(model));
else
{
prob_estimates = (double *) malloc(nr_class*sizeof(double));
}
}
x = (struct svm_node *) malloc((len+1)*sizeof(struct svm_node));
for (int i = 0; i < len; i++) {
x[i].index = i;
x[i].value = input[i];
}
x[len].index = -1;
double predict_label;
if (predict_probability && (svm_type==C_SVC || svm_type==NU_SVC))
{
predict_label = svm_predict_probability(model,x,prob_estimates);
*index = (int) predict_label;
*prob = prob_estimates[*index];
}
else
{
predict_label = svm_predict(model,x);
*index = (int) predict_label;
*prob = 0.0;
}
if(predict_probability)
free(prob_estimates);
}
void exit_with_help()
{
debug(
"Usage: svm-predict [options] test_file model_file output_file\n"
"options:\n"
"-b probability_estimates: whether to predict probability estimates, 0 or 1 (default 0); for one-class SVM only 0 is supported\n"
"-q : quiet mode (no outputs)\n"
);
exit(1);
}
int main(int argc, char **argv, float *input, int len, int *index, double *prob)
{
int i;
// parse options
for(i=1;i<argc;i++)
{
if(argv[i][0] != '-') break;
++i;
switch(argv[i-1][1])
{
case 'b':
predict_probability = atoi(argv[i]);
break;
case 'q':
//info = &print_null;
i--;
break;
default:
debug("Unknown option: -%c\n", argv[i-1][1]);
exit_with_help();
}
}
if(i>=argc)
exit_with_help();
if((model=svm_load_model(argv[i]))==0)
{
debug("can't open model file %s\n",argv[i]);
exit(1);
}
x = (struct svm_node *) malloc(max_nr_attr*sizeof(struct svm_node));
if(predict_probability)
{
if(svm_check_probability_model(model)==0)
{
debug("Model does not support probabiliy estimates\n");
exit(1);
}
}
else
{
if(svm_check_probability_model(model)!=0)
debug("Model supports probability estimates, but disabled in prediction.\n");
}
predict(input,len,index,prob);
svm_free_and_destroy_model(&model);
free(x);
free(line);
return 0;
}
}
| [
"[email protected]"
] | |
d289a98c42184370b79c8fe9fddc5c5431a4403c | 2ba94892764a44d9c07f0f549f79f9f9dc272151 | /Engine/Source/Runtime/Core/Private/Math/Color.cpp | d8747f31902c2506eedb4e85d7928f86b45b951c | [
"BSD-2-Clause",
"LicenseRef-scancode-proprietary-license"
] | permissive | PopCap/GameIdea | 934769eeb91f9637f5bf205d88b13ff1fc9ae8fd | 201e1df50b2bc99afc079ce326aa0a44b178a391 | refs/heads/master | 2021-01-25T00:11:38.709772 | 2018-09-11T03:38:56 | 2018-09-11T03:38:56 | 37,818,708 | 0 | 0 | BSD-2-Clause | 2018-09-11T03:39:05 | 2015-06-21T17:36:44 | null | UTF-8 | C++ | false | false | 21,893 | cpp | // Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
/*=============================================================================
Color.cpp: Unreal color implementation.
=============================================================================*/
#include "CorePrivatePCH.h"
// Common colors.
const FLinearColor FLinearColor::White(1.f,1.f,1.f);
const FLinearColor FLinearColor::Gray(0.5f,0.5f,0.5f);
const FLinearColor FLinearColor::Black(0,0,0);
const FLinearColor FLinearColor::Transparent(0,0,0,0);
const FLinearColor FLinearColor::Red(1.f,0,0);
const FLinearColor FLinearColor::Green(0,1.f,0);
const FLinearColor FLinearColor::Blue(0,0,1.f);
const FLinearColor FLinearColor::Yellow(1.f,1.f,0);
const FColor FColor::White(255,255,255);
const FColor FColor::Black(0,0,0);
const FColor FColor::Transparent(0, 0, 0, 0);
const FColor FColor::Red(255,0,0);
const FColor FColor::Green(0,255,0);
const FColor FColor::Blue(0,0,255);
const FColor FColor::Yellow(255,255,0);
const FColor FColor::Cyan(0,255,255);
const FColor FColor::Magenta(255,0,255);
/**
* Helper used by FColor -> FLinearColor conversion. We don't use a lookup table as unlike pow, multiplication is fast.
*/
static const float OneOver255 = 1.0f / 255.0f;
// FColor->FLinearColor conversion.
FLinearColor::FLinearColor(const FColor& Color)
{
R = sRGBToLinearTable[Color.R];
G = sRGBToLinearTable[Color.G];
B = sRGBToLinearTable[Color.B];
A = float(Color.A) * OneOver255;
}
FLinearColor::FLinearColor(const FVector& Vector) :
R(Vector.X),
G(Vector.Y),
B(Vector.Z),
A(1.0f)
{}
FLinearColor::FLinearColor(const FFloat16Color& C)
{
R = C.R.GetFloat();
G = C.G.GetFloat();
B = C.B.GetFloat();
A = C.A.GetFloat();
}
FLinearColor FLinearColor::FromSRGBColor(const FColor& Color)
{
FLinearColor LinearColor;
LinearColor.R = sRGBToLinearTable[Color.R];
LinearColor.G = sRGBToLinearTable[Color.G];
LinearColor.B = sRGBToLinearTable[Color.B];
LinearColor.A = float(Color.A) * OneOver255;
return LinearColor;
}
FLinearColor FLinearColor::FromPow22Color(const FColor& Color)
{
FLinearColor LinearColor;
LinearColor.R = Pow22OneOver255Table[Color.R];
LinearColor.G = Pow22OneOver255Table[Color.G];
LinearColor.B = Pow22OneOver255Table[Color.B];
LinearColor.A = float(Color.A) * OneOver255;
return LinearColor;
}
// Convert from float to RGBE as outlined in Gregory Ward's Real Pixels article, Graphics Gems II, page 80.
FColor FLinearColor::ToRGBE() const
{
const float Primary = FMath::Max3( R, G, B );
FColor Color;
if( Primary < 1E-32 )
{
Color = FColor(0,0,0,0);
}
else
{
int32 Exponent;
const float Scale = frexp(Primary, &Exponent) / Primary * 255.f;
Color.R = FMath::Clamp(FMath::TruncToInt(R * Scale), 0, 255);
Color.G = FMath::Clamp(FMath::TruncToInt(G * Scale), 0, 255);
Color.B = FMath::Clamp(FMath::TruncToInt(B * Scale), 0, 255);
Color.A = FMath::Clamp(FMath::TruncToInt(Exponent),-128,127) + 128;
}
return Color;
}
/** Quantizes the linear color and returns the result as a FColor with optional sRGB conversion and quality as goal. */
FColor FLinearColor::ToFColor(const bool bSRGB) const
{
float FloatR = FMath::Clamp(R, 0.0f, 1.0f);
float FloatG = FMath::Clamp(G, 0.0f, 1.0f);
float FloatB = FMath::Clamp(B, 0.0f, 1.0f);
float FloatA = FMath::Clamp(A, 0.0f, 1.0f);
if(bSRGB)
{
FloatR = FloatR <= 0.0031308f ? FloatR * 12.92f : FMath::Pow( FloatR, 1.0f / 2.4f ) * 1.055f - 0.055f;
FloatG = FloatG <= 0.0031308f ? FloatG * 12.92f : FMath::Pow( FloatG, 1.0f / 2.4f ) * 1.055f - 0.055f;
FloatB = FloatB <= 0.0031308f ? FloatB * 12.92f : FMath::Pow( FloatB, 1.0f / 2.4f ) * 1.055f - 0.055f;
}
FColor ret;
ret.A = FMath::FloorToInt(FloatA * 255.999f);
ret.R = FMath::FloorToInt(FloatR * 255.999f);
ret.G = FMath::FloorToInt(FloatG * 255.999f);
ret.B = FMath::FloorToInt(FloatB * 255.999f);
return ret;
}
FColor FLinearColor::Quantize() const
{
return FColor(
(uint8)FMath::Clamp<int32>(FMath::TruncToInt(R*255.f),0,255),
(uint8)FMath::Clamp<int32>(FMath::TruncToInt(G*255.f),0,255),
(uint8)FMath::Clamp<int32>(FMath::TruncToInt(B*255.f),0,255),
(uint8)FMath::Clamp<int32>(FMath::TruncToInt(A*255.f),0,255)
);
}
/**
* Returns a desaturated color, with 0 meaning no desaturation and 1 == full desaturation
*
* @param Desaturation Desaturation factor in range [0..1]
* @return Desaturated color
*/
FLinearColor FLinearColor::Desaturate( float Desaturation ) const
{
float Lum = ComputeLuminance();
return FMath::Lerp( *this, FLinearColor( Lum, Lum, Lum, 0 ), Desaturation );
}
/** Computes the perceptually weighted luminance value of a color. */
float FLinearColor::ComputeLuminance() const
{
return R * 0.3f + G * 0.59f + B * 0.11f;
}
FColor FColor::FromHex( const FString& HexString )
{
int32 StartIndex = (!HexString.IsEmpty() && HexString[0] == TCHAR('#')) ? 1 : 0;
if (HexString.Len() == 3 + StartIndex)
{
const int32 R = FParse::HexDigit(HexString[StartIndex++]);
const int32 G = FParse::HexDigit(HexString[StartIndex++]);
const int32 B = FParse::HexDigit(HexString[StartIndex]);
return FColor((R << 4) + R, (G << 4) + G, (B << 4) + B, 255);
}
if (HexString.Len() == 6 + StartIndex)
{
FColor Result;
Result.R = (FParse::HexDigit(HexString[StartIndex+0]) << 4) + FParse::HexDigit(HexString[StartIndex+1]);
Result.G = (FParse::HexDigit(HexString[StartIndex+2]) << 4) + FParse::HexDigit(HexString[StartIndex+3]);
Result.B = (FParse::HexDigit(HexString[StartIndex+4]) << 4) + FParse::HexDigit(HexString[StartIndex+5]);
Result.A = 255;
return Result;
}
if (HexString.Len() == 8 + StartIndex)
{
FColor Result;
Result.R = (FParse::HexDigit(HexString[StartIndex+0]) << 4) + FParse::HexDigit(HexString[StartIndex+1]);
Result.G = (FParse::HexDigit(HexString[StartIndex+2]) << 4) + FParse::HexDigit(HexString[StartIndex+3]);
Result.B = (FParse::HexDigit(HexString[StartIndex+4]) << 4) + FParse::HexDigit(HexString[StartIndex+5]);
Result.A = (FParse::HexDigit(HexString[StartIndex+6]) << 4) + FParse::HexDigit(HexString[StartIndex+7]);
return Result;
}
return FColor(ForceInitToZero);
}
// Convert from RGBE to float as outlined in Gregory Ward's Real Pixels article, Graphics Gems II, page 80.
FLinearColor FColor::FromRGBE() const
{
if( A == 0 )
return FLinearColor::Black;
else
{
const float Scale = ldexp( 1 / 255.0, A - 128 );
return FLinearColor( R * Scale, G * Scale, B * Scale, 1.0f );
}
}
/**
* Converts byte hue-saturation-brightness to floating point red-green-blue.
*/
FLinearColor FLinearColor::FGetHSV( uint8 H, uint8 S, uint8 V )
{
float Brightness = V * 1.4f / 255.f;
Brightness *= 0.7f/(0.01f + FMath::Sqrt(Brightness));
Brightness = FMath::Clamp(Brightness,0.f,1.f);
const FVector Hue = (H<86) ? FVector((85-H)/85.f,(H-0)/85.f,0) : (H<171) ? FVector(0,(170-H)/85.f,(H-85)/85.f) : FVector((H-170)/85.f,0,(255-H)/84.f);
const FVector ColorVector = (Hue + S/255.f * (FVector(1,1,1) - Hue)) * Brightness;
return FLinearColor(ColorVector.X,ColorVector.Y,ColorVector.Z,1);
}
/** Converts a linear space RGB color to an HSV color */
FLinearColor FLinearColor::LinearRGBToHSV() const
{
const float RGBMin = FMath::Min3(R, G, B);
const float RGBMax = FMath::Max3(R, G, B);
const float RGBRange = RGBMax - RGBMin;
const float Hue = (RGBMax == RGBMin ? 0.0f :
RGBMax == R ? fmod((((G - B) / RGBRange) * 60.0f) + 360.0f, 360.0f) :
RGBMax == G ? (((B - R) / RGBRange) * 60.0f) + 120.0f :
RGBMax == B ? (((R - G) / RGBRange) * 60.0f) + 240.0f :
0.0f);
const float Saturation = (RGBMax == 0.0f ? 0.0f : RGBRange / RGBMax);
const float Value = RGBMax;
// In the new color, R = H, G = S, B = V, A = A
return FLinearColor(Hue, Saturation, Value, A);
}
/** Converts an HSV color to a linear space RGB color */
FLinearColor FLinearColor::HSVToLinearRGB() const
{
// In this color, R = H, G = S, B = V
const float Hue = R;
const float Saturation = G;
const float Value = B;
const float HDiv60 = Hue / 60.0f;
const float HDiv60_Floor = floorf(HDiv60);
const float HDiv60_Fraction = HDiv60 - HDiv60_Floor;
const float RGBValues[4] = {
Value,
Value * (1.0f - Saturation),
Value * (1.0f - (HDiv60_Fraction * Saturation)),
Value * (1.0f - ((1.0f - HDiv60_Fraction) * Saturation)),
};
const uint32 RGBSwizzle[6][3] = {
{0, 3, 1},
{2, 0, 1},
{1, 0, 3},
{1, 2, 0},
{3, 1, 0},
{0, 1, 2},
};
const uint32 SwizzleIndex = ((uint32)HDiv60_Floor) % 6;
return FLinearColor(RGBValues[RGBSwizzle[SwizzleIndex][0]],
RGBValues[RGBSwizzle[SwizzleIndex][1]],
RGBValues[RGBSwizzle[SwizzleIndex][2]],
A);
}
FLinearColor FLinearColor::LerpUsingHSV( const FLinearColor& From, const FLinearColor& To, const float Progress )
{
const FLinearColor FromHSV = From.LinearRGBToHSV();
const FLinearColor ToHSV = To.LinearRGBToHSV();
float FromHue = FromHSV.R;
float ToHue = ToHSV.R;
// Take the shortest path to the new hue
if( FMath::Abs( FromHue - ToHue ) > 180.0f )
{
if( ToHue > FromHue )
{
FromHue += 360.0f;
}
else
{
ToHue += 360.0f;
}
}
float NewHue = FMath::Lerp( FromHue, ToHue, Progress );
NewHue = FMath::Fmod( NewHue, 360.0f );
if( NewHue < 0.0f )
{
NewHue += 360.0f;
}
const float NewSaturation = FMath::Lerp( FromHSV.G, ToHSV.G, Progress );
const float NewValue = FMath::Lerp( FromHSV.B, ToHSV.B, Progress );
FLinearColor Interpolated = FLinearColor( NewHue, NewSaturation, NewValue ).HSVToLinearRGB();
const float NewAlpha = FMath::Lerp( From.A, To.A, Progress );
Interpolated.A = NewAlpha;
return Interpolated;
}
/**
* Makes a random but quite nice color.
*/
FLinearColor FLinearColor::MakeRandomColor()
{
const uint8 Hue = (uint8)(FMath::FRand()*255.f);
return FLinearColor::FGetHSV(Hue, 0, 255);
}
FColor FColor::MakeRandomColor()
{
return FLinearColor::MakeRandomColor().ToFColor(true);
}
FLinearColor FLinearColor::MakeFromColorTemperature( float Temp )
{
Temp = FMath::Clamp( Temp, 1000.0f, 15000.0f );
// Approximate Planckian locus in CIE 1960 UCS
float u = ( 0.860117757f + 1.54118254e-4f * Temp + 1.28641212e-7f * Temp*Temp ) / ( 1.0f + 8.42420235e-4f * Temp + 7.08145163e-7f * Temp*Temp );
float v = ( 0.317398726f + 4.22806245e-5f * Temp + 4.20481691e-8f * Temp*Temp ) / ( 1.0f - 2.89741816e-5f * Temp + 1.61456053e-7f * Temp*Temp );
float x = 3.0f * u / ( 2.0f * u - 8.0f * v + 4.0f );
float y = 2.0f * v / ( 2.0f * u - 8.0f * v + 4.0f );
float z = 1.0f - x - y;
float Y = 1.0f;
float X = Y/y * x;
float Z = Y/y * z;
// XYZ to RGB with BT.709 primaries
float R = 3.2404542f * X + -1.5371385f * Y + -0.4985314f * Z;
float G = -0.9692660f * X + 1.8760108f * Y + 0.0415560f * Z;
float B = 0.0556434f * X + -0.2040259f * Y + 1.0572252f * Z;
return FLinearColor(R,G,B);
}
FColor FColor::MakeFromColorTemperature( float Temp )
{
return FLinearColor::MakeFromColorTemperature( Temp ).ToFColor( true );
}
FColor FColor::MakeRedToGreenColorFromScalar(float Scalar)
{
float RedSclr = FMath::Clamp<float>((1.0f - Scalar)/0.5f,0.f,1.f);
float GreenSclr = FMath::Clamp<float>((Scalar/0.5f),0.f,1.f);
int32 R = FMath::TruncToInt(255 * RedSclr);
int32 G = FMath::TruncToInt(255 * GreenSclr);
int32 B = 0;
return FColor(R, G, B);
}
void ComputeAndFixedColorAndIntensity(const FLinearColor& InLinearColor,FColor& OutColor,float& OutIntensity)
{
float MaxComponent = FMath::Max(DELTA,FMath::Max(InLinearColor.R,FMath::Max(InLinearColor.G,InLinearColor.B)));
OutColor = ( InLinearColor / MaxComponent ).ToFColor(true);
OutIntensity = MaxComponent;
}
/**
* Pow table for fast FColor -> FLinearColor conversion.
*
* FMath::Pow( i / 255.f, 2.2f )
*/
float FLinearColor::Pow22OneOver255Table[256] =
{
0, 5.07705190066176E-06, 2.33280046660989E-05, 5.69217657121931E-05, 0.000107187362341244, 0.000175123977503027, 0.000261543754548491, 0.000367136269815943, 0.000492503787191433,
0.000638182842167022, 0.000804658499513058, 0.000992374304074325, 0.0012017395224384, 0.00143313458967186, 0.00168691531678928, 0.00196341621339647, 0.00226295316070643,
0.00258582559623417, 0.00293231832393836, 0.00330270303200364, 0.00369723957890013, 0.00411617709328275, 0.00455975492252602, 0.00502820345685554, 0.00552174485023966,
0.00604059365484981, 0.00658495738258168, 0.00715503700457303, 0.00775102739766061, 0.00837311774514858, 0.00902149189801213, 0.00969632870165823, 0.0103978022925553,
0.0111260823683832, 0.0118813344348137, 0.0126637200315821, 0.0134733969401426, 0.0143105193748841, 0.0151752381596252, 0.0160677008908869, 0.01698805208925, 0.0179364333399502,
0.0189129834237215, 0.0199178384387857, 0.0209511319147811, 0.0220129949193365, 0.0231035561579214, 0.0242229420675342, 0.0253712769047346, 0.0265486828284729, 0.027755279978126,
0.0289911865471078, 0.0302565188523887, 0.0315513914002264, 0.0328759169483838, 0.034230206565082, 0.0356143696849188, 0.0370285141619602, 0.0384727463201946, 0.0399471710015256,
0.0414518916114625, 0.0429870101626571, 0.0445526273164214, 0.0461488424223509, 0.0477757535561706, 0.049433457555908, 0.0511220500564934, 0.052841625522879, 0.0545922772817603,
0.0563740975519798, 0.0581871774736854, 0.0600316071363132, 0.0619074756054558, 0.0638148709486772, 0.0657538802603301, 0.0677245896854243, 0.0697270844425988, 0.0717614488462391,
0.0738277663277846, 0.0759261194562648, 0.0780565899581019, 0.080219258736215, 0.0824142058884592, 0.0846415107254295, 0.0869012517876603, 0.0891935068622478, 0.0915183529989195,
0.0938758665255778, 0.0962661230633397, 0.0986891975410945, 0.1011451642096, 0.103634096655137, 0.106156067812744, 0.108711149979039, 0.11129941482466, 0.113920933406333,
0.116575776178572, 0.119264013005047, 0.121985713169619, 0.124740945387051, 0.127529777813422, 0.130352278056244, 0.1332085131843, 0.136098549737202, 0.139022453734703,
0.141980290685736, 0.144972125597231, 0.147998022982685, 0.151058046870511, 0.154152260812165, 0.157280727890073, 0.160443510725344, 0.16364067148529, 0.166872271890766,
0.170138373223312, 0.173439036332135, 0.176774321640903, 0.18014428915439, 0.183548998464951, 0.186988508758844, 0.190462878822409, 0.193972167048093, 0.19751643144034,
0.201095729621346, 0.204710118836677, 0.208359655960767, 0.212044397502288, 0.215764399609395, 0.219519718074868, 0.223310408341127, 0.227136525505149, 0.230998124323267,
0.23489525921588, 0.238827984272048, 0.242796353254002, 0.24680041960155, 0.2508402364364, 0.254915856566385, 0.259027332489606, 0.263174716398492, 0.267358060183772,
0.271577415438375, 0.275832833461245, 0.280124365261085, 0.284452061560024, 0.288815972797219, 0.293216149132375, 0.297652640449211, 0.302125496358853, 0.306634766203158,
0.311180499057984, 0.315762743736397, 0.32038154879181, 0.325036962521076, 0.329729032967515, 0.334457807923889, 0.339223334935327, 0.344025661302187, 0.348864834082879,
0.353740900096629, 0.358653905926199, 0.363603897920553, 0.368590922197487, 0.373615024646202, 0.37867625092984, 0.383774646487975, 0.388910256539059, 0.394083126082829,
0.399293299902674, 0.404540822567962, 0.409825738436323, 0.415148091655907, 0.420507926167587, 0.425905285707146, 0.43134021380741, 0.436812753800359, 0.442322948819202,
0.44787084180041, 0.453456475485731, 0.45907989242416, 0.46474113497389, 0.470440245304218, 0.47617726539744, 0.481952237050698, 0.487765201877811, 0.493616201311074,
0.49950527660303, 0.505432468828216, 0.511397818884879, 0.517401367496673, 0.523443155214325, 0.529523222417277, 0.535641609315311, 0.541798355950137, 0.547993502196972,
0.554227087766085, 0.560499152204328, 0.566809734896638, 0.573158875067523, 0.579546611782525, 0.585972983949661, 0.592438030320847, 0.598941789493296, 0.605484299910907,
0.612065599865624, 0.61868572749878, 0.625344720802427, 0.632042617620641, 0.638779455650817, 0.645555272444934, 0.652370105410821, 0.659223991813387, 0.666116968775851,
0.673049073280942, 0.680020342172095, 0.687030812154625, 0.694080519796882, 0.701169501531402, 0.708297793656032, 0.715465432335048, 0.722672453600255, 0.729918893352071,
0.737204787360605, 0.744530171266715, 0.751895080583051, 0.759299550695091, 0.766743616862161, 0.774227314218442, 0.781750677773962, 0.789313742415586, 0.796916542907978,
0.804559113894567, 0.81224148989849, 0.819963705323528, 0.827725794455034, 0.835527791460841, 0.843369730392169, 0.851251645184515, 0.859173569658532, 0.867135537520905,
0.875137582365205, 0.883179737672745, 0.891262036813419, 0.899384513046529, 0.907547199521614, 0.915750129279253, 0.923993335251873, 0.932276850264543, 0.940600707035753,
0.948964938178195, 0.957369576199527, 0.96581465350313, 0.974300202388861, 0.982826255053791, 0.99139284359294, 1
};
/**
* Table for fast FColor -> FLinearColor conversion.
*
* Color > 0.04045 ? pow( Color * (1.0 / 1.055) + 0.0521327, 2.4 ) : Color * (1.0 / 12.92);
*/
float FLinearColor::sRGBToLinearTable[256] =
{
0,
0.000303526983548838, 0.000607053967097675, 0.000910580950646512, 0.00121410793419535, 0.00151763491774419,
0.00182116190129302, 0.00212468888484186, 0.0024282158683907, 0.00273174285193954, 0.00303526983548838,
0.00334653564113713, 0.00367650719436314, 0.00402471688178252, 0.00439144189356217, 0.00477695332960869,
0.005181516543916, 0.00560539145834456, 0.00604883284946662, 0.00651209061157708, 0.00699540999852809,
0.00749903184667767, 0.00802319278093555, 0.0085681254056307, 0.00913405848170623, 0.00972121709156193,
0.0103298227927056, 0.0109600937612386, 0.0116122449260844, 0.012286488094766, 0.0129830320714536,
0.0137020827679224, 0.0144438433080002, 0.0152085141260192, 0.0159962930597398, 0.0168073754381669,
0.0176419541646397, 0.0185002197955389, 0.0193823606149269, 0.0202885627054049, 0.0212190100154473,
0.0221738844234532, 0.02315336579873, 0.0241576320596103, 0.0251868592288862, 0.0262412214867272,
0.0273208912212394, 0.0284260390768075, 0.0295568340003534, 0.0307134432856324, 0.0318960326156814,
0.0331047661035236, 0.0343398063312275, 0.0356013143874111, 0.0368894499032755, 0.0382043710872463,
0.0395462347582974, 0.0409151963780232, 0.0423114100815264, 0.0437350287071788, 0.0451862038253117,
0.0466650857658898, 0.0481718236452158, 0.049706565391714, 0.0512694577708345, 0.0528606464091205,
0.0544802758174765, 0.0561284894136735, 0.0578054295441256, 0.0595112375049707, 0.0612460535624849,
0.0630100169728596, 0.0648032660013696, 0.0666259379409563, 0.0684781691302512, 0.070360094971063,
0.0722718499453493, 0.0742135676316953, 0.0761853807213167, 0.0781874210336082, 0.0802198195312533,
0.0822827063349132, 0.0843762107375113, 0.0865004612181274, 0.0886555854555171, 0.0908417103412699,
0.0930589619926197, 0.0953074657649191, 0.0975873462637915, 0.0998987273569704, 0.102241732185838,
0.104616483176675, 0.107023102051626, 0.109461709839399, 0.1119324268857, 0.114435372863418,
0.116970666782559, 0.119538426999953, 0.122138771228724, 0.124771816547542, 0.127437679409664,
0.130136475651761, 0.132868320502552, 0.135633328591233, 0.138431613955729, 0.141263290050755,
0.144128469755705, 0.147027265382362, 0.149959788682454, 0.152926150855031, 0.155926462553701,
0.158960833893705, 0.162029374458845, 0.16513219330827, 0.168269398983119, 0.171441099513036,
0.174647402422543, 0.17788841473729, 0.181164242990184, 0.184474993227387, 0.187820771014205,
0.191201681440861, 0.194617829128147, 0.198069318232982, 0.201556252453853, 0.205078735036156,
0.208636868777438, 0.212230756032542, 0.215860498718652, 0.219526198320249, 0.223227955893977,
0.226965872073417, 0.23074004707378, 0.23455058069651, 0.238397572333811, 0.242281120973093,
0.246201325201334, 0.250158283209375, 0.254152092796134, 0.258182851372752, 0.262250655966664,
0.266355603225604, 0.270497789421545, 0.274677310454565, 0.278894261856656, 0.283148738795466,
0.287440836077983, 0.291770648154158, 0.296138269120463, 0.300543792723403, 0.304987312362961,
0.309468921095997, 0.313988711639584, 0.3185467763743, 0.323143207347467, 0.32777809627633,
0.332451534551205, 0.337163613238559, 0.341914423084057, 0.346704054515559, 0.351532597646068,
0.356400142276637, 0.361306777899234, 0.36625259369956, 0.371237678559833, 0.376262121061519,
0.381326009488037, 0.386429431827418, 0.39157247577492, 0.396755228735618, 0.401977777826949,
0.407240209881218, 0.41254261144808, 0.417885068796976, 0.423267667919539, 0.428690494531971,
0.434153634077377, 0.439657171728079, 0.445201192387887, 0.450785780694349, 0.456411021020965,
0.462076997479369, 0.467783793921492, 0.473531493941681, 0.479320180878805, 0.485149937818323,
0.491020847594331, 0.496932992791578, 0.502886455747457, 0.50888131855397, 0.514917663059676,
0.520995570871595, 0.527115123357109, 0.533276401645826, 0.539479486631421, 0.545724458973463,
0.552011399099209, 0.558340387205378, 0.56471150325991, 0.571124827003694, 0.577580437952282,
0.584078415397575, 0.590618838409497, 0.597201785837643, 0.603827336312907, 0.610495568249093,
0.617206559844509, 0.623960389083534, 0.630757133738175, 0.637596871369601, 0.644479679329661,
0.651405634762384, 0.658374814605461, 0.665387295591707, 0.672443154250516, 0.679542466909286,
0.686685309694841, 0.693871758534824, 0.701101889159085, 0.708375777101046, 0.71569349769906,
0.723055126097739, 0.730460737249286, 0.737910405914797, 0.745404206665559, 0.752942213884326,
0.760524501766589, 0.768151144321824, 0.775822215374732, 0.783537788566466, 0.791297937355839,
0.799102735020525, 0.806952254658248, 0.81484656918795, 0.822785751350956, 0.830769873712124,
0.838799008660978, 0.846873228412837, 0.854992605009927, 0.863157210322481, 0.871367116049835,
0.879622393721502, 0.887923114698241, 0.896269350173118, 0.904661171172551, 0.913098648557343,
0.921581853023715, 0.930110855104312, 0.938685725169219, 0.947306533426946, 0.955973349925421,
0.964686244552961, 0.973445287039244, 0.982250546956257, 0.991102093719252, 1.0,
};
| [
"[email protected]"
] | |
c5a45ca0f55f623c6a2939d2b26eab4c08152a77 | 64456529e55a2bb93507f03cf4541a98b6c41aa0 | /SeasonalGlobe/SeasonSetup.cpp | 67635bc3c6fe480ddb08a3f7838f0911586df380 | [] | no_license | wrdn/SeasonalGlobe | df62a85855a550b3400664c011456649e9c669b1 | f8005be78d257dc366ff68259ba295b5285e3cbd | refs/heads/master | 2021-01-25T00:10:39.684946 | 2012-03-27T13:29:37 | 2012-03-27T13:29:37 | 3,248,688 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,498 | cpp | #include "World.h"
// This file contains global functions used for seasonal events
void StartTreeGrowth(const World *w) // start tree growing
{
World *wt = (World*)w;
wt->GetTree()->SetActive(true);
wt->GetTree()->InitGrow();
};
void InitiateLeafGrowth(const World *w) // make leaves appear
{
World *wt = (World*)w;
wt->GetLeafParticleEmitter()->SetActive(true);
wt->GetLeafParticleEmitter()->SetStartColor(Color4f(1,1,1,1));
wt->GetLeafParticleEmitter()->InitiateParticleFadeIn();
};
void InitiateLeafColorChange(const World *w) // make leaves change color
{
World *wt = (World*)w;
wt->GetLeafParticleEmitter()->SetEndColor(Color4f(0.8f, 0.35f, 0.35f, 1));
wt->GetLeafParticleEmitter()->InitiateMainColorChange();
};
void InitiateLeafFall(const World *w) // make leaves fall
{
World *wt = (World*)w;
wt->GetLeafParticleEmitter()->InitiateParticleFall();
};
void InitiateTreeIgnitionFire(const World *w) // make tree catch fire
{
FireParticleEmitter *fp = (FireParticleEmitter*)w->GetFireParticleEmitter();
fp->SetRuntime(0);
fp->SetBurnLevel(0);
fp->SetBurningState(Igniting);
fp->SetActive(true);
};
void InitiateTreeDeath(const World *w) // make tree die
{
FireParticleEmitter *fp = (FireParticleEmitter*)w->GetFireParticleEmitter();
fp->InitDeath();
};
void InitiateLeafVanish(const World *w) // makes leaves vanish
{
World *wt = (World*)w;
wt->GetLeafParticleEmitter()->InitiateParticleFadeOut();
}
void InitialiseHouseSmoke(const World *w) // start smoke
{
((World*)w)->ActivateSmokeParticleEffect();
};
void InitialiseSnow(const World *w) // start snow
{
((World*)w)->ActivateSnow();
};
void PlaySpringSummerSound(const World *w)
{
World *wr = (World*)w;
// ensure every other sound has been stopped
wr->GetAppSounds().bellsSound->Stop();
wr->GetAppSounds().fireSound->Stop();
wr->GetAppSounds().lightningSound->Stop();
if(wr->GetAppSounds().springSummerSound->GetSourceState() != AL_PLAYING) // accounts for the sound being started during the loading screen
{
wr->GetAppSounds().springSummerSound->Play();
}
};
void PlayLightningSound(const World *w)
{
World *wr = (World*)w;
wr->GetAppSounds().lightningSound->Play();
wr->GetAppSounds().springSummerSound->Stop();
};
void PlayFireSound(const World *w)
{
World *wr = (World*)w;
wr->GetAppSounds().fireSound->SetVolume(1.0f);
wr->GetAppSounds().fireSound->Play();
};
void PlayBellsSound(const World *w)
{
World *wr = (World*)w;
wr->GetAppSounds().fireSound->SetVolume(0.5f);
wr->GetAppSounds().lightningSound->Stop();
wr->GetAppSounds().bellsSound->Play();
};
// start terrain elevation, and texture merge
void InitialiseTerrainElevation(const World *w) { ((World*)w)->ActivateTerrainElevation(Up); }
void InitialiseTerrainMelt(const World *w) { ((World*)w)->ActivateTerrainElevation(Down); }
void InitialiseTerrainTextureMergeToSnow(const World *w) { ((World*)w)->ActiveTerrainTextureMerge(1); }
void InitialiseTerrainTextureMergeToGrass(const World *w) { ((World*)w)->ActiveTerrainTextureMerge(-1); }
// show/hide lightning
void InitLightningAppear(const World *w) { ((World*)w)->SetLightningActive(true); }
void InitLightningVanish(const World *w) { ((World*)w)->SetLightningActive(false); }
// deactivate snow
void DeactivateWorldSnow(const World *w) { ((World*)w)->DeactivateSnow(); };
// start slowing snow
void ActivateSnowSlowing(const World *w) { ((World*)w)->SetSnowSlowing(true); }
// setup world seasons
void World::SetupSeasons()
{
i32 timePerSeasons = conf.Read("TimePerSeason", 16);
seasonMan.SetTimePerSeason((f32)timePerSeasons); // 8 seconds per season, 32 seconds per cycle
seasonMan.SetWorldPointer(this);
// Spring: Tree grows
seasonMan.AddEvent(Spring, SeasonalEvent(0.1f, PlaySpringSummerSound));
seasonMan.AddEvent(Spring, SeasonalEvent(0.1f, StartTreeGrowth)); // tree grows at start of spring
// Summer: Leaves appear on tree
seasonMan.AddEvent(Summer, SeasonalEvent(0.0f, InitiateLeafGrowth));
// Autumn: Leaves change colour and fall from tree (then disappear over time), lightning bolt hits tree and it burns down
seasonMan.AddEvent(Autumn, SeasonalEvent(0, InitiateLeafColorChange));
seasonMan.AddEvent(Autumn, SeasonalEvent(0.2f, InitiateLeafFall));
seasonMan.AddEvent(Autumn, SeasonalEvent(0.3f, InitiateLeafVanish));
seasonMan.AddEvent(Autumn, SeasonalEvent(0.24f, PlayLightningSound));
seasonMan.AddEvent(Autumn, SeasonalEvent(0.28f, InitLightningAppear));
seasonMan.AddEvent(Autumn, SeasonalEvent(0.3f, InitLightningVanish));
seasonMan.AddEvent(Autumn, SeasonalEvent(0.3f, InitiateTreeIgnitionFire));
seasonMan.AddEvent(Autumn, SeasonalEvent(0.32f, PlayFireSound));
seasonMan.AddEvent(Autumn, SeasonalEvent(0.78f, InitiateTreeDeath));
// Winter
seasonMan.AddEvent(Winter, SeasonalEvent(0, InitialiseSnow ));
seasonMan.AddEvent(Winter, SeasonalEvent(0.05f, InitialiseHouseSmoke));
seasonMan.AddEvent(Winter, SeasonalEvent(0.275f, PlayBellsSound));
seasonMan.AddEvent(Winter, SeasonalEvent(0.3f, InitialiseTerrainTextureMergeToSnow));
seasonMan.AddEvent(Winter, SeasonalEvent(0.45f, InitialiseTerrainElevation));
seasonMan.AddEvent(Winter, SeasonalEvent(0.8f, InitialiseTerrainMelt));
seasonMan.AddEvent(Winter, SeasonalEvent(0.85f, InitialiseTerrainTextureMergeToGrass));
seasonMan.AddEvent(Winter, SeasonalEvent(0.8f, ActivateSnowSlowing));
seasonMan.AddEvent(Winter, SeasonalEvent(0.9f, DeactivateWorldSnow));
UpdateSceneTimings();
};
// update scene timings
void World::UpdateSceneTimings()
{
tree->SetBuildTime(seasonMan.GetTimePerSeason() * 0.85f);
particleSystem.GetEmitter<StaticParticleEmitter>(leafParticleEmitterID)->SetTimeToFadeIn(seasonMan.GetTimePerSeason() * 0.25f);
particleSystem.GetEmitter<StaticParticleEmitter>(leafParticleEmitterID)->SetTimeToChangeColor(seasonMan.GetTimePerSeason() * 0.15f);
particleSystem.GetEmitter<StaticParticleEmitter>(leafParticleEmitterID)->SetTimeToFall(seasonMan.GetTimePerSeason() * 0.1f);
particleSystem.GetEmitter<StaticParticleEmitter>(leafParticleEmitterID)->SetTimeToChangeColor(seasonMan.GetTimePerSeason() * 0.2f);
fireParticleEmitter->SetIgnitionTime(seasonMan.GetTimePerSeason() * 0.45f);
fireParticleEmitter->SetDeathTime(seasonMan.GetTimePerSeason() * 0.75f);
particleSystem.GetEmitter<HemiSphericalParticleEmitter>(snowEmitterID)->SetTimeToFall(seasonMan.GetTimePerSeason() * 0.1f);
timeToMergeTextures = seasonMan.GetTimePerSeason() * 0.25f;
terrainElevation.timeToElevateFully = seasonMan.GetTimePerSeason() * 0.25f;
}; | [
"[email protected]"
] | |
4e4a26800b4fec016509d42f766ad83e23447b26 | d462920d37c7ff884bdca79a14b231847c9feaf4 | /use-the-fork/Player.h | c02ab21103529d5ee855395c4c823d35457bb928 | [
"BSD-2-Clause"
] | permissive | greenteamleader/invaders | 34397f639e858ae81f8ab73722b0a35442723650 | 95fac6e0d6d468d2c23bfc404caee20214a22aaa | refs/heads/master | 2023-03-17T04:51:20.111138 | 2019-06-02T20:23:04 | 2019-06-02T20:23:04 | 511,322,086 | 0 | 0 | null | 2022-07-06T23:32:12 | 2022-07-06T23:32:12 | null | UTF-8 | C++ | false | false | 360 | h | /*
* Player.h
*
* Created on: Oct 20, 2018
* Author: george
*/
#ifndef PLAYER_H_
#define PLAY_
#include "SpaceObject.h"
#include <SFML/Graphics.hpp>
#include <memory>
class Player : public sf::CircleShape, public virtual SpaceObject
{
public:
Player( int radius = 5 );
virtual ~Player();
void fire();
void step();
private:
};
#endif
| [
"[email protected]"
] | |
a7e404f030ef459aa9b46882beb7c33f801e4641 | d228c045d5a49edba42108e69521a71c32eb4bb2 | /nebula/scriptengine/scriptengine_test/scriptegine_test.cc | dbb680237a82c5f6c602c18f7a6c236a3f0642a3 | [
"Apache-2.0"
] | permissive | iineva/nebula | 11a889ad0fc1ba1cc2ac6f8258336c2dc73dae24 | feb4f309d896210aeda7a606d38aab4af5cb6ada | refs/heads/master | 2021-02-12T09:23:00.307402 | 2020-03-13T04:28:05 | 2020-03-13T04:28:05 | 244,581,726 | 0 | 0 | Apache-2.0 | 2020-03-03T08:30:42 | 2020-03-03T08:30:41 | null | UTF-8 | C++ | false | false | 3,165 | cc | /*
* Copyright (c) 2016, https://github.com/nebula-im/nebula
* 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 <iostream>
#include "nebula/base/crypto_util/md5.h"
#include "nebula/scriptengine/script_engine.h"
std::string MD5String2(const std::string& str) {
nebula::MD5Digest digest;
nebula::MD5Sum(str.c_str(), str.length(), &digest);
return nebula::MD5DigestToBase16(digest);
}
lua_tinker::table TableTest(lua_tinker::table t) {
//base::MD5Digest digest;
//base::MD5Sum(str.c_str(), str.length(), &digest);
//return base::MD5DigestToBase16(digest);
return t;
}
// void Luabind_Base_Register(lua_State* L) {
// lua_tinker::def(L, "MD5String", &MD5String2);
// lua_tinker::def(L, "UTF8ToNativeMB", &UTF8ToNativeMB);
// }
struct T {
//public:
// T() {
// std::cout << "T::T()" << std::endl;
// }
// ~T() {
// std::cout << "T::~T()" << std::endl;
// }
void Print() {
std::cout << "T::Print()" << std::endl;
}
};
std::shared_ptr<T> CreateTSharedPtrTest() {
return std::shared_ptr<T>(new T());
}
T CreateTTest() {
return T();
}
void CppTestingRegister(ScriptEngine* script_engine) {
#undef RegisterClass
script_engine->RegisterClass<T>("T");
script_engine->RegisterClassFuncnction<T>("Print", &T::Print);
script_engine->RegisterClass<std::shared_ptr<T> >("SharedPtr_T");
script_engine->RegisterClassFuncnction<std::shared_ptr<T> >("Get", &std::shared_ptr<T>::get);
script_engine->RegisterFunction("MD5String", &MD5String2);
script_engine->RegisterFunction("TableTest", &TableTest);
script_engine->RegisterFunction("CreateTSharedPtrTest", &CreateTSharedPtrTest);
script_engine->RegisterFunction("CreateTTest", &CreateTTest);
}
int main(int argc, char* argv[]) {
/*
ScriptEngine script_engine;
script_engine.Initialize();
CppTestingRegister(&script_engine);
script_engine.DoFile(argv[1]);
script_engine.CallFunction<int>("DoMain");
script_engine.Destroy();
*/
ScriptEngine script_engine;
script_engine.Initialize();
CppTestingRegister(&script_engine);
script_engine.DoFile(argv[1]);
// lua_tinker::table haha(script_engine.GetLuaState(),"haha");
script_engine.CallFunction<int>("DoMain");
{
// lua_tinker::table ret = lua_tinker::call<lua_tinker::table>(script_engine.GetLuaState(), "return_table", "give me a table !!");
// script_engine.CallFunction<void>("print_table", ret);
// script_engine.CallFunction<void>("print_table2", ret);
}
// script_engine.CallFunction<int>("DoMain");
// lua_tinker::table haha(L,"haha");
script_engine.Destroy();
// lua_tinker::table haha(L,"haha");
return 0;
}
| [
"[email protected]"
] | |
21a15463cd4a60f2e05788be5ad63c1b230d5b72 | e25b7bb3fd43f763f4e5dcb09cdda35b9a3f30a0 | /device/bluetooth/test/test_bluetooth_adapter_observer.cc | eccdf250f0e0d2d71391f661a272df92e5467f2d | [
"BSD-3-Clause"
] | permissive | trustcrypto/chromium | 281ff06e944b1ff7da7a5005e41173ccc78eb2cd | 6e3be4ab657ddd91505753ab67801efcf8541367 | refs/heads/master | 2023-03-08T03:58:49.920358 | 2018-12-26T20:55:44 | 2018-12-26T20:55:44 | 163,217,833 | 1 | 0 | NOASSERTION | 2018-12-26T21:07:41 | 2018-12-26T21:07:40 | null | UTF-8 | C++ | false | false | 12,236 | cc | // Copyright 2015 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 "device/bluetooth/test/test_bluetooth_adapter_observer.h"
#include <string>
#include <vector>
#include "base/run_loop.h"
#include "device/bluetooth/bluetooth_remote_gatt_characteristic.h"
#include "device/bluetooth/bluetooth_remote_gatt_descriptor.h"
#include "device/bluetooth/bluetooth_remote_gatt_service.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace device {
TestBluetoothAdapterObserver::TestBluetoothAdapterObserver(
scoped_refptr<BluetoothAdapter> adapter)
: adapter_(adapter) {
Reset();
adapter_->AddObserver(this);
}
TestBluetoothAdapterObserver::~TestBluetoothAdapterObserver() {
adapter_->RemoveObserver(this);
}
void TestBluetoothAdapterObserver::Reset() {
present_changed_count_ = 0;
powered_changed_count_ = 0;
discoverable_changed_count_ = 0;
discovering_changed_count_ = 0;
last_present_ = false;
last_powered_ = false;
last_discovering_ = false;
device_added_count_ = 0;
device_changed_count_ = 0;
device_address_changed_count_ = 0;
device_advertisement_raw_received_count_ = 0;
last_device_name_ = "";
last_advertisement_name_ = "";
last_rssi_ = 128;
last_tx_power_ = 128;
last_appearance_ = 128;
#if defined(OS_CHROMEOS) || defined(OS_LINUX)
device_paired_changed_count_ = 0;
device_new_paired_status_ = false;
device_mtu_changed_count_ = 0;
device_mtu_ = 0;
device_advertisement_received_count_ = 0;
device_eir_.clear();
device_connected_state_changed_values_.clear();
#endif
device_removed_count_ = 0;
last_device_ = NULL;
last_device_address_.clear();
gatt_service_added_count_ = 0;
gatt_service_removed_count_ = 0;
gatt_services_discovered_count_ = 0;
gatt_service_changed_count_ = 0;
gatt_discovery_complete_count_ = 0;
gatt_characteristic_added_count_ = 0;
gatt_characteristic_removed_count_ = 0;
gatt_characteristic_value_changed_count_ = 0;
gatt_descriptor_added_count_ = 0;
gatt_descriptor_removed_count_ = 0;
gatt_descriptor_value_changed_count_ = 0;
last_gatt_service_id_.clear();
last_gatt_service_uuid_ = BluetoothUUID();
last_gatt_characteristic_id_.clear();
last_gatt_characteristic_uuid_ = BluetoothUUID();
last_changed_characteristic_value_.clear();
previous_characteristic_value_changed_values_.clear();
last_gatt_descriptor_id_.clear();
last_gatt_descriptor_uuid_ = BluetoothUUID();
last_changed_descriptor_value_.clear();
}
void TestBluetoothAdapterObserver::AdapterPresentChanged(
BluetoothAdapter* adapter,
bool present) {
EXPECT_EQ(adapter_.get(), adapter);
++present_changed_count_;
last_present_ = present;
}
void TestBluetoothAdapterObserver::AdapterPoweredChanged(
BluetoothAdapter* adapter,
bool powered) {
EXPECT_EQ(adapter_.get(), adapter);
++powered_changed_count_;
last_powered_ = powered;
}
void TestBluetoothAdapterObserver::AdapterDiscoverableChanged(
BluetoothAdapter* adapter,
bool discoverable) {
EXPECT_EQ(adapter_.get(), adapter);
++discoverable_changed_count_;
}
void TestBluetoothAdapterObserver::AdapterDiscoveringChanged(
BluetoothAdapter* adapter,
bool discovering) {
EXPECT_EQ(adapter_.get(), adapter);
++discovering_changed_count_;
last_discovering_ = discovering;
}
void TestBluetoothAdapterObserver::DeviceAdded(BluetoothAdapter* adapter,
BluetoothDevice* device) {
EXPECT_EQ(adapter_.get(), adapter);
++device_added_count_;
last_device_ = device;
last_device_address_ = device->GetAddress();
QuitMessageLoop();
}
void TestBluetoothAdapterObserver::DeviceChanged(BluetoothAdapter* adapter,
BluetoothDevice* device) {
EXPECT_EQ(adapter_.get(), adapter);
++device_changed_count_;
last_device_ = device;
last_device_address_ = device->GetAddress();
QuitMessageLoop();
}
void TestBluetoothAdapterObserver::DeviceAddressChanged(
device::BluetoothAdapter* adapter,
device::BluetoothDevice* device,
const std::string& old_address) {
++device_address_changed_count_;
last_device_ = device;
last_device_address_ = device->GetAddress();
QuitMessageLoop();
}
void TestBluetoothAdapterObserver::DeviceAdvertisementReceived(
const std::string& device_address,
const base::Optional<std::string>& device_name,
const base::Optional<std::string>& advertisement_name,
base::Optional<int8_t> rssi,
base::Optional<int8_t> tx_power,
uint16_t appearance,
const device::BluetoothDevice::UUIDList& advertised_uuids,
const device::BluetoothDevice::ServiceDataMap& service_data_map,
const device::BluetoothDevice::ManufacturerDataMap& manufacturer_data_map) {
++device_advertisement_raw_received_count_;
last_device_name_ = device_address;
last_advertisement_name_ = device_name;
last_rssi_ = rssi;
last_tx_power_ = tx_power;
last_appearance_ = appearance;
// TODO(dougt): Test advertised_uuids, service_data_map, manufacturer_data_map
QuitMessageLoop();
}
#if defined(OS_CHROMEOS) || defined(OS_LINUX)
void TestBluetoothAdapterObserver::DevicePairedChanged(
device::BluetoothAdapter* adapter,
device::BluetoothDevice* device,
bool new_paired_status) {
++device_paired_changed_count_;
last_device_ = device;
device_new_paired_status_ = new_paired_status;
QuitMessageLoop();
}
void TestBluetoothAdapterObserver::DeviceMTUChanged(
device::BluetoothAdapter* adapter,
device::BluetoothDevice* device,
uint16_t mtu) {
++device_mtu_changed_count_;
last_device_ = device;
device_mtu_ = mtu;
QuitMessageLoop();
}
void TestBluetoothAdapterObserver::DeviceAdvertisementReceived(
device::BluetoothAdapter* adapter,
device::BluetoothDevice* device,
int16_t rssi,
const std::vector<uint8_t>& eir) {
++device_advertisement_received_count_;
last_device_ = device;
device_eir_ = eir;
QuitMessageLoop();
}
void TestBluetoothAdapterObserver::DeviceConnectedStateChanged(
device::BluetoothAdapter* adapter,
device::BluetoothDevice* device,
bool is_now_connected) {
last_device_ = device;
device_connected_state_changed_values_.push_back(is_now_connected);
QuitMessageLoop();
}
#endif
void TestBluetoothAdapterObserver::DeviceRemoved(BluetoothAdapter* adapter,
BluetoothDevice* device) {
EXPECT_EQ(adapter_.get(), adapter);
++device_removed_count_;
// Can't save device, it may be freed
last_device_address_ = device->GetAddress();
QuitMessageLoop();
}
void TestBluetoothAdapterObserver::GattServiceAdded(
BluetoothAdapter* adapter,
BluetoothDevice* device,
BluetoothRemoteGattService* service) {
ASSERT_EQ(adapter_.get(), adapter);
ASSERT_EQ(service->GetDevice(), device);
++gatt_service_added_count_;
last_gatt_service_id_ = service->GetIdentifier();
last_gatt_service_uuid_ = service->GetUUID();
EXPECT_TRUE(service->IsPrimary());
EXPECT_EQ(device->GetGattService(last_gatt_service_id_), service);
QuitMessageLoop();
}
void TestBluetoothAdapterObserver::GattServiceRemoved(
BluetoothAdapter* adapter,
BluetoothDevice* device,
BluetoothRemoteGattService* service) {
ASSERT_EQ(adapter_.get(), adapter);
ASSERT_EQ(service->GetDevice(), device);
++gatt_service_removed_count_;
last_gatt_service_id_ = service->GetIdentifier();
last_gatt_service_uuid_ = service->GetUUID();
EXPECT_TRUE(service->IsPrimary());
// The device should return NULL for this service.
EXPECT_FALSE(device->GetGattService(last_gatt_service_id_));
QuitMessageLoop();
}
void TestBluetoothAdapterObserver::GattServicesDiscovered(
BluetoothAdapter* adapter,
BluetoothDevice* device) {
ASSERT_EQ(adapter_.get(), adapter);
++gatt_services_discovered_count_;
last_device_ = device;
last_device_address_ = device->GetAddress();
QuitMessageLoop();
}
void TestBluetoothAdapterObserver::GattDiscoveryCompleteForService(
BluetoothAdapter* adapter,
BluetoothRemoteGattService* service) {
ASSERT_EQ(adapter_.get(), adapter);
++gatt_discovery_complete_count_;
QuitMessageLoop();
}
void TestBluetoothAdapterObserver::GattServiceChanged(
BluetoothAdapter* adapter,
BluetoothRemoteGattService* service) {
ASSERT_EQ(adapter_.get(), adapter);
++gatt_service_changed_count_;
QuitMessageLoop();
}
void TestBluetoothAdapterObserver::GattCharacteristicAdded(
BluetoothAdapter* adapter,
BluetoothRemoteGattCharacteristic* characteristic) {
ASSERT_EQ(adapter_.get(), adapter);
++gatt_characteristic_added_count_;
last_gatt_characteristic_id_ = characteristic->GetIdentifier();
last_gatt_characteristic_uuid_ = characteristic->GetUUID();
ASSERT_TRUE(characteristic->GetService());
EXPECT_EQ(characteristic->GetService()->GetCharacteristic(
last_gatt_characteristic_id_),
characteristic);
QuitMessageLoop();
}
void TestBluetoothAdapterObserver::GattCharacteristicRemoved(
BluetoothAdapter* adapter,
BluetoothRemoteGattCharacteristic* characteristic) {
ASSERT_EQ(adapter_.get(), adapter);
++gatt_characteristic_removed_count_;
last_gatt_characteristic_id_ = characteristic->GetIdentifier();
last_gatt_characteristic_uuid_ = characteristic->GetUUID();
// The service should return NULL for this characteristic.
ASSERT_TRUE(characteristic->GetService());
EXPECT_FALSE(characteristic->GetService()->GetCharacteristic(
last_gatt_characteristic_id_));
QuitMessageLoop();
}
void TestBluetoothAdapterObserver::GattDescriptorAdded(
BluetoothAdapter* adapter,
BluetoothRemoteGattDescriptor* descriptor) {
ASSERT_EQ(adapter_.get(), adapter);
++gatt_descriptor_added_count_;
last_gatt_descriptor_id_ = descriptor->GetIdentifier();
last_gatt_descriptor_uuid_ = descriptor->GetUUID();
ASSERT_TRUE(descriptor->GetCharacteristic());
EXPECT_EQ(
descriptor->GetCharacteristic()->GetDescriptor(last_gatt_descriptor_id_),
descriptor);
QuitMessageLoop();
}
void TestBluetoothAdapterObserver::GattDescriptorRemoved(
BluetoothAdapter* adapter,
BluetoothRemoteGattDescriptor* descriptor) {
ASSERT_EQ(adapter_.get(), adapter);
++gatt_descriptor_removed_count_;
last_gatt_descriptor_id_ = descriptor->GetIdentifier();
last_gatt_descriptor_uuid_ = descriptor->GetUUID();
// The characteristic should return NULL for this descriptor..
ASSERT_TRUE(descriptor->GetCharacteristic());
EXPECT_FALSE(
descriptor->GetCharacteristic()->GetDescriptor(last_gatt_descriptor_id_));
QuitMessageLoop();
}
void TestBluetoothAdapterObserver::GattCharacteristicValueChanged(
BluetoothAdapter* adapter,
BluetoothRemoteGattCharacteristic* characteristic,
const std::vector<uint8_t>& value) {
ASSERT_EQ(adapter_.get(), adapter);
++gatt_characteristic_value_changed_count_;
last_gatt_characteristic_id_ = characteristic->GetIdentifier();
last_gatt_characteristic_uuid_ = characteristic->GetUUID();
last_changed_characteristic_value_ = value;
previous_characteristic_value_changed_values_.push_back(value);
ASSERT_TRUE(characteristic->GetService());
EXPECT_EQ(characteristic->GetService()->GetCharacteristic(
last_gatt_characteristic_id_),
characteristic);
QuitMessageLoop();
}
void TestBluetoothAdapterObserver::GattDescriptorValueChanged(
BluetoothAdapter* adapter,
BluetoothRemoteGattDescriptor* descriptor,
const std::vector<uint8_t>& value) {
ASSERT_EQ(adapter_.get(), adapter);
++gatt_descriptor_value_changed_count_;
last_gatt_descriptor_id_ = descriptor->GetIdentifier();
last_gatt_descriptor_uuid_ = descriptor->GetUUID();
last_changed_descriptor_value_ = value;
ASSERT_TRUE(descriptor->GetCharacteristic());
EXPECT_EQ(
descriptor->GetCharacteristic()->GetDescriptor(last_gatt_descriptor_id_),
descriptor);
QuitMessageLoop();
}
void TestBluetoothAdapterObserver::QuitMessageLoop() {
if (base::RunLoop::IsRunningOnCurrentThread())
base::RunLoop::QuitCurrentWhenIdleDeprecated();
}
} // namespace device
| [
"[email protected]"
] | |
264a2ba398de2ba3b4d5568ab232250d5cb6e548 | bf45db9332e0246a24a3a04b71d9b5d8bd9797d1 | /1000-1100/1005.cpp | add9694cc03d7812034ae5fdea34d8395216ae84 | [] | no_license | Stupiderman/HDoj | 3efebefe326b2f477d8d01b6ac17b924929bc171 | a18c23468b7c28f892f1bbd5934f90bd93eceba0 | refs/heads/master | 2020-03-07T16:42:15.566433 | 2018-04-01T03:05:56 | 2018-04-01T03:05:56 | 127,590,566 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 396 | cpp | #include<iostream>
using namespace std;
int main(){
int A = 0,B= 0,n= 0;
int a[1000];
int i=0;
while (cin>>A>>B>>n) {
if (n==0) {
continue;
}
memset(a,0,1000);
a[0] = 1;
a[1] = 1;
for (i = 2; i <49; i++) {
a[i] = (A*a[i-1]+B*a[i-2])%7;
}
cout<<a[(n-1)%49]<<endl;
}
}
| [
"[email protected]"
] | |
7f3b7990f427c5d27c1fd3c38aa96d8d7934f482 | f9c5341ffcde2bd3ea3ac85f5fb119f93e92935b | /BOJ/C++/1019_책 페이지.cpp | 652b80ed0373f60ee4c117812744caab120441ba | [] | no_license | leejaeseung/Algorithm | d9ab4f65b59c091cb65185c0d1f5f4772593eff9 | 644c69836cd0c578961d3b00741af4f4ff7c8339 | refs/heads/master | 2023-07-09T12:21:35.248238 | 2021-07-30T08:35:36 | 2021-07-30T08:35:36 | 247,437,095 | 1 | 1 | null | null | null | null | UHC | C++ | false | false | 1,220 | cpp | /*
문제
지민이는 N쪽인 책이 한권 있다. 첫 페이지는 1쪽이고, 마지막 페이지는 N쪽이다. 각 숫자가 모두 몇 번이 나오는지 출력하는 프로그램을 작성하시오.
입력
첫째 줄에 N이 주어진다. N은 1,000,000,000보다 작거나 같은 자연수이다.
출력
첫째 줄에 0이 총 몇 번 나오는지, 1이 총 몇 번 나오는지, ..., 9가 총 몇 번 나오는지를 출력한다.
풀이:
*/
#include<iostream>
#include<algorithm>
#include<math.h>
#include<string.h>
#include<string>
#include<vector>
#include<queue>
using namespace std;
#define FIO ios_base::sync_with_stdio(false); cin.tie(NULL)
#define pii pair<int, int>
#define ll long long
int N;
ll num[10];
void add(ll n, ll mul) {
while (n > 0) {
num[n % 10] += mul;
n /= 10;
}
}
void recul(ll A, ll B, ll mul) {
while (A % 10 != 0 && A <= B) {
add(A, mul);
A++;
}
if (A > B) return;
while (B % 10 != 9 && B >= A) {
add(B, mul);
B--;
}
for (int i = 0; i < 10; i++)
{
num[i] += (B / 10 - A / 10 + 1) * mul;
}
recul(A / 10, B / 10, mul * 10);
}
int main(void) {
FIO;
cin >> N;
recul(1, N, 1);
for (int i = 0; i < 10; i++)
{
cout << num[i] << " ";
}
} | [
"[email protected]"
] | |
cd0fb6807623012565ec49e04f3172b2997a742f | a2e9639153e71dcf84d34b7349d69aa31b2eb678 | /zBTLC/zBTLC/game_sa/CTaskSimpleDead.h | 62b08956c657d2e11474d316b51116d5b1196ebe | [] | no_license | DaDj/GTA-BTLC | ade014b3d8dbb1ecce6422328be95631226cd6f4 | 15d60cb5d5f14291317235066d64a639fffaf3ea | refs/heads/master | 2023-08-16T23:12:57.867204 | 2023-08-13T21:45:06 | 2023-08-13T21:45:06 | 83,485,003 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 248 | h | #pragma once
#include "plbase/PluginBase_SA.h"
#include "CTaskSimple.h"
class CTaskSimpleDead : public CTaskSimple {
protected:
CTaskSimpleDead(plugin::dummy_func_t a) : CTaskSimple(a) {}
public:
};
//VALIDATE_SIZE(CTaskSimpleDead, 0x); | [
"[email protected]"
] | |
6edc811bc76ecc7661ac04e514d5ec2ad8d7478b | d6f55d40bdddd5b08c81ed5e0ae19cac9e492b80 | /my codes/after mid/midpoint.cpp | 81d55f766909cdb66839653ae8aebe7bbfc71939 | [] | no_license | Hasanul-Bari/numerical-code | 6b175b27322ac8f0c8a7535ed989a892d544736a | c3380659fb22276b14570d5ce1cc6ea45e9358ca | refs/heads/master | 2021-05-17T02:25:54.999609 | 2020-12-31T14:06:22 | 2020-12-31T14:06:22 | 250,575,032 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 778 | cpp | #include<iostream>
#include<cmath>
using namespace std;
double func(double x)
{
// x=x*(3.142/180.0);
return 1.0/(1.0+pow(x,5));
}
int main()
{
double a,b,h,n;
cout<<"Enter the lower limit : "<<endl;
cin>>a;
cout<<"Enter the upper limit : "<<endl;
cin>>b;
cout<<"Enter the number of intervals"<<endl;
cin>>n;
h=(b-a)/n;
//cout<<h<<endl;
int size=int(n);
double p[size+1];
p[0]=a;
for(int i=1; i<=size; i++)
{
p[i]=p[i-1]+h;
}
double midp [size];
double ans=0;
for(int i=0; i<size; i++)
{
midp[i]=(p[i]+p[i+1])/2.0;
//cout<<midp[i]<<" ";
//cout<<func(midp[i])<<" ";
//cout<<endl;
ans=ans+func(midp[i]);
}
cout<<ans*h<<endl;
}
| [
"[email protected]"
] | |
e78e38b3732c600ab004fde7effbc3bddd6c2dfb | 669867cdb1b238f899abb149d17a4a495d638e92 | /Source/3rdParty/PlayRho/Dynamics/Contacts/PositionConstraint.hpp | 71d77507db4beea622e4ca6f36676936e7004986 | [
"MIT"
] | permissive | Jilliana8397/Dorothy-SSR | 208bbee37d0445f8f84f160cf9e22f34699c20ac | 5ad647909c5e20cb7ebde9a1a054cdb944969dcb | refs/heads/main | 2023-06-15T20:35:26.750737 | 2021-07-16T02:02:31 | 2021-07-16T02:02:31 | 387,440,975 | 1 | 0 | NOASSERTION | 2021-07-19T11:30:23 | 2021-07-19T11:30:22 | null | UTF-8 | C++ | false | false | 2,553 | hpp | /*
* Original work Copyright (c) 2006-2009 Erin Catto http://www.box2d.org
* Modified work Copyright (c) 2020 Louis Langholtz https://github.com/louis-langholtz/PlayRho
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#ifndef PLAYRHO_DYNAMICS_CONTACTS_POSITIONCONSTRAINT_HPP
#define PLAYRHO_DYNAMICS_CONTACTS_POSITIONCONSTRAINT_HPP
#include "PlayRho/Collision/Manifold.hpp"
#include "PlayRho/Dynamics/Contacts/BodyConstraint.hpp"
namespace playrho {
namespace d2 {
/// @brief The per-contact position constraint data structure.
class PositionConstraint
{
public:
PositionConstraint() = default;
/// @brief Initializing constructor.
PositionConstraint(const Manifold& m, BodyID bA, BodyID bB, Length radius)
: manifold{m}, m_bodyA{bA}, m_bodyB{bB}, m_totalRadius{radius}
{
assert(m.GetPointCount() > 0);
assert(bA != bB);
assert(radius >= 0_m);
}
Manifold manifold; ///< Copy of contact's manifold with 1 or more contact points (64-bytes).
/// @brief Gets body A.
BodyID GetBodyA() const noexcept
{
return m_bodyA;
}
/// @brief Gets body B.
BodyID GetBodyB() const noexcept
{
return m_bodyB;
}
/// @brief Gets total radius - i.e. combined radius of shapes of fixtures A and B.
Length GetTotalRadius() const noexcept
{
return m_totalRadius;
}
private:
BodyID m_bodyA; ///< Identifier for body-A.
BodyID m_bodyB; ///< Identifier for body-B.
/// @brief Total "Radius" distance of the associated shapes of fixture A and fixture B.
/// @note 0 or greater.
Length m_totalRadius; // 4-bytes.
};
} // namespace d2
} // namespace playrho
#endif // PLAYRHO_DYNAMICS_CONTACTS_POSITIONCONSTRAINT_HPP
| [
"[email protected]"
] | |
e34491c69c229a5070929b9c6b21cf886d41ca8a | 36183993b144b873d4d53e7b0f0dfebedcb77730 | /GameDevelopment/Game Programming Gems 2/SourceCode/06 Audio Programming/05 Patterson/Sequence.h | 5dc383cd7773e6be06f39815a1c0c4c01e868cdf | [] | no_license | alecnunn/bookresources | b95bf62dda3eb9b0ba0fb4e56025c5c7b6d605c0 | 4562f6430af5afffde790c42d0f3a33176d8003b | refs/heads/master | 2020-04-12T22:28:54.275703 | 2018-12-22T09:00:31 | 2018-12-22T09:00:31 | 162,790,540 | 20 | 14 | null | null | null | null | UTF-8 | C++ | false | false | 965 | h | /* Copyright (C) Scott Patterson, 2001.
* All rights reserved worldwide.
*
* This software is provided "as is" without express or implied
* warranties. You may freely copy and compile this source into
* applications you distribute provided that the copyright text
* below is included in the resulting source code, for example:
* "Portions Copyright (C) Scott Patterson, 2001"
*/
// Sequence.h
#ifndef SEQUENCE_H
#define SEQUENCE_H
#include "Def.h"
#include "Track.h"
class SequenceState_t {
public:
Tempo_t m_Tempo;
Volume_t m_Volume;
};
class Sequence_t {
public:
bool m_bActive; // this sequence is playing
SequenceState_t m_State;
TimeFrac_t m_Ppq; // parts per quarter note
TimeFrac_t m_TimeElapsedFrac;
TimeFrac_t m_TimeStep;
TrackPtrList_t m_TrackPtrList;
};
typedef std::vector< Sequence_t > SequenceVector_t;
typedef std::list< Sequence_t * > SequencePtrList_t;
#endif | [
"[email protected]"
] | |
5a78c7f38dde48fd70e3c4f9d3fc3c68328faca0 | 872f0d7e0d65bb5b67dcd633d3f14ff9c74177fb | /src/methyGff.cpp | a60ce29003f9f37eb7b5527b7e5f3c2752677f41 | [] | no_license | jingquanlim/BatMeth2 | e9e76c96223c66b47046dea8e53e8c8d289b77b2 | 849acf53822bb4e7c584d21d66795c29560f9f9a | refs/heads/master | 2021-04-30T01:49:30.678325 | 2018-01-31T09:24:49 | 2018-01-31T09:24:49 | 121,491,160 | 0 | 0 | null | 2018-02-14T09:12:46 | 2018-02-14T09:12:46 | null | UTF-8 | C++ | false | false | 49,366 | cpp | #include <iostream>
#include <string.h>
#include <cstdio>
#include <assert.h>
#include <cstdlib>
#include <string>
#include <math.h>
#include "limits.h"
#include <map>
#include <sstream>
#define CHROMSIZE 100
#define BATBUF 2000
struct Methy_Hash
{
int *plusMethyratio,*plusCount_C,*plusCount_CT;
int *NegMethyratio,*NegCount_C,*NegCount_CT;
int *plusMethContext;
int *NegMethContext;
int Index;
// int *binsPlusCount_C,*binsPlusCount_CT;
// int *binsNegCount_C,*binsNegCount_CT;
};
struct GeneDensity
{
long *plusGeneDensity;
long *NegGeneDensity;
unsigned *PN_Cover;
unsigned *plusCover;
unsigned *NegCover;
int Index;
};
struct Methy_Gff
{
long *CG_C,*CHG_C,*CHH_C;
long *CG_CT,*CHG_CT,*CHH_CT; // density plot
long AverPerCG,AverPerCHG,AverPerCHH; //DM
long AverCG,AverCHG,AverCHH;
int countCG,countCHG,countCHH;
//int *MethContext;
int Index;
};
using namespace std;
bool Collision=false;
map <string,int> String_Hash;
map <string,int> Context_Hash;
//{----------------------------- FUNCTION PRTOTYPES -------------------------------------------------
FILE* File_Open(const char* File_Name,const char* Mode);
void Show_Progress(float Percentage);
void caculate(int start,int end,Methy_Hash MethyList,char Strand,Methy_Gff & methGff_List);
void caculate(int start,int end,Methy_Hash MethyList,char Strand,Methy_Gff & methGff_List,GeneDensity & GeneD_List);
void caculateHeatmap(const char* type,int start,int end,Methy_Hash MethyList,char Strand,const char* id,FILE *methGffcg,FILE *methGffchg,FILE *methGffchh,char* chrom, bool printtitle=true);
#define Init_Progress() printf("======================]\r[");//progress bar....
#define Done_Progress() printf("\r[++++++++ 100%% ++++++++]\n");//progress bar....
unsigned u=0;
unsigned Total_Reads;//total hits in the input file...
float binspan=0.025;
unsigned nLevel=ceil(1/(double)binspan)-1;//
void int2str(int &int_temp,string &string_temp)
{
stringstream stream;
stream<<int_temp;
string_temp=stream.str();
}
void unsigned2str(unsigned &int_temp,string &string_temp)
{
stringstream stream;
stream<<int_temp;
string_temp=stream.str();
}
void str2int(int &int_temp,string &string_temp)
{
stringstream stream(string_temp);
stream>>int_temp;
}
//}----------------------------- GLOBAL VARIABLES -------------------------------------------------
const int INITIAL_PROGRESS_READS =1000;//progress bar initial count..
long AverPerCG=0,AverPerCHG=0,AverPerCHH=0;
long AverCG=0,AverCHG=0,AverCHH=0;
int main(int argc, char* argv[])
{
time_t Start_Time,End_Time;
printf("\nBatMeth2: MethyGff v1.0\n");
const char* Help_String="Command Format : methyGff [options] -o <OUT_PREFIX> -G GENOME -gff <GFF file>/-gtf <GTF file>/-b <bed file> -m <from Split methratio outfile> [-B] [-P]\n"
"\nUsage:\n"
"\t-o|--out Output file prefix\n"
"\t-G|--genome Genome\n"
"\t-m|--methratio Methratio output file.\n"
"\t-C|--coverage >= <INT> coverage. default:5\n"
"\t-nC >= <INT> Cs per bins or genes. default:5\n"
"\t-gtf|-gff Gtf/gff file\n"
"\t-b|--BED Bed file\n"
//"\t--bins DMR bins step, default 1000bp.\n"
"\t-d|--distance DNA methylation level distributions in body and <INT>-bp flanking sequences. The distance of upstream and downstream. default:2000\n"
"\t-B|--body For different analysis input format, gene/TEs body methylation level. [Different Methylation Gene(DMG/DMT...)]\n"
"\t-P|--promoter For different analysis input format.[Different Methylation Promoter(DMP)]\n"
"\t--TSS Caculate heatmap for TSS. [Outfile: outPrefix.TSS.cg.n.txt]\n"
"\t--TTS Caculate heatmap for TTS. [Outfile: outPrefix.TTS.cg.n.txt] \n"
"\t--GENE Caculate heatmap for GENE and flank 2k. [Outfile: outPrefix.GENE.cg.n.txt] \n"
"\t-s|--step Gene body and their flanking sequences using an overlapping sliding window of 5% of the sequence length at a step of 2.5% of the sequence length. So default step: 0.025 (2.5%)\n"
"\t-S|--chromStep Caculate the density of genes/TEs in chromsome using an overlapping sliding window of 100000bp at a step of 50000bp, must equal \"-s\" in Split.. default step: 50000(bp)\n"//
"\t-h|--help";
int Genome_CountX=0;
char* Output_Name;
//char* methInfileName;
int InFileStart=0,InFileEnd=0;
string Geno;
char *InFile;
bool InputGff=false;
int GffInFileStart=0,GffInFileEnd=0;
bool InputBed=false;
int BedInFileStart=0,BedInFileEnd=0;
int distance=2000;
int distanceHeatmap=2000;
int chromStep=50000;
int binsStep=1000;
bool Diff=false;
bool PU=false;
bool TSS=false;
bool TTS=false;
bool GENE=false;
bool GTF=false;
int Coverage = 5;
int nC=5;
//
if(argc<8)
{
printf("%s \n",Help_String);
exit(0);
}
for(int i=1;i<argc;i++)
{
if(!strcmp(argv[i], "-o") ||!strcmp(argv[i], "--out") )
{
Output_Name=argv[++i];
}
else if(!strcmp(argv[i], "-G") || !strcmp(argv[i], "--genome"))
{
Geno=argv[++i];
}else if(!strcmp(argv[i], "-C") || !strcmp(argv[i], "--coverage"))
{
Coverage=atoi(argv[++i]);
}else if(!strcmp(argv[i], "-nC"))
{
nC=atoi(argv[++i]);
}
else if(!strcmp(argv[i], "-s") || !strcmp(argv[i], "--step"))
{
binspan=atof(argv[++i]);
nLevel=ceil(1/(double)binspan)-1;
printf("binspn: %f, nLevel: %d\n", binspan, nLevel);
}
else if(!strcmp(argv[i], "--bins"))
{
binsStep=atoi(argv[++i]);
}
else if(!strcmp(argv[i], "-B") || !strcmp(argv[i], "--body"))
{
Diff=true;
}
else if(!strcmp(argv[i], "-P") || !strcmp(argv[i], "--promoter"))
{
PU=true;//promoter UP
}
else if( !strcmp(argv[i], "--TSS"))
{
TSS=true;//promoter UP
}
else if( !strcmp(argv[i], "--TTS"))
{
TTS=true;//promoter UP
}
else if( !strcmp(argv[i], "--GENE"))
{
GENE=true;//promoter UP
}
else if(!strcmp(argv[i], "-S") || !strcmp(argv[i], "--chromStep"))
{
chromStep=atoi(argv[++i]);
}
else if(!strcmp(argv[i], "-d") || !strcmp(argv[i], "--distance"))
{
distance=atoi(argv[++i]);
distanceHeatmap = distance;
}
else if(!strcmp(argv[i],"-m") || !strcmp(argv[i],"--methratio"))
{
InFileStart=++i;
while(i!=(argc-1) && argv[i][0]!='-'){i++;continue;}
if(argv[i][0]=='-') {InFileEnd=--i;}else {InFileEnd=i ;}
//methInfileName=argv[++i];
}
else if(!strcmp(argv[i], "-gtf") || !strcmp(argv[i], "-gff"))
{
InputGff=true;
if(!strcmp(argv[i], "-gtf")) GTF=true;
GffInFileStart=++i;
while(i!=(argc-1) && argv[i][0]!='-'){i++;continue;}
if(argv[i][0]=='-') {GffInFileEnd=--i;}else {GffInFileEnd=i ;}
}else if(!strcmp(argv[i], "-b") || !strcmp(argv[i], "--BED"))
{
InputBed=true;
BedInFileStart=++i;
while(i!=(argc-1) && argv[i][0]!='-'){i++;continue;}
if(argv[i][0]=='-') {BedInFileEnd=--i;}else {BedInFileEnd=i ;}
}
else
{
printf("%s \n",Help_String);
exit(0);
}
}
if (argc >1)
{
try
{
time(&Start_Time);
string L=Geno;L+=".ann.location";
FILE* Location_File=File_Open(L.c_str(),"r");
printf("LocationFile: %s\n",L.c_str() );
struct Offset_Record
{
char Genome[40];
unsigned Offset;
} Temp_OR;
while (fgets(Temp_OR.Genome,39,Location_File)!=0)//count genomes..
{
fgets(Temp_OR.Genome,39,Location_File);
Genome_CountX++;
}
rewind(Location_File);
Offset_Record Genome_Offsets[Genome_CountX+1];
int Genome_Count=0;
while (fgets(Genome_Offsets[Genome_Count].Genome,39,Location_File)!=0 && Genome_Count<=Genome_CountX)
{
Genome_Offsets[Genome_Count].Offset=atoi(Genome_Offsets[Genome_Count].Genome);
fgets(Genome_Offsets[Genome_Count].Genome,39,Location_File);
for(int i=0;i<40;i++)
{
if (Genome_Offsets[Genome_Count].Genome[i] == '\n' ||Genome_Offsets[Genome_Count].Genome[i] == '\r')
{
Genome_Offsets[Genome_Count].Genome[i]=0;
break;
}
}
Genome_Count++;
}
Genome_Count--;
GeneDensity GeneD_List[Genome_Count];
Methy_Hash Methy_List[Genome_Count];
for ( int i=0;i<Genome_Count;i++)//Stores the location in value corresponding to has..
{
printf("%s, ",Genome_Offsets[i].Genome);
String_Hash[Genome_Offsets[i].Genome]=i;
//meth ini
Methy_List[i].plusMethContext =new int[Genome_Offsets[i+1].Offset];
Methy_List[i].NegMethContext =new int[Genome_Offsets[i+1].Offset];
Methy_List[i].plusMethyratio = new int[Genome_Offsets[i+1].Offset];
Methy_List[i].plusCount_C = new int[Genome_Offsets[i+1].Offset];
Methy_List[i].plusCount_CT = new int[Genome_Offsets[i+1].Offset];
Methy_List[i].NegMethyratio = new int[Genome_Offsets[i+1].Offset];
Methy_List[i].NegCount_C = new int[Genome_Offsets[i+1].Offset];
Methy_List[i].NegCount_CT = new int[Genome_Offsets[i+1].Offset];
Methy_List[i].Index=i;
//Methy_List[i].binsPlusCount_C =new int[(int)ceil((double)Genome_Offsets[i+1].Offset/binsStep)];
//Methy_List[i].binsPlusCount_CT =new int[(int)ceil((double)Genome_Offsets[i+1].Offset/binsStep)];
//Methy_List[i].binsNegCount_C =new int[(int)ceil((double)Genome_Offsets[i+1].Offset/binsStep)];
//Methy_List[i].binsNegCount_CT =new int[(int)ceil((double)Genome_Offsets[i+1].Offset/binsStep)];
unsigned len=ceil(Genome_Offsets[i+1].Offset/double(chromStep))-1;
GeneD_List[i].plusGeneDensity=new long[len];
GeneD_List[i].NegGeneDensity=new long[len];
GeneD_List[i].PN_Cover=new unsigned[Genome_Offsets[i+1].Offset];
GeneD_List[i].plusCover=new unsigned[Genome_Offsets[i+1].Offset];
GeneD_List[i].NegCover=new unsigned[Genome_Offsets[i+1].Offset];
GeneD_List[i].Index=i;
}
printf("Loaded\n");
string CG="CG",CHG="CHG",CHH="CHH";
Context_Hash[CG.c_str()]=1;Context_Hash[CHG.c_str()]=2;Context_Hash[CHH.c_str()]=3;
unsigned pos;float methratio=0;int countC=0,countCT=0;
//int revG=0,revGA=0;
//start to read batman hit file
char Buf[BATBUF],Meth[BATBUF],Chrom[CHROMSIZE], noChrom[CHROMSIZE], Strand,context[BATBUF],effCT[BATBUF];
printf("\nLoading methyratio file...\n");
FILE* INFILE;//=File_Open(methInfileName,"r");
for(int f=InFileStart;f<=InFileEnd;f++)
{
INFILE=File_Open(argv[f],"r");
int Progress=0;unsigned Number_of_Tags=INITIAL_PROGRESS_READS;
fseek(INFILE, 0L, SEEK_END);off64_t File_Size=ftello64(INFILE);rewind(INFILE);
Init_Progress();
fgets(Buf,BATBUF,INFILE);//read first header marker..
while (!feof(INFILE))
{
Total_Reads++;
Progress++;
if (Progress>Number_of_Tags)
{
off64_t Current_Pos=ftello64(INFILE);
off64_t Average_Length=Current_Pos/Total_Reads+1;//+1 avoids divide by zero..
Number_of_Tags=(File_Size/Average_Length)/20;
Progress=0;
Show_Progress(Current_Pos*100/File_Size);
}
fgets(Meth,BATBUF,INFILE);
// sscanf(Meth,"%s%u%s%s%*s%*s%d%d",Chrom,&pos,&Strand,context,&countC,&countCT);//,&revG,&revGA
sscanf(Meth,"%s%u%s%s%d%d",Chrom,&pos,&Strand,context,&countC,&countCT);
if(countCT<Coverage) continue;
if(countC > countCT) printf("Wrong pos %d, %d %d\n", pos, countC, countCT);
int H=String_Hash[Chrom];
pos--;//0-- for array start 0
//int whichBins = (int)floor((double)pos/binsStep);//1000
if(Strand=='+')
{
Methy_List[H].plusMethContext[pos]=Context_Hash[context];
Methy_List[H].plusCount_C[pos]=countC;
Methy_List[H].plusCount_CT[pos]=countCT;
//Methy_List[H].binsPlusCount_C[whichBins]+=countC;
//Methy_List[H].binsPlusCount_CT[whichBins]+=countCT;
}else if(Strand=='-')
{
Methy_List[H].NegMethContext[pos]=Context_Hash[context];
Methy_List[H].NegCount_C[pos]=countC;
Methy_List[H].NegCount_CT[pos]=countCT;
//Methy_List[H].binsNegCount_C[whichBins]+=countC;
//Methy_List[H].binsNegCount_CT[whichBins]+=countCT;
}else printf("wrong strand...\n");
}//end read file while
Done_Progress();
} //end foreach meth file
printf("Methratio file Loaded.\n");
//
Methy_Gff methGff_List[3];
for ( int i=0;i<3;i++)
{//0--UP 1--BODY 2--DOWN
methGff_List[i].CG_C=new long[nLevel];
methGff_List[i].CHG_C=new long[nLevel];
methGff_List[i].CHH_C=new long[nLevel];
methGff_List[i].CG_CT=new long[nLevel];
methGff_List[i].CHG_CT=new long[nLevel];
methGff_List[i].CHH_CT=new long[nLevel];
methGff_List[i].AverPerCG=0;
methGff_List[i].AverPerCHG=0;
methGff_List[i].AverPerCHH=0;
methGff_List[i].AverCG=0;
methGff_List[i].AverCHG=0;
methGff_List[i].AverCHH=0;
methGff_List[i].countCG=0;
methGff_List[i].countCHG=0;
methGff_List[i].countCHH=0;
methGff_List[i].Index=i;
}
string du[3];
du[0]="UP";du[1]="BODY";du[2]="DOWN";
int FileS=0,FileE=0;
if(InputGff)
{
FileS=GffInFileStart;
FileE=GffInFileEnd;
}else if(InputBed)
{
FileS=BedInFileStart;
FileE=BedInFileEnd;
}else
{
fprintf(stderr,"\nNo input Gff/Bed file .\n");
exit(0);
}
for(int f=FileS;f<=FileE;f++){
AverPerCG=0;AverPerCHG=0;AverPerCHH=0;AverCG=0;AverCHG=0;AverCHH=0;
printf("\nProcessing %d out of %d. InFile: %s", f-FileS+1,FileE-FileS+1, argv[f]);
FILE* GFFINFILE=File_Open(argv[f],"r");
bool bed4 = false; int showbed = 0;
int filelen = strlen(argv[f]);
if(filelen>3 && argv[f][filelen-4]=='b' && argv[f][filelen-3]=='e' && argv[f][filelen-2]=='d' && argv[f][filelen-1]=='4' )
bed4 = true;
char T[100];sprintf (T, "%s.AverMethylevel.%d.txt", Output_Name, f-FileS+1);
//gene body && Promoter
char G_cg[100];sprintf (G_cg, "%s.body.cg.%d.txt", Output_Name, f-FileS+1);
char G_chg[100];sprintf (G_chg, "%s.body.chg.%d.txt", Output_Name, f-FileS+1);
char G_chh[100];sprintf (G_chh, "%s.body.chh.%d.txt", Output_Name, f-FileS+1);
char P_cg[100];sprintf (P_cg, "%s.Promoter.cg.%d.txt", Output_Name, f-FileS+1);
char P_chg[100];sprintf (P_chg, "%s.Promoter.chg.%d.txt", Output_Name, f-FileS+1);
char P_chh[100];sprintf (P_chh, "%s.Promoter.chh.%d.txt", Output_Name, f-FileS+1);
char mode[10];
strcpy(mode, "aw+");
if(f == FileS) strcpy(mode, "w");
//
FILE* MethGffbodyOUTFILEcg;
FILE* MethGffbodyOUTFILEchg;
FILE* MethGffbodyOUTFILEchh;
if(Diff)
{
MethGffbodyOUTFILEcg=File_Open(G_cg,mode);
MethGffbodyOUTFILEchg=File_Open(G_chg,mode);
MethGffbodyOUTFILEchh=File_Open(G_chh,mode);
}
FILE* MethGffpromoterOUTFILEcg;
FILE* MethGffpromoterOUTFILEchg;
FILE* MethGffpromoterOUTFILEchh;
if(PU){
MethGffpromoterOUTFILEcg=File_Open(P_cg,mode);
MethGffpromoterOUTFILEchg=File_Open(P_chg,mode);
MethGffpromoterOUTFILEchh=File_Open(P_chh,mode);
}
//heatmap
//TSS
char TSS_cg[100];sprintf (TSS_cg, "%s.TSS.cg.%d.txt", Output_Name, f-FileS+1);
char TSS_chg[100];sprintf (TSS_chg, "%s.TSS.chg.%d.txt", Output_Name, f-FileS+1);
char TSS_chh[100];sprintf (TSS_chh, "%s.TSS.chh.%d.txt", Output_Name, f-FileS+1);
FILE* MethGff_TSS_OUTFILEcg;
FILE* MethGff_TSS_OUTFILEchg;
FILE* MethGff_TSS_OUTFILEchh;
if(TSS)
{
MethGff_TSS_OUTFILEcg=File_Open(TSS_cg,mode);
MethGff_TSS_OUTFILEchg=File_Open(TSS_chg,mode);
MethGff_TSS_OUTFILEchh=File_Open(TSS_chh,mode);
}
//TTS
char TTS_cg[100];sprintf (TTS_cg, "%s.TTS.cg.%d.txt", Output_Name, f-FileS+1);
char TTS_chg[100];sprintf (TTS_chg, "%s.TTS.chg.%d.txt", Output_Name, f-FileS+1);
char TTS_chh[100];sprintf (TTS_chh, "%s.TTS.chh.%d.txt", Output_Name, f-FileS+1);
FILE* MethGff_TTS_OUTFILEcg;
FILE* MethGff_TTS_OUTFILEchg;
FILE* MethGff_TTS_OUTFILEchh;
if(TTS)
{
MethGff_TTS_OUTFILEcg=File_Open(TTS_cg,mode);
MethGff_TTS_OUTFILEchg=File_Open(TTS_chg,mode);
MethGff_TTS_OUTFILEchh=File_Open(TTS_chh,mode);
}
//GENE
char GENE_cg[100];sprintf (GENE_cg, "%s.GENE.cg.%d.txt", Output_Name, f-FileS+1);
char GENE_chg[100];sprintf (GENE_chg, "%s.GENE.chg.%d.txt", Output_Name, f-FileS+1);
char GENE_chh[100];sprintf (GENE_chh, "%s.GENE.chh.%d.txt", Output_Name, f-FileS+1);
FILE* MethGff_GENE_OUTFILEcg;
FILE* MethGff_GENE_OUTFILEchg;
FILE* MethGff_GENE_OUTFILEchh;
if(GENE)
{
MethGff_GENE_OUTFILEcg=File_Open(GENE_cg,mode);
MethGff_GENE_OUTFILEchg=File_Open(GENE_chg,mode);
MethGff_GENE_OUTFILEchh=File_Open(GENE_chh,mode);
}
//---------------------------------------------------------------------------
char N[100];sprintf (N, "%s.Methylevel.%d.txt", Output_Name, f-FileS+1);
char D[100];sprintf (D, "%s.annoDensity.%d.txt", Output_Name, f-FileS+1);
//-----------------------------------------------------------------------------------------------
printf("\n------------------------------------------------------------------------------------------------\n");
printf("\nAverage methylation level output file: %s\n",T);
printf("Methylation level output file: %s\n",N);
printf("Gff/Bed density output file: %s\n",D);
if(Diff) printf("Gff/Bed different analysis methylation file: %s.regions.context.%d.txt\n",Output_Name,f-FileS+1);
printf("\n------------------------------------------------------------------------------------------------\n");
//--------------------------------------------------------------------------------------------------
FILE* MethGffAverOUTFILE=File_Open(T,"w");
if(f==FileS) fprintf(MethGffAverOUTFILE,"Context\tRegions\tDNA methylation level\n");
int Progress=0;int Number_of_Tags=INITIAL_PROGRESS_READS;
fseek(GFFINFILE, 0L, SEEK_END);off64_t File_Size=ftello64(GFFINFILE);rewind(GFFINFILE);//
Init_Progress();Total_Reads=0;//
char Gff[BATBUF],temp[BATBUF];
string id="";
char Symbol[BATBUF];
unsigned start=0,end=0;
Strand = '.';
while(!feof(GFFINFILE))
{
Total_Reads++;
Progress++;
if (Progress>Number_of_Tags)
{
off64_t Current_Pos=ftello64(GFFINFILE);
off64_t Average_Length=Current_Pos/Total_Reads+1;//+1 avoids divide by zero..
Number_of_Tags=(File_Size/Average_Length)/20;
Progress=0;
Show_Progress(Current_Pos*100/File_Size);
}
fgets(Gff,BATBUF,GFFINFILE);
//string id="";
if(InputGff)
{
sscanf(Gff,"%s\t%s\t%s\t%u\t%u\t%s\t%s\t%s\t%[^;]",Chrom,temp,temp,&start,&end,temp,&Strand,temp,Symbol);
// if(GTF) sscanf(Gff,"%s\t%s\t%s\t%u\t%u\t%s\t%s\t%s\t%s\t%s",Chrom,temp,temp,&start,&end,temp,&Strand,temp,temp,Symbol);
// else sscanf(Gff,"%s\t%s\t%s\t%u\t%u\t%s\t%s\t%s\t%[^\n\t]",Chrom,temp,temp,&start,&end,temp,&Strand,temp,Symbol);
id = Symbol;
}else if(InputBed)
{
if(bed4){
sscanf(Gff,"%s\t%u\t%u\t%c",Chrom,&start,&end,&Strand);
if(showbed == 0)
{
fprintf(stderr, "bed format and defined strand %c\n", Strand);
showbed = 1;
}
}else{
sscanf(Gff,"%s\t%u\t%u",Chrom,&start,&end);
Strand='.';
if(showbed == 0){
fprintf(stderr, "bed format without strand, if you want define strand, please use bed4 format.\n");
showbed = 1;
}
}
}
if(!strcmp(noChrom, Chrom)) continue;
map<string, int>::iterator it= String_Hash.find(Chrom);
if(it == String_Hash.end()) {
printf("%s not detected meth\n", Chrom);
strcpy(noChrom,Chrom);
continue;
}
int H=String_Hash[Chrom];
if(start>distance && end+distance <Genome_Offsets[H+1].Offset && end-start > nLevel ) //&& end-start > nLevel
{
start--;end--;
if(Strand=='-')
{//Down
caculate(start-distance,start,Methy_List[H],Strand,methGff_List[2]);
if(TTS)
{
caculateHeatmap("TTS",start-distanceHeatmap,start+distanceHeatmap,Methy_List[H],Strand,id.c_str(),MethGff_TTS_OUTFILEcg,MethGff_TTS_OUTFILEchg,MethGff_TTS_OUTFILEchh,Chrom);
}
}else
{//Up
caculate(start-distance,start,Methy_List[H],Strand,methGff_List[0]);
if(TSS)
{
caculateHeatmap("TSS",start-distanceHeatmap,start+distanceHeatmap,Methy_List[H],Strand,id.c_str(),MethGff_TSS_OUTFILEcg,MethGff_TSS_OUTFILEchg,MethGff_TSS_OUTFILEchh,Chrom);
}
if(GENE) {
caculateHeatmap("GENE",start-distanceHeatmap,start,Methy_List[H],Strand,id.c_str(),MethGff_GENE_OUTFILEcg,MethGff_GENE_OUTFILEchg,MethGff_GENE_OUTFILEchh,Chrom,true);
}
}
//body
caculate(start,end,Methy_List[H],Strand,methGff_List[1],GeneD_List[H]);
float binspan_b = binspan;
if(Strand!='-' && GENE){
binspan = binspan/2;
caculateHeatmap("GENE",start,end,Methy_List[H],Strand,id.c_str(),MethGff_GENE_OUTFILEcg,MethGff_GENE_OUTFILEchg,MethGff_GENE_OUTFILEchh,Chrom,false);
binspan = binspan_b;
}
//
if(Strand=='-')
{
caculate(end,end+distance,Methy_List[H],Strand,methGff_List[0]);
if(TSS)
{
caculateHeatmap("TSS",end-distanceHeatmap,end+distanceHeatmap,Methy_List[H],Strand,id.c_str(),MethGff_TSS_OUTFILEcg,MethGff_TSS_OUTFILEchg,MethGff_TSS_OUTFILEchh,Chrom);
}
if(GENE) {
caculateHeatmap("GENE",end,end+distanceHeatmap,Methy_List[H],Strand,id.c_str(),MethGff_GENE_OUTFILEcg,MethGff_GENE_OUTFILEchg,MethGff_GENE_OUTFILEchh,Chrom, true);
}
}else
{//down
caculate(end,end+distance,Methy_List[H],Strand,methGff_List[2]);
if(TTS)
{
caculateHeatmap("TTS",end-distanceHeatmap,end+distanceHeatmap,Methy_List[H],Strand,id.c_str(),MethGff_TTS_OUTFILEcg,MethGff_TTS_OUTFILEchg,MethGff_TTS_OUTFILEchh,Chrom);
}
if(GENE) {
caculateHeatmap("GENE",end, end+distanceHeatmap,Methy_List[H],Strand,id.c_str(),MethGff_GENE_OUTFILEcg,MethGff_GENE_OUTFILEchg,MethGff_GENE_OUTFILEchh,Chrom,false);
}
}
if(Strand=='-' && GENE) {
binspan = binspan/2;
caculateHeatmap("GENE",start,end,Methy_List[H],Strand,id.c_str(),MethGff_GENE_OUTFILEcg,MethGff_GENE_OUTFILEchg,MethGff_GENE_OUTFILEchh,Chrom,false);
binspan = binspan_b;
caculateHeatmap("GENE",start-distanceHeatmap,start,Methy_List[H],Strand,id.c_str(),MethGff_GENE_OUTFILEcg,MethGff_GENE_OUTFILEchg,MethGff_GENE_OUTFILEchh,Chrom,false);
}
if(GENE) {
fprintf(MethGff_GENE_OUTFILEcg, "\n");
fprintf(MethGff_GENE_OUTFILEchg, "\n");
fprintf(MethGff_GENE_OUTFILEchh, "\n");
}
}
//if(Strand=='.') Strand='+';
if(InputBed)
{
string temp="";
unsigned2str(start,temp);
id=Chrom;id+=("."+temp);
unsigned2str(end,temp);
id=id+"."+temp;
}
for(int i=0;i<3;i++)
{
if(i==0 && PU)//Promoter
{
if(methGff_List[i].AverCG>0 && methGff_List[i].countCG >= nC) fprintf(MethGffpromoterOUTFILEcg,"%s\t%d\t%c\tCG\t%d\t%d\t%s\n",Chrom,start,Strand,methGff_List[i].AverPerCG,methGff_List[i].AverCG,id.c_str());
if(methGff_List[i].AverCHG>0 && methGff_List[i].countCHG >= nC) fprintf(MethGffpromoterOUTFILEchg,"%s\t%d\t%c\tCHG\t%d\t%d\t%s\n",Chrom,start,Strand,methGff_List[i].AverPerCHG,methGff_List[i].AverCHG,id.c_str());
if(methGff_List[i].AverCHH>0 && methGff_List[i].countCHH >= nC) fprintf(MethGffpromoterOUTFILEchh,"%s\t%d\t%c\tCHH\t%d\t%d\t%s\n",Chrom,start,Strand,methGff_List[i].AverPerCHH,methGff_List[i].AverCHH,id.c_str());
}
if(i==1 && Diff)//body
{
if(methGff_List[i].AverCG>0 && methGff_List[i].countCG >= nC) fprintf(MethGffbodyOUTFILEcg,"%s\t%d\t%c\tCG\t%d\t%d\t%s\n",Chrom,start,Strand,methGff_List[i].AverPerCG,methGff_List[i].AverCG,id.c_str());
if(methGff_List[i].AverCHG>0 && methGff_List[i].countCHG >= nC) fprintf(MethGffbodyOUTFILEchg,"%s\t%d\t%c\tCHG\t%d\t%d\t%s\n",Chrom,start,Strand,methGff_List[i].AverPerCHG,methGff_List[i].AverCHG,id.c_str());
if(methGff_List[i].AverCHH>0 && methGff_List[i].countCHH >= nC) fprintf(MethGffbodyOUTFILEchh,"%s\t%d\t%c\tCHH\t%d\t%d\t%s\n",Chrom,start,Strand,methGff_List[i].AverPerCHH,methGff_List[i].AverCHH,id.c_str());
}
if(methGff_List[i].AverCG>0 && methGff_List[i].countCG >= nC) fprintf(MethGffAverOUTFILE,"CG\t%s\t%f\n",du[i].c_str(),(double)methGff_List[i].AverPerCG/(double)methGff_List[i].AverCG);
if(methGff_List[i].AverCHG>0 && methGff_List[i].countCHG >= nC) fprintf(MethGffAverOUTFILE,"CHG\t%s\t%f\n",du[i].c_str(),(double)methGff_List[i].AverPerCHG/(double)methGff_List[i].AverCHG);
if(methGff_List[i].AverCHH>0 && methGff_List[i].countCHH >= nC) fprintf(MethGffAverOUTFILE,"CHH\t%s\t%f\n",du[i].c_str(),(double)methGff_List[i].AverPerCHH/(double)methGff_List[i].AverCHH);
}
//
}
fclose(MethGffAverOUTFILE);
FILE* DensityGffOUTFILE=File_Open(D,"w");
for ( int i=0;i<Genome_Count;i++)
{
unsigned pnCoverage=0,plusCoverage=0,NegCoverage=0,pnCoverage_1=0,plusCoverage_1=0,NegCoverage_1=0;int nbins=0;
unsigned len=ceil(Genome_Offsets[i+1].Offset/double(chromStep))-1;
for(int l=0;l<Genome_Offsets[i+1].Offset;l++)
{
pnCoverage+=GeneD_List[i].PN_Cover[l];
plusCoverage+=GeneD_List[i].plusCover[l];
NegCoverage+=GeneD_List[i].NegCover[l];
if( (nbins!=len && l == ((nbins+1)*chromStep)) || l==end){
if(nbins<=len &&nbins>0){
fprintf(DensityGffOUTFILE,"%s\t%d\t%f\t+-\n",Genome_Offsets[i].Genome,nbins-1,(pnCoverage+pnCoverage_1)/(double(chromStep*2)));
fprintf(DensityGffOUTFILE,"%s\t%d\t%f\t+\n",Genome_Offsets[i].Genome,nbins-1,(plusCoverage+plusCoverage_1)/(double(chromStep*2)));
fprintf(DensityGffOUTFILE,"%s\t%d\t-%f\t-\n",Genome_Offsets[i].Genome,nbins-1,(NegCoverage+NegCoverage_1)/(double(chromStep*2)));
}
plusCoverage_1=plusCoverage,NegCoverage_1=NegCoverage,pnCoverage_1=pnCoverage;
nbins++;
plusCoverage=0,NegCoverage=0,pnCoverage=0;
}
}
}
fclose(DensityGffOUTFILE);
FILE* MethGffOUTFILE=File_Open(N,"w");
//CG
fprintf(MethGffOUTFILE,"CG");
for(int i=0;i<3;i++)
{
for(int j=0;j<nLevel;j++)
{
if(methGff_List[i].CG_C[j] > methGff_List[i].CG_CT[j])
printf("\nError bin %d, %ld %ld", i, methGff_List[i].CG_C[j], methGff_List[i].CG_CT[j]);
fprintf(MethGffOUTFILE,"\t%f",(double)methGff_List[i].CG_C[j]/(double)methGff_List[i].CG_CT[j]);
}
}
//CHG
fprintf(MethGffOUTFILE,"\nCHG");
for(int i=0;i<3;i++)
{
for(int j=0;j<nLevel;j++)
{
fprintf(MethGffOUTFILE,"\t%f",(double)methGff_List[i].CHG_C[j]/(double)methGff_List[i].CHG_CT[j]);
}
}
//CHH
fprintf(MethGffOUTFILE,"\nCHH");
for(int i=0;i<3;i++)
{
for(int j=0;j<nLevel;j++)
{
fprintf(MethGffOUTFILE,"\t%f",(double)methGff_List[i].CHH_C[j]/(double)methGff_List[i].CHH_CT[j]);
}
}
fprintf(MethGffOUTFILE,"\n");
fclose(MethGffOUTFILE);
Done_Progress();
printf("\n%s\nC : %f\n",argv[f],(double)(AverPerCG+AverPerCHG+AverPerCHH)/(double)(AverCG+AverCHG+AverCHH) );//AverPerCHG
printf("CG : %f\n",(double)AverPerCG/(double)AverCG);
printf("CHG : %f\n",(double)AverPerCHG/(double)AverCHG);
printf("CHH : %f\n",(double)AverPerCHH/(double)AverCHH);
}
//delete
for ( int i=0;i<Genome_Count;i++)//Stores the location in value corresponding to has..
{
delete[] Methy_List[i].plusMethContext;
delete[] Methy_List[i].NegMethContext;
delete[] Methy_List[i].plusMethyratio;
delete[] Methy_List[i].plusCount_C ;
delete[] Methy_List[i].plusCount_CT ;
delete[] Methy_List[i].NegMethyratio ;
delete[] Methy_List[i].NegCount_C;
delete[] Methy_List[i].NegCount_CT;
delete[] GeneD_List[i].plusGeneDensity;
delete[] GeneD_List[i].NegGeneDensity;
delete[] GeneD_List[i].PN_Cover;
delete[] GeneD_List[i].plusCover;
delete[] GeneD_List[i].NegCover;
}
for ( int i=0;i<3;i++)
{//0--UP 1--BODY 2--DOWN
delete[] methGff_List[i].CG_C;
delete[] methGff_List[i].CHG_C;
delete[] methGff_List[i].CHH_C;
delete[] methGff_List[i].CG_CT;
delete[] methGff_List[i].CHG_CT;
delete[] methGff_List[i].CHH_CT;
}
}
catch(char* Err)
{
printf(Err);
exit(-1);
}
time(&End_Time);printf("\nTime Taken - %.0lf Seconds ..\n ",difftime(End_Time,Start_Time));
}
else
printf("%s \n",Help_String);
}
//{----------------------------------- FILE HANDLING ---------------------------------------------------------
/*
* === FUNCTION ======================================================================
* Name: File_Open
* Description: Open a file:
* Mode - "w" create/Write text from top - "wb" Write/Binary -"w+" open text read/write -"w+b" same as prev/Binary
* "r" Read text from top - "rb" Read/Binary -"r+" open text read/write/nocreate -"r+b" same as prev/binary
* - "a" text append/write -"a+" text open file read/append -"a+b" open binary read/append
*
* =====================================================================================
*/
FILE* File_Open(const char* File_Name,const char* Mode)
{
FILE* Handle;
Handle=fopen64(File_Name,Mode);
if (Handle==NULL)
{
printf("File %s Cannot be opened ....",File_Name);
exit(1);
}
else return Handle;
}
//}----------------------------------- FILE HANDLING ---------------------------------------------------------
void Show_Progress(float Percentage)
{
if (Percentage >98) return;
printf("+%.0f%\b\b\b",Percentage);
fflush(stdout);
}
void caculate(int start,int end,Methy_Hash MethyList,char Strand,Methy_Gff & methGff_List,GeneDensity & GeneD_List){
int step = floor((double(end - start))*binspan);// 5% 2.5% step
int nbins=0;
methGff_List.AverPerCG=0;methGff_List.AverCG=0;
methGff_List.AverPerCHG=0;methGff_List.AverCHG=0;
methGff_List.AverPerCHH=0;methGff_List.AverCHH=0;
unsigned long countperCG=0,countperCHG=0,countperCHH=0,countCG=0,countCHG=0,countCHH=0;
unsigned long countperCG_1=0,countperCHG_1=0,countperCHH_1=0,countCG_1=0,countCHG_1=0,countCHH_1=0;
for(int i=start;i<=end;i++)
{
GeneD_List.PN_Cover[i]=1;
//context
if(Strand=='+' || Strand=='.')
{
GeneD_List.plusCover[i]=1;
if( MethyList.plusMethContext[i] ==1 ){
countperCG+= MethyList.plusCount_C[i];
countCG+=MethyList.plusCount_CT[i];
methGff_List.AverPerCG +=MethyList.plusCount_C[i];
methGff_List.AverCG +=MethyList.plusCount_CT[i];
AverPerCG +=MethyList.plusCount_C[i];
AverCG +=MethyList.plusCount_CT[i];
methGff_List.countCG++;
}else if( MethyList.plusMethContext[i] ==2 ){
countperCHG+=MethyList.plusCount_C[i];
countCHG+=MethyList.plusCount_CT[i];
methGff_List.AverPerCHG +=MethyList.plusCount_C[i];
methGff_List.AverCHG += MethyList.plusCount_CT[i];
AverPerCHG +=MethyList.plusCount_C[i];
AverCHG +=MethyList.plusCount_CT[i];
methGff_List.countCHG++;
}else if( MethyList.plusMethContext[i] ==3 ){
countperCHH+=MethyList.plusCount_C[i];
countCHH+=MethyList.plusCount_CT[i];
methGff_List.AverPerCHH +=MethyList.plusCount_C[i];
methGff_List.AverCHH +=MethyList.plusCount_CT[i];
AverPerCHH +=MethyList.plusCount_C[i];
AverCHH +=MethyList.plusCount_CT[i];
methGff_List.countCHH++;
}
}
if(Strand=='-' || Strand=='.')
{
GeneD_List.NegCover[i]=1;
if( MethyList.NegMethContext[i] ==1 ){
countperCG+= MethyList.NegCount_C[i];
countCG+=MethyList.NegCount_CT[i];
methGff_List.AverPerCG +=MethyList.NegCount_C[i];
methGff_List.AverCG +=MethyList.NegCount_CT[i];
AverPerCG +=MethyList.NegCount_C[i];
AverCG +=MethyList.NegCount_CT[i];
methGff_List.countCG++;
}else if( MethyList.NegMethContext[i] ==2 ){
countperCHG+=MethyList.NegCount_C[i];
countCHG+=MethyList.NegCount_CT[i];
methGff_List.AverPerCHG +=MethyList.NegCount_C[i];
methGff_List.AverCHG += MethyList.NegCount_CT[i];
AverPerCHG +=MethyList.NegCount_C[i];
AverCHG +=MethyList.NegCount_CT[i];
methGff_List.countCHG++;
}else if( MethyList.NegMethContext[i] ==3 ){
countperCHH+=MethyList.NegCount_C[i];
countCHH+=MethyList.NegCount_CT[i];
methGff_List.AverPerCHH +=MethyList.NegCount_C[i];
methGff_List.AverCHH +=MethyList.NegCount_CT[i];
AverPerCHH +=MethyList.NegCount_C[i];
AverCHH +=MethyList.NegCount_CT[i];
methGff_List.countCHH++;
}
}
if( (nbins!=nLevel && (i-start) == ((nbins+1)*step)) || i==end){
if(i==end) nbins=nLevel;
if(nbins<=nLevel &&nbins>0){
if(Strand=='+' || Strand=='.')
{
methGff_List.CG_C[nbins-1] += (countperCG+countperCG_1);
methGff_List.CG_CT[nbins-1] += (countCG+countCG_1);
methGff_List.CHG_C[nbins-1] += (countperCHG+countperCHG_1);
methGff_List.CHG_CT[nbins-1] += (countCHG+countCHG_1);
methGff_List.CHH_C[nbins-1] += (countperCHH+countperCHH_1);
methGff_List.CHH_CT[nbins-1] += (countCHH+countCHH_1);
}
else
{
methGff_List.CG_C[nLevel-nbins] += (countperCG+countperCG_1);
methGff_List.CG_CT[nLevel-nbins] += (countCG+countCG_1);
methGff_List.CHG_C[nLevel-nbins] += (countperCHG+countperCHG_1);
methGff_List.CHG_CT[nLevel-nbins] += (countCHG+countCHG_1);
methGff_List.CHH_C[nLevel-nbins] += (countperCHH+countperCHH_1);
methGff_List.CHH_CT[nLevel-nbins] += (countCHH+countCHH_1);
}
}
countperCG_1=countperCG;countperCHG_1=countperCHG;countperCHH_1=countperCHH;countCG_1=countCG;countCHG_1=countCHG;countCHH_1=countCHH;
nbins++;
countperCG=0;countperCHG=0;countperCHH=0;countCG=0;countCHG=0;countCHH=0;
}
}
}
void caculate(int start,int end,Methy_Hash MethyList,char Strand,Methy_Gff & methGff_List){
int step = floor((double(end - start))*binspan);// 5% 2.5% step
int nbins=0;
methGff_List.AverPerCG=0;methGff_List.AverCG=0;
methGff_List.AverPerCHG=0;methGff_List.AverCHG=0;
methGff_List.AverPerCHH=0;methGff_List.AverCHH=0;
unsigned long countperCG=0,countperCHG=0,countperCHH=0,countCG=0,countCHG=0,countCHH=0;
unsigned long countperCG_1=0,countperCHG_1=0,countperCHH_1=0,countCG_1=0,countCHG_1=0,countCHH_1=0;
for(int i=start;i<=end;i++)
{
//context
if(Strand=='+' || Strand=='.')
{
if( MethyList.plusMethContext[i] ==1 ){
countperCG+= MethyList.plusCount_C[i];
countCG+=MethyList.plusCount_CT[i];
methGff_List.AverPerCG +=MethyList.plusCount_C[i];
methGff_List.AverCG +=MethyList.plusCount_CT[i];
methGff_List.countCG++;
}else if( MethyList.plusMethContext[i] ==2 ){
countperCHG+=MethyList.plusCount_C[i];
countCHG+=MethyList.plusCount_CT[i];
methGff_List.AverPerCHG +=MethyList.plusCount_C[i];
methGff_List.AverCHG += MethyList.plusCount_CT[i];
methGff_List.countCHG++;
}else if( MethyList.plusMethContext[i] ==3 ){
countperCHH+=MethyList.plusCount_C[i];
countCHH+=MethyList.plusCount_CT[i];
methGff_List.AverPerCHH +=MethyList.plusCount_C[i];
methGff_List.AverCHH +=MethyList.plusCount_CT[i];
methGff_List.countCHH++;
}
}
if(Strand=='-' || Strand=='.')
{
if( MethyList.NegMethContext[i] ==1 ){
countperCG+= MethyList.NegCount_C[i];
countCG+=MethyList.NegCount_CT[i];
methGff_List.AverPerCG +=MethyList.NegCount_C[i];
methGff_List.AverCG +=MethyList.NegCount_CT[i];
methGff_List.countCG++;
}else if( MethyList.NegMethContext[i] ==2 ){
countperCHG+=MethyList.NegCount_C[i];
countCHG+=MethyList.NegCount_CT[i];
methGff_List.AverPerCHG +=MethyList.NegCount_C[i];
methGff_List.AverCHG += MethyList.NegCount_CT[i];
methGff_List.countCHG++;
}else if( MethyList.NegMethContext[i] ==3 ){
countperCHH+=MethyList.NegCount_C[i];
countCHH+=MethyList.NegCount_CT[i];
methGff_List.AverPerCHH +=MethyList.NegCount_C[i];
methGff_List.AverCHH +=MethyList.NegCount_CT[i];
methGff_List.countCHH++;
}
}
if( (nbins!=nLevel && (i-start) == ((nbins+1)*step)) || i==end){
if(i==end) nbins=nLevel;
if(nbins<=nLevel &&nbins>0){
if(Strand=='+' || Strand=='.')
{
methGff_List.CG_C[nbins-1] += (countperCG+countperCG_1);
methGff_List.CG_CT[nbins-1] += (countCG+countCG_1);
methGff_List.CHG_C[nbins-1] += (countperCHG+countperCHG_1);
methGff_List.CHG_CT[nbins-1] += (countCHG+countCHG_1);
methGff_List.CHH_C[nbins-1] += (countperCHH+countperCHH_1);
methGff_List.CHH_CT[nbins-1] += (countCHH+countCHH_1);
}
else
{
methGff_List.CG_C[nLevel-nbins] += (countperCG+countperCG_1);
methGff_List.CG_CT[nLevel-nbins] += (countCG+countCG_1);
methGff_List.CHG_C[nLevel-nbins] += (countperCHG+countperCHG_1);
methGff_List.CHG_CT[nLevel-nbins] += (countCHG+countCHG_1);
methGff_List.CHH_C[nLevel-nbins] += (countperCHH+countperCHH_1);
methGff_List.CHH_CT[nLevel-nbins] += (countCHH+countCHH_1);
}
}
countperCG_1=countperCG;countperCHG_1=countperCHG;countperCHH_1=countperCHH;countCG_1=countCG;countCHG_1=countCHG;countCHH_1=countCHH;
nbins++;
countperCG=0;countperCHG=0;countperCHH=0;countCG=0;countCHG=0;countCHH=0;
}
}
}
//caculate gene heatmap //http://www.sciencedirect.com/science/article/pii/S0092867413002225 //Fig.6G
void caculateHeatmap(const char* type,int start,int end,Methy_Hash MethyList,char Strand,const char* id,FILE *methGffcg,FILE *methGffchg,FILE *methGffchh,char* chrom, bool printtitle){
int step = floor((double(end - start))*((double)binspan/2)); //5% 2.5% step
unsigned nLevel=ceil(1/((double)binspan/2))-1;
int nbins=0;
double* Smeth_cg=new double[nLevel];double* Smeth_chg=new double[nLevel];double* Smeth_chh=new double[nLevel];
int countperCG=0,countperCHG=0,countperCHH=0,countCG=0,countCHG=0,countCHH=0;
int countperCG_1=0,countperCHG_1=0,countperCHH_1=0,countCG_1=0,NegcountCG_1=0,countCHG_1=0,countCHH_1=0;
for(int i=start;i<=end;i++)
{
//context
if(Strand=='+' || Strand=='.')
{
if( MethyList.plusMethContext[i] ==1 ){
countperCG+= MethyList.plusCount_C[i];
countCG+=MethyList.plusCount_CT[i];
}else if( MethyList.plusMethContext[i] ==2 ){
countperCHG+=MethyList.plusCount_C[i];
countCHG+=MethyList.plusCount_CT[i];
}else if( MethyList.plusMethContext[i] ==3 ){
countperCHH+=MethyList.plusCount_C[i];
countCHH+=MethyList.plusCount_CT[i];
}
}
else if(Strand=='-' )//|| Strand=='.'
{
if( MethyList.NegMethContext[i] ==1 ){
countperCG+= MethyList.NegCount_C[i];
countCG+=MethyList.NegCount_CT[i];
}else if( MethyList.NegMethContext[i] ==2 ){
countperCHG+=MethyList.NegCount_C[i];
countCHG+=MethyList.NegCount_CT[i];
}else if( MethyList.NegMethContext[i] ==3 ){
countperCHH+=MethyList.NegCount_C[i];
countCHH+=MethyList.NegCount_CT[i];
}
}
if( (nbins!=nLevel && (i-start) == ((nbins+1)*step)) || i==end){
if(nbins<=nLevel &&nbins>0){
if(Strand=='+' || Strand=='.')
{
//if(countCG+countCG_1>0) fprintf(methGffcg,"\t%f",double(countperCG+countperCG_1)/double(countCG+countCG_1));
if(countCG+countCG_1>0) Smeth_cg[nbins-1]=double(countperCG+countperCG_1)/(double(countCG+countCG_1));
if(!strcmp(type,"GENE") && countCG+countCG_1<=5) Smeth_cg[nbins-1]=-1;
if(countCHG+countCHG_1>0) Smeth_chg[nbins-1]=double(countperCHG+countperCHG_1)/(double(countCHG+countCHG_1));
if(!strcmp(type,"GENE") &&countCHG+countCHG_1<=5) Smeth_chg[nbins-1] = -1;
if(countCHH+countCHH_1>0) Smeth_chh[nbins-1]=double(countperCHH+countperCHH_1)/(double(countCHH+countCHH_1));
if(!strcmp(type,"GENE") && countCHH+countCHH_1<=5) Smeth_chh[nbins-1]=-1;
}
else
{
if(countCG+countCG_1>0) Smeth_cg[nLevel-nbins]=double(countperCG+countperCG_1)/(double(countCG+countCG_1));
if(!strcmp(type,"GENE") && countCG+countCG_1<=5) Smeth_cg[nLevel-nbins] = -1;
if(countCHG+countCHG_1>0) Smeth_chg[nLevel-nbins]=double(countperCHG+countperCHG_1)/(double(countCHG+countCHG_1));
if(!strcmp(type,"GENE") && countCHG+countCHG_1<=5) Smeth_chg[nLevel-nbins] = -1;
if(countCHH+countCHH_1>0) Smeth_chh[nLevel-nbins]=double(countperCHH+countperCHH_1)/(double(countCHH+countCHH_1));
if(!strcmp(type,"GENE") && countCHH+countCHH_1<=5) Smeth_chh[nLevel-nbins] = -1;
}
}
countperCG_1=countperCG;countperCHG_1=countperCHG;countperCHH_1=countperCHH;countCG_1=countCG;countCHG_1=countCHG;countCHH_1=countCHH;
nbins++;
countperCG=0;countperCHG=0;countperCHH=0;countCG=0;countCHG=0;countCHH=0;
if(i==end) nbins=nLevel;
}
}
if(printtitle && !strcmp(type,"GENE"))
{
fprintf(methGffcg,"%s\t%d\t%d\t%s\t.\t.",chrom,start,end,id);
fprintf(methGffchg,"%s\t%d\t%d\t%s\t.\t.",chrom,start,end,id);
fprintf(methGffchh,"%s\t%d\t%d\t%s\t.\t.",chrom,start,end,id);
}else if(printtitle) {
fprintf(methGffcg,"%s",id);
fprintf(methGffchg,"%s",id);
fprintf(methGffchh,"%s",id);
}
unsigned cut = ceil((double)nLevel/2);
unsigned BeginNo_cg=0,BeginNo_chg=0,BeginNo_chh=0;
//if(!strcmp(type,"TSS"))
{
for(int i=0;i<nLevel;i++)
{
if(BeginNo_cg==0 && !strcmp(type,"TSS"))
{
if(i>=cut )
{
if(Smeth_cg[i]>0) BeginNo_cg=i;
else if(i==nLevel-1) BeginNo_cg=0;
}
}
if(Smeth_cg[i]>1) Smeth_cg[i]=0;
if(Smeth_cg[i] == -1) fprintf(methGffcg,"\tnan");
else
fprintf(methGffcg,"\t%f",Smeth_cg[i]);
if(BeginNo_chg==0 && !strcmp(type,"TSS"))
{
if(i>=cut)
{
if(Smeth_chg[i]>0) BeginNo_chg=i;
else if(i==nLevel-1) BeginNo_chg=0;
}
}
if(Smeth_chg[i]>1) Smeth_chg[i]=0;
if(Smeth_chg[i] == -1) fprintf(methGffchg,"\tnan");
else fprintf(methGffchg,"\t%f",Smeth_chg[i]);
if(BeginNo_chh==0 && !strcmp(type,"TSS"))
{
if(i>=cut)
{
if(Smeth_chh[i]>0) BeginNo_chh=i;
else if(i==nLevel-1) BeginNo_chh=0;
}
}
if(Smeth_chh[i]>1) Smeth_chh[i]=0;
if(Smeth_chh[i] == -1) fprintf(methGffchh,"\tnan");
else fprintf(methGffchh,"\t%f",Smeth_chh[i]);
}
}
if(!strcmp(type,"TTS"))
{
for(int i=nLevel-1;i>=0;i--)
{
if(BeginNo_cg==0)
{
if(i< cut-1 )
{
if(Smeth_cg[i]>0) BeginNo_cg=i;
else if(i==0) BeginNo_cg=cut;
}
}
if(BeginNo_chg==0)
{
if(i<cut-1)
{
if(Smeth_chg[i]>0) BeginNo_chg=i;
else if(i==0) BeginNo_chg=cut;
}
}
if(BeginNo_chh==0)
{
if(i<cut-1)
{
if(Smeth_chh[i]>0) BeginNo_chh=i;
else if(i==0) BeginNo_chh=cut;
}
}
}
}
if(strcmp(type,"GENE")!=0){
fprintf(methGffcg,"\t%d\n",BeginNo_cg);
fprintf(methGffchg,"\t%d\n",BeginNo_chg);
fprintf(methGffchh,"\t%d\n",BeginNo_chh);
}
}
| [
"qwzhou@login.(none)"
] | qwzhou@login.(none) |
1bf91f7626e1e6b488a85d0a4427fd07be18e818 | 88393722c482a885b55329fd227cbaa66fdc9f8d | /Dominio.cpp | 510850a04c63452eb4b7c5a37b2318bf3a2fc211 | [] | no_license | nelleo/Libreria-de-Diccionarios-y-Hashing---C- | f2f5cb2a8f1dcd81be436db0fa36aea9c5f1c7a1 | fa7bfbd407f9ef1809323e19d424eb12c50a6e02 | refs/heads/master | 2020-11-26T15:21:48.027939 | 2019-12-19T19:40:36 | 2019-12-19T19:40:36 | 229,120,688 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,321 | cpp | #include "Dominio.h"
#include <string>
using UndavDominio::Dominio;
using std::string;
struct UndavDominio::Dominio{
string ip;
string dns;
string pais;
string descripcion;
};
Dominio* UndavDominio::Crear(string dns, string ip, string pais, string descripcion){
Dominio* dominio = new Dominio;
dominio->descripcion = descripcion;
dominio->dns = dns;
dominio->ip = ip;
dominio->pais = pais;
return dominio;
}
Dominio* UndavDominio::Crear(string dns, string ip, string pais){
return Crear(dns, ip, pais, "");
}
bool UndavDominio::SonIguales(const Dominio* dominioA, const Dominio* dominioB){
return dominioA->ip == dominioB->ip;
}
string UndavDominio::ObtenerIp(const Dominio* dominio){
return dominio->ip;
}
string UndavDominio::ObtenerDns(const Dominio* dominio){
return dominio->dns;
}
string UndavDominio::ObtenerDescripcion(const Dominio* dominio){
return dominio->descripcion;
}
string UndavDominio::ObtenerPais(const Dominio* dominio){
return dominio->pais;
}
void UndavDominio::CambiarDescripcion(Dominio* dominio, string descripcion){
dominio->descripcion = descripcion;
}
Dominio* UndavDominio::CrearCopia(const Dominio* dominio){
return Crear(dominio->dns, dominio->ip, dominio->pais, dominio->descripcion);
}
void UndavDominio::Destruir(const Dominio* dominio){
delete dominio;
}
| [
"[email protected]"
] | |
d0b7b706ab0c09afee4c3c2b8dee29b5cdde449d | da4c3d153dab76894b1d6142bfd816b5b36df227 | /interface/PurityFit.hpp | dc7f0e492b2706949eaf3feae1630503773a9f82 | [] | no_license | kfiekas/ChargedHiggs | d02e1b50051f674a1b5c3a7dfe2a36d0b1c9c059 | 7e3424b74445b175d1896055f9015e010110128a | refs/heads/master | 2020-05-29T11:52:57.998990 | 2016-02-03T12:59:19 | 2016-02-03T12:59:19 | 37,123,283 | 0 | 0 | null | 2015-06-09T09:36:05 | 2015-06-09T09:36:05 | null | UTF-8 | C++ | false | false | 1,442 | hpp | #ifndef PURITY_FIT_H
#define PURITY_FIT_H
// --- STD ---
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
// --- ROOT ---
#include "TFile.h"
#include "TDirectory.h"
#include "TH1D.h"
#include "TH1F.h"
#include "TCanvas.h"
#include "TROOT.h"
#include "TLatex.h"
#include "TLegend.h"
// --- ROOFIT ---
#include "RooGlobalFunc.h"
#include "RooPlot.h"
#include "RooWorkspace.h"
#include "RooGaussian.h"
#include "RooVoigtian.h"
#include "RooProduct.h"
#include "RooAddition.h"
#include "RooConstVar.h"
#include "RooFormulaVar.h"
#include "RooDataHist.h"
#include "RooRealVar.h"
#include "RooAddPdf.h"
#include "RooHistPdf.h"
#include "RooFitResult.h"
class PurityFit{
protected:
float fit_specific( const TH1* h, const TH1* sig, const TH1* bkg,
string name, // unique name of the result
string outname="" , // output file name, where to save results
map<string,float> *pars =NULL // to gather additional params
);
TFile *fIn_;
public:
PurityFit(){outname="";inname="";verbose_=0;};
~PurityFit(){};
vector<float> PtBins;
string outname;
string inname;
int verbose_;
virtual void init();
virtual void fit();
};
#endif
// Local Variables:
// mode:c++
// indent-tabs-mode:nil
// tab-width:4
// c-basic-offset:4
// End:
// vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
| [
"[email protected]"
] | |
acf5ba790407469704042c116b56968d0408882f | 6e1be414e3aa48f752839cc1437ebba20f11b814 | /camino-minimo-en-una-matriz/src/81-bottom-up.cpp | 4ad3bbf186b9aef75988dec16e45ae50fe583df7 | [] | no_license | msclar/classes | bc623353388f441128efdb4152b49b11550d7b6a | 46f84f770b6bdd125b53a83a9f0428c2be8728aa | refs/heads/master | 2020-04-07T06:49:05.729355 | 2017-09-27T02:00:32 | 2017-09-27T02:00:32 | 45,066,675 | 1 | 1 | null | 2015-10-28T03:24:13 | 2015-10-27T20:01:54 | TeX | UTF-8 | C++ | false | false | 799 | cpp | #include <iostream>
#include <cstdio>
using namespace std;
int main () {
freopen("81.in", "r", stdin);
freopen("81.out", "w", stderr);
int best[128][128], matriz[128][128];
int n = 80;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> matriz[i][j];
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
/* notar que las casillas en la primera columna solo tienen
* una opcion posible. Tambien incluimos aqui el caso base */
if (i == 0 && j == 0)
best[0][0] = matriz[0][0];
else if (i == 0)
best[i][j] = best[i][j-1] + matriz[i][j];
else if (j == 0)
best[i][j] = best[i-1][j] + matriz[i][j];
else
best[i][j] = min(best[i-1][j], best[i][j-1]) + matriz[i][j];
}
}
cout << best[n-1][n-1] << endl;
return 0;
}
| [
"[email protected]"
] | |
7afe26bb4324876911808b3cd74b5fe5fa6b2e29 | 711e5c8b643dd2a93fbcbada982d7ad489fb0169 | /XPSP1/NT/base/cluster/mgmt/cluscfg/basecluster/cclusdbform.cpp | 096a7b57e4ba3bad3a3091e525bbb2dabea8ffb6 | [] | no_license | aurantst/windows-XP-SP1 | 629a7763c082fd04d3b881e0d32a1cfbd523b5ce | d521b6360fcff4294ae6c5651c539f1b9a6cbb49 | refs/heads/master | 2023-03-21T01:08:39.870106 | 2020-09-28T08:10:11 | 2020-09-28T08:10:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 30,813 | cpp | //////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 1999-2000 Microsoft Corporation
//
// Module Name:
// CClusDBForm.cpp
//
// Description:
// Contains the definition of the CClusDBForm class.
//
// Documentation:
// TODO: Add pointer to external documentation later.
//
// Maintained By:
// Vij Vasu (Vvasu) 08-MAR-2000
//
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
// Include Files
//////////////////////////////////////////////////////////////////////////////
// The precompiled header.
#include "pch.h"
// For cluster registry key and value names.
#include "clusudef.h"
// For ClRtlSetObjSecurityInfo() and other functions.
#include "clusrtl.h"
// The header for this file
#include "CClusDBForm.h"
// For the CBaseClusterForm class.
#include "CBaseClusterForm.h"
// For UUID related utilities.
#include "CUuid.h"
// For CEnableThreadPrivilege
#include "CEnableThreadPrivilege.h"
// For the CStr class.
#include "CStr.h"
// For sending status reports.
#include "CStatusReport.h"
// For DwRemoveDirectory()
#include "Common.h"
// For inet_ntoa
#include <winsock2.h>
//////////////////////////////////////////////////////////////////////////
// Macros definitions
//////////////////////////////////////////////////////////////////////////
// Section in the INF file that deals with populating the cluster hive.
#define CLUSDB_POPULATE_INF_SECTION_NAME L"ClusDB_Form"
// A placeholder for the cluster group key name in the cluster registry.
#define CLUSREG_KEYNAME_CLUSTERGROUP_PLACEHOLDER L"ClusterGroupGUIDPlaceholder"
// A placeholder for the cluster name resource key name in the cluster registry.
#define CLUSREG_KEYNAME_CLUSTERNAME_RES_PLACEHOLDER L"ClusterNameResGUIDPlaceHolder"
// A placeholder for the cluster IP address resource key name in the cluster registry.
#define CLUSREG_KEYNAME_CLUSTERIP_RES_PLACEHOLDER L"ClusterIPAddrResGUIDPlaceHolder"
// A placeholder for the local quorum resource key name in the cluster registry.
#define CLUSREG_KEYNAME_LOCALQUORUM_RES_PLACEHOLDER L"LocalQuorumResGUIDPlaceHolder"
//////////////////////////////////////////////////////////////////////////////
//++
//
// CClusDBForm::CClusDBForm()
//
// Description:
// Constructor of the CClusDBForm class
//
// Arguments:
// pfaParentActionIn
// Pointer to the base cluster action of which this action is a part.
//
// Return Value:
// None.
//
// Exceptions Thrown:
// Any exceptions thrown by underlying functions
//
//--
//////////////////////////////////////////////////////////////////////////////
CClusDBForm::CClusDBForm( CBaseClusterForm * pfaParentActionIn )
: BaseClass( pfaParentActionIn )
{
BCATraceScope( "" );
SetRollbackPossible( true );
} //*** CClusDBForm::CClusDBForm()
//////////////////////////////////////////////////////////////////////////////
//++
//
// CClusDBForm::~CClusDBForm()
//
// Description:
// Destructor of the CClusDBForm class.
//
// Arguments:
// None.
//
// Return Value:
// None.
//
// Exceptions Thrown:
// Any exceptions thrown by underlying functions
//
//--
//////////////////////////////////////////////////////////////////////////////
CClusDBForm::~CClusDBForm( void )
{
BCATraceScope( "" );
} //*** CClusDBForm::~CClusDBForm()
//////////////////////////////////////////////////////////////////////////////
//++
//
// void
// CClusDBForm::Commit()
//
// Description:
// Create the cluster database. If anything goes wrong with the creation,
// cleanup the tasks already done.
//
// Arguments:
// None.
//
// Return Value:
// None.
//
// Exceptions Thrown:
// Any that are thrown by the contained actions.
//
//--
//////////////////////////////////////////////////////////////////////////////
void
CClusDBForm::Commit( void )
{
BCATraceScope( "" );
// Call the base class commit method.
BaseClass::Commit();
//
// Perform a ClusDB cleanup just to make sure that we do not use some files left over
// from a previous install, aborted uninstall, etc.
//
LogMsg( "Cleaning up old cluster database files that may already exist before starting creation." );
{
CStatusReport srCleanDB(
PbcaGetParent()->PBcaiGetInterfacePointer()
, TASKID_Major_Configure_Cluster_Services
, TASKID_Minor_Cleaning_Up_Cluster_Database
, 0, 1
, IDS_TASK_CLEANINGUP_CLUSDB
);
// Send the next step of this status report.
srCleanDB.SendNextStep( S_OK );
CleanupHive();
// Send the last step of this status report.
srCleanDB.SendNextStep( S_OK );
}
try
{
// Create the cluster database
Create();
} // try:
catch( ... )
{
// If we are here, then something went wrong with the create.
BCATraceMsg( "Caught exception during commit." );
//
// Cleanup anything that the failed form might have done.
// Catch any exceptions thrown during Cleanup to make sure that there
// is no collided unwind.
//
try
{
CleanupHive();
}
catch( ... )
{
//
// The rollback of the committed action has failed.
// There is nothing that we can do.
// We certainly cannot rethrow this exception, since
// the exception that caused the rollback is more important.
//
THR( E_UNEXPECTED );
BCATraceMsg( "Caught exception during cleanup." );
LogMsg( "THIS COMPUTER MAY BE IN AN INVALID STATE. An error has occurred during cleanup." );
} // catch: all
// Rethrow the exception thrown by commit.
throw;
} // catch: all
// If we are here, then everything went well.
SetCommitCompleted( true );
} //*** CClusDBForm::Commit()
//////////////////////////////////////////////////////////////////////////////
//++
//
// void
// CClusDBForm::Rollback()
//
// Description:
// Unload the cluster hive and cleanup any associated files.
//
// Arguments:
// None.
//
// Return Value:
// None.
//
// Exceptions Thrown:
// Any that are thrown by the underlying functions.
//
//--
//////////////////////////////////////////////////////////////////////////////
void
CClusDBForm::Rollback( void )
{
BCATraceScope( "" );
// Call the base class rollback method.
BaseClass::Rollback();
// Cleanup the cluster database.
CleanupHive();
SetCommitCompleted( false );
} //*** CClusDBForm::Rollback()
//////////////////////////////////////////////////////////////////////////////
//++
//
// void
// CClusDBForm::Create()
//
// Description:
// Create the cluster database.
//
// Arguments:
// None.
//
// Return Value:
// None.
//
// Exceptions Thrown:
// CAssert
// The parent action of this action is not CBaseClusterForm
//
// CRuntimeError
// If any of the APIs fail.
//
// Any that are thrown by the called functions.
//
//--
//////////////////////////////////////////////////////////////////////////////
void
CClusDBForm::Create( void )
{
BCATraceScope( "" );
LogMsg( "Attempting to create the cluster database required to form a cluster." );
DWORD dwError = ERROR_SUCCESS;
OBJECT_ATTRIBUTES oaClusterHiveKey;
OBJECT_ATTRIBUTES oaClusterHiveFile;
HRESULT hrStatus = STATUS_SUCCESS;
// Get the parent action pointer.
CBaseClusterForm * pcfClusterForm = dynamic_cast< CBaseClusterForm *>( PbcaGetParent() );
CStatusReport srCustomizingDB(
PbcaGetParent()->PBcaiGetInterfacePointer()
, TASKID_Major_Configure_Cluster_Services
, TASKID_Minor_Form_Customizing_Cluster_Database
, 0, 1
, IDS_TASK_FORM_CUSTOMIZING_CLUSDB
);
// If the parent action of this action is not CBaseClusterForm
if ( pcfClusterForm == NULL )
{
THROW_ASSERT( E_POINTER, "The parent action of this action is not CBaseClusterForm." );
} // an invalid pointer was passed in.
// Create the cluster hive.
{
CStatusReport srCreatingDB(
PbcaGetParent()->PBcaiGetInterfacePointer()
, TASKID_Major_Configure_Cluster_Services
, TASKID_Minor_Form_Creating_Cluster_Database
, 0, 1
, IDS_TASK_FORM_CREATING_CLUSDB
);
// Send the next step of this status report.
srCreatingDB.SendNextStep( S_OK );
// Create an empty cluster hive in the registry.
CreateHive( pcfClusterForm );
// Send the last step of this status report.
srCreatingDB.SendNextStep( S_OK );
}
// Send the next step of this status report.
srCustomizingDB.SendNextStep( S_OK );
// Fill up the newly created hive.
PopulateHive( pcfClusterForm );
//
// Create the quorum directory and set its security attributes.
//
do
{
HANDLE hQuorumDirHandle;
const WCHAR * pcszQuorumDir = pcfClusterForm->RStrGetLocalQuorumDirectory().PszData();
// First, remove the local quorum directory, if it exists.
dwError = TW32( DwRemoveDirectory( pcszQuorumDir ) );
if ( dwError != ERROR_SUCCESS )
{
BCATraceMsg2( "The local quorum directory '%s' already exists, but error %#x occurred trying to remove it.\n", pcszQuorumDir, dwError );
LogMsg( "The local quorum directory '%s' already exists, but error %#x occurred trying to remove it.\n", pcszQuorumDir, dwError );
break;
} // if: we could not remove the local quorum directory
if ( CreateDirectory( pcszQuorumDir, NULL ) == FALSE )
{
dwError = TW32( GetLastError() );
BCATraceMsg1( "Failed to create directory '%ws'", pcszQuorumDir );
break;
} // if: the localquorum directory could not be created
//
// Enable the SE_BACKUP_PRIVILEGE and SE_RESTORE_PRIVILEGE.
//
// What we are doing here is that we are creating an object of
// type CEnableThreadPrivilege. This object enables the privilege
// in the constructor and restores it to its original state in the destructor.
//
CEnableThreadPrivilege etpAcquireBackupPrivilege( SE_BACKUP_NAME );
CEnableThreadPrivilege etpAcquireRestorePrivilege( SE_RESTORE_NAME );
//
// Open a handle to the quorum directory. The calling thread should have SE_BACKUP_PRIVILEGE and
// SE_RESTORE_PRIVILEGE enabled.
//
hQuorumDirHandle = CreateFile(
pcszQuorumDir
, GENERIC_ALL
, FILE_SHARE_WRITE
, NULL
, OPEN_EXISTING
, FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
if ( hQuorumDirHandle == INVALID_HANDLE_VALUE )
{
// The directory does not exist. This is an error.
dwError = TW32( GetLastError() );
BCATraceMsg1( "The directory '%ws' does not exist.", pcszQuorumDir );
break;
} // if: the quorum directory does not exist.
// Set the security for this directory.
dwError = TW32( ClRtlSetObjSecurityInfo(
hQuorumDirHandle
, SE_FILE_OBJECT
, GENERIC_ALL
, GENERIC_ALL
, GENERIC_READ
) );
// First close the handle we opened.
CloseHandle( hQuorumDirHandle );
if ( dwError != ERROR_SUCCESS )
{
// ClRtlSetObjSecurityInfo() failed.
BCATraceMsg( "ClRtlSetObjSecurityInfo() failed." );
break;
} // if: ClRtlSetObjSecurityInfo() failed
}
while( false ); // dummy do-while loop to avoid gotos.
if ( dwError != ERROR_SUCCESS )
{
LogMsg( "Error %#08x occurred while trying to create the local quorum directory.", dwError );
BCATraceMsg1( "Error %#08x occurred while trying to create the local quorum directory. Throwing exception.", dwError );
THROW_RUNTIME_ERROR( HRESULT_FROM_WIN32( dwError ), IDS_ERROR_QUORUM_DIR_CREATE );
} // if: something went wrong.
// Send the last step of this status report.
srCustomizingDB.SendNextStep( S_OK );
} //*** CClusDBForm::Create()
//////////////////////////////////////////////////////////////////////////////
//++
//
// void
// CClusDBForm::PopulateHive()
//
// Description:
// Make the entries required by the cluster service in the hive.
//
// Arguments:
// pcfClusterFormIn
// Pointer to the CBaseClusterForm object which contains this object.
//
// Return Value:
// None.
//
// Exceptions Thrown:
// CRuntimeError
// If any of the APIs fail.
//
// Any that are thrown by the called functions.
//
//--
//////////////////////////////////////////////////////////////////////////////
void
CClusDBForm::PopulateHive( CBaseClusterForm * pcfClusterFormIn )
{
BCATraceScope( "" );
LogMsg( "Populating the cluster hive." );
DWORD dwError = ERROR_SUCCESS;
do
{
DWORD dwSDSize = 0;
CRegistryKey rkClusterHiveRoot(
HKEY_LOCAL_MACHINE
, CLUSREG_KEYNAME_CLUSTER
, KEY_ALL_ACCESS
);
if ( SetupInstallFromInfSection(
NULL // optional, handle of a parent window
, pcfClusterFormIn->HGetMainInfFileHandle() // handle to the INF file
, CLUSDB_POPULATE_INF_SECTION_NAME // name of the Install section
, SPINST_REGISTRY // which lines to install from section
, rkClusterHiveRoot.HGetKey() // optional, key for registry installs
, NULL // optional, path for source files
, 0 // optional, specifies copy behavior
, NULL // optional, specifies callback routine
, NULL // optional, callback routine context
, NULL // optional, device information set
, NULL // optional, device info structure
) == FALSE
)
{
dwError = TW32( GetLastError() );
LogMsg( "Error %#08x occurred while trying to populate the cluster hive.", dwError );
BCATraceMsg( "Setup API returned an error while trying to populate the cluster hive." );
break;
} // if: SetupInstallServicesFromInfSection failed
LogMsg( "Basic hive structure created." );
// Set the cluster name.
rkClusterHiveRoot.SetValue(
CLUSREG_NAME_CLUS_NAME
, REG_SZ
, reinterpret_cast< const BYTE * >( pcfClusterFormIn->RStrGetClusterNetBIOSName().PszData() )
, ( pcfClusterFormIn->RStrGetClusterNetBIOSName().NGetLen() + 1 ) * sizeof( WCHAR )
);
//
// Set the default cluster security descriptor.
//
{
SECURITY_DESCRIPTOR * psdSecurityDescriptor = NULL;
// Form the security descriptor.
dwError = TW32( ClRtlBuildDefaultClusterSD(
pcfClusterFormIn->PSidGetServiceAccountSID()
, reinterpret_cast< void ** >( &psdSecurityDescriptor )
, &dwSDSize
) );
// Assign it to a smart pointer for safe release.
CSmartResource<
CHandleTrait<
HLOCAL
, HLOCAL
, LocalFree
>
>
smartSD( reinterpret_cast< HLOCAL >( psdSecurityDescriptor ) );
if ( dwError != ERROR_SUCCESS )
{
BCATraceMsg( "ClRtlBuildDefaultClusterSD() failed." );
break;
} // if: ClRtlBuildDefaultClusterSD() failed.
// Set the security descriptor in the registry.
rkClusterHiveRoot.SetValue(
CLUSREG_NAME_CLUS_SD
, REG_BINARY
, reinterpret_cast< const BYTE * >( psdSecurityDescriptor )
, dwSDSize
);
// Set the NT4 version of the security descriptor in the registry.
rkClusterHiveRoot.SetValue(
CLUSREG_NAME_CLUS_SECURITY
, REG_BINARY
, reinterpret_cast< const BYTE * >( psdSecurityDescriptor )
, dwSDSize
);
}
LogMsg( "Cluster common properties set." );
//
// Set the values under the HKLM\Cluster\Nodes key.
//
{
DWORD dwTemp;
CRegistryKey rkNodesKey(
rkClusterHiveRoot.HGetKey()
, CLUSREG_KEYNAME_NODES
, KEY_WRITE
);
CRegistryKey rkThisNodeKey;
// Create a subkey for this node.
rkThisNodeKey.CreateKey(
rkNodesKey.HGetKey()
, pcfClusterFormIn->PszGetNodeIdString()
);
// Set the node name.
rkThisNodeKey.SetValue(
CLUSREG_NAME_NODE_NAME
, REG_SZ
, reinterpret_cast< const BYTE *>( pcfClusterFormIn->PszGetNodeName() )
, ( pcfClusterFormIn->DwGetNodeNameLength() + 1 ) * sizeof( WCHAR )
);
// Set the node highest version.
dwTemp = pcfClusterFormIn->DwGetNodeHighestVersion();
rkThisNodeKey.SetValue(
CLUSREG_NAME_NODE_HIGHEST_VERSION
, REG_DWORD
, reinterpret_cast< const BYTE *>( &dwTemp )
, sizeof( dwTemp )
);
// Set the node lowest version.
dwTemp = pcfClusterFormIn->DwGetNodeLowestVersion();
rkThisNodeKey.SetValue(
CLUSREG_NAME_NODE_LOWEST_VERSION
, REG_DWORD
, reinterpret_cast< const BYTE *>( &dwTemp )
, sizeof( dwTemp )
);
}
LogMsg( "Cluster node subtree customized." );
// Customize the cluster group and the core resources.
CustomizeClusterGroup( pcfClusterFormIn, rkClusterHiveRoot );
// Flush the changes to the registry.
RegFlushKey( rkClusterHiveRoot.HGetKey() );
LogMsg( "Cluster hive successfully populated." );
}
while( false ); // dummy do-while loop to avoid gotos.
if ( dwError != ERROR_SUCCESS )
{
LogMsg( "Error %#08x occurred while trying to populate the cluster hive.", dwError );
BCATraceMsg1( "Error %#08x occurred while trying to populate the cluster hive. Throwing exception.", dwError );
THROW_RUNTIME_ERROR( HRESULT_FROM_WIN32( dwError ), IDS_ERROR_CLUSDB_POPULATE_HIVE );
} // if: something went wrong.
} //*** CClusDBForm::PopulateHive()
//////////////////////////////////////////////////////////////////////////////
//++
//
// void
// CClusDBForm::CustomizeClusterGroup()
//
// Description:
// Customize the cluster group and the core resources.
//
// Arguments:
// pcfClusterFormIn
// Pointer to the CBaseClusterForm object which contains this object.
//
// rkClusterHiveRootIn
// A CRegistryKey object representing the root of the cluster hive.
//
// Return Value:
// None.
//
// Exceptions Thrown:
// CRuntimeError
// If any of the APIs fail.
//
// Any that are thrown by the called functions.
//
//--
//////////////////////////////////////////////////////////////////////////////
void
CClusDBForm::CustomizeClusterGroup(
CBaseClusterForm * pcfClusterFormIn
, CRegistryKey & rkClusterHiveRootIn
)
{
BCATraceScope( "" );
// UUIDs of the cluster group and core resources.
CUuid uuidClusterGroupUuid;
CUuid uuidClusterIPAddressResourceUuid;
CUuid uuidClusterNameResourceUuid;
CUuid uuidLocalQuorumResourceUuid;
// The lengths of the string versions of the above UUIDs.
UINT uiGroupUuidLen = wcslen( uuidClusterGroupUuid.PszGetUuidString() );
UINT uiIPUuidLen = wcslen( uuidClusterIPAddressResourceUuid.PszGetUuidString() );
UINT uiNameUuidLen = wcslen( uuidClusterNameResourceUuid.PszGetUuidString() );
UINT uiLocalQuorumUuidLen = wcslen( uuidLocalQuorumResourceUuid.PszGetUuidString() );
UINT uiUuidLen;
// Length of the multisz string that can hold the above resource UUIDs.
uiUuidLen =
( ( uiIPUuidLen + 1 )
+ ( uiNameUuidLen + 1 )
+ ( uiLocalQuorumUuidLen + 1 )
+ 1
);
// Allocate a buffer for this multisz string.
SmartSz sszResourceUuids( new WCHAR[ uiUuidLen ] );
// Was the memory successfully allocated?
if ( sszResourceUuids.FIsEmpty() )
{
BCATraceMsg1( "Could not allocate %d character in memory. Throwing an exception.", uiUuidLen );
THROW_RUNTIME_ERROR(
E_OUTOFMEMORY
, IDS_ERROR_CUSTOMIZE_CLUSTER_GROUP
);
} // if: memory allocation failed.
//
// Fill this buffer with the uuids of the core resources.
//
// Make sure that the IP address uuid is the first string in this multisz string.
// This is buffer is reused during setting of the network name dependency on the
// IP address resource.
CopyMemory(
sszResourceUuids.PMem()
, uuidClusterIPAddressResourceUuid.PszGetUuidString()
, ( uiIPUuidLen + 1 ) * sizeof( WCHAR )
);
CopyMemory(
sszResourceUuids.PMem() + uiIPUuidLen + 1
, uuidClusterNameResourceUuid.PszGetUuidString()
, ( uiNameUuidLen + 1 ) * sizeof( WCHAR )
);
CopyMemory(
sszResourceUuids.PMem() + uiIPUuidLen + uiNameUuidLen + 2
, uuidLocalQuorumResourceUuid.PszGetUuidString()
, ( uiLocalQuorumUuidLen + 1 ) * sizeof( WCHAR )
);
( sszResourceUuids.PMem() )[ uiUuidLen - 1 ] = L'\0';
//
// Customize the cluster group.
//
{
CRegistryKey rkClusterGroupKey(
rkClusterHiveRootIn.HGetKey()
, CLUSREG_KEYNAME_GROUPS L"\\" CLUSREG_KEYNAME_CLUSTERGROUP_PLACEHOLDER
, KEY_WRITE
);
// Replace the placeholder for the cluster group key with an actual UUID.
rkClusterGroupKey.RenameKey( uuidClusterGroupUuid.PszGetUuidString() );
// Set the list of contained resources uuids.
rkClusterGroupKey.SetValue(
CLUSREG_NAME_GRP_CONTAINS
, REG_MULTI_SZ
, reinterpret_cast< const BYTE * >( sszResourceUuids.PMem() )
, uiUuidLen * sizeof( WCHAR )
);
BCATraceMsg( "Cluster group customized." );
}
//
// Customize the localquorum resource and update the HKLM\Quorum key.
//
{
CRegistryKey rkLocalQuorumResourceKey(
rkClusterHiveRootIn.HGetKey()
, CLUSREG_KEYNAME_RESOURCES L"\\" CLUSREG_KEYNAME_LOCALQUORUM_RES_PLACEHOLDER
, KEY_WRITE
);
CRegistryKey rkQuorumKey(
rkClusterHiveRootIn.HGetKey()
, CLUSREG_KEYNAME_QUORUM
, KEY_WRITE
);
// Replace the placeholder for the localquorum resource key with an actual UUID.
rkLocalQuorumResourceKey.RenameKey( uuidLocalQuorumResourceUuid.PszGetUuidString() );
// Set the uuid of the localquorum resource under the HKLM\Quorum key
rkQuorumKey.SetValue(
CLUSREG_NAME_QUORUM_RESOURCE
, REG_SZ
, reinterpret_cast< const BYTE * >( uuidLocalQuorumResourceUuid.PszGetUuidString() )
, ( uiLocalQuorumUuidLen + 1 ) * sizeof( WCHAR )
);
BCATraceMsg( "Localquorum resource customized." );
}
//
// Set the cluster IP address resource private properties.
//
{
CRegistryKey rkClusterIPResourceKey(
rkClusterHiveRootIn.HGetKey()
, CLUSREG_KEYNAME_RESOURCES L"\\" CLUSREG_KEYNAME_CLUSTERIP_RES_PLACEHOLDER
, KEY_WRITE
);
LPSTR pszAddr; // don't free!
WCHAR szIPBuffer[ 3 + 1 + 3 + 1 + 3 + 1 + 3 + 1 ]; // "xxx.xxx.xxx.xxx\0"
DWORD dwTemp;
// Replace the placeholder for the cluster IP address resource key with an actual UUID.
rkClusterIPResourceKey.RenameKey( uuidClusterIPAddressResourceUuid.PszGetUuidString() );
// Create the cluster IP address parameters registry key.
CRegistryKey rkIPResParams;
rkIPResParams.CreateKey(
rkClusterIPResourceKey.HGetKey()
, CLUSREG_KEYNAME_PARAMETERS
);
// Format the cluster IP address into a dotted quad.
dwTemp = pcfClusterFormIn->DwGetIPAddress();
pszAddr = inet_ntoa( * (struct in_addr *) &dwTemp );
if ( pszAddr == NULL )
{
LogMsg( "inet_ntoa() returned NULL. Mapping it to E_OUTOFMEMORY." );
THROW_RUNTIME_ERROR( E_OUTOFMEMORY, IDS_ERROR_CLUSDB_POPULATE_HIVE );
}
mbstowcs( szIPBuffer, pszAddr, strlen(pszAddr) + 1 );
// Write the IP address to the registry.
rkIPResParams.SetValue(
CLUSREG_NAME_IPADDR_ADDRESS
, REG_SZ
, reinterpret_cast< const BYTE * >( szIPBuffer )
, ( wcslen( szIPBuffer ) + 1 ) * sizeof(WCHAR)
);
// Format the cluster IP subnet mask into a dotted quad.
dwTemp = pcfClusterFormIn->DwGetIPSubnetMask();
pszAddr = inet_ntoa( * (struct in_addr *) &dwTemp );
if ( pszAddr == NULL )
{
LogMsg( "inet_ntoa() returned NULL. Mapping it to E_OUTOFMEMORY." );
THROW_RUNTIME_ERROR( E_OUTOFMEMORY, IDS_ERROR_CLUSDB_POPULATE_HIVE );
}
mbstowcs( szIPBuffer, pszAddr, strlen( pszAddr ) + 1 );
// Write the IP subnet mask to the registry.
rkIPResParams.SetValue(
CLUSREG_NAME_IPADDR_SUBNET_MASK
, REG_SZ
, reinterpret_cast< const BYTE * >( szIPBuffer )
, ( wcslen( szIPBuffer ) + 1 ) * sizeof(WCHAR)
);
// Write the IP address network to the registry.
rkIPResParams.SetValue(
CLUSREG_NAME_IPADDR_NETWORK
, REG_SZ
, reinterpret_cast< const BYTE * >( pcfClusterFormIn->RStrGetClusterIPNetwork().PszData() )
, ( pcfClusterFormIn->RStrGetClusterIPNetwork().NGetLen() + 1 ) * sizeof( WCHAR )
);
BCATraceMsg( "IP address resource customized." );
}
//
// Set the cluster network name resource private properties and dependencies.
//
{
CRegistryKey rkClusterNameResourceKey(
rkClusterHiveRootIn.HGetKey()
, CLUSREG_KEYNAME_RESOURCES L"\\" CLUSREG_KEYNAME_CLUSTERNAME_RES_PLACEHOLDER
, KEY_WRITE
);
// Replace the placeholder for the network name resource key with an actual UUID.
rkClusterNameResourceKey.RenameKey( uuidClusterNameResourceUuid.PszGetUuidString() );
//
// Indicate that the network name resource depends on the IP address resource.
//
( sszResourceUuids.PMem() )[ uiIPUuidLen + 1 ] = L'\0';
rkClusterNameResourceKey.SetValue(
CLUSREG_NAME_RES_DEPENDS_ON
, REG_MULTI_SZ
, reinterpret_cast< const BYTE * >( sszResourceUuids.PMem() )
, ( uiIPUuidLen + 2 ) * sizeof( WCHAR )
);
//
// Create the cluster name parameters registry key.
//
CRegistryKey rkNetNameResParams;
rkNetNameResParams.CreateKey(
rkClusterNameResourceKey.HGetKey()
, CLUSREG_KEYNAME_PARAMETERS
);
// Write the cluster name to the registry.
rkNetNameResParams.SetValue(
CLUSREG_NAME_NETNAME_NAME
, REG_SZ
, reinterpret_cast< const BYTE * >( pcfClusterFormIn->RStrGetClusterNetBIOSName().PszData() )
, ( pcfClusterFormIn->RStrGetClusterNetBIOSName().NGetLen() + 1 ) * sizeof( WCHAR )
);
// Store the UUID of the network name resource under HKLM\Cluster\ClusterNameResource.
rkClusterHiveRootIn.SetValue(
CLUSREG_NAME_CLUS_CLUSTER_NAME_RES
, REG_SZ
, reinterpret_cast< const BYTE * >( uuidClusterNameResourceUuid.PszGetUuidString() )
, ( uiNameUuidLen + 1 ) * sizeof( WCHAR )
);
BCATraceMsg( "Network name resource customized." );
}
LogMsg( "Cluster group and core resources customized." );
} //*** CClusDBForm::CustomizeClusterGroup()
| [
"[email protected]"
] | |
f09ecdaf382125ad6073da71f0a13926370b8f77 | 1d928c3f90d4a0a9a3919a804597aa0a4aab19a3 | /c++/xbmc/2016/8/Settings.h | 0829f6b15207bf0b8f2e4a699600b46427fe6267 | [] | no_license | rosoareslv/SED99 | d8b2ff5811e7f0ffc59be066a5a0349a92cbb845 | a062c118f12b93172e31e8ca115ce3f871b64461 | refs/heads/main | 2023-02-22T21:59:02.703005 | 2021-01-28T19:40:51 | 2021-01-28T19:40:51 | 306,497,459 | 1 | 1 | null | 2020-11-24T20:56:18 | 2020-10-23T01:18:07 | null | UTF-8 | C++ | false | false | 28,466 | h | #pragma once
/*
* Copyright (C) 2005-2013 Team XBMC
* http://xbmc.org
*
* 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, 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 XBMC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include <set>
#include <string>
#include <vector>
#include <memory>
#include "settings/SettingControl.h"
#include "settings/SettingCreator.h"
#include "settings/lib/ISettingCallback.h"
#include "threads/CriticalSection.h"
class CSetting;
class CSettingList;
class CSettingSection;
class CSettingsManager;
class TiXmlElement;
class TiXmlNode;
class CVariant;
/*!
\brief Wrapper around CSettingsManager responsible for properly setting up
the settings manager and registering all the callbacks, handlers and custom
setting types.
\sa CSettingsManager
*/
class CSettings : public CSettingCreator, public CSettingControlCreator
{
public:
static const std::string SETTING_LOOKANDFEEL_SKIN;
static const std::string SETTING_LOOKANDFEEL_SKINSETTINGS;
static const std::string SETTING_LOOKANDFEEL_SKINTHEME;
static const std::string SETTING_LOOKANDFEEL_SKINCOLORS;
static const std::string SETTING_LOOKANDFEEL_FONT;
static const std::string SETTING_LOOKANDFEEL_SKINZOOM;
static const std::string SETTING_LOOKANDFEEL_STARTUPWINDOW;
static const std::string SETTING_LOOKANDFEEL_SOUNDSKIN;
static const std::string SETTING_LOOKANDFEEL_ENABLERSSFEEDS;
static const std::string SETTING_LOOKANDFEEL_RSSEDIT;
static const std::string SETTING_LOOKANDFEEL_STEREOSTRENGTH;
static const std::string SETTING_LOCALE_LANGUAGE;
static const std::string SETTING_LOCALE_COUNTRY;
static const std::string SETTING_LOCALE_CHARSET;
static const std::string SETTING_LOCALE_KEYBOARDLAYOUTS;
static const std::string SETTING_LOCALE_TIMEZONECOUNTRY;
static const std::string SETTING_LOCALE_TIMEZONE;
static const std::string SETTING_LOCALE_SHORTDATEFORMAT;
static const std::string SETTING_LOCALE_LONGDATEFORMAT;
static const std::string SETTING_LOCALE_TIMEFORMAT;
static const std::string SETTING_LOCALE_USE24HOURCLOCK;
static const std::string SETTING_LOCALE_TEMPERATUREUNIT;
static const std::string SETTING_LOCALE_SPEEDUNIT;
static const std::string SETTING_FILELISTS_SHOWPARENTDIRITEMS;
static const std::string SETTING_FILELISTS_SHOWEXTENSIONS;
static const std::string SETTING_FILELISTS_IGNORETHEWHENSORTING;
static const std::string SETTING_FILELISTS_ALLOWFILEDELETION;
static const std::string SETTING_FILELISTS_SHOWADDSOURCEBUTTONS;
static const std::string SETTING_FILELISTS_SHOWHIDDEN;
static const std::string SETTING_SCREENSAVER_MODE;
static const std::string SETTING_SCREENSAVER_SETTINGS;
static const std::string SETTING_SCREENSAVER_PREVIEW;
static const std::string SETTING_SCREENSAVER_TIME;
static const std::string SETTING_SCREENSAVER_USEMUSICVISINSTEAD;
static const std::string SETTING_SCREENSAVER_USEDIMONPAUSE;
static const std::string SETTING_WINDOW_WIDTH;
static const std::string SETTING_WINDOW_HEIGHT;
static const std::string SETTING_VIDEOLIBRARY_SHOWUNWATCHEDPLOTS;
static const std::string SETTING_VIDEOLIBRARY_ACTORTHUMBS;
static const std::string SETTING_MYVIDEOS_FLATTEN;
static const std::string SETTING_VIDEOLIBRARY_FLATTENTVSHOWS;
static const std::string SETTING_VIDEOLIBRARY_TVSHOWSSELECTFIRSTUNWATCHEDITEM;
static const std::string SETTING_VIDEOLIBRARY_TVSHOWSINCLUDEALLSEASONSANDSPECIALS;
static const std::string SETTING_VIDEOLIBRARY_SHOWALLITEMS;
static const std::string SETTING_VIDEOLIBRARY_GROUPMOVIESETS;
static const std::string SETTING_VIDEOLIBRARY_GROUPSINGLEITEMSETS;
static const std::string SETTING_VIDEOLIBRARY_UPDATEONSTARTUP;
static const std::string SETTING_VIDEOLIBRARY_BACKGROUNDUPDATE;
static const std::string SETTING_VIDEOLIBRARY_CLEANUP;
static const std::string SETTING_VIDEOLIBRARY_EXPORT;
static const std::string SETTING_VIDEOLIBRARY_IMPORT;
static const std::string SETTING_VIDEOLIBRARY_SHOWEMPTYTVSHOWS;
static const std::string SETTING_LOCALE_AUDIOLANGUAGE;
static const std::string SETTING_VIDEOPLAYER_PREFERDEFAULTFLAG;
static const std::string SETTING_VIDEOPLAYER_AUTOPLAYNEXTITEM;
static const std::string SETTING_VIDEOPLAYER_SEEKSTEPS;
static const std::string SETTING_VIDEOPLAYER_SEEKDELAY;
static const std::string SETTING_VIDEOPLAYER_ADJUSTREFRESHRATE;
static const std::string SETTING_VIDEOPLAYER_USEDISPLAYASCLOCK;
static const std::string SETTING_VIDEOPLAYER_ERRORINASPECT;
static const std::string SETTING_VIDEOPLAYER_STRETCH43;
static const std::string SETTING_VIDEOPLAYER_TELETEXTENABLED;
static const std::string SETTING_VIDEOPLAYER_TELETEXTSCALE;
static const std::string SETTING_VIDEOPLAYER_STEREOSCOPICPLAYBACKMODE;
static const std::string SETTING_VIDEOPLAYER_QUITSTEREOMODEONSTOP;
static const std::string SETTING_VIDEOPLAYER_RENDERMETHOD;
static const std::string SETTING_VIDEOPLAYER_HQSCALERS;
static const std::string SETTING_VIDEOPLAYER_USEAMCODEC;
static const std::string SETTING_VIDEOPLAYER_USEAMCODECMPEG2;
static const std::string SETTING_VIDEOPLAYER_USEAMCODECMPEG4;
static const std::string SETTING_VIDEOPLAYER_USEAMCODECH264;
static const std::string SETTING_VIDEOPLAYER_USEMEDIACODEC;
static const std::string SETTING_VIDEOPLAYER_USEMEDIACODECSURFACE;
static const std::string SETTING_VIDEOPLAYER_USEVDPAU;
static const std::string SETTING_VIDEOPLAYER_USEVDPAUMIXER;
static const std::string SETTING_VIDEOPLAYER_USEVDPAUMPEG2;
static const std::string SETTING_VIDEOPLAYER_USEVDPAUMPEG4;
static const std::string SETTING_VIDEOPLAYER_USEVDPAUVC1;
static const std::string SETTING_VIDEOPLAYER_USEVAAPI;
static const std::string SETTING_VIDEOPLAYER_USEVAAPIMPEG2;
static const std::string SETTING_VIDEOPLAYER_USEVAAPIMPEG4;
static const std::string SETTING_VIDEOPLAYER_USEVAAPIVC1;
static const std::string SETTING_VIDEOPLAYER_PREFERVAAPIRENDER;
static const std::string SETTING_VIDEOPLAYER_USEDXVA2;
static const std::string SETTING_VIDEOPLAYER_USEOMXPLAYER;
static const std::string SETTING_VIDEOPLAYER_USEOMX;
static const std::string SETTING_VIDEOPLAYER_USEVTB;
static const std::string SETTING_VIDEOPLAYER_USEMMAL;
static const std::string SETTING_VIDEOPLAYER_USESTAGEFRIGHT;
static const std::string SETTING_VIDEOPLAYER_LIMITGUIUPDATE;
static const std::string SETTING_VIDEOPLAYER_SUPPORTMVC;
static const std::string SETTING_MYVIDEOS_SELECTACTION;
static const std::string SETTING_MYVIDEOS_EXTRACTFLAGS;
static const std::string SETTING_MYVIDEOS_EXTRACTCHAPTERTHUMBS;
static const std::string SETTING_MYVIDEOS_REPLACELABELS;
static const std::string SETTING_MYVIDEOS_EXTRACTTHUMB;
static const std::string SETTING_MYVIDEOS_STACKVIDEOS;
static const std::string SETTING_LOCALE_SUBTITLELANGUAGE;
static const std::string SETTING_SUBTITLES_PARSECAPTIONS;
static const std::string SETTING_SUBTITLES_ALIGN;
static const std::string SETTING_SUBTITLES_STEREOSCOPICDEPTH;
static const std::string SETTING_SUBTITLES_FONT;
static const std::string SETTING_SUBTITLES_HEIGHT;
static const std::string SETTING_SUBTITLES_STYLE;
static const std::string SETTING_SUBTITLES_COLOR;
static const std::string SETTING_SUBTITLES_CHARSET;
static const std::string SETTING_SUBTITLES_OVERRIDEASSFONTS;
static const std::string SETTING_SUBTITLES_LANGUAGES;
static const std::string SETTING_SUBTITLES_STORAGEMODE;
static const std::string SETTING_SUBTITLES_CUSTOMPATH;
static const std::string SETTING_SUBTITLES_PAUSEONSEARCH;
static const std::string SETTING_SUBTITLES_DOWNLOADFIRST;
static const std::string SETTING_SUBTITLES_TV;
static const std::string SETTING_SUBTITLES_MOVIE;
static const std::string SETTING_DVDS_AUTORUN;
static const std::string SETTING_DVDS_PLAYERREGION;
static const std::string SETTING_DVDS_AUTOMENU;
static const std::string SETTING_DISC_PLAYBACK;
static const std::string SETTING_BLURAY_PLAYERREGION;
static const std::string SETTING_ACCESSIBILITY_AUDIOVISUAL;
static const std::string SETTING_ACCESSIBILITY_AUDIOHEARING;
static const std::string SETTING_ACCESSIBILITY_SUBHEARING;
static const std::string SETTING_SCRAPERS_MOVIESDEFAULT;
static const std::string SETTING_SCRAPERS_TVSHOWSDEFAULT;
static const std::string SETTING_SCRAPERS_MUSICVIDEOSDEFAULT;
static const std::string SETTING_PVRMANAGER_HIDECONNECTIONLOSTWARNING;
static const std::string SETTING_PVRMANAGER_SYNCCHANNELGROUPS;
static const std::string SETTING_PVRMANAGER_BACKENDCHANNELORDER;
static const std::string SETTING_PVRMANAGER_USEBACKENDCHANNELNUMBERS;
static const std::string SETTING_PVRMANAGER_CHANNELMANAGER;
static const std::string SETTING_PVRMANAGER_GROUPMANAGER;
static const std::string SETTING_PVRMANAGER_CHANNELSCAN;
static const std::string SETTING_PVRMANAGER_RESETDB;
static const std::string SETTING_PVRMENU_DISPLAYCHANNELINFO;
static const std::string SETTING_PVRMENU_CLOSECHANNELOSDONSWITCH;
static const std::string SETTING_PVRMENU_ICONPATH;
static const std::string SETTING_PVRMENU_SEARCHICONS;
static const std::string SETTING_EPG_DAYSTODISPLAY;
static const std::string SETTING_EPG_SELECTACTION;
static const std::string SETTING_EPG_HIDENOINFOAVAILABLE;
static const std::string SETTING_EPG_EPGUPDATE;
static const std::string SETTING_EPG_PREVENTUPDATESWHILEPLAYINGTV;
static const std::string SETTING_EPG_IGNOREDBFORCLIENT;
static const std::string SETTING_EPG_RESETEPG;
static const std::string SETTING_PVRPLAYBACK_PLAYMINIMIZED;
static const std::string SETTING_PVRPLAYBACK_STARTLAST;
static const std::string SETTING_PVRPLAYBACK_SIGNALQUALITY;
static const std::string SETTING_PVRPLAYBACK_SCANTIME;
static const std::string SETTING_PVRPLAYBACK_CONFIRMCHANNELSWITCH;
static const std::string SETTING_PVRPLAYBACK_CHANNELENTRYTIMEOUT;
static const std::string SETTING_PVRPLAYBACK_FPS;
static const std::string SETTING_PVRRECORD_INSTANTRECORDACTION;
static const std::string SETTING_PVRRECORD_INSTANTRECORDTIME;
static const std::string SETTING_PVRRECORD_DEFAULTPRIORITY;
static const std::string SETTING_PVRRECORD_DEFAULTLIFETIME;
static const std::string SETTING_PVRRECORD_MARGINSTART;
static const std::string SETTING_PVRRECORD_MARGINEND;
static const std::string SETTING_PVRRECORD_PREVENTDUPLICATEEPISODES;
static const std::string SETTING_PVRRECORD_TIMERNOTIFICATIONS;
static const std::string SETTING_PVRRECORD_GROUPRECORDINGS;
static const std::string SETTING_PVRPOWERMANAGEMENT_ENABLED;
static const std::string SETTING_PVRPOWERMANAGEMENT_BACKENDIDLETIME;
static const std::string SETTING_PVRPOWERMANAGEMENT_SETWAKEUPCMD;
static const std::string SETTING_PVRPOWERMANAGEMENT_PREWAKEUP;
static const std::string SETTING_PVRPOWERMANAGEMENT_DAILYWAKEUP;
static const std::string SETTING_PVRPOWERMANAGEMENT_DAILYWAKEUPTIME;
static const std::string SETTING_PVRPARENTAL_ENABLED;
static const std::string SETTING_PVRPARENTAL_PIN;
static const std::string SETTING_PVRPARENTAL_DURATION;
static const std::string SETTING_PVRCLIENT_MENUHOOK;
static const std::string SETTING_PVRTIMERS_HIDEDISABLEDTIMERS;
static const std::string SETTING_MUSICLIBRARY_SHOWCOMPILATIONARTISTS;
static const std::string SETTING_MUSICLIBRARY_DOWNLOADINFO;
static const std::string SETTING_MUSICLIBRARY_ALBUMSSCRAPER;
static const std::string SETTING_MUSICLIBRARY_ARTISTSSCRAPER;
static const std::string SETTING_MUSICLIBRARY_OVERRIDETAGS;
static const std::string SETTING_MUSICLIBRARY_SHOWALLITEMS;
static const std::string SETTING_MUSICLIBRARY_UPDATEONSTARTUP;
static const std::string SETTING_MUSICLIBRARY_BACKGROUNDUPDATE;
static const std::string SETTING_MUSICLIBRARY_CLEANUP;
static const std::string SETTING_MUSICLIBRARY_EXPORT;
static const std::string SETTING_MUSICLIBRARY_IMPORT;
static const std::string SETTING_MUSICPLAYER_AUTOPLAYNEXTITEM;
static const std::string SETTING_MUSICPLAYER_QUEUEBYDEFAULT;
static const std::string SETTING_MUSICPLAYER_SEEKSTEPS;
static const std::string SETTING_MUSICPLAYER_SEEKDELAY;
static const std::string SETTING_MUSICPLAYER_REPLAYGAINTYPE;
static const std::string SETTING_MUSICPLAYER_REPLAYGAINPREAMP;
static const std::string SETTING_MUSICPLAYER_REPLAYGAINNOGAINPREAMP;
static const std::string SETTING_MUSICPLAYER_REPLAYGAINAVOIDCLIPPING;
static const std::string SETTING_MUSICPLAYER_CROSSFADE;
static const std::string SETTING_MUSICPLAYER_CROSSFADEALBUMTRACKS;
static const std::string SETTING_MUSICPLAYER_VISUALISATION;
static const std::string SETTING_MUSICFILES_USETAGS;
static const std::string SETTING_MUSICFILES_TRACKFORMAT;
static const std::string SETTING_MUSICFILES_NOWPLAYINGTRACKFORMAT;
static const std::string SETTING_MUSICFILES_LIBRARYTRACKFORMAT;
static const std::string SETTING_MUSICFILES_FINDREMOTETHUMBS;
static const std::string SETTING_AUDIOCDS_AUTOACTION;
static const std::string SETTING_AUDIOCDS_USECDDB;
static const std::string SETTING_AUDIOCDS_RECORDINGPATH;
static const std::string SETTING_AUDIOCDS_TRACKPATHFORMAT;
static const std::string SETTING_AUDIOCDS_ENCODER;
static const std::string SETTING_AUDIOCDS_SETTINGS;
static const std::string SETTING_AUDIOCDS_EJECTONRIP;
static const std::string SETTING_MYMUSIC_SONGTHUMBINVIS;
static const std::string SETTING_MYMUSIC_DEFAULTLIBVIEW;
static const std::string SETTING_PICTURES_GENERATETHUMBS;
static const std::string SETTING_PICTURES_SHOWVIDEOS;
static const std::string SETTING_PICTURES_DISPLAYRESOLUTION;
static const std::string SETTING_SLIDESHOW_STAYTIME;
static const std::string SETTING_SLIDESHOW_DISPLAYEFFECTS;
static const std::string SETTING_SLIDESHOW_SHUFFLE;
static const std::string SETTING_SLIDESHOW_HIGHQUALITYDOWNSCALING;
static const std::string SETTING_WEATHER_CURRENTLOCATION;
static const std::string SETTING_WEATHER_ADDON;
static const std::string SETTING_WEATHER_ADDONSETTINGS;
static const std::string SETTING_SERVICES_DEVICENAME;
static const std::string SETTING_SERVICES_UPNPSERVER;
static const std::string SETTING_SERVICES_UPNPANNOUNCE;
static const std::string SETTING_SERVICES_UPNPLOOKFOREXTERNALSUBTITLES;
static const std::string SETTING_SERVICES_UPNPCONTROLLER;
static const std::string SETTING_SERVICES_UPNPRENDERER;
static const std::string SETTING_SERVICES_WEBSERVER;
static const std::string SETTING_SERVICES_WEBSERVERPORT;
static const std::string SETTING_SERVICES_WEBSERVERUSERNAME;
static const std::string SETTING_SERVICES_WEBSERVERPASSWORD;
static const std::string SETTING_SERVICES_WEBSKIN;
static const std::string SETTING_SERVICES_ESENABLED;
static const std::string SETTING_SERVICES_ESPORT;
static const std::string SETTING_SERVICES_ESPORTRANGE;
static const std::string SETTING_SERVICES_ESMAXCLIENTS;
static const std::string SETTING_SERVICES_ESALLINTERFACES;
static const std::string SETTING_SERVICES_ESINITIALDELAY;
static const std::string SETTING_SERVICES_ESCONTINUOUSDELAY;
static const std::string SETTING_SERVICES_ZEROCONF;
static const std::string SETTING_SERVICES_AIRPLAY;
static const std::string SETTING_SERVICES_AIRPLAYVOLUMECONTROL;
static const std::string SETTING_SERVICES_USEAIRPLAYPASSWORD;
static const std::string SETTING_SERVICES_AIRPLAYPASSWORD;
static const std::string SETTING_SERVICES_AIRPLAYVIDEOSUPPORT;
static const std::string SETTING_SMB_WINSSERVER;
static const std::string SETTING_SMB_WORKGROUP;
static const std::string SETTING_VIDEOSCREEN_MONITOR;
static const std::string SETTING_VIDEOSCREEN_SCREEN;
static const std::string SETTING_VIDEOSCREEN_RESOLUTION;
static const std::string SETTING_VIDEOSCREEN_SCREENMODE;
static const std::string SETTING_VIDEOSCREEN_FAKEFULLSCREEN;
static const std::string SETTING_VIDEOSCREEN_BLANKDISPLAYS;
static const std::string SETTING_VIDEOSCREEN_STEREOSCOPICMODE;
static const std::string SETTING_VIDEOSCREEN_PREFEREDSTEREOSCOPICMODE;
static const std::string SETTING_VIDEOSCREEN_NOOFBUFFERS;
static const std::string SETTING_VIDEOSCREEN_3DLUT;
static const std::string SETTING_VIDEOSCREEN_DISPLAYPROFILE;
static const std::string SETTING_VIDEOSCREEN_GUICALIBRATION;
static const std::string SETTING_VIDEOSCREEN_TESTPATTERN;
static const std::string SETTING_VIDEOSCREEN_LIMITEDRANGE;
static const std::string SETTING_VIDEOSCREEN_FRAMEPACKING;
static const std::string SETTING_AUDIOOUTPUT_AUDIODEVICE;
static const std::string SETTING_AUDIOOUTPUT_CHANNELS;
static const std::string SETTING_AUDIOOUTPUT_CONFIG;
static const std::string SETTING_AUDIOOUTPUT_SAMPLERATE;
static const std::string SETTING_AUDIOOUTPUT_STEREOUPMIX;
static const std::string SETTING_AUDIOOUTPUT_MAINTAINORIGINALVOLUME;
static const std::string SETTING_AUDIOOUTPUT_PROCESSQUALITY;
static const std::string SETTING_AUDIOOUTPUT_ATEMPOTHRESHOLD;
static const std::string SETTING_AUDIOOUTPUT_STREAMSILENCE;
static const std::string SETTING_AUDIOOUTPUT_DSPADDONSENABLED;
static const std::string SETTING_AUDIOOUTPUT_DSPSETTINGS;
static const std::string SETTING_AUDIOOUTPUT_DSPRESETDB;
static const std::string SETTING_AUDIOOUTPUT_GUISOUNDMODE;
static const std::string SETTING_AUDIOOUTPUT_PASSTHROUGH;
static const std::string SETTING_AUDIOOUTPUT_PASSTHROUGHDEVICE;
static const std::string SETTING_AUDIOOUTPUT_AC3PASSTHROUGH;
static const std::string SETTING_AUDIOOUTPUT_AC3TRANSCODE;
static const std::string SETTING_AUDIOOUTPUT_EAC3PASSTHROUGH;
static const std::string SETTING_AUDIOOUTPUT_DTSPASSTHROUGH;
static const std::string SETTING_AUDIOOUTPUT_TRUEHDPASSTHROUGH;
static const std::string SETTING_AUDIOOUTPUT_DTSHDPASSTHROUGH;
static const std::string SETTING_AUDIOOUTPUT_VOLUMESTEPS;
static const std::string SETTING_INPUT_PERIPHERALS;
static const std::string SETTING_INPUT_ENABLEMOUSE;
static const std::string SETTING_INPUT_CONTROLLERCONFIG;
static const std::string SETTING_INPUT_TESTRUMBLE;
static const std::string SETTING_INPUT_CONTROLLERPOWEROFF;
static const std::string SETTING_INPUT_APPLEREMOTEMODE;
static const std::string SETTING_INPUT_APPLEREMOTEALWAYSON;
static const std::string SETTING_INPUT_APPLEREMOTESEQUENCETIME;
static const std::string SETTING_NETWORK_USEHTTPPROXY;
static const std::string SETTING_NETWORK_HTTPPROXYTYPE;
static const std::string SETTING_NETWORK_HTTPPROXYSERVER;
static const std::string SETTING_NETWORK_HTTPPROXYPORT;
static const std::string SETTING_NETWORK_HTTPPROXYUSERNAME;
static const std::string SETTING_NETWORK_HTTPPROXYPASSWORD;
static const std::string SETTING_NETWORK_BANDWIDTH;
static const std::string SETTING_POWERMANAGEMENT_DISPLAYSOFF;
static const std::string SETTING_POWERMANAGEMENT_SHUTDOWNTIME;
static const std::string SETTING_POWERMANAGEMENT_SHUTDOWNSTATE;
static const std::string SETTING_POWERMANAGEMENT_WAKEONACCESS;
static const std::string SETTING_DEBUG_SHOWLOGINFO;
static const std::string SETTING_DEBUG_EXTRALOGGING;
static const std::string SETTING_DEBUG_SETEXTRALOGLEVEL;
static const std::string SETTING_DEBUG_SCREENSHOTPATH;
static const std::string SETTING_EVENTLOG_ENABLED;
static const std::string SETTING_EVENTLOG_ENABLED_NOTIFICATIONS;
static const std::string SETTING_EVENTLOG_SHOW;
static const std::string SETTING_MASTERLOCK_LOCKCODE;
static const std::string SETTING_MASTERLOCK_STARTUPLOCK;
static const std::string SETTING_MASTERLOCK_MAXRETRIES;
static const std::string SETTING_CACHE_HARDDISK;
static const std::string SETTING_CACHEVIDEO_DVDROM;
static const std::string SETTING_CACHEVIDEO_LAN;
static const std::string SETTING_CACHEVIDEO_INTERNET;
static const std::string SETTING_CACHEAUDIO_DVDROM;
static const std::string SETTING_CACHEAUDIO_LAN;
static const std::string SETTING_CACHEAUDIO_INTERNET;
static const std::string SETTING_CACHEDVD_DVDROM;
static const std::string SETTING_CACHEDVD_LAN;
static const std::string SETTING_CACHEUNKNOWN_INTERNET;
static const std::string SETTING_SYSTEM_PLAYLISTSPATH;
static const std::string SETTING_ADDONS_AUTOUPDATES;
static const std::string SETTING_ADDONS_NOTIFICATIONS;
static const std::string SETTING_ADDONS_SHOW_RUNNING;
static const std::string SETTING_ADDONS_MANAGE_DEPENDENCIES;
static const std::string SETTING_ADDONS_ALLOW_UNKNOWN_SOURCES;
static const std::string SETTING_GENERAL_ADDONFOREIGNFILTER;
static const std::string SETTING_GENERAL_ADDONBROKENFILTER;
static const std::string SETTING_SOURCE_VIDEOS;
static const std::string SETTING_SOURCE_MUSIC;
static const std::string SETTING_SOURCE_PICTURES;
/*!
\brief Creates a new settings wrapper around a new settings manager.
For access to the "global" settings wrapper the static GetInstance() method should
be used.
*/
CSettings();
virtual ~CSettings();
/*!
\brief Returns a "global" settings wrapper which can be used from anywhere.
\return "global" settings wrapper
*/
static CSettings& GetInstance();
CSettingsManager* GetSettingsManager() const { return m_settingsManager; }
/*!
\brief Initializes the setting system with the generic
settings definition and platform specific setting definitions.
\return True if the initialization was successful, false otherwise
*/
bool Initialize();
/*!
\brief Loads the setting values.
\return True if the setting values are successfully loaded, false otherwise
*/
bool Load();
/*!
\brief Loads setting values from the given (XML) file.
\param file Path to an XML file containing setting values
\return True if the setting values were successfully loaded, false otherwise
*/
bool Load(const std::string &file);
/*!
\brief Loads setting values from the given XML element.
\param root XML element containing setting values
\param hide Whether to hide the loaded settings or not
\return True if the setting values were successfully loaded, false otherwise
*/
bool Load(const TiXmlElement *root, bool hide = false);
/*!
\brief Tells the settings system that all setting values
have been loaded.
This manual trigger is necessary to enable the ISettingCallback methods
being executed.
*/
void SetLoaded();
/*!
\brief Saves the setting values.
\return True if the setting values were successfully saved, false otherwise
*/
bool Save();
/*!
\brief Saves the setting values to the given (XML) file.
\param file Path to an XML file
\return True if the setting values were successfully saved, false otherwise
*/
bool Save(const std::string &file);
/*!
\brief Unloads the previously loaded setting values.
The values of all the settings are reset to their default values.
*/
void Unload();
/*!
\brief Uninitializes the settings system.
Unregisters all previously registered callbacks and destroys all setting
objects.
*/
void Uninitialize();
/*!
\brief Registers the given ISettingCallback implementation for the given
set of settings.
\param callback ISettingCallback implementation
\param settingList List of setting identifiers for which the given callback shall be triggered
*/
void RegisterCallback(ISettingCallback *callback, const std::set<std::string> &settingList);
/*!
\brief Unregisters the given ISettingCallback implementation.
\param callback ISettingCallback implementation
*/
void UnregisterCallback(ISettingCallback *callback);
/*!
\brief Gets the setting with the given identifier.
\param id Setting identifier
\return Setting object with the given identifier or NULL if the identifier is unknown
*/
CSetting* GetSetting(const std::string &id) const;
/*!
\brief Gets the full list of setting sections.
\return List of setting sections
*/
std::vector<CSettingSection*> GetSections() const;
/*!
\brief Gets the setting section with the given identifier.
\param section Setting section identifier
\return Setting section with the given identifier or NULL if the identifier is unknown
*/
CSettingSection* GetSection(const std::string §ion) const;
/*!
\brief Gets the boolean value of the setting with the given identifier.
\param id Setting identifier
\return Boolean value of the setting with the given identifier
*/
bool GetBool(const std::string &id) const;
/*!
\brief Gets the integer value of the setting with the given identifier.
\param id Setting identifier
\return Integer value of the setting with the given identifier
*/
int GetInt(const std::string &id) const;
/*!
\brief Gets the real number value of the setting with the given identifier.
\param id Setting identifier
\return Real number value of the setting with the given identifier
*/
double GetNumber(const std::string &id) const;
/*!
\brief Gets the string value of the setting with the given identifier.
\param id Setting identifier
\return String value of the setting with the given identifier
*/
std::string GetString(const std::string &id) const;
/*!
\brief Gets the values of the list setting with the given identifier.
\param id Setting identifier
\return List of values of the setting with the given identifier
*/
std::vector<CVariant> GetList(const std::string &id) const;
/*!
\brief Sets the boolean value of the setting with the given identifier.
\param id Setting identifier
\param value Boolean value to set
\return True if setting the value was successful, false otherwise
*/
bool SetBool(const std::string &id, bool value);
/*!
\brief Toggles the boolean value of the setting with the given identifier.
\param id Setting identifier
\return True if toggling the boolean value was successful, false otherwise
*/
bool ToggleBool(const std::string &id);
/*!
\brief Sets the integer value of the setting with the given identifier.
\param id Setting identifier
\param value Integer value to set
\return True if setting the value was successful, false otherwise
*/
bool SetInt(const std::string &id, int value);
/*!
\brief Sets the real number value of the setting with the given identifier.
\param id Setting identifier
\param value Real number value to set
\return True if setting the value was successful, false otherwise
*/
bool SetNumber(const std::string &id, double value);
/*!
\brief Sets the string value of the setting with the given identifier.
\param id Setting identifier
\param value String value to set
\return True if setting the value was successful, false otherwise
*/
bool SetString(const std::string &id, const std::string &value);
/*!
\brief Sets the values of the list setting with the given identifier.
\param id Setting identifier
\param value Values to set
\return True if setting the values was successful, false otherwise
*/
bool SetList(const std::string &id, const std::vector<CVariant> &value);
/*!
\brief Loads the setting being represented by the given XML node with the
given identifier.
\param node XML node representing the setting to load
\param settingId Setting identifier
\return True if the setting was successfully loaded from the given XML node, false otherwise
*/
bool LoadSetting(const TiXmlNode *node, const std::string &settingId);
private:
CSettings(const CSettings&);
CSettings const& operator=(CSettings const&);
bool Initialize(const std::string &file);
bool InitializeDefinitions();
void InitializeSettingTypes();
void InitializeControls();
void InitializeVisibility();
void InitializeDefaults();
void InitializeOptionFillers();
void InitializeConditions();
void InitializeISettingsHandlers();
void InitializeISubSettings();
void InitializeISettingCallbacks();
bool Reset();
bool m_initialized;
CSettingsManager *m_settingsManager;
CCriticalSection m_critical;
};
| [
"[email protected]"
] | |
760533b4a0b1f281a1f540efeedfeb41cc440fc3 | c767fff367ea1399ed741235329c65ef8b1ed196 | /Service/jni/innoextract/cmake/check-cxx11-std-codecvt_utf8_utf16.cpp | 42819e2e32850d9694df7d6f21697d0c5dc71e33 | [
"Zlib",
"MIT",
"Apache-2.0"
] | permissive | shortcrazychick/innoextract-android | 6695c4aa75aeb01dd4e299e6c346bacfebe8f06c | 5a69382ac9104d47383c1af0aaa0bc8a336c9744 | refs/heads/master | 2020-03-23T13:41:15.737916 | 2018-02-07T17:57:46 | 2018-02-07T17:57:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 95 | cpp | #include <codecvt>
int main() {
std::codecvt_utf8_utf16<wchar_t> codecvt;
return 0;
}
| [
"[email protected]"
] | |
2fa9bc2cdbb65249067dffc43188742857a64f3d | f4e17640afef6d1b4d4a85f583a90e37f705dbd5 | /B2G/gecko/dom/activities/src/Activity.cpp | 68c9363d90699fbd791f4b6d139dc0ac46042a57 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | wilebeast/FireFox-OS | d370362916f0c5a5408fa08285dbf4779f8b5eb3 | 43067f28711d78c429a1d6d58c77130f6899135f | refs/heads/master | 2016-09-05T22:06:54.838558 | 2013-09-03T13:49:21 | 2013-09-03T13:49:21 | 12,572,236 | 4 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 3,554 | cpp | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "Activity.h"
#include "nsDOMClassInfo.h"
#include "nsContentUtils.h"
#include "nsIDOMActivityOptions.h"
#include "nsIDocShell.h"
#include "nsIConsoleService.h"
using namespace mozilla::dom;
DOMCI_DATA(MozActivity, Activity)
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_INHERITED(Activity)
NS_INTERFACE_MAP_ENTRY(nsIDOMMozActivity)
NS_INTERFACE_MAP_ENTRY(nsIJSNativeInitializer)
NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO(MozActivity)
NS_INTERFACE_MAP_END_INHERITING(DOMRequest)
NS_IMPL_ADDREF_INHERITED(Activity, DOMRequest)
NS_IMPL_RELEASE_INHERITED(Activity, DOMRequest)
NS_IMPL_CYCLE_COLLECTION_CLASS(Activity)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(Activity,
DOMRequest)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mProxy)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(Activity,
DOMRequest)
NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mProxy)
NS_IMPL_CYCLE_COLLECTION_UNLINK_END
NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN_INHERITED(Activity, DOMRequest)
NS_IMPL_CYCLE_COLLECTION_TRACE_END
NS_IMETHODIMP
Activity::Initialize(nsISupports* aOwner,
JSContext* aContext,
JSObject* aObject,
uint32_t aArgc,
JS::Value* aArgv)
{
nsCOMPtr<nsPIDOMWindow> window = do_QueryInterface(aOwner);
NS_ENSURE_TRUE(window, NS_ERROR_UNEXPECTED);
Init(window);
nsCOMPtr<nsIDocument> document = do_QueryInterface(window->GetExtantDoc());
bool isActive;
window->GetDocShell()->GetIsActive(&isActive);
if (!isActive &&
!nsContentUtils::IsChromeDoc(document)) {
nsCOMPtr<nsIDOMRequestService> rs =
do_GetService("@mozilla.org/dom/dom-request-service;1");
rs->FireErrorAsync(static_cast<DOMRequest*>(this),
NS_LITERAL_STRING("NotUserInput"));
nsCOMPtr<nsIConsoleService> console(
do_GetService("@mozilla.org/consoleservice;1"));
NS_ENSURE_TRUE(console, NS_OK);
nsString message =
NS_LITERAL_STRING("Can start activity from non user input or chrome code");
console->LogStringMessage(message.get());
return NS_OK;
}
// We expect a single argument, which is a nsIDOMMozActivityOptions.
if (aArgc != 1 || !aArgv[0].isObject()) {
return NS_ERROR_INVALID_ARG;
}
nsCOMPtr<nsISupports> tmp;
nsContentUtils::XPConnect()->WrapJS(aContext, aArgv[0].toObjectOrNull(),
NS_GET_IID(nsIDOMMozActivityOptions),
getter_AddRefs(tmp));
nsCOMPtr<nsIDOMMozActivityOptions> options = do_QueryInterface(tmp);
if (!options) {
return NS_ERROR_INVALID_ARG;
}
// Instantiate a JS proxy that will do the child <-> parent communication
// with the JS implementation of the backend.
nsresult rv;
mProxy = do_CreateInstance("@mozilla.org/dom/activities/proxy;1", &rv);
NS_ENSURE_SUCCESS(rv, rv);
mProxy->StartActivity(this, options, window);
return NS_OK;
}
Activity::~Activity()
{
if (mProxy) {
mProxy->Cleanup();
}
}
Activity::Activity()
: DOMRequest()
{
// Unfortunately we must explicitly declare the default constructor in order
// to prevent an implicitly deleted constructor in DOMRequest compile error
// in GCC 4.6.
}
| [
"[email protected]"
] | |
b7ff09653f625a9a1f3265d99da29b41127f1981 | c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64 | /Engine/Source/Programs/UnrealHeaderTool/Private/Scope.cpp | 264147f3403e52b6337c01e4648d6ed3e7087bb4 | [
"MIT",
"LicenseRef-scancode-proprietary-license"
] | permissive | windystrife/UnrealEngine_NVIDIAGameWorks | c3c7863083653caf1bc67d3ef104fb4b9f302e2a | b50e6338a7c5b26374d66306ebc7807541ff815e | refs/heads/4.18-GameWorks | 2023-03-11T02:50:08.471040 | 2022-01-13T20:50:29 | 2022-01-13T20:50:29 | 124,100,479 | 262 | 179 | MIT | 2022-12-16T05:36:38 | 2018-03-06T15:44:09 | C++ | UTF-8 | C++ | false | false | 3,939 | cpp | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "Scope.h"
#include "UnrealHeaderTool.h"
#include "UObject/ErrorException.h"
#include "ParserHelper.h"
extern FCompilerMetadataManager GScriptHelper;
FScope::FScope(FScope* InParent)
: Parent(InParent)
{ }
FScope::FScope()
: Parent(nullptr)
{
}
void FScope::AddType(UField* Type)
{
TypeMap.Add(Type->GetFName(), Type);
}
/**
* Dispatch type to one of three arrays Enums, Structs and DelegateFunctions.
*
* @param Type Input type.
* @param Enums (Output parameter) Array to fill with enums.
* @param Structs (Output parameter) Array to fill with structs.
* @param DelegateFunctions (Output parameter) Array to fill with delegate functions.
*/
void DispatchType(UField* Type, TArray<UEnum*> &Enums, TArray<UScriptStruct*> &Structs, TArray<UDelegateFunction*> &DelegateFunctions)
{
UClass* TypeClass = Type->GetClass();
if (TypeClass == UClass::StaticClass() || TypeClass == UStruct::StaticClass())
{
// Inner scopes.
FScope::GetTypeScope((UStruct*)Type)->SplitTypesIntoArrays(Enums, Structs, DelegateFunctions);
}
else if (TypeClass == UEnum::StaticClass())
{
UEnum* Enum = (UEnum*)Type;
Enums.Add(Enum);
}
else if (TypeClass == UScriptStruct::StaticClass())
{
UScriptStruct* Struct = (UScriptStruct*)Type;
Structs.Add(Struct);
}
else if (TypeClass == UDelegateFunction::StaticClass())
{
bool bAdded = false;
UDelegateFunction* Function = (UDelegateFunction*)Type;
if (Function->GetSuperFunction() == NULL)
{
DelegateFunctions.Add(Function);
bAdded = true;
}
check(bAdded);
}
}
void FScope::SplitTypesIntoArrays(TArray<UEnum*>& Enums, TArray<UScriptStruct*>& Structs, TArray<UDelegateFunction*>& DelegateFunctions)
{
for (auto& TypePair : TypeMap)
{
auto* Type = TypePair.Value;
DispatchType(Type, Enums, Structs, DelegateFunctions);
}
}
TSharedRef<FScope> FScope::GetTypeScope(UStruct* Type)
{
auto* ScopeRefPtr = ScopeMap.Find(Type);
if (!ScopeRefPtr)
{
FError::Throwf(TEXT("Couldn't find scope for the type %s."), *Type->GetName());
}
return *ScopeRefPtr;
}
TSharedRef<FScope> FScope::AddTypeScope(UStruct* Type, FScope* ParentScope)
{
FStructScope* ScopePtr = new FStructScope(Type, ParentScope);
TSharedRef<FScope> Scope = MakeShareable(ScopePtr);
ScopeMap.Add(Type, Scope);
return Scope;
}
UField* FScope::FindTypeByName(FName Name)
{
auto TypeIterator = TDeepScopeTypeIterator<UField, false>(this);
while (TypeIterator.MoveNext())
{
auto* Type = *TypeIterator;
if (Type->GetFName() == Name)
{
return Type;
}
}
return nullptr;
}
const UField* FScope::FindTypeByName(FName Name) const
{
auto TypeIterator = GetTypeIterator();
while (TypeIterator.MoveNext())
{
auto* Type = *TypeIterator;
if (Type->GetFName() == Name)
{
return Type;
}
}
return nullptr;
}
bool FScope::ContainsType(UField* Type)
{
return FindTypeByName(Type->GetFName()) != nullptr;
}
bool FScope::IsFileScope() const
{
return Parent == nullptr;
}
bool FScope::ContainsTypes() const
{
return TypeMap.Num() > 0;
}
FFileScope* FScope::GetFileScope()
{
FScope* CurrentScope = this;
while (!CurrentScope->IsFileScope())
{
CurrentScope = const_cast<FScope*>(CurrentScope->GetParent());
}
return CurrentScope->AsFileScope();
}
TMap<UStruct*, TSharedRef<FScope> > FScope::ScopeMap;
FFileScope::FFileScope(FName InName, FUnrealSourceFile* InSourceFile)
: SourceFile(InSourceFile), Name(InName)
{ }
void FFileScope::IncludeScope(FFileScope* IncludedScope)
{
IncludedScopes.Add(IncludedScope);
}
FUnrealSourceFile* FFileScope::GetSourceFile() const
{
return SourceFile;
}
FName FFileScope::GetName() const
{
return Name;
}
UStruct* FStructScope::GetStruct() const
{
return Struct;
}
FName FStructScope::GetName() const
{
return Struct->GetFName();
}
FStructScope::FStructScope(UStruct* InStruct, FScope* InParent)
: FScope(InParent), Struct(InStruct)
{
}
| [
"[email protected]"
] | |
74ea9a4b12d5be82b848485eb472da43811c6f99 | 5d83739af703fb400857cecc69aadaf02e07f8d1 | /Archive2/62/5cb0f476ea3333/main.cpp | aa3f9d29b0c4983b3bbe256ec00880ccec2ed6d1 | [] | no_license | WhiZTiM/coliru | 3a6c4c0bdac566d1aa1c21818118ba70479b0f40 | 2c72c048846c082f943e6c7f9fa8d94aee76979f | refs/heads/master | 2021-01-01T05:10:33.812560 | 2015-08-24T19:09:22 | 2015-08-24T19:09:22 | 56,789,706 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,368 | cpp | #include <iostream>
#include <string>
#include <vector>
#include <mutex>
#include <chrono>
int main()
{
typedef std::chrono::high_resolution_clock Clock;
typedef std::chrono::time_point<Clock> Timestamp;
typedef std::chrono::nanoseconds Duration;
Timestamp st, en;
st = Clock::now();
std::array<std::mutex, 10000> locks;
en = Clock::now();
std::cout << "Construct mutex elapsed: " << std::chrono::duration_cast<Duration>(en - st).count() / 10000 << "ns each" << std::endl;
st = Clock::now();
std::array<std::unique_lock<std::mutex>, 10000> holders;
en = Clock::now();
std::cout << "Construct unique_lock elapsed: " << std::chrono::duration_cast<Duration>(en - st).count() / 10000 << "ns each" << std::endl;
st = Clock::now();
for (auto i = 0; i < 10000; ++i)
holders[i] = std::unique_lock<std::mutex>(locks[i]);
en = Clock::now();
std::cout << "Acquire unique_lock elapsed: " << std::chrono::duration_cast<Duration>(en - st).count() / 10000 << "ns each" << std::endl;
st = Clock::now();
for (auto i = 0; i < 10000; ++i)
holders[i].unlock();
en = Clock::now();
std::cout << "Release unique_lock elapsed: " << std::chrono::duration_cast<Duration>(en - st).count() / 10000 << "ns each" << std::endl;
std::cout << "Size: " << sizeof(std::mutex) << std::endl;
}
| [
"francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df"
] | francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df |
0f1dabfb9de1ea8b4016f2c555785388a8dcc71d | ea6d5494d9f4f5a15a703aff3f3608e8a949da14 | /期末project/code/Classes/GameScene1.cpp | 723c86254637545a6d7896f6c27bfb888a8be8a9 | [
"MIT"
] | permissive | 54huaxiao/Cocos2d-Game | b54ed255575a26d2162805b4abe3b4f6b7847b89 | 35aca88812b17e9152e65333e604b34fe33eeafc | refs/heads/master | 2022-09-02T17:31:22.239608 | 2016-08-20T14:16:44 | 2016-08-20T14:16:57 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 22,812 | cpp | #include "GameScene1.h"
#include <stdlib.h>
#include "SimpleAudioEngine.h"
#include "GameScene2.h"
using namespace CocosDenshion;
//--------------------------------------------------------------------
// 设置难度: 简单【2】;中等【3】;难【4】;变态难【5】
// 难度体现: 攻击(子弹、陨石)个数;清屏工具大小、出现时间;初始血量多少
//
// 游戏玩法: 按【A/方向左】【D/方向右】移动,【空格键】跳跃;
// 要躲避陨石、子弹、炸弹的攻击,受攻击则掉血;
// 要收集20颗钻石,收集完见到胜利Logo,靠近则跳转到下一场景。
//--------------------------------------------------------------------
//#define DIFFICULTY 2
USING_NS_CC;
void GameScene1::setPhysicsWorld(PhysicsWorld * world) {
MyWorld = world;
}
Scene* GameScene1::createScene(int difficulty_send)
{
auto scene = Scene::createWithPhysics();
//scene->getPhysicsWorld()->setDebugDrawMask(PhysicsWorld::DEBUGDRAW_ALL);
scene->getPhysicsWorld()->setGravity(Vec2(0, -600.0f));
// 传递PhysicsWorld
auto layer = GameScene1::create(scene->getPhysicsWorld(), difficulty_send);
scene->addChild(layer);
return scene;
}
// on "init" you need to initialize your instance
bool GameScene1::init(PhysicsWorld * world, int difficulty_send)
{
if ( !Layer::init() )
{
return false;
}
this->setPhysicsWorld(world);
visibleSize = Director::getInstance()->getVisibleSize();
origin = Director::getInstance()->getVisibleOrigin();
DIFFICULTY = difficulty_send;
leftMoveFlag = false;
rightMoveFlag = false;
jumpFlag = false;
jump_time = 0.0;
lastkey = 'D';
clearTool = true;
bloodTool = true;
victory_flag = false;
leftBlood = 10 - DIFFICULTY;
addBackgroundEdge();
preloadMusic();
play_bgm();
auto bg_photo = Sprite::create("bg/bg7.jpg");
bg_photo->setScale(0.8f);
bg_photo->setPosition(visibleSize / 2);
this->addChild(bg_photo, 0);
// 运动动画
auto texture = Director::getInstance()->getTextureCache()->addImage("$lucia_forward.png");
for (int i = 0; i < 8; i++) {
auto frame = SpriteFrame::createWithTexture(texture, CC_RECT_PIXELS_TO_POINTS(Rect(68 * i, 0, 68, 101)));
run.pushBack(frame);
}
//玩家player
player = Sprite::createWithSpriteFrame(run.at(0));
player->setPosition(Vec2(visibleSize.width / 2, 2));
player->setPhysicsBody(PhysicsBody::createCircle(35));
player->getPhysicsBody()->setCategoryBitmask(0x03); //0011
player->getPhysicsBody()->setCollisionBitmask(0x03); //0011
player->getPhysicsBody()->setContactTestBitmask(0x02); //0010
this->addChild(player);
//蓄力条bg
jumpLength_bg = Sprite::create("photo.png", CC_RECT_PIXELS_TO_POINTS(Rect(232, 429, 117, 33)));
jumpLength_bg->setPosition(Vec2(player->getPositionX(), player->getPositionY() + 70));
jumpLength_bg->setVisible(false);
this->addChild(jumpLength_bg, 1);
//蓄力条
jumpLength_inner = Sprite::create("photo.png", CC_RECT_PIXELS_TO_POINTS(Rect(610, 362, 4, 16)));
jumpLength_progress = ProgressTimer::create(jumpLength_inner);
jumpLength_progress->setScaleX(1);
jumpLength_progress->setAnchorPoint(Vec2(0, 0));
jumpLength_progress->setType(ProgressTimerType::BAR);
jumpLength_progress->setBarChangeRate(Point(1, 0));
jumpLength_progress->setMidpoint(Point(0, 1));
jumpLength_progress->setPercentage(100);
jumpLength_progress->setPosition(Vec2(jumpLength_bg->getPositionX() - 14, jumpLength_bg->getPositionY() - 9));
jumpLength_progress->setVisible(false);
addChild(jumpLength_progress, 1);
//左右头盖骨
skull_right = Sprite::createWithSpriteFrameName("skull.png");
skull_left = Sprite::createWithSpriteFrameName("skull.png");
skull_right->setScale(1.5);
skull_left->setScale(1.5);
skull_right->setPosition(Vec2(visibleSize.width - 48, 40));
skull_right->setRotation(35.0f);
skull_left->setPosition(Vec2(48, 40));
skull_left->setRotation(-35.0f);
skull_left->setFlipX(true);
this->addChild(skull_right, 1);
this->addChild(skull_left, 1);
TTFConfig ttfConfig;
ttfConfig.fontFilePath = "fonts/Marker Felt.ttf";
ttfConfig.fontSize = 44;
//获得diamond数
auto diamond_text = Label::createWithTTF(ttfConfig, "Diamond: / 20");
diamond_text->setColor(Color3B::WHITE);
diamond_text->setPosition(Vec2(visibleSize.width - 155, visibleSize.height - 45));
diamond_num = Label::createWithTTF(ttfConfig, "0");
diamond_num->setColor(Color3B::WHITE);
diamond_num->setPosition(Vec2(visibleSize.width - 111, visibleSize.height - 45));
this->addChild(diamond_text, 2);
this->addChild(diamond_num, 2);
//初始化钻石集 diamond_set
diamond_index = 0;
get_diamond_num = 0;
diamond_set.resize(20);
diamond_in_scene = false;
//初始化生命值
auto blood_label = Label::createWithTTF(ttfConfig, "Blood:");
blood_label->setColor(Color3B::WHITE);
blood_label->setPosition(Vec2(55, visibleSize.height - 45));
this->addChild(blood_label, 2);
for (int i = 0; i < leftBlood; i++) {
auto blood = Sprite::createWithSpriteFrame(run.at(0));
blood->setScale(0.6f);
blood->setPosition(Vec2(blood_label->getPositionX() + (i + 1) * 30 + 50, blood_label->getPositionY()));
player_blood.pushBack(blood);
this->addChild(blood, 2);
}
//调度器:更新 跳跃蓄力时间、跳跃力度、左右移动、蓄力条的位置、stone拐弯、检测钻石是否被获取、
// 飞出的子弹清空、检测清屏道具/回血包是否被获取、player是否触碰到stone/bullet/bomb
schedule(schedule_selector(GameScene1::updateSomething), 0.02f, kRepeatForever, 0);
//调度器:更新 游戏胜利时刻
schedule(schedule_selector(GameScene1::VictoryTime), 0.05f, kRepeatForever, 0);
//调度器:更新 头盖骨喷火
schedule(schedule_selector(GameScene1::skullFire), 1.0f, kRepeatForever, 0);
//调度器:更新 产生钻石
schedule(schedule_selector(GameScene1::createDiamond), 2.0f, kRepeatForever, 0);
//调度器:更新 产生enemy
schedule(schedule_selector(GameScene1::createEnemy), 3.0f, kRepeatForever, 0);
//调度器:更新 炸弹爆炸
schedule(schedule_selector(GameScene1::bombExplosion), 4.5f, kRepeatForever, 3.0f);
addKeyboardListener();
return true;
}
GameScene1* GameScene1::create(PhysicsWorld * world, int difficulty_send) {
GameScene1* pRet = new(std::nothrow) GameScene1();
if (pRet && pRet->init(world, difficulty_send)) {
pRet->autorelease();
return pRet;
}
delete pRet;
pRet = NULL;
return NULL;
}
void GameScene1::addBackgroundEdge() {
auto edgeSp = Sprite::create();
auto boundbody = PhysicsBody::createEdgeBox(visibleSize);
boundbody->setDynamic(false);
edgeSp->setPosition(Point(visibleSize.width / 2, visibleSize.height / 2));
edgeSp->setPhysicsBody(boundbody);
this->addChild(edgeSp);
}
void GameScene1::preloadMusic() {
SimpleAudioEngine::getInstance()->preloadBackgroundMusic("sound/bgm1.mp3");
SimpleAudioEngine::getInstance()->preloadBackgroundMusic("sound/bgm2.mp3");
SimpleAudioEngine::getInstance()->preloadBackgroundMusic("sound/bgm3.mp3");
SimpleAudioEngine::getInstance()->preloadEffect("sound/beingAttack.wav");
SimpleAudioEngine::getInstance()->preloadEffect("sound/blood_Tool.mp3");
SimpleAudioEngine::getInstance()->preloadEffect("sound/bomb.wav");
SimpleAudioEngine::getInstance()->preloadEffect("sound/bullet.wav");
SimpleAudioEngine::getInstance()->preloadEffect("sound/clear_Tool.wav");
SimpleAudioEngine::getInstance()->preloadEffect("sound/get_diamond.wav");
SimpleAudioEngine::getInstance()->preloadEffect("sound/jump.wav");
SimpleAudioEngine::getInstance()->preloadEffect("sound/stone.wav");
SimpleAudioEngine::getInstance()->preloadEffect("sound/explore.wav");
}
void GameScene1::play_bgm() {
SimpleAudioEngine::getInstance()->playBackgroundMusic("sound/bgm1.mp3", true);
}
void GameScene1::addKeyboardListener() {
auto keyboardListener = EventListenerKeyboard::create();
keyboardListener->onKeyPressed = CC_CALLBACK_2(GameScene1::onKeyPressed, this);
keyboardListener->onKeyReleased = CC_CALLBACK_2(GameScene1::onKeyReleased, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(keyboardListener, this);
}
void GameScene1::onKeyPressed(EventKeyboard::KeyCode code, Event* event) {
//-----------------------
// 跳跃和移动状态并发执行
//-----------------------
// 跳跃的情况
if (player->getPositionY() <= 37 && code == EventKeyboard::KeyCode::KEY_SPACE) {
jumpFlag = true;
jumpLength_bg->setVisible(true);
jumpLength_progress->setVisible(true);
}
// 左右移动
if (code == EventKeyboard::KeyCode::KEY_A || code == EventKeyboard::KeyCode::KEY_LEFT_ARROW) {
leftMoveFlag = true;
if (lastkey == 'D') {
lastkey = 'A';
player->setFlipX(true);
}
}
else if (code == EventKeyboard::KeyCode::KEY_D || code == EventKeyboard::KeyCode::KEY_RIGHT_ARROW) {
rightMoveFlag = true;
if (lastkey == 'A') {
lastkey = 'D';
player->setFlipX(false);
}
}
if (code == EventKeyboard::KeyCode::KEY_Q) {
this->Quit(this, 'Q');
}
}
void GameScene1::onKeyReleased(EventKeyboard::KeyCode code, Event* event) {
if (jumpFlag && code == EventKeyboard::KeyCode::KEY_SPACE) {
player->getPhysicsBody()->setVelocity(Vec2(0, jump_time * 400.0f + 400.0f));
SimpleAudioEngine::getInstance()->playEffect("sound/jump.wav");
jump_time = 0.0;
jumpFlag = false;
jumpLength_bg->setVisible(false);
jumpLength_progress->setVisible(false);
jumpLength_progress->setScaleX(1);
}
if (code == EventKeyboard::KeyCode::KEY_A || code == EventKeyboard::KeyCode::KEY_LEFT_ARROW) {
leftMoveFlag = false;
}
else if (code == EventKeyboard::KeyCode::KEY_D || code == EventKeyboard::KeyCode::KEY_RIGHT_ARROW) {
rightMoveFlag = false;
}
}
void GameScene1::updateSomething(float dt) {
//跳跃蓄力时间、跳跃力度
if (jumpFlag) {
if (jump_time <= 1.00f) {
jump_time += 0.02;
jumpLength_progress->setScaleX(jump_time * 15);
}
}
//左右移动
if (leftMoveFlag) {
player->setPositionX(player->getPositionX() - 150 * dt);
}
else if (rightMoveFlag) {
player->setPositionX(player->getPositionX() + 150 * dt);
}
//蓄力条的位置跟着player移动
jumpLength_bg->setPosition(Vec2(player->getPositionX(), player->getPositionY() + 70));
jumpLength_progress->setPosition(Vec2(jumpLength_bg->getPositionX() - 14, jumpLength_bg->getPositionY() - 9));
//stone拐弯
for (int i = 0; i < stone_set.size(); i++) {
if (stone_set.at(i)->getPositionX() == stone_set.at(i)->getTag()) {
if (stone_set.at(i)->getPositionY() <= visibleSize.height + 25) {
stone_set.at(i)->setPositionY(stone_set.at(i)->getPositionY() + 7);
}
else { //飞出界面的stone
stone_set.at(i)->removeFromParentAndCleanup(true);
stone_set.eraseObject(stone_set.at(i), false);
}
}
}
//检测钻石是否被获取
if (diamond_in_scene && diamond_index <= 20) {
if (diamond_set.at(diamond_index - 1)->getPosition().getDistance(player->getPosition()) < 25) {
SimpleAudioEngine::getInstance()->playEffect("sound/get_diamond.wav");
get_diamond_num++;
char num[10];
sprintf(num, "%d", get_diamond_num);
diamond_num->setString(num);
diamond_set.at(diamond_index - 1)->setVisible(false);
diamond_set.at(diamond_index - 1) = NULL;
diamond_in_scene = false;
//获得20个钻石,出现胜利label,清屏,跳转页面
if (get_diamond_num == 20) {
win_label = Sprite::create("photo.png", CC_RECT_PIXELS_TO_POINTS(Rect(0, 0, 610, 320)));
win_label->setPosition(visibleSize / 2);
this->addChild(win_label, 3);
victory_flag = true;
}
}
}
//飞出的子弹清空
for (int i = 0; i < bullet_set.size(); i++) {
if (bullet_set.at(i)->getPositionX() < -40 || bullet_set.at(i)->getPositionX() > visibleSize.width + 40) {
bullet_set.at(i)->removeFromParentAndCleanup(true);
bullet_set.eraseObject(bullet_set.at(i), false);
}
}
//检测清屏道具是否被获取
if (clear_Tool != NULL && clear_Tool->getPosition().getDistance(player->getPosition()) < (75 - DIFFICULTY * 10)) {
ClearAllAttack();
}
//检测回血包是否被获取
if (blood_Tool != NULL && blood_Tool->getPosition().getDistance(player->getPosition()) < 30) {
SimpleAudioEngine::getInstance()->playEffect("sound/blood_Tool.mp3");
int count = 0;
for (int i = leftBlood; i < player_blood.size(); i++) {
if (count < 3) {
player_blood.at(i)->setVisible(true);
count++;
leftBlood++;
}
else
break;
}
blood_Tool->setVisible(false);
blood_Tool = NULL;
}
//player是否触碰到stone
for (int i = 0; i < stone_set.size(); i++) {
if (stone_set.at(i)->getPosition().getDistance(player->getPosition()) < 25) {
//爆炸效果
auto hurtExploration = ParticleSun::createWithTotalParticles(150);
hurtExploration->setPosition(player->getPosition());
hurtExploration->setDuration(1.5f);
this->addChild(hurtExploration);
BeingAttacked();
}
}
//player是否触碰到bullet
for (int i = 0; i < bullet_set.size(); i++) {
if (bullet_set.at(i)->getPosition().getDistance(player->getPosition()) < 25) {
//爆炸效果
auto hurtExploration = ParticleSun::createWithTotalParticles(150);
hurtExploration->setPosition(player->getPosition());
hurtExploration->setDuration(1.5f);
this->addChild(hurtExploration);
BeingAttacked();
}
}
//player是否触碰到bomb
for (int i = 0; i < bomb_set.size(); i++) {
if (bomb_set.at(i)->getPosition().getDistance(player->getPosition()) < 25) {
//爆炸效果
auto hurtExploration = ParticleSun::createWithTotalParticles(150);
hurtExploration->setPosition(player->getPosition());
hurtExploration->setDuration(1.5f);
this->addChild(hurtExploration);
BeingAttacked();
}
}
}
void GameScene1::skullFire(float dt) {
int timePlus, destPlus;
float destX;
timePlus = rand() % 7 + 1;
if (timePlus == 1 || timePlus == 7) {
destPlus = rand() % 4 + 1;
destX = visibleSize.width / 5 * destPlus;
if (timePlus == 1)
skull_fire_stone(destX, 'L');
else
skull_fire_stone(destX, 'R');
}
}
void GameScene1::skull_fire_stone(float destX, char direc) {
for (int i = 0; i < DIFFICULTY; i++) {
SimpleAudioEngine::getInstance()->playEffect("sound/stone.wav");
auto stone = Sprite::create("stone.png");
MoveTo* moveto;
if (direc == 'L') {
stone->setPosition(Vec2(skull_left->getPositionX() + 50, skull_left->getPositionY() - 5));
moveto = MoveTo::create((destX - stone->getPositionX()) * 0.003, Vec2(destX, stone->getPositionY()));
}
else {
stone->setPosition(Vec2(skull_right->getPositionX() - 50, skull_right->getPositionY() - 5));
moveto = MoveTo::create((stone->getPositionX() - destX) * 0.003, Vec2(destX, stone->getPositionY()));
}
stone->setScale(0.5);
stone->setTag(destX);
this->addChild(stone, 1);
stone_set.pushBack(stone);
auto delayTime = DelayTime::create(i * 0.15f);
auto sequ = Sequence::create(delayTime, moveto, NULL);
stone->runAction(sequ);
}
}
void GameScene1::createDiamond(float dt) {
int randX, randY;
float destX, destY;
randX = rand() % 15 + 1; // 1 - 15
randY = rand() % 10 + 1; // 1 - 10
destX = visibleSize.width / 17 * randX;
destY = visibleSize.height / 2 / 15 * randY + visibleSize.height / 2;
if (diamond_index == 0) {
auto diamond = Sprite::create("diamond.png");
diamond_set.at(diamond_index) = diamond;
diamond_set.at(diamond_index)->setPosition(Vec2(destX, destY));
this->addChild(diamond_set.at(diamond_index), 1);
diamond_index++;
diamond_in_scene = true;
}
else if (diamond_index < 20) {
if (diamond_set.at(diamond_index - 1) == NULL) {
auto diamond = Sprite::create("diamond.png");
diamond_set.at(diamond_index) = diamond;
diamond_set.at(diamond_index)->setPosition(Vec2(destX, destY));
this->addChild(diamond_set.at(diamond_index), 1);
diamond_index++;
diamond_in_scene = true;
}
}
}
void GameScene1::createEnemy(float dt) {
// enemyB 某时候出现: 4、7、10、13(其一)掉清屏道具、15掉回血包、其余掉炸弹
if (get_diamond_num == DIFFICULTY * 3 - 2 ||
get_diamond_num == 15 ||
get_diamond_num == 6 || get_diamond_num == 9 || get_diamond_num == 16 ||
get_diamond_num == 17 || get_diamond_num == 18 || get_diamond_num == 19) {
int X_rand = rand() % 13;
float X_pos = visibleSize.width / 16 * X_rand + 50;
auto enemyB = Sprite::create("photo.png", CC_RECT_PIXELS_TO_POINTS(Rect(860, 130, 100, 100)));
enemyB->setPosition(Vec2(X_pos, visibleSize.height + 60));
this->addChild(enemyB, 2);
auto moveDown = MoveBy::create(0.4f, Vec2(0, -110));
auto moveUp = MoveBy::create(0.4f, Vec2(0, 110));
auto delay = DelayTime::create(1.4f);
auto seq = Sequence::create(moveDown, delay, moveUp, NULL);
enemyB->runAction(seq);
char op;
if (clearTool && get_diamond_num == DIFFICULTY * 3 - 2) { //清屏clear
op = 'C';
clearTool = false;
}
else if (bloodTool && get_diamond_num == 15) { //回血blood
op = 'B';
bloodTool = false;
}
else { //放炸弹
op = 'A';
}
enemyBout(X_pos, op);
}
// enemyA 永远出现
int LorR_rand = rand() % 2; // 左0、右1
int Y_rand = rand() % 10;
float verti_height = visibleSize.height / 3 * 2 / 13 * Y_rand + visibleSize.height / 3;
auto enemyA = Sprite::create("enemyA.png");
MoveBy* moveOut;
MoveBy* moveIn;
if (LorR_rand == 0) { //左
enemyA->setPosition(Vec2(-30, verti_height));
enemyA->setRotation(90.0f);
moveOut = MoveBy::create(0.2f, Vec2(65, 0));
moveIn = MoveBy::create(0.5f, Vec2(-65, 0));
}
else { //右
enemyA->setPosition(Vec2(visibleSize.width + 30, verti_height));
enemyA->setRotation(-90.0f);
moveOut = MoveBy::create(0.2f, Vec2(-65, 0));
moveIn = MoveBy::create(0.5f, Vec2(65, 0));
}
this->addChild(enemyA, 1);
auto delay = DelayTime::create(1.0f);
auto seq = Sequence::create(moveOut, delay, moveIn, NULL);
enemyA->runAction(seq);
enemyAfire(verti_height, LorR_rand);
}
void GameScene1::enemyAfire(float verti_height, int direc) {
for (int i = 0; i < DIFFICULTY; i++) {
SimpleAudioEngine::getInstance()->playEffect("sound/bullet.wav");
auto bullet = Sprite::create("bullet.png");
MoveTo* moveto;
if (direc == 0) { // 左
bullet->setRotation(90.0f);
bullet->setPosition(Vec2(80, verti_height));
moveto = MoveTo::create(2.2f, Vec2(visibleSize.width + 50, bullet->getPositionY()));
}
else { // 右
bullet->setRotation(-90.0f);
bullet->setPosition(Vec2(visibleSize.width - 80, verti_height));
moveto = MoveTo::create(2.2f, Vec2(-50, bullet->getPositionY()));
}
this->addChild(bullet, 2);
bullet_set.pushBack(bullet);
auto delayTime = DelayTime::create(i * 0.15f);
auto sequ = Sequence::create(delayTime, moveto, NULL);
bullet->runAction(sequ);
}
}
void GameScene1::enemyBout(float X_pos, char op) {
int height_rand = rand() % 6 + 1;
auto moveby = MoveBy::create(0.75f + height_rand*0.08, Vec2(0, -180 - height_rand * 50));
if (op == 'A') { //放炸弹
auto bomb = Sprite::createWithSpriteFrameName("TNT.png");
bomb->setPosition(Vec2(X_pos, visibleSize.height + 40));
bomb->setScale(0.7f);
bomb_set.pushBack(bomb);
this->addChild(bomb, 1);
bomb->runAction(moveby);
}
else if (op == 'B') { //回血包
blood_Tool = Sprite::createWithSpriteFrameName("treasure-bag.png");
blood_Tool->setPosition(Vec2(X_pos, visibleSize.height + 40));
this->addChild(blood_Tool, 1);
blood_Tool->runAction(moveby);
}
else if (op == 'C') { //清屏道具
SimpleAudioEngine::getInstance()->playEffect("sound/clear_Tool.wav");
clear_Tool = Sprite::create("photo.png", CC_RECT_PIXELS_TO_POINTS(Rect(620, 0, 242, 245)));
clear_Tool->setPosition(Vec2(X_pos, visibleSize.height + 40));
float scale = 0.45f - 0.05f * DIFFICULTY;
clear_Tool->setScale(scale);
this->addChild(clear_Tool, 1);
clear_Tool->runAction(moveby);
}
}
void GameScene1::bombExplosion(float dt) {
if (bomb_set.size() > 0) {
//爆炸
SimpleAudioEngine::getInstance()->playEffect("sound/bomb.wav");
auto explosion = ParticleExplosion::createWithTotalParticles(50);
explosion->setPosition(bomb_set.at(0)->getPosition());
this->addChild(explosion, 2);
//判断玩家是否在爆炸周围
if (bomb_set.at(0)->getPosition().getDistance(player->getPosition()) < 80) {
BeingAttacked();
}
else {
//清除炸弹
bomb_set.at(0)->removeFromParentAndCleanup(true);
bomb_set.eraseObject(bomb_set.at(0), false);
}
}
}
void GameScene1::ClearAllAttack() {
SimpleAudioEngine::getInstance()->playEffect("sound/explore.wav");
while (stone_set.size() > 0) {
auto explosion = ParticleExplosion::createWithTotalParticles(50);
explosion->setPosition(stone_set.at(0)->getPosition());
this->addChild(explosion, 2);
stone_set.at(0)->removeFromParentAndCleanup(true);
stone_set.eraseObject(stone_set.at(0), false);
}
while (bullet_set.size() > 0) {
auto explosion = ParticleExplosion::createWithTotalParticles(50);
explosion->setPosition(bullet_set.at(0)->getPosition());
this->addChild(explosion, 2);
bullet_set.at(0)->removeFromParentAndCleanup(true);
bullet_set.eraseObject(bullet_set.at(0), false);
}
while (bomb_set.size() > 0) {
auto explosion = ParticleExplosion::createWithTotalParticles(50);
explosion->setPosition(bomb_set.at(0)->getPosition());
this->addChild(explosion, 2);
bomb_set.at(0)->removeFromParentAndCleanup(true);
bomb_set.eraseObject(bomb_set.at(0), false);
}
}
void GameScene1::BeingAttacked() {
SimpleAudioEngine::getInstance()->playEffect("sound/beingAttack.wav");
//扣血
if (leftBlood > 0) {
player_blood.at(leftBlood - 1)->setVisible(false);
leftBlood--;
if (leftBlood == 0) {
//----------------------------------
// player血量为0,GameOver
//----------------------------------
auto label = Label::createWithTTF("Game Over!!", "fonts/Marker Felt.TTF", 50);
label->setColor(Color3B(255, 255, 255));
label->setPosition(Vec2(visibleSize.width / 2, visibleSize.height - label->getContentSize().height - 180));
this->addChild(label, 1);
ClearAllAttack();
_eventDispatcher->removeAllEventListeners();
return;
}
}
//清屏
ClearAllAttack();
//玩家回到固定位置
player->setPosition(Vec2(visibleSize.width / 2, 100));
}
void GameScene1::VictoryTime(float dt) {
if (victory_flag) {
ClearAllAttack();
if (win_label != NULL) {
if (win_label->getPosition().getDistance(player->getPosition()) < 160) {
auto scene = GameScene2::createScene();
// 让导演用场景替换现在的场景
Director::getInstance()->replaceScene(scene);
}
}
}
}
void GameScene1::Quit(Ref*, char cid) {
if (cid == 'Q') {
auto gameEnd = GameScene2::createScene();
Director::getInstance()->replaceScene(gameEnd);
}
} | [
"[email protected]"
] | |
2b9ce957eb94e79cdd139032b6b2148e03a5c1ac | 6bd203e7cf256fd7cbb0ff5aab313e7954c89da5 | /node_modules/realm/src/node/node_exception.hpp | 17eca27fb2e5ec116f366533682768aa2e085ec1 | [
"MIT",
"Apache-2.0",
"LicenseRef-scancode-generic-export-compliance",
"LicenseRef-scancode-realm-platform-extension-2017"
] | permissive | Jhones1001/ListarRepos | c8771109426e52e7642dd4ebcaed2540fb2ada25 | 31512618233b1565817dc662110bf7493a31a143 | refs/heads/master | 2022-12-12T17:51:31.214559 | 2020-01-18T17:26:34 | 2020-01-18T17:26:34 | 234,766,294 | 0 | 0 | MIT | 2022-12-10T15:20:25 | 2020-01-18T16:52:42 | Java | UTF-8 | C++ | false | false | 999 | hpp | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2016 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
#pragma once
#include "node_types.hpp"
namespace realm {
namespace js {
template<>
inline v8::Local<v8::Value> node::Exception::value(v8::Isolate* isolate, const std::string &message) {
return Nan::Error(message.c_str());
}
} // js
} // realm
| [
"[email protected]"
] | |
878af2c70ca94f66a50ae8d9481550a51a501106 | 485de741dd7696d495562e13225018b086fff62a | /OOP/CTime.cpp | e3274a6b31b3f4239c33975ed9bf9cb993b81872 | [] | no_license | chen-create/C-_homework | d11761b54669df42c22aaaa56d32cf8298abaeb2 | 2f41d0d32b94b50ab79b3fa72e07f5c1353b93dc | refs/heads/master | 2022-11-04T18:40:14.227961 | 2020-06-21T08:51:32 | 2020-06-21T08:51:32 | 273,860,570 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,908 | cpp | #include<iostream>
#include<cmath>
using namespace std;
class CTime
{
public:
CTime(int Year,int Month,int Day,int Hour,int Minute,int Second);
void showTime();
int isvalid();
CTime(CTime&another);
~CTime()
{
cout<<"析构函数被调用"<<endl;
}
int dayDiff(CTime t);
int subdays();
private:
int year,month,day,hour,minute,second;
};
CTime::CTime(int Year=0,int Month=0,int Day=0,int Hour=0,int Minute=0,int Second=0)
{
year=Year;
month=Month;
day=Day;
hour=Hour;
minute=Minute;
second=Second;
int td=0,time=0,date=1;
switch(month)
{
case 1:case 3:case 5:case 7:case 8:case 10:case 12:
if(day<=31)
time=1;break;
case 4:case 6:case 9:case 11:
if(day<=30)
time=1;break;
case 2:
{
if((year%4==0&&year%100!=0||year%400==0)&&(day<=29))
time=1;
else
{
if(day<=28)
time=1;
}
break;
}
}
if(hour>23||minute>59||second>59)
date=0;
if(time==0||date==0)
{
year=0;
month=0;
day=0;
hour=0;
minute=0;
second=0;
}
if(time==0&&date==0)
cout<<"time and date erro!"<<endl;
else if(time==0)
cout<<"date erro!"<<endl;
else if(date==0)
cout<<"time erro!"<<endl;
cout<<"构造函数被调用"<<endl;
}
void CTime::showTime()
{
cout<<year<<"/"<<month<<"/"<<day<<" "<<hour<<":"<<minute<<":"<<second<<endl;
}
CTime::CTime(CTime&another)
{
cout<<"拷贝构造函数被调用"<<endl;
year=another.year;
month=another.month;
day=another.day;
hour=another.hour;
minute=another.minute;
second=another.second;
}
int CTime::isvalid()
{
int td=0,time=0,date=1;
switch(month)
{
case 1:case 3:case 5:case 7:case 8:case 10:case 12:
if(day<=31)
time=1;break;
case 4:case 6:case 9:case 11:
if(day<=30)
time=1;break;
case 2:
{
if((year%4==0&&year%100!=0||year%400==0)&&(day<=29))
time=1;
else
{
if(day<=28)
time=1;
}
break;
}
}
if(hour>23||minute>59||second>59)
date=0;
if(time==1&&date==1)
td=1;
if(time==0||date==0)
{
year=0;
month=0;
day=0;
hour=0;
minute=0;
second=0;
}
return td;
}
int CTime::subdays()
{
int iyear=0, imonth=0, iday=0;
imonth=(month+9)%12;
iyear=year-imonth/10;
iday=365*iyear+iyear/4-iyear/100+iyear/400+(imonth*306+5)/10+(day-1);
return iday;
}
int CTime::dayDiff(CTime t)
{
return abs(subdays()-t.subdays()) ;
}
int main()
{
int year,month,day,hour,minute,second;
cin>>year>>month>>day>>hour>>minute>>second;
CTime t1(year,month,day,hour,minute,second);
t1.showTime();
CTime t2(2000,1,1); //利用默认形参将时间初始化为00:00:00
if(t1.isvalid()) //如果日期和时间合法,则计算天数
{
int days=0;
days=t1.dayDiff(t2);
cout<<"这两天之间相隔了"<<days<<"天"<<endl;
days=t2.dayDiff(t1);
cout<<"这两天之间相隔了"<<days<<"天"<<endl;
}
}
| [
"[email protected]"
] | |
b87ad37a22a63f83be42db8dd4ac42432f2a44ef | 5f4b7850caed77bf1d2ca8d5125dc21099b79209 | /dataStructures/training/1.11 I like.cpp | b8e1a3953f51a2a799676ba0fc4a21f0ef738b33 | [] | no_license | Inuyashaaaaa/IntroductionToAlgorithmicContests | 92720cffae226b6951aa389a14fcaacb94b3c275 | 55c69843f42162ed3b8f661c20f451c1174bfff1 | refs/heads/master | 2020-06-20T00:24:10.893652 | 2020-03-14T06:32:12 | 2020-03-14T06:32:12 | 196,926,192 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 801 | cpp | #include<bits/stdc++.h>
#define LL long long
#define ms(s) memset(s, 0, sizeof(s))
#define REP(i, a, b) for(int i = (a); i < (b); i++)
#define INF 0X7fffffff
using namespace std;
const int maxn = 1e5 + 10;
string s[maxn];
int cnt[maxn];
int name[maxn];
int main() {
// freopen("in.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
ios::sync_with_stdio(false);
cin.tie(0);
int n, m;
cin >> n;
for(int i = 1; i <= n; i++) {
cin >> s[i];
name[i] = i;
}
cin >> m;
int a, b;
ms(cnt);
for(int i = 1; i <= m; i++) {
cin >> a >> b;
name[a] = name[b];
cnt[a] = 1;
cnt[a] += cnt[b];
}
for(int i = 1; i <= cnt[1]; i++) {
cout << "I_love_";
}
cout << s[name[1]] << endl;
return 0;
} | [
"[email protected]"
] | |
48d8b77e956b2d6b22b6b49467599af01cb3dc63 | 5a6e95ea550c1ab70933db273782c79c520ac2ec | /DDK/src/print/oemdll/jtsample/ui/oemjtprovider.hxx | 357ae9b1f945fefd5113ee529e137756de663808 | [] | no_license | 15831944/Longhorn_SDK_And_DDK_4074 | ffa9ce6c99345a6c43a414dab9458e4c29f9eb2a | c07d26bb49ecfa056d00b1dffd8981f50e11c553 | refs/heads/master | 2023-03-21T09:27:53.770894 | 2020-10-10T03:34:29 | 2020-10-10T03:34:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,341 | hxx |
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright 1998 - 2003 Microsoft Corporation. All Rights Reserved.
//
// FILE: oemjtprovider.hxx
//
//
// PURPOSE: Definition of TOEMJTProvider Class.
//
//
#ifndef _OEMJTPROVIDER_HXX_
#define _OEMJTPROVIDER_HXX_
#include "jthandler.hxx"
//
//The Provider class to Implement IPrintOemJobTicketProvider Interface
//
class TOEMJTProvider : public IPrintOemJobTicketProvider
{
public:
//
//Public Methods go here
//
TOEMJTProvider();
~TOEMJTProvider();
//
//Basic COM Methods
//
STDMETHODIMP QueryInterface(THIS_ REFIID riid, void **ppvObj);
STDMETHODIMP_(ULONG) AddRef(THIS);
STDMETHODIMP_(ULONG) Release(THIS);
//
// IPrintOemJobTicketProvider methods
//
STDMETHOD(GetSupportedVersions)( THIS_
IN HANDLE hPrinter,
OUT INT *ppVersions[],
OUT INT *cVersions
) ;
STDMETHOD(BindPrinter)( THIS_
IN HANDLE hPrinter,
IN INT version,
OUT POEMJTOPTS pOptions,
OUT INT *cNamespaces,
OUT BSTR **ppNamespaces
) ;
STDMETHOD(PublishJobTicketHelperInterface)( THIS_
IN IPrintJobTicketPluginHelperUI *pHelper
) ;
STDMETHOD(QueryDeviceDefaultNamespace)( THIS_
OUT BSTR *pbstrNamespaceUri
) ;
STDMETHOD(ConvertJobTicketToDevMode)( THIS_
IN IXMLDOMDocument2 *pJobTicket,
IN ULONG cbDevmode,
IN OUT PDEVMODE pDevmode,
IN ULONG cbDrvPrivateSize,
IN PVOID pPrivateDevmode
) ;
STDMETHOD(ConvertDevModeToJobTicket)( THIS_
IN ULONG cbDevmode,
IN PDEVMODE pDevmode,
IN ULONG cbDrvPrivateSize,
IN PVOID pPrivateDevmode,
IN OUT IXMLDOMDocument2 *pJobTicket
) ;
STDMETHOD(CompleteDeviceCapabilities)( THIS_
IN IXMLDOMDocument2 *pJobTicket,
IN OUT IXMLDOMDocument2 *pCapabilities
) ;
STDMETHOD(CompleteDeviceDefaultJobTicket)( THIS_
IN OUT IXMLDOMDocument2 *pJobTicket
) ;
STDMETHOD(ExpandIntentOptions)( THIS_
IN OUT IXMLDOMDocument2 *pJobTicket
);
STDMETHOD(ValidateJobTicket)( THIS_
IN OUT IXMLDOMDocument2 *pBaseTicket
) ;
private:
//
//Data members go here
//
LONG m_cRef; // COM reference count
HANDLE m_hPrinterCached; // printer handle cached
IPrintJobTicketPluginHelperUI * m_pCoreDriverJTHelp; //cached pointer to plug-in helper interface
//
//Private Methods
//
HRESULT ReadAndDeleteGPDStapleFeatureFromJT(
IN OUT ihvjthandler::JobTicketHandler * jth,
IN OUT INT * stapleIndex
);
HRESULT AddGPDStapleFeatureToJT(
IN OUT ihvjthandler::JobTicketHandler * jth,
IN INT stapleIndex
);
HRESULT ReadAndDeletePrintschemaStapleFeatureFromJT(
IN OUT ihvjthandler::JobTicketHandler * jth,
IN OUT INT * stapleIndex
);
HRESULT ReadAndDeleteGPDStapleFeatureFromDevCaps(
IN OUT ihvjthandler::JobTicketHandler * pJth,
OUT INT stapleIndexArray[], // can be NULL
OUT BSTR stapleConstrainArray[]
);
HRESULT AddPrintschemaStapleFeatureToJT(
IN OUT ihvjthandler::JobTicketHandler * jth,
IN INT stapleIndex
);
HRESULT AddPrintschemaStapleFeatureToDevCaps(
IN OUT ihvjthandler::JobTicketHandler * jth,
IN OUT INT stapleIndexArray[],
IN OUT BSTR stapleConstrainArray[]
);
HRESULT PerformSmartNup(
IN OUT ihvjthandler::JobTicketHandler * pJth
);
};
#endif
| [
"[email protected]"
] | |
9361d8d8e58fce377536d485c87696388e34db29 | 2a8a290eb1d0703a7c7b21429b07870c5ffa868e | /Include/NiPSSpawner.h | ed296a4db12439e7675aaba6abb3640239c56288 | [] | no_license | sigmaco/gamebryo-v32 | b935d737b773497bf9e663887e326db4eca81885 | 0709c2570e21f6bb06a9382f9e1aa524070f3751 | refs/heads/master | 2023-03-31T13:56:37.844472 | 2021-04-17T02:30:46 | 2021-04-17T02:30:46 | 198,067,949 | 4 | 4 | null | 2021-04-17T02:30:47 | 2019-07-21T14:39:54 | C++ | UTF-8 | C++ | false | false | 12,681 | h | // EMERGENT GAME TECHNOLOGIES PROPRIETARY INFORMATION
//
// This software is supplied under the terms of a license agreement or
// nondisclosure agreement with Emergent Game Technologies and may not
// be copied or disclosed except in accordance with the terms of that
// agreement.
//
// Copyright (c) 1996-2009 Emergent Game Technologies.
// All Rights Reserved.
//
// Emergent Game Technologies, Calabasas, CA 91302
// http://www.emergent.net
#pragma once
#ifndef NIPSSPAWNER_H
#define NIPSSPAWNER_H
#include "NiParticleLibType.h"
#include <NiObject.h>
class NiPSParticleSystem;
/**
Creates a new particle whose initial parameters are based on an existing
particle.
Each NiPSParticleSystem object owns a set of NiPSSpawner objects. It also
references a "death spawner", which is used to spawn new particles when
particles in that system are killed. Additionally, each NiPSCollider
object can optionally reference a spawner from which particles should be
spawned upon a collision.
The spawner that is referenced by particle systems and particle colliders
need not be owned by the same particle system. Thus, it is possible to
spawn particles from a different particle system instead of from the
current system. This allows spawned particles to look different from the
original particles.
Each time a particle is spawned, its generation value is incremented. The
generation value is used by NiPSMeshParticleSystem objects to determine
which master particle to use when emitting the particle. It is also used
to grow and shrink particles over time.
The number of particles to spawn can be set in this class, along with a
randomization value. The speed, direction, and life span for spawned
particles can also be randomized. All other particle parameters are copied
from the original particle when a particle is spawned.
The IDs of spawners are globally managed. At most 255 spawners may
be in the application at any one time. After loading or otherwise
creating 255 spawners, any attempt to add another spawner will
assert in debug builds and fail in other configuration. Deleting a
particle system and its spawners provides space for another spawner.
*/
class NIPARTICLE_ENTRY NiPSSpawner : public NiObject
{
/// @cond EMERGENT_INTERNAL
NiDeclareRTTI;
NiDeclareClone(NiPSSpawner);
NiDeclareStream;
NiDeclareViewerStrings;
/// @endcond
public:
/// Used to indicate an invalid spawner ID.
static const NiUInt16 INVALID_ID;
/// @name Construction and Destruction
//@{
/**
Main constructor.
@param usNumSpawnGenerations The number of generations allowed for
spawning particles. Particles whose generation equals or exceeds
this value will not be spawned.
@param fPercentageSpawned A ratio determining the likelihood of a
particular particle being spawned. Must be between 0.0 and 1.0.
@param uiMinNumToSpawn The minimum number of particles to spawn for
any given original particle.
@param uiMaxNumToSpawn The maximum number of particles to spawn for
any given original particle.
@param fSpawnSpeedFactor Determines how much the speed of the spawned
particle will inherit from that of the original particle.
@param fSpawnSpeedFactorVar Determines the amount by which the speed factor
will vary for each spawned particle.
@param fSpawnDirChaos Determines how much the direction of the
spawned particle will vary from that of the original particle.
@param fLifeSpan The life span to assign to spawned particles.
@param fLifeSpanVar Determines the amount by which the life span for
the spawned particle will vary from that of the original particle.
@param bRelativeSpeed Determines if the speed of the spawned
particle will vary from that of the original particle.
*/
NiPSSpawner(
NiUInt16 usNumSpawnGenerations = 1,
float fPercentageSpawned = 1.0f,
NiUInt32 uiMinNumToSpawn = 1,
NiUInt32 uiMaxNumToSpawn = 1,
float fSpawnSpeedFactor = 1.0f,
float fSpawnSpeedFactorVar = 0.0f,
float fSpawnDirChaos = 0.0f,
float fLifeSpan = 0.0f,
float fLifeSpanVar = 0.0f,
bool bRelativeSpeed = true);
//@}
/// Destructor
~NiPSSpawner();
/**
Uses the stored spawning variables to determine how many particles to
spawn, calling SpawnParticle to spawn each particle appropriately.
@param fCurrentTime The current simulation time.
@param fSpawnTime The time at which the spawn occurred. This value
should be less than fCurrentTime.
@param uiOldIndex The original particle index.
@param pkOldPSystem The particle system containing the original
particle.
*/
virtual void SpawnParticles(
float fCurrentTime,
float fSpawnTime,
NiUInt32 uiOldIndex,
NiPSParticleSystem* pkOldPSystem);
/**
Spawns a single particle.
@param fCurrentTime The current simulation time.
@param fSpawnTime The time at which the spawn occurred. This value
should be less than fCurrentTime.
@param uiOldIndex The original particle index.
@param pkOldPSystem The particle system containing the original
particle.
*/
virtual void SpawnParticle(
float fCurrentTime,
float fSpawnTime,
NiUInt32 uiOldIndex,
NiPSParticleSystem* pkOldPSystem);
//@{
/**
Accesses the number of generations allowed for spawning particles.
Particles whose generation equals or exceeds this value will not be
spawned.
*/
inline NiUInt16 GetNumSpawnGenerations() const;
inline void SetNumSpawnGenerations(NiUInt16 usNumSpawnGenerations);
//@}
//@{
/**
Accesses a ratio determining the likelihood of a particular particle
being spawned.
This value must be between 0.0 and 1.0 and is multiplied by a random
number to determine if a particular particle should get spawned.
*/
inline float GetPercentageSpawned() const;
inline void SetPercentageSpawned(float fPercentageSpawned);
//@}
//@{
/**
Accesses the minimum number of particles to spawn for any given
original particle.
This value may be the same as the maximum number of particles to
spawn, in which case the same number of particles will always be
spawned. If these values differ, the number of particles actually
spawned will be randomly selected from this range.
@note This value must be less than or equal to the maximum number of
particles to spawn.
*/
inline NiUInt32 GetMinNumToSpawn() const;
inline void SetMinNumToSpawn(NiUInt32 uiMinNumToSpawn);
//@}
//@{
/**
Accesses the maximum number of particles to spawn for any given
original particle.
This value may be the same as the minimum number of particles to
spawn, in which case the same number of particles will always be
spawned. If these values differ, the number of particles actually
spawned will be randomly selected from this range.
@note This value must be greater than or equal to the minimum number
of particles to spawn.
*/
inline NiUInt32 GetMaxNumToSpawn() const;
inline void SetMaxNumToSpawn(NiUInt32 uiMaxNumToSpawn);
//@}
//@{
/**
Accesses a value determining if the speed of the spawned
particle will vary from that of the original particle.
If true the speed of the spawned particles are determined relative to
the speed of the original particle. If false the speed of the spawned
particles are absolute speed given by the value in the speed chaos value.
*/
inline bool GetRelativeSpeed() const;
inline void SetRelativeSpeed(bool bRelativeSpeed);
//@}
//@{
/**
Accesses a value determining how much the speed of the spawned
particle will vary from that of the original particle.
NewSpeed = OriginalSpeed + (OriginalSpeed * (SpeedFactor +
(SpeedFactor * SpeedFactorVar * SymetricalRand))
*/
inline float GetSpawnSpeedFactor() const;
inline float GetSpawnSpeedFactorVar() const;
inline void SetSpawnSpeedFactor(float fSpawnSpeedFactor);
inline void SetSpawnSpeedFactorVar(float fSpawnSpeedFactorVar);
//@}
//@{
/**
Accesses a value determining how much the direction of the spawned
particle will vary from that of the original particle.
This value must be between 0.0 and 1.0 and indicates how much the
direction spawned velocity is allowed to deviate from the original
velocity. Here are some examples:
- 0.0 indicates no variance.
- 0.5 allows the spawned velocity to deviate from the original
velocity by up to 90 degrees.
- 1.0 causes the spawned velocity to be in any random direction.
*/
inline float GetSpawnDirChaos() const;
inline void SetSpawnDirChaos(float fSpawnDirChaos);
//@}
//@{
/// Accesses the life span to assign to spawned particles.
inline float GetLifeSpan() const;
inline void SetLifeSpan(float fLifeSpan);
//@}
//@{
/**
Accesses a value determining the amount by which the life span for
the spawned particle will vary from that of the original particle.
The life span assigned to spawned particles will be evenly distributed
over the range [LifeSpan - LifeSpanVar/2, LifeSpan + LifeSpanVar/2].
*/
inline float GetLifeSpanVar() const;
inline void SetLifeSpanVar(float fLifeSpanVar);
//@}
/**
The master particle system.
Accesses the pointer that is used to store the master particle system. This system
is responsible for managing the spawned particles.
*/
inline NiPSParticleSystem* GetMasterPSystem() const;
void SetMasterPSystem(NiPSParticleSystem* pkMasterPSystem);
/// @cond EMERGENT_INTERNAL
/// Removes the reference to the master particle system, without calling back into it
/// This should only be called from the destructor of the target system.
void RemoveMasterPSystem(NiPSParticleSystem* pkMasterPSystem);
/// @name Base Class Overrides
//@{
virtual void ProcessClone(NiCloningProcess& kCloning);
//@}
/// @endcond
protected:
/// A pointer to the particle system object that owns the spawner. Do not set this pointer
/// directly; always call the SetMasterPSystem() function. It handles reference counting for
/// the particle system.
NiPSParticleSystem* m_pkMasterPSystem;
/// A ratio determining the likelihood of a particular particle being spawned.
float m_fPercentageSpawned;
/// Determines how much the speed of the spawned particle will inherit from that of the
/// original particle.
float m_fSpawnSpeedFactor;
/// Determines how much the speed of the spawned particle will vary from that of the original
/// particle.
float m_fSpawnSpeedFactorVar;
/// Determines how much the direction of the spawned particle will vary from that of the
/// original particle.
float m_fSpawnDirChaos;
/// The life span to assign to spawned particles.
float m_fLifeSpan;
/// Determines the amount by which the life span for the spawned particle will vary from that
/// of the original particle.
float m_fLifeSpanVar;
/// The minimum number of particles to spawn for any given original particle.
NiUInt32 m_uiMinNumToSpawn;
/// The maximum number of particles to spawn for any given original particle.
NiUInt32 m_uiMaxNumToSpawn;
/// The number of generations allowed for spawning particles.
NiUInt16 m_usNumSpawnGenerations;
/// Determines if the speed of the spawned particle will vary from that of the original
/// particle.
bool m_bRelativeSpeed;
};
NiSmartPointer(NiPSSpawner);
#include "NiPSSpawner.inl"
#endif // #ifndef NIPSSPAWNER_H
| [
"[email protected]"
] | |
ed3987618ef6adef94b88088d3779b1ebf2804fa | 7267e98e439670d2bc197e84cfba78902bbbd338 | /350. Intersection of Two Arrays II/350. Intersection of Two Arrays II/main.cpp | 8907dbab98a4a28916af261bdde70acb5142969a | [] | no_license | Ckend/myLeetcode | 82262a2d420a3e4987de1b995ac329a0fb1486bf | bac1f58d3eb1f57a69252a4a2e7e665a4eb0e6dd | refs/heads/master | 2021-01-22T20:59:34.356625 | 2017-10-12T18:33:33 | 2017-10-12T18:33:33 | 85,380,445 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 928 | cpp | //
// main.cpp
// 350. Intersection of Two Arrays II
//
// Created by ckend on 2017/5/5.
// Copyright © 2017年 ckend. All rights reserved.
//
#include <iostream>
#include <map>
#include <vector>
class Solution{
public:
std::vector<int> intersect(std::vector<int> &nums1, std::vector<int> &nums2){
std::vector<int> result;
std::map<int, int> dict;
for (int i = 0; i < nums1.size(); ++i) {
++dict[nums1[i]];
}
for (int i = 0; i < nums2.size(); ++i) {
if (--dict[nums2[i]] >= 0){
result.push_back(nums2[i]);
}
}
return result;
}
};
int main(int argc, const char * argv[]) {
Solution y;
std::vector<int> nums1,nums2,result;
result = y.intersect(nums1, nums2);
nums2.push_back(1);
for (int i = 0; i < result.size(); ++i) {
std::cout << result[i] <<std::endl;
}
return 0;
}
| [
"[email protected]"
] | |
737324c239d92e7aa6a8f5e52593fa1bcf6012fd | 958b50231677da79168ede927cb3c119acea051a | /include/Mat4.h | 472b62031b155f751d7f28c60b0836b913fbe010 | [] | no_license | galib2145/ray_tracer | f4e523be9ae047990d9519e356ecd468657f60f1 | eff3dddc45b0c92664fcc468768766793de3367d | refs/heads/master | 2021-01-23T07:16:47.927810 | 2015-02-05T11:09:38 | 2015-02-05T11:09:38 | 28,383,417 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,802 | h | #include <iostream>
#include <math.h>
#define PI 3.1415196
class Mat4
{
public:
float m[4][4];
static const Mat4 Identity;
Mat4()
{
m[0][0] = 1.0;
m[0][1] = 0.0;
m[0][2] = 0.0;
m[0][3] = 0.0;
m[1][0] = 0.0;
m[1][1] = 1.0;
m[1][2] = 0.0;
m[1][3] = 0.0;
m[2][0] = 0.0;
m[2][1] = 0.0;
m[2][2] = 1.0;
m[2][3] = 0.0;
m[3][0] = 0.0;
m[3][1] = 0.0;
m[3][2] = 0.0;
m[3][3] = 1.0;
}
Mat4 operator * (const Mat4 right) const
{
Mat4 r;
for (int i = 0; i < 4; ++i)
for (int j = 0; j < 4; ++j)
r.m[i][j] =
m[i][0] * right.m[0][j] +
m[i][1] * right.m[1][j] +
m[i][2] * right.m[2][j] +
m[i][3] * right.m[3][j];
return r;
}
void scale(float scale_factor){
m[0][0]*= scale_factor;
m[1][1]*= scale_factor;
m[2][2]*= scale_factor;
}
void scaleX(float x){
m[0][0]*= x;
}
void scaleY(float y){
m[1][1]*= y;
}
void scaleZ(float z){
m[2][2]*= z;
}
Vec3 mulitply_direction_by_matrix(Vec3 source_vector)
{
Vec3 destination_vector;
destination_vector.x = source_vector.x * m[0][0] + source_vector.y * m[1][0] + source_vector.z * m[2][0];
destination_vector.y = source_vector.x * m[0][1] + source_vector.y * m[1][1] + source_vector.z * m[2][1];
destination_vector.z = source_vector.x * m[0][2] + source_vector.y * m[1][2] + source_vector.z * m[2][2];
return destination_vector;
}
Vec3 multiply_vector_by_matrix(const Vec3 source_vector) const
{
Vec3 destination_vector;
destination_vector.x = source_vector.x * m[0][0] + source_vector.y * m[1][0] + source_vector.z * m[2][0] + m[3][0];
destination_vector.y = source_vector.x * m[0][1] + source_vector.y * m[1][1] + source_vector.z * m[2][1] + m[3][1];
destination_vector.z = source_vector.x * m[0][2] + source_vector.y * m[1][2] + source_vector.z * m[2][2] + m[3][2];
float w = source_vector.x * m[0][3] + source_vector.y * m[1][3] + source_vector.z * m[2][3] + m[3][3];
if (w != 1 && w != 0) {
destination_vector.x/= w;
destination_vector.y/= w;
destination_vector.z/= w;
}
return destination_vector;
}
Mat4 get_inverse(){
int i, j, k;
Mat4 s;
Mat4 t = (*this);
for (i = 0; i < 3 ; i++) {
int pivot = i;
float pivotsize = t.m[i][i];
if (pivotsize < 0)
pivotsize = -pivotsize;
for (j = i + 1; j < 4; j++) {
float tmp = t.m[j][i];
if (tmp < 0)
tmp = -tmp;
if (tmp > pivotsize) {
pivot = j;
pivotsize = tmp;
}
}
if (pivotsize == 0) {
return Mat4();
}
if (pivot != i) {
for (j = 0; j < 4; j++) {
float tmp;
tmp = t.m[i][j];
t.m[i][j] = t.m[pivot][j];
t.m[pivot][j] = tmp;
tmp = s.m[i][j];
s.m[i][j] = s.m[pivot][j];
s.m[pivot][j] = tmp;
}
}
for (j = i + 1; j < 4; j++) {
float f = t.m[j][i] / t.m[i][i];
for (k = 0; k < 4; k++) {
t.m[j][k] -= f * t.m[i][k];
s.m[j][k] -= f * s.m[i][k];
}
}
}
for (i = 3; i >= 0; --i) {
float f;
if ((f = t.m[i][i]) == 0) {
return Mat4();
}
for (j = 0; j < 4; j++) {
t.m[i][j] /= f;
s.m[i][j] /= f;
}
for (j = 0; j < i; j++) {
f = t.m[j][i];
for (k = 0; k < 4; k++) {
t.m[j][k] -= f * t.m[i][k];
s.m[j][k] -= f * s.m[i][k];
}
}
}
return s;
}
void rotateX(float angle){
Mat4 matrix;
float theta = (PI*angle)/180;
matrix.m[1][1] = cos(theta);
matrix.m[1][2] = -sin(theta);
matrix.m[2][1] = sin(theta);
matrix.m[2][2] = cos(theta);
*(this) = *(this) * matrix;
}
void rotateY(float angle){
Mat4 matrix;
float theta = (PI*angle)/180;
matrix.m[0][0] = cos(theta);
matrix.m[0][2] = sin(theta);
matrix.m[2][0] = -sin(theta);
matrix.m[2][2] = cos(theta);
*(this) = *(this) * matrix;
}
void rotateZ(float angle){
Mat4 matrix;
float theta = (PI*angle)/180;
matrix.m[0][0] = cos(theta);
matrix.m[0][1] = -sin(theta);
matrix.m[1][0] = sin(theta);
matrix.m[1][1] = cos(theta);
*(this) = *(this) * matrix;
}
};
const Mat4 Mat4::Identity;
| [
"[email protected]"
] | |
3f088003c91f76efc5f1a9704bf7630760185ade | 022132a275c7dd085b526fd17de5e10431af53b0 | /shapes/squareringdrawer.cpp | b9d72a56d245eee91591cf0d73fd4f83b3c7f17e | [] | no_license | bli0428/waluigi-time | 57668bb95ea0afa241d1d914585456067ed38a6e | ffbfec91f72a2c0bdf1e93347a7ea1fc47d2b6c7 | refs/heads/master | 2020-04-09T06:45:49.606753 | 2019-01-14T12:55:13 | 2019-01-14T12:55:13 | 160,125,975 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,174 | cpp | #include "squareringdrawer.h"
#include "math.h"
#include "glm/trigonometric.hpp"
SquareRingDrawer::SquareRingDrawer()
{
}
/**
* @brief SquareRingDrawer::draw Draws a ring in a rectangular formation.
* @param upperRadius Radius of the upper ring
* @param lowerRadius Radius of the lower ring
* @param upperY Height of the upper ring
* @param lowerY Height of the lower ring
* @param numIntervals Number of intervals to draw
*/
std::vector<glm::vec3> SquareRingDrawer::draw(float upperRadius, float lowerRadius, float upperY, float lowerY, int numIntervals) {
std::vector<glm::vec3> coords;
coords.reserve(2 * (numIntervals + 1));
// calculates the theta interval
float thetaInterval = 2.0 * M_PI / numIntervals;
for (int i = 0; i <= numIntervals; i++) {
// for each interval we're at, plot two points; this will create the zig-zag triangle effect
coords.push_back(glm::vec3(glm::cos(thetaInterval * i) * upperRadius, upperY, glm::sin(thetaInterval * i) * upperRadius));
coords.push_back(glm::vec3(glm::cos(thetaInterval * i) * lowerRadius, lowerY, glm::sin(thetaInterval * i) * lowerRadius));
}
return coords;
}
| [
"[email protected]"
] | |
50fd4c2a2fc427f4bf1b9261d5fd31eb1780d3cb | 1ad310fc8abf44dbcb99add43f6c6b4c97a3767c | /samples_c++/cc/sprite_devl/CompressedSprite.h | d4ff5bec6bf824a5d6b3841e5bed421b791543b4 | [] | no_license | Jazzinghen/spamOSEK | fed44979b86149809f0fe70355f2117e9cb954f3 | 7223a2fb78401e1d9fa96ecaa2323564c765c970 | refs/heads/master | 2020-06-01T03:55:48.113095 | 2010-05-19T14:37:30 | 2010-05-19T14:37:30 | 580,640 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 3,334 | h | class Sprite
{
public:
Sprite(const char* sprite);
~Sprite();
char const * const getDecompressedSprite(U8 frameNumber);
private:
void decompressSprite(U8 frameNumber);
//compressed data
char mSentinal;
U8 mNumFrames;
U8 mWidth;
U8 mHeight;
U16 mNumflagBytes;
char const * mCompressedSprite;
char const * mCompressedFlags;
char const * mFrameOffsets;
//char *mDecompressBuffer;
char mDecompressBuffer[100];
//uncompressed data
U8 mCurrentFrame;
//1 byte - sentinel value
//1 byte - num frames
//1 byte - width
//1 byte - height
//1 byte - offset to compressed offset data
//max 32 bytes for 255 framse for compressed flag bitfield
//max 512 bytes for data offset into frames
static const U8 mSentinalIndex = 0;
static const U8 mNumFramesIndex = 1;
static const U8 mWidthIndex = 2;
static const U8 mHeightIndex = 3;
static const U8 mNumFlagBytes = 4;
static const U8 mHeaderPad00 = 5;
static const U8 mStartOfCompressedFlags = 6;
static const U8 mInvalidFrameNumber = 255;
};
Sprite::Sprite(const char* sprite)
: mSentinal(sprite[mSentinalIndex])
, mNumFrames(sprite[mNumFramesIndex])
, mWidth(sprite[mWidthIndex])
, mHeight(sprite[mHeightIndex])
, mCurrentFrame(mInvalidFrameNumber)
{
//mDecompressBuffer = new char[(mWidth*mHeight)/8];
//memset(mDecompressBuffer, 0, (mWidth*mHeight)/8);
mNumflagBytes = sprite[mNumFlagBytes];
mCompressedFlags = &sprite[mStartOfCompressedFlags];
int bufferOffset = 0;
bufferOffset += mStartOfCompressedFlags + mNumflagBytes;
mFrameOffsets = &sprite[bufferOffset];
bufferOffset = bufferOffset + (mNumFrames * 2);
mCompressedSprite = &sprite[bufferOffset];
}
Sprite::~Sprite()
{
//delete [] mDecompressBuffer;
}
char const * const Sprite::getDecompressedSprite(U8 frameNumber)
{
if(mCurrentFrame != frameNumber)
{
decompressSprite(frameNumber);
}
return mDecompressBuffer;
}
void Sprite::decompressSprite(U8 frameNumber)
{
int numCompressedBytes = 0;
char const *frameToDecompress = 0;
if(frameNumber == 0)
{
numCompressedBytes = reinterpret_cast<const unsigned short*>(mFrameOffsets)[frameNumber];
frameToDecompress = mCompressedSprite;
}
else
{
unsigned short nextOffset = reinterpret_cast<const unsigned short*>(mFrameOffsets)[frameNumber];
unsigned short currentOffset = reinterpret_cast<const unsigned short*>(mFrameOffsets)[frameNumber - 1];
numCompressedBytes = nextOffset - currentOffset;
frameToDecompress = &mCompressedSprite[currentOffset];
}
if(mCompressedFlags[frameNumber/8] & (1<<frameNumber))
{
//decompress the frame
int i = 0;
int uncmpBuffer = 0;
while(i < numCompressedBytes)
{
char character = frameToDecompress[i];
if(mSentinal == character)
{
unsigned char numChars = frameToDecompress[i + 1];
for(int j = 0; j < numChars; ++j)
{
if(uncmpBuffer < (mWidth*mHeight)/8)
{
mDecompressBuffer[uncmpBuffer++] = frameToDecompress[i + 2];
}
}
i += 3;
}
else
{
if(uncmpBuffer < (mWidth*mHeight)/8)
{
mDecompressBuffer[uncmpBuffer++] = character;
}
i++;
}
}
}
else
{
memcpy(mDecompressBuffer, frameToDecompress, (mWidth*mHeight)/8);
}
}
| [
"jazzinghen@Jehuty.(none)"
] | jazzinghen@Jehuty.(none) |
5eca38463cebf4dd084525eb2f1aab3fa6f9d4ca | 0958cceb81de1c7ee74b0c436b800a1dc54dd48a | /wincewebkit/WebKitTools/DumpRenderTree/chromium/AccessibilityController.h | 9d5122c72cec8479405037314d708e7e5c7ff214 | [] | no_license | datadiode/WinCEWebKit | 3586fac69ba7ce9efbde42250266ddbc5c920c5e | d331d103dbc58406ed610410736b59899d688632 | refs/heads/master | 2023-03-15T23:47:30.374484 | 2014-08-14T14:41:13 | 2014-08-14T14:41:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,344 | h | /*
* Copyright (C) 2010 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.
*/
#ifndef AccessibilityController_h
#define AccessibilityController_h
#include "AccessibilityUIElement.h"
#include "CppBoundClass.h"
namespace WebKit {
class WebAccessibilityObject;
class WebFrame;
}
class TestShell;
class AccessibilityController : public CppBoundClass {
public:
explicit AccessibilityController(TestShell*);
// Shadow to include accessibility initialization.
void bindToJavascript(WebKit::WebFrame*, const WebKit::WebString& classname);
void reset();
void setFocusedElement(const WebKit::WebAccessibilityObject&);
AccessibilityUIElement* getFocusedElement();
AccessibilityUIElement* getRootElement();
// This function sets a flag that tells the test_shell to dump all
// accessibility notifications.
void dumpAccessibilityNotifications(const CppArgumentList&, CppVariant*);
public:
// The following methods are not exposed to JavaScript.
bool shouldDumpAccessibilityNotifications() { return m_dumpAccessibilityNotifications; }
private:
// If true, the test_shell will dump all accessibility notifications.
bool m_dumpAccessibilityNotifications;
// Bound methods and properties
void logFocusEventsCallback(const CppArgumentList&, CppVariant*);
void logScrollingStartEventsCallback(const CppArgumentList&, CppVariant*);
void fallbackCallback(const CppArgumentList&, CppVariant*);
void focusedElementGetterCallback(CppVariant*);
void rootElementGetterCallback(CppVariant*);
WebKit::WebAccessibilityObject m_focusedElement;
WebKit::WebAccessibilityObject m_rootElement;
AccessibilityUIElementList m_elements;
TestShell* m_shell;
};
#endif // AccessibilityController_h
| [
"[email protected]"
] | |
df29f2762921200f094cb6e02222b302dce11944 | 7c8880bf917acdd05c0038fbf442d6985099771d | /LodeRunner/cSound.cpp | 896b0a16806eeb0de5455507525aa10c61f5cd95 | [
"MIT"
] | permissive | kelvinc1024/OpenGL-Game-Engine-Platformer-Example | 824ab8d552d6bdda7d155093428633346e858894 | e0472b4fffbcf8203bd569b7850d4a682f7820ae | refs/heads/master | 2021-01-18T08:14:23.562110 | 2016-07-15T04:40:09 | 2016-07-15T04:40:09 | 45,771,714 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,294 | cpp | // Copyright 2015 Kelvin Chandra, Software Laboratory Center, Binus University. All Rights Reserved.
#include "cSound.h"
cSound::cSound(void)
{
FMOD::System_Create(&system);// create an instance of the game engine
system->init(32, FMOD_INIT_NORMAL, 0);// initialise the game engine with 32 channels
}
cSound::~cSound(void)
{
for (int i = 0; i < NUM_SOUNDS; i++) sounds[i]->release();
system->release();
}
bool cSound::Load()
{
system->createStream("Sounds/03_-_Lode_Runner_-_NES_-_In-Game.ogg", FMOD_SOFTWARE | FMOD_LOOP_NORMAL, 0, &sounds[SOUND_AMBIENT1]);
//system->createStream("Sounds/ambient1.mp3", FMOD_SOFTWARE | FMOD_LOOP_NORMAL, 0, &sounds[SOUND_AMBIENT1]);
return true;
}
void cSound::Play(int sound_id)
{
if (sound_id == SOUND_AMBIENT1) {
system->playSound(FMOD_CHANNEL_FREE, sounds[SOUND_AMBIENT1], false, &ambient1Channel);
ambient1Channel->setVolume(0.25f); //between 0 and 1
}
else if (sound_id == SOUND_AMBIENT2) {
system->playSound(FMOD_CHANNEL_FREE, sounds[SOUND_AMBIENT2], false, &ambient2Channel);
ambient2Channel->setVolume(0.2f); //between 0 and 1
}
else system->playSound(FMOD_CHANNEL_FREE, sounds[sound_id], false, 0);
}
void cSound::StopAll()
{
ambient1Channel->stop();
ambient2Channel->stop();
}
void cSound::Update()
{
system->update();
} | [
"[email protected]"
] | |
a18253f012c07716641c7d017c5bfc1d492ad289 | 29d03de811ad0a7e16dc73790b89c69e1f436006 | /src/engine/GameEngine.hpp | 3af79ed18131959336c6174be25b7820317aeea3 | [] | no_license | koerriva/GameEngine | 8ecbe0f47a1a4e8613221bb0ba4097737276a6ec | ed11e422a96b7473e7b78607c136e7081a345211 | refs/heads/master | 2021-12-29T09:36:54.707471 | 2021-12-20T10:10:25 | 2021-12-20T10:10:25 | 150,728,131 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,621 | hpp | #pragma once
#include <chrono>
#include <thread>
#include "IGameLogic.hpp"
#include "Renderer.hpp"
namespace Engine {
using namespace std::chrono;
//duration_cast<nanoseconds>(high_resolution_clock::now().time_since_epoch());
//1ms = 1000000ns
struct GameTime{
nanoseconds start;
nanoseconds now;
nanoseconds steps;
};
class Timer {
private:
double lastLoopTime;
public:
~Timer(){
cout << "Drop Timer" << endl;
}
void Init(){
lastLoopTime = GetTime();
}
double GetElapsedTime(){
double time = GetTime();
auto elapsedTime = time - lastLoopTime;
lastLoopTime = time;
return elapsedTime;
}
[[nodiscard]] double GetLastLoopTime() const{
return lastLoopTime;
}
static double GetTime(){
return duration_cast<nanoseconds>(steady_clock::now().time_since_epoch()).count()/1000000000.0;
}
};
class GameEngine
{
private:
const float TARGET_FPS = 60;
const float TARGET_UPS = 30;
Window* window;
IGameLogic* game;
Timer* timer;
public:
GameEngine(const char* title,int width,int height,bool vsync,IGameLogic* game);
~GameEngine();
void Run();
protected:
void Init();
void Input();
void Update(float elapsedTime);
void Render(float elapsedTime);
void Sync();
void Cleanup();
};
GameEngine::GameEngine(const char *title, int width, int height, bool vsync, IGameLogic *game) {
this->game = game;
this->window = new Window(title,width,height,vsync);
this->timer = new Timer();
}
GameEngine::~GameEngine()
{
cout << "Drop GameEngine" << endl;
}
void GameEngine::Init(){
timer->Init();
//窗口先初始化
window->Init();
//加载资源
ResourceLoader::Init();
//加载字体
Font::Init();
//加载游戏
game->Init();
}
void GameEngine::Run(){
Init();
float elapsedTime;
float acc = 0.f;
float interval = 1.f/TARGET_UPS;
while (!window->Closed())
{
elapsedTime = float(timer->GetElapsedTime());
acc += elapsedTime;
Input();
if(!window->VSynced()){
while (acc >= interval){
Update(interval);
acc -= interval;
}
}else{
Update(elapsedTime);
}
Render(elapsedTime);
if(!window->VSynced()){
Sync();
}
}
Cleanup();
}
void GameEngine::Sync() {
auto loopSlot = 1.f/TARGET_FPS;
auto endTime = timer->GetLastLoopTime()+loopSlot;
auto now = Engine::Timer::GetTime();
while(now<endTime){
this_thread::sleep_for(milliseconds(1));
now = Engine::Timer::GetTime();
}
}
void GameEngine::Input(){
game->Input(window);
}
void GameEngine::Update(float elapsedTime){
window->Update();
game->Update(elapsedTime);
}
void GameEngine::Render(float elapsedTime){
game->Render(window,elapsedTime);
}
void GameEngine::Cleanup(){
game->Cleanup();
ResourceLoader::Cleanup();
Font::Cleanup();
//窗口必须最后清理,防止OpenGL Context关闭。
window->Cleanup();
}
} | [
"[email protected]"
] | |
97bcd76377ba893c781355ad75a6dc46819eaad5 | 9a22480693a4cc768a09f15d71950bff167f0951 | /ps-thin/src/petuum_ps/util/thread.cpp | dce4005975103e623182e776dee0d4b3d7344ec5 | [
"BSD-2-Clause",
"LicenseRef-scancode-generic-cla"
] | permissive | raajay/pmls-caffe | b3b9bc0cb53f18b9578eb281999a6b85ce6ef1ed | 5c60f74f92fe2fb10c819e162960407cad801172 | refs/heads/master | 2021-01-22T01:10:43.474812 | 2017-10-16T18:04:55 | 2017-10-16T18:04:55 | 102,202,226 | 0 | 1 | null | 2017-10-09T19:25:55 | 2017-09-02T14:30:26 | C++ | UTF-8 | C++ | false | false | 2,932 | cpp | #include <petuum_ps/util/thread.hpp>
#include <petuum_ps/thread/ps_msgs.hpp>
namespace petuum {
Thread::Thread(int32_t my_id, pthread_barrier_t *init_barrier)
: my_id_(my_id),
init_barrier_(init_barrier),
comm_bus_(GlobalContext::comm_bus) {}
/**
*/
void Thread::SendToAll(MsgBase *msg, std::vector<int32_t> dest_ids) {
for (const auto &id : dest_ids) {
Send(msg, id);
}
}
/**
*/
void Thread::Send(MsgBase *msg, int32_t dest_id) {
size_t sent_size = (comm_bus_->*(comm_bus_->SendAny_))(dest_id, msg->get_mem(), msg->get_size());
CHECK_EQ(sent_size, msg->get_size());
}
/**
*/
void Thread::ConnectTo(int32_t dest_id, int32_t my_id) {
ConnectMsg connect_msg;
connect_msg.get_client_id() = GlobalContext::get_client_id();
connect_msg.get_thread_id() = my_id;
void *msg = connect_msg.get_mem();
int32_t msg_size = connect_msg.get_size();
if (comm_bus_->IsLocalEntity(dest_id)) {
comm_bus_->ConnectTo(dest_id, msg, msg_size);
} else {
HostInfo dest_info = GlobalContext::get_host_info(dest_id);
std::string server_addr = dest_info.ip + ":" + dest_info.port;
comm_bus_->ConnectTo(dest_id, server_addr, msg, msg_size);
}
}
/**
*/
int32_t Thread::WaitForConnect() {
int32_t sender_id;
zmq::message_t zmq_msg;
(comm_bus_->*(comm_bus_->RecvAny_))(&sender_id, &zmq_msg);
MsgType msg_type = MsgBase::get_msg_type(zmq_msg.data());
CHECK_EQ(msg_type, kGenericConnect) << "Unknown type of connect message";
ConnectMsg msg(zmq_msg.data());
VLOG(5) << "Received connection from client_id=" << msg.get_client_id()
<< " and thread_id=" << msg.get_thread_id();
return sender_id;
}
/**
*/
void Thread::WaitForReply(int32_t dest_id, MsgType expected_msg_type) {
zmq::message_t zmq_msg;
int32_t sender_id;
(comm_bus_->*(comm_bus_->RecvAny_))(&sender_id, &zmq_msg);
MsgType msg_type = MsgBase::get_msg_type(zmq_msg.data());
CHECK_EQ(msg_type, expected_msg_type);
if (dest_id == GlobalContext::kAnyThreadId) {
return;
}
CHECK_EQ(sender_id, dest_id);
}
/**
*/
void Thread::SetupCommBus(int32_t thread_id) {
CommBus::Config comm_config;
comm_config.entity_id_ = thread_id;
if (GlobalContext::get_num_clients() > 1
&& !GlobalContext::is_worker_thread(thread_id)) {
comm_config.ltype_ = CommBus::kInProc | CommBus::kInterProc;
HostInfo host_info = GlobalContext::get_host_info(thread_id);
comm_config.network_addr_ = "*:" + host_info.port;
} else {
comm_config.ltype_ = CommBus::kInProc;
}
comm_bus_->ThreadRegister(comm_config);
}
/**
*/
int32_t Thread::GetNextMessage(zmq::message_t &msg) {
int32_t sender_id;
(comm_bus_->*(comm_bus_->RecvAny_))(&sender_id, &msg);
return sender_id;
}
}
| [
"[email protected]"
] | |
3e0c0b314f3e3575ddf93a33c5fb69acb62be0d5 | f6f808a90aae23e36d6096e3c6ab5cc2c224f934 | /glibr.cpp | 630fa5249094314233814971e58deaa54896e51d | [
"Apache-2.0"
] | permissive | iotkitv3/APDS-9960 | 301f9c2f06d8cc94140ef506c10012b1158b12ee | 65f7b93e4a8f424270e947ca48b2bbe0be673be5 | refs/heads/main | 2023-02-03T21:44:19.082580 | 2020-12-26T17:00:49 | 2020-12-26T17:00:49 | 324,598,631 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 56,705 | cpp | #include "glibr.h"
#include "mbed.h"
glibr::glibr(PinName sda, PinName scl):i2c(sda, scl){
gesture_ud_delta_ = 0;
gesture_lr_delta_ = 0;
gesture_ud_count_ = 0;
gesture_lr_count_ = 0;
gesture_near_count_ = 0;
gesture_far_count_ = 0;
gesture_state_ = 0;
gesture_motion_ = DIR_NONE;
}
glibr::~glibr(){
}
bool glibr::ginit(){
uint8_t id;
id=I2CreadByte(APDS9960_I2C_ADDR, APDS9960_ID);
if( (!(id == APDS9960_ID_1 || id == APDS9960_ID_2))||id==ERROR) {
return false;
}
if(!setMode(ALL, Off)) {
return false;
}
if(I2CwriteByte(APDS9960_I2C_ADDR,APDS9960_ATIME, DEFAULT_ATIME)){
return false;
}
if(I2CwriteByte(APDS9960_I2C_ADDR,APDS9960_WTIME, DEFAULT_WTIME)){
return false;
}
if(I2CwriteByte(APDS9960_I2C_ADDR,APDS9960_PPULSE, DEFAULT_PROX_PPULSE)){
return false;
}
if(I2CwriteByte(APDS9960_I2C_ADDR,APDS9960_POFFSET_UR, DEFAULT_POFFSET_UR)){
return false;
}
if(I2CwriteByte(APDS9960_I2C_ADDR,APDS9960_POFFSET_DL, DEFAULT_POFFSET_DL)){
return false;
}
if(I2CwriteByte(APDS9960_I2C_ADDR,APDS9960_CONFIG1, DEFAULT_CONFIG1)){
return false;
}
if( !setLEDDrive(DEFAULT_LDRIVE) ) {
return false;
}
if( !setProximityGain(DEFAULT_PGAIN) ) {
return false;
}
if( !setAmbientLightGain(DEFAULT_AGAIN) ) {
return false;
}
if( !setProxIntLowThresh(DEFAULT_PILT) ) {
return false;
}
if( !setProxIntHighThresh(DEFAULT_PIHT) ) {
return false;
}
if( !setLightIntLowThreshold(DEFAULT_AILT) ) {
return false;
}
if( I2CwriteByte(APDS9960_I2C_ADDR,APDS9960_CONFIG2, DEFAULT_CONFIG2) ) {
return false;
}
if( I2CwriteByte(APDS9960_I2C_ADDR,APDS9960_CONFIG3, DEFAULT_CONFIG3) ) {
return false;
}
if( !setGestureEnterThresh(DEFAULT_GPENTH) ) {
return false;
}
if( !setGestureExitThresh(DEFAULT_GEXTH) ) {
return false;
}
if( I2CwriteByte(APDS9960_I2C_ADDR,APDS9960_GCONF1, DEFAULT_GCONF1) ) {
return false;
}
if( !setGestureGain(DEFAULT_GGAIN) ) {
return false;
}
if( !setGestureLEDDrive(DEFAULT_GLDRIVE) ) {
return false;
}
if( !setGestureWaitTime(DEFAULT_GWTIME) ) {
return false;
}
if( I2CwriteByte(APDS9960_I2C_ADDR,APDS9960_GOFFSET_U, DEFAULT_GOFFSET) ) {
return false;
}
if( I2CwriteByte(APDS9960_I2C_ADDR,APDS9960_GOFFSET_D, DEFAULT_GOFFSET) ) {
return false;
}
if( I2CwriteByte(APDS9960_I2C_ADDR,APDS9960_GOFFSET_L, DEFAULT_GOFFSET) ) {
return false;
}
if( I2CwriteByte(APDS9960_I2C_ADDR,APDS9960_GOFFSET_R, DEFAULT_GOFFSET) ) {
return false;
}
if(I2CwriteByte(APDS9960_I2C_ADDR,APDS9960_GPULSE, DEFAULT_GPULSE) ) {
return false;
}
if( I2CwriteByte(APDS9960_I2C_ADDR,APDS9960_GCONF3, DEFAULT_GCONF3) ) {
return false;
}
if( !setGestureIntEnable(DEFAULT_GIEN) ) {
return false;
}
return true;
}
//#if 0
// /* Gesture config register dump */
// uint8_t reg;
// uint8_t val;
//
// for(reg = 0x80; reg <= 0xAF; reg++) {
// if( (reg != 0x82) && \
// (reg != 0x8A) && \
// (reg != 0x91) && \
// (reg != 0xA8) && \
// (reg != 0xAC) && \
// (reg != 0xAD) )
// {
// val= I2CreadByte(APDS9960_I2C_ADDR, reg);
// if(val==ERROR){
// printf("ERROR");
// }
// /*
// print(reg, HEX);
// print(": 0x");
// println(val, HEX);*/
// }
// }
//
// for(reg = 0xE4; reg <= 0xE7; reg++) {
// val= I2CreadByte(APDS9960_I2C_ADDR, reg);
// /* Serial.print(reg, HEX);
// Serial.print(": 0x");
// Serial.println(val, HEX);*/
// }
//#endif
// return true;
/**
* @brief Enables or disables a feature in the APDS-9960
*
* @param[in] mode which feature to enable
* @param[in] enable On (1) or Off (0)
* @return True if operation success. False otherwise.
*/
bool glibr::setMode(uint8_t mode, uint8_t enable)
{
uint8_t reg_val;
/* Read current ENABLE register */
reg_val = getMode();
if( reg_val == ERROR ) {
return false;
}
/* Change bit(s) in ENABLE register */
enable = enable & 0x01;
if( mode >= 0 && mode <= 6 ) {
if (enable) {
reg_val |= (1 << mode);
} else {
reg_val &= ~(1 << mode);
}
} else if( mode == ALL ) {
if (enable) {
reg_val = 0x7F;
} else {
reg_val = 0x00;
}
}
/* Write value back to ENABLE register */
if(I2CwriteByte(APDS9960_I2C_ADDR,APDS9960_ENABLE, reg_val)){
return false;
}
return true;
}
uint8_t glibr::getMode()
{
uint8_t val;
val= I2CreadByte(APDS9960_I2C_ADDR, APDS9960_ENABLE);
if(val==ERROR){
return ERROR;
}
return val;
}
bool glibr::enableLightSensor(bool interrupts)
{
/* Set default gain, interrupts, enable power, and enable sensor */
if( !setAmbientLightGain(DEFAULT_AGAIN) ) {
return false;
}
if( interrupts ) {
if( !setAmbientLightIntEnable(1) ) {
return false;
}
} else {
if( !setAmbientLightIntEnable(0) ) {
return false;
}
}
if( !enablePower() ){
return false;
}
if( !setMode(AMBIENT_LIGHT, 1) ) {
return false;
}
return true;
}
/**
* @brief Ends the light sensor on the APDS-9960
*
* @return True if sensor disabled correctly. False on error.
*/
bool glibr::disableLightSensor()
{
if( !setAmbientLightIntEnable(0) ) {
return false;
}
if( !setMode(AMBIENT_LIGHT, 0) ) {
return false;
}
return true;
}
/**
* @brief Starts the proximity sensor on the APDS-9960
*
* @param[in] interrupts true to enable hardware external interrupt on proximity
* @return True if sensor enabled correctly. False on error.
*/
bool glibr::enableProximitySensor(bool interrupts)
{
/* Set default gain, LED, interrupts, enable power, and enable sensor */
if( !setProximityGain(DEFAULT_PGAIN) ) {
return false;
}
if( !setLEDDrive(DEFAULT_LDRIVE) ) {
return false;
}
if( interrupts ) {
if( !setProximityIntEnable(1) ) {
return false;
}
} else {
if( !setProximityIntEnable(0) ) {
return false;
}
}
if( !enablePower() ){
return false;
}
if( !setMode(PROXIMITY, 1) ) {
return false;
}
return true;
}
/**
* @brief Ends the proximity sensor on the APDS-9960
*
* @return True if sensor disabled correctly. False on error.
*/
bool glibr::disableProximitySensor()
{
if( !setProximityIntEnable(0) ) {
return false;
}
if( !setMode(PROXIMITY, 0) ) {
return false;
}
return true;
}
/**
* @brief Starts the gesture recognition engine on the APDS-9960
*
* @param[in] interrupts true to enable hardware external interrupt on gesture
* @return True if engine enabled correctly. False on error.
*/
bool glibr::enableGestureSensor(bool interrupts)
{
/* Enable gesture mode
Set ENABLE to 0 (power off)
Set WTIME to 0xFF
Set AUX to LED_BOOST_300
Enable PON, WEN, PEN, GEN in ENABLE
*/
resetGestureParameters();
if(I2CwriteByte(APDS9960_I2C_ADDR,APDS9960_WTIME, 0xFF) ) {
return false;
}
if(I2CwriteByte(APDS9960_I2C_ADDR,APDS9960_PPULSE, DEFAULT_GESTURE_PPULSE) ) {
return false;
}
if( !setLEDBoost(LED_BOOST_300) ) {
return false;
}
if( interrupts ) {
if( !setGestureIntEnable(1) ) {
return false;
}
} else {
if( !setGestureIntEnable(0) ) {
return false;
}
}
if( !setGestureMode(1) ) {
return false;
}
if( !enablePower() ){
return false;
}
if( !setMode(WAIT, 1) ) {
return false;
}
if( !setMode(PROXIMITY, 1) ) {
return false;
}
if( !setMode(GESTURE, 1) ) {
return false;
}
return true;
}
/**
* @brief Ends the gesture recognition engine on the APDS-9960
*
* @return True if engine disabled correctly. False on error.
*/
bool glibr::disableGestureSensor()
{
resetGestureParameters();
if( !setGestureIntEnable(0) ) {
return false;
}
if( !setGestureMode(0) ) {
return false;
}
if( !setMode(GESTURE, 0) ) {
return false;
}
return true;
}
/**
* @brief Determines if there is a gesture available for reading
*
* @return True if gesture available. False otherwise.
*/
bool glibr::isGestureAvailable()
{
uint8_t val;
/* Read value from GSTATUS register */
val=I2CreadByte(APDS9960_I2C_ADDR,APDS9960_GSTATUS);
if( val==ERROR) {
return ERROR;
}
/* Shift and mask out GVALID bit */
val &= APDS9960_GVALID;
/* Return true/false based on GVALID bit */
if( val == 1) {
return true;
} else {
return false;
}
}
int glibr::readGesture()
{
uint8_t fifo_level = 0;
// uint8_t bytes_expected= 0;
int check;
//char fifo_data[128];
char fifo_data[128];
char *fptr;
fptr= fifo_data;
uint8_t gstatus;
int motion;
int i;
/* Make sure that power and gesture is on and data is valid */
if( !isGestureAvailable() || !(getMode() & 0x41) ) {
return DIR_NONE;
}
/* Keep looping as long as gesture data is valid */
while(1) {
/* Wait some time to collect next batch of FIFO data */
thread_sleep_for(FIFO_PAUSE_TIME);
/* Get the contents of the STATUS register. Is data still valid? */
gstatus=I2CreadByte(APDS9960_I2C_ADDR,APDS9960_GSTATUS);
if( gstatus==ERROR ) {
return ERROR;
}
/* If we have valid data, read in FIFO */
if( (gstatus & APDS9960_GVALID) == APDS9960_GVALID ) {
/* Read the current FIFO level */
fifo_level=I2CreadByte(APDS9960_I2C_ADDR,APDS9960_GFLVL);
if( fifo_level==ERROR ) {
return ERROR;
}
//#if DEBUG
// Serial.print("FIFO Level: ");
// Serial.println(fifo_level);
//#endif
/* If there's stuff in the FIFO, read it into our data block */ //NEED TO FIGURE OUT WHAT THIS IS DOING.
if( fifo_level > 0) {
check = I2CReadDataBlock(APDS9960_I2C_ADDR,APDS9960_GFIFO_U,
fptr,
(fifo_level * 4) );
if( check == -1 ) {
return ERROR;
}
#if DEBUG
//Serial.print("FIFO Dump: ");
for ( i = 0; i < (fifo_level * 4); i++ ) {
// Serial.print(fifo_data[i]);
// Serial.print(" ");
}
//Serial.println();
#endif
/* If at least 1 set of data, sort the data into U/D/L/R */
if((fifo_level * 4) >= 4 ) {
for( i = 0; i < (fifo_level * 4); i += 4 ) {
gesture_data_.u_data[gesture_data_.sindex] = \
fifo_data[i + 0];
gesture_data_.d_data[gesture_data_.sindex] = \
fifo_data[i + 1];
gesture_data_.l_data[gesture_data_.sindex] = \
fifo_data[i + 2];
gesture_data_.r_data[gesture_data_.sindex] = \
fifo_data[i + 3];
gesture_data_.sindex++;
gesture_data_.total_gestures++;
}
#if DEBUG
// Serial.print("Up Data: ");
for ( i = 0; i < gesture_data_.total_gestures; i++ ) {
// Serial.print(gesture_data_.u_data[i]);
// Serial.print(" ");
}
// Serial.println();
#endif
/* Filter and process gesture data. Decode near/far state */
if( processGestureData() ) {
if( decodeGesture() ) {
//***TODO: U-Turn Gestures
#if DEBUG
//Serial.println(gesture_motion_);
#endif
}
}
/* Reset data */
gesture_data_.sindex = 0;
gesture_data_.total_gestures = 0;
}
}
} else {
/* Determine best guessed gesture and clean up */
thread_sleep_for(FIFO_PAUSE_TIME);
decodeGesture();
motion = gesture_motion_;
#if DEBUG
// Serial.print("END: ");
// Serial.println(gesture_motion_);
#endif
resetGestureParameters();
return motion;
}
}
// delete fptr;
}
/**
* Turn the APDS-9960 on
*
* @return True if operation successful. False otherwise.
*/
bool glibr::enablePower()
{
if( !setMode(Power, 1) ) {
return false;
}
return true;
}
/**
* Turn the APDS-9960 off
*
* @return True if operation successful. False otherwise.
*/
bool glibr::disablePower()
{
if( !setMode(Power, 0) ) {
return false;
}
return true;
}
/*******************************************************************************
* Ambient light and color sensor controls
******************************************************************************/
/**
* @brief Reads the ambient (clear) light level as a 16-bit value
*
* @param[out] val value of the light sensor.
* @return True if operation successful. False otherwise.
*/
bool glibr::readAmbientLight(uint16_t &val)
{
uint8_t val_byte;
val = 0;
/* Read value from clear channel, low byte register */
val_byte=I2CreadByte(APDS9960_I2C_ADDR,APDS9960_CDATAL);
if( val_byte==ERROR) {
return false;
}
val = val_byte;
/* Read value from clear channel, high byte register */
val_byte=I2CreadByte(APDS9960_I2C_ADDR,APDS9960_CDATAH);
if( val_byte==ERROR) {
return false;
}
val = val + ((uint16_t)val_byte << 8);
return true;
}
/**
* @brief Reads the red light level as a 16-bit value
*
* @param[out] val value of the light sensor.
* @return True if operation successful. False otherwise.
*/
bool glibr::readRedLight(uint16_t &val)
{
uint8_t val_byte;
val = 0;
/* Read value from clear channel, low byte register */
val_byte=I2CreadByte(APDS9960_I2C_ADDR,APDS9960_RDATAL);
if( val_byte==ERROR) {
return false;
}
val = val_byte;
/* Read value from clear channel, high byte register */
val_byte=I2CreadByte(APDS9960_I2C_ADDR,APDS9960_RDATAH);
if( val_byte==ERROR) {
return false;
}
val = val + ((uint16_t)val_byte << 8);
return true;
}
/**
* @brief Reads the green light level as a 16-bit value
*
* @param[out] val value of the light sensor.
* @return True if operation successful. False otherwise.
*/
bool glibr::readGreenLight(uint16_t &val)
{
uint8_t val_byte;
val = 0;
/* Read value from clear channel, low byte register */
val_byte=I2CreadByte(APDS9960_I2C_ADDR,APDS9960_GDATAL);
if( val_byte==ERROR) {
return false;
}
val = val_byte;
/* Read value from clear channel, high byte register */
val_byte=I2CreadByte(APDS9960_I2C_ADDR,APDS9960_GDATAH);
if( val_byte==ERROR) {
return false;
}
val = val + ((uint16_t)val_byte << 8);
return true;
}
/**
* @brief Reads the red light level as a 16-bit value
*
* @param[out] val value of the light sensor.
* @return True if operation successful. False otherwise.
*/
bool glibr::readBlueLight(uint16_t &val)
{
uint8_t val_byte;
val = 0;
/* Read value from clear channel, low byte register */
val_byte=I2CreadByte(APDS9960_I2C_ADDR,APDS9960_BDATAL);
if( val_byte==ERROR) {
return false;
}
val = val_byte;
/* Read value from clear channel, high byte register */
val_byte=I2CreadByte(APDS9960_I2C_ADDR,APDS9960_BDATAH);
if( val_byte==ERROR) {
return false;
}
val = val + ((uint16_t)val_byte << 8);
return true;
}
/*******************************************************************************
* Proximity sensor controls
******************************************************************************/
/**
* @brief Reads the proximity level as an 8-bit value
*
* @param[out] val value of the proximity sensor.
* @return True if operation successful. False otherwise.
*/
bool glibr::readProximity(uint8_t &val)
{
val = 0;
/* Read value from proximity data register */
val=I2CreadByte(APDS9960_I2C_ADDR,APDS9960_PDATA);
if(val==ERROR){
return false;
}
return true;
}
/*******************************************************************************
* High-level gesture controls
******************************************************************************/
/**
* @brief Resets all the parameters in the gesture data member
*/
void glibr::resetGestureParameters()
{
gesture_data_.sindex = 0;
gesture_data_.total_gestures = 0;
gesture_ud_delta_ = 0;
gesture_lr_delta_ = 0;
gesture_ud_count_ = 0;
gesture_lr_count_ = 0;
gesture_near_count_ = 0;
gesture_far_count_ = 0;
gesture_state_ = 0;
gesture_motion_ = DIR_NONE;
}
bool glibr::processGestureData()
{
uint8_t u_first = 0;
uint8_t d_first = 0;
uint8_t l_first = 0;
uint8_t r_first = 0;
uint8_t u_last = 0;
uint8_t d_last = 0;
uint8_t l_last = 0;
uint8_t r_last = 0;
int ud_ratio_first;
int lr_ratio_first;
int ud_ratio_last;
int lr_ratio_last;
int ud_delta;
int lr_delta;
int i;
/* If we have less than 4 total gestures, that's not enough */
if( gesture_data_.total_gestures <= 4 ) {
return false;
}
/* Check to make sure our data isn't out of bounds */
if( (gesture_data_.total_gestures <= 32) && \
(gesture_data_.total_gestures > 0) ) {
/* Find the first value in U/D/L/R above the threshold */
for( i = 0; i < gesture_data_.total_gestures; i++ ) {
if( (gesture_data_.u_data[i] > GESTURE_THRESHOLD_OUT) &&
(gesture_data_.d_data[i] > GESTURE_THRESHOLD_OUT) &&
(gesture_data_.l_data[i] > GESTURE_THRESHOLD_OUT) &&
(gesture_data_.r_data[i] > GESTURE_THRESHOLD_OUT) ) {
u_first = gesture_data_.u_data[i];
d_first = gesture_data_.d_data[i];
l_first = gesture_data_.l_data[i];
r_first = gesture_data_.r_data[i];
break;
}
}
/* If one of the _first values is 0, then there is no good data */
if( (u_first == 0) || (d_first == 0) || \
(l_first == 0) || (r_first == 0) ) {
return false;
}
/* Find the last value in U/D/L/R above the threshold */
for( i = gesture_data_.total_gestures - 1; i >= 0; i-- ) {
/* #if DEBUG
Serial.print(F("Finding last: "));
Serial.print(F("U:"));
Serial.print(gesture_data_.u_data[i]);
Serial.print(F(" D:"));
Serial.print(gesture_data_.d_data[i]);
Serial.print(F(" L:"));
Serial.print(gesture_data_.l_data[i]);
Serial.print(F(" R:"));
Serial.println(gesture_data_.r_data[i]);
#endif */
if( (gesture_data_.u_data[i] > GESTURE_THRESHOLD_OUT) &&
(gesture_data_.d_data[i] > GESTURE_THRESHOLD_OUT) &&
(gesture_data_.l_data[i] > GESTURE_THRESHOLD_OUT) &&
(gesture_data_.r_data[i] > GESTURE_THRESHOLD_OUT) ) {
u_last = gesture_data_.u_data[i];
d_last = gesture_data_.d_data[i];
l_last = gesture_data_.l_data[i];
r_last = gesture_data_.r_data[i];
break;
}
}
}
/* Calculate the first vs. last ratio of up/down and left/right */
ud_ratio_first = ((u_first - d_first) * 100) / (u_first + d_first);
lr_ratio_first = ((l_first - r_first) * 100) / (l_first + r_first);
ud_ratio_last = ((u_last - d_last) * 100) / (u_last + d_last);
lr_ratio_last = ((l_last - r_last) * 100) / (l_last + r_last);
/* #if DEBUG
Serial.print(F("Last Values: "));
Serial.print(F("U:"));
Serial.print(u_last);
Serial.print(F(" D:"));
Serial.print(d_last);
Serial.print(F(" L:"));
Serial.print(l_last);
Serial.print(F(" R:"));
Serial.println(r_last);
Serial.print(F("Ratios: "));
Serial.print(F("UD Fi: "));
Serial.print(ud_ratio_first);
Serial.print(F(" UD La: "));
Serial.print(ud_ratio_last);
Serial.print(F(" LR Fi: "));
Serial.print(lr_ratio_first);
Serial.print(F(" LR La: "));
Serial.println(lr_ratio_last);
#endif */
/* Determine the difference between the first and last ratios */
ud_delta = ud_ratio_last - ud_ratio_first;
lr_delta = lr_ratio_last - lr_ratio_first;
/* #if DEBUG
Serial.print("Deltas: ");
Serial.print("UD: ");
Serial.print(ud_delta);
Serial.print(" LR: ");
Serial.println(lr_delta);
#endif */
/* Accumulate the UD and LR delta values */
gesture_ud_delta_ += ud_delta;
gesture_lr_delta_ += lr_delta;
/* #if DEBUG
Serial.print("Accumulations: ");
Serial.print("UD: ");
Serial.print(gesture_ud_delta_);
Serial.print(" LR: ");
Serial.println(gesture_lr_delta_);
#endif */
/* Determine U/D gesture */
if( gesture_ud_delta_ >= GESTURE_SENSITIVITY_1 ) {
gesture_ud_count_ = 1;
} else if( gesture_ud_delta_ <= -GESTURE_SENSITIVITY_1 ) {
gesture_ud_count_ = -1;
} else {
gesture_ud_count_ = 0;
}
/* Determine L/R gesture */
if( gesture_lr_delta_ >= GESTURE_SENSITIVITY_1 ) {
gesture_lr_count_ = 1;
} else if( gesture_lr_delta_ <= -GESTURE_SENSITIVITY_1 ) {
gesture_lr_count_ = -1;
} else {
gesture_lr_count_ = 0;
}
/* Determine Near/Far gesture */
if( (gesture_ud_count_ == 0) && (gesture_lr_count_ == 0) ) {
if( (abs(ud_delta) < GESTURE_SENSITIVITY_2) && \
(abs(lr_delta) < GESTURE_SENSITIVITY_2) ) {
if( (ud_delta == 0) && (lr_delta == 0) ) {
gesture_near_count_++;
} else if( (ud_delta != 0) || (lr_delta != 0) ) {
gesture_far_count_++;
}
if( (gesture_near_count_ >= 10) && (gesture_far_count_ >= 2) ) {
if( (ud_delta == 0) && (lr_delta == 0) ) {
gesture_state_ = NEAR_STATE;
} else if( (ud_delta != 0) && (lr_delta != 0) ) {
gesture_state_ = FAR_STATE;
}
return true;
}
}
} else {
if( (abs(ud_delta) < GESTURE_SENSITIVITY_2) && \
(abs(lr_delta) < GESTURE_SENSITIVITY_2) ) {
if( (ud_delta == 0) && (lr_delta == 0) ) {
gesture_near_count_++;
}
if( gesture_near_count_ >= 5 ) {
gesture_ud_count_ = 0;
gesture_lr_count_ = 0;
gesture_ud_delta_ = 0;
gesture_lr_delta_ = 0;
}
}
}
// #if DEBUG
/* printf("UD_CT: %d\n",gesture_ud_count_);
printf("LR_CT: %d\n",gesture_lr_count_);
printf("NEAR_CT: %d\n",gesture_near_count_);
printf(" FAR_CT: %d\n",gesture_far_count_);
printf("----------"); */
//#endif */
return false;
}
/**
* @brief Determines swipe direction or near/far state
*
* @return True if near/far event. False otherwise.
*/
bool glibr::decodeGesture()
{
/* Return if near or far event is detected */
if( gesture_state_ == NEAR_STATE ) {
gesture_motion_ = DIR_NEAR;
return true;
} else if ( gesture_state_ == FAR_STATE ) {
gesture_motion_ = DIR_FAR;
return true;
}
/* Determine swipe direction */
if( (gesture_ud_count_ == -1) && (gesture_lr_count_ == 0) ) {
gesture_motion_ = DIR_UP;
} else if( (gesture_ud_count_ == 1) && (gesture_lr_count_ == 0) ) {
gesture_motion_ = DIR_DOWN;
} else if( (gesture_ud_count_ == 0) && (gesture_lr_count_ == 1) ) {
gesture_motion_ = DIR_RIGHT;
} else if( (gesture_ud_count_ == 0) && (gesture_lr_count_ == -1) ) {
gesture_motion_ = DIR_LEFT;
} else if( (gesture_ud_count_ == -1) && (gesture_lr_count_ == 1) ) {
if( abs(gesture_ud_delta_) > abs(gesture_lr_delta_) ) {
gesture_motion_ = DIR_UP;
} else {
gesture_motion_ = DIR_RIGHT;
}
} else if( (gesture_ud_count_ == 1) && (gesture_lr_count_ == -1) ) {
if( abs(gesture_ud_delta_) > abs(gesture_lr_delta_) ) {
gesture_motion_ = DIR_DOWN;
} else {
gesture_motion_ = DIR_LEFT;
}
} else if( (gesture_ud_count_ == -1) && (gesture_lr_count_ == -1) ) {
if( abs(gesture_ud_delta_) > abs(gesture_lr_delta_) ) {
gesture_motion_ = DIR_UP;
} else {
gesture_motion_ = DIR_LEFT;
}
} else if( (gesture_ud_count_ == 1) && (gesture_lr_count_ == 1) ) {
if( abs(gesture_ud_delta_) > abs(gesture_lr_delta_) ) {
gesture_motion_ = DIR_DOWN;
} else {
gesture_motion_ = DIR_RIGHT;
}
} else {
return false;
}
return true;
}
/*******************************************************************************
* Getters and setters for register values
******************************************************************************/
/**
* @brief Returns the lower threshold for proximity detection
*
* @return lower threshold
*/
uint8_t glibr::getProxIntLowThresh()
{
uint8_t val;
/* Read value from PILT register */
/* if( !wireReadDataByte(APDS9960_PILT, val) ) {
val = 0;
}*/
val=I2CreadByte(APDS9960_I2C_ADDR,APDS9960_PILT);
if(val==ERROR){
val=0;
}
return val;
}
/**
* @brief Sets the lower threshold for proximity detection
*
* @param[in] threshold the lower proximity threshold
* @return True if operation successful. False otherwise.
*/
bool glibr::setProxIntLowThresh(uint8_t threshold)
{
if( I2CwriteByte(APDS9960_I2C_ADDR,APDS9960_PILT, threshold) ) {
return false;
}
return true;
}
/**
* @brief Returns the high threshold for proximity detection
*
* @return high threshold
*/
uint8_t glibr::getProxIntHighThresh()
{
uint8_t val;
/* Read value from PIHT register */
val=I2CreadByte(APDS9960_I2C_ADDR,APDS9960_PILT);
if( val==ERROR ) {
val = 0;
}
return val;
}
/**
* @brief Sets the high threshold for proximity detection
*
* @param[in] threshold the high proximity threshold
* @return True if operation successful. False otherwise.
*/
bool glibr::setProxIntHighThresh(uint8_t threshold)
{
if( I2CwriteByte(APDS9960_I2C_ADDR,APDS9960_PIHT, threshold) ) {
return false;
}
return true;
}
/**
* @brief Returns LED drive strength for proximity and ALS
*
* Value LED Current
* 0 100 mA
* 1 50 mA
* 2 25 mA
* 3 12.5 mA
*
* @return the value of the LED drive strength. 0xFF on failure.
*/
uint8_t glibr::getLEDDrive()
{
uint8_t val;
/* Read value from CONTROL register */
val=I2CreadByte(APDS9960_I2C_ADDR,APDS9960_CONTROL);
if( val == ERROR ){//!wireReadDataByte(APDS9960_CONTROL, val) ) {
return ERROR;
}
/* Shift and mask out LED drive bits */
val = (val >> 6) & 0x03;//0b00000011;
return val;
}
/**
* @brief Sets the LED drive strength for proximity and ALS
*
* Value LED Current
* 0 100 mA
* 1 50 mA
* 2 25 mA
* 3 12.5 mA
*
* @param[in] drive the value (0-3) for the LED drive strength
* @return True if operation successful. False otherwise.
*/
bool glibr::setLEDDrive(uint8_t drive)
{
uint8_t val;
/* Read value from CONTROL register */
val=I2CreadByte(APDS9960_I2C_ADDR,APDS9960_CONTROL);
if(val==ERROR){
return false;
}
/* Set bits in register to given value */
//drive &= 0b00000011
drive &= 0x03;
drive = drive << 6;
//val &= 0b00111111;
val &= 0x3F;
val |= drive;
/* Write register value back into CONTROL register */
if( I2CwriteByte(APDS9960_I2C_ADDR,APDS9960_CONTROL, val) ) {
return false;
}
return true;
}
/**
* @brief Returns receiver gain for proximity detection
*
* Value Gain
* 0 1x
* 1 2x
* 2 4x
* 3 8x
*
* @return the value of the proximity gain. 0xFF on failure.
*/
uint8_t glibr::getProximityGain()
{
uint8_t val;
/* Read value from CONTROL register */
val=I2CreadByte(APDS9960_I2C_ADDR,APDS9960_CONTROL);
if( val == ERROR){//!wireReadDataByte(APDS9960_CONTROL, val) ) {
return ERROR;
}
/* Shift and mask out PDRIVE bits */
val = (val >> 2) & 0x03;//0b00000011;
return val;
}
/**
* @brief Sets the receiver gain for proximity detection
*
* Value Gain
* 0 1x
* 1 2x
* 2 4x
* 3 8x
*
* @param[in] drive the value (0-3) for the gain
* @return True if operation successful. False otherwise.
*/
bool glibr::setProximityGain(uint8_t drive)
{
uint8_t val;
/* Read value from CONTROL register */
val=I2CreadByte(APDS9960_I2C_ADDR,APDS9960_CONTROL);
if(val==ERROR){
return false;
}
/* Set bits in register to given value */
//drive &= 0b00000011;
drive &=0x03;
drive = drive << 2;
//val &= 0b11110011
val &= 0xF3;
val |= drive;
/* Write register value back into CONTROL register */
if( I2CwriteByte(APDS9960_I2C_ADDR,APDS9960_CONTROL, val) ) {
return false;
}
return true;
}
/**
* @brief Returns receiver gain for the ambient light sensor (ALS)
*
* Value Gain
* 0 1x
* 1 4x
* 2 16x
* 3 64x
*
* @return the value of the ALS gain. 0xFF on failure.
*/
uint8_t glibr::getAmbientLightGain()
{
uint8_t val;
/* Read value from CONTROL register */
val=I2CreadByte(APDS9960_I2C_ADDR,APDS9960_CONTROL);
if( val == ERROR){//!wireReadDataByte(APDS9960_CONTROL, val) ) {
return ERROR;
}
/* Shift and mask out ADRIVE bits */
val &= 0x03;//0b00000011;
return val;
}
/**
* @brief Sets the receiver gain for the ambient light sensor (ALS)
*
* Value Gain
* 0 1x
* 1 4x
* 2 16x
* 3 64x
*
* @param[in] drive the value (0-3) for the gain
* @return True if operation successful. False otherwise.
*/
bool glibr::setAmbientLightGain(uint8_t drive){
uint8_t val;
/* Read value from CONTROL register */
val=I2CreadByte(APDS9960_I2C_ADDR,APDS9960_CONTROL);
if(val==ERROR){
return false;
}
/* Set bits in register to given value */
//drive &= 0b00000011;
drive &=0x03;
drive = drive << 2;
//val &=0b11111100
val &= 0xF3;
val |= drive;
/* Write register value back into CONTROL register */
if( I2CwriteByte(APDS9960_I2C_ADDR,APDS9960_CONTROL, val) ) {
return false;
}
return true;
}
/**
* @brief Get the current LED boost value
*
* Value Boost Current
* 0 100%
* 1 150%
* 2 200%
* 3 300%
*
* @return The LED boost value. 0xFF on failure.
*/
uint8_t glibr::getLEDBoost() {
uint8_t val;
/* Read value from CONFIG2 register */
val = I2CreadByte(APDS9960_I2C_ADDR, APDS9960_CONFIG2);
if( val == ERROR){//!wireReadDataByte(APDS9960_CONFIG2, val) ) {
return ERROR;
}
/* Shift and mask out LED_BOOST bits */
val = (val >> 4) & 0x03;//0b00000011;
return val;
}
/**
* @brief Sets the LED current boost value
*
* Value Boost Current
* 0 100%
* 1 150%
* 2 200%
* 3 300%
*
* @param[in] drive the value (0-3) for current boost (100-300%)
* @return True if operation successful. False otherwise.
*/
bool glibr::setLEDBoost(uint8_t boost)
{
uint8_t val;
/* Read value from CONFIG2 register */
val = I2CreadByte(APDS9960_I2C_ADDR, APDS9960_CONFIG2);
if( val == ERROR){//!wireReadDataByte(APDS9960_CONFIG2, val) ) {
return false;
}
/* Set bits in register to given value */
boost &= 0x03;//0b00000011;
boost = boost << 4;
val &= 0xCF;//0b11001111;
val |= boost;
/* Write register value back into CONFIG2 register */
if( I2CwriteByte(APDS9960_I2C_ADDR,APDS9960_CONFIG2, val)){//!wireWriteDataByte(APDS9960_CONFIG2, val) ) {
return false;
}
return true;
}
/**
* @brief Gets proximity gain compensation enable
*
* @return 1 if compensation is enabled. 0 if not. 0xFF on error.
*/
uint8_t glibr::getProxGainCompEnable()
{
uint8_t val;
/* Read value from CONFIG3 register */
val = I2CreadByte(APDS9960_I2C_ADDR, APDS9960_CONFIG3);
if( val == ERROR){//!wireReadDataByte(APDS9960_CONFIG3, val) ) {
return ERROR;
}
/* Shift and mask out PCMP bits */
val = (val >> 5) & 0x01;//0b00000001;
return val;
}
/**
* @brief Sets the proximity gain compensation enable
*
* @param[in] enable 1 to enable compensation. 0 to disable compensation.
* @return True if operation successful. False otherwise.
*/
bool glibr::setProxGainCompEnable(uint8_t enable)
{
uint8_t val;
/* Read value from CONFIG3 register */
val = I2CreadByte(APDS9960_I2C_ADDR, APDS9960_CONFIG3);
if( val == ERROR){//!wireReadDataByte(APDS9960_CONFIG3, val) ) {
return false;
}
/* Set bits in register to given value */
enable &= 0x01;//0b00000001;
enable = enable << 5;
val &= 0xCF;//0b11011111;
val |= enable;
/* Write register value back into CONFIG3 register */
if( I2CwriteByte(APDS9960_I2C_ADDR,APDS9960_CONFIG3, val)){//!wireWriteDataByte(APDS9960_CONFIG3, val) ) {
return false;
}
return true;
}
/**
* @brief Gets the current mask for enabled/disabled proximity photodiodes
*
* 1 = disabled, 0 = enabled
* Bit Photodiode
* 3 UP
* 2 DOWN
* 1 LEFT
* 0 RIGHT
*
* @return Current proximity mask for photodiodes. 0xFF on error.
*/
uint8_t glibr::getProxPhotoMask()
{
uint8_t val;
/* Read value from CONFIG3 register */
val = I2CreadByte(APDS9960_I2C_ADDR, APDS9960_CONFIG3);
if( val == ERROR){//!wireReadDataByte(APDS9960_CONFIG3, val) ) {
return ERROR;
}
/* Mask out photodiode enable mask bits */
val &= 0x0F;//0b00001111;
return val;
}
/**
* @brief Sets the mask for enabling/disabling proximity photodiodes
*
* 1 = disabled, 0 = enabled
* Bit Photodiode
* 3 UP
* 2 DOWN
* 1 LEFT
* 0 RIGHT
*
* @param[in] mask 4-bit mask value
* @return True if operation successful. False otherwise.
*/
bool glibr::setProxPhotoMask(uint8_t mask)
{
uint8_t val;
/* Read value from CONFIG3 register */
val = I2CreadByte(APDS9960_I2C_ADDR, APDS9960_CONFIG3);
if( val == ERROR){//!wireReadDataByte(APDS9960_CONFIG3, val) ) {
return false;
}
/* Set bits in register to given value */
mask &= 0x0F;//0b00001111;
val &= 0xF0;//0b11110000;
val |= mask;
/* Write register value back into CONFIG3 register */
I2CwriteByte(APDS9960_I2C_ADDR, APDS9960_CONFIG3, val);
if( val == ERROR){//!wireWriteDataByte(APDS9960_CONFIG3, val) ) {
return false;
}
return true;
}
/**
* @brief Gets the entry proximity threshold for gesture sensing
*
* @return Current entry proximity threshold.
*/
uint8_t glibr::getGestureEnterThresh()
{
uint8_t val;
/* Read value from GPENTH register */
val = I2CreadByte(APDS9960_I2C_ADDR, APDS9960_GPENTH);
if( val == ERROR){//!wireReadDataByte(APDS9960_GPENTH, val) ) {
val = 0;
}
return val;
}
/**
* @brief Sets the entry proximity threshold for gesture sensing
*
* @param[in] threshold proximity value needed to start gesture mode
* @return True if operation successful. False otherwise.
*/
bool glibr::setGestureEnterThresh(uint8_t threshold)
{
if( I2CwriteByte(APDS9960_I2C_ADDR, APDS9960_GPENTH, threshold)){;//!wireWriteDataByte(APDS9960_GPENTH, threshold) ) {
return false;
}
return true;
}
/**
* @brief Gets the exit proximity threshold for gesture sensing
*
* @return Current exit proximity threshold.
*/
uint8_t glibr::getGestureExitThresh()
{
uint8_t val;
/* Read value from GEXTH register */
val = I2CreadByte(APDS9960_I2C_ADDR, APDS9960_GEXTH);
if( val == ERROR){//!wireReadDataByte(APDS9960_GEXTH, val) ) {
val = 0;
}
return val;
}
/**
* @brief Sets the exit proximity threshold for gesture sensing
*
* @param[in] threshold proximity value needed to end gesture mode
* @return True if operation successful. False otherwise.
*/
bool glibr::setGestureExitThresh(uint8_t threshold)
{
if( I2CwriteByte(APDS9960_I2C_ADDR, APDS9960_GEXTH, threshold)){//!wireWriteDataByte(APDS9960_GEXTH, threshold) ) {
return false;
}
return true;
}
/**
* @brief Gets the gain of the photodiode during gesture mode
*
* Value Gain
* 0 1x
* 1 2x
* 2 4x
* 3 8x
*
* @return the current photodiode gain. 0xFF on error.
*/
uint8_t glibr::getGestureGain()
{
uint8_t val;
/* Read value from GCONF2 register */
val = I2CreadByte(APDS9960_I2C_ADDR, APDS9960_GCONF2);
if( val == ERROR){//!wireReadDataByte(APDS9960_GCONF2, val) ) {
return ERROR;
}
/* Shift and mask out GGAIN bits */
val = (val >> 5) & 0x03;//0b00000011;
return val;
}
/**
* @brief Sets the gain of the photodiode during gesture mode
*
* Value Gain
* 0 1x
* 1 2x
* 2 4x
* 3 8x
*
* @param[in] gain the value for the photodiode gain
* @return True if operation successful. False otherwise.
*/
bool glibr::setGestureGain(uint8_t gain)
{
uint8_t val;
/* Read value from GCONF2 register */
val = I2CreadByte(APDS9960_I2C_ADDR, APDS9960_GCONF2);
if( val == ERROR){//!wireReadDataByte(APDS9960_GCONF2, val) ) {
return false;
}
/* Set bits in register to given value */
gain &= 0x03;//0b00000011;
gain = gain << 5;
val &= 0x9F;//0b10011111;
val |= gain;
/* Write register value back into GCONF2 register */
if( I2CwriteByte(APDS9960_I2C_ADDR, APDS9960_GCONF2, val)){//!wireWriteDataByte(APDS9960_GCONF2, val) ) {
return false;
}
return true;
}
/**
* @brief Gets the drive current of the LED during gesture mode
*
* Value LED Current
* 0 100 mA
* 1 50 mA
* 2 25 mA
* 3 12.5 mA
*
* @return the LED drive current value. 0xFF on error.
*/
uint8_t glibr::getGestureLEDDrive()
{
uint8_t val;
/* Read value from GCONF2 register */
val = I2CreadByte(APDS9960_I2C_ADDR, APDS9960_GCONF2);
if( val == ERROR){//!wireReadDataByte(APDS9960_GCONF2, val) ) {
return ERROR;
}
/* Shift and mask out GLDRIVE bits */
val = (val >> 3) & 0x03;//0b00000011;
return val;
}
/**
* @brief Sets the LED drive current during gesture mode
*
* Value LED Current
* 0 100 mA
* 1 50 mA
* 2 25 mA
* 3 12.5 mA
*
* @param[in] drive the value for the LED drive current
* @return True if operation successful. False otherwise.
*/
bool glibr::setGestureLEDDrive(uint8_t drive)
{
uint8_t val;
/* Read value from GCONF2 register */
val = I2CreadByte(APDS9960_I2C_ADDR, APDS9960_GCONF2);
if( val == ERROR){//!wireReadDataByte(APDS9960_GCONF2, val) ) {
return false;
}
/* Set bits in register to given value */
drive &= 0x03;//0b00000011;
drive = drive << 3;
val &= 0xE7;//0b11100111;
val |= drive;
/* Write register value back into GCONF2 register */
if( I2CwriteByte(APDS9960_I2C_ADDR, APDS9960_GCONF2, val)){//!wireWriteDataByte(APDS9960_GCONF2, val) ) {
return false;
}
return true;
}
/**
* @brief Gets the time in low power mode between gesture detections
*
* Value Wait time
* 0 0 ms
* 1 2.8 ms
* 2 5.6 ms
* 3 8.4 ms
* 4 14.0 ms
* 5 22.4 ms
* 6 30.8 ms
* 7 39.2 ms
*
* @return the current wait time between gestures. 0xFF on error.
*/
uint8_t glibr::getGestureWaitTime()
{
uint8_t val;
/* Read value from GCONF2 register */
val = I2CreadByte(APDS9960_I2C_ADDR, APDS9960_GCONF2);
if( val == ERROR){//!wireReadDataByte(APDS9960_GCONF2, val) ) {
return ERROR;
}
/* Mask out GWTIME bits */
val &= 0x07;//0b00000111;
return val;
}
/*
*
*
*
*LEFT Off HERE AT 3:47PM On 3/6/15
*
*
*
*
*/
/**
* @brief Sets the time in low power mode between gesture detections
*
* Value Wait time
* 0 0 ms
* 1 2.8 ms
* 2 5.6 ms
* 3 8.4 ms
* 4 14.0 ms
* 5 22.4 ms
* 6 30.8 ms
* 7 39.2 ms
*
* @param[in] the value for the wait time
* @return True if operation successful. False otherwise.
*/
bool glibr::setGestureWaitTime(uint8_t time)
{
uint8_t val;
/* Read value from GCONF2 register */
val = I2CreadByte(APDS9960_I2C_ADDR, APDS9960_GCONF2);
if( val == ERROR){//!wireReadDataByte(APDS9960_GCONF2, val) ) {
return false;
}
/* if( !wireReadDataByte(APDS9960_GCONF2, val) ) {
return false;
} */
/* Set bits in register to given value */
time &= 0x07;//0b00000111;
val &= 0xF8;//0b11111000;
val |= time;
/* Write register value back into GCONF2 register */
if( I2CwriteByte(APDS9960_I2C_ADDR,APDS9960_GCONF2,val)){//!wireWriteDataByte(APDS9960_GCONF2, val) ) {
return false;
}
/*if( !wireWriteDataByte(APDS9960_GCONF2, val) ) {
return false;
}*/
return true;
}
/**
* @brief Gets the low threshold for ambient light interrupts
*
* @param[out] threshold current low threshold stored on the APDS-9960
* @return True if operation successful. False otherwise.
*/
bool glibr::getLightIntLowThreshold(uint16_t &threshold)
{
uint8_t val_byte;
threshold = 0;
/* Read value from ambient light low threshold, low byte register */
val_byte = I2CreadByte(APDS9960_I2C_ADDR, APDS9960_AILTL);
if( val_byte == ERROR){//!wireReadDataByte(APDS9960_AILTL, val_byte) ) {
return false;
}
threshold = val_byte;
/* Read value from ambient light low threshold, high byte register */
val_byte = I2CreadByte(APDS9960_I2C_ADDR, APDS9960_AILTH);
if( val_byte == ERROR){//!wireReadDataByte(APDS9960_AILTH, val_byte) ) {
return false;
}
threshold = threshold + ((uint16_t)val_byte << 8);
return true;
}
/**
* @brief Sets the low threshold for ambient light interrupts
*
* @param[in] threshold low threshold value for interrupt to trigger
* @return True if operation successful. False otherwise.
*/
bool glibr::setLightIntLowThreshold(uint16_t threshold)
{
uint8_t val_low;
uint8_t val_high;
/* Break 16-bit threshold into 2 8-bit values */
val_low = threshold & 0x00FF;
val_high = (threshold & 0xFF00) >> 8;
/* Write low byte */
if( I2CwriteByte(APDS9960_I2C_ADDR,APDS9960_AILTL,val_low)){//!wireWriteDataByte(APDS9960_AILTL, val_low) ) {
return false;
}
/* Write high byte */
if( I2CwriteByte(APDS9960_I2C_ADDR,APDS9960_AILTH,val_high)){//!wireWriteDataByte(APDS9960_AILTH, val_high) ) {
return false;
}
return true;
}
/**
* @brief Gets the high threshold for ambient light interrupts
*
* @param[out] threshold current low threshold stored on the APDS-9960
* @return True if operation successful. False otherwise.
*/
bool glibr::getLightIntHighThreshold(uint16_t &threshold)
{
uint8_t val_byte;
threshold = 0;
/* Read value from ambient light high threshold, low byte register */
val_byte = I2CreadByte(APDS9960_I2C_ADDR, APDS9960_AIHTL);
if( val_byte == ERROR){//!wireReadDataByte(APDS9960_AIHTL, val_byte) ) {
return false;
}
threshold = val_byte;
/* Read value from ambient light high threshold, high byte register */
val_byte = I2CreadByte(APDS9960_I2C_ADDR, APDS9960_AIHTH);
if( val_byte == ERROR){//!wireReadDataByte(APDS9960_AIHTH, val_byte) ) {
return false;
}
threshold = threshold + ((uint16_t)val_byte << 8);
return true;
}
/**
* @brief Sets the high threshold for ambient light interrupts
*
* @param[in] threshold high threshold value for interrupt to trigger
* @return True if operation successful. False otherwise.
*/
bool glibr::setLightIntHighThreshold(uint16_t threshold)
{
uint8_t val_low;
uint8_t val_high;
/* Break 16-bit threshold into 2 8-bit values */
val_low = threshold & 0x00FF;
val_high = (threshold & 0xFF00) >> 8;
/* Write low byte */
if( I2CwriteByte(APDS9960_I2C_ADDR,APDS9960_AIHTL,val_low)){//!wireWriteDataByte(APDS9960_AIHTL, val_low) ) {
return false;
}
/* Write high byte */
if( I2CwriteByte(APDS9960_I2C_ADDR,APDS9960_AIHTH,val_high)){//!wireWriteDataByte(APDS9960_AIHTH, val_high) ) {
return false;
}
return true;
}
/**
* @brief Gets the low threshold for proximity interrupts
*
* @param[out] threshold current low threshold stored on the APDS-9960
* @return True if operation successful. False otherwise.
*/
bool glibr::getProximityIntLowThreshold(uint8_t &threshold)
{
threshold = 0;
/* Read value from proximity low threshold register */
threshold = I2CreadByte(APDS9960_I2C_ADDR, APDS9960_PILT);
if( threshold == ERROR){//!wireReadDataByte(APDS9960_PILT, threshold) ) {
return false;
}
return true;
}
/**
* @brief Sets the low threshold for proximity interrupts
*
* @param[in] threshold low threshold value for interrupt to trigger
* @return True if operation successful. False otherwise.
*/
bool glibr::setProximityIntLowThreshold(uint8_t threshold)
{
/* Write threshold value to register */
if( I2CwriteByte(APDS9960_I2C_ADDR,APDS9960_PILT,threshold)){//!wireWriteDataByte(APDS9960_PILT, threshold) ) {
return false;
}
return true;
}
/**
* @brief Gets the high threshold for proximity interrupts
*
* @param[out] threshold current low threshold stored on the APDS-9960
* @return True if operation successful. False otherwise.
*/
bool glibr::getProximityIntHighThreshold(uint8_t &threshold)
{
threshold = 0;
/* Read value from proximity low threshold register */
threshold = I2CreadByte(APDS9960_I2C_ADDR, APDS9960_PIHT);
if( threshold == ERROR){//!wireReadDataByte(APDS9960_PIHT, threshold) ) {
return false;
}
return true;
}
/**
* @brief Sets the high threshold for proximity interrupts
*
* @param[in] threshold high threshold value for interrupt to trigger
* @return True if operation successful. False otherwise.
*/
bool glibr::setProximityIntHighThreshold(uint8_t threshold)
{
/* Write threshold value to register */
if( I2CwriteByte(APDS9960_I2C_ADDR,APDS9960_PIHT,threshold)){//!wireWriteDataByte(APDS9960_PIHT, threshold) ) {
return false;
}
return true;
}
/**
* @brief Gets if ambient light interrupts are enabled or not
*
* @return 1 if interrupts are enabled, 0 if not. 0xFF on error.
*/
uint8_t glibr::getAmbientLightIntEnable()
{
uint8_t val;
/* Read value from ENABLE register */
val = I2CreadByte(APDS9960_I2C_ADDR, APDS9960_ENABLE);
if( val == ERROR){//!wireReadDataByte(APDS9960_ENABLE, val) ) {
return ERROR;
}
/* Shift and mask out AIEN bit */
val = (val >> 4) & 0x01;//0b00000001;
return val;
}
/**
* @brief Turns ambient light interrupts on or off
*
* @param[in] enable 1 to enable interrupts, 0 to turn them off
* @return True if operation successful. False otherwise.
*/
bool glibr::setAmbientLightIntEnable(uint8_t enable)
{
uint8_t val;
/* Read value from ENABLE register */
val = I2CreadByte(APDS9960_I2C_ADDR, APDS9960_ENABLE);
if( val == ERROR){//!wireReadDataByte(APDS9960_ENABLE, val) ) {
return false;
}
/* Set bits in register to given value */
enable &= 0x01;//0b00000001;
enable = enable << 4;
val &= 0xEF;//0b11101111;
val |= enable;
/* Write register value back into ENABLE register */
if( I2CwriteByte(APDS9960_I2C_ADDR,APDS9960_ENABLE,val)){//!wireWriteDataByte(APDS9960_ENABLE, val) ) {
return false;
}
return true;
}
/**
* @brief Gets if proximity interrupts are enabled or not
*
* @return 1 if interrupts are enabled, 0 if not. 0xFF on error.
*/
uint8_t glibr::getProximityIntEnable()
{
uint8_t val;
/* Read value from ENABLE register */
val = I2CreadByte(APDS9960_I2C_ADDR, APDS9960_ENABLE);
if( val == ERROR){//!wireReadDataByte(APDS9960_ENABLE, val) ) {
return ERROR;
}
/* Shift and mask out PIEN bit */
val = (val >> 5) & 0x01;//0b00000001;
return val;
}
/**
* @brief Turns proximity interrupts on or off
*
* @param[in] enable 1 to enable interrupts, 0 to turn them off
* @return True if operation successful. False otherwise.
*/
bool glibr::setProximityIntEnable(uint8_t enable)
{
uint8_t val;
/* Read value from ENABLE register */
val = I2CreadByte(APDS9960_I2C_ADDR, APDS9960_ENABLE);
if( val == ERROR){//!wireReadDataByte(APDS9960_ENABLE, val) ) {
return false;
}
/* Set bits in register to given value */
enable &= 0x01;//0b00000001;
enable = enable << 5;
val &= 0xDF;//0b11011111;
val |= enable;
/* Write register value back into ENABLE register */
if( I2CwriteByte(APDS9960_I2C_ADDR,APDS9960_ENABLE,val)){//!wireWriteDataByte(APDS9960_ENABLE, val) ) {
return false;
}
return true;
}
/**
* @brief Gets if gesture interrupts are enabled or not
*
* @return 1 if interrupts are enabled, 0 if not. 0xFF on error.
*/
uint8_t glibr::getGestureIntEnable()
{
uint8_t val;
/* Read value from GCONF4 register */
val = I2CreadByte(APDS9960_I2C_ADDR, APDS9960_GCONF4);
if( val == ERROR){//!wireReadDataByte(APDS9960_GCONF4, val) ) {
return ERROR;
}
/* Shift and mask out GIEN bit */
val = (val >> 1) & 0x01;//0b00000001;
return val;
}
/**
* @brief Turns gesture-related interrupts on or off
*
* @param[in] enable 1 to enable interrupts, 0 to turn them off
* @return True if operation successful. False otherwise.
*/
bool glibr::setGestureIntEnable(uint8_t enable)
{
uint8_t val;
/* Read value from GCONF4 register */
val = I2CreadByte(APDS9960_I2C_ADDR, APDS9960_GCONF4);
if( val == ERROR){//!wireReadDataByte(APDS9960_GCONF4, val) ) {
return false;
}
/* Set bits in register to given value */
enable &= 0x01;//0b00000001;
enable = enable << 1;
val &= 0xFD;//0b11111101;
val |= enable;
/* Write register value back into GCONF4 register */
if( I2CwriteByte(APDS9960_I2C_ADDR,APDS9960_GCONF4,val)){//!wireWriteDataByte(APDS9960_GCONF4, val) ) {
return false;
}
return true;
}
/**
* @brief Clears the ambient light interrupt
*
* @return True if operation completed successfully. False otherwise.
*/
bool glibr::clearAmbientLightInt()
{
uint8_t throwaway;
throwaway = I2CreadByte(APDS9960_I2C_ADDR, APDS9960_AICLEAR);
if( throwaway == ERROR){//!wireReadDataByte(APDS9960_AICLEAR, throwaway) ) {
return false;
}
return true;
}
/**
* @brief Clears the proximity interrupt
*
* @return True if operation completed successfully. False otherwise.
*/
bool glibr::clearProximityInt()
{
uint8_t throwaway;
throwaway = I2CreadByte(APDS9960_I2C_ADDR, APDS9960_PICLEAR);
if( throwaway == ERROR){//!wireReadDataByte(APDS9960_PICLEAR, throwaway) ) {
return false;
}
return true;
}
/**
* @brief Tells if the gesture state machine is currently running
*
* @return 1 if gesture state machine is running, 0 if not. 0xFF on error.
*/
uint8_t glibr::getGestureMode()
{
uint8_t val;
/* Read value from GCONF4 register */
val = I2CreadByte(APDS9960_I2C_ADDR, APDS9960_GCONF4);
if( val == ERROR){//!wireReadDataByte(APDS9960_GCONF4, val) ) {
return ERROR;
}
/* Mask out GMODE bit */
val &= 0x01;//0b00000001;
return val;
}
/**
* @brief Tells the state machine to either enter or exit gesture state machine
*
* @param[in] mode 1 to enter gesture state machine, 0 to exit.
* @return True if operation successful. False otherwise.
*/
bool glibr::setGestureMode(uint8_t mode)
{
uint8_t val;
/* Read value from GCONF4 register */
val = I2CreadByte(APDS9960_I2C_ADDR, APDS9960_GCONF4);
if( val == ERROR){//!wireReadDataByte(APDS9960_GCONF4, val) ) {
return false;
}
/* Set bits in register to given value */
mode &= 0x01;//0b00000001;
val &= 0xFE;//0b11111110;
val |= mode;
/* Write register value back into GCONF4 register */
if( I2CwriteByte(APDS9960_I2C_ADDR,APDS9960_GCONF4,val)){//!wireWriteDataByte(APDS9960_GCONF4, val) ) {
return false;
}
return true;
}
int glibr::I2CwriteByte(char address, char subAddress, char data)
{
int ret;
char cmd[2] = {subAddress, data};
ret=i2c.write(address<<1, cmd, 2); //if ret is 1, then not acked.
return ret;
}
uint8_t glibr::I2CreadByte(char address, char subAddress)
{
char data; // store the register data
if(i2c.write(address<<1, &subAddress, 1, true)){
return ERROR; //7 bit //not acked
}
if(i2c.read(address<<1, &data, 1)){ /////CHANGED THIS NEED TO TEST.
return ERROR;
}
//i2c.read(address<<1, &data, 1);
return data;
}
// * @brief Reads a block (array) of bytes from the I2C device and register
// *
// * @param[in] reg the register to read from
// * @param[out] val pointer to the beginning of the data
// * @param[in] len number of bytes to read
// * @return Number of bytes read. -1 on read error.
// */
int glibr::I2CReadDataBlock(char address, char subAddress, char *data, unsigned int len)
{
// unsigned char i = 0;
/* Indicate which register we want to read from */
if(i2c.write(address<<1, &subAddress, 1, true)){
return -1; //7 bit //not acked
}
/* Read block data */
if(i2c.read(address<<1, data, len)){
return -1;
}
return 1;
//Wire.requestFrom(APDS9960_I2C_ADDR, len);
/*while (Wire.available()) {
if (i >= len) {
return -1;
}
val[i] = Wire.read();
i++;
}*/
} | [
"[email protected]"
] | |
d0c307898bec64267e8f8ed8d845b47b78a5fd8f | 9fc919b7e778361bc81137f6a0a1abe6acbc74bc | /onerut_parser_rules/include/onerut_parser_rules/function_factory_constant.hpp | 47d8e1861623341aab4c62a94b3bf23588728fd6 | [] | no_license | MateuszSnamina/onerut | 315f712d36d2ebc797e0292b9d78b7629d81df2c | a38b3790f995aac1a89f415c47f27f7b63bf8c0d | refs/heads/master | 2020-04-16T10:41:44.417458 | 2019-06-02T21:49:07 | 2019-06-02T21:49:07 | 165,513,612 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 937 | hpp | #ifndef ONERUT_PARSER_RULES_FUNCTION_FACTORY_CONSTANTS
#define ONERUT_PARSER_RULES_FUNCTION_FACTORY_CONSTANTS
#include<onerut_scalar/scalar_real.hpp>
#include<onerut_scalar/scalar_complex.hpp>
#include<onerut_parser_rules/function_factory_abstract.hpp>
namespace onerut_parser_rules {
class RealConstantFunctionFactory : public NaryFunctionFactory<0> {
public:
RealConstantFunctionFactory(double);
onerut_parser_exec::Asset make_function_otherwise_make_error(std::array<onerut_parser_exec::Asset, 0>) const override;
private:
double value;
};
class ComplexConstantFunctionFactory : public NaryFunctionFactory<0> {
public:
ComplexConstantFunctionFactory(std::complex<double>);
onerut_parser_exec::Asset make_function_otherwise_make_error(std::array<onerut_parser_exec::Asset, 0>) const override;
private:
std::complex<double> value;
};
}
#endif
| [
"[email protected]"
] | |
722f685da82facb340287135d104584e835ea42a | 70b823c30bb382dd51e2fb9b6f4933c10b551947 | /bullet/src/BulletCollision/NarrowPhaseCollision/btSubSimplexConvexCast.cpp | 0a42049978cad5509365ba9a9f5a47c6e94df856 | [
"WTFPL"
] | permissive | Hi-Angel/Gmod-vphysics | 74945c433ddfd76d2611dfe8aae2817a26712139 | 528790e0931f5a3f1c118032c3332e6253520236 | refs/heads/master | 2021-01-11T15:01:27.961056 | 2017-01-28T15:43:23 | 2017-01-28T15:43:23 | 80,281,651 | 4 | 2 | null | 2017-01-28T11:50:43 | 2017-01-28T11:50:43 | null | UTF-8 | C++ | false | false | 5,077 | cpp | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "btSubSimplexConvexCast.h"
#include "BulletCollision/CollisionShapes/btConvexShape.h"
#include "BulletCollision/CollisionShapes/btMinkowskiSumShape.h"
#include "BulletCollision/NarrowPhaseCollision/btSimplexSolverInterface.h"
#include "btPointCollector.h"
#include "LinearMath/btTransformUtil.h"
btSubsimplexConvexCast::btSubsimplexConvexCast (const btConvexShape* convexA, const btConvexShape* convexB, btSimplexSolverInterface* simplexSolver)
:m_simplexSolver(simplexSolver),
m_convexA(convexA), m_convexB(convexB)
{
}
///Typically the conservative advancement reaches solution in a few iterations, clip it to 32 for degenerate cases.
///See discussion about this here http://continuousphysics.com/Bullet/phpBB2/viewtopic.php?t=565
#ifdef BT_USE_DOUBLE_PRECISION
#define MAX_ITERATIONS 64
#else
#define MAX_ITERATIONS 32
#endif
bool btSubsimplexConvexCast::calcTimeOfImpact(
const btTransform& fromA,
const btTransform& toA,
const btTransform& fromB,
const btTransform& toB,
CastResult& result)
{
m_simplexSolver->reset();
btVector3 linVelA, linVelB;
linVelA = toA.getOrigin()-fromA.getOrigin();
linVelB = toB.getOrigin()-fromB.getOrigin();
btScalar lambda = btScalar(0.);
btTransform interpolatedTransA = fromA;
btTransform interpolatedTransB = fromB;
///take relative motion
btVector3 r = (linVelA-linVelB);
btVector3 v;
btVector3 supVertexA = fromA(m_convexA->localGetSupportingVertex(-r*fromA.getBasis()));
btVector3 supVertexB = fromB(m_convexB->localGetSupportingVertex(r*fromB.getBasis()));
v = supVertexA-supVertexB;
int maxIter = MAX_ITERATIONS;
btVector3 n;
n.setValue(btScalar(0.), btScalar(0.), btScalar(0.));
bool hasResult = false;
btVector3 c;
btScalar lastLambda = lambda;
btScalar dist2 = v.length2();
#ifdef BT_USE_DOUBLE_PRECISION
btScalar epsilon = btScalar(0.0001);
#else
btScalar epsilon = btScalar(0.0001);
#endif //BT_USE_DOUBLE_PRECISION
btVector3 w, p;
btScalar VdotR;
while ( (dist2 > epsilon) && maxIter--)
{
supVertexA = interpolatedTransA(m_convexA->localGetSupportingVertex(-v*interpolatedTransA.getBasis()));
supVertexB = interpolatedTransB(m_convexB->localGetSupportingVertex(v*interpolatedTransB.getBasis()));
w = supVertexA-supVertexB;
btScalar VdotW = v.dot(w);
if (lambda > btScalar(1.0))
{
return false;
}
if ( VdotW > btScalar(0.))
{
VdotR = v.dot(r);
if (VdotR >= -(SIMD_EPSILON*SIMD_EPSILON))
return false;
else
{
lambda = lambda - VdotW / VdotR;
//interpolate to next lambda
// x = s + lambda * r;
interpolatedTransA.getOrigin().setInterpolate3(fromA.getOrigin(), toA.getOrigin(), lambda);
interpolatedTransB.getOrigin().setInterpolate3(fromB.getOrigin(), toB.getOrigin(), lambda);
//m_simplexSolver->reset();
//check next line
w = supVertexA-supVertexB;
lastLambda = lambda;
n = v;
hasResult = true;
}
}
///Just like regular GJK only add the vertex if it isn't already (close) to current vertex, it would lead to divisions by zero and NaN etc.
if (!m_simplexSolver->inSimplex(w))
m_simplexSolver->addVertex( w, supVertexA, supVertexB);
if (m_simplexSolver->closest(v))
{
dist2 = v.length2();
hasResult = true;
//todo: check this normal for validity
//n=v;
//printf("V=%f, %f, %f\n", v[0], v[1], v[2]);
//printf("DIST2=%f\n", dist2);
//printf("numverts = %i\n", m_simplexSolver->numVertices());
} else
{
dist2 = btScalar(0.);
}
}
//int numiter = MAX_ITERATIONS - maxIter;
// printf("number of iterations: %d", numiter);
//don't report a time of impact when moving 'away' from the hitnormal
result.m_fraction = lambda;
if (n.length2() >= (SIMD_EPSILON*SIMD_EPSILON))
result.m_normal = n.normalized();
else
result.m_normal = btVector3(btScalar(0.0), btScalar(0.0), btScalar(0.0));
//don't report time of impact for motion away from the contact normal (or causes minor penetration)
if (result.m_normal.dot(r)>=-result.m_allowedPenetration)
return false;
btVector3 hitA, hitB;
m_simplexSolver->compute_points(hitA, hitB);
result.m_hitPoint=hitB;
return true;
}
| [
"[email protected]"
] | |
e70c46a17185f90d1bea9d76d0b3b1419187facd | cf8ddfc720bf6451c4ef4fa01684327431db1919 | /SDK/ARKSurvivalEvolved_CaveWolf_UpdateTargetZiplineAndLocation_SRV_classes.hpp | 5f29cc357193fe2e8fd944505f2119285bd6f540 | [
"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 | 2,070 | hpp | #pragma once
// ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_CaveWolf_UpdateTargetZiplineAndLocation_SRV_structs.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass CaveWolf_UpdateTargetZiplineAndLocation_SRV.CaveWolf_UpdateTargetZiplineAndLocation_SRV_C
// 0x00D0 (0x0150 - 0x0080)
class UCaveWolf_UpdateTargetZiplineAndLocation_SRV_C : public UBTService_BlueprintBase
{
public:
struct FBlackboardKeySelector TargetLastZiplineLocationKey; // 0x0080(0x0028) (Edit, BlueprintVisible)
struct FBlackboardKeySelector TargetLastZiplineUsedKey; // 0x00A8(0x0028) (Edit, BlueprintVisible)
struct FBlackboardKeySelector CurrentZipline; // 0x00D0(0x0028) (Edit, BlueprintVisible)
struct FBlackboardKeySelector TargetCurrentZipline; // 0x00F8(0x0028) (Edit, BlueprintVisible)
class APrimalBuff* TargetBuff; // 0x0120(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnTemplate, DisableEditOnInstance, IsPlainOldData)
struct FBlackboardKeySelector OrderedMoveToLocationKey; // 0x0128(0x0028) (Edit, BlueprintVisible)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass CaveWolf_UpdateTargetZiplineAndLocation_SRV.CaveWolf_UpdateTargetZiplineAndLocation_SRV_C");
return ptr;
}
void ReceiveActivation(class AActor** OwnerActor);
void ReceiveTick(class AActor** OwnerActor, float* DeltaSeconds);
void ExecuteUbergraph_CaveWolf_UpdateTargetZiplineAndLocation_SRV(int EntryPoint);
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"[email protected]"
] | |
dd4c13a89d5b022147a5e77b1ebd2fd7f3899965 | d0fb46aecc3b69983e7f6244331a81dff42d9595 | /devops-rdc/src/model/DeleteDevopsProjectMembersRequest.cc | 545823fddc2785b19e64d5bac0032c98e13799bf | [
"Apache-2.0"
] | permissive | aliyun/aliyun-openapi-cpp-sdk | 3d8d051d44ad00753a429817dd03957614c0c66a | e862bd03c844bcb7ccaa90571bceaa2802c7f135 | refs/heads/master | 2023-08-29T11:54:00.525102 | 2023-08-29T03:32:48 | 2023-08-29T03:32:48 | 115,379,460 | 104 | 82 | NOASSERTION | 2023-09-14T06:13:33 | 2017-12-26T02:53:27 | C++ | UTF-8 | C++ | false | false | 1,839 | cc | /*
* Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/devops-rdc/model/DeleteDevopsProjectMembersRequest.h>
using AlibabaCloud::Devops_rdc::Model::DeleteDevopsProjectMembersRequest;
DeleteDevopsProjectMembersRequest::DeleteDevopsProjectMembersRequest()
: RpcServiceRequest("devops-rdc", "2020-03-03", "DeleteDevopsProjectMembers") {
setMethod(HttpRequest::Method::Post);
}
DeleteDevopsProjectMembersRequest::~DeleteDevopsProjectMembersRequest() {}
std::string DeleteDevopsProjectMembersRequest::getUserIds() const {
return userIds_;
}
void DeleteDevopsProjectMembersRequest::setUserIds(const std::string &userIds) {
userIds_ = userIds;
setBodyParameter(std::string("UserIds"), userIds);
}
std::string DeleteDevopsProjectMembersRequest::getProjectId() const {
return projectId_;
}
void DeleteDevopsProjectMembersRequest::setProjectId(const std::string &projectId) {
projectId_ = projectId;
setBodyParameter(std::string("ProjectId"), projectId);
}
std::string DeleteDevopsProjectMembersRequest::getOrgId() const {
return orgId_;
}
void DeleteDevopsProjectMembersRequest::setOrgId(const std::string &orgId) {
orgId_ = orgId;
setBodyParameter(std::string("OrgId"), orgId);
}
| [
"[email protected]"
] | |
93e74bae39803f6bbab02794f6e1a7fe58f88878 | 631a61d0e773801efc122053fe01de8a67f87ad5 | /NSUPS Bootcamp S8 Weekly Contest 3(Bigmod, Prime Factorization, STL - 1)/B_Easy_Queue.cpp | 198e1c46b410309b2dc4ea55f2294fc8e6f09129 | [] | no_license | FahimMuntashir/NSU-PS | 8137ec025b5e042cf2285c66a66ea5333fe01a9a | ab57f36d62fda528cefb4b6ce94343ebb9198d78 | refs/heads/master | 2023-02-04T13:06:56.824319 | 2020-12-23T09:05:02 | 2020-12-23T09:05:02 | 304,408,151 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 676 | cpp | #include <bits/stdc++.h>
#define fastio ios_base::sync_with_stdio(false), cin.tie(NULL)
#define endl "\n"
using namespace std;
queue<int> que;
int main()
{
fastio;
int t;
cin >> t;
while (t--)
{
int n;
cin >> n;
if (n == 1)
{
cin >> n;
que.push(n);
}
else if (n == 2)
{
if (que.empty() == 0)
{
que.pop();
}
}
else
{
if (que.empty() == 1)
{
cout << "Empty!" << endl;
}
else
cout << que.front() << endl;
}
}
} | [
"[email protected]"
] | |
59fc280a5938e9c64aec275c65dda8fcc9a3aa66 | 3cf9e141cc8fee9d490224741297d3eca3f5feff | /TypeShield Source/old/dyninst-pass/instrumentation.h | d4a2ae0dfedf8f49a0126fe3fb8363e92fc48c43 | [] | no_license | TeamVault/tauCFI | e0ac60b8106fc1bb9874adc515fc01672b775123 | e677d8cc7acd0b1dd0ac0212ff8362fcd4178c10 | refs/heads/master | 2023-05-30T20:57:13.450360 | 2021-06-14T09:10:24 | 2021-06-14T09:10:24 | 154,563,655 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,769 | h | #ifndef __INSTRUMENTATION_H
#define __INSTRUMENTATION_H
#include <BPatch.h>
#include <BPatch_basicBlock.h>
#include <BPatch_flowGraph.h>
#include <BPatch_function.h>
#include <PatchCFG.h>
#include "ca_defines.h"
#include "ast/parsing/function_borders.h"
#include "ast/ast.h"
#include "logging.h"
#include "utils.h"
template <typename instr_op_t, typename... arg_ts>
void instrument_function_basicBlocks_unordered(BPatch_function *function,
instr_op_t instr_op, arg_ts &&... args)
{
std::set<BPatch_basicBlock *> blocks;
BPatch_flowGraph *cfg = function->getCFG();
cfg->getAllBasicBlocks(blocks);
function_borders::apply(function, blocks);
for (auto block : blocks)
{
// Instrument BasicBlock
LOG_TRACE(LOG_FILTER_INSTRUMENTATION, "Processing basic block %lx",
block->getStartAddress());
instr_op(block, std::forward<arg_ts>(args)...);
}
}
template <typename instr_op_t, typename... arg_ts>
void instrument_ast_basicBlocks_unordered(ast::ast const &ast, instr_op_t instr_op,
arg_ts &&... args)
{
util::for_each(ast.get_functions(), [&instr_op,
&args...](ast::function const &ast_function) {
LOG_TRACE(LOG_FILTER_INSTRUMENTATION, "Processing function %s",
ast_function.get_name().c_str());
instrument_function_basicBlocks_unordered(ast_function.get_function(), instr_op,
std::forward<arg_ts>(args)...);
});
}
template <typename instr_op_t, typename... arg_ts>
void instrument_basicBlock_instructions(BPatch_basicBlock *block, instr_op_t instr_op,
arg_ts &&... args)
{
Dyninst::PatchAPI::PatchBlock::Insns insns;
auto patch_block = Dyninst::PatchAPI::convert(block);
patch_block->getInsns(insns);
for (auto &instruction : insns)
{
// Instrument Instruction
auto address = reinterpret_cast<uint64_t>(instruction.first);
LOG_TRACE(LOG_FILTER_INSTRUMENTATION, "Processing instruction %lx", address);
instr_op(instruction, std::forward<arg_ts>(args)...);
}
}
template <typename instr_op_t, typename decoder_t, typename... arg_ts>
void instrument_basicBlock_decoded(BPatch_basicBlock *block, decoder_t *decoder,
instr_op_t instr_op, arg_ts &&... args)
{
Dyninst::PatchAPI::PatchBlock::Insns insns;
auto patch_block = Dyninst::PatchAPI::convert(block);
patch_block->getInsns(insns);
for (auto &instruction : insns)
{
auto const address = reinterpret_cast<uint64_t>(instruction.first);
Dyninst::InstructionAPI::Instruction::Ptr instruction_ptr = instruction.second;
LOG_TRACE(LOG_FILTER_INSTRUMENTATION, "Processing instruction %lx", address);
if (!decoder->decode(address, instruction_ptr))
{
LOG_ERROR(LOG_FILTER_INSTRUMENTATION, "Could not decode instruction %lx",
address);
}
else
{
instr_op(decoder, std::forward<arg_ts>(args)...);
}
}
}
template <typename instr_op_t, typename decoder_t, typename... arg_ts>
void instrument_function_decoded_unordered(BPatch_function *function, decoder_t *decoder,
instr_op_t instr_op, arg_ts &&... args)
{
instrument_function_basicBlocks_unordered(
function, [&instr_op, &decoder, &args...](BPatch_basicBlock *block) {
instrument_basicBlock_decoded(block, decoder, instr_op,
std::forward<arg_ts>(args)...);
});
}
#endif /* __INSTRUMENTATION_H */
| [
"[email protected]"
] | |
d39583877ae016510f564b766dcf9aca14d7436c | 706673179ed294468d382daa36e6a12a0bbfc43a | /Sorting/UsingSTL.cpp | 106185ab853080d456220df6915f15c8e8f1d192 | [] | no_license | Aj-108/LearningDataStructuresC- | 73ba4e75cb6fa7846c892caf76e35c7f7501f058 | 79347fa6bef3ff1a0dea3d89b9be836cb0c75ef3 | refs/heads/main | 2023-07-23T20:04:47.993923 | 2021-09-03T18:19:25 | 2021-09-03T18:19:25 | 392,215,009 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 363 | cpp | #include<bits/stdc++.h>
using namespace std ;
int main(){
int arr[] = {1,7,3,6,23,7,3,5,35,2,1,3};
int n = sizeof(arr) / sizeof(arr[0]);
sort(arr,arr+n) ; // ascending orer
for(auto i : arr) cout << i <<" ";
sort(arr,arr+n,greater<int>()) ; // Descending order
cout << endl ;
for(auto i : arr) cout << i ;
return 0 ;
} | [
"[email protected]"
] | |
35c0f8c36cbb5b5b73f02dfb70e009a6e6d537d8 | 958aeffcc61b420fbb9f42e4559e534cdb8eb505 | /src/graphic/Shader.cpp | a0da446bddc4a894e445f04499e7a3c56480c628 | [] | no_license | wnsrl7659/Project-ShootingBoard | df04f9a9183446d2f0979cafe6ed09a6232785db | 5d0cbeb217bb964dd97ab2d2154436f91caf4ae8 | refs/heads/master | 2023-07-17T13:21:26.295627 | 2021-09-05T06:17:07 | 2021-09-05T06:17:07 | 403,212,671 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,950 | cpp | #include <iostream>
#include <string>
#include "Shader.h"
GLuint ShaderArray[Shader_Last];
Location location[Shader_Last];
char* StringReadFromFile(const char* filename)
{
FILE* fp;
long int FileSize;
char* string;
fopen_s(&fp, filename, "rb");
if (!fp)
{
return (char*)"error";
}
fseek(fp, 0, SEEK_END);
FileSize = ftell(fp);
fseek(fp, 0, SEEK_SET);
string = new char[FileSize + 1];
if (fread(string, FileSize, 1, fp) != 1)
{
fclose(fp);
delete[] string;
return (char*)"error";
}
fclose(fp);
string[FileSize] = 0;
return string;
}
static char* ShaderReadFromFile(const char * filename)
{
return StringReadFromFile(filename);
}
static unsigned int ShaderCompile(GLenum shaderType, const char* filename)
{
//Get the shader code from a file
const char* shaderCode = ShaderReadFromFile(filename);
if (strcmp(shaderCode, "error") == 0)
{
std::cout << "Shader has error reading file: " << filename << std::endl;
}
//create the shader from the code
GLuint shader = glCreateShader(shaderType);
glShaderSource(shader, 1, &shaderCode, NULL);
glCompileShader(shader);
//delete the now pointless code
delete[] shaderCode;
//ERROR HANDLING
GLint errorResult;
glGetShaderiv(shader, GL_COMPILE_STATUS, &errorResult);
if (errorResult == GL_FALSE)
{
GLint size;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &size);
GLchar *message = new GLchar[size + 1];
glGetShaderInfoLog(shader, size, &size, message);
std::cout << filename << ": " << std::endl << message << std::endl;
delete[] message;
glDeleteShader(shader);
return 0;
}
return shader;
}
GLuint ShaderCreate(const char* vertexFile, const char* fragmentFile)
{
GLuint program = glCreateProgram();
GLuint vertShader = ShaderCompile(GL_VERTEX_SHADER, vertexFile);
GLuint fragShader = ShaderCompile(GL_FRAGMENT_SHADER, fragmentFile);
glAttachShader(program, vertShader);
glAttachShader(program, fragShader);
glLinkProgram(program);
glValidateProgram(program);
glDeleteShader(vertShader);
glDeleteShader(fragShader);
return program;
}
void ShaderInit()
{
ShaderArray[Shader_BasicColor] = ShaderCreate("./data/shaders/Vert_Default.txt", "./data/shaders/Frag_Col.txt");
ShaderArray[Shader_BasicTexture] = ShaderCreate("./data/shaders/Vert_Default.txt", "./data/shaders/Frag_Tex.txt");
SetAddress();
}
void ShaderShutdown()
{
for (int i = Shader_StartOfList + 1; i < Shader_Last; i++)
glDeleteProgram(ShaderArray[i]);
}
void SetAddress()
{
for(int i = 0; i < Shader_Last; i ++)
{
location[i].uColor = glGetUniformLocation(ShaderArray[i], "uColor");
location[i].utransform = glGetUniformLocation(ShaderArray[i], "transform");
location[i].uview = glGetUniformLocation(ShaderArray[i], "view");
location[i].uprojection = glGetUniformLocation(ShaderArray[i], "projection");
location[i].image_alpha = glGetUniformLocation(ShaderArray[i], "image_alpha");
}
}
| [
"[email protected]"
] | |
5f1f754add7e1d97ef433d3fbabc8fc65c6b1522 | 9da899bf6541c6a0514219377fea97df9907f0ae | /Runtime/CoreUObject/Private/Tests/ObjectHandleTest.cpp | 771f6b50bbcf18b02241a163da375f513687f21e | [] | no_license | peichangliang123/UE4 | 1aa4df3418c077dd8f82439ecc808cd2e6de4551 | 20e38f42edc251ee96905ed8e96e1be667bc14a5 | refs/heads/master | 2023-08-17T11:31:53.304431 | 2021-09-15T00:31:03 | 2021-09-15T00:31:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,374 | cpp | // Copyright Epic Games, Inc. All Rights Reserved.
#include "UObject/ObjectHandle.h"
#include "HAL/PlatformProperties.h"
#include "ObjectRefTrackingTestBase.h"
#include "IO/IoDispatcher.h"
static_assert(sizeof(FObjectHandle) == sizeof(void*), "FObjectHandle type must always compile to something equivalent to a pointer size.");
#if WITH_DEV_AUTOMATION_TESTS
class FObjectHandleTestBase : public FObjectRefTrackingTestBase
{
public:
FObjectHandleTestBase(const FString& InName, const bool bInComplexTask)
: FObjectRefTrackingTestBase(InName, bInComplexTask)
{
}
protected:
UObject* ConstructAndResolveHandle(const ANSICHAR* PackageName, const ANSICHAR* ObjectName, const ANSICHAR* ClassPackageName = nullptr, const ANSICHAR* ClassName = nullptr)
{
FObjectRef TargetRef{FName(PackageName), FName(ClassPackageName), FName(ClassName), FObjectPathId(ObjectName)};
if (!TestFalse(TEXT("Reference to target is null"), IsObjectRefNull(TargetRef)))
{
return nullptr;
}
FObjectHandle TargetHandle = MakeObjectHandle(TargetRef);
#if UE_WITH_OBJECT_HANDLE_LATE_RESOLVE
// Late resolved handles cannot be null or resolved at this point
if (!TestFalse(TEXT("Handle to target is null"), IsObjectHandleNull(TargetHandle)))
{
return nullptr;
}
if (!TestFalse(TEXT("Handle to target is resolved"), IsObjectHandleResolved(TargetHandle)))
{
return nullptr;
}
#else
// Immediately resolved handles may be null (if the target is invalid) and must be resolved at this point
if (!TestTrue(TEXT("Handle to target is not resolved"), IsObjectHandleResolved(TargetHandle)))
{
return nullptr;
}
#endif
return ResolveObjectHandle(TargetHandle);
}
bool TestResolvableNonNull(const ANSICHAR* PackageName, const ANSICHAR* ObjectName, const ANSICHAR* ClassPackageName = nullptr, const ANSICHAR* ClassName = nullptr, bool bExpectSubRefReads = false)
{
FSnapshotObjectRefMetrics ObjectRefMetrics(*this);
UObject* ResolvedObject = ConstructAndResolveHandle(PackageName, ObjectName, ClassPackageName, ClassName);
ObjectRefMetrics.TestNumResolves(TEXT("NumResolves should be incremented by one after a resolve attempt"), 1);
ObjectRefMetrics.TestNumReads(TEXT("NumReads should be incremented by one after a resolve attempt"), 1, bExpectSubRefReads /*bAllowAdditionalReads*/);
if (!ResolvedObject)
{
AddError(FString::Printf(TEXT("Expected '%s.%s' to resolve to non null."), ANSI_TO_TCHAR(PackageName), ANSI_TO_TCHAR(ObjectName)), 1);
return false;
}
ObjectRefMetrics.TestNumFailedResolves(TEXT("NumFailedResolves should not change after a successful resolve attempt"), 0);
return true;
}
bool TestResolveFailure(const ANSICHAR* PackageName, const ANSICHAR* ObjectName, const ANSICHAR* ClassPackageName = nullptr, const ANSICHAR* ClassName = nullptr)
{
FSnapshotObjectRefMetrics ObjectRefMetrics(*this);
UObject* ResolvedObject = ConstructAndResolveHandle(PackageName, ObjectName, ClassPackageName, ClassName);
ObjectRefMetrics.TestNumResolves(TEXT("NumResolves should be incremented by one after a resolve attempt"), 1);
ObjectRefMetrics.TestNumReads(TEXT("NumReads should be incremented by one after a resolve attempt"), 1);
if (ResolvedObject)
{
AddError(FString::Printf(TEXT("Expected '%s.%s' to resolve to null."), ANSI_TO_TCHAR(PackageName), ANSI_TO_TCHAR(ObjectName)), 1);
return false;
}
ObjectRefMetrics.TestNumFailedResolves(TEXT("NumFailedResolves should be incremented by one after a failed resolve attempt"), 1);
return true;
}
};
#define TEST_NAME_ROOT TEXT("System.CoreUObject.ObjectHandle")
constexpr const uint32 ObjectHandleTestFlags = EAutomationTestFlags::ApplicationContextMask | EAutomationTestFlags::EngineFilter;
IMPLEMENT_CUSTOM_SIMPLE_AUTOMATION_TEST(FObjectHandleTestNullBehavior, FObjectHandleTestBase, TEST_NAME_ROOT TEXT(".NullBehavior"), ObjectHandleTestFlags)
bool FObjectHandleTestNullBehavior::RunTest(const FString& Parameters)
{
FObjectHandle TargetHandle = MakeObjectHandle(nullptr);
TestTrue(TEXT("Handle to target is null"), IsObjectHandleNull(TargetHandle));
TestTrue(TEXT("Handle to target is resolved"), IsObjectHandleResolved(TargetHandle));
FSnapshotObjectRefMetrics ObjectRefMetrics(*this);
UObject* ResolvedObject = ResolveObjectHandle(TargetHandle);
TestEqual(TEXT("Resolved object is equal to original object"), (UObject*)nullptr, ResolvedObject);
ObjectRefMetrics.TestNumFailedResolves(TEXT("NumFailedResolves should not change after a resolve attempt on a null handle"), 0);
ObjectRefMetrics.TestNumResolves(TEXT("NumResolves should not change after a resolve attempt on a null handle"), 0);
ObjectRefMetrics.TestNumReads(TEXT("NumReads should be incremented by one after a resolve attempt on a null handle"), 1);
return true;
}
IMPLEMENT_CUSTOM_SIMPLE_AUTOMATION_TEST(FObjectHandleTestPointerBehavior, FObjectHandleTestBase, TEST_NAME_ROOT TEXT(".PointerBehavior"), ObjectHandleTestFlags)
bool FObjectHandleTestPointerBehavior::RunTest(const FString& Parameters)
{
FObjectHandle TargetHandle = MakeObjectHandle((UObject*)0x0042);
TestFalse(TEXT("Handle to target is null"), IsObjectHandleNull(TargetHandle));
TestTrue(TEXT("Handle to target is resolved"), IsObjectHandleResolved(TargetHandle));
FSnapshotObjectRefMetrics ObjectRefMetrics(*this);
UObject* ResolvedObject = ResolveObjectHandle(TargetHandle);
TestEqual(TEXT("Resolved object is equal to original object"), (UObject*)0x0042, ResolvedObject);
ObjectRefMetrics.TestNumResolves(TEXT("NumResolves should not change after a resolve attempt on a pointer handle"), 0);
ObjectRefMetrics.TestNumFailedResolves(TEXT("NumFailedResolves should not change after a resolve attempt on a pointer handle"), 0);
ObjectRefMetrics.TestNumReads(TEXT("NumReads should be incremented by one after a resolve attempt on a pointer handle"),1);
return true;
}
IMPLEMENT_CUSTOM_SIMPLE_AUTOMATION_TEST(FObjectHandleTestResolveEngineContentTarget, FObjectHandleTestBase, TEST_NAME_ROOT TEXT(".ResolveEngineContentTarget"), ObjectHandleTestFlags)
bool FObjectHandleTestResolveEngineContentTarget::RunTest(const FString& Parameters)
{
// Confirm we successfully resolve a correct reference to engine content
TestResolvableNonNull("/Engine/EngineResources/DefaultTexture", "DefaultTexture");
// @TODO: OBJPTR: These assets aren't in a standard cook of EngineTest, so avoid testing them when using cooked content. Should look for other assets to use instead.
if (!FPlatformProperties::RequiresCookedData())
{
// Confirm we successfully resolve a correct reference to a subobject in engine content
TestResolvableNonNull("/Engine/FunctionalTesting/Blueprints/AITesting_MoveGoal", "AITesting_MoveGoal.EventGraph.K2Node_VariableGet_142", nullptr, nullptr, true);
// Attempt to load something that uses a User Defined Enum
TestResolvableNonNull("/Engine/ArtTools/RenderToTexture/Macros/RenderToTextureMacros", "RenderToTextureMacros:Array to HLSL Float Array.K2Node_Select_1", nullptr, nullptr, true);
}
return true;
}
IMPLEMENT_CUSTOM_SIMPLE_AUTOMATION_TEST(FObjectHandleTestFailResolveInvalidTarget, FObjectHandleTestBase, TEST_NAME_ROOT TEXT(".FailResolveInvalidTarget"), ObjectHandleTestFlags)
bool FObjectHandleTestFailResolveInvalidTarget::RunTest(const FString& Parameters)
{
if (FPlatformProperties::RequiresCookedData())
{
if (FIoDispatcher::IsInitialized())
{
AddExpectedError(TEXT("SkipPackage"));
}
else
{
AddExpectedError(TEXT("Couldn't find file for package"));
AddExpectedError(TEXT("Found 0 dependent packages..."));
}
}
// Confirm we don't successfully resolve an incorrect reference to engine content
TestResolveFailure("/Engine/EngineResources/NonExistentPackageName_0", "DefaultTexture");
TestResolveFailure("/Engine/EngineResources/DefaultTexture", "NonExistentObject_0");
return true;
}
IMPLEMENT_CUSTOM_SIMPLE_AUTOMATION_TEST(FObjectHandleTestResolveScriptTarget, FObjectHandleTestBase, TEST_NAME_ROOT TEXT(".ResolveScriptTarget"), ObjectHandleTestFlags)
bool FObjectHandleTestResolveScriptTarget::RunTest(const FString& Parameters)
{
// Confirm we successfully resolve a correct reference to engine content
TestResolvableNonNull("/Script/Engine", "Default__Actor");
TestResolvableNonNull("/Script/Engine", "DefaultPawn");
return true;
}
#undef TEST_NAME_ROOT
#endif // WITH_DEV_AUTOMATION_TESTS
| [
"[email protected]"
] | |
c56e5d8838a5907e6b21f405098716a4479e2d3b | 0897560a7ebde50481f950c9a441e2fc3c34ba04 | /10.0.15042.0/winrt/Windows.Devices.Perception.Provider.h | f4736d65594b721e11dc23a01e2e5df895494503 | [
"LicenseRef-scancode-generic-cla",
"MIT"
] | permissive | dngoins/cppwinrt | 338f01171153cbca14a723217129ed36b6ce2c9d | 0bb7a57392673f793ba99978738490100a9684ec | refs/heads/master | 2021-01-19T19:14:59.993078 | 2017-03-01T22:14:18 | 2017-03-01T22:14:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 63,450 | h | // C++ for the Windows Runtime v1.0.private
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
#include "base.h"
WINRT_WARNING_PUSH
#include "internal/Windows.Foundation.Collections.3.h"
#include "internal/Windows.Foundation.3.h"
#include "internal/Windows.Graphics.Imaging.3.h"
#include "internal/Windows.Media.3.h"
#include "internal/Windows.Devices.Perception.3.h"
#include "internal/Windows.Devices.Perception.Provider.3.h"
#include "Windows.Devices.Perception.h"
#include "Windows.Foundation.h"
WINRT_EXPORT namespace winrt {
namespace Windows::Devices::Perception::Provider {
template <typename L> PerceptionStartFaceAuthenticationHandler::PerceptionStartFaceAuthenticationHandler(L lambda) :
PerceptionStartFaceAuthenticationHandler(impl::make_delegate<impl_PerceptionStartFaceAuthenticationHandler<L>, PerceptionStartFaceAuthenticationHandler>(std::forward<L>(lambda)))
{}
template <typename F> PerceptionStartFaceAuthenticationHandler::PerceptionStartFaceAuthenticationHandler(F * function) :
PerceptionStartFaceAuthenticationHandler([=](auto && ... args) { return function(args ...); })
{}
template <typename O, typename M> PerceptionStartFaceAuthenticationHandler::PerceptionStartFaceAuthenticationHandler(O * object, M method) :
PerceptionStartFaceAuthenticationHandler([=](auto && ... args) { return ((*object).*(method))(args ...); })
{}
inline bool PerceptionStartFaceAuthenticationHandler::operator()(const Windows::Devices::Perception::Provider::PerceptionFaceAuthenticationGroup & sender) const
{
bool result {};
check_hresult((*(abi<PerceptionStartFaceAuthenticationHandler> **)this)->abi_Invoke(get_abi(sender), &result));
return result;
}
template <typename L> PerceptionStopFaceAuthenticationHandler::PerceptionStopFaceAuthenticationHandler(L lambda) :
PerceptionStopFaceAuthenticationHandler(impl::make_delegate<impl_PerceptionStopFaceAuthenticationHandler<L>, PerceptionStopFaceAuthenticationHandler>(std::forward<L>(lambda)))
{}
template <typename F> PerceptionStopFaceAuthenticationHandler::PerceptionStopFaceAuthenticationHandler(F * function) :
PerceptionStopFaceAuthenticationHandler([=](auto && ... args) { function(args ...); })
{}
template <typename O, typename M> PerceptionStopFaceAuthenticationHandler::PerceptionStopFaceAuthenticationHandler(O * object, M method) :
PerceptionStopFaceAuthenticationHandler([=](auto && ... args) { ((*object).*(method))(args ...); })
{}
inline void PerceptionStopFaceAuthenticationHandler::operator()(const Windows::Devices::Perception::Provider::PerceptionFaceAuthenticationGroup & sender) const
{
check_hresult((*(abi<PerceptionStopFaceAuthenticationHandler> **)this)->abi_Invoke(get_abi(sender)));
}
}
namespace impl {
template <typename D>
struct produce<D, Windows::Devices::Perception::Provider::IKnownPerceptionFrameKindStatics> : produce_base<D, Windows::Devices::Perception::Provider::IKnownPerceptionFrameKindStatics>
{
HRESULT __stdcall get_Color(impl::abi_arg_out<hstring> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().Color());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall get_Depth(impl::abi_arg_out<hstring> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().Depth());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall get_Infrared(impl::abi_arg_out<hstring> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().Infrared());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Devices::Perception::Provider::IPerceptionControlGroup> : produce_base<D, Windows::Devices::Perception::Provider::IPerceptionControlGroup>
{
HRESULT __stdcall get_FrameProviderIds(impl::abi_arg_out<Windows::Foundation::Collections::IVectorView<hstring>> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().FrameProviderIds());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Devices::Perception::Provider::IPerceptionControlGroupFactory> : produce_base<D, Windows::Devices::Perception::Provider::IPerceptionControlGroupFactory>
{
HRESULT __stdcall abi_Create(impl::abi_arg_in<Windows::Foundation::Collections::IIterable<hstring>> ids, impl::abi_arg_out<Windows::Devices::Perception::Provider::IPerceptionControlGroup> result) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*result = detach_abi(this->shim().Create(*reinterpret_cast<const Windows::Foundation::Collections::IIterable<hstring> *>(&ids)));
return S_OK;
}
catch (...)
{
*result = nullptr;
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Devices::Perception::Provider::IPerceptionCorrelation> : produce_base<D, Windows::Devices::Perception::Provider::IPerceptionCorrelation>
{
HRESULT __stdcall get_TargetId(impl::abi_arg_out<hstring> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().TargetId());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall get_Position(impl::abi_arg_out<Windows::Foundation::Numerics::float3> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().Position());
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall get_Orientation(impl::abi_arg_out<Windows::Foundation::Numerics::quaternion> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().Orientation());
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Devices::Perception::Provider::IPerceptionCorrelationFactory> : produce_base<D, Windows::Devices::Perception::Provider::IPerceptionCorrelationFactory>
{
HRESULT __stdcall abi_Create(impl::abi_arg_in<hstring> targetId, impl::abi_arg_in<Windows::Foundation::Numerics::float3> position, impl::abi_arg_in<Windows::Foundation::Numerics::quaternion> orientation, impl::abi_arg_out<Windows::Devices::Perception::Provider::IPerceptionCorrelation> result) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*result = detach_abi(this->shim().Create(*reinterpret_cast<const hstring *>(&targetId), *reinterpret_cast<const Windows::Foundation::Numerics::float3 *>(&position), *reinterpret_cast<const Windows::Foundation::Numerics::quaternion *>(&orientation)));
return S_OK;
}
catch (...)
{
*result = nullptr;
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Devices::Perception::Provider::IPerceptionCorrelationGroup> : produce_base<D, Windows::Devices::Perception::Provider::IPerceptionCorrelationGroup>
{
HRESULT __stdcall get_RelativeLocations(impl::abi_arg_out<Windows::Foundation::Collections::IVectorView<Windows::Devices::Perception::Provider::PerceptionCorrelation>> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().RelativeLocations());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Devices::Perception::Provider::IPerceptionCorrelationGroupFactory> : produce_base<D, Windows::Devices::Perception::Provider::IPerceptionCorrelationGroupFactory>
{
HRESULT __stdcall abi_Create(impl::abi_arg_in<Windows::Foundation::Collections::IIterable<Windows::Devices::Perception::Provider::PerceptionCorrelation>> relativeLocations, impl::abi_arg_out<Windows::Devices::Perception::Provider::IPerceptionCorrelationGroup> result) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*result = detach_abi(this->shim().Create(*reinterpret_cast<const Windows::Foundation::Collections::IIterable<Windows::Devices::Perception::Provider::PerceptionCorrelation> *>(&relativeLocations)));
return S_OK;
}
catch (...)
{
*result = nullptr;
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Devices::Perception::Provider::IPerceptionFaceAuthenticationGroup> : produce_base<D, Windows::Devices::Perception::Provider::IPerceptionFaceAuthenticationGroup>
{
HRESULT __stdcall get_FrameProviderIds(impl::abi_arg_out<Windows::Foundation::Collections::IVectorView<hstring>> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().FrameProviderIds());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Devices::Perception::Provider::IPerceptionFaceAuthenticationGroupFactory> : produce_base<D, Windows::Devices::Perception::Provider::IPerceptionFaceAuthenticationGroupFactory>
{
HRESULT __stdcall abi_Create(impl::abi_arg_in<Windows::Foundation::Collections::IIterable<hstring>> ids, impl::abi_arg_in<Windows::Devices::Perception::Provider::PerceptionStartFaceAuthenticationHandler> startHandler, impl::abi_arg_in<Windows::Devices::Perception::Provider::PerceptionStopFaceAuthenticationHandler> stopHandler, impl::abi_arg_out<Windows::Devices::Perception::Provider::IPerceptionFaceAuthenticationGroup> result) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*result = detach_abi(this->shim().Create(*reinterpret_cast<const Windows::Foundation::Collections::IIterable<hstring> *>(&ids), *reinterpret_cast<const Windows::Devices::Perception::Provider::PerceptionStartFaceAuthenticationHandler *>(&startHandler), *reinterpret_cast<const Windows::Devices::Perception::Provider::PerceptionStopFaceAuthenticationHandler *>(&stopHandler)));
return S_OK;
}
catch (...)
{
*result = nullptr;
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Devices::Perception::Provider::IPerceptionFrame> : produce_base<D, Windows::Devices::Perception::Provider::IPerceptionFrame>
{
HRESULT __stdcall get_RelativeTime(impl::abi_arg_out<Windows::Foundation::TimeSpan> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().RelativeTime());
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall put_RelativeTime(impl::abi_arg_in<Windows::Foundation::TimeSpan> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().RelativeTime(*reinterpret_cast<const Windows::Foundation::TimeSpan *>(&value));
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall get_Properties(impl::abi_arg_out<Windows::Foundation::Collections::IPropertySet> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().Properties());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall get_FrameData(impl::abi_arg_out<Windows::Foundation::IMemoryBuffer> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().FrameData());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Devices::Perception::Provider::IPerceptionFrameProvider> : produce_base<D, Windows::Devices::Perception::Provider::IPerceptionFrameProvider>
{
HRESULT __stdcall get_FrameProviderInfo(impl::abi_arg_out<Windows::Devices::Perception::Provider::IPerceptionFrameProviderInfo> result) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*result = detach_abi(this->shim().FrameProviderInfo());
return S_OK;
}
catch (...)
{
*result = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall get_Available(bool * value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().Available());
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall get_Properties(impl::abi_arg_out<Windows::Foundation::Collections::IPropertySet> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().Properties());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall abi_Start() noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().Start();
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall abi_Stop() noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().Stop();
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall abi_SetProperty(impl::abi_arg_in<Windows::Devices::Perception::Provider::IPerceptionPropertyChangeRequest> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().SetProperty(*reinterpret_cast<const Windows::Devices::Perception::Provider::PerceptionPropertyChangeRequest *>(&value));
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Devices::Perception::Provider::IPerceptionFrameProviderInfo> : produce_base<D, Windows::Devices::Perception::Provider::IPerceptionFrameProviderInfo>
{
HRESULT __stdcall get_Id(impl::abi_arg_out<hstring> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().Id());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall put_Id(impl::abi_arg_in<hstring> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().Id(*reinterpret_cast<const hstring *>(&value));
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall get_DisplayName(impl::abi_arg_out<hstring> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().DisplayName());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall put_DisplayName(impl::abi_arg_in<hstring> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().DisplayName(*reinterpret_cast<const hstring *>(&value));
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall get_DeviceKind(impl::abi_arg_out<hstring> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().DeviceKind());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall put_DeviceKind(impl::abi_arg_in<hstring> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().DeviceKind(*reinterpret_cast<const hstring *>(&value));
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall get_FrameKind(impl::abi_arg_out<hstring> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().FrameKind());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall put_FrameKind(impl::abi_arg_in<hstring> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().FrameKind(*reinterpret_cast<const hstring *>(&value));
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall get_Hidden(bool * value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().Hidden());
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall put_Hidden(bool value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().Hidden(value);
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Devices::Perception::Provider::IPerceptionFrameProviderManager> : produce_base<D, Windows::Devices::Perception::Provider::IPerceptionFrameProviderManager>
{
HRESULT __stdcall abi_GetFrameProvider(impl::abi_arg_in<Windows::Devices::Perception::Provider::IPerceptionFrameProviderInfo> frameProviderInfo, impl::abi_arg_out<Windows::Devices::Perception::Provider::IPerceptionFrameProvider> result) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*result = detach_abi(this->shim().GetFrameProvider(*reinterpret_cast<const Windows::Devices::Perception::Provider::PerceptionFrameProviderInfo *>(&frameProviderInfo)));
return S_OK;
}
catch (...)
{
*result = nullptr;
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Devices::Perception::Provider::IPerceptionFrameProviderManagerServiceStatics> : produce_base<D, Windows::Devices::Perception::Provider::IPerceptionFrameProviderManagerServiceStatics>
{
HRESULT __stdcall abi_RegisterFrameProviderInfo(impl::abi_arg_in<Windows::Devices::Perception::Provider::IPerceptionFrameProviderManager> manager, impl::abi_arg_in<Windows::Devices::Perception::Provider::IPerceptionFrameProviderInfo> frameProviderInfo) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().RegisterFrameProviderInfo(*reinterpret_cast<const Windows::Devices::Perception::Provider::IPerceptionFrameProviderManager *>(&manager), *reinterpret_cast<const Windows::Devices::Perception::Provider::PerceptionFrameProviderInfo *>(&frameProviderInfo));
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall abi_UnregisterFrameProviderInfo(impl::abi_arg_in<Windows::Devices::Perception::Provider::IPerceptionFrameProviderManager> manager, impl::abi_arg_in<Windows::Devices::Perception::Provider::IPerceptionFrameProviderInfo> frameProviderInfo) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().UnregisterFrameProviderInfo(*reinterpret_cast<const Windows::Devices::Perception::Provider::IPerceptionFrameProviderManager *>(&manager), *reinterpret_cast<const Windows::Devices::Perception::Provider::PerceptionFrameProviderInfo *>(&frameProviderInfo));
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall abi_RegisterFaceAuthenticationGroup(impl::abi_arg_in<Windows::Devices::Perception::Provider::IPerceptionFrameProviderManager> manager, impl::abi_arg_in<Windows::Devices::Perception::Provider::IPerceptionFaceAuthenticationGroup> faceAuthenticationGroup) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().RegisterFaceAuthenticationGroup(*reinterpret_cast<const Windows::Devices::Perception::Provider::IPerceptionFrameProviderManager *>(&manager), *reinterpret_cast<const Windows::Devices::Perception::Provider::PerceptionFaceAuthenticationGroup *>(&faceAuthenticationGroup));
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall abi_UnregisterFaceAuthenticationGroup(impl::abi_arg_in<Windows::Devices::Perception::Provider::IPerceptionFrameProviderManager> manager, impl::abi_arg_in<Windows::Devices::Perception::Provider::IPerceptionFaceAuthenticationGroup> faceAuthenticationGroup) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().UnregisterFaceAuthenticationGroup(*reinterpret_cast<const Windows::Devices::Perception::Provider::IPerceptionFrameProviderManager *>(&manager), *reinterpret_cast<const Windows::Devices::Perception::Provider::PerceptionFaceAuthenticationGroup *>(&faceAuthenticationGroup));
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall abi_RegisterControlGroup(impl::abi_arg_in<Windows::Devices::Perception::Provider::IPerceptionFrameProviderManager> manager, impl::abi_arg_in<Windows::Devices::Perception::Provider::IPerceptionControlGroup> controlGroup) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().RegisterControlGroup(*reinterpret_cast<const Windows::Devices::Perception::Provider::IPerceptionFrameProviderManager *>(&manager), *reinterpret_cast<const Windows::Devices::Perception::Provider::PerceptionControlGroup *>(&controlGroup));
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall abi_UnregisterControlGroup(impl::abi_arg_in<Windows::Devices::Perception::Provider::IPerceptionFrameProviderManager> manager, impl::abi_arg_in<Windows::Devices::Perception::Provider::IPerceptionControlGroup> controlGroup) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().UnregisterControlGroup(*reinterpret_cast<const Windows::Devices::Perception::Provider::IPerceptionFrameProviderManager *>(&manager), *reinterpret_cast<const Windows::Devices::Perception::Provider::PerceptionControlGroup *>(&controlGroup));
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall abi_RegisterCorrelationGroup(impl::abi_arg_in<Windows::Devices::Perception::Provider::IPerceptionFrameProviderManager> manager, impl::abi_arg_in<Windows::Devices::Perception::Provider::IPerceptionCorrelationGroup> correlationGroup) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().RegisterCorrelationGroup(*reinterpret_cast<const Windows::Devices::Perception::Provider::IPerceptionFrameProviderManager *>(&manager), *reinterpret_cast<const Windows::Devices::Perception::Provider::PerceptionCorrelationGroup *>(&correlationGroup));
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall abi_UnregisterCorrelationGroup(impl::abi_arg_in<Windows::Devices::Perception::Provider::IPerceptionFrameProviderManager> manager, impl::abi_arg_in<Windows::Devices::Perception::Provider::IPerceptionCorrelationGroup> correlationGroup) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().UnregisterCorrelationGroup(*reinterpret_cast<const Windows::Devices::Perception::Provider::IPerceptionFrameProviderManager *>(&manager), *reinterpret_cast<const Windows::Devices::Perception::Provider::PerceptionCorrelationGroup *>(&correlationGroup));
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall abi_UpdateAvailabilityForProvider(impl::abi_arg_in<Windows::Devices::Perception::Provider::IPerceptionFrameProvider> provider, bool available) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().UpdateAvailabilityForProvider(*reinterpret_cast<const Windows::Devices::Perception::Provider::IPerceptionFrameProvider *>(&provider), available);
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall abi_PublishFrameForProvider(impl::abi_arg_in<Windows::Devices::Perception::Provider::IPerceptionFrameProvider> provider, impl::abi_arg_in<Windows::Devices::Perception::Provider::IPerceptionFrame> frame) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().PublishFrameForProvider(*reinterpret_cast<const Windows::Devices::Perception::Provider::IPerceptionFrameProvider *>(&provider), *reinterpret_cast<const Windows::Devices::Perception::Provider::PerceptionFrame *>(&frame));
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Devices::Perception::Provider::IPerceptionPropertyChangeRequest> : produce_base<D, Windows::Devices::Perception::Provider::IPerceptionPropertyChangeRequest>
{
HRESULT __stdcall get_Name(impl::abi_arg_out<hstring> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().Name());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall get_Value(impl::abi_arg_out<Windows::Foundation::IInspectable> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().Value());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall get_Status(Windows::Devices::Perception::PerceptionFrameSourcePropertyChangeStatus * value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().Status());
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall put_Status(Windows::Devices::Perception::PerceptionFrameSourcePropertyChangeStatus value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().Status(value);
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall abi_GetDeferral(impl::abi_arg_out<Windows::Foundation::IDeferral> result) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*result = detach_abi(this->shim().GetDeferral());
return S_OK;
}
catch (...)
{
*result = nullptr;
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Devices::Perception::Provider::IPerceptionVideoFrameAllocator> : produce_base<D, Windows::Devices::Perception::Provider::IPerceptionVideoFrameAllocator>
{
HRESULT __stdcall abi_AllocateFrame(impl::abi_arg_out<Windows::Devices::Perception::Provider::IPerceptionFrame> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().AllocateFrame());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall abi_CopyFromVideoFrame(impl::abi_arg_in<Windows::Media::IVideoFrame> frame, impl::abi_arg_out<Windows::Devices::Perception::Provider::IPerceptionFrame> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().CopyFromVideoFrame(*reinterpret_cast<const Windows::Media::VideoFrame *>(&frame)));
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Devices::Perception::Provider::IPerceptionVideoFrameAllocatorFactory> : produce_base<D, Windows::Devices::Perception::Provider::IPerceptionVideoFrameAllocatorFactory>
{
HRESULT __stdcall abi_Create(uint32_t maxOutstandingFrameCountForWrite, Windows::Graphics::Imaging::BitmapPixelFormat format, impl::abi_arg_in<Windows::Foundation::Size> resolution, Windows::Graphics::Imaging::BitmapAlphaMode alpha, impl::abi_arg_out<Windows::Devices::Perception::Provider::IPerceptionVideoFrameAllocator> result) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*result = detach_abi(this->shim().Create(maxOutstandingFrameCountForWrite, format, *reinterpret_cast<const Windows::Foundation::Size *>(&resolution), alpha));
return S_OK;
}
catch (...)
{
*result = nullptr;
return impl::to_hresult();
}
}
};
}
namespace Windows::Devices::Perception::Provider {
template <typename D> hstring impl_IKnownPerceptionFrameKindStatics<D>::Color() const
{
hstring value;
check_hresult(WINRT_SHIM(IKnownPerceptionFrameKindStatics)->get_Color(put_abi(value)));
return value;
}
template <typename D> hstring impl_IKnownPerceptionFrameKindStatics<D>::Depth() const
{
hstring value;
check_hresult(WINRT_SHIM(IKnownPerceptionFrameKindStatics)->get_Depth(put_abi(value)));
return value;
}
template <typename D> hstring impl_IKnownPerceptionFrameKindStatics<D>::Infrared() const
{
hstring value;
check_hresult(WINRT_SHIM(IKnownPerceptionFrameKindStatics)->get_Infrared(put_abi(value)));
return value;
}
template <typename D> void impl_IPerceptionFrameProviderManagerServiceStatics<D>::RegisterFrameProviderInfo(const Windows::Devices::Perception::Provider::IPerceptionFrameProviderManager & manager, const Windows::Devices::Perception::Provider::PerceptionFrameProviderInfo & frameProviderInfo) const
{
check_hresult(WINRT_SHIM(IPerceptionFrameProviderManagerServiceStatics)->abi_RegisterFrameProviderInfo(get_abi(manager), get_abi(frameProviderInfo)));
}
template <typename D> void impl_IPerceptionFrameProviderManagerServiceStatics<D>::UnregisterFrameProviderInfo(const Windows::Devices::Perception::Provider::IPerceptionFrameProviderManager & manager, const Windows::Devices::Perception::Provider::PerceptionFrameProviderInfo & frameProviderInfo) const
{
check_hresult(WINRT_SHIM(IPerceptionFrameProviderManagerServiceStatics)->abi_UnregisterFrameProviderInfo(get_abi(manager), get_abi(frameProviderInfo)));
}
template <typename D> void impl_IPerceptionFrameProviderManagerServiceStatics<D>::RegisterFaceAuthenticationGroup(const Windows::Devices::Perception::Provider::IPerceptionFrameProviderManager & manager, const Windows::Devices::Perception::Provider::PerceptionFaceAuthenticationGroup & faceAuthenticationGroup) const
{
check_hresult(WINRT_SHIM(IPerceptionFrameProviderManagerServiceStatics)->abi_RegisterFaceAuthenticationGroup(get_abi(manager), get_abi(faceAuthenticationGroup)));
}
template <typename D> void impl_IPerceptionFrameProviderManagerServiceStatics<D>::UnregisterFaceAuthenticationGroup(const Windows::Devices::Perception::Provider::IPerceptionFrameProviderManager & manager, const Windows::Devices::Perception::Provider::PerceptionFaceAuthenticationGroup & faceAuthenticationGroup) const
{
check_hresult(WINRT_SHIM(IPerceptionFrameProviderManagerServiceStatics)->abi_UnregisterFaceAuthenticationGroup(get_abi(manager), get_abi(faceAuthenticationGroup)));
}
template <typename D> void impl_IPerceptionFrameProviderManagerServiceStatics<D>::RegisterControlGroup(const Windows::Devices::Perception::Provider::IPerceptionFrameProviderManager & manager, const Windows::Devices::Perception::Provider::PerceptionControlGroup & controlGroup) const
{
check_hresult(WINRT_SHIM(IPerceptionFrameProviderManagerServiceStatics)->abi_RegisterControlGroup(get_abi(manager), get_abi(controlGroup)));
}
template <typename D> void impl_IPerceptionFrameProviderManagerServiceStatics<D>::UnregisterControlGroup(const Windows::Devices::Perception::Provider::IPerceptionFrameProviderManager & manager, const Windows::Devices::Perception::Provider::PerceptionControlGroup & controlGroup) const
{
check_hresult(WINRT_SHIM(IPerceptionFrameProviderManagerServiceStatics)->abi_UnregisterControlGroup(get_abi(manager), get_abi(controlGroup)));
}
template <typename D> void impl_IPerceptionFrameProviderManagerServiceStatics<D>::RegisterCorrelationGroup(const Windows::Devices::Perception::Provider::IPerceptionFrameProviderManager & manager, const Windows::Devices::Perception::Provider::PerceptionCorrelationGroup & correlationGroup) const
{
check_hresult(WINRT_SHIM(IPerceptionFrameProviderManagerServiceStatics)->abi_RegisterCorrelationGroup(get_abi(manager), get_abi(correlationGroup)));
}
template <typename D> void impl_IPerceptionFrameProviderManagerServiceStatics<D>::UnregisterCorrelationGroup(const Windows::Devices::Perception::Provider::IPerceptionFrameProviderManager & manager, const Windows::Devices::Perception::Provider::PerceptionCorrelationGroup & correlationGroup) const
{
check_hresult(WINRT_SHIM(IPerceptionFrameProviderManagerServiceStatics)->abi_UnregisterCorrelationGroup(get_abi(manager), get_abi(correlationGroup)));
}
template <typename D> void impl_IPerceptionFrameProviderManagerServiceStatics<D>::UpdateAvailabilityForProvider(const Windows::Devices::Perception::Provider::IPerceptionFrameProvider & provider, bool available) const
{
check_hresult(WINRT_SHIM(IPerceptionFrameProviderManagerServiceStatics)->abi_UpdateAvailabilityForProvider(get_abi(provider), available));
}
template <typename D> void impl_IPerceptionFrameProviderManagerServiceStatics<D>::PublishFrameForProvider(const Windows::Devices::Perception::Provider::IPerceptionFrameProvider & provider, const Windows::Devices::Perception::Provider::PerceptionFrame & frame) const
{
check_hresult(WINRT_SHIM(IPerceptionFrameProviderManagerServiceStatics)->abi_PublishFrameForProvider(get_abi(provider), get_abi(frame)));
}
template <typename D> Windows::Devices::Perception::Provider::IPerceptionFrameProvider impl_IPerceptionFrameProviderManager<D>::GetFrameProvider(const Windows::Devices::Perception::Provider::PerceptionFrameProviderInfo & frameProviderInfo) const
{
Windows::Devices::Perception::Provider::IPerceptionFrameProvider result;
check_hresult(WINRT_SHIM(IPerceptionFrameProviderManager)->abi_GetFrameProvider(get_abi(frameProviderInfo), put_abi(result)));
return result;
}
template <typename D> Windows::Devices::Perception::Provider::PerceptionFrameProviderInfo impl_IPerceptionFrameProvider<D>::FrameProviderInfo() const
{
Windows::Devices::Perception::Provider::PerceptionFrameProviderInfo result { nullptr };
check_hresult(WINRT_SHIM(IPerceptionFrameProvider)->get_FrameProviderInfo(put_abi(result)));
return result;
}
template <typename D> bool impl_IPerceptionFrameProvider<D>::Available() const
{
bool value {};
check_hresult(WINRT_SHIM(IPerceptionFrameProvider)->get_Available(&value));
return value;
}
template <typename D> Windows::Foundation::Collections::IPropertySet impl_IPerceptionFrameProvider<D>::Properties() const
{
Windows::Foundation::Collections::IPropertySet value;
check_hresult(WINRT_SHIM(IPerceptionFrameProvider)->get_Properties(put_abi(value)));
return value;
}
template <typename D> void impl_IPerceptionFrameProvider<D>::Start() const
{
check_hresult(WINRT_SHIM(IPerceptionFrameProvider)->abi_Start());
}
template <typename D> void impl_IPerceptionFrameProvider<D>::Stop() const
{
check_hresult(WINRT_SHIM(IPerceptionFrameProvider)->abi_Stop());
}
template <typename D> void impl_IPerceptionFrameProvider<D>::SetProperty(const Windows::Devices::Perception::Provider::PerceptionPropertyChangeRequest & value) const
{
check_hresult(WINRT_SHIM(IPerceptionFrameProvider)->abi_SetProperty(get_abi(value)));
}
template <typename D> hstring impl_IPerceptionFrameProviderInfo<D>::Id() const
{
hstring value;
check_hresult(WINRT_SHIM(IPerceptionFrameProviderInfo)->get_Id(put_abi(value)));
return value;
}
template <typename D> void impl_IPerceptionFrameProviderInfo<D>::Id(hstring_view value) const
{
check_hresult(WINRT_SHIM(IPerceptionFrameProviderInfo)->put_Id(get_abi(value)));
}
template <typename D> hstring impl_IPerceptionFrameProviderInfo<D>::DisplayName() const
{
hstring value;
check_hresult(WINRT_SHIM(IPerceptionFrameProviderInfo)->get_DisplayName(put_abi(value)));
return value;
}
template <typename D> void impl_IPerceptionFrameProviderInfo<D>::DisplayName(hstring_view value) const
{
check_hresult(WINRT_SHIM(IPerceptionFrameProviderInfo)->put_DisplayName(get_abi(value)));
}
template <typename D> hstring impl_IPerceptionFrameProviderInfo<D>::DeviceKind() const
{
hstring value;
check_hresult(WINRT_SHIM(IPerceptionFrameProviderInfo)->get_DeviceKind(put_abi(value)));
return value;
}
template <typename D> void impl_IPerceptionFrameProviderInfo<D>::DeviceKind(hstring_view value) const
{
check_hresult(WINRT_SHIM(IPerceptionFrameProviderInfo)->put_DeviceKind(get_abi(value)));
}
template <typename D> hstring impl_IPerceptionFrameProviderInfo<D>::FrameKind() const
{
hstring value;
check_hresult(WINRT_SHIM(IPerceptionFrameProviderInfo)->get_FrameKind(put_abi(value)));
return value;
}
template <typename D> void impl_IPerceptionFrameProviderInfo<D>::FrameKind(hstring_view value) const
{
check_hresult(WINRT_SHIM(IPerceptionFrameProviderInfo)->put_FrameKind(get_abi(value)));
}
template <typename D> bool impl_IPerceptionFrameProviderInfo<D>::Hidden() const
{
bool value {};
check_hresult(WINRT_SHIM(IPerceptionFrameProviderInfo)->get_Hidden(&value));
return value;
}
template <typename D> void impl_IPerceptionFrameProviderInfo<D>::Hidden(bool value) const
{
check_hresult(WINRT_SHIM(IPerceptionFrameProviderInfo)->put_Hidden(value));
}
template <typename D> Windows::Devices::Perception::Provider::PerceptionControlGroup impl_IPerceptionControlGroupFactory<D>::Create(iterable<hstring> ids) const
{
Windows::Devices::Perception::Provider::PerceptionControlGroup result { nullptr };
check_hresult(WINRT_SHIM(IPerceptionControlGroupFactory)->abi_Create(get_abi(ids), put_abi(result)));
return result;
}
template <typename D> Windows::Foundation::Collections::IVectorView<hstring> impl_IPerceptionControlGroup<D>::FrameProviderIds() const
{
Windows::Foundation::Collections::IVectorView<hstring> value;
check_hresult(WINRT_SHIM(IPerceptionControlGroup)->get_FrameProviderIds(put_abi(value)));
return value;
}
template <typename D> Windows::Devices::Perception::Provider::PerceptionFaceAuthenticationGroup impl_IPerceptionFaceAuthenticationGroupFactory<D>::Create(iterable<hstring> ids, const Windows::Devices::Perception::Provider::PerceptionStartFaceAuthenticationHandler & startHandler, const Windows::Devices::Perception::Provider::PerceptionStopFaceAuthenticationHandler & stopHandler) const
{
Windows::Devices::Perception::Provider::PerceptionFaceAuthenticationGroup result { nullptr };
check_hresult(WINRT_SHIM(IPerceptionFaceAuthenticationGroupFactory)->abi_Create(get_abi(ids), get_abi(startHandler), get_abi(stopHandler), put_abi(result)));
return result;
}
template <typename D> Windows::Foundation::Collections::IVectorView<hstring> impl_IPerceptionFaceAuthenticationGroup<D>::FrameProviderIds() const
{
Windows::Foundation::Collections::IVectorView<hstring> value;
check_hresult(WINRT_SHIM(IPerceptionFaceAuthenticationGroup)->get_FrameProviderIds(put_abi(value)));
return value;
}
template <typename D> Windows::Devices::Perception::Provider::PerceptionCorrelation impl_IPerceptionCorrelationFactory<D>::Create(hstring_view targetId, const Windows::Foundation::Numerics::float3 & position, const Windows::Foundation::Numerics::quaternion & orientation) const
{
Windows::Devices::Perception::Provider::PerceptionCorrelation result { nullptr };
check_hresult(WINRT_SHIM(IPerceptionCorrelationFactory)->abi_Create(get_abi(targetId), get_abi(position), get_abi(orientation), put_abi(result)));
return result;
}
template <typename D> hstring impl_IPerceptionCorrelation<D>::TargetId() const
{
hstring value;
check_hresult(WINRT_SHIM(IPerceptionCorrelation)->get_TargetId(put_abi(value)));
return value;
}
template <typename D> Windows::Foundation::Numerics::float3 impl_IPerceptionCorrelation<D>::Position() const
{
Windows::Foundation::Numerics::float3 value {};
check_hresult(WINRT_SHIM(IPerceptionCorrelation)->get_Position(put_abi(value)));
return value;
}
template <typename D> Windows::Foundation::Numerics::quaternion impl_IPerceptionCorrelation<D>::Orientation() const
{
Windows::Foundation::Numerics::quaternion value {};
check_hresult(WINRT_SHIM(IPerceptionCorrelation)->get_Orientation(put_abi(value)));
return value;
}
template <typename D> Windows::Devices::Perception::Provider::PerceptionCorrelationGroup impl_IPerceptionCorrelationGroupFactory<D>::Create(iterable<Windows::Devices::Perception::Provider::PerceptionCorrelation> relativeLocations) const
{
Windows::Devices::Perception::Provider::PerceptionCorrelationGroup result { nullptr };
check_hresult(WINRT_SHIM(IPerceptionCorrelationGroupFactory)->abi_Create(get_abi(relativeLocations), put_abi(result)));
return result;
}
template <typename D> Windows::Foundation::Collections::IVectorView<Windows::Devices::Perception::Provider::PerceptionCorrelation> impl_IPerceptionCorrelationGroup<D>::RelativeLocations() const
{
Windows::Foundation::Collections::IVectorView<Windows::Devices::Perception::Provider::PerceptionCorrelation> value;
check_hresult(WINRT_SHIM(IPerceptionCorrelationGroup)->get_RelativeLocations(put_abi(value)));
return value;
}
template <typename D> Windows::Foundation::TimeSpan impl_IPerceptionFrame<D>::RelativeTime() const
{
Windows::Foundation::TimeSpan value {};
check_hresult(WINRT_SHIM(IPerceptionFrame)->get_RelativeTime(put_abi(value)));
return value;
}
template <typename D> void impl_IPerceptionFrame<D>::RelativeTime(const Windows::Foundation::TimeSpan & value) const
{
check_hresult(WINRT_SHIM(IPerceptionFrame)->put_RelativeTime(get_abi(value)));
}
template <typename D> Windows::Foundation::Collections::ValueSet impl_IPerceptionFrame<D>::Properties() const
{
Windows::Foundation::Collections::ValueSet value { nullptr };
check_hresult(WINRT_SHIM(IPerceptionFrame)->get_Properties(put_abi(value)));
return value;
}
template <typename D> Windows::Foundation::IMemoryBuffer impl_IPerceptionFrame<D>::FrameData() const
{
Windows::Foundation::IMemoryBuffer value;
check_hresult(WINRT_SHIM(IPerceptionFrame)->get_FrameData(put_abi(value)));
return value;
}
template <typename D> Windows::Devices::Perception::Provider::PerceptionVideoFrameAllocator impl_IPerceptionVideoFrameAllocatorFactory<D>::Create(uint32_t maxOutstandingFrameCountForWrite, Windows::Graphics::Imaging::BitmapPixelFormat format, const Windows::Foundation::Size & resolution, Windows::Graphics::Imaging::BitmapAlphaMode alpha) const
{
Windows::Devices::Perception::Provider::PerceptionVideoFrameAllocator result { nullptr };
check_hresult(WINRT_SHIM(IPerceptionVideoFrameAllocatorFactory)->abi_Create(maxOutstandingFrameCountForWrite, format, get_abi(resolution), alpha, put_abi(result)));
return result;
}
template <typename D> Windows::Devices::Perception::Provider::PerceptionFrame impl_IPerceptionVideoFrameAllocator<D>::AllocateFrame() const
{
Windows::Devices::Perception::Provider::PerceptionFrame value { nullptr };
check_hresult(WINRT_SHIM(IPerceptionVideoFrameAllocator)->abi_AllocateFrame(put_abi(value)));
return value;
}
template <typename D> Windows::Devices::Perception::Provider::PerceptionFrame impl_IPerceptionVideoFrameAllocator<D>::CopyFromVideoFrame(const Windows::Media::VideoFrame & frame) const
{
Windows::Devices::Perception::Provider::PerceptionFrame value { nullptr };
check_hresult(WINRT_SHIM(IPerceptionVideoFrameAllocator)->abi_CopyFromVideoFrame(get_abi(frame), put_abi(value)));
return value;
}
template <typename D> hstring impl_IPerceptionPropertyChangeRequest<D>::Name() const
{
hstring value;
check_hresult(WINRT_SHIM(IPerceptionPropertyChangeRequest)->get_Name(put_abi(value)));
return value;
}
template <typename D> Windows::Foundation::IInspectable impl_IPerceptionPropertyChangeRequest<D>::Value() const
{
Windows::Foundation::IInspectable value;
check_hresult(WINRT_SHIM(IPerceptionPropertyChangeRequest)->get_Value(put_abi(value)));
return value;
}
template <typename D> Windows::Devices::Perception::PerceptionFrameSourcePropertyChangeStatus impl_IPerceptionPropertyChangeRequest<D>::Status() const
{
Windows::Devices::Perception::PerceptionFrameSourcePropertyChangeStatus value {};
check_hresult(WINRT_SHIM(IPerceptionPropertyChangeRequest)->get_Status(&value));
return value;
}
template <typename D> void impl_IPerceptionPropertyChangeRequest<D>::Status(Windows::Devices::Perception::PerceptionFrameSourcePropertyChangeStatus value) const
{
check_hresult(WINRT_SHIM(IPerceptionPropertyChangeRequest)->put_Status(value));
}
template <typename D> Windows::Foundation::Deferral impl_IPerceptionPropertyChangeRequest<D>::GetDeferral() const
{
Windows::Foundation::Deferral result { nullptr };
check_hresult(WINRT_SHIM(IPerceptionPropertyChangeRequest)->abi_GetDeferral(put_abi(result)));
return result;
}
inline hstring KnownPerceptionFrameKind::Color()
{
return get_activation_factory<KnownPerceptionFrameKind, IKnownPerceptionFrameKindStatics>().Color();
}
inline hstring KnownPerceptionFrameKind::Depth()
{
return get_activation_factory<KnownPerceptionFrameKind, IKnownPerceptionFrameKindStatics>().Depth();
}
inline hstring KnownPerceptionFrameKind::Infrared()
{
return get_activation_factory<KnownPerceptionFrameKind, IKnownPerceptionFrameKindStatics>().Infrared();
}
inline PerceptionControlGroup::PerceptionControlGroup(iterable<hstring> ids) :
PerceptionControlGroup(get_activation_factory<PerceptionControlGroup, IPerceptionControlGroupFactory>().Create(ids))
{}
inline PerceptionCorrelation::PerceptionCorrelation(hstring_view targetId, const Windows::Foundation::Numerics::float3 & position, const Windows::Foundation::Numerics::quaternion & orientation) :
PerceptionCorrelation(get_activation_factory<PerceptionCorrelation, IPerceptionCorrelationFactory>().Create(targetId, position, orientation))
{}
inline PerceptionCorrelationGroup::PerceptionCorrelationGroup(iterable<Windows::Devices::Perception::Provider::PerceptionCorrelation> relativeLocations) :
PerceptionCorrelationGroup(get_activation_factory<PerceptionCorrelationGroup, IPerceptionCorrelationGroupFactory>().Create(relativeLocations))
{}
inline PerceptionFaceAuthenticationGroup::PerceptionFaceAuthenticationGroup(iterable<hstring> ids, const Windows::Devices::Perception::Provider::PerceptionStartFaceAuthenticationHandler & startHandler, const Windows::Devices::Perception::Provider::PerceptionStopFaceAuthenticationHandler & stopHandler) :
PerceptionFaceAuthenticationGroup(get_activation_factory<PerceptionFaceAuthenticationGroup, IPerceptionFaceAuthenticationGroupFactory>().Create(ids, startHandler, stopHandler))
{}
inline PerceptionFrameProviderInfo::PerceptionFrameProviderInfo() :
PerceptionFrameProviderInfo(activate_instance<PerceptionFrameProviderInfo>())
{}
inline void PerceptionFrameProviderManagerService::RegisterFrameProviderInfo(const Windows::Devices::Perception::Provider::IPerceptionFrameProviderManager & manager, const Windows::Devices::Perception::Provider::PerceptionFrameProviderInfo & frameProviderInfo)
{
get_activation_factory<PerceptionFrameProviderManagerService, IPerceptionFrameProviderManagerServiceStatics>().RegisterFrameProviderInfo(manager, frameProviderInfo);
}
inline void PerceptionFrameProviderManagerService::UnregisterFrameProviderInfo(const Windows::Devices::Perception::Provider::IPerceptionFrameProviderManager & manager, const Windows::Devices::Perception::Provider::PerceptionFrameProviderInfo & frameProviderInfo)
{
get_activation_factory<PerceptionFrameProviderManagerService, IPerceptionFrameProviderManagerServiceStatics>().UnregisterFrameProviderInfo(manager, frameProviderInfo);
}
inline void PerceptionFrameProviderManagerService::RegisterFaceAuthenticationGroup(const Windows::Devices::Perception::Provider::IPerceptionFrameProviderManager & manager, const Windows::Devices::Perception::Provider::PerceptionFaceAuthenticationGroup & faceAuthenticationGroup)
{
get_activation_factory<PerceptionFrameProviderManagerService, IPerceptionFrameProviderManagerServiceStatics>().RegisterFaceAuthenticationGroup(manager, faceAuthenticationGroup);
}
inline void PerceptionFrameProviderManagerService::UnregisterFaceAuthenticationGroup(const Windows::Devices::Perception::Provider::IPerceptionFrameProviderManager & manager, const Windows::Devices::Perception::Provider::PerceptionFaceAuthenticationGroup & faceAuthenticationGroup)
{
get_activation_factory<PerceptionFrameProviderManagerService, IPerceptionFrameProviderManagerServiceStatics>().UnregisterFaceAuthenticationGroup(manager, faceAuthenticationGroup);
}
inline void PerceptionFrameProviderManagerService::RegisterControlGroup(const Windows::Devices::Perception::Provider::IPerceptionFrameProviderManager & manager, const Windows::Devices::Perception::Provider::PerceptionControlGroup & controlGroup)
{
get_activation_factory<PerceptionFrameProviderManagerService, IPerceptionFrameProviderManagerServiceStatics>().RegisterControlGroup(manager, controlGroup);
}
inline void PerceptionFrameProviderManagerService::UnregisterControlGroup(const Windows::Devices::Perception::Provider::IPerceptionFrameProviderManager & manager, const Windows::Devices::Perception::Provider::PerceptionControlGroup & controlGroup)
{
get_activation_factory<PerceptionFrameProviderManagerService, IPerceptionFrameProviderManagerServiceStatics>().UnregisterControlGroup(manager, controlGroup);
}
inline void PerceptionFrameProviderManagerService::RegisterCorrelationGroup(const Windows::Devices::Perception::Provider::IPerceptionFrameProviderManager & manager, const Windows::Devices::Perception::Provider::PerceptionCorrelationGroup & correlationGroup)
{
get_activation_factory<PerceptionFrameProviderManagerService, IPerceptionFrameProviderManagerServiceStatics>().RegisterCorrelationGroup(manager, correlationGroup);
}
inline void PerceptionFrameProviderManagerService::UnregisterCorrelationGroup(const Windows::Devices::Perception::Provider::IPerceptionFrameProviderManager & manager, const Windows::Devices::Perception::Provider::PerceptionCorrelationGroup & correlationGroup)
{
get_activation_factory<PerceptionFrameProviderManagerService, IPerceptionFrameProviderManagerServiceStatics>().UnregisterCorrelationGroup(manager, correlationGroup);
}
inline void PerceptionFrameProviderManagerService::UpdateAvailabilityForProvider(const Windows::Devices::Perception::Provider::IPerceptionFrameProvider & provider, bool available)
{
get_activation_factory<PerceptionFrameProviderManagerService, IPerceptionFrameProviderManagerServiceStatics>().UpdateAvailabilityForProvider(provider, available);
}
inline void PerceptionFrameProviderManagerService::PublishFrameForProvider(const Windows::Devices::Perception::Provider::IPerceptionFrameProvider & provider, const Windows::Devices::Perception::Provider::PerceptionFrame & frame)
{
get_activation_factory<PerceptionFrameProviderManagerService, IPerceptionFrameProviderManagerServiceStatics>().PublishFrameForProvider(provider, frame);
}
inline PerceptionVideoFrameAllocator::PerceptionVideoFrameAllocator(uint32_t maxOutstandingFrameCountForWrite, Windows::Graphics::Imaging::BitmapPixelFormat format, const Windows::Foundation::Size & resolution, Windows::Graphics::Imaging::BitmapAlphaMode alpha) :
PerceptionVideoFrameAllocator(get_activation_factory<PerceptionVideoFrameAllocator, IPerceptionVideoFrameAllocatorFactory>().Create(maxOutstandingFrameCountForWrite, format, resolution, alpha))
{}
}
}
template<>
struct std::hash<winrt::Windows::Devices::Perception::Provider::IKnownPerceptionFrameKindStatics>
{
size_t operator()(const winrt::Windows::Devices::Perception::Provider::IKnownPerceptionFrameKindStatics & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Devices::Perception::Provider::IPerceptionControlGroup>
{
size_t operator()(const winrt::Windows::Devices::Perception::Provider::IPerceptionControlGroup & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Devices::Perception::Provider::IPerceptionControlGroupFactory>
{
size_t operator()(const winrt::Windows::Devices::Perception::Provider::IPerceptionControlGroupFactory & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Devices::Perception::Provider::IPerceptionCorrelation>
{
size_t operator()(const winrt::Windows::Devices::Perception::Provider::IPerceptionCorrelation & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Devices::Perception::Provider::IPerceptionCorrelationFactory>
{
size_t operator()(const winrt::Windows::Devices::Perception::Provider::IPerceptionCorrelationFactory & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Devices::Perception::Provider::IPerceptionCorrelationGroup>
{
size_t operator()(const winrt::Windows::Devices::Perception::Provider::IPerceptionCorrelationGroup & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Devices::Perception::Provider::IPerceptionCorrelationGroupFactory>
{
size_t operator()(const winrt::Windows::Devices::Perception::Provider::IPerceptionCorrelationGroupFactory & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Devices::Perception::Provider::IPerceptionFaceAuthenticationGroup>
{
size_t operator()(const winrt::Windows::Devices::Perception::Provider::IPerceptionFaceAuthenticationGroup & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Devices::Perception::Provider::IPerceptionFaceAuthenticationGroupFactory>
{
size_t operator()(const winrt::Windows::Devices::Perception::Provider::IPerceptionFaceAuthenticationGroupFactory & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Devices::Perception::Provider::IPerceptionFrame>
{
size_t operator()(const winrt::Windows::Devices::Perception::Provider::IPerceptionFrame & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Devices::Perception::Provider::IPerceptionFrameProvider>
{
size_t operator()(const winrt::Windows::Devices::Perception::Provider::IPerceptionFrameProvider & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Devices::Perception::Provider::IPerceptionFrameProviderInfo>
{
size_t operator()(const winrt::Windows::Devices::Perception::Provider::IPerceptionFrameProviderInfo & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Devices::Perception::Provider::IPerceptionFrameProviderManager>
{
size_t operator()(const winrt::Windows::Devices::Perception::Provider::IPerceptionFrameProviderManager & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Devices::Perception::Provider::IPerceptionFrameProviderManagerServiceStatics>
{
size_t operator()(const winrt::Windows::Devices::Perception::Provider::IPerceptionFrameProviderManagerServiceStatics & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Devices::Perception::Provider::IPerceptionPropertyChangeRequest>
{
size_t operator()(const winrt::Windows::Devices::Perception::Provider::IPerceptionPropertyChangeRequest & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Devices::Perception::Provider::IPerceptionVideoFrameAllocator>
{
size_t operator()(const winrt::Windows::Devices::Perception::Provider::IPerceptionVideoFrameAllocator & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Devices::Perception::Provider::IPerceptionVideoFrameAllocatorFactory>
{
size_t operator()(const winrt::Windows::Devices::Perception::Provider::IPerceptionVideoFrameAllocatorFactory & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Devices::Perception::Provider::PerceptionControlGroup>
{
size_t operator()(const winrt::Windows::Devices::Perception::Provider::PerceptionControlGroup & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Devices::Perception::Provider::PerceptionCorrelation>
{
size_t operator()(const winrt::Windows::Devices::Perception::Provider::PerceptionCorrelation & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Devices::Perception::Provider::PerceptionCorrelationGroup>
{
size_t operator()(const winrt::Windows::Devices::Perception::Provider::PerceptionCorrelationGroup & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Devices::Perception::Provider::PerceptionFaceAuthenticationGroup>
{
size_t operator()(const winrt::Windows::Devices::Perception::Provider::PerceptionFaceAuthenticationGroup & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Devices::Perception::Provider::PerceptionFrame>
{
size_t operator()(const winrt::Windows::Devices::Perception::Provider::PerceptionFrame & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Devices::Perception::Provider::PerceptionFrameProviderInfo>
{
size_t operator()(const winrt::Windows::Devices::Perception::Provider::PerceptionFrameProviderInfo & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Devices::Perception::Provider::PerceptionPropertyChangeRequest>
{
size_t operator()(const winrt::Windows::Devices::Perception::Provider::PerceptionPropertyChangeRequest & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Devices::Perception::Provider::PerceptionVideoFrameAllocator>
{
size_t operator()(const winrt::Windows::Devices::Perception::Provider::PerceptionVideoFrameAllocator & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
WINRT_WARNING_POP
| [
"[email protected]"
] | |
486df054b3e19154eb5c9d4e3fc0ae894a8ecd8c | fa8437ac4d82aca92cdd63a350fa6311e6c715c6 | /tests/cookie_test_3.cc | f007b2acee961c76fd6901ce961e1d6ac3509082 | [
"Apache-2.0"
] | permissive | beo-teis/pistache | 5c825971fd2f99737e7116bc3f7d614819f8209e | 673cf423261dd3101b9bac81f9141ecaf7a428b1 | refs/heads/master | 2020-04-08T08:34:13.369628 | 2018-11-24T23:35:24 | 2018-11-24T23:35:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,564 | cc | #include <pistache/client.h>
#include <pistache/cookie.h>
#include <pistache/endpoint.h>
#include <pistache/http.h>
#include "gtest/gtest.h"
#include <chrono>
#include <unordered_map>
using namespace Pistache;
struct CookieHandler : public Http::Handler {
HTTP_PROTOTYPE(CookieHandler)
void onRequest(const Http::Request& request, Http::ResponseWriter response) override {
// Synthetic behaviour, just for testing purposes
for(auto&& cookie: request.cookies()) {
response.cookies().add(cookie);
}
response.send(Http::Code::Ok, "Ok");
}
};
TEST(http_client_test, one_client_with_one_request_with_cookies) {
const std::string address = "localhost:9085";
Http::Endpoint server(address);
auto flags = Tcp::Options::InstallSignalHandler | Tcp::Options::ReuseAddr;
auto server_opts = Http::Endpoint::options().flags(flags);
server.init(server_opts);
server.setHandler(Http::make_handler<CookieHandler>());
server.serveThreaded();
Http::Client client;
client.init();
std::vector<Async::Promise<Http::Response>> responses;
const std::string name1 = "FOO";
const std::string value1 = "bar";
auto cookie1 = Http::Cookie(name1, value1);
const std::string name2 = "FIZZ";
const std::string value2 = "Buzz";
auto cookie2 = Http::Cookie(name2, value2);
const std::string name3 = "Key";
const std::string value3 = "value";
auto cookie3 = Http::Cookie(name3, value3);
auto rb = client.get(address).cookie(cookie1).cookie(cookie2).cookie(cookie3);
auto response = rb.send();
std::unordered_map<std::string, std::string> cookiesStorages;
response.then([&](Http::Response rsp) {
for (auto&& cookie: rsp.cookies()) {
cookiesStorages[cookie.name] = cookie.value;
std::cout << "get: " << cookie.name << "\n";
}
},
Async::IgnoreException);
responses.push_back(std::move(response));
auto sync = Async::whenAll(responses.begin(), responses.end());
Async::Barrier<std::vector<Http::Response>> barrier(sync);
barrier.wait_for(std::chrono::seconds(5));
server.shutdown();
client.shutdown();
ASSERT_NE(cookiesStorages.find(name1), cookiesStorages.end());
ASSERT_EQ(cookiesStorages[name1], value1);
ASSERT_NE(cookiesStorages.find(name2), cookiesStorages.end());
ASSERT_EQ(cookiesStorages[name2], value2);
ASSERT_NE(cookiesStorages.find(name3), cookiesStorages.end());
ASSERT_EQ(cookiesStorages[name3], value3);
}
| [
"[email protected]"
] | |
a5fad3085ab422296fc9f5772e0ed0af772a12e7 | 1f18bc8d02288b98df04ec90c84a1befdbf69a16 | /www/iridium/files/patch-chrome_updater_configurator.cc | 03311ec13ac9c8b6b3cf93864a8eefa81d94576b | [
"BSD-2-Clause",
"BSD-3-Clause"
] | permissive | SchaichAlonso/freebsd-ports-kde | 7b4234c7b49f6aa3eff537a4eac76d002e90f2eb | 47664b577ae7923d128e20539827c3430c5ba5f2 | refs/heads/main | 2023-08-03T11:48:29.571565 | 2023-04-14T16:29:17 | 2023-04-21T10:35:00 | 158,081,621 | 0 | 0 | NOASSERTION | 2018-11-18T12:29:52 | 2018-11-18T12:29:51 | null | UTF-8 | C++ | false | false | 597 | cc | --- chrome/updater/configurator.cc.orig 2023-03-13 07:33:08 UTC
+++ chrome/updater/configurator.cc
@@ -57,7 +57,7 @@ Configurator::Configurator(scoped_refptr<UpdaterPrefs>
base::MakeRefCounted<update_client::InProcessUnzipperFactory>()),
patch_factory_(
base::MakeRefCounted<update_client::InProcessPatcherFactory>()) {
-#if BUILDFLAG(IS_LINUX)
+#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_BSD)
// On Linux creating the NetworkFetcherFactory requires performing blocking IO
// to load an external library. This should be done when the configurator is
// created.
| [
"[email protected]"
] | |
adfca04dabe17db42d35a56b65a529e00dba3155 | 75e904f7658ce405369714daa4886cd418ef10f8 | /webkit/WebKit/win/WebFrame.cpp | d58458a011bca3879f159762474a2098eeb36240 | [
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | s1rcheese/new-3ds-internetbrowser | 3cee62f244e359269f4f09b6a84e40954a98eda5 | 93987629e307342c667bec74ee432ab332857cc1 | refs/heads/master | 2023-08-19T11:07:29.459670 | 2021-10-02T20:25:01 | 2021-10-02T20:25:01 | 410,396,874 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 77,117 | cpp | /*
* Copyright (C) 2006, 2007, 2008, 2009, 2011 Apple Inc. All rights reserved.
* Copyright (C) Research In Motion Limited 2009. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "WebKitDLL.h"
#include "WebFrame.h"
#include "CFDictionaryPropertyBag.h"
#include "COMPropertyBag.h"
#include "DOMCoreClasses.h"
#include "DefaultPolicyDelegate.h"
#include "HTMLFrameOwnerElement.h"
#include "MarshallingHelpers.h"
#include "WebActionPropertyBag.h"
#include "WebChromeClient.h"
#include "WebDataSource.h"
#include "WebDocumentLoader.h"
#include "WebDownload.h"
#include "WebEditorClient.h"
#include "WebError.h"
#include "WebFrameNetworkingContext.h"
#include "WebFramePolicyListener.h"
#include "WebHistory.h"
#include "WebHistoryItem.h"
#include "WebKit.h"
#include "WebKitStatisticsPrivate.h"
#include "WebMutableURLRequest.h"
#include "WebNotificationCenter.h"
#include "WebScriptWorld.h"
#include "WebURLResponse.h"
#include "WebView.h"
#include <WebCore/BString.h>
#include <WebCore/COMPtr.h>
#include <WebCore/MemoryCache.h>
#include <WebCore/Document.h>
#include <WebCore/DocumentLoader.h>
#include <WebCore/DocumentMarkerController.h>
#include <WebCore/DOMImplementation.h>
#include <WebCore/DOMWindow.h>
#include <WebCore/Event.h>
#include <WebCore/EventHandler.h>
#include <WebCore/FormState.h>
#include <WebCore/Frame.h>
#include <WebCore/FrameLoader.h>
#include <WebCore/FrameLoadRequest.h>
#include <WebCore/FrameTree.h>
#include <WebCore/FrameView.h>
#include <WebCore/FrameWin.h>
#include <WebCore/GDIObjectCounter.h>
#include <WebCore/GraphicsContext.h>
#include <WebCore/HistoryItem.h>
#include <WebCore/HTMLAppletElement.h>
#include <WebCore/HTMLFormElement.h>
#include <WebCore/HTMLFormControlElement.h>
#include <WebCore/HTMLInputElement.h>
#include <WebCore/HTMLNames.h>
#include <WebCore/HTMLPlugInElement.h>
#include <WebCore/JSDOMWindow.h>
#include <WebCore/KeyboardEvent.h>
#include <WebCore/MouseRelatedEvent.h>
#include <WebCore/NotImplemented.h>
#include <WebCore/Page.h>
#include <WebCore/PlatformKeyboardEvent.h>
#include <WebCore/PluginData.h>
#include <WebCore/PluginDatabase.h>
#include <WebCore/PluginView.h>
#include <WebCore/PrintContext.h>
#include <WebCore/ResourceHandle.h>
#include <WebCore/ResourceRequest.h>
#include <WebCore/RenderView.h>
#include <WebCore/RenderTreeAsText.h>
#include <WebCore/Settings.h>
#include <WebCore/TextIterator.h>
#include <WebCore/JSDOMBinding.h>
#include <WebCore/ScriptController.h>
#include <WebCore/ScriptValue.h>
#include <WebCore/SecurityOrigin.h>
#include <JavaScriptCore/APICast.h>
#include <JavaScriptCore/JSLock.h>
#include <JavaScriptCore/JSObject.h>
#include <JavaScriptCore/JSValue.h>
#include <wtf/MathExtras.h>
#if USE(CG)
#include <CoreGraphics/CoreGraphics.h>
#elif USE(CAIRO)
#include "PlatformContextCairo.h"
#include <cairo-win32.h>
#endif
#if USE(CG)
// CG SPI used for printing
extern "C" {
CGAffineTransform CGContextGetBaseCTM(CGContextRef c);
void CGContextSetBaseCTM(CGContextRef c, CGAffineTransform m);
}
#endif
using namespace WebCore;
using namespace HTMLNames;
using namespace std;
using JSC::JSGlobalObject;
using JSC::JSLock;
using JSC::JSValue;
#define FLASH_REDRAW 0
// By imaging to a width a little wider than the available pixels,
// thin pages will be scaled down a little, matching the way they
// print in IE and Camino. This lets them use fewer sheets than they
// would otherwise, which is presumably why other browsers do this.
// Wide pages will be scaled down more than this.
const float PrintingMinimumShrinkFactor = 1.25f;
// This number determines how small we are willing to reduce the page content
// in order to accommodate the widest line. If the page would have to be
// reduced smaller to make the widest line fit, we just clip instead (this
// behavior matches MacIE and Mozilla, at least)
const float PrintingMaximumShrinkFactor = 2.0f;
//-----------------------------------------------------------------------------
// Helpers to convert from WebCore to WebKit type
WebFrame* kit(Frame* frame)
{
if (!frame)
return 0;
FrameLoaderClient* frameLoaderClient = frame->loader()->client();
if (frameLoaderClient)
return static_cast<WebFrame*>(frameLoaderClient); // eek, is there a better way than static cast?
return 0;
}
Frame* core(WebFrame* webFrame)
{
if (!webFrame)
return 0;
return webFrame->impl();
}
// This function is not in WebFrame.h because we don't want to advertise the ability to get a non-const Frame from a const WebFrame
Frame* core(const WebFrame* webFrame)
{
if (!webFrame)
return 0;
return const_cast<WebFrame*>(webFrame)->impl();
}
//-----------------------------------------------------------------------------
static Element *elementFromDOMElement(IDOMElement *element)
{
if (!element)
return 0;
COMPtr<IDOMElementPrivate> elePriv;
HRESULT hr = element->QueryInterface(IID_IDOMElementPrivate, (void**) &elePriv);
if (SUCCEEDED(hr)) {
Element* ele;
hr = elePriv->coreElement((void**)&ele);
if (SUCCEEDED(hr))
return ele;
}
return 0;
}
static HTMLFormElement *formElementFromDOMElement(IDOMElement *element)
{
if (!element)
return 0;
IDOMElementPrivate* elePriv;
HRESULT hr = element->QueryInterface(IID_IDOMElementPrivate, (void**) &elePriv);
if (SUCCEEDED(hr)) {
Element* ele;
hr = elePriv->coreElement((void**)&ele);
elePriv->Release();
if (SUCCEEDED(hr) && ele && ele->hasTagName(formTag))
return static_cast<HTMLFormElement*>(ele);
}
return 0;
}
static HTMLInputElement* inputElementFromDOMElement(IDOMElement* element)
{
if (!element)
return 0;
IDOMElementPrivate* elePriv;
HRESULT hr = element->QueryInterface(IID_IDOMElementPrivate, (void**) &elePriv);
if (SUCCEEDED(hr)) {
Element* ele;
hr = elePriv->coreElement((void**)&ele);
elePriv->Release();
if (SUCCEEDED(hr) && ele && ele->hasTagName(inputTag))
return static_cast<HTMLInputElement*>(ele);
}
return 0;
}
// WebFramePrivate ------------------------------------------------------------
class WebFrame::WebFramePrivate {
public:
WebFramePrivate()
: frame(0)
, webView(0)
, m_policyFunction(0)
{
}
~WebFramePrivate() { }
FrameView* frameView() { return frame ? frame->view() : 0; }
Frame* frame;
WebView* webView;
FramePolicyFunction m_policyFunction;
COMPtr<WebFramePolicyListener> m_policyListener;
};
// WebFrame ----------------------------------------------------------------
WebFrame::WebFrame()
: WebFrameLoaderClient(this)
, m_refCount(0)
, d(new WebFrame::WebFramePrivate)
, m_quickRedirectComing(false)
, m_inPrintingMode(false)
, m_pageHeight(0)
{
WebFrameCount++;
gClassCount++;
gClassNameCount.add("WebFrame");
}
WebFrame::~WebFrame()
{
delete d;
WebFrameCount--;
gClassCount--;
gClassNameCount.remove("WebFrame");
}
WebFrame* WebFrame::createInstance()
{
WebFrame* instance = new WebFrame();
instance->AddRef();
return instance;
}
HRESULT STDMETHODCALLTYPE WebFrame::setAllowsScrolling(
/* [in] */ BOOL flag)
{
if (Frame* frame = core(this))
if (FrameView* view = frame->view())
view->setCanHaveScrollbars(!!flag);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebFrame::allowsScrolling(
/* [retval][out] */ BOOL *flag)
{
if (flag)
if (Frame* frame = core(this))
if (FrameView* view = frame->view())
*flag = view->canHaveScrollbars();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebFrame::setIsDisconnected(
/* [in] */ BOOL flag)
{
if (Frame* frame = core(this)) {
frame->setIsDisconnected(flag);
return S_OK;
}
return E_FAIL;
}
HRESULT STDMETHODCALLTYPE WebFrame::setExcludeFromTextSearch(
/* [in] */ BOOL flag)
{
if (Frame* frame = core(this)) {
frame->setExcludeFromTextSearch(flag);
return S_OK;
}
return E_FAIL;
}
HRESULT WebFrame::reloadFromOrigin()
{
Frame* coreFrame = core(this);
if (!coreFrame)
return E_FAIL;
coreFrame->loader()->reload(true);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebFrame::paintDocumentRectToContext(
/* [in] */ RECT rect,
/* [in] */ OLE_HANDLE deviceContext)
{
Frame* coreFrame = core(this);
if (!coreFrame)
return E_FAIL;
FrameView* view = coreFrame->view();
if (!view)
return E_FAIL;
// We can't paint with a layout still pending.
view->updateLayoutAndStyleIfNeededRecursive();
HDC dc = reinterpret_cast<HDC>(static_cast<ULONG64>(deviceContext));
GraphicsContext gc(dc);
gc.setShouldIncludeChildWindows(true);
gc.save();
LONG width = rect.right - rect.left;
LONG height = rect.bottom - rect.top;
FloatRect dirtyRect;
dirtyRect.setWidth(width);
dirtyRect.setHeight(height);
gc.clip(dirtyRect);
gc.translate(-rect.left, -rect.top);
view->paintContents(&gc, rect);
gc.restore();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebFrame::paintScrollViewRectToContextAtPoint(
/* [in] */ RECT rect,
/* [in] */ POINT pt,
/* [in] */ OLE_HANDLE deviceContext)
{
Frame* coreFrame = core(this);
if (!coreFrame)
return E_FAIL;
FrameView* view = coreFrame->view();
if (!view)
return E_FAIL;
// We can't paint with a layout still pending.
view->updateLayoutAndStyleIfNeededRecursive();
HDC dc = reinterpret_cast<HDC>(static_cast<ULONG64>(deviceContext));
GraphicsContext gc(dc);
gc.setShouldIncludeChildWindows(true);
gc.save();
IntRect dirtyRect(rect);
dirtyRect.move(-pt.x, -pt.y);
view->paint(&gc, dirtyRect);
gc.restore();
return S_OK;
}
// IUnknown -------------------------------------------------------------------
HRESULT STDMETHODCALLTYPE WebFrame::QueryInterface(REFIID riid, void** ppvObject)
{
*ppvObject = 0;
if (IsEqualGUID(riid, __uuidof(WebFrame)))
*ppvObject = this;
else if (IsEqualGUID(riid, IID_IUnknown))
*ppvObject = static_cast<IWebFrame*>(this);
else if (IsEqualGUID(riid, IID_IWebFrame))
*ppvObject = static_cast<IWebFrame*>(this);
else if (IsEqualGUID(riid, IID_IWebFramePrivate))
*ppvObject = static_cast<IWebFramePrivate*>(this);
else if (IsEqualGUID(riid, IID_IWebDocumentText))
*ppvObject = static_cast<IWebDocumentText*>(this);
else
return E_NOINTERFACE;
AddRef();
return S_OK;
}
ULONG STDMETHODCALLTYPE WebFrame::AddRef(void)
{
return ++m_refCount;
}
ULONG STDMETHODCALLTYPE WebFrame::Release(void)
{
ULONG newRef = --m_refCount;
if (!newRef)
delete(this);
return newRef;
}
// IWebFrame -------------------------------------------------------------------
HRESULT STDMETHODCALLTYPE WebFrame::name(
/* [retval][out] */ BSTR* frameName)
{
if (!frameName) {
ASSERT_NOT_REACHED();
return E_POINTER;
}
*frameName = 0;
Frame* coreFrame = core(this);
if (!coreFrame)
return E_FAIL;
*frameName = BString(coreFrame->tree()->uniqueName()).release();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebFrame::webView(
/* [retval][out] */ IWebView** view)
{
*view = 0;
if (!d->webView)
return E_FAIL;
*view = d->webView;
(*view)->AddRef();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebFrame::frameView(
/* [retval][out] */ IWebFrameView** /*view*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE WebFrame::DOMDocument(
/* [retval][out] */ IDOMDocument** result)
{
if (!result) {
ASSERT_NOT_REACHED();
return E_POINTER;
}
*result = 0;
if (Frame* coreFrame = core(this))
if (Document* document = coreFrame->document())
*result = DOMDocument::createInstance(document);
return *result ? S_OK : E_FAIL;
}
HRESULT WebFrame::DOMWindow(/* [retval][out] */ IDOMWindow** window)
{
if (!window) {
ASSERT_NOT_REACHED();
return E_POINTER;
}
*window = 0;
if (Frame* coreFrame = core(this)) {
if (WebCore::DOMWindow* coreWindow = coreFrame->domWindow())
*window = ::DOMWindow::createInstance(coreWindow);
}
return *window ? S_OK : E_FAIL;
}
HRESULT STDMETHODCALLTYPE WebFrame::frameElement(
/* [retval][out] */ IDOMHTMLElement** frameElement)
{
if (!frameElement)
return E_POINTER;
*frameElement = 0;
Frame* coreFrame = core(this);
if (!coreFrame)
return E_FAIL;
COMPtr<IDOMElement> domElement(AdoptCOM, DOMElement::createInstance(coreFrame->ownerElement()));
COMPtr<IDOMHTMLElement> htmlElement(Query, domElement);
if (!htmlElement)
return E_FAIL;
return htmlElement.copyRefTo(frameElement);
}
HRESULT STDMETHODCALLTYPE WebFrame::currentForm(
/* [retval][out] */ IDOMElement **currentForm)
{
if (!currentForm) {
ASSERT_NOT_REACHED();
return E_POINTER;
}
*currentForm = 0;
if (Frame* coreFrame = core(this)) {
if (HTMLFormElement* formElement = coreFrame->selection()->currentForm())
*currentForm = DOMElement::createInstance(formElement);
}
return *currentForm ? S_OK : E_FAIL;
}
JSGlobalContextRef STDMETHODCALLTYPE WebFrame::globalContext()
{
Frame* coreFrame = core(this);
if (!coreFrame)
return 0;
return toGlobalRef(coreFrame->script()->globalObject(mainThreadNormalWorld())->globalExec());
}
JSGlobalContextRef WebFrame::globalContextForScriptWorld(IWebScriptWorld* iWorld)
{
Frame* coreFrame = core(this);
if (!coreFrame)
return 0;
COMPtr<WebScriptWorld> world(Query, iWorld);
if (!world)
return 0;
return toGlobalRef(coreFrame->script()->globalObject(world->world())->globalExec());
}
HRESULT STDMETHODCALLTYPE WebFrame::loadRequest(
/* [in] */ IWebURLRequest* request)
{
COMPtr<WebMutableURLRequest> requestImpl;
HRESULT hr = request->QueryInterface(&requestImpl);
if (FAILED(hr))
return hr;
Frame* coreFrame = core(this);
if (!coreFrame)
return E_FAIL;
coreFrame->loader()->load(requestImpl->resourceRequest(), false);
return S_OK;
}
void WebFrame::loadData(PassRefPtr<WebCore::SharedBuffer> data, BSTR mimeType, BSTR textEncodingName, BSTR baseURL, BSTR failingURL)
{
String mimeTypeString(mimeType, SysStringLen(mimeType));
if (!mimeType)
mimeTypeString = "text/html";
String encodingString(textEncodingName, SysStringLen(textEncodingName));
// FIXME: We should really be using MarshallingHelpers::BSTRToKURL here,
// but that would turn a null BSTR into a null KURL, and we crash inside of
// WebCore if we use a null KURL in constructing the ResourceRequest.
KURL baseKURL = KURL(KURL(), String(baseURL ? baseURL : L"", SysStringLen(baseURL)));
KURL failingKURL = MarshallingHelpers::BSTRToKURL(failingURL);
ResourceRequest request(baseKURL);
SubstituteData substituteData(data, mimeTypeString, encodingString, failingKURL);
// This method is only called from IWebFrame methods, so don't ASSERT that the Frame pointer isn't null.
if (Frame* coreFrame = core(this))
coreFrame->loader()->load(request, substituteData, false);
}
HRESULT STDMETHODCALLTYPE WebFrame::loadData(
/* [in] */ IStream* data,
/* [in] */ BSTR mimeType,
/* [in] */ BSTR textEncodingName,
/* [in] */ BSTR url)
{
RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create();
STATSTG stat;
if (SUCCEEDED(data->Stat(&stat, STATFLAG_NONAME))) {
if (!stat.cbSize.HighPart && stat.cbSize.LowPart) {
Vector<char> dataBuffer(stat.cbSize.LowPart);
ULONG read;
// FIXME: this does a needless copy, would be better to read right into the SharedBuffer
// or adopt the Vector or something.
if (SUCCEEDED(data->Read(dataBuffer.data(), static_cast<ULONG>(dataBuffer.size()), &read)))
sharedBuffer->append(dataBuffer.data(), static_cast<int>(dataBuffer.size()));
}
}
loadData(sharedBuffer, mimeType, textEncodingName, url, 0);
return S_OK;
}
HRESULT WebFrame::loadPlainTextString(
/* [in] */ BSTR string,
/* [in] */ BSTR url)
{
RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<char*>(string), sizeof(UChar) * SysStringLen(string));
BString plainTextMimeType(TEXT("text/plain"), 10);
BString utf16Encoding(TEXT("utf-16"), 6);
loadData(sharedBuffer.release(), plainTextMimeType, utf16Encoding, url, 0);
return S_OK;
}
void WebFrame::loadHTMLString(BSTR string, BSTR baseURL, BSTR unreachableURL)
{
RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<char*>(string), sizeof(UChar) * SysStringLen(string));
BString utf16Encoding(TEXT("utf-16"), 6);
loadData(sharedBuffer.release(), 0, utf16Encoding, baseURL, unreachableURL);
}
HRESULT STDMETHODCALLTYPE WebFrame::loadHTMLString(
/* [in] */ BSTR string,
/* [in] */ BSTR baseURL)
{
loadHTMLString(string, baseURL, 0);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebFrame::loadAlternateHTMLString(
/* [in] */ BSTR str,
/* [in] */ BSTR baseURL,
/* [in] */ BSTR unreachableURL)
{
loadHTMLString(str, baseURL, unreachableURL);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebFrame::loadArchive(
/* [in] */ IWebArchive* /*archive*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
static inline WebDataSource *getWebDataSource(DocumentLoader* loader)
{
return loader ? static_cast<WebDocumentLoader*>(loader)->dataSource() : 0;
}
HRESULT STDMETHODCALLTYPE WebFrame::dataSource(
/* [retval][out] */ IWebDataSource** source)
{
if (!source) {
ASSERT_NOT_REACHED();
return E_POINTER;
}
*source = 0;
Frame* coreFrame = core(this);
if (!coreFrame)
return E_FAIL;
WebDataSource* webDataSource = getWebDataSource(coreFrame->loader()->documentLoader());
*source = webDataSource;
if (webDataSource)
webDataSource->AddRef();
return *source ? S_OK : E_FAIL;
}
HRESULT STDMETHODCALLTYPE WebFrame::provisionalDataSource(
/* [retval][out] */ IWebDataSource** source)
{
if (!source) {
ASSERT_NOT_REACHED();
return E_POINTER;
}
*source = 0;
Frame* coreFrame = core(this);
if (!coreFrame)
return E_FAIL;
WebDataSource* webDataSource = getWebDataSource(coreFrame->loader()->provisionalDocumentLoader());
*source = webDataSource;
if (webDataSource)
webDataSource->AddRef();
return *source ? S_OK : E_FAIL;
}
KURL WebFrame::url() const
{
Frame* coreFrame = core(this);
if (!coreFrame)
return KURL();
return coreFrame->document()->url();
}
HRESULT STDMETHODCALLTYPE WebFrame::stopLoading( void)
{
if (Frame* coreFrame = core(this))
coreFrame->loader()->stopAllLoaders();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebFrame::reload( void)
{
Frame* coreFrame = core(this);
if (!coreFrame)
return E_FAIL;
coreFrame->loader()->reload();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebFrame::findFrameNamed(
/* [in] */ BSTR name,
/* [retval][out] */ IWebFrame** frame)
{
if (!frame) {
ASSERT_NOT_REACHED();
return E_POINTER;
}
*frame = 0;
Frame* coreFrame = core(this);
if (!coreFrame)
return E_FAIL;
Frame* foundFrame = coreFrame->tree()->find(AtomicString(name, SysStringLen(name)));
if (!foundFrame)
return S_OK;
WebFrame* foundWebFrame = kit(foundFrame);
if (!foundWebFrame)
return E_FAIL;
return foundWebFrame->QueryInterface(IID_IWebFrame, (void**)frame);
}
HRESULT STDMETHODCALLTYPE WebFrame::parentFrame(
/* [retval][out] */ IWebFrame** frame)
{
HRESULT hr = S_OK;
*frame = 0;
if (Frame* coreFrame = core(this))
if (WebFrame* webFrame = kit(coreFrame->tree()->parent()))
hr = webFrame->QueryInterface(IID_IWebFrame, (void**) frame);
return hr;
}
class EnumChildFrames : public IEnumVARIANT
{
public:
EnumChildFrames(Frame* f) : m_refCount(1), m_frame(f), m_curChild(f ? f->tree()->firstChild() : 0) { }
virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppvObject)
{
*ppvObject = 0;
if (IsEqualGUID(riid, IID_IUnknown) || IsEqualGUID(riid, IID_IEnumVARIANT))
*ppvObject = this;
else
return E_NOINTERFACE;
AddRef();
return S_OK;
}
virtual ULONG STDMETHODCALLTYPE AddRef(void)
{
return ++m_refCount;
}
virtual ULONG STDMETHODCALLTYPE Release(void)
{
ULONG newRef = --m_refCount;
if (!newRef)
delete(this);
return newRef;
}
virtual HRESULT STDMETHODCALLTYPE Next(ULONG celt, VARIANT *rgVar, ULONG *pCeltFetched)
{
if (pCeltFetched)
*pCeltFetched = 0;
if (!rgVar)
return E_POINTER;
VariantInit(rgVar);
if (!celt || celt > 1)
return S_FALSE;
if (!m_frame || !m_curChild)
return S_FALSE;
WebFrame* webFrame = kit(m_curChild);
IUnknown* unknown;
HRESULT hr = webFrame->QueryInterface(IID_IUnknown, (void**)&unknown);
if (FAILED(hr))
return hr;
V_VT(rgVar) = VT_UNKNOWN;
V_UNKNOWN(rgVar) = unknown;
m_curChild = m_curChild->tree()->nextSibling();
if (pCeltFetched)
*pCeltFetched = 1;
return S_OK;
}
virtual HRESULT STDMETHODCALLTYPE Skip(ULONG celt)
{
if (!m_frame)
return S_FALSE;
for (unsigned i = 0; i < celt && m_curChild; i++)
m_curChild = m_curChild->tree()->nextSibling();
return m_curChild ? S_OK : S_FALSE;
}
virtual HRESULT STDMETHODCALLTYPE Reset(void)
{
if (!m_frame)
return S_FALSE;
m_curChild = m_frame->tree()->firstChild();
return S_OK;
}
virtual HRESULT STDMETHODCALLTYPE Clone(IEnumVARIANT**)
{
return E_NOTIMPL;
}
private:
ULONG m_refCount;
Frame* m_frame;
Frame* m_curChild;
};
HRESULT STDMETHODCALLTYPE WebFrame::childFrames(
/* [retval][out] */ IEnumVARIANT **enumFrames)
{
if (!enumFrames)
return E_POINTER;
*enumFrames = new EnumChildFrames(core(this));
return S_OK;
}
// IWebFramePrivate ------------------------------------------------------
HRESULT WebFrame::renderTreeAsExternalRepresentation(BOOL forPrinting, BSTR *result)
{
if (!result)
return E_POINTER;
Frame* coreFrame = core(this);
if (!coreFrame)
return E_FAIL;
*result = BString(externalRepresentation(coreFrame, forPrinting ? RenderAsTextPrintingMode : RenderAsTextBehaviorNormal)).release();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebFrame::counterValueForElementById(
/* [in] */ BSTR id, /* [retval][out] */ BSTR *result)
{
if (!result)
return E_POINTER;
Frame* coreFrame = core(this);
if (!coreFrame)
return E_FAIL;
String coreId = String(id, SysStringLen(id));
Element* element = coreFrame->document()->getElementById(coreId);
if (!element)
return E_FAIL;
*result = BString(counterValueForElement(element)).release();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebFrame::pageNumberForElementById(
/* [in] */ BSTR id,
/* [in] */ float pageWidthInPixels,
/* [in] */ float pageHeightInPixels,
/* [retval][out] */ int* result)
{
if (!result)
return E_POINTER;
Frame* coreFrame = core(this);
if (!coreFrame)
return E_FAIL;
String coreId = String(id, SysStringLen(id));
Element* element = coreFrame->document()->getElementById(coreId);
if (!element)
return E_FAIL;
*result = PrintContext::pageNumberForElement(element, FloatSize(pageWidthInPixels, pageHeightInPixels));
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebFrame::numberOfPages(
/* [in] */ float pageWidthInPixels,
/* [in] */ float pageHeightInPixels,
/* [retval][out] */ int* result)
{
if (!result)
return E_POINTER;
Frame* coreFrame = core(this);
if (!coreFrame)
return E_FAIL;
*result = PrintContext::numberOfPages(coreFrame, FloatSize(pageWidthInPixels, pageHeightInPixels));
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebFrame::scrollOffset(
/* [retval][out] */ SIZE* offset)
{
if (!offset) {
ASSERT_NOT_REACHED();
return E_POINTER;
}
Frame* coreFrame = core(this);
if (!coreFrame)
return E_FAIL;
FrameView* view = coreFrame->view();
if (!view)
return E_FAIL;
*offset = view->scrollOffset();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebFrame::layout()
{
Frame* coreFrame = core(this);
if (!coreFrame)
return E_FAIL;
FrameView* view = coreFrame->view();
if (!view)
return E_FAIL;
view->layout();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebFrame::firstLayoutDone(
/* [retval][out] */ BOOL* result)
{
if (!result) {
ASSERT_NOT_REACHED();
return E_POINTER;
}
*result = 0;
Frame* coreFrame = core(this);
if (!coreFrame)
return E_FAIL;
*result = coreFrame->loader()->stateMachine()->firstLayoutDone();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebFrame::loadType(
/* [retval][out] */ WebFrameLoadType* type)
{
if (!type) {
ASSERT_NOT_REACHED();
return E_POINTER;
}
*type = (WebFrameLoadType)0;
Frame* coreFrame = core(this);
if (!coreFrame)
return E_FAIL;
*type = (WebFrameLoadType)coreFrame->loader()->loadType();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebFrame::pendingFrameUnloadEventCount(
/* [retval][out] */ UINT* result)
{
if (!result) {
ASSERT_NOT_REACHED();
return E_POINTER;
}
*result = 0;
Frame* coreFrame = core(this);
if (!coreFrame)
return E_FAIL;
*result = coreFrame->domWindow()->pendingUnloadEventListeners();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebFrame::unused2()
{
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE WebFrame::hasSpellingMarker(
/* [in] */ UINT from,
/* [in] */ UINT length,
/* [retval][out] */ BOOL* result)
{
Frame* coreFrame = core(this);
if (!coreFrame)
return E_FAIL;
*result = coreFrame->editor()->selectionStartHasMarkerFor(DocumentMarker::Spelling, from, length);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebFrame::clearOpener()
{
HRESULT hr = S_OK;
if (Frame* coreFrame = core(this))
coreFrame->loader()->setOpener(0);
return hr;
}
HRESULT WebFrame::setTextDirection(BSTR direction)
{
Frame* coreFrame = core(this);
if (!coreFrame || !coreFrame->editor())
return E_FAIL;
String directionString(direction, SysStringLen(direction));
if (directionString == "auto")
coreFrame->editor()->setBaseWritingDirection(NaturalWritingDirection);
else if (directionString == "ltr")
coreFrame->editor()->setBaseWritingDirection(LeftToRightWritingDirection);
else if (directionString == "rtl")
coreFrame->editor()->setBaseWritingDirection(RightToLeftWritingDirection);
return S_OK;
}
// IWebDocumentText -----------------------------------------------------------
HRESULT STDMETHODCALLTYPE WebFrame::supportsTextEncoding(
/* [retval][out] */ BOOL* result)
{
*result = FALSE;
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE WebFrame::selectedString(
/* [retval][out] */ BSTR* result)
{
*result = 0;
Frame* coreFrame = core(this);
if (!coreFrame)
return E_FAIL;
String text = coreFrame->displayStringModifiedByEncoding(coreFrame->editor()->selectedText());
*result = BString(text).release();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebFrame::selectAll()
{
Frame* coreFrame = core(this);
if (!coreFrame)
return E_FAIL;
if (!coreFrame->editor()->command("SelectAll").execute())
return E_FAIL;
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebFrame::deselectAll()
{
return E_NOTIMPL;
}
// WebFrame ---------------------------------------------------------------
PassRefPtr<Frame> WebFrame::init(IWebView* webView, Page* page, HTMLFrameOwnerElement* ownerElement)
{
webView->QueryInterface(&d->webView);
d->webView->Release(); // don't hold the extra ref
HWND viewWindow;
d->webView->viewWindow((OLE_HANDLE*)&viewWindow);
this->AddRef(); // We release this ref in frameLoaderDestroyed()
RefPtr<Frame> frame = Frame::create(page, ownerElement, this);
d->frame = frame.get();
return frame.release();
}
Frame* WebFrame::impl()
{
return d->frame;
}
void WebFrame::invalidate()
{
Frame* coreFrame = core(this);
ASSERT(coreFrame);
if (Document* document = coreFrame->document())
document->recalcStyle(Node::Force);
}
HRESULT WebFrame::inViewSourceMode(BOOL* flag)
{
if (!flag) {
ASSERT_NOT_REACHED();
return E_POINTER;
}
*flag = FALSE;
Frame* coreFrame = core(this);
if (!coreFrame)
return E_FAIL;
*flag = coreFrame->inViewSourceMode() ? TRUE : FALSE;
return S_OK;
}
HRESULT WebFrame::setInViewSourceMode(BOOL flag)
{
Frame* coreFrame = core(this);
if (!coreFrame)
return E_FAIL;
coreFrame->setInViewSourceMode(!!flag);
return S_OK;
}
HRESULT WebFrame::elementWithName(BSTR name, IDOMElement* form, IDOMElement** element)
{
if (!form)
return E_INVALIDARG;
HTMLFormElement* formElement = formElementFromDOMElement(form);
if (formElement) {
const Vector<FormAssociatedElement*>& elements = formElement->associatedElements();
AtomicString targetName((UChar*)name, SysStringLen(name));
for (unsigned int i = 0; i < elements.size(); i++) {
if (!elements[i]->isFormControlElement())
continue;
HTMLFormControlElement* elt = static_cast<HTMLFormControlElement*>(elements[i]);
// Skip option elements, other duds
if (elt->name() == targetName) {
*element = DOMElement::createInstance(elt);
return S_OK;
}
}
}
return E_FAIL;
}
HRESULT WebFrame::formForElement(IDOMElement* element, IDOMElement** form)
{
if (!element)
return E_INVALIDARG;
HTMLInputElement *inputElement = inputElementFromDOMElement(element);
if (!inputElement)
return E_FAIL;
HTMLFormElement *formElement = inputElement->form();
if (!formElement)
return E_FAIL;
*form = DOMElement::createInstance(formElement);
return S_OK;
}
HRESULT WebFrame::elementDoesAutoComplete(IDOMElement *element, BOOL *result)
{
*result = false;
if (!element)
return E_INVALIDARG;
HTMLInputElement *inputElement = inputElementFromDOMElement(element);
if (!inputElement)
*result = false;
else
*result = inputElement->isTextField() && !inputElement->isPasswordField() && inputElement->shouldAutocomplete();
return S_OK;
}
HRESULT WebFrame::pauseAnimation(BSTR animationName, IDOMNode* node, double secondsFromNow, BOOL* animationWasRunning)
{
if (!node || !animationWasRunning)
return E_POINTER;
*animationWasRunning = FALSE;
Frame* frame = core(this);
if (!frame)
return E_FAIL;
AnimationController* controller = frame->animation();
if (!controller)
return E_FAIL;
COMPtr<DOMNode> domNode(Query, node);
if (!domNode)
return E_FAIL;
*animationWasRunning = controller->pauseAnimationAtTime(domNode->node()->renderer(), String(animationName, SysStringLen(animationName)), secondsFromNow);
return S_OK;
}
HRESULT WebFrame::pauseTransition(BSTR propertyName, IDOMNode* node, double secondsFromNow, BOOL* transitionWasRunning)
{
if (!node || !transitionWasRunning)
return E_POINTER;
*transitionWasRunning = FALSE;
Frame* frame = core(this);
if (!frame)
return E_FAIL;
AnimationController* controller = frame->animation();
if (!controller)
return E_FAIL;
COMPtr<DOMNode> domNode(Query, node);
if (!domNode)
return E_FAIL;
*transitionWasRunning = controller->pauseTransitionAtTime(domNode->node()->renderer(), String(propertyName, SysStringLen(propertyName)), secondsFromNow);
return S_OK;
}
HRESULT WebFrame::visibleContentRect(RECT* rect)
{
if (!rect)
return E_POINTER;
SetRectEmpty(rect);
Frame* frame = core(this);
if (!frame)
return E_FAIL;
FrameView* view = frame->view();
if (!view)
return E_FAIL;
*rect = view->visibleContentRect(false);
return S_OK;
}
HRESULT WebFrame::numberOfActiveAnimations(UINT* number)
{
if (!number)
return E_POINTER;
*number = 0;
Frame* frame = core(this);
if (!frame)
return E_FAIL;
AnimationController* controller = frame->animation();
if (!controller)
return E_FAIL;
*number = controller->numberOfActiveAnimations(frame->document());
return S_OK;
}
HRESULT WebFrame::suspendAnimations()
{
Frame* frame = core(this);
if (!frame)
return E_FAIL;
frame->animation()->suspendAnimations();
return S_OK;
}
HRESULT WebFrame::resumeAnimations()
{
Frame* frame = core(this);
if (!frame)
return E_FAIL;
frame->animation()->resumeAnimations();
return S_OK;
}
HRESULT WebFrame::isDisplayingStandaloneImage(BOOL* result)
{
if (!result)
return E_POINTER;
*result = FALSE;
Frame* frame = core(this);
if (!frame)
return E_FAIL;
Document* document = frame->document();
*result = document && document->isImageDocument();
return S_OK;
}
HRESULT WebFrame::allowsFollowingLink(BSTR url, BOOL* result)
{
if (!result)
return E_POINTER;
*result = TRUE;
Frame* frame = core(this);
if (!frame)
return E_FAIL;
*result = frame->document()->securityOrigin()->canDisplay(MarshallingHelpers::BSTRToKURL(url));
return S_OK;
}
HRESULT WebFrame::controlsInForm(IDOMElement* form, IDOMElement** controls, int* cControls)
{
if (!form)
return E_INVALIDARG;
HTMLFormElement* formElement = formElementFromDOMElement(form);
if (!formElement)
return E_FAIL;
int inCount = *cControls;
int count = (int) formElement->associatedElements().size();
*cControls = count;
if (!controls)
return S_OK;
if (inCount < count)
return E_FAIL;
*cControls = 0;
const Vector<FormAssociatedElement*>& elements = formElement->associatedElements();
for (int i = 0; i < count; i++) {
if (elements.at(i)->isEnumeratable()) { // Skip option elements, other duds
controls[*cControls] = DOMElement::createInstance(toHTMLElement(elements.at(i)));
(*cControls)++;
}
}
return S_OK;
}
HRESULT WebFrame::elementIsPassword(IDOMElement *element, bool *result)
{
HTMLInputElement* inputElement = inputElementFromDOMElement(element);
*result = inputElement && inputElement->isPasswordField();
return S_OK;
}
HRESULT WebFrame::searchForLabelsBeforeElement(const BSTR* labels, unsigned cLabels, IDOMElement* beforeElement, unsigned* outResultDistance, BOOL* outResultIsInCellAbove, BSTR* result)
{
if (!result) {
ASSERT_NOT_REACHED();
return E_POINTER;
}
if (outResultDistance)
*outResultDistance = 0;
if (outResultIsInCellAbove)
*outResultIsInCellAbove = FALSE;
*result = 0;
if (!cLabels)
return S_OK;
if (cLabels < 1)
return E_INVALIDARG;
Frame* coreFrame = core(this);
if (!coreFrame)
return E_FAIL;
Vector<String> labelStrings(cLabels);
for (int i=0; i<cLabels; i++)
labelStrings[i] = String(labels[i], SysStringLen(labels[i]));
Element *coreElement = elementFromDOMElement(beforeElement);
if (!coreElement)
return E_FAIL;
size_t resultDistance;
bool resultIsInCellAbove;
String label = coreFrame->searchForLabelsBeforeElement(labelStrings, coreElement, &resultDistance, &resultIsInCellAbove);
*result = SysAllocStringLen(label.characters(), label.length());
if (label.length() && !*result)
return E_OUTOFMEMORY;
if (outResultDistance)
*outResultDistance = resultDistance;
if (outResultIsInCellAbove)
*outResultIsInCellAbove = resultIsInCellAbove;
return S_OK;
}
HRESULT WebFrame::matchLabelsAgainstElement(const BSTR* labels, int cLabels, IDOMElement* againstElement, BSTR* result)
{
if (!result) {
ASSERT_NOT_REACHED();
return E_POINTER;
}
*result = 0;
if (!cLabels)
return S_OK;
if (cLabels < 1)
return E_INVALIDARG;
Frame* coreFrame = core(this);
if (!coreFrame)
return E_FAIL;
Vector<String> labelStrings(cLabels);
for (int i=0; i<cLabels; i++)
labelStrings[i] = String(labels[i], SysStringLen(labels[i]));
Element *coreElement = elementFromDOMElement(againstElement);
if (!coreElement)
return E_FAIL;
String label = coreFrame->matchLabelsAgainstElement(labelStrings, coreElement);
*result = SysAllocStringLen(label.characters(), label.length());
if (label.length() && !*result)
return E_OUTOFMEMORY;
return S_OK;
}
HRESULT WebFrame::canProvideDocumentSource(bool* result)
{
HRESULT hr = S_OK;
*result = false;
COMPtr<IWebDataSource> dataSource;
hr = WebFrame::dataSource(&dataSource);
if (FAILED(hr))
return hr;
COMPtr<IWebURLResponse> urlResponse;
hr = dataSource->response(&urlResponse);
if (SUCCEEDED(hr) && urlResponse) {
BSTR mimeTypeBStr;
if (SUCCEEDED(urlResponse->MIMEType(&mimeTypeBStr))) {
String mimeType(mimeTypeBStr, SysStringLen(mimeTypeBStr));
*result = mimeType == "text/html" || WebCore::DOMImplementation::isXMLMIMEType(mimeType);
SysFreeString(mimeTypeBStr);
}
}
return hr;
}
HRESULT STDMETHODCALLTYPE WebFrame::layerTreeAsText(BSTR* result)
{
if (!result)
return E_POINTER;
*result = 0;
Frame* frame = core(this);
if (!frame)
return E_FAIL;
String text = frame->layerTreeAsText();
*result = BString(text).release();
return S_OK;
}
void WebFrame::frameLoaderDestroyed()
{
// The FrameLoader going away is equivalent to the Frame going away,
// so we now need to clear our frame pointer.
d->frame = 0;
this->Release();
}
void WebFrame::makeRepresentation(DocumentLoader*)
{
notImplemented();
}
void WebFrame::forceLayoutForNonHTML()
{
notImplemented();
}
void WebFrame::setCopiesOnScroll()
{
notImplemented();
}
void WebFrame::detachedFromParent2()
{
notImplemented();
}
void WebFrame::detachedFromParent3()
{
notImplemented();
}
void WebFrame::cancelPolicyCheck()
{
if (d->m_policyListener) {
d->m_policyListener->invalidate();
d->m_policyListener = 0;
}
d->m_policyFunction = 0;
}
void WebFrame::dispatchWillSendSubmitEvent(PassRefPtr<WebCore::FormState>)
{
}
void WebFrame::dispatchWillSubmitForm(FramePolicyFunction function, PassRefPtr<FormState> formState)
{
Frame* coreFrame = core(this);
ASSERT(coreFrame);
COMPtr<IWebFormDelegate> formDelegate;
if (FAILED(d->webView->formDelegate(&formDelegate))) {
(coreFrame->loader()->policyChecker()->*function)(PolicyUse);
return;
}
COMPtr<IDOMElement> formElement(AdoptCOM, DOMElement::createInstance(formState->form()));
HashMap<String, String> formValuesMap;
const StringPairVector& textFieldValues = formState->textFieldValues();
size_t size = textFieldValues.size();
for (size_t i = 0; i < size; ++i)
formValuesMap.add(textFieldValues[i].first, textFieldValues[i].second);
COMPtr<IPropertyBag> formValuesPropertyBag(AdoptCOM, COMPropertyBag<String>::createInstance(formValuesMap));
COMPtr<WebFrame> sourceFrame(kit(formState->sourceDocument()->frame()));
if (SUCCEEDED(formDelegate->willSubmitForm(this, sourceFrame.get(), formElement.get(), formValuesPropertyBag.get(), setUpPolicyListener(function).get())))
return;
// FIXME: Add a sane default implementation
(coreFrame->loader()->policyChecker()->*function)(PolicyUse);
}
void WebFrame::revertToProvisionalState(DocumentLoader*)
{
notImplemented();
}
void WebFrame::setMainFrameDocumentReady(bool)
{
notImplemented();
}
void WebFrame::willChangeTitle(DocumentLoader*)
{
notImplemented();
}
void WebFrame::didChangeTitle(DocumentLoader*)
{
notImplemented();
}
void WebFrame::didChangeIcons(DocumentLoader*)
{
notImplemented();
}
bool WebFrame::canHandleRequest(const ResourceRequest& request) const
{
return WebView::canHandleRequest(request);
}
bool WebFrame::canShowMIMETypeAsHTML(const String& /*MIMEType*/) const
{
notImplemented();
return true;
}
bool WebFrame::canShowMIMEType(const String& /*MIMEType*/) const
{
notImplemented();
return true;
}
bool WebFrame::representationExistsForURLScheme(const String& /*URLScheme*/) const
{
notImplemented();
return false;
}
String WebFrame::generatedMIMETypeForURLScheme(const String& /*URLScheme*/) const
{
notImplemented();
ASSERT_NOT_REACHED();
return String();
}
void WebFrame::frameLoadCompleted()
{
}
void WebFrame::restoreViewState()
{
}
void WebFrame::provisionalLoadStarted()
{
notImplemented();
}
bool WebFrame::shouldTreatURLAsSameAsCurrent(const KURL&) const
{
notImplemented();
return false;
}
void WebFrame::addHistoryItemForFragmentScroll()
{
notImplemented();
}
void WebFrame::didFinishLoad()
{
notImplemented();
}
void WebFrame::prepareForDataSourceReplacement()
{
notImplemented();
}
String WebFrame::userAgent(const KURL& url)
{
return d->webView->userAgentForKURL(url);
}
void WebFrame::saveViewStateToItem(HistoryItem*)
{
}
ResourceError WebFrame::cancelledError(const ResourceRequest& request)
{
// FIXME: Need ChickenCat to include CFNetwork/CFURLError.h to get these values
// Alternatively, we could create our own error domain/codes.
return ResourceError(String(WebURLErrorDomain), -999, request.url().string(), String());
}
ResourceError WebFrame::blockedError(const ResourceRequest& request)
{
// FIXME: Need to implement the String descriptions for errors in the WebKitErrorDomain and have them localized
return ResourceError(String(WebKitErrorDomain), WebKitErrorCannotUseRestrictedPort, request.url().string(), String());
}
ResourceError WebFrame::cannotShowURLError(const ResourceRequest& request)
{
// FIXME: Need to implement the String descriptions for errors in the WebKitErrorDomain and have them localized
return ResourceError(String(WebKitErrorDomain), WebKitErrorCannotShowURL, request.url().string(), String());
}
ResourceError WebFrame::interruptedForPolicyChangeError(const ResourceRequest& request)
{
// FIXME: Need to implement the String descriptions for errors in the WebKitErrorDomain and have them localized
return ResourceError(String(WebKitErrorDomain), WebKitErrorFrameLoadInterruptedByPolicyChange, request.url().string(), String());
}
ResourceError WebFrame::cannotShowMIMETypeError(const ResourceResponse&)
{
notImplemented();
return ResourceError();
}
ResourceError WebFrame::fileDoesNotExistError(const ResourceResponse&)
{
notImplemented();
return ResourceError();
}
ResourceError WebFrame::pluginWillHandleLoadError(const ResourceResponse& response)
{
return ResourceError(String(WebKitErrorDomain), WebKitErrorPlugInWillHandleLoad, response.url().string(), String());
}
bool WebFrame::shouldFallBack(const ResourceError& error)
{
if (error.errorCode() == WebURLErrorCancelled && error.domain() == String(WebURLErrorDomain))
return false;
if (error.errorCode() == WebKitErrorPlugInWillHandleLoad && error.domain() == String(WebKitErrorDomain))
return false;
return true;
}
COMPtr<WebFramePolicyListener> WebFrame::setUpPolicyListener(WebCore::FramePolicyFunction function)
{
// FIXME: <rdar://5634381> We need to support multiple active policy listeners.
if (d->m_policyListener)
d->m_policyListener->invalidate();
Frame* coreFrame = core(this);
ASSERT(coreFrame);
d->m_policyListener.adoptRef(WebFramePolicyListener::createInstance(coreFrame));
d->m_policyFunction = function;
return d->m_policyListener;
}
void WebFrame::receivedPolicyDecision(PolicyAction action)
{
ASSERT(d->m_policyListener);
ASSERT(d->m_policyFunction);
FramePolicyFunction function = d->m_policyFunction;
d->m_policyListener = 0;
d->m_policyFunction = 0;
Frame* coreFrame = core(this);
ASSERT(coreFrame);
(coreFrame->loader()->policyChecker()->*function)(action);
}
void WebFrame::dispatchDecidePolicyForResponse(FramePolicyFunction function, const ResourceResponse& response, const ResourceRequest& request)
{
Frame* coreFrame = core(this);
ASSERT(coreFrame);
COMPtr<IWebPolicyDelegate> policyDelegate;
if (FAILED(d->webView->policyDelegate(&policyDelegate)))
policyDelegate = DefaultPolicyDelegate::sharedInstance();
COMPtr<IWebURLRequest> urlRequest(AdoptCOM, WebMutableURLRequest::createInstance(request));
if (SUCCEEDED(policyDelegate->decidePolicyForMIMEType(d->webView, BString(response.mimeType()), urlRequest.get(), this, setUpPolicyListener(function).get())))
return;
(coreFrame->loader()->policyChecker()->*function)(PolicyUse);
}
void WebFrame::dispatchDecidePolicyForNewWindowAction(FramePolicyFunction function, const NavigationAction& action, const ResourceRequest& request, PassRefPtr<FormState> formState, const String& frameName)
{
Frame* coreFrame = core(this);
ASSERT(coreFrame);
COMPtr<IWebPolicyDelegate> policyDelegate;
if (FAILED(d->webView->policyDelegate(&policyDelegate)))
policyDelegate = DefaultPolicyDelegate::sharedInstance();
COMPtr<IWebURLRequest> urlRequest(AdoptCOM, WebMutableURLRequest::createInstance(request));
COMPtr<WebActionPropertyBag> actionInformation(AdoptCOM, WebActionPropertyBag::createInstance(action, formState ? formState->form() : 0, coreFrame));
if (SUCCEEDED(policyDelegate->decidePolicyForNewWindowAction(d->webView, actionInformation.get(), urlRequest.get(), BString(frameName), setUpPolicyListener(function).get())))
return;
(coreFrame->loader()->policyChecker()->*function)(PolicyUse);
}
void WebFrame::dispatchDecidePolicyForNavigationAction(FramePolicyFunction function, const NavigationAction& action, const ResourceRequest& request, PassRefPtr<FormState> formState)
{
Frame* coreFrame = core(this);
ASSERT(coreFrame);
COMPtr<IWebPolicyDelegate> policyDelegate;
if (FAILED(d->webView->policyDelegate(&policyDelegate)))
policyDelegate = DefaultPolicyDelegate::sharedInstance();
COMPtr<IWebURLRequest> urlRequest(AdoptCOM, WebMutableURLRequest::createInstance(request));
COMPtr<WebActionPropertyBag> actionInformation(AdoptCOM, WebActionPropertyBag::createInstance(action, formState ? formState->form() : 0, coreFrame));
if (SUCCEEDED(policyDelegate->decidePolicyForNavigationAction(d->webView, actionInformation.get(), urlRequest.get(), this, setUpPolicyListener(function).get())))
return;
(coreFrame->loader()->policyChecker()->*function)(PolicyUse);
}
void WebFrame::dispatchUnableToImplementPolicy(const ResourceError& error)
{
COMPtr<IWebPolicyDelegate> policyDelegate;
if (FAILED(d->webView->policyDelegate(&policyDelegate)))
policyDelegate = DefaultPolicyDelegate::sharedInstance();
COMPtr<IWebError> webError(AdoptCOM, WebError::createInstance(error));
policyDelegate->unableToImplementPolicyWithError(d->webView, webError.get(), this);
}
void WebFrame::download(ResourceHandle* handle, const ResourceRequest& request, const ResourceResponse& response)
{
COMPtr<IWebDownloadDelegate> downloadDelegate;
COMPtr<IWebView> webView;
if (SUCCEEDED(this->webView(&webView))) {
if (FAILED(webView->downloadDelegate(&downloadDelegate))) {
// If the WebView doesn't successfully provide a download delegate we'll pass a null one
// into the WebDownload - which may or may not decide to use a DefaultDownloadDelegate
LOG_ERROR("Failed to get downloadDelegate from WebView");
downloadDelegate = 0;
}
}
// Its the delegate's job to ref the WebDownload to keep it alive - otherwise it will be destroyed
// when this method returns
COMPtr<WebDownload> download;
download.adoptRef(WebDownload::createInstance(handle, request, response, downloadDelegate.get()));
}
bool WebFrame::dispatchDidLoadResourceFromMemoryCache(DocumentLoader*, const ResourceRequest&, const ResourceResponse&, int /*length*/)
{
notImplemented();
return false;
}
void WebFrame::dispatchDidFailProvisionalLoad(const ResourceError& error)
{
COMPtr<IWebFrameLoadDelegate> frameLoadDelegate;
if (SUCCEEDED(d->webView->frameLoadDelegate(&frameLoadDelegate))) {
COMPtr<IWebError> webError;
webError.adoptRef(WebError::createInstance(error));
frameLoadDelegate->didFailProvisionalLoadWithError(d->webView, webError.get(), this);
}
}
void WebFrame::dispatchDidFailLoad(const ResourceError& error)
{
COMPtr<IWebFrameLoadDelegate> frameLoadDelegate;
if (SUCCEEDED(d->webView->frameLoadDelegate(&frameLoadDelegate))) {
COMPtr<IWebError> webError;
webError.adoptRef(WebError::createInstance(error));
frameLoadDelegate->didFailLoadWithError(d->webView, webError.get(), this);
}
}
void WebFrame::startDownload(const ResourceRequest& request, const String& /* suggestedName */)
{
d->webView->downloadURL(request.url());
}
PassRefPtr<Widget> WebFrame::createJavaAppletWidget(const IntSize& pluginSize, HTMLAppletElement* element, const KURL& /*baseURL*/, const Vector<String>& paramNames, const Vector<String>& paramValues)
{
RefPtr<PluginView> pluginView = PluginView::create(core(this), pluginSize, element, KURL(), paramNames, paramValues, "application/x-java-applet", false);
// Check if the plugin can be loaded successfully
if (pluginView->plugin() && pluginView->plugin()->load())
return pluginView;
COMPtr<IWebResourceLoadDelegate> resourceLoadDelegate;
if (FAILED(d->webView->resourceLoadDelegate(&resourceLoadDelegate)))
return pluginView;
COMPtr<CFDictionaryPropertyBag> userInfoBag = CFDictionaryPropertyBag::createInstance();
ResourceError resourceError(String(WebKitErrorDomain), WebKitErrorJavaUnavailable, String(), String());
COMPtr<IWebError> error(AdoptCOM, WebError::createInstance(resourceError, userInfoBag.get()));
resourceLoadDelegate->plugInFailedWithError(d->webView, error.get(), getWebDataSource(d->frame->loader()->documentLoader()));
return pluginView;
}
ObjectContentType WebFrame::objectContentType(const KURL& url, const String& mimeType, bool shouldPreferPlugInsForImages)
{
return WebCore::FrameLoader::defaultObjectContentType(url, mimeType, shouldPreferPlugInsForImages);
}
String WebFrame::overrideMediaType() const
{
notImplemented();
return String();
}
void WebFrame::dispatchDidClearWindowObjectInWorld(DOMWrapperWorld* world)
{
Frame* coreFrame = core(this);
ASSERT(coreFrame);
Settings* settings = coreFrame->settings();
if (!settings || !settings->isScriptEnabled())
return;
COMPtr<IWebFrameLoadDelegate> frameLoadDelegate;
if (FAILED(d->webView->frameLoadDelegate(&frameLoadDelegate)))
return;
COMPtr<IWebFrameLoadDelegatePrivate2> delegatePrivate(Query, frameLoadDelegate);
if (delegatePrivate && delegatePrivate->didClearWindowObjectForFrameInScriptWorld(d->webView, this, WebScriptWorld::findOrCreateWorld(world).get()) != E_NOTIMPL)
return;
if (world != mainThreadNormalWorld())
return;
JSContextRef context = toRef(coreFrame->script()->globalObject(world)->globalExec());
JSObjectRef windowObject = toRef(coreFrame->script()->globalObject(world));
ASSERT(windowObject);
if (FAILED(frameLoadDelegate->didClearWindowObject(d->webView, context, windowObject, this)))
frameLoadDelegate->windowScriptObjectAvailable(d->webView, context, windowObject);
}
void WebFrame::documentElementAvailable()
{
}
void WebFrame::didPerformFirstNavigation() const
{
COMPtr<IWebPreferences> preferences;
if (FAILED(d->webView->preferences(&preferences)))
return;
COMPtr<IWebPreferencesPrivate> preferencesPrivate(Query, preferences);
if (!preferencesPrivate)
return;
BOOL automaticallyDetectsCacheModel;
if (FAILED(preferencesPrivate->automaticallyDetectsCacheModel(&automaticallyDetectsCacheModel)))
return;
WebCacheModel cacheModel;
if (FAILED(preferences->cacheModel(&cacheModel)))
return;
if (automaticallyDetectsCacheModel && cacheModel < WebCacheModelDocumentBrowser)
preferences->setCacheModel(WebCacheModelDocumentBrowser);
}
void WebFrame::registerForIconNotification(bool listen)
{
d->webView->registerForIconNotification(listen);
}
static IntRect printerRect(HDC printDC)
{
return IntRect(0, 0,
GetDeviceCaps(printDC, PHYSICALWIDTH) - 2 * GetDeviceCaps(printDC, PHYSICALOFFSETX),
GetDeviceCaps(printDC, PHYSICALHEIGHT) - 2 * GetDeviceCaps(printDC, PHYSICALOFFSETY));
}
void WebFrame::setPrinting(bool printing, const FloatSize& pageSize, const FloatSize& originalPageSize, float maximumShrinkRatio, AdjustViewSizeOrNot adjustViewSize)
{
Frame* coreFrame = core(this);
ASSERT(coreFrame);
coreFrame->setPrinting(printing, pageSize, originalPageSize, maximumShrinkRatio, adjustViewSize ? AdjustViewSize : DoNotAdjustViewSize);
}
HRESULT STDMETHODCALLTYPE WebFrame::setInPrintingMode(
/* [in] */ BOOL value,
/* [in] */ HDC printDC)
{
if (m_inPrintingMode == !!value)
return S_OK;
Frame* coreFrame = core(this);
if (!coreFrame || !coreFrame->document())
return E_FAIL;
m_inPrintingMode = !!value;
// If we are a frameset just print with the layout we have onscreen, otherwise relayout
// according to the paper size
FloatSize minLayoutSize(0.0, 0.0);
FloatSize originalPageSize(0.0, 0.0);
if (m_inPrintingMode && !coreFrame->document()->isFrameSet()) {
if (!printDC) {
ASSERT_NOT_REACHED();
return E_POINTER;
}
const int desiredPixelsPerInch = 72;
IntRect printRect = printerRect(printDC);
int paperHorizontalPixelsPerInch = ::GetDeviceCaps(printDC, LOGPIXELSX);
int paperVerticalPixelsPerInch = ::GetDeviceCaps(printDC, LOGPIXELSY);
int paperWidth = printRect.width() * desiredPixelsPerInch / paperHorizontalPixelsPerInch;
int paperHeight = printRect.height() * desiredPixelsPerInch / paperVerticalPixelsPerInch;
originalPageSize = FloatSize(paperWidth, paperHeight);
Frame* coreFrame = core(this);
minLayoutSize = coreFrame->resizePageRectsKeepingRatio(originalPageSize, FloatSize(paperWidth * PrintingMinimumShrinkFactor, paperHeight * PrintingMinimumShrinkFactor));
}
setPrinting(m_inPrintingMode, minLayoutSize, originalPageSize, PrintingMaximumShrinkFactor / PrintingMinimumShrinkFactor, AdjustViewSize);
if (!m_inPrintingMode)
m_pageRects.clear();
return S_OK;
}
void WebFrame::headerAndFooterHeights(float* headerHeight, float* footerHeight)
{
if (headerHeight)
*headerHeight = 0;
if (footerHeight)
*footerHeight = 0;
float height = 0;
COMPtr<IWebUIDelegate> ui;
if (FAILED(d->webView->uiDelegate(&ui)))
return;
if (headerHeight && SUCCEEDED(ui->webViewHeaderHeight(d->webView, &height)))
*headerHeight = height;
if (footerHeight && SUCCEEDED(ui->webViewFooterHeight(d->webView, &height)))
*footerHeight = height;
}
IntRect WebFrame::printerMarginRect(HDC printDC)
{
IntRect emptyRect(0, 0, 0, 0);
COMPtr<IWebUIDelegate> ui;
if (FAILED(d->webView->uiDelegate(&ui)))
return emptyRect;
RECT rect;
if (FAILED(ui->webViewPrintingMarginRect(d->webView, &rect)))
return emptyRect;
rect.left = MulDiv(rect.left, ::GetDeviceCaps(printDC, LOGPIXELSX), 1000);
rect.top = MulDiv(rect.top, ::GetDeviceCaps(printDC, LOGPIXELSY), 1000);
rect.right = MulDiv(rect.right, ::GetDeviceCaps(printDC, LOGPIXELSX), 1000);
rect.bottom = MulDiv(rect.bottom, ::GetDeviceCaps(printDC, LOGPIXELSY), 1000);
return IntRect(rect.left, rect.top, (rect.right - rect.left), rect.bottom - rect.top);
}
const Vector<WebCore::IntRect>& WebFrame::computePageRects(HDC printDC)
{
ASSERT(m_inPrintingMode);
Frame* coreFrame = core(this);
ASSERT(coreFrame);
ASSERT(coreFrame->document());
if (!printDC)
return m_pageRects;
// adjust the page rect by the header and footer
float headerHeight = 0, footerHeight = 0;
headerAndFooterHeights(&headerHeight, &footerHeight);
IntRect pageRect = printerRect(printDC);
IntRect marginRect = printerMarginRect(printDC);
IntRect adjustedRect = IntRect(
pageRect.x() + marginRect.x(),
pageRect.y() + marginRect.y(),
pageRect.width() - marginRect.x() - marginRect.maxX(),
pageRect.height() - marginRect.y() - marginRect.maxY());
computePageRectsForFrame(coreFrame, adjustedRect, headerHeight, footerHeight, 1.0,m_pageRects, m_pageHeight);
return m_pageRects;
}
HRESULT STDMETHODCALLTYPE WebFrame::getPrintedPageCount(
/* [in] */ HDC printDC,
/* [retval][out] */ UINT *pageCount)
{
if (!pageCount || !printDC) {
ASSERT_NOT_REACHED();
return E_POINTER;
}
*pageCount = 0;
if (!m_inPrintingMode) {
ASSERT_NOT_REACHED();
return E_FAIL;
}
Frame* coreFrame = core(this);
if (!coreFrame || !coreFrame->document())
return E_FAIL;
const Vector<IntRect>& pages = computePageRects(printDC);
*pageCount = (UINT) pages.size();
return S_OK;
}
#if USE(CG)
void WebFrame::drawHeader(PlatformGraphicsContext* pctx, IWebUIDelegate* ui, const IntRect& pageRect, float headerHeight)
{
int x = pageRect.x();
int y = 0;
RECT headerRect = {x, y, x+pageRect.width(), y+static_cast<int>(headerHeight)};
ui->drawHeaderInRect(d->webView, &headerRect, static_cast<OLE_HANDLE>(reinterpret_cast<LONG64>(pctx)));
}
void WebFrame::drawFooter(PlatformGraphicsContext* pctx, IWebUIDelegate* ui, const IntRect& pageRect, UINT page, UINT pageCount, float headerHeight, float footerHeight)
{
int x = pageRect.x();
int y = max((int)headerHeight+pageRect.height(), m_pageHeight-static_cast<int>(footerHeight));
RECT footerRect = {x, y, x+pageRect.width(), y+static_cast<int>(footerHeight)};
ui->drawFooterInRect(d->webView, &footerRect, static_cast<OLE_HANDLE>(reinterpret_cast<LONG64>(pctx)), page+1, pageCount);
}
void WebFrame::spoolPage(PlatformGraphicsContext* pctx, GraphicsContext* spoolCtx, HDC printDC, IWebUIDelegate* ui, float headerHeight, float footerHeight, UINT page, UINT pageCount)
{
Frame* coreFrame = core(this);
IntRect pageRect = m_pageRects[page];
CGContextSaveGState(pctx);
IntRect printRect = printerRect(printDC);
CGRect mediaBox = CGRectMake(CGFloat(0),
CGFloat(0),
CGFloat(printRect.width()),
CGFloat(printRect.height()));
CGContextBeginPage(pctx, &mediaBox);
CGFloat scale = static_cast<float>(mediaBox.size.width)/static_cast<float>(pageRect.width());
CGAffineTransform ctm = CGContextGetBaseCTM(pctx);
ctm = CGAffineTransformScale(ctm, -scale, -scale);
ctm = CGAffineTransformTranslate(ctm, CGFloat(-pageRect.x()), CGFloat(-pageRect.y()+headerHeight)); // reserves space for header
CGContextScaleCTM(pctx, scale, scale);
CGContextTranslateCTM(pctx, CGFloat(-pageRect.x()), CGFloat(-pageRect.y()+headerHeight)); // reserves space for header
CGContextSetBaseCTM(pctx, ctm);
coreFrame->view()->paintContents(spoolCtx, pageRect);
CGContextTranslateCTM(pctx, CGFloat(pageRect.x()), CGFloat(pageRect.y())-headerHeight);
if (headerHeight)
drawHeader(pctx, ui, pageRect, headerHeight);
if (footerHeight)
drawFooter(pctx, ui, pageRect, page, pageCount, headerHeight, footerHeight);
CGContextEndPage(pctx);
CGContextRestoreGState(pctx);
}
#elif USE(CAIRO)
static float scaleFactor(HDC printDC, const IntRect& marginRect, const IntRect& pageRect)
{
const IntRect& printRect = printerRect(printDC);
IntRect adjustedRect = IntRect(
printRect.x() + marginRect.x(),
printRect.y() + marginRect.y(),
printRect.width() - marginRect.x() - marginRect.maxX(),
printRect.height() - marginRect.y() - marginRect.maxY());
float scale = static_cast<float>(adjustedRect.width()) / static_cast<float>(pageRect.width());
if (!scale)
scale = 1.0;
return scale;
}
static HDC hdcFromContext(PlatformGraphicsContext* pctx)
{
return cairo_win32_surface_get_dc(cairo_get_target(pctx->cr()));
}
void WebFrame::drawHeader(PlatformGraphicsContext* pctx, IWebUIDelegate* ui, const IntRect& pageRect, float headerHeight)
{
HDC hdc = hdcFromContext(pctx);
int x = pageRect.x();
int y = 0;
RECT headerRect = {x, y, x + pageRect.width(), y + static_cast<int>(headerHeight)};
ui->drawHeaderInRect(d->webView, &headerRect, static_cast<OLE_HANDLE>(reinterpret_cast<LONG64>(hdc)));
}
void WebFrame::drawFooter(PlatformGraphicsContext* pctx, IWebUIDelegate* ui, const IntRect& pageRect, UINT page, UINT pageCount, float headerHeight, float footerHeight)
{
HDC hdc = hdcFromContext(pctx);
int x = pageRect.x();
int y = max(static_cast<int>(headerHeight) + pageRect.height(), m_pageHeight -static_cast<int>(footerHeight));
RECT footerRect = {x, y, x + pageRect.width(), y + static_cast<int>(footerHeight)};
ui->drawFooterInRect(d->webView, &footerRect, static_cast<OLE_HANDLE>(reinterpret_cast<LONG64>(hdc)), page+1, pageCount);
}
static XFORM buildXFORMFromCairo(HDC targetDC, cairo_t* previewContext)
{
XFORM scaled;
GetWorldTransform(targetDC, &scaled);
cairo_matrix_t ctm;
cairo_get_matrix(previewContext, &ctm);
// Scale to the preview screen bounds
scaled.eM11 = ctm.xx;
scaled.eM22 = ctm.yy;
return scaled;
}
void WebFrame::spoolPage(PlatformGraphicsContext* pctx, GraphicsContext* spoolCtx, HDC printDC, IWebUIDelegate* ui, float headerHeight, float footerHeight, UINT page, UINT pageCount)
{
Frame* coreFrame = core(this);
const IntRect& pageRect = m_pageRects[page];
const IntRect& marginRect = printerMarginRect(printDC);
// In preview, the printDC is a placeholder, so just always use the HDC backing the graphics context.
HDC hdc = hdcFromContext(pctx);
spoolCtx->save();
XFORM original, scaled;
GetWorldTransform(hdc, &original);
cairo_t* cr = pctx->cr();
bool preview = (hdc != printDC);
if (preview) {
// If this is a preview, the Windows HDC was set to a non-scaled state so that Cairo will
// draw correctly. We need to retain the correct preview scale here for use when the Cairo
// drawing completes so that we can scale our GDI-based header/footer calls. This is a
// workaround for a bug in Cairo (see https://bugs.freedesktop.org/show_bug.cgi?id=28161)
scaled = buildXFORMFromCairo(hdc, cr);
}
float scale = scaleFactor(printDC, marginRect, pageRect);
IntRect cairoMarginRect(marginRect);
cairoMarginRect.scale(1 / scale);
// We cannot scale the display HDC because the print surface also scales fonts,
// resulting in invalid printing (and print preview)
cairo_scale(cr, scale, scale);
cairo_translate(cr, cairoMarginRect.x(), cairoMarginRect.y() + headerHeight);
// Modify Cairo (only) to account for page position.
cairo_translate(cr, -pageRect.x(), -pageRect.y());
coreFrame->view()->paintContents(spoolCtx, pageRect);
cairo_translate(cr, pageRect.x(), pageRect.y());
if (preview) {
// If this is a preview, the Windows HDC was set to a non-scaled state so that Cairo would
// draw correctly. We need to rescale the HDC to the correct preview scale so our GDI-based
// header/footer calls will draw properly. This is a workaround for a bug in Cairo.
// (see https://bugs.freedesktop.org/show_bug.cgi?id=28161)
SetWorldTransform(hdc, &scaled);
}
XFORM xform = TransformationMatrix().translate(marginRect.x(), marginRect.y()).scale(scale);
ModifyWorldTransform(hdc, &xform, MWT_LEFTMULTIPLY);
if (headerHeight)
drawHeader(pctx, ui, pageRect, headerHeight);
if (footerHeight)
drawFooter(pctx, ui, pageRect, page, pageCount, headerHeight, footerHeight);
SetWorldTransform(hdc, &original);
cairo_show_page(cr);
ASSERT(!cairo_status(cr));
spoolCtx->restore();
}
static void setCairoTransformToPreviewHDC(cairo_t* previewCtx, HDC previewDC)
{
XFORM passedCTM;
GetWorldTransform(previewDC, &passedCTM);
// Reset HDC WorldTransform to unscaled state. Scaling must be
// done in Cairo to avoid drawing errors.
XFORM unscaledCTM = passedCTM;
unscaledCTM.eM11 = 1.0;
unscaledCTM.eM22 = 1.0;
SetWorldTransform(previewDC, &unscaledCTM);
// Make the Cairo transform match the information passed to WebKit
// in the HDC's WorldTransform.
cairo_matrix_t ctm = { passedCTM.eM11, passedCTM.eM12, passedCTM.eM21,
passedCTM.eM22, passedCTM.eDx, passedCTM.eDy };
cairo_set_matrix(previewCtx, &ctm);
}
#endif
HRESULT STDMETHODCALLTYPE WebFrame::spoolPages(
/* [in] */ HDC printDC,
/* [in] */ UINT startPage,
/* [in] */ UINT endPage,
/* [retval][out] */ void* ctx)
{
#if USE(CG)
if (!printDC || !ctx) {
ASSERT_NOT_REACHED();
return E_POINTER;
}
#elif USE(CAIRO)
if (!printDC) {
ASSERT_NOT_REACHED();
return E_POINTER;
}
HDC targetDC = (ctx) ? (HDC)ctx : printDC;
cairo_surface_t* printSurface = 0;
if (ctx)
printSurface = cairo_win32_surface_create(targetDC); // in-memory
else
printSurface = cairo_win32_printing_surface_create(targetDC); // metafile
cairo_t* cr = cairo_create(printSurface);
if (!cr) {
cairo_surface_destroy(printSurface);
return E_FAIL;
}
PlatformContextCairo platformContext(cr);
PlatformGraphicsContext* pctx = &platformContext;
cairo_destroy(cr);
if (ctx) {
// If this is a preview, the Windows HDC was sent with scaling information.
// Retrieve it and reset it so that it draws properly. This is a workaround
// for a bug in Cairo (see https://bugs.freedesktop.org/show_bug.cgi?id=28161)
setCairoTransformToPreviewHDC(cr, targetDC);
}
cairo_surface_set_fallback_resolution(printSurface, 72.0, 72.0);
#endif
if (!m_inPrintingMode) {
ASSERT_NOT_REACHED();
return E_FAIL;
}
Frame* coreFrame = core(this);
if (!coreFrame || !coreFrame->document())
return E_FAIL;
UINT pageCount = (UINT) m_pageRects.size();
#if USE(CG)
PlatformGraphicsContext* pctx = (PlatformGraphicsContext*)ctx;
#endif
if (!pageCount || startPage > pageCount) {
ASSERT_NOT_REACHED();
return E_FAIL;
}
if (startPage > 0)
startPage--;
if (endPage == 0)
endPage = pageCount;
COMPtr<IWebUIDelegate> ui;
if (FAILED(d->webView->uiDelegate(&ui)))
return E_FAIL;
float headerHeight = 0, footerHeight = 0;
headerAndFooterHeights(&headerHeight, &footerHeight);
GraphicsContext spoolCtx(pctx);
spoolCtx.setShouldIncludeChildWindows(true);
for (UINT ii = startPage; ii < endPage; ii++)
spoolPage(pctx, &spoolCtx, printDC, ui.get(), headerHeight, footerHeight, ii, pageCount);
#if USE(CAIRO)
cairo_surface_finish(printSurface);
ASSERT(!cairo_surface_status(printSurface));
cairo_surface_destroy(printSurface);
#endif
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebFrame::isFrameSet(
/* [retval][out] */ BOOL* result)
{
*result = FALSE;
Frame* coreFrame = core(this);
if (!coreFrame || !coreFrame->document())
return E_FAIL;
*result = coreFrame->document()->isFrameSet() ? TRUE : FALSE;
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebFrame::string(
/* [retval][out] */ BSTR *result)
{
*result = 0;
Frame* coreFrame = core(this);
if (!coreFrame)
return E_FAIL;
RefPtr<Range> allRange(rangeOfContents(coreFrame->document()));
String allString = plainText(allRange.get());
*result = BString(allString).release();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebFrame::size(
/* [retval][out] */ SIZE *size)
{
if (!size)
return E_POINTER;
size->cx = size->cy = 0;
Frame* coreFrame = core(this);
if (!coreFrame)
return E_FAIL;
FrameView* view = coreFrame->view();
if (!view)
return E_FAIL;
size->cx = view->width();
size->cy = view->height();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebFrame::hasScrollBars(
/* [retval][out] */ BOOL *result)
{
if (!result)
return E_POINTER;
*result = FALSE;
Frame* coreFrame = core(this);
if (!coreFrame)
return E_FAIL;
FrameView* view = coreFrame->view();
if (!view)
return E_FAIL;
if (view->horizontalScrollbar() || view->verticalScrollbar())
*result = TRUE;
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebFrame::contentBounds(
/* [retval][out] */ RECT *result)
{
if (!result)
return E_POINTER;
::SetRectEmpty(result);
Frame* coreFrame = core(this);
if (!coreFrame)
return E_FAIL;
FrameView* view = coreFrame->view();
if (!view)
return E_FAIL;
result->bottom = view->contentsHeight();
result->right = view->contentsWidth();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebFrame::frameBounds(
/* [retval][out] */ RECT *result)
{
if (!result)
return E_POINTER;
::SetRectEmpty(result);
Frame* coreFrame = core(this);
if (!coreFrame)
return E_FAIL;
FrameView* view = coreFrame->view();
if (!view)
return E_FAIL;
FloatRect bounds = view->visibleContentRect(true);
result->bottom = (LONG) bounds.height();
result->right = (LONG) bounds.width();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebFrame::isDescendantOfFrame(
/* [in] */ IWebFrame *ancestor,
/* [retval][out] */ BOOL *result)
{
if (!result)
return E_POINTER;
*result = FALSE;
Frame* coreFrame = core(this);
COMPtr<WebFrame> ancestorWebFrame(Query, ancestor);
if (!ancestorWebFrame)
return S_OK;
*result = (coreFrame && coreFrame->tree()->isDescendantOf(core(ancestorWebFrame.get()))) ? TRUE : FALSE;
return S_OK;
}
HRESULT WebFrame::stringByEvaluatingJavaScriptInScriptWorld(IWebScriptWorld* iWorld, JSObjectRef globalObjectRef, BSTR script, BSTR* evaluationResult)
{
if (!evaluationResult)
return E_POINTER;
*evaluationResult = 0;
if (!iWorld)
return E_POINTER;
COMPtr<WebScriptWorld> world(Query, iWorld);
if (!world)
return E_INVALIDARG;
Frame* coreFrame = core(this);
String string = String(script, SysStringLen(script));
// Start off with some guess at a frame and a global object, we'll try to do better...!
JSDOMWindow* anyWorldGlobalObject = coreFrame->script()->globalObject(mainThreadNormalWorld());
// The global object is probably a shell object? - if so, we know how to use this!
JSC::JSObject* globalObjectObj = toJS(globalObjectRef);
if (!strcmp(globalObjectObj->classInfo()->className, "JSDOMWindowShell"))
anyWorldGlobalObject = static_cast<JSDOMWindowShell*>(globalObjectObj)->window();
// Get the frame frome the global object we've settled on.
Frame* frame = anyWorldGlobalObject->impl()->frame();
ASSERT(frame->document());
JSValue result = frame->script()->executeScriptInWorld(world->world(), string, true).jsValue();
if (!frame) // In case the script removed our frame from the page.
return S_OK;
// This bizarre set of rules matches behavior from WebKit for Safari 2.0.
// If you don't like it, use -[WebScriptObject evaluateWebScript:] or
// JSEvaluateScript instead, since they have less surprising semantics.
if (!result || !result.isBoolean() && !result.isString() && !result.isNumber())
return S_OK;
JSC::ExecState* exec = anyWorldGlobalObject->globalExec();
JSC::JSLockHolder lock(exec);
String resultString = ustringToString(result.toString(exec)->value(exec));
*evaluationResult = BString(resultString).release();
return S_OK;
}
void WebFrame::unmarkAllMisspellings()
{
Frame* coreFrame = core(this);
for (Frame* frame = coreFrame; frame; frame = frame->tree()->traverseNext(coreFrame)) {
Document *doc = frame->document();
if (!doc)
return;
doc->markers()->removeMarkers(DocumentMarker::Spelling);
}
}
void WebFrame::unmarkAllBadGrammar()
{
Frame* coreFrame = core(this);
for (Frame* frame = coreFrame; frame; frame = frame->tree()->traverseNext(coreFrame)) {
Document *doc = frame->document();
if (!doc)
return;
doc->markers()->removeMarkers(DocumentMarker::Grammar);
}
}
WebView* WebFrame::webView() const
{
return d->webView;
}
void WebFrame::setWebView(WebView* webView)
{
d->webView = webView;
}
COMPtr<IAccessible> WebFrame::accessible() const
{
Frame* coreFrame = core(this);
ASSERT(coreFrame);
Document* currentDocument = coreFrame->document();
if (!currentDocument)
m_accessible = 0;
else if (!m_accessible || m_accessible->document() != currentDocument) {
// Either we've never had a wrapper for this frame's top-level Document,
// the Document renderer was destroyed and its wrapper was detached, or
// the previous Document is in the page cache, and the current document
// needs to be wrapped.
m_accessible = new AccessibleDocument(currentDocument);
}
return m_accessible.get();
}
void WebFrame::updateBackground()
{
Color backgroundColor = webView()->transparent() ? Color::transparent : Color::white;
Frame* coreFrame = core(this);
if (!coreFrame || !coreFrame->view())
return;
coreFrame->view()->updateBackgroundRecursively(backgroundColor, webView()->transparent());
}
PassRefPtr<FrameNetworkingContext> WebFrame::createNetworkingContext()
{
return WebFrameNetworkingContext::create(core(this), userAgent(url()));
}
| [
"[email protected]"
] | |
528f4299e2ac5c95daefe39edb38ef1d868878bb | cb80a8562d90eb969272a7ff2cf52c1fa7aeb084 | /inletTest5/0.056/yPlus | 6471014766fb972859c3a701e1bd2f1c3aace24d | [] | no_license | mahoep/inletCFD | eb516145fad17408f018f51e32aa0604871eaa95 | 0df91e3fbfa60d5db9d52739e212ca6d3f0a28b2 | refs/heads/main | 2023-08-30T22:07:41.314690 | 2021-10-14T19:23:51 | 2021-10-14T19:23:51 | 314,657,843 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,324 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: v2006 |
| \\ / A nd | Website: www.openfoam.com |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "0.056";
object yPlus;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 0 0 0 0 0 0];
internalField uniform 0;
boundaryField
{
bottomEmptyFaces
{
type empty;
}
topEmptyFaces
{
type empty;
}
inlet
{
type calculated;
value uniform 0;
}
outlet
{
type calculated;
value uniform 0;
}
walls
{
type calculated;
value nonuniform List<scalar>
988
(
13.3669
13.3757
13.3836
13.3922
13.4
13.4084
13.4159
13.4242
13.4315
13.4395
13.4466
13.4544
13.4614
13.4689
13.4756
13.4829
13.4895
13.4966
13.503
13.5099
13.5161
13.5228
13.5288
13.5353
13.5412
13.5475
13.5532
13.5593
13.5649
13.5709
13.5763
13.582
13.5873
13.593
13.5981
13.6036
13.6086
13.6138
13.6187
13.6238
13.6285
13.6335
13.6381
13.6429
13.6474
13.652
13.6563
13.6608
13.665
13.6694
13.6734
13.6776
13.6815
13.6856
13.6893
13.6933
13.697
13.7008
13.7043
13.708
13.7114
13.715
13.7183
13.7218
13.725
13.7283
13.7314
13.7347
13.7377
13.7408
13.7438
13.7468
13.7496
13.7525
13.7552
13.7581
13.7607
13.7635
13.766
13.7686
13.7711
13.7737
13.776
13.7785
13.7808
13.7832
13.7854
13.7877
13.7899
13.7921
13.7941
13.7964
13.7983
13.8005
13.8023
13.8044
13.8063
13.8082
13.81
13.812
13.8137
13.8155
13.8172
13.819
13.8206
13.8224
13.8239
13.8256
13.8271
13.8288
13.8302
13.8318
13.8332
13.8348
13.8361
13.8376
13.8389
13.8404
13.8417
13.8431
13.8443
13.8458
13.8469
13.8483
13.8495
13.8508
13.8519
13.8532
13.8543
13.8555
13.8566
13.8578
13.8588
13.86
13.861
13.8622
13.8632
13.8643
13.8652
13.8663
13.8673
13.8683
13.8692
13.8702
13.8711
13.8721
13.873
13.874
13.8748
13.8758
13.8766
13.8775
13.8783
13.8792
13.88
13.8809
13.8817
13.8826
13.8833
13.8842
13.8849
13.8858
13.8865
13.8873
13.888
13.8889
13.8895
13.8904
13.8911
13.8919
13.8925
13.8934
13.894
13.8948
13.8954
13.8962
13.8969
13.8976
13.8983
13.8991
13.8997
13.9005
13.9011
13.9019
13.9026
13.9034
13.9041
13.9049
13.9056
13.9064
13.9073
13.9082
13.9088
13.9098
13.9105
13.9116
13.9123
13.9134
13.9141
13.9153
13.9161
13.9172
13.918
13.9192
13.92
13.9212
13.9219
13.9231
13.9238
13.9249
13.9256
13.9267
13.9273
13.9283
13.929
13.9299
13.9308
13.9316
13.9332
13.9242
13.9461
13.9175
13.9318
13.9121
14.2114
14.6744
11.0265
7.6188
8.08304
9.77849
8.53726
8.69584
7.01037
7.22744
8.59653
9.24374
8.28012
9.02055
8.26894
8.89821
8.88758
9.56043
9.60933
9.9127
8.50172
9.22979
10.6525
9.29738
9.59248
7.74217
7.99609
10.256
8.11346
8.71182
8.9464
9.11248
8.06858
8.5699
7.43348
7.7737
7.78982
8.47682
59.8803
38.7556
47.9283
9.74462
7.28901
6.1537
30.7573
9.39985
16.7664
422.482
188.903
125.679
156.815
356.263
238.22
278.473
478.844
514.089
509.359
420.458
475.355
107.493
72.3993
84.3656
376.662
281.694
315.787
240.179
202.785
147.763
164.768
124.886
105.158
84.2694
69.5766
55.5909
43.6061
45.873
20.2447
19.0176
18.7115
18.4678
6.43754
6.54178
18.5935
17.4113
22.733
17.0499
15.0287
7.75781
7.76188
23.4184
23.5061
8.44894
6.28776
6.3013
6.85096
7.23697
23.5516
23.271
8.45133
7.33907
7.30035
6.35904
6.32747
7.37996
7.28534
22.722
22.1296
21.4371
20.719
20.0039
19.3124
18.6547
18.038
7.64533
7.43472
6.2788
5.73397
7.31139
6.83395
6.54108
5.75753
5.52644
6.22851
5.69788
17.4639
16.9325
16.4415
15.988
7.38437
6.21818
5.28411
15.5722
15.1916
6.80076
5.42526
4.9442
7.11803
5.86843
5.15361
7.98552
6.52501
5.31891
6.64143
6.13273
14.8459
14.5318
8.24727
7.84802
5.92306
5.8011
7.16554
6.84286
7.703
6.58692
6.32815
5.84105
5.88379
8.16149
8.27357
8.00982
8.0513
7.10725
7.42008
9.12459
6.62476
6.75455
7.2656
7.70678
7.71389
8.3499
7.42407
7.94298
9.36432
6.79763
6.95653
8.92123
6.50756
6.76218
42.1378
34.8116
28.1126
14.2489
16.3646
13.9939
8.47814
7.10666
13.7667
6.16642
13.5643
5.59603
13.3863
13.2295
13.0932
12.9743
7.43256
4.17699
8.73992
7.74625
7.39573
12.872
7.13397
7.04663
12.7835
12.708
6.89755
12.6438
6.86567
6.7425
6.71936
12.5894
6.59675
6.57747
12.5435
12.505
12.4729
6.4661
6.43998
6.34826
6.35298
6.27847
6.26382
6.1854
6.20249
6.1327
6.12056
12.4457
6.05031
6.06797
12.4229
12.4033
12.3868
12.3721
12.3595
12.3474
12.3371
12.3265
12.3171
6.00453
12.3069
5.99398
12.2978
5.93033
5.94825
5.89007
5.88063
12.2875
12.2784
5.82219
12.2672
5.84018
12.2588
5.78627
5.77772
5.72367
5.74179
5.69172
5.68424
5.63448
5.65304
5.60689
5.6006
5.55995
5.57148
5.53407
5.52974
5.4946
5.50807
5.4855
5.48625
5.49769
5.56599
5.69093
5.94634
6.45252
7.05079
12.2471
12.239
12.2275
12.2196
12.2083
12.2006
12.1894
12.1822
12.1715
12.1652
12.155
12.1496
12.1405
12.1363
12.1282
12.1254
12.1187
12.1176
12.1122
12.1126
12.1092
12.1105
12.1088
12.1112
12.1117
12.115
12.1176
12.1218
12.1257
12.1307
12.1352
12.1414
12.1466
12.1539
12.1596
12.1677
12.174
12.1833
12.19
12.2001
12.2074
12.2186
12.2265
12.2383
12.2473
12.2598
12.2697
12.2827
12.2936
12.3074
12.319
12.3332
12.3458
12.3606
12.3738
12.3889
12.4028
12.4184
12.4327
12.4487
12.4634
12.4798
12.4947
12.5113
12.5265
12.5433
12.5586
12.5755
12.5909
12.6079
12.6233
12.6402
12.6557
12.6726
12.6879
12.7048
12.7201
12.7368
12.7518
12.7684
12.7834
12.7997
12.8145
12.8305
12.8451
12.861
12.8753
12.8908
12.9049
12.9201
12.9339
12.9488
12.9623
12.9769
12.9901
13.0044
13.0173
13.0312
13.0438
13.0573
13.0697
13.0829
13.0949
13.1078
13.1195
13.1321
13.1434
13.1556
13.1667
13.1786
13.1893
13.2009
13.2113
13.2226
13.2327
13.2437
13.2536
13.2642
13.2738
13.2841
13.2935
13.3035
13.3126
13.3223
13.3312
13.3406
13.3493
13.3584
13.2939
10.256
10.9686
11.4385
11.6524
9.55632
10.1595
10.8331
11.1982
12.4787
9.199
9.62058
9.84479
10.7433
13.0201
11.2976
11.5856
10.2583
11.1733
10.0023
10.5918
9.51446
9.90651
14.0815
14.5508
12.5875
12.6052
10.6327
11.1023
14.05
10.4847
10.7811
12.0617
12.2237
10.4199
10.8321
12.3385
12.3917
15.695
15.6012
15.4402
12.8003
12.6236
12.6975
12.3834
16.0581
17.1299
16.1133
13.3382
13.1111
14.0209
13.3765
15.6747
13.042
12.6876
13.0193
12.6467
14.8625
11.0707
11.3807
13.0542
13.0591
13.5177
11.6632
12.0045
10.7163
11.4409
11.9728
12.2211
9.95305
10.3197
10.4771
11.1583
9.66133
10.074
9.73128
10.6313
9.51495
10.3259
11.7787
9.40155
10.1735
10.2334
10.6093
9.15586
9.87658
8.47619
8.90632
8.89387
9.60206
11.3439
9.92746
10.2877
8.2757
8.58777
9.21395
9.91936
8.9027
9.65813
8.63113
9.26548
7.99949
8.32111
9.152
10.0474
12.1742
10.5978
10.9814
8.8603
9.21787
19.2174
14.8246
14.1208
16.9286
15.1585
14.1465
7.6514
15.2756
32.9656
30.6995
29.1292
28.0244
27.1971
26.5247
25.9053
25.1954
24.6218
24.1832
23.8607
23.5272
23.2875
23.0246
22.8386
22.6251
22.4741
22.2958
22.1684
22.015
21.9045
21.7692
21.6709
21.5492
21.4602
21.3488
21.267
21.1638
21.088
20.9914
20.92
20.8288
20.7613
20.6746
20.6103
20.5276
20.4661
20.3868
20.3277
20.2514
20.1944
20.1208
20.0656
19.9944
19.9409
19.8719
19.8198
19.7527
19.702
19.6367
19.5872
19.5234
19.475
19.4128
19.3654
19.3045
19.2579
19.1982
19.1525
19.0938
19.0488
18.9911
18.9466
18.8897
18.8457
18.7895
18.746
18.6904
18.6472
18.5921
18.5493
18.4946
18.4519
18.3976
18.3551
18.3009
18.2585
18.2044
18.162
18.108
18.0655
18.0115
17.9689
17.9147
17.8719
17.8175
17.7745
17.7197
17.6763
17.6212
17.5774
17.5218
17.4775
17.4214
17.3766
17.3198
17.2744
17.2169
17.171
17.1127
17.066
17.0069
16.9595
16.8994
16.8512
16.7902
16.7411
16.679
16.629
16.5658
16.5148
16.4502
16.3982
16.3323
16.2791
16.2117
16.1573
16.0884
16.0328
15.9622
15.9052
15.833
15.7746
15.7005
15.6405
15.5646
15.503
15.4251
15.3619
15.2819
15.217
15.1348
15.0681
14.9836
14.9151
14.8283
14.7578
14.6685
14.596
14.5042
14.4296
14.3351
14.2584
14.1612
14.0822
13.9821
13.9009
13.7977
13.7142
13.6079
13.522
13.4126
13.3242
13.2116
13.1208
13.005
12.9117
12.7928
12.6971
12.575
12.4768
12.3516
12.2509
12.1229
12.0191
11.8894
11.7809
11.6525
11.5344
11.4157
11.3284
11.2243
11.1426
11.04
10.9576
10.8534
10.7691
10.6629
10.5768
10.4688
10.3811
10.2718
10.1832
10.073
9.98395
9.87341
9.78463
9.67447
9.58662
9.47754
9.39134
9.2841
9.20031
9.09566
9.01501
8.91371
8.8369
8.73969
8.66742
8.57483
8.50762
8.42027
8.35849
8.27675
8.22059
8.14459
8.09414
8.02401
7.97925
7.91491
7.87562
7.81675
7.78249
7.72881
7.69917
7.65034
7.62483
7.58037
7.55848
7.51801
7.49918
7.46214
7.44544
7.41136
7.39618
7.36469
7.35061
7.32096
7.30741
7.27863
7.26493
7.2348
7.22216
7.18645
7.17434
7.14465
7.12052
7.10518
7.04538
7.06318
7.2028
35.7773
7.41277
)
;
}
rightWall
{
type calculated;
value uniform 0;
}
symmetryLine
{
type symmetryPlane;
}
}
// ************************************************************************* //
| [
"[email protected]"
] | ||
fda61649c745dea668781f5c01f35f23a8f90c05 | 606df8f6d7095e5f10a697f4acf66cf9aa9ebd61 | /topcoder/problems/EllysChessboard.cpp | d59f53df2ffac5615cb465bd85836683148eb62b | [] | no_license | memset0x3f/oj-data | 15cb8a6f878f819e6e32443648ca8cfb75bf61e0 | c20e0da978195aa8d72679a6a0ae1a1eff2b94f7 | refs/heads/master | 2020-05-02T01:03:00.607743 | 2016-01-09T07:39:01 | 2016-01-09T07:39:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,854 | cpp | #include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cstring>
#include <cmath>
using namespace std;
const int inf = 100000;
int dp[15][15][15][15];
int dat[15][15];
class EllysChessboard {
public:
int Max(int a, int b, int c) {
return max(max(a, b), c);
}
void checkmin(int &x, int y) {
if (y < x) x = y;
}
int gao(int ax, int ay, int bx, int by, int deep) {
if (ax > bx || ay > by) return inf;
if (ax==bx && ay==by) return (dp[ax][ay][bx][by] = 0);
if (dp[ax][ay][bx][by] != -1) return dp[ax][ay][bx][by];
dp[ax][ay][bx][by] = inf;
int nows = gao(ax+1, ay, bx, by, deep+1);
for (int i = ay; i <= by; ++i)
if (dat[ax][i]) nows += Max(bx-ax, i-ay, by-i);
checkmin(dp[ax][ay][bx][by], nows);
nows = gao(ax, ay+1, bx, by, deep+1);
for (int i = ax; i <= bx; ++i)
if (dat[i][ay]) nows += Max(by-ay, i-ax, bx-i);
checkmin(dp[ax][ay][bx][by], nows);
nows = gao(ax, ay, bx-1, by, deep+1);
for (int i = ay; i <= by; ++i)
if (dat[bx][i]) nows += Max(bx-ax, i-ay, by-i);
checkmin(dp[ax][ay][bx][by], nows);
nows = gao(ax, ay, bx, by-1, deep+1);
for (int i = ax; i <= bx; ++i)
if (dat[i][by]) nows += Max(by-ay, i-ax, bx-i);
checkmin(dp[ax][ay][bx][by], nows);
return dp[ax][ay][bx][by];
}
int minCost(vector <string> board) {
memset(dat, 0, sizeof(dat));
memset(dp, -1, sizeof(dp));
for (int i = 0; i < 8; ++i)
for (int j = 0; j < 8; ++j)
dat[i+j][i-j+7] = (bool)(board[i][j]=='#');
return gao(0, 0, 14, 14, 0);
}
};
| [
"[email protected]"
] | |
3f0fba7325708e42757e17b0b37f5292b816bb43 | 9fdb6486b12a6241fcad5daf5a70f0af10f0c050 | /src/rpcrawtransaction.cpp | df8c924f917944cbc10bda724573a8598faf2b15 | [
"MIT"
] | permissive | QUAR-Network/QUAR-core | 95f49e5a5caeb4b0e6edb860de19a01837ec31c6 | e415ee0962939577da856cb05d335f3939ca17af | refs/heads/master | 2020-03-22T20:19:24.361867 | 2018-08-07T15:57:22 | 2018-08-07T15:57:22 | 140,589,771 | 0 | 6 | null | null | null | null | UTF-8 | C++ | false | false | 38,736 | cpp | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Copyright (c) 2014-2017 The Dash Core developers
// Copyright (c) 2017-2018 The Proton Core developers
// Copyright (c) 2018 The QUAR Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "base58.h"
#include "chain.h"
#include "coins.h"
#include "consensus/validation.h"
#include "core_io.h"
#include "init.h"
#include "keystore.h"
#include "main.h"
#include "merkleblock.h"
#include "net.h"
#include "policy/policy.h"
#include "primitives/transaction.h"
#include "rpcserver.h"
#include "script/script.h"
#include "script/script_error.h"
#include "script/sign.h"
#include "script/standard.h"
#include "txmempool.h"
#include "uint256.h"
#include "utilstrencodings.h"
#include "instantx.h"
#ifdef ENABLE_WALLET
#include "wallet/wallet.h"
#endif
#include <stdint.h>
#include <boost/assign/list_of.hpp>
#include <univalue.h>
using namespace std;
void ScriptPubKeyToJSON(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex)
{
txnouttype type;
vector<CTxDestination> addresses;
int nRequired;
out.push_back(Pair("asm", ScriptToAsmStr(scriptPubKey)));
if (fIncludeHex)
out.push_back(Pair("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end())));
if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired)) {
out.push_back(Pair("type", GetTxnOutputType(type)));
return;
}
out.push_back(Pair("reqSigs", nRequired));
out.push_back(Pair("type", GetTxnOutputType(type)));
UniValue a(UniValue::VARR);
BOOST_FOREACH(const CTxDestination& addr, addresses)
a.push_back(CBitcoinAddress(addr).ToString());
out.push_back(Pair("addresses", a));
}
void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry)
{
uint256 txid = tx.GetHash();
entry.push_back(Pair("txid", txid.GetHex()));
entry.push_back(Pair("size", (int)::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION)));
entry.push_back(Pair("version", tx.nVersion));
entry.push_back(Pair("locktime", (int64_t)tx.nLockTime));
UniValue vin(UniValue::VARR);
BOOST_FOREACH(const CTxIn& txin, tx.vin) {
UniValue in(UniValue::VOBJ);
if (tx.IsCoinBase())
in.push_back(Pair("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
else {
in.push_back(Pair("txid", txin.prevout.hash.GetHex()));
in.push_back(Pair("vout", (int64_t)txin.prevout.n));
UniValue o(UniValue::VOBJ);
o.push_back(Pair("asm", ScriptToAsmStr(txin.scriptSig, true)));
o.push_back(Pair("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
in.push_back(Pair("scriptSig", o));
// Add address and value info if spentindex enabled
CSpentIndexValue spentInfo;
CSpentIndexKey spentKey(txin.prevout.hash, txin.prevout.n);
if (GetSpentIndex(spentKey, spentInfo)) {
in.push_back(Pair("value", ValueFromAmount(spentInfo.satoshis)));
in.push_back(Pair("valueSat", spentInfo.satoshis));
if (spentInfo.addressType == 1) {
in.push_back(Pair("address", CBitcoinAddress(CKeyID(spentInfo.addressHash)).ToString()));
} else if (spentInfo.addressType == 2) {
in.push_back(Pair("address", CBitcoinAddress(CScriptID(spentInfo.addressHash)).ToString()));
}
}
}
in.push_back(Pair("sequence", (int64_t)txin.nSequence));
vin.push_back(in);
}
entry.push_back(Pair("vin", vin));
UniValue vout(UniValue::VARR);
for (unsigned int i = 0; i < tx.vout.size(); i++) {
const CTxOut& txout = tx.vout[i];
UniValue out(UniValue::VOBJ);
out.push_back(Pair("value", ValueFromAmount(txout.nValue)));
out.push_back(Pair("valueSat", txout.nValue));
out.push_back(Pair("n", (int64_t)i));
UniValue o(UniValue::VOBJ);
ScriptPubKeyToJSON(txout.scriptPubKey, o, true);
out.push_back(Pair("scriptPubKey", o));
// Add spent information if spentindex is enabled
CSpentIndexValue spentInfo;
CSpentIndexKey spentKey(txid, i);
if (GetSpentIndex(spentKey, spentInfo)) {
out.push_back(Pair("spentTxId", spentInfo.txid.GetHex()));
out.push_back(Pair("spentIndex", (int)spentInfo.inputIndex));
out.push_back(Pair("spentHeight", spentInfo.blockHeight));
}
vout.push_back(out);
}
entry.push_back(Pair("vout", vout));
if (!hashBlock.IsNull()) {
entry.push_back(Pair("blockhash", hashBlock.GetHex()));
BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
if (mi != mapBlockIndex.end() && (*mi).second) {
CBlockIndex* pindex = (*mi).second;
if (chainActive.Contains(pindex)) {
entry.push_back(Pair("height", pindex->nHeight));
entry.push_back(Pair("confirmations", 1 + chainActive.Height() - pindex->nHeight));
entry.push_back(Pair("time", pindex->GetBlockTime()));
entry.push_back(Pair("blocktime", pindex->GetBlockTime()));
} else {
entry.push_back(Pair("height", -1));
entry.push_back(Pair("confirmations", 0));
}
}
}
}
UniValue getrawtransaction(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getrawtransaction \"txid\" ( verbose )\n"
"\nNOTE: By default this function only works sometimes. This is when the tx is in the mempool\n"
"or there is an unspent output in the utxo for this transaction. To make it always work,\n"
"you need to maintain a transaction index, using the -txindex command line option.\n"
"\nReturn the raw transaction data.\n"
"\nIf verbose=0, returns a string that is serialized, hex-encoded data for 'txid'.\n"
"If verbose is non-zero, returns an Object with information about 'txid'.\n"
"\nArguments:\n"
"1. \"txid\" (string, required) The transaction id\n"
"2. verbose (numeric, optional, default=0) If 0, return a string, other return a json object\n"
"\nResult (if verbose is not set or set to 0):\n"
"\"data\" (string) The serialized, hex-encoded data for 'txid'\n"
"\nResult (if verbose > 0):\n"
"{\n"
" \"hex\" : \"data\", (string) The serialized, hex-encoded data for 'txid'\n"
" \"txid\" : \"id\", (string) The transaction id (same as provided)\n"
" \"size\" : n, (numeric) The transaction size\n"
" \"version\" : n, (numeric) The version\n"
" \"locktime\" : ttt, (numeric) The lock time\n"
" \"vin\" : [ (array of json objects)\n"
" {\n"
" \"txid\": \"id\", (string) The transaction id\n"
" \"vout\": n, (numeric) \n"
" \"scriptSig\": { (json object) The script\n"
" \"asm\": \"asm\", (string) asm\n"
" \"hex\": \"hex\" (string) hex\n"
" },\n"
" \"sequence\": n (numeric) The script sequence number\n"
" }\n"
" ,...\n"
" ],\n"
" \"vout\" : [ (array of json objects)\n"
" {\n"
" \"value\" : x.xxx, (numeric) The value in " + CURRENCY_UNIT + "\n"
" \"n\" : n, (numeric) index\n"
" \"scriptPubKey\" : { (json object)\n"
" \"asm\" : \"asm\", (string) the asm\n"
" \"hex\" : \"hex\", (string) the hex\n"
" \"reqSigs\" : n, (numeric) The required sigs\n"
" \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n"
" \"addresses\" : [ (json array of string)\n"
" \"QUARaddress\" (string) QUAR address\n"
" ,...\n"
" ]\n"
" }\n"
" }\n"
" ,...\n"
" ],\n"
" \"blockhash\" : \"hash\", (string) the block hash\n"
" \"confirmations\" : n, (numeric) The confirmations\n"
" \"time\" : ttt, (numeric) The transaction time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"blocktime\" : ttt (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getrawtransaction", "\"mytxid\"")
+ HelpExampleCli("getrawtransaction", "\"mytxid\" 1")
+ HelpExampleRpc("getrawtransaction", "\"mytxid\", 1")
);
LOCK(cs_main);
uint256 hash = ParseHashV(params[0], "parameter 1");
bool fVerbose = false;
if (params.size() > 1)
fVerbose = (params[1].get_int() != 0);
CTransaction tx;
uint256 hashBlock;
if (!GetTransaction(hash, tx, Params().GetConsensus(), hashBlock, true))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction");
string strHex = EncodeHexTx(tx);
if (!fVerbose)
return strHex;
UniValue result(UniValue::VOBJ);
result.push_back(Pair("hex", strHex));
TxToJSON(tx, hashBlock, result);
return result;
}
UniValue gettxoutproof(const UniValue& params, bool fHelp)
{
if (fHelp || (params.size() != 1 && params.size() != 2))
throw runtime_error(
"gettxoutproof [\"txid\",...] ( blockhash )\n"
"\nReturns a hex-encoded proof that \"txid\" was included in a block.\n"
"\nNOTE: By default this function only works sometimes. This is when there is an\n"
"unspent output in the utxo for this transaction. To make it always work,\n"
"you need to maintain a transaction index, using the -txindex command line option or\n"
"specify the block in which the transaction is included in manually (by blockhash).\n"
"\nReturn the raw transaction data.\n"
"\nArguments:\n"
"1. \"txids\" (string) A json array of txids to filter\n"
" [\n"
" \"txid\" (string) A transaction hash\n"
" ,...\n"
" ]\n"
"2. \"block hash\" (string, optional) If specified, looks for txid in the block with this hash\n"
"\nResult:\n"
"\"data\" (string) A string that is a serialized, hex-encoded data for the proof.\n"
);
set<uint256> setTxids;
uint256 oneTxid;
UniValue txids = params[0].get_array();
for (unsigned int idx = 0; idx < txids.size(); idx++) {
const UniValue& txid = txids[idx];
if (txid.get_str().length() != 64 || !IsHex(txid.get_str()))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid txid ")+txid.get_str());
uint256 hash(uint256S(txid.get_str()));
if (setTxids.count(hash))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated txid: ")+txid.get_str());
setTxids.insert(hash);
oneTxid = hash;
}
LOCK(cs_main);
CBlockIndex* pblockindex = NULL;
uint256 hashBlock;
if (params.size() > 1)
{
hashBlock = uint256S(params[1].get_str());
if (!mapBlockIndex.count(hashBlock))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
pblockindex = mapBlockIndex[hashBlock];
} else {
CCoins coins;
if (pcoinsTip->GetCoins(oneTxid, coins) && coins.nHeight > 0 && coins.nHeight <= chainActive.Height())
pblockindex = chainActive[coins.nHeight];
}
if (pblockindex == NULL)
{
CTransaction tx;
if (!GetTransaction(oneTxid, tx, Params().GetConsensus(), hashBlock, false) || hashBlock.IsNull())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not yet in block");
if (!mapBlockIndex.count(hashBlock))
throw JSONRPCError(RPC_INTERNAL_ERROR, "Transaction index corrupt");
pblockindex = mapBlockIndex[hashBlock];
}
CBlock block;
if(!ReadBlockFromDisk(block, pblockindex, Params().GetConsensus()))
throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk");
unsigned int ntxFound = 0;
BOOST_FOREACH(const CTransaction&tx, block.vtx)
if (setTxids.count(tx.GetHash()))
ntxFound++;
if (ntxFound != setTxids.size())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "(Not all) transactions not found in specified block");
CDataStream ssMB(SER_NETWORK, PROTOCOL_VERSION);
CMerkleBlock mb(block, setTxids);
ssMB << mb;
std::string strHex = HexStr(ssMB.begin(), ssMB.end());
return strHex;
}
UniValue verifytxoutproof(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"verifytxoutproof \"proof\"\n"
"\nVerifies that a proof points to a transaction in a block, returning the transaction it commits to\n"
"and throwing an RPC error if the block is not in our best chain\n"
"\nArguments:\n"
"1. \"proof\" (string, required) The hex-encoded proof generated by gettxoutproof\n"
"\nResult:\n"
"[\"txid\"] (array, strings) The txid(s) which the proof commits to, or empty array if the proof is invalid\n"
);
CDataStream ssMB(ParseHexV(params[0], "proof"), SER_NETWORK, PROTOCOL_VERSION);
CMerkleBlock merkleBlock;
ssMB >> merkleBlock;
UniValue res(UniValue::VARR);
vector<uint256> vMatch;
if (merkleBlock.txn.ExtractMatches(vMatch) != merkleBlock.header.hashMerkleRoot)
return res;
LOCK(cs_main);
if (!mapBlockIndex.count(merkleBlock.header.GetHash()) || !chainActive.Contains(mapBlockIndex[merkleBlock.header.GetHash()]))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found in chain");
BOOST_FOREACH(const uint256& hash, vMatch)
res.push_back(hash.GetHex());
return res;
}
UniValue createrawtransaction(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 3)
throw runtime_error(
"createrawtransaction [{\"txid\":\"id\",\"vout\":n},...] {\"address\":amount,\"data\":\"hex\",...} ( locktime )\n"
"\nCreate a transaction spending the given inputs and creating new outputs.\n"
"Outputs can be addresses or data.\n"
"Returns hex-encoded raw transaction.\n"
"Note that the transaction's inputs are not signed, and\n"
"it is not stored in the wallet or transmitted to the network.\n"
"\nArguments:\n"
"1. \"transactions\" (string, required) A json array of json objects\n"
" [\n"
" {\n"
" \"txid\":\"id\", (string, required) The transaction id\n"
" \"vout\":n (numeric, required) The output number\n"
" }\n"
" ,...\n"
" ]\n"
"2. \"outputs\" (string, required) a json object with outputs\n"
" {\n"
" \"address\": x.xxx (numeric or string, required) The key is the QUAR address, the numeric value (can be string) is the " + CURRENCY_UNIT + " amount\n"
" \"data\": \"hex\", (string, required) The key is \"data\", the value is hex encoded data\n"
" ...\n"
" }\n"
"3. locktime (numeric, optional, default=0) Raw locktime. Non-0 value also locktime-activates inputs\n"
"\nResult:\n"
"\"transaction\" (string) hex string of the transaction\n"
"\nExamples\n"
+ HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"{\\\"address\\\":0.01}\"")
+ HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"{\\\"data\\\":\\\"00010203\\\"}\"")
+ HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"{\\\"address\\\":0.01}\"")
+ HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"{\\\"data\\\":\\\"00010203\\\"}\"")
);
LOCK(cs_main);
RPCTypeCheck(params, boost::assign::list_of(UniValue::VARR)(UniValue::VOBJ)(UniValue::VNUM), true);
if (params[0].isNull() || params[1].isNull())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, arguments 1 and 2 must be non-null");
UniValue inputs = params[0].get_array();
UniValue sendTo = params[1].get_obj();
CMutableTransaction rawTx;
if (params.size() > 2 && !params[2].isNull()) {
int64_t nLockTime = params[2].get_int64();
if (nLockTime < 0 || nLockTime > std::numeric_limits<uint32_t>::max())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, locktime out of range");
rawTx.nLockTime = nLockTime;
}
for (unsigned int idx = 0; idx < inputs.size(); idx++) {
const UniValue& input = inputs[idx];
const UniValue& o = input.get_obj();
uint256 txid = ParseHashO(o, "txid");
const UniValue& vout_v = find_value(o, "vout");
if (!vout_v.isNum())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key");
int nOutput = vout_v.get_int();
if (nOutput < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive");
uint32_t nSequence = (rawTx.nLockTime ? std::numeric_limits<uint32_t>::max() - 1 : std::numeric_limits<uint32_t>::max());
CTxIn in(COutPoint(txid, nOutput), CScript(), nSequence);
rawTx.vin.push_back(in);
}
set<CBitcoinAddress> setAddress;
vector<string> addrList = sendTo.getKeys();
BOOST_FOREACH(const string& name_, addrList) {
if (name_ == "data") {
std::vector<unsigned char> data = ParseHexV(sendTo[name_].getValStr(),"Data");
CTxOut out(0, CScript() << OP_RETURN << data);
rawTx.vout.push_back(out);
} else {
CBitcoinAddress address(name_);
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid QUAR address: ")+name_);
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+name_);
setAddress.insert(address);
CScript scriptPubKey = GetScriptForDestination(address.Get());
CAmount nAmount = AmountFromValue(sendTo[name_]);
CTxOut out(nAmount, scriptPubKey);
rawTx.vout.push_back(out);
}
}
return EncodeHexTx(rawTx);
}
UniValue decoderawtransaction(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"decoderawtransaction \"hexstring\"\n"
"\nReturn a JSON object representing the serialized, hex-encoded transaction.\n"
"\nArguments:\n"
"1. \"hex\" (string, required) The transaction hex string\n"
"\nResult:\n"
"{\n"
" \"txid\" : \"id\", (string) The transaction id\n"
" \"size\" : n, (numeric) The transaction size\n"
" \"version\" : n, (numeric) The version\n"
" \"locktime\" : ttt, (numeric) The lock time\n"
" \"vin\" : [ (array of json objects)\n"
" {\n"
" \"txid\": \"id\", (string) The transaction id\n"
" \"vout\": n, (numeric) The output number\n"
" \"scriptSig\": { (json object) The script\n"
" \"asm\": \"asm\", (string) asm\n"
" \"hex\": \"hex\" (string) hex\n"
" },\n"
" \"sequence\": n (numeric) The script sequence number\n"
" }\n"
" ,...\n"
" ],\n"
" \"vout\" : [ (array of json objects)\n"
" {\n"
" \"value\" : x.xxx, (numeric) The value in " + CURRENCY_UNIT + "\n"
" \"n\" : n, (numeric) index\n"
" \"scriptPubKey\" : { (json object)\n"
" \"asm\" : \"asm\", (string) the asm\n"
" \"hex\" : \"hex\", (string) the hex\n"
" \"reqSigs\" : n, (numeric) The required sigs\n"
" \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n"
" \"addresses\" : [ (json array of string)\n"
" \"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" (string) QUAR address\n"
" ,...\n"
" ]\n"
" }\n"
" }\n"
" ,...\n"
" ],\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("decoderawtransaction", "\"hexstring\"")
+ HelpExampleRpc("decoderawtransaction", "\"hexstring\"")
);
LOCK(cs_main);
RPCTypeCheck(params, boost::assign::list_of(UniValue::VSTR));
CTransaction tx;
if (!DecodeHexTx(tx, params[0].get_str()))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
UniValue result(UniValue::VOBJ);
TxToJSON(tx, uint256(), result);
return result;
}
UniValue decodescript(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"decodescript \"hex\"\n"
"\nDecode a hex-encoded script.\n"
"\nArguments:\n"
"1. \"hex\" (string) the hex encoded script\n"
"\nResult:\n"
"{\n"
" \"asm\":\"asm\", (string) Script public key\n"
" \"hex\":\"hex\", (string) hex encoded public key\n"
" \"type\":\"type\", (string) The output type\n"
" \"reqSigs\": n, (numeric) The required signatures\n"
" \"addresses\": [ (json array of string)\n"
" \"address\" (string) QUAR address\n"
" ,...\n"
" ],\n"
" \"p2sh\",\"address\" (string) script address\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("decodescript", "\"hexstring\"")
+ HelpExampleRpc("decodescript", "\"hexstring\"")
);
RPCTypeCheck(params, boost::assign::list_of(UniValue::VSTR));
UniValue r(UniValue::VOBJ);
CScript script;
if (params[0].get_str().size() > 0){
vector<unsigned char> scriptData(ParseHexV(params[0], "argument"));
script = CScript(scriptData.begin(), scriptData.end());
} else {
// Empty scripts are valid
}
ScriptPubKeyToJSON(script, r, false);
r.push_back(Pair("p2sh", CBitcoinAddress(CScriptID(script)).ToString()));
return r;
}
/** Pushes a JSON object for script verification or signing errors to vErrorsRet. */
static void TxInErrorToJSON(const CTxIn& txin, UniValue& vErrorsRet, const std::string& strMessage)
{
UniValue entry(UniValue::VOBJ);
entry.push_back(Pair("txid", txin.prevout.hash.ToString()));
entry.push_back(Pair("vout", (uint64_t)txin.prevout.n));
entry.push_back(Pair("scriptSig", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
entry.push_back(Pair("sequence", (uint64_t)txin.nSequence));
entry.push_back(Pair("error", strMessage));
vErrorsRet.push_back(entry);
}
UniValue signrawtransaction(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 4)
throw runtime_error(
"signrawtransaction \"hexstring\" ( [{\"txid\":\"id\",\"vout\":n,\"scriptPubKey\":\"hex\",\"redeemScript\":\"hex\"},...] [\"privatekey1\",...] sighashtype )\n"
"\nSign inputs for raw transaction (serialized, hex-encoded).\n"
"The second optional argument (may be null) is an array of previous transaction outputs that\n"
"this transaction depends on but may not yet be in the block chain.\n"
"The third optional argument (may be null) is an array of base58-encoded private\n"
"keys that, if given, will be the only keys used to sign the transaction.\n"
#ifdef ENABLE_WALLET
+ HelpRequiringPassphrase() + "\n"
#endif
"\nArguments:\n"
"1. \"hexstring\" (string, required) The transaction hex string\n"
"2. \"prevtxs\" (string, optional) An json array of previous dependent transaction outputs\n"
" [ (json array of json objects, or 'null' if none provided)\n"
" {\n"
" \"txid\":\"id\", (string, required) The transaction id\n"
" \"vout\":n, (numeric, required) The output number\n"
" \"scriptPubKey\": \"hex\", (string, required) script key\n"
" \"redeemScript\": \"hex\" (string, required for P2SH) redeem script\n"
" }\n"
" ,...\n"
" ]\n"
"3. \"privatekeys\" (string, optional) A json array of base58-encoded private keys for signing\n"
" [ (json array of strings, or 'null' if none provided)\n"
" \"privatekey\" (string) private key in base58-encoding\n"
" ,...\n"
" ]\n"
"4. \"sighashtype\" (string, optional, default=ALL) The signature hash type. Must be one of\n"
" \"ALL\"\n"
" \"NONE\"\n"
" \"SINGLE\"\n"
" \"ALL|ANYONECANPAY\"\n"
" \"NONE|ANYONECANPAY\"\n"
" \"SINGLE|ANYONECANPAY\"\n"
"\nResult:\n"
"{\n"
" \"hex\" : \"value\", (string) The hex-encoded raw transaction with signature(s)\n"
" \"complete\" : true|false, (boolean) If the transaction has a complete set of signatures\n"
" \"errors\" : [ (json array of objects) Script verification errors (if there are any)\n"
" {\n"
" \"txid\" : \"hash\", (string) The hash of the referenced, previous transaction\n"
" \"vout\" : n, (numeric) The index of the output to spent and used as input\n"
" \"scriptSig\" : \"hex\", (string) The hex-encoded signature script\n"
" \"sequence\" : n, (numeric) Script sequence number\n"
" \"error\" : \"text\" (string) Verification or signing error related to the input\n"
" }\n"
" ,...\n"
" ]\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("signrawtransaction", "\"myhex\"")
+ HelpExampleRpc("signrawtransaction", "\"myhex\"")
);
#ifdef ENABLE_WALLET
LOCK2(cs_main, pwalletMain ? &pwalletMain->cs_wallet : NULL);
#else
LOCK(cs_main);
#endif
RPCTypeCheck(params, boost::assign::list_of(UniValue::VSTR)(UniValue::VARR)(UniValue::VARR)(UniValue::VSTR), true);
vector<unsigned char> txData(ParseHexV(params[0], "argument 1"));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
vector<CMutableTransaction> txVariants;
while (!ssData.empty()) {
try {
CMutableTransaction tx;
ssData >> tx;
txVariants.push_back(tx);
}
catch (const std::exception&) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
}
}
if (txVariants.empty())
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Missing transaction");
// mergedTx will end up with all the signatures; it
// starts as a clone of the rawtx:
CMutableTransaction mergedTx(txVariants[0]);
// Fetch previous transactions (inputs):
CCoinsView viewDummy;
CCoinsViewCache view(&viewDummy);
{
LOCK(mempool.cs);
CCoinsViewCache &viewChain = *pcoinsTip;
CCoinsViewMemPool viewMempool(&viewChain, mempool);
view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view
BOOST_FOREACH(const CTxIn& txin, mergedTx.vin) {
const uint256& prevHash = txin.prevout.hash;
CCoins coins;
view.AccessCoins(prevHash); // this is certainly allowed to fail
}
view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long
}
bool fGivenKeys = false;
CBasicKeyStore tempKeystore;
if (params.size() > 2 && !params[2].isNull()) {
fGivenKeys = true;
UniValue keys = params[2].get_array();
for (unsigned int idx = 0; idx < keys.size(); idx++) {
UniValue k = keys[idx];
CBitcoinSecret vchSecret;
bool fGood = vchSecret.SetString(k.get_str());
if (!fGood)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
CKey key = vchSecret.GetKey();
if (!key.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range");
tempKeystore.AddKey(key);
}
}
#ifdef ENABLE_WALLET
else if (pwalletMain)
EnsureWalletIsUnlocked();
#endif
// Add previous txouts given in the RPC call:
if (params.size() > 1 && !params[1].isNull()) {
UniValue prevTxs = params[1].get_array();
for (unsigned int idx = 0; idx < prevTxs.size(); idx++) {
const UniValue& p = prevTxs[idx];
if (!p.isObject())
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}");
UniValue prevOut = p.get_obj();
RPCTypeCheckObj(prevOut, boost::assign::map_list_of("txid", UniValue::VSTR)("vout", UniValue::VNUM)("scriptPubKey", UniValue::VSTR));
uint256 txid = ParseHashO(prevOut, "txid");
int nOut = find_value(prevOut, "vout").get_int();
if (nOut < 0)
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout must be positive");
vector<unsigned char> pkData(ParseHexO(prevOut, "scriptPubKey"));
CScript scriptPubKey(pkData.begin(), pkData.end());
{
CCoinsModifier coins = view.ModifyCoins(txid);
if (coins->IsAvailable(nOut) && coins->vout[nOut].scriptPubKey != scriptPubKey) {
string err("Previous output scriptPubKey mismatch:\n");
err = err + ScriptToAsmStr(coins->vout[nOut].scriptPubKey) + "\nvs:\n"+
ScriptToAsmStr(scriptPubKey);
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err);
}
if ((unsigned int)nOut >= coins->vout.size())
coins->vout.resize(nOut+1);
coins->vout[nOut].scriptPubKey = scriptPubKey;
coins->vout[nOut].nValue = 0; // we don't know the actual output value
}
// if redeemScript given and not using the local wallet (private keys
// given), add redeemScript to the tempKeystore so it can be signed:
if (fGivenKeys && scriptPubKey.IsPayToScriptHash()) {
RPCTypeCheckObj(prevOut, boost::assign::map_list_of("txid", UniValue::VSTR)("vout", UniValue::VNUM)("scriptPubKey", UniValue::VSTR)("redeemScript",UniValue::VSTR));
UniValue v = find_value(prevOut, "redeemScript");
if (!v.isNull()) {
vector<unsigned char> rsData(ParseHexV(v, "redeemScript"));
CScript redeemScript(rsData.begin(), rsData.end());
tempKeystore.AddCScript(redeemScript);
}
}
}
}
#ifdef ENABLE_WALLET
const CKeyStore& keystore = ((fGivenKeys || !pwalletMain) ? tempKeystore : *pwalletMain);
#else
const CKeyStore& keystore = tempKeystore;
#endif
int nHashType = SIGHASH_ALL;
if (params.size() > 3 && !params[3].isNull()) {
static map<string, int> mapSigHashValues =
boost::assign::map_list_of
(string("ALL"), int(SIGHASH_ALL))
(string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY))
(string("NONE"), int(SIGHASH_NONE))
(string("NONE|ANYONECANPAY"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY))
(string("SINGLE"), int(SIGHASH_SINGLE))
(string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY))
;
string strHashType = params[3].get_str();
if (mapSigHashValues.count(strHashType))
nHashType = mapSigHashValues[strHashType];
else
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid sighash param");
}
bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
// Script verification errors
UniValue vErrors(UniValue::VARR);
// Sign what we can:
for (unsigned int i = 0; i < mergedTx.vin.size(); i++) {
CTxIn& txin = mergedTx.vin[i];
const CCoins* coins = view.AccessCoins(txin.prevout.hash);
if (coins == NULL || !coins->IsAvailable(txin.prevout.n)) {
TxInErrorToJSON(txin, vErrors, "Input not found or already spent");
continue;
}
const CScript& prevPubKey = coins->vout[txin.prevout.n].scriptPubKey;
txin.scriptSig.clear();
// Only sign SIGHASH_SINGLE if there's a corresponding output:
if (!fHashSingle || (i < mergedTx.vout.size()))
SignSignature(keystore, prevPubKey, mergedTx, i, nHashType);
// ... and merge in other signatures:
BOOST_FOREACH(const CMutableTransaction& txv, txVariants) {
txin.scriptSig = CombineSignatures(prevPubKey, mergedTx, i, txin.scriptSig, txv.vin[i].scriptSig);
}
ScriptError serror = SCRIPT_ERR_OK;
if (!VerifyScript(txin.scriptSig, prevPubKey, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker(&mergedTx, i), &serror)) {
TxInErrorToJSON(txin, vErrors, ScriptErrorString(serror));
}
}
bool fComplete = vErrors.empty();
UniValue result(UniValue::VOBJ);
result.push_back(Pair("hex", EncodeHexTx(mergedTx)));
result.push_back(Pair("complete", fComplete));
if (!vErrors.empty()) {
result.push_back(Pair("errors", vErrors));
}
return result;
}
UniValue sendrawtransaction(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 3)
throw runtime_error(
"sendrawtransaction \"hexstring\" ( allowhighfees instantsend )\n"
"\nSubmits raw transaction (serialized, hex-encoded) to local node and network.\n"
"\nAlso see createrawtransaction and signrawtransaction calls.\n"
"\nArguments:\n"
"1. \"hexstring\" (string, required) The hex string of the raw transaction)\n"
"2. allowhighfees (boolean, optional, default=false) Allow high fees\n"
"3. instantsend (boolean, optional, default=false) Use InstantSend to send this transaction\n"
"\nResult:\n"
"\"hex\" (string) The transaction hash in hex\n"
"\nExamples:\n"
"\nCreate a transaction\n"
+ HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\" : \\\"mytxid\\\",\\\"vout\\\":0}]\" \"{\\\"myaddress\\\":0.01}\"") +
"Sign the transaction, and get back the hex\n"
+ HelpExampleCli("signrawtransaction", "\"myhex\"") +
"\nSend the transaction (signed hex)\n"
+ HelpExampleCli("sendrawtransaction", "\"signedhex\"") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("sendrawtransaction", "\"signedhex\"")
);
LOCK(cs_main);
RPCTypeCheck(params, boost::assign::list_of(UniValue::VSTR)(UniValue::VBOOL)(UniValue::VBOOL));
// parse hex string from parameter
CTransaction tx;
if (!DecodeHexTx(tx, params[0].get_str()))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
uint256 hashTx = tx.GetHash();
bool fOverrideFees = false;
if (params.size() > 1)
fOverrideFees = params[1].get_bool();
bool fInstantSend = false;
if (params.size() > 2)
fInstantSend = params[2].get_bool();
CCoinsViewCache &view = *pcoinsTip;
const CCoins* existingCoins = view.AccessCoins(hashTx);
bool fHaveMempool = mempool.exists(hashTx);
bool fHaveChain = existingCoins && existingCoins->nHeight < 1000000000;
if (!fHaveMempool && !fHaveChain) {
// push to local node and sync with wallets
CValidationState state;
bool fMissingInputs;
if (!AcceptToMemoryPool(mempool, state, tx, false, &fMissingInputs, false, !fOverrideFees)) {
if (state.IsInvalid()) {
throw JSONRPCError(RPC_TRANSACTION_REJECTED, strprintf("%i: %s", state.GetRejectCode(), state.GetRejectReason()));
} else {
if (fMissingInputs) {
throw JSONRPCError(RPC_TRANSACTION_ERROR, "Missing inputs");
}
throw JSONRPCError(RPC_TRANSACTION_ERROR, state.GetRejectReason());
}
}
} else if (fHaveChain) {
throw JSONRPCError(RPC_TRANSACTION_ALREADY_IN_CHAIN, "transaction already in block chain");
}
if (fInstantSend && !instantsend.ProcessTxLockRequest(tx)) {
throw JSONRPCError(RPC_TRANSACTION_ERROR, "Not a valid InstantSend transaction, see debug.log for more info");
}
RelayTransaction(tx);
return hashTx.GetHex();
}
| [
"[email protected]"
] | |
9e841374c1e86e20998a43ce8dfaba6c382d4104 | 0f2e7c408c54798523d154f9206a78f8332021a5 | /backup/CODE9_1C.CPP | 7bc9cc6191298fc7940ba77bc9240c54c8b0791b | [] | no_license | RabinPhaiju/3rd-sem-project-khec-DSMS | 730ffd4e6ad6f330de216a2d67a8c645f167a234 | 74f09fb1bd98d8c6365eb623eea3b8d323c1eab3 | refs/heads/master | 2022-09-13T10:16:22.657038 | 2022-08-10T04:04:33 | 2022-08-10T04:04:33 | 189,875,730 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 63,662 | cpp | #include<graphics.h>
#include<iostream.h>
#include<stdio.h>
#include<alloc.h>
#include<conio.h>
#include<dos.h>
#include<stdlib.h>
#include<string.h>
#include<fstream.h>
#include<ctype.h>
#include<dir.h>
#define bkclr 1
union REGS in, out;
struct date today;
struct time t;
char string[25];
char charnotice[75],charnotice1[75];
int scrollx,scrollx1;
int ucount,iich;//esc to menu
int cat;//choseCategoty
int adminread;
int end=1,enduser=1,end1=1,end2=1,end3=1,end4=1,end5=1,logincount=0,passcode1,passcode2,passend=1;
int button,x,y,option,ooption,x_co,y_co,displaycount,displaycount1,x_cor,y_cor;
char name[20],password[20],pstring[20],filestring[30];
int sn_temp,itemcode,itemquantity,flag,fileexist;
int ycod,xcod;
double total,total1;
int return_pass;
int return_login=0;
char printname[15];
void login();
void hidemouse();
int callmouse();
void callprogramend();
void displayforever();
void alwaysdisplay();
void useralwaysdisplay();
void calculatebill();
void additem();
void additem1();
void edititem();
void display();
void display1();
void search();
void deelete();
void exxit();
void cusdetail();
void vendetail();
void finance();
void finance1(int,int,int);
void financeMonthy();
void finance2(int,int,int);
void history();
void checkexp();
void time();
void passwordMatch();
void getmousepos(int *,int *,int *);
void buytoreceipt();
void displayAddCart();
long input(int,int,char[]);
struct record
{
char goodname1[20],vendor1[20];
int quantity1;
long price1,rs1;
};
struct customer
{
char cusname[25],phoneno[14];
double money;
int yr,mo,da;
};
class userpass
{
private:
char USER[20],ADDRESS[30],PHONE[14],PASSWORD[8];
public:
void checkpass();
void deletepass();
int loginpass(char[20],char[8]);
};
FILE *p,*pp;
struct record r;
struct customer c;
class Store
{
private:
int sn,quantity;
int expdatem,expdated,expdatey;
char goodname[20],vendor[20],category[15];
long price;
public:
void getGoodData();
void displayGoodData();
void searchGoodDataByName();
void searchGoodDataByCode();
void deleteGoodData();
void editGoodData();
void cart();
void copyfile();
void checkExpDate();
void vendorDetail();
void choseCategory();
void notice();
};
void Store::copyfile()
{
ifstream fin;
ofstream fout;
fin.open("c:\\turboc3\\file\\record3.exe",ios::in|ios::binary);
fout.open("c:\\turboc3\\file\\temp",ios::out|ios::binary);
fin.read((char *)this,sizeof(*this));
while(!fin.eof())
{
fout.write((char *)this,sizeof(*this));
fin.read((char *)this,sizeof(*this));
}
fin.close();
fout.close();
}
void Store::vendorDetail()
{
cleardevice();
end4=1;
ifstream fin;
fin.open("c:\\turboc3\\file\\record3.exe",ios::in|ios::binary);
fin.read((char *)this,sizeof(*this));
display100:
rectangle(25,100,590,410);
displayforever();
ycod=9,xcod=5;
displaycount1=0;
while(!fin.eof())
{
if(kbhit()) { getch(); }
hidemouse();
gotoxy(30,6); cout<<" Vendor Information";
gotoxy(5,8); cout<<" Vendor";
gotoxy(25,8); cout<<"Product";
gotoxy(45,8); cout<<"Quantity";
gotoxy(65,8); cout<<"Amount";
gotoxy(xcod,ycod); cout<<vendor;
gotoxy(xcod+20,ycod); cout<<goodname;
gotoxy(xcod+40,ycod); cout<<quantity;
gotoxy(xcod+60,ycod); cout<<price;
callmouse();
fin.read((char *)this,sizeof(*this));
ycod=ycod+1;
displaycount1=displaycount1+1;
if(displaycount1==17)
{
if(!fin.eof())
{ outtextxy(310,30," NEXT");
rectangle(485,35,545,55);
}
rectangle(47,35,112,53);
outtextxy(50,30," BACK ");
while(!kbhit())
{
getmousepos(&button,&x,&y);
if(button ==1)
{
if(x>=485 && x<=545 && y>=35 && y<=55)
{ ungetch('\n'); }
else if(x>=47 && x<=112 && y>=35 && y<=53)
{ goto menu100; }
}
}
getch(); clrscr(); cleardevice(); goto display100;
}
}
fin.close();
rectangle(47,35,112,53);
outtextxy(50,30," BACK ");
while(end4==1)
{
getmousepos(&button,&x,&y);
if(button ==1)
{
if(x>=47 && x<=112 && y>=35 && y<=53)
{ end4=0; }
else button=-1;
} }
menu100:
hidemouse();
cleardevice();
displayforever();
}
void Store::cart() //cart ma item rakhna
{
flag=0;
clrscr();
cleardevice();
displayforever();
gotoxy(12,1);
choseCategory();
itemcode=input(12,6,"Enter item code:");
fstream file;
file.open("c:\\turboc3\\file\\temp",ios::in|ios::out|ios::ate|ios::binary);
file.seekg(0);
for(int IJ=1;IJ<10;IJ++)
{
gotoxy(52,5+IJ); cout<<" ";
}
file.read((char *)this,sizeof(*this));
while(!file.eof())
{
if(itemcode==sn)
{
outtextxy(35,196,"Note:");
rectangle(35,220,607,420);
gotoxy(52,6); cout<<"Item info";
gotoxy(52,7); cout<<"Item Name:"; cout<<goodname;
gotoxy(52,8); cout<<" Vendor:"; cout<<vendor;
gotoxy(52,9); cout<<"Serial no:"; cout<<sn;
gotoxy(52,10); cout<<" price:"; cout<<price;
gotoxy(52,11); cout<<" Quantity:"; cout<<quantity;
gotoxy(52,12); cout<<" Date:"; cout<<expdated; cout<<"/"<<expdatem; cout<<"/"<<expdatey;
line(400,95,607,95);// for before record ko lagi rectangle
rectangle(400,80,607,205);
outtextxy(50,230,"Record found");
rectangle(35,220,607,420);
itemquantity=input(12,7,">Enter quantity:");// func for integer
flag=1;
if(itemquantity>quantity)
{
outtextxy(50,260,"Item left->");
outtextxy(150,260,itoa(quantity,filestring,10));
outtextxy(50,290,"Add again");
outtextxy(50,320,"Enter any key to continue");
getch();
}
else
{
outtextxy(280,230,"-> Pay Rs.:");
outtextxy(405,230,ltoa(itemquantity*price,filestring,10));
/////////////////
p=fopen("c:\\turboc3\\file\\cart.exe","ab");
strcpy(r.goodname1,goodname);
strcpy(r.vendor1,vendor);
r.price1=price;
r.quantity1=itemquantity;
r.rs1=itemquantity*price;
fwrite(&r,sizeof(r),1,p);
fclose(p);
quantity=quantity-itemquantity;
file.seekp(file.tellp()-sizeof(*this));
file.write((char *)this,sizeof(*this));
outtextxy(50,260,"Enter any key to continue");
displayforever();
getch();
}
break;
}
file.read((char *)this,sizeof(*this));
}
if(flag==0)
{outtextxy(35,196,"Note:");
rectangle(35,220,605,420);
outtextxy(50,230,"Record not found");
delay(400);
}
file.close();
hidemouse();
clrscr();
cleardevice();
}
void Store::getGoodData()
{
clrscr();
cleardevice();
displayforever();
hidemouse();
rectangle(85,43,400,63);
rectangle(85,63,400,160);
outtextxy(128,41,"Enter Item Information.");
outtextxy(35,196,"Note:");
rectangle(35,220,605,420);
ifstream fin;
fin.open("c:\\turboc3\\file\\record3.exe",ios::in|ios::binary);
if(!fin)
{
hidemouse();
outtextxy(200,230,"File not found -- Created new file");
sn_temp=0; //if file nae xena vane sn 1 bata suru hunxa
callmouse();
}
else
{
while(!fin.eof())
{
fin.read((char *)this,sizeof(*this));
}
sn_temp=sn; //if file xa vane last+1
}
fin.close();
sn=sn_temp+1;
if(option==1)
{ strcpy(category,"biscuits"); }
if(option==3)
{ strcpy(category,"chocolate"); }
if(option==4)
{ strcpy(category,"drinks"); }
if(option==5)
{ strcpy(category,"noodles"); }
if(option==6)
{ strcpy(category,"rice"); }
if(option==7)
{ strcpy(category,"spices"); }
getdataname:
gotoxy(18,5); cout<<"Item name:";
gets(goodname);
if(goodname[0]=='\0')
{
rectangle(420,45,530,110);
gotoxy(55,4); cout<<"Notice";
gotoxy(55,5); cout<<"Enter name";
goto getdataname;
}
getdatavendor:
gotoxy(55,5); cout<<" ";
gotoxy(18,6); cout<<" Vendor:";
gets(vendor);
if(vendor[0]=='\0')
{
gotoxy(55,4); cout<<"Notice";
gotoxy(54,6); cout<<"Enter Vendor";
goto getdatavendor;
}
gotoxy(54,6); cout<<" ";
price=input(12,7," Price:");
quantity=input(12,8," Quantity:");
getdate(&today);
expdated=today.da_day;
expdatey=today.da_year;
expdatem=today.da_mon+6;
if(expdatem>=13){ expdatem=expdatem-12; expdatey=expdatey+1; }
ofstream fout;
fout.open("c:\\turboc3\\file\\record3.exe",ios::app|ios::binary);
fout.write((char *)this,sizeof(*this));
fout.close();
outtextxy(50,230,"Item Added");
outtextxy(50,280,"Enter any key to continue");
getch();
cleardevice();
}
void Store::choseCategory()
{
callmouse();
int iy=6;
cat=0;
settextstyle(3,0,1);
rectangle(200,50,270,72);
outtextxy(203,47,"Drinks");
rectangle(270,50,340,72);
outtextxy(273,47,"Noodles");
rectangle(340,50,400,72);
outtextxy(343,47,"Rice");
rectangle(400,50,480,72);
outtextxy(403,47,"Spices");
getmousepos(&button,&x,&y);
while(cat==0)
{
getmousepos(&button,&x,&y);
rectangle(40,50,110,72);
outtextxy(43,47,"Biscuits");
rectangle(110,50,200,72);
outtextxy(113,47,"Chocolate");
if(button==1)
{
if(x>=40 && x<=110 && y>=50 && y<=72)
{ cat=1; }
else if(x>=110 && x<=200 && y>=50 && y<=72)
{ cat =2;}
else if(x>=200 && x<=270 && y>=50 && y<=72)
{ cat =3;}
else if(x>=270 && x<=340 && y>=50 && y<=72)
{ cat=4;}
else if(x>=340 && x<=400 && y>=50 && y<=72)
{ cat=5;}
else if(x>=400 && x<=480 && y>=50 && y<=72)
{ cat=6;}
else { button= -1; }
}
if(kbhit())
{
iich=getche();
if(iich==27)
{ hidemouse(); cleardevice();
if(return_pass==1)
{ remove("c:\\turboc3\\file\\cart.exe"); remove("c:\\turboc3\\file\\temp");
useralwaysdisplay();
}
else
{ remove("c:\\turboc3\\file\\cart.exe"); remove("c:\\turboc3\\file\\temp");
alwaysdisplay();
}
}
else
{ cat=7;
rectangle(40,50,110,72);
outtextxy(43,47,"Biscuits");
rectangle(110,50,200,72);
outtextxy(113,47,"Chocolate");
}
}
}
switch(cat)
{
case 1: callmouse(); cat='b'; break;
case 2: callmouse(); cat='c'; break;
case 3: callmouse(); cat='d'; break;
case 4: callmouse(); cat='n'; break;
case 5: callmouse(); cat='r'; break;
case 6: callmouse(); cat='s'; break;
default: break;
}
ifstream fin;
fin.open("c:\\turboc3\\file\\record3.exe",ios::in|ios::binary);
fin.read((char *)this,sizeof(*this));
while(!fin.eof())
{
if(cat==category[0])
{
gotoxy(7,6); cout<<" ";
gotoxy(7,7); cout<<" ";
gotoxy(57,6); cout<<"Code";
gotoxy(64,6); cout<<"Name";
gotoxy(57,iy+2); cout<<sn;
gotoxy(54+10,iy+2); cout<<goodname;
iy++;
}
fin.read((char *)this,sizeof(*this));
}
fin.close();
}
void Store::editGoodData()
{
flag=0;
int INTTT,qty;
gotoxy(5,3); cout<<"Enter a detail to edit goods information";
choseCategory();
INTTT=input(9,6," Code no.:");
fstream file;
file.open("c:\\turboc3\\file\\record3.exe",ios::in|ios::out|ios::ate|ios::binary);
file.seekg(0);
file.read((char *)this,sizeof(*this));
while(!file.eof())
{
if(INTTT==sn)
{
hidemouse();
gotoxy(8,9); cout<<"Previous record";
gotoxy(8,10); cout<<" Item Name:"<<goodname;
gotoxy(8,11); cout<<" price--:"<<price;
gotoxy(8,12);cout<<" Quantity-:"<<quantity;
line(48,143,220,143);
rectangle(48,125,220,200);
price=input(5,14," Enter price:");
qty=input(5,15,"Add quantity:");
quantity=quantity+qty;
getdate(&today);
expdated=today.da_day;
expdatey=today.da_year;
expdatem=today.da_mon+6;
if(expdatem>=13){ expdatem=expdatem-12; expdatey=expdatey+1; }
file.seekp(file.tellp()-sizeof(*this));
file.write((char *)this,sizeof(*this));
flag=1;
outtextxy(50,400,"Updated || Press Enter");
getch();
break;
}
file.read((char *)this,sizeof(*this));
}
if(flag==0)
{
outtextxy(35,196,"Note:");
rectangle(35,220,605,420);
outtextxy(50,300,"No such information found");
outtextxy(50,330,"Enter any key to continue");
getch();
}
file.close();
}
void Store::deleteGoodData()
{
int match=0;
ifstream fin;
ofstream fout;
clrscr();
int INT;
cleardevice();
displayforever();
gotoxy(6,3); cout<<"Enter information to delete item\n";
choseCategory();
INT=input(4,6," Item code:");
fin.open("c:\\turboc3\\file\\record3.exe",ios::in|ios::binary);
if(!fin)
{
outtextxy(35,196,"Note:");
rectangle(35,220,605,420);
outtextxy(50,230,"File not found");
outtextxy(50,260,"Enter any key to continue");
getch();
}
else
{ fin.read((char *)this,sizeof(*this));
while(!fin.eof())
{
if(INT==sn)
{ match=1; }
fin.read((char *)this,sizeof(*this));
}
fin.close();
if(match==1)
{
fout.open("c:\\turboc3\\file\\temprecord3.exe",ios::out|ios::binary);
ifstream fin;
fin.open("c:\\turboc3\\file\\record3.exe",ios::in|ios::binary);
fin.read((char *)this,sizeof(*this));
while(!fin.eof())
{
if(INT==sn)
{
hidemouse();
outtextxy(35,196,"Note:");
rectangle(35,220,305,420);
outtextxy(50,230,"Item found");
outtextxy(50,230,"Item found ...Deleting....");
displayforever();
}
else
{
fout.write((char *)this,sizeof(*this));
}
fin.read((char *)this,sizeof(*this));
}
delay(300);
setcolor(bkclr);
outtextxy(50,230,"Item found ...Deleting....");
setcolor(WHITE);
outtextxy(50,230,"Item found ...Deleted.....");
outtextxy(50,260,"Enter any key to continue");
fin.close();
fout.close();
remove("c:\\turboc3\\file\\record3.exe");
rename("c:\\turboc3\\file\\temprecord3.exe","c:\\turboc3\\file\\record3.exe");
getch();
}
else
{ outtextxy(35,196,"Note:");
rectangle(35,220,605,420);
outtextxy(50,230,"Item not found");
outtextxy(50,260,"Enter any key to continue");
getch();
}
}
hidemouse();
}
void Store::searchGoodDataByName()
{
int flag=0;
char ch[20];
clrscr();
cleardevice();
displayforever();
gotoxy(18,3); cout<<"Enter a Good information to search";
gotoxy(18,4); cout<<"Name:";
gets(ch);
ifstream fin;
fin.open("c:\\turboc3\\file\\record3.exe",ios::in|ios::binary);
fin.read((char *)this,sizeof(*this));
while(!fin.eof())
{
if(!strcmp(ch,goodname))
{
outtextxy(35,196,"Note:");
rectangle(35,220,605,420);
gotoxy(50,5); cout<<"Previous record";
gotoxy(50,6); cout<<" Item Name:"<<goodname;
gotoxy(50,7); cout<<"Vendor :"<<vendor;
gotoxy(50,8); cout<<" Serail no:"<<sn;
gotoxy(50,9); cout<<" price--:"<<price;
gotoxy(50,10);cout<<" Quantity-:"<<quantity;
gotoxy(50,11);cout<<" Date-:"<<expdated<<"/"<<expdatem<<"/"<<expdatey;
line(380,78,550,78);
rectangle(380,60,550,180);
outtextxy(50,230,"Record found");
rectangle(35,220,605,420);
outtextxy(50,260,"Enter any key to continue");
getch();
flag=1;
break;
}
fin.read((char *)this,sizeof(*this));
}
if(flag==0)
{ outtextxy(35,196,"Note:");
rectangle(35,220,605,420);
outtextxy(50,230,"Record not found");
delay(800);
}
fin.close();
hidemouse();
cleardevice();
displayforever();
}
void Store::searchGoodDataByCode()
{
int flag4=0;
int INTT;
clrscr();
cleardevice();
displayforever();
gotoxy(18,3); cout<<"Enter a Good information to search\n";
choseCategory();
INTT=input(4,6," Code:");
for(int II=1;II<10;II++)
{ gotoxy(52,5+II); cout<<" "; }
ifstream fin;
fin.open("c:\\turboc3\\file\\record3.exe",ios::in|ios::binary);
fin.read((char *)this,sizeof(*this));
while(!fin.eof())
{
if(INTT==sn)
{
outtextxy(35,196,"Note:");
rectangle(35,220,605,420);
gotoxy(52,6); cout<<" Item Detail";
gotoxy(52,7); cout<<" Item Name:"<<goodname;
gotoxy(52,8); cout<<"Vendor :"<<vendor;
gotoxy(52,9); cout<<" Serail no:"<<sn;
gotoxy(52,10); cout<<" price--:"<<price;
gotoxy(52,11);cout<<" Quantity-:"<<quantity;
gotoxy(52,12);cout<<" Date-:"<<expdated<<"/"<<expdatem<<"/"<<expdatey;
line(400,95,595,95);
rectangle(400,80,595,200);
outtextxy(50,230,"Record found");
rectangle(35,220,605,420);
outtextxy(50,260,"Enter any key to continue");
getch();
flag4=1;
break;
}
fin.read((char *)this,sizeof(*this));
}
if(flag4==0)
{ outtextxy(35,196,"Note:");
rectangle(35,220,605,420);
outtextxy(50,230,"Record not found");
delay(800);
}
fin.close();
hidemouse();
cleardevice();
displayforever();
}
void Store::displayGoodData()
{
ifstream fin;
fin.open("c:\\turboc3\\file\\record3.exe",ios::in|ios::binary);
if(!fin)
{
hidemouse();
clrscr();
cleardevice();
displayforever();
outtextxy(35,196,"Note:");
rectangle(35,220,605,420);
outtextxy(50,230,"File not found");
callmouse();
}
else
{
fin.read((char *)this,sizeof(*this));
display29:
x_co=40; y_co=100;
displaycount=0;
while(!fin.eof())
{
if(kbhit()) { getch(); }
hidemouse();
displayforever();
outtextxy(55,50,"---------------- List of Items ---------------");
rectangle(35,75,605,420);
displayforever();
settextstyle(11,0,1);
setcolor(RED);
outtextxy(37,85,"Code");
outtextxy(90,85,"Product");
outtextxy(220,85,"Quantity");
outtextxy(310,85,"Price");
outtextxy(389,85,"Vendor");
outtextxy(530,85,"Category");
setcolor(WHITE);
settextstyle(3,0,1);
rectangle(35,75,605,420);
settextstyle(11,0,1);
outtextxy(x_co,y_co,itoa(sn,filestring,10));
outtextxy(x_co+50,y_co,goodname);
outtextxy(x_co+190,y_co,itoa(quantity,filestring,10));
outtextxy(x_co+270,y_co,ltoa(price,filestring,10));
outtextxy(x_co+350,y_co,vendor);
outtextxy(x_co+490,y_co,category);
// outtextxy(x_co+460,y_co,itoa(expdated,filestring,10));
// outtextxy(x_co+470,y_co,"/");
// outtextxy(x_co+480,y_co,itoa(expdatem,filestring,10));
// outtextxy(x_co+490,y_co,"/");
// outtextxy(x_co+500,y_co,itoa(expdatey,filestring,10));
y_co=y_co+11;
rectangle(35,75,605,420);
settextstyle(3,0,1);
displaycount=displaycount+1;
callmouse();
fin.read((char *)this,sizeof(*this));
if(displaycount==29)
{
if(!fin.eof())
{ outtextxy(310,30," NEXT");
rectangle(485,35,545,55);
}
rectangle(47,35,112,53);
outtextxy(50,30," BACK ");
while(!kbhit())
{
getmousepos(&button,&x,&y);
if(button == 1)
{
if(x>=485 && x<=545 && y>=35 && y<=55)
{ ungetch('\n'); }//enter key auto click garna lai
else if(x>=47 && x<=112 && y>=35 && y<=53)
{ goto menu; }
} //file complete check na gari nae menu ma jana lai
}
getch(); if(fin.eof()) { goto menu; }
clrscr(); cleardevice(); goto display29;
}
}
}
menu:
fin.close();
}
void Store::checkExpDate()
{
int click=1;
cleardevice();
displayforever();
ifstream fin;
fin.open("c:\\turboc3\\file\\record3.exe",ios::in|ios::binary);
if(!fin)
{
hidemouse();
clrscr();
cleardevice();
displayforever();
outtextxy(35,196,"Note:");
rectangle(35,220,605,420);
outtextxy(50,230,"File not found");
}
else
{
getdate(&today);
fin.read((char *)this,sizeof(*this));
displayexp:
x_co=40; y_co=100;
displaycount=0;
while(!fin.eof())
{
if(kbhit()) { getch(); }
hidemouse();
displayforever();
outtextxy(55,50,"---------------- Expired Items ---------------");
rectangle(35,75,605,420);
displayforever();
hidemouse();
settextstyle(11,0,1);
setcolor(RED);
outtextxy(37,85,"Code");
outtextxy(90,85,"Product");
outtextxy(220,85,"Quantity");
outtextxy(310,85,"Price");
outtextxy(389,85,"Vendor");
outtextxy(495,85,"Exp.date");
setcolor(WHITE);
settextstyle(3,0,1);
rectangle(35,75,605,420);
settextstyle(11,0,1);
getdate(&today);
if(today.da_day>=expdated && today.da_mon>=expdatem && today.da_year>=expdatey )
{
outtextxy(x_co,y_co,itoa(sn,filestring,10));
outtextxy(x_co+50,y_co,goodname);
outtextxy(x_co+190,y_co,itoa(quantity,filestring,10));
outtextxy(x_co+270,y_co,ltoa(price,filestring,10));
outtextxy(x_co+350,y_co,vendor);
outtextxy(x_co+460,y_co,itoa(expdated,filestring,10));
outtextxy(x_co+470,y_co,"/");
outtextxy(x_co+480,y_co,itoa(expdatem,filestring,10));
outtextxy(x_co+490,y_co,"/");
outtextxy(x_co+500,y_co,itoa(expdatey,filestring,10));
y_co=y_co+11;
rectangle(35,75,605,420);
settextstyle(3,0,1);
displaycount=displaycount+1;
}
callmouse();
fin.read((char *)this,sizeof(*this));
if(displaycount==29)
{
if(!fin.eof())
{ outtextxy(310,30," NEXT");
rectangle(485,35,545,55);
}
rectangle(47,35,112,53);
outtextxy(50,30," BACK ");
while(!kbhit())
{
getmousepos(&button,&x,&y);
if(button == 1)
{
if(x>=485 && x<=545 && y>=35 && y<=55)
{ ungetch('\n'); }
else if(x>=47 && x<=112 && y>=35 && y<=53)
{ goto returnmenu; }
}
}
getch(); if(fin.eof()) { goto returnmenu; }
clrscr(); cleardevice(); goto displayexp;
}
}
}
returnmenu:
rectangle(47,35,112,53);
settextstyle(3,0,1);
outtextxy(50,30," BACK ");
while(click!=0)
{
getmousepos(&button,&x,&y);
if(button==1)
{ if(x>=47 && x<=112 && y>=35 && y<=53)
{click=0;}
}
}
fin.close();
hidemouse();
}
Store s; //class ko object
userpass u;
void time()
{
gettime(&t);
settextstyle(3,0,1);
if(t.ti_hour>12)
{
t.ti_hour=t.ti_hour-12;
outtextxy(348,432,"pm");
}
else
{ outtextxy(348,432,"am"); }
outtextxy(280,432,itoa(t.ti_hour,string,10));
outtextxy(317,432,itoa(t.ti_min,string,10));
// outtextxy(352,432,itoa(t.ti_sec,string,10));
outtextxy(225,432,"Time:");
outtextxy(280,432," : ");
if(t.ti_sec==0)
{
gettime(&t);
settextstyle(3,0,1);
setcolor(WHITE);
setfillstyle(SOLID_FILL,bkclr);
bar(278,438,342,455);
outtextxy(280,432,itoa(t.ti_hour,string,10));
outtextxy(317,432,itoa(t.ti_min,string,10));
settextstyle(11,0,1);
setcolor(WHITE);
delay(990);
}
}
void date() //date print garna lai..
{
getdate(&today);
setcolor(WHITE);
settextstyle(11,0,1);
outtextxy(525,20,itoa(today.da_day,string,10));
outtextxy(556,20,itoa(today.da_mon,string,10));
outtextxy(583,20,itoa(today.da_year,string,10));
outtextxy(477,20," / /");
settextstyle(3,0,1);
}
void storename() //store name print garna lai..
{
setcolor(14);
settextstyle(8,0,2);//2,0,6 //6,0,1 //8,0,1
//setfillstyle(1,9);
//bar(0,0,640,29);
//bar(0,0,19,480);
// bar(621,30,640,480);
//bar(0,434,640,480);
outtextxy(250,2,"Libali Store");
}
int callmouse() //mouse call garna lai..
{
in.x.ax=1;
int86(51,&in,&out);
return 1;
}
void hidemouse()
{
in.x.ax=2;
int86(51,&in,&out);
}
void getmousepos(int *button,int *x, int *y) //mouse ko position search garna...
{
in.x.ax = 3;
int86(51, &in, &out);
*button = out.x.bx;
*x = out.x.cx;
*y = out.x.dx;
}
void restrictmouseptr(int x1,int y1, int x2, int y2)
{ // mouse bahera na pathauna lai..
in.x.ax=7;
in.x.cx=x1;
in.x.dx=x2;
int86(51,&in,&out);
in.x.ax=8;
in.x.cx=y1;
in.x.dx=y2;
int86(51,&in,&out);
}
void Store::notice()
{
for(int tin=0;tin<69;tin++)
{ charnotice[tin]=NULL; charnotice1[tin]=NULL; }
ifstream fin;
fin.open("c:\\turboc3\\file\\record3.exe",ios::in|ios::binary);
if(!fin) //record3 file xena vane, create garxa
{ ofstream fincreate;
fincreate.open("c:\\turboc3\\file\\record3.exe",ios::app| ios::binary);
fincreate.close();
fin.close();
fin.open("c:\\turboc3\\file\\record3.exe",ios::in|ios::binary);
}
fin.read((char *)this,sizeof(*this));
while(!fin.eof())
{
if(quantity<=20)
{
if(strlen(charnotice)<=68)
{
strcat(charnotice,goodname);
strcat(charnotice,"(");
strcat(charnotice,itoa(sn,string,10));
strcat(charnotice,") is ");
strcat(charnotice,itoa(quantity,string,10));
strcat(charnotice,"left. ");
}
else if(strlen(charnotice1)<=68)
{
strcat(charnotice1,goodname);
strcat(charnotice1,"(");
strcat(charnotice1,itoa(sn,string,10));
strcat(charnotice1,") is ");
strcat(charnotice1,itoa(quantity,string,10));
strcat(charnotice1,"left. ");
}
}
fin.read((char *)this,sizeof(*this));
}
fin.close();
}
void rectangle1()
{
setcolor(3);
rectangle(118,64,230,84);
rectangle(118,94,230,113);
rectangle(118,124,230,145);
rectangle(118,154,230,176);
rectangle(118,184,230,205);
rectangle(118,214,230,235);
rectangle(118,243,230,264);
rectangle(295,64,450,84);
rectangle(295,94,450,113);
rectangle(295,124,450,145);
rectangle(295,154,450,176);
rectangle(295,184,450,205);
rectangle(295,214,450,238);
setcolor(WHITE);
}
void rectangle2()
{
setcolor(3);
rectangle(117,63,231,85);
rectangle(117,93,231,114);
rectangle(117,123,231,146);
rectangle(117,153,231,177);
rectangle(117,183,231,206);
rectangle(117,213,231,236);
rectangle(117,242,231,265);
rectangle(294,63,451,85);
rectangle(294,93,451,114);
rectangle(294,123,451,146);
rectangle(294,153,451,177);
rectangle(294,183,451,206);
rectangle(294,213,451,239);
setcolor(WHITE);
}
void menu() //main menu..
{
if(return_pass==2)
{
settextstyle(11,0,1);
outtextxy(30,35,"Admin:");
outtextxy(80,35,printname);
settextstyle(3,0,1);
}
rectangle1();
rectangle2();
setcolor(WHITE);
settextstyle(3,0,1);
outtextxy(95,60," Calculate bill");
outtextxy(95,90," Add item");
outtextxy(95,120," Edit item");
outtextxy(95,150," Display All");
outtextxy(95,180," Search item");
outtextxy(95,210," Delete item");
outtextxy(95,240," Exit");
outtextxy(302,60,"Customer Detail");
outtextxy(302,90,"Vendor Detail");
outtextxy(302,120,"Finance");
outtextxy(302,150,"Check Expiration");
outtextxy(302,180,"Add User ");
outtextxy(302,210,"Delete User");
}
void usermenu() //user menu..
{
if(return_pass==1)
{
settextstyle(11,0,1);
outtextxy(30,35,"User:");
outtextxy(70,35,printname);
settextstyle(3,0,1);
}
rectangle(118,64,230,84);
rectangle(118,94,230,113);
rectangle(118,124,230,145);
rectangle(118,154,230,176);
rectangle(118,184,230,205);
rectangle(118,214,230,235);
rectangle(295,64,450,84);
rectangle(295,94,450,113);
setcolor(WHITE);
settextstyle(3,0,1);
outtextxy(95,60," Calculate bill");
outtextxy(95,90," Add item");
outtextxy(95,120," Edit item");
outtextxy(95,150," Display All");
outtextxy(95,180," Search item");
outtextxy(95,210," Exit");
outtextxy(302,60,"Customer Detail");
outtextxy(302,90,"Check Expiration");
}
void main()
{
//importbackup();
mkdir("c:\\turboc3\\file");
return_pass=0;
int gd=DETECT, gm,status;
initgraph(&gd,&gm,"c:\\turboc3\\bgi");
ifstream finlogin;
finlogin.open("c:\\turboc3\\file\\log.exe",ios::in | ios::binary);
if(!finlogin)
{
finlogin.close(); u.checkpass(); login();
}
else
// { finlogin.close(); login(); }
alwaysdisplay();
getch();
}
void passwordMatch() //input
{
ucount=0;
while(ucount<8)
{
if(password[ucount]==10) { ucount=15;}
else
{ password[ucount]=getch();
}
if(password[ucount]==8)
{
if(!ucount<=0)
{
gotoxy(38+ucount,13); cout<<" \b";
ucount--;
}
}
else if(password[ucount]==13) break;
else
{ gotoxy(39+ucount,13); cout<<"*"; ucount++; }
}
}
void callprogramend()
{
end=0;
alwaysdisplay();
closegraph();
}
void login()
{
if(logincount==3)
{
displayforever();
outtextxy(200,70,"Incorrect password Attempted"); delay(500);
callprogramend();
}
else
{
clrscr(); /// same place bata input lina lai
cleardevice();
displayforever();
outtextxy(400,30,"Password Attempt=");
outtextxy(40,30,"..LOGIN PAGE..");
rectangle(200,142,440,222);
outtextxy(570,30,itoa(logincount,pstring,10));
gotoxy(28,11);cout<<" Username: ";
gotoxy(28,8); cout<<"Enter Username";
rectangle(300,155,430,177);
loginname:
gotoxy(39,11);
gets(name);
if(name[0]=='\0')
{
gotoxy(28,15); cout<<"Notice:";
gotoxy(35,15); cout<<"Name cant be empty.";
gotoxy(39,11); cout<<" ";
goto loginname;
}
else if(isdigit(name[0]))
{
gotoxy(28,15); cout<<"Notice:";
gotoxy(35,15); cout<<"Name cant be number.";
gotoxy(39,11); cout<<" ";
goto loginname;
}
gotoxy(28,15); cout<<" ";
gotoxy(28,13); cout<<" Password:";
rectangle(300,188,430,210);
gotoxy(28,8); cout<<"Enter password";
passwordMatch();
passcode1= strcmp(password,"password");
passcode2= strcmp(name,"rabin");
return_pass=u.loginpass(name,password);
if((passcode1==0 && passcode2==0) || return_pass==1 || return_login==2)
{
cleardevice();
if(return_pass==1)
{
strcpy(printname,name);
useralwaysdisplay();
}
else
{ if(return_pass==2) { strcpy(printname,name); } alwaysdisplay(); }
}
else
{
outtextxy(200,70,"Incorrect password Attempted"); delay(500);
logincount++;
cleardevice();
login();
}
}
}
void displayforever() // store name, date, mouse rectriction and rectangle....print garna..
{
setbkcolor(bkclr);
rectangle(20,30,620,433);
callmouse();
restrictmouseptr(20,30,620,433);
storename();
date();
}
void alwaysdisplay() // display forever + menu..
{
settextstyle(11,0,1);
outtextxy(10,440," Notice:");
settextstyle(3,0,1);
s.notice();//notice update
scrollx=600,scrollx1=600;
callmouse();
setbkcolor(bkclr);
rectangle(20,30,620,433);
restrictmouseptr(20,30,620,433);
storename();
date();
callmouse();
getmousepos(&button,&x,&y);
hidemouse();
rectangle1();
rectangle2();
callmouse();
while(end!=0)
{
if(scrollx>0 )
{
settextstyle(11,0,1);
setfillstyle(1,bkclr);
bar(0,457,640,467);
outtextxy(scrollx,458,charnotice);
settextstyle(3,0,1);
scrollx--;
scrollx1=600;
}
else
{
if(scrollx==0 && strlen(charnotice1)!=0)
{
settextstyle(11,0,1);
setfillstyle(1,bkclr);
bar(0,457,640,480);
outtextxy(scrollx1,458,charnotice1);
settextstyle(3,0,1);
scrollx1--;
if(scrollx1==0)
{
scrollx=600;
}
}
else scrollx=600;
}
if(kbhit())
{
iich=getche();
if(iich==27)
{ cleardevice(); callprogramend(); callmouse(); }
}
if(kbhit()) { getch(); } // unwanted thau ma keyboard press
menu(); // garyo vane ignore
getmousepos(&button,&x,&y);
if(button == 1)
{
if(x>=118 && x<=230 && y>=64 && y<=84)
{ option=1; }
else if(x>=118 && x<=230 && y>=94 && y<=113)
{ option=2; }
else if(x>=118 && x<=230 && y>=124 && y<=145)
{ option=3; }
else if(x>=118 && x<=230 && y>=154 && y<=176)
{ option=4; }
else if(x>=118 && x<=230 && y>=184 && y<=205)
{ option=5; }
else if(x>=118 && x<=230 && y>=214 && y<=235)
{ option=6; }
else if(x>=118 && x<=230 && y>=243 && y<=264)
{ option=7; }
else if(x>=295 && x<=450 && y>=64 && y<=84)
{ option=8; }
else if(x>=295 && x<=450 && y>=94 && y<=113)
{ option=9; }
else if(x>=295 && x<=450 && y>=124 && y<=145)
{ option=10; }
else if(x>=295 && x<=450 && y>=154 && y<=176)
{ option=11; }
else if(x>=295 && x<=450 && y>=184 && y<=205)
{ option=12; }
else if (x>=295 && x<=450 && y>=214 && y<=238)
{ option=13; }
else option=-1;
hidemouse();
switch(option)
{
case 1: calculatebill(); break;
case 2: delay(150); additem(); break;
case 3: edititem(); break;
case 4: display(); break;
case 5: search(); break;
case 6: deelete(); break;
case 8: cusdetail(); break;
case 9: vendetail(); break;
case 10: hidemouse(); finance(); break;
case 11: checkexp(); break;
case 12: u.checkpass(); break;
case 13: u.deletepass(); break;
case 7: exxit();
default: callmouse(); break;
}
button= -1;
}
// time();
}
cleardevice();
}
void useralwaysdisplay() // display user forever + menu..
{
settextstyle(11,0,1);
outtextxy(10,440," Notice:");
settextstyle(3,0,1);
s.notice();
scrollx=600,scrollx1=600;
setbkcolor(bkclr);
rectangle(20,30,620,433);
restrictmouseptr(20,30,620,433);
storename();
date();
callmouse();
getmousepos(&button,&x,&y);
while(enduser!=0)
{
if(scrollx>0)
{
settextstyle(11,0,1);
setfillstyle(1,bkclr);
bar(0,457,640,480);
outtextxy(scrollx,458,charnotice);
settextstyle(3,0,1);
scrollx--;
scrollx1=600;
}
else
{
if(scrollx==0 && strlen(charnotice1)!=0)
{
settextstyle(11,0,1);
setfillstyle(1,bkclr);
bar(0,457,640,480);
outtextxy(scrollx1,458,charnotice1);
settextstyle(3,0,1);
scrollx1--;
if(scrollx1==0)
{
scrollx=600;
}
}
else scrollx=600;
}
if(kbhit())
{
iich=getche();
if(iich==27)
{ cleardevice(); callprogramend(); callmouse(); }
}
if(kbhit()) { getch(); }
usermenu();
getmousepos(&button,&x,&y);
if(button == 1)
{
if(x>=118 && x<=230 && y>=64 && y<=84)
{ ooption=1; }
else if(x>=118 && x<=230 && y>=94 && y<=113)
{ ooption=2; }
else if(x>=118 && x<=230 && y>=124 && y<=145)
{ ooption=3; }
else if(x>=118 && x<=230 && y>=154 && y<=176)
{ ooption=4; }
else if(x>=118 && x<=230 && y>=184 && y<=205)
{ ooption=5; }
else if(x>=118 && x<=230 && y>=214 && y<=235)
{ ooption=6; }
else if(x>=295 && x<=450 && y>=64 && y<=84)
{ ooption=7; }
else if(x>=295 && x<=450 && y>=94 && y<=113)
{ ooption=8; }
else ooption=-1;
hidemouse();
switch(ooption)
{
case 1: calculatebill(); break;
case 2: delay(150); additem(); break;
case 3: edititem(); break;
case 4: display(); break;
case 5: search(); break;
case 7: cusdetail(); break;
case 8: checkexp(); break;
case 6: exxit();
default: callmouse(); break;
}
button= -1;
}
// time();
}
cleardevice();
}
void calculatebill() //case 1..
{
end3=1;
fileexist=0;
cleardevice();
displayforever();
getmousepos(&button,&x,&y);
s.copyfile();//cart ma quantity decrease garna arko file
delay(150);
ifstream finn;
while(end3!=0)
{
if(kbhit()) { getch(); }
rectangle(20,30,620,433);
restrictmouseptr(20,30,620,433);
storename();
date();
finn.open("c:\\turboc3\\file\\cart.exe",ios::in);
if(finn)
{
fileexist=1;
}
if(fileexist==1)
{
rectangle(310,50,380,75);
outtextxy(330,50,"BUY");
}
p=fopen("c:\\turboc3\\file\\cart.exe","rb");
fread(&r,sizeof(r),1,p);
x_cor=40; y_cor=170;
total=0;
settextstyle(11,0,1);
displayAddCart(); // cart ma vako items print garna
fclose(p);
settextstyle(3,0,1);
rectangle(48,55,165,75);
rectangle(47,85,110,103);
callmouse();
outtextxy(50,50,"Add to cart");
outtextxy(50,80,"Cancel");
outtextxy(35,126,"Cart:");
rectangle(33,150,430,420);
getmousepos(&button,&x,&y);
if(button == 1)
{
if(x>=48 && x<=165 && y>=55 && y<=75)
{ option=1; }
else if(x>=48 && x<=110 && y>=85 && y<=103)
{ option=2; }
else if(x>=310 && x<=380 && y>=50 && y<=75 && fileexist==1 )
{ option=3; } //buy button ko lagi
else option=-1;
hidemouse();
switch(option)
{
case 1: delay(150); s.cart(); break;
case 2: end3=0; remove("c:\\turboc3\\file\\cart.exe"); remove("c:\\turboc3\\file\\temp"); break;
case 3: end3=0; buytoreceipt(); break;
default: callmouse(); break;
}
button= -1;
}
}
clrscr();
cleardevice();
if(return_pass==1)
{ useralwaysdisplay(); }
else
{ alwaysdisplay(); }
finn.close();
}
void displayAddCart()
{
while(!feof(p))
{
outtextxy(40,155,"Name");
outtextxy(154,155,"Vendor");
outtextxy(245,155,"Price");
outtextxy(300,155,"Quantity");
outtextxy(370,155," Rs. ");
outtextxy(x_cor,y_cor,r.goodname1);
outtextxy(x_cor+115,y_cor,r.vendor1);
outtextxy(x_cor+205,y_cor,ltoa(r.price1,filestring,10));
outtextxy(x_cor+270,y_cor,itoa(r.quantity1,filestring,10));
outtextxy(x_cor+332,y_cor,ltoa(r.rs1,filestring,10));
total=total+r.rs1;
y_cor=y_cor+12;
fread(&r,sizeof(r),1,p);
}
gotoxy(55,6); printf("-Total Rs:%.1f",total);
}
void buytoreceipt()
{
char printname[25];
char printphone[14];
int printday,printmon,printyear;
char printfile[30];
clrscr();
cleardevice();
displayforever();
p=fopen("c:\\turboc3\\file\\cart.exe","rb");
fread(&r,sizeof(r),1,p);
settextstyle(11,0,1);
total=0;
displayAddCart();
gotoxy(55,7); printf(" Tax: %.1f",(total*13/100));
total1=total*13/100+total;
gotoxy(55,8); printf(" Total: %.1f",total1);
line(420,110,600,110);
rectangle(33,150,430,420);
settextstyle(3,0,1);
fclose(p);
pp=fopen("c:\\turboc3\\file\\cusinfo.exe","ab");
gotoxy(14,3); cout<<"--> Enter customer info ";
cusNAMEE:
gotoxy(12,4); cout<<"Name :"; gets(printname);
if(printname[0]=='\0')
{
gotoxy(8,6); cout<<"Notice:";
gotoxy(8,7); cout<<"Name cant be empty. ";
gotoxy(17,5); cout<<" ";
goto cusNAMEE;
}
gotoxy(8,6); cout<<" ";
gotoxy(8,7); cout<<" ";
cusPHONEE:
gotoxy(8,5); cout<<"Phone no.:";gets(printphone);
if(printphone[0]=='\0')
{
gotoxy(8,6); cout<<"Notice:";
gotoxy(8,7); cout<<"Phone cant be empty. ";
gotoxy(17,5); cout<<" ";
goto cusPHONEE;
}
else if(printphone[0]!='9')
{
gotoxy(8,6); cout<<"Notice:";
gotoxy(8,7); cout<<"Phone no must start with 9.";
gotoxy(17,5); cout<<" ";
goto cusPHONEE;
}
else if(!isdigit(printphone[0]))
{
gotoxy(8,6); cout<<"Notice:";
gotoxy(8,7); cout<<"Phone cant be character. ";
gotoxy(17,5); cout<<" ";
goto cusPHONEE;
}
if(!isdigit(printphone[9]))
{
gotoxy(8,6); cout<<"Notice:";
gotoxy(8,7); cout<<"Phone no must be 10 digits. ";
gotoxy(17,5); cout<<" ";
goto cusPHONEE;
}
gotoxy(8,6); cout<<" ";
gotoxy(8,7); cout<<" ";
strcpy(c.cusname,printname);
strcpy(c.phoneno,printphone);
c.money=total1;
getdate(&today);
printyear=c.yr=today.da_year;
printmon=c.mo=today.da_mon;
printday=c.da=today.da_day;
fwrite(&c,sizeof(c),1,pp);
fclose(pp);
strcpy(printfile,"c:\\turboc3\\file\\print.txt");
/////
p=fopen("c:\\turboc3\\file\\cart.exe","rb");
ofstream files;
files.open(printfile);
fread(&r,sizeof(r),1,p);
files<<"Bill no.\n";
files<<"Name:"<<printname<<"\n";
files<<"Phone:"<<printphone<<"\n";
files<<"Date of purchase :"<<printday<<"-"<<printmon<<"-"<<printyear<<"\n";
files<<"Rs. price Qty Item\n";
while(!feof(p))
{
files<<r.rs1<<" "<<r.price1<<" "<<r.quantity1<<" "<<r.goodname1<<"\n";
fread(&r,sizeof(r),1,p);
}
files.close();
fclose(p);
outtextxy(70,107,"Enter any key to continue");
getch();
remove("c:\\turboc3\\file\\cart.exe"); //print it before delete
remove("c:\\turboc3\\file\\record3.exe");
rename("c:\\turboc3\\file\\temp","c:\\turboc3\\file\\record3.exe");
hidemouse();
}
void cusdetail() //case 8..
{
cleardevice();
end4=1;
pp=fopen("c:\\turboc3\\file\\cusinfo.exe","rb");
fread(&c,sizeof(c),1,pp);
display10:
rectangle(25,100,590,410);
displayforever();
ycod=9,xcod=5;
displaycount1=0;
while(!feof(pp))
{
if(kbhit()) { getch(); }
hidemouse();
gotoxy(30,6); cout<<"Customer Information";
gotoxy(5,8); cout<<"Customer";
gotoxy(25,8); cout<<"Phone no.";
gotoxy(45,8); cout<<"Paid Ammount";
gotoxy(65,8); cout<<"Paid Date";
gotoxy(xcod,ycod); cout<<c.cusname;
gotoxy(xcod+20,ycod); cout<<c.phoneno;
gotoxy(xcod+40,ycod); cout<<c.money;
gotoxy(xcod+60,ycod); cout<<c.da<<"/"<<c.mo<<"/"<<c.yr;
callmouse();
fread(&c,sizeof(c),1,pp);
ycod=ycod+1;
displaycount1=displaycount1+1;
if(displaycount1==17)
{
if(!feof(pp))
{ outtextxy(310,30," NEXT");
rectangle(485,35,545,55);
}
rectangle(47,35,112,53);
outtextxy(50,30," BACK ");
while(!kbhit())
{
getmousepos(&button,&x,&y);
if(button ==1)
{
if(x>=485 && x<=545 && y>=35 && y<=55)
{ ungetch('\n'); }
else if(x>=47 && x<=112 && y>=35 && y<=53)
{ goto menu1; }
}
}
getch(); clrscr(); cleardevice(); goto display10;
}
}
fclose(pp);
rectangle(47,35,112,53);
outtextxy(50,30," BACK ");
while(end4==1)
{
getmousepos(&button,&x,&y);
if(button ==1)
{
if(x>=47 && x<=112 && y>=35 && y<=53)
{ end4=0; }
else button= -1;
} }
menu1:
hidemouse();
cleardevice();
displayforever();
if(return_pass==1)
{ useralwaysdisplay(); }
else
{ alwaysdisplay(); }
}
void vendetail() //case 9..
{
s.vendorDetail();
if(return_pass==1)
{ useralwaysdisplay(); }
else
{ alwaysdisplay(); }
}
void finance() //case 10..
{
getdate(&today);
finance1(today.da_day,today.da_mon,today.da_year);
}
void financeMonthy()
{
getdate(&today);
finance2(today.da_day,today.da_mon,today.da_year);
}
void finance2(int finday,int finmon,int finyear)
{
cleardevice();
int end55=1;
double totalfinc2=0;
outtextxy(55,55,"Daily");
rectangle(47,60,110,80);
callmouse();
FILE *ppp;
ppp=fopen("c:\\turboc3\\file\\cusinfo.exe","rb");
fread(&c,sizeof(c),1,ppp);
display101:
rectangle(25,100,590,340);
displayforever();
ycod=9,xcod=5;
int displaycount101=0;
while(!feof(ppp))
{
if(kbhit()) { getch(); }
hidemouse();
gotoxy(28,6); cout<<"Financial Report Monthly "<<finmon<<"-"<<finyear;
gotoxy(5,8); cout<<"Customer";
gotoxy(25,8); cout<<"Paid Ammount";
gotoxy(45,8); cout<<"Phone";
if(finmon==c.mo && finyear==c.yr)
{
gotoxy(xcod,ycod); cout<<c.cusname;
gotoxy(xcod+20,ycod); cout<<c.money;
gotoxy(xcod+40,ycod); cout<<c.phoneno;
totalfinc2=totalfinc2+c.money;
ycod=ycod+1;
displaycount101=displaycount101+1;
}
callmouse();
fread(&c,sizeof(c),1,ppp);
if(displaycount101==12)
{
if(!feof(ppp))
{ outtextxy(210,32," NEXT");
rectangle(385,35,445,55);
}
rectangle(47,35,112,53);
outtextxy(50,30," BACK ");
while(!kbhit())
{
getmousepos(&button,&x,&y);
if(button ==1)
{
if(x>=385 && x<=445 && y>=35 && y<=55)
{ ungetch('\n'); }
else if(x>=47 && x<=112 && y>=35 && y<=53)
{ goto menu201; }
}
}
getch(); clrscr(); cleardevice(); goto display101;
}
}
fclose(ppp);
gotoxy(50,23); cout<<"Total : "<<totalfinc2;
gotoxy(50,24); printf(" Vat : %.1f",(totalfinc2*13/100));
gotoxy(50,25); printf("Profit: %.1f",(totalfinc2*2/100));
rectangle(47,35,112,53);
outtextxy(50,30," BACK ");
rectangle(500,52,530,77);
rectangle(530,52,560,77);
outtextxy(502,52,"<-");
outtextxy(533,52,"->");
gotoxy(62,3); cout<<"Change Month";
hidemouse();
outtextxy(55,55,"Daily");
rectangle(47,60,110,80);
callmouse();
while(end55==1)
{
outtextxy(55,55,"Daily");
rectangle(47,60,110,80);
getmousepos(&button,&x,&y);
if(button ==1)
{
if(x>=47 && x<=112 && y>=35 && y<=53)
{ if(return_pass==1)
{ hidemouse(); clrscr(); cleardevice(); useralwaysdisplay(); }
else
{ hidemouse(); clrscr(); cleardevice(); alwaysdisplay(); }
}
else if(x>=47 && x<=110 && y>=60 && y<=80)
{
hidemouse();delay(150); finance();
}
else if(x>=500 && x<=530 && y>=52 && y<=77)
{
if(finmon==1)
{ finmon=13; finyear--; }
delay(150); finance2(finday,finmon-1,finyear);
}
else if(x>=530 && x<=560 && y>=52 && y<=77)
{
getdate(&today);
if(finday>=today.da_day && finmon>=today.da_mon && finyear>=today.da_year)
{ gotoxy(60,6); cout<<" Not Available";}
else
{
if(finmon==12)
{ finmon=0; finyear++; }
delay(150); finance2(finday,finmon+1,finyear);
}
}
else button= -1;
} }
menu201:
hidemouse();
cleardevice();
displayforever();
}
void finance1(int finday,int finmon,int finyear)
{
cleardevice();
end5=1;
double totalfinc=0;
outtextxy(50,55,"Monthly");
rectangle(47,60,120,80);
callmouse();
pp=fopen("c:\\turboc3\\file\\cusinfo.exe","rb");
fread(&c,sizeof(c),1,pp);
display10:
rectangle(25,100,590,340);
displayforever();
ycod=9,xcod=5;
displaycount1=0;
while(!feof(pp))
{
if(kbhit()) { getch(); }
hidemouse();
gotoxy(28,6); cout<<"Financial Report Daily "<<finday<<"-"<<finmon<<"-"<<finyear;
gotoxy(5,8); cout<<"Customer";
gotoxy(25,8); cout<<"Paid Ammount";
gotoxy(45,8); cout<<"Phone";
if(finday==c.da && finmon==c.mo && finyear==c.yr)
{
gotoxy(xcod,ycod); cout<<c.cusname;
gotoxy(xcod+20,ycod); cout<<c.money;
gotoxy(xcod+40,ycod); cout<<c.phoneno;
totalfinc=totalfinc+c.money;
ycod=ycod+1;
displaycount1=displaycount1+1;
}
callmouse();
fread(&c,sizeof(c),1,pp);
if(displaycount1==12)
{
if(!feof(pp))
{ outtextxy(210,32," NEXT");
rectangle(385,35,445,55);
}
rectangle(47,35,112,53);
outtextxy(50,30," BACK ");
while(!kbhit())
{
getmousepos(&button,&x,&y);
if(button ==1)
{
if(x>=385 && x<=445 && y>=35 && y<=55)
{ ungetch('\n'); }
else if(x>=47 && x<=112 && y>=35 && y<=53)
{ goto menu2; }
}
}
getch(); clrscr(); cleardevice(); goto display10;
}
}
fclose(pp);
gotoxy(50,23); cout<<"Total : "<<totalfinc;
gotoxy(50,24); printf(" Vat : %.1f",(totalfinc*13/100));
gotoxy(50,25); printf("Profit: %.1f",(totalfinc*2/100));
rectangle(47,35,112,53);
outtextxy(50,30," BACK ");
rectangle(500,52,530,77);
rectangle(530,52,560,77);
outtextxy(502,52,"<-");
outtextxy(533,52,"->");
hidemouse();
outtextxy(50,55,"Monthly");
rectangle(47,60,120,80);
callmouse();
gotoxy(62,3); cout<<"Change Date";
while(end5==1)
{
outtextxy(50,55,"Monthly");
rectangle(47,60,120,80);
getmousepos(&button,&x,&y);
if(button ==1)
{
if(x>=47 && x<=112 && y>=35 && y<=53)
{ if(return_pass==1)
{ hidemouse(); clrscr(); cleardevice(); useralwaysdisplay(); }
else
{ hidemouse(); clrscr(); cleardevice(); alwaysdisplay(); }
}
else if(x>=47 && x<=120 && y>=60 && y<=80)
{
hidemouse(); delay(150); financeMonthy();
}
else if(x>=500 && x<=530 && y>=52 && y<=77)
{
if(finday==1)
{ finday=32; finmon--; }
if(finmon==0)
{ finmon=12; finyear--; }
delay(150); finance1(finday-1,finmon,finyear);
}
else if(x>=530 && x<=560 && y>=52 && y<=77)
{
getdate(&today);
if(finday>=today.da_day && finmon>=today.da_mon && finyear>=today.da_year)
{ gotoxy(60,6); cout<<" Not Available";}
else
{
if(finday==31)
{ finday=0; finmon++; }
if(finmon==13)
{ finmon=1; finyear++; }
delay(150); finance1(finday+1,finmon,finyear);
}
}
else button= -1;
} }
menu2:
hidemouse();
cleardevice();
displayforever();
}
void checkexp() //case 11..
{
s.checkExpDate();
cleardevice();
if(return_pass==1)
{ useralwaysdisplay(); }
else
{ alwaysdisplay(); }
hidemouse();
}
void additem() //case 2..
{
end1=1;
cleardevice();
displayforever();
getmousepos(&button,&x,&y);
while(end1!=0)
{//mouse lag then print menu here./////
if(kbhit()) { getch(); }
rectangle(53,63,145,84);
rectangle(53,93,145,114);
rectangle(53,123,145,144);
rectangle(53,153,145,174);
rectangle(53,183,145,204);
rectangle(53,213,145,234); //
rectangle(27,35,76,53);
outtextxy(60,60,"Biscuit"); //category
outtextxy(60,90,"Chocolate");
outtextxy(60,120,"Drinks");
outtextxy(60,150,"Noodles");
outtextxy(60,180,"Rice");
outtextxy(60,210,"Spices");
outtextxy(30,30,"BACK");
getmousepos(&button,&x,&y);
if(button == 1)
{
if(x>=48 && x<=137 && y>=65 && y<=81)
{ option=1; }
else if(x>=48 && x<=137 && y>=95 && y<=111)
{ option=3; }
else if(x>=48 && x<=137 && y>=125 && y<=141)
{ option=4; }
else if(x>=48 && x<=137 && y>=155 && y<=171)
{ option=5; }
else if(x>=48 && x<=137 && y>=185 && y<=201)
{ option=6; }
else if(x>=48 && x<=137 && y>=215 && y<=231)
{ option=7; }
else if(x>=28 && x<=76 && y>=35 && y<=53)
{ option=2; }
else option=-1;
hidemouse();
switch(option)
{
case 1: additem1(); end1=0; break; /// end1 vaya paxi, fere additem ma jana pauxa....
case 2: end1=0; break;
case 3: additem1(); end1=0; break;
case 4: additem1(); end1=0; break;
case 5: additem1(); end1=0; break;
case 6: additem1(); end1=0; break;
case 7: additem1(); end1=0; break;
default: callmouse(); break;
}
button= -1;
}
}
cleardevice();
if(return_pass==1)
{ useralwaysdisplay(); }
else
{ alwaysdisplay(); }
}
void additem1()
{
s.getGoodData();
}
void edititem() //case 3..
{
clrscr();
cleardevice();
displayforever();
s.editGoodData();
clrscr();
cleardevice();
if(return_pass==1)
{ useralwaysdisplay(); }
else
{ alwaysdisplay(); }
}
void display() //display all list ...
{
end2=1;
clrscr();
cleardevice();
displayforever();
display1();
getmousepos(&button,&x,&y);
while(end2!=0)
{//mouse lag then print menu here./////
rectangle(47,35,112,53);
outtextxy(50,30," BACK ");
getmousepos(&button,&x,&y);
if(button == 1)
{
if(x>=48 && x<=112 && y>=35 && y<=53)
{ option=1; }
else option=-1;
hidemouse();
switch(option)
{
case 1:cleardevice();
if(return_pass==1)
{ useralwaysdisplay(); }
else
{ alwaysdisplay(); } end2=0; break; /// end1 vaya paxi, fere additem ma jana pauxa....
default: callmouse(); break;
}
button= -1;
}
}
cleardevice();
if(return_pass==1)
{ useralwaysdisplay(); }
else
{ alwaysdisplay(); }
}
void display1() //case 4..
{
s.displayGoodData();
}
void search() //case 5...............
{
clrscr();
cleardevice();
displayforever();
int searchend=1;
int searchchoice;
while(searchend!=0)
{
if(kbhit()) { getch(); }
gotoxy(9,4); cout<<"Search By. ";
rectangle(50,70,130,95);
outtextxy(50,70," Name ");
rectangle(50,110,130,135);
outtextxy(50,110," Code ");
rectangle(50,150,130,175);
outtextxy(50,150," Cancel ");
getmousepos(&button,&x,&y);
if(button==1)
{
if(x>=50 && x<=130 && y>=70 && y<=95)
{ searchchoice=1; }
else if(x>=50 && x<=130 && y>=110 && y<=135)
{ searchchoice =2; }
else if(x>=50 && x<=130 && y>=150 && y<=175)
{ searchchoice =3; }
else searchchoice=-1;
switch(searchchoice)
{
case 1: hidemouse(); searchend=0; s.searchGoodDataByName(); break;
case 2: hidemouse(); searchend=0; s.searchGoodDataByCode(); break;
case 3: searchend=0; delay(150); hidemouse(); break;
default: break;
}
button= -1;
}
}
cleardevice();
if(return_pass==1)
{ useralwaysdisplay(); }
else
{ alwaysdisplay(); }
}
void deelete() //case 6..
{
s.deleteGoodData();
cleardevice();
alwaysdisplay();
}
void exxit() //case 7...
{
cleardevice();
displayforever();
outtextxy(50,50,"Have a Nice Day"); delay(150);
cleardevice();
closegraph();
//exportbackup();
end=0;
}
long input(int x_cord,int y_cord,char ch_cord[30])
{
long aaa;
int flag3;
char chhh[13];
again:
flag3=1;
gotoxy(x_cord,y_cord); cout<<ch_cord; gets(chhh);
if(chhh[0]==NULL)
{ flag3=0; }
for(int i=0; chhh[i]!='\0';i++)
{
if(!isdigit(chhh[i]))
{ flag3=0; break; }
}
if(flag3==0)
{
gotoxy(x_cord+16,y_cord); cout<<" ";
gotoxy(x_cord,y_cord+1); cout<<"->Number only";
goto again;
}
aaa=atol(chhh);
return(aaa);
}
void userpass::checkpass() //case 12...
{
char pass_bb[9];
pass_bb[8]='#';
int vv,get;
cleardevice();
displayforever();
ifstream fin;
ofstream fout;
int flagpass=0, flagpass1=0;
fin.open("c:\\turboc3\\file\\log.exe",ios::in | ios::binary);
if(!fin)
{
flagpass1=1;
gotoxy(25,3); cout<<"Admin Registration";
}
else
{
gotoxy(25,3); cout<<"New User Registration";
fin.read((char *)this,sizeof(* this));
gotoxy(15,17); cout<<"User Name";
gotoxy(30,17); cout<<"Address";
gotoxy(45,17); cout<<"Phone no";
gotoxy(60,17); cout<<"Password";
rectangle(50,250,580,400);
int yb=19;
while(!fin.eof())
{
gotoxy(10,yb); cout<<"User:";
gotoxy(9,19); cout<<"Admin:";
gotoxy(17,yb); cout<<USER;
gotoxy(32,yb); cout<<ADDRESS;
gotoxy(47,yb); cout<<PHONE;
for(vv=0;vv<8;vv++)
{
pass_bb[vv]=PASSWORD[vv];
}
gotoxy(62,yb); cout<<pass_bb;
flagpass++;
yb++;
fin.read((char *)this,sizeof(* this));
}
fin.close();
}
if(flagpass>5 && flagpass1==0)
{
gotoxy(22,9); cout<<"-- User are more than 5 --";
}
else
{
fout.open("c:\\turboc3\\file\\log.exe",ios::app | ios::binary);
hidemouse();
ifstream check;
check.open("c:\\turboc3\\file\\log1",ios::in | ios::binary);
if(check)
{
gotoxy(25,3); cout<<"Admin Registration";
}
check.close();
gotoxy(29,7); cout<<"Username:";
rectangle(200,80,440,218);
gotoxy(25,5); cout<<"-> Enter Username";
rectangle(300,89,430,113);
loginUSER:
gotoxy(39,7); gets(USER);
if(USER[0]=='\0')
{
gotoxy(28,15); cout<<"Notice:";
gotoxy(35,15); cout<<"Name cant be empty.";
gotoxy(39,7); cout<<" ";
goto loginUSER;
}
else if(isdigit(USER[0]))
{
gotoxy(28,15); cout<<"Notice:";
gotoxy(35,15); cout<<"Name cant be number.";
gotoxy(39,7); cout<<" ";
goto loginUSER;
}
gotoxy(28,15); cout<<" ";
gotoxy(29,9); cout<<" Address:";
rectangle(300,122,430,144);
gotoxy(25,5); cout<<"-> Enter Address";
loginADDRESS:
gotoxy(39,9); gets(ADDRESS);
if(ADDRESS[0]=='\0')
{
gotoxy(28,15); cout<<"Notice:";
gotoxy(35,15); cout<<"Address cant be empty.";
gotoxy(39,9); cout<<" ";
goto loginADDRESS;
}
else if(isdigit(ADDRESS[0]))
{
gotoxy(28,15); cout<<"Notice:";
gotoxy(35,15); cout<<"Address cant be number.";
gotoxy(39,9); cout<<" ";
goto loginADDRESS;
}
gotoxy(28,15); cout<<" ";
gotoxy(29,11); cout<<" Phone:";
rectangle(300,155,430,177);
gotoxy(25,5); cout<<"-> Enter phone no.";
loginPHONE:
gotoxy(39,11); gets(PHONE);
int zz=0;
zz=strlen(PHONE);
if(PHONE[0]=='\0')
{
gotoxy(28,15); cout<<"Notice:";
gotoxy(35,15); cout<<"Phone cant be empty. ";
gotoxy(39,11); cout<<" ";
goto loginPHONE;
}
else if(!isdigit(PHONE[0]))
{
gotoxy(28,15); cout<<"Notice:";
gotoxy(35,15); cout<<"Phone cant be character. ";
gotoxy(39,11); cout<<" ";
goto loginPHONE;
}
else if(zz!=10)
{
gotoxy(28,15); cout<<"Notice:";
gotoxy(35,15); cout<<"Phone number must be 10 digit.";
gotoxy(39,11); cout<<" ";
goto loginPHONE;
}
else if(PHONE[0]!=57)
{
gotoxy(28,15); cout<<"Notice:";
gotoxy(35,15); cout<<"Phone number must start with 9. ";
gotoxy(39,11); cout<<" ";
goto loginPHONE;
}
gotoxy(28,15); cout<<" ";
gotoxy(29,13); cout<<"Password:";
rectangle(300,188,430,210);
gotoxy(25,5); cout<<"-> Enter New password";
ucount=0;
while(ucount<8)
{
gotoxy(39,13); cout<<" ";
passwordMatch();
if(password[0]==13)
{ gotoxy(28,15); cout<<" Password can't be empty"; }
else if(ucount<7)
{ gotoxy(28,15); cout<<" Password must be 8 character"; }
else if(ucount==8)
{ gotoxy(28,15); cout<<" Account Added "; }
}
for(int v=0;v<8;v++)
{
PASSWORD[v]=password[v]+5;
}
fout.write((char *)this,sizeof(*this));
}
fout.close();
ifstream finadmin;
ofstream foutadmin;
finadmin.open("c:\\turboc3\\file\\log1",ios::in|ios::binary);
foutadmin.open("c:\\turboc3\\file\\log.exe",ios::app|ios::binary);
finadmin.read((char *)this,sizeof(*this));
if(finadmin) //if log1 xa vane copy hunxa///
{ finadmin.read((char *)this,sizeof(*this));
while(!finadmin.eof())
{
foutadmin.write((char *)this,sizeof(*this));
finadmin.read((char *)this,sizeof(*this));
}
}
finadmin.close();
foutadmin.close();
remove("c:\\turboc3\\file\\log1");
callmouse();
rectangle(460,35,545,60);
outtextxy(310,30," Continue.");
while(get!=13)
{
while(!kbhit())
{
getmousepos(&button,&x,&y);
if(button==1)
{if(x>=460 && x<=545 && y>=35 && y<=60){ungetch(13);}}}
get=getch();
}
clrscr();
cleardevice();
displayforever();
}
void userpass::deletepass() //case 13...
{
char pass_bbb[9];
pass_bbb[8]='#';
char us[15],ps[8];
int vvb,same=0,gett,admincount;
cleardevice();
displayforever();
ifstream fin;
ofstream fout;
ofstream foout;
int flagpassb=0, flagpassb1=0;
fin.open("c:\\turboc3\\file\\log.exe",ios::in | ios::binary);
foout.open("c:\\turboc3\\file\\log1",ios::out | ios::binary);
if(!fin)
{
flagpassb1=1;
}
else
{
fin.read((char *)this,sizeof(* this));
gotoxy(15,17); cout<<"User Name";
gotoxy(30,17); cout<<"Address";
gotoxy(45,17); cout<<"Phone no";
gotoxy(60,17); cout<<"Password";
rectangle(50,250,580,400);
int ybb=19;
while(!fin.eof())
{
gotoxy(9,19); cout<<"Admin:";
gotoxy(10,ybb); cout<<"User:";
gotoxy(17,ybb); cout<<USER;
gotoxy(32,ybb); cout<<ADDRESS;
gotoxy(47,ybb); cout<<PHONE;
for(vvb=0;vvb<8;vvb++)
{
pass_bbb[vvb]=PASSWORD[vvb];
}
gotoxy(62,ybb); cout<<pass_bbb;
flagpassb++;
ybb++;
foout.write((char *)this,sizeof(*this));
fin.read((char *)this,sizeof(* this));
}
fin.close();
foout.close();
}
if(flagpassb==0 || flagpassb1==1)
{
gotoxy(20,7); cout<<"-> Empty list";
}
else
{
fin.open("c:\\turboc3\\file\\log.exe",ios::in | ios::binary);
fout.open("c:\\turboc3\\file\\log",ios::app | ios::binary);
hidemouse();
gotoxy(25,8); cout<<"-> Enter username to delete";
gotoxy(29,11); cout<<"Username:";
rectangle(200,142,440,218);
rectangle(300,155,430,177);
callmouse();
loginus:
gotoxy(39,11);
gets(us);
if(us[0]=='\0')
{
gotoxy(28,15); cout<<"Notice:";
gotoxy(35,15); cout<<"Name cant be empty. ";
gotoxy(39,11); cout<<" ";
goto loginus;
}
else if(isdigit(us[0]))
{
gotoxy(28,15); cout<<"Notice:";
gotoxy(35,15); cout<<"Name cant be number. ";
gotoxy(39,11); cout<<" ";
goto loginus;
}
gotoxy(25,8); cout<<"-> Enter password to delete";
gotoxy(29,13); cout<<"Password:";
gotoxy(35,15); cout<<" ";
rectangle(300,188,430,210);
ucount=0;
while(ucount<8)
{
gotoxy(39,13); cout<<" ";
passwordMatch();
if(password[0]==13)
{ gotoxy(28,15); cout<<" Password can't be empty"; }
else if(ucount<7)
{ gotoxy(28,15); cout<<" Password must be 8 character"; }
}
for(int vb=0;vb<8;vb++)
{
ps[vb]=password[vb]+5;
}
adminread=0; admincount=0;
fin.read((char *)this,sizeof(*this));
while(!fin.eof())
{ if(strcmp(us,USER)==0 && (ps[0]==PASSWORD[0] && ps[1]==PASSWORD[1] && ps[2]==PASSWORD[2] && ps[3]==PASSWORD[3] && ps[4]==PASSWORD[4] && ps[5]==PASSWORD[5] && ps[6]==PASSWORD[6] && ps[7]==PASSWORD[7] ))
{ same=1; }
else {
fout.write((char *)this,sizeof(*this));
}
if(same==1 && admincount==0) { adminread=1; break; }
admincount++;
fin.read((char *)this,sizeof(*this));
}
}
fin.close();
fout.close();
remove("c:\\turboc3\\file\\log.exe");
rename("c:\\turboc3\\file\\log","c:\\turboc3\\file\\log.exe");
hidemouse();
if(same==1)
{
if(adminread==1)
{
gotoxy(20,15); cout<<"...Admin Account Deleted... Add another Admin...";
}
else
{ gotoxy(28,15); cout<<" Account Deleted ";}
}
else
{
if(!flagpassb==0 || !flagpassb1==1)
{
gotoxy(25,15); cout<<"Username or password donot match. ";
}
}
rectangle(460,35,545,60);
callmouse();
outtextxy(310,30," Continue.");
while(gett!=13)
{
while(!kbhit())
{
getmousepos(&button,&x,&y);
if(button==1)
{if(x>=460 && x<=545 && y>=35 && y<=60){ungetch(13);}
}
}
gett=getch();
}
hidemouse();
cleardevice();
if(adminread==1)
{ adminread=0; u.checkpass(); }
else
{
remove("c:\\turboc3\\file\\log1");
alwaysdisplay();
} }
int userpass::loginpass(char name_a[20],char pass_a[8])
{
char pass_b[8];
int v,logincheck=0;
return_login=0;
ifstream fiin;
fiin.open("c:\\turboc3\\file\\log.exe",ios::in |ios::binary);
if(!fiin) { return_login=0; }
else {
fiin.read((char *)this,sizeof(* this));
while(!fiin.eof())
{
for(v=0;v<8;v++)
{
pass_b[v]=PASSWORD[v]-5;
}
if(strcmp(name_a,USER)==0)
{
if(pass_a[0]==pass_b[0] && pass_a[1]==pass_b[1] && pass_a[2]==pass_b[2] && pass_a[3]==pass_b[3] && pass_a[4]==pass_b[4] && pass_a[5]==pass_b[5] && pass_a[6]==pass_b[6] && pass_a[7]==pass_b[7] )
{ return_login=1; }
}
if(return_login==1 && logincheck==0)
{
return_login=2;
}
logincheck++;
fiin.read((char *)this,sizeof(* this));
}
}
fiin.close();
return(return_login);
}
| [
"[email protected]"
] | |
59582435def41ecb5ce25bebbc5711397fb9b565 | de2709047252f8e946f033c58168191275da5216 | /SeePage/AssemblyInfo.cpp | afd4821365b67c83545f2231981121814fb8d115 | [] | no_license | qxornet/Void | 8cdac4b78339513d2e66ce890fb0c527ff5df956 | de85c803f5e613d002c24d89e81289e7884b3827 | refs/heads/master | 2022-12-12T12:51:18.194778 | 2022-12-05T11:15:17 | 2022-12-05T11:15:17 | 164,511,600 | 2 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 1,650 | cpp | #include "stdafx.h"
using namespace System;
using namespace System::Reflection;
using namespace System::Runtime::CompilerServices;
using namespace System::Runtime::InteropServices;
using namespace System::Security::Permissions;
//
// Общие сведения об этой сборке предоставляются следующим набором
// атрибутов. Отредактируйте значения этих атрибутов, чтобы изменить
// общие сведения об этой сборке.
//
[assembly:AssemblyTitleAttribute("SeePage")];
[assembly:AssemblyDescriptionAttribute("")];
[assembly:AssemblyConfigurationAttribute("")];
[assembly:AssemblyCompanyAttribute("")];
[assembly:AssemblyProductAttribute("SeePage")];
[assembly:AssemblyCopyrightAttribute("Copyright (c) 2017")];
[assembly:AssemblyTrademarkAttribute("")];
[assembly:AssemblyCultureAttribute("")];
//
// Сведения о версии сборки состоят из следующих четырех значений:
//
// Основной номер версии
// Дополнительный номер версии
// Номер построения
// Редакция
//
// Можно задать все значения или принять номер построения и номер редакции по умолчанию,
// используя "*", как показано ниже:
[assembly:AssemblyVersionAttribute("1.0.*")];
[assembly:ComVisible(false)];
[assembly:CLSCompliantAttribute(true)];
[assembly:SecurityPermission(SecurityAction::RequestMinimum, UnmanagedCode = true)];
| [
"[email protected]"
] |
Subsets and Splits