blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 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 listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
eeb2583f3e400cc5c10adbff6e46e39b37f6249f | 7ee3bd7cd631eb17d34e79b9350d45ecbf0c4d49 | /src/core/observer.h | d63d9e08f4a031b33a50bb5645733ece4064d12b | [] | no_license | fhieber/cclir | 85a80e3b5e2d140b95cf53359521573f8669db7d | 8d3f10f1d595a60a6d43b0a4879c6bffa0a54bb3 | refs/heads/master | 2016-09-02T01:34:23.270781 | 2015-01-27T13:52:49 | 2015-01-27T13:52:49 | 25,041,187 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,202 | h | /*
* observer.h
*
* Created on: May 27, 2013
*/
#ifndef OBSERVER_H_
#define OBSERVER_H_
#include <vector>
#include <string>
#include <queue>
#include <boost/unordered_set.hpp>
#include "kbest.h" // cdec
#include "viterbi.h"
#include "inside_outside.h"
#include "sparse_vector.h"
#include "sampler.h"
#include "verbose.h"
#include "viterbi.h"
#include "ff_register.h"
#include "decoder.h"
#include "weights.h"
#include "prob.h"
#include "nbest-ttable.h"
/*
* implements a traversal struct that collects translations for all rules
* used in the derivation.
* ( compare with viterbi.h's ViterbiPathTraversal )
*/
struct TranslationPairTraversal {
typedef std::vector<translation> Result;
inline void selectAlignments(const Hypergraph::Edge& edge, std::vector<translation>& result, const bool filter=false) const {
if (!filter) { // use all alignments
for (unsigned j = 0; j < edge.rule_->a_.size(); ++j)
result.push_back(std::make_pair( edge.rule_->f_[edge.rule_->a_[j].s_] , edge.rule_->e_[edge.rule_->a_[j].t_]) );
} else { // only one-to-one
// we assume that alignment points are ordered by source index
std::vector<AlignmentPoint>& as = edge.rule_->a_;
std::vector<unsigned short> cf(edge.rule_->FLength(),0); // counts times source tokens are visited by as
std::vector<unsigned short> ce(edge.rule_->ELength(),0); // counts times target tokens are visited by as
for (unsigned j=0;j<as.size();++j) {
++cf[as[j].s_];
++ce[as[j].t_];
}
for (unsigned j=0;j<as.size();++j) {
if (cf[as[j].s_] == 1 && ce[as[j].t_] == 1) // if both s_ and t_ only visited once
result.push_back(std::make_pair( edge.rule_->f_[as[j].s_] , edge.rule_->e_[as[j].t_]) );
}
}
}
void operator()(const Hypergraph::Edge& edge,
const std::vector<const Result*>& ants,
Result* result) const {
for (unsigned i=0; i<ants.size(); ++i) {
for (unsigned j=0;j<ants[i]->size(); ++j)
result->push_back((*ants[i])[j]);
}
if (!edge.rule_->a_.empty())
selectAlignments(edge, *result, false);
}
};
struct NbestTTableGetter : public DecoderObserver {
/*
* unique filter for kbest derivations
*/
struct FilterUnique {
boost::unordered_set<std::vector<translation> > unique;
bool operator()(const std::vector<translation>& yield) {
return !unique.insert(yield).second;
}
};
NbestTTable nbest_ttable_;
const unsigned n_; // size of nbest
const bool ignore_derivation_scores_;
const prob_t L_;
const prob_t C_;
const bool unique_nbest_;
const bool swf_; // stopword filter?
NbestTTableGetter(
const unsigned n,
const bool ignore_derivation_scores,
const bool /*add_passthrough_rules*/, // TODO
const prob_t& L,
const prob_t& C,
const bool unique_nbest,
const bool target_swf)
: n_(n),
ignore_derivation_scores_(ignore_derivation_scores),
L_(L), C_(C),
unique_nbest_(unique_nbest),
swf_(target_swf) {
nbest_ttable_.clear();
}
template<class Filter>
void KbestGet(const Hypergraph& hg) {
typedef KBest::KBestDerivations<std::vector<translation>,
TranslationPairTraversal, Filter> K;
K kbest(hg, n_);
// for each item in kbest list:
for (int i=0; i<n_;++i) {
typename K::Derivation *d = kbest.LazyKthBest(
hg.nodes_.size() - 1, i);
if (!d) break;
if ( d->yield.empty() ) { continue; }
for (std::vector<translation>::const_iterator t_it=d->yield.begin(); t_it!=d->yield.end();t_it++)
nbest_ttable_.addPair(t_it->first, t_it->second, ignore_derivation_scores_ ? prob_t(1) : d->score);
}
}
void GetNbestTTableFromForest(Hypergraph* hg) {
if (!unique_nbest_)
KbestGet<KBest::NoFilter<std::vector<translation> > >(*hg);
else
KbestGet<FilterUnique>(*hg);
}
virtual void NotifyTranslationForest(const SentenceMetadata& /*smeta*/, Hypergraph* hg) {
ClearNbestTTable();
GetNbestTTableFromForest(hg);
NormalizeNbestTTable();
}
void ClearNbestTTable() { nbest_ttable_.clear(); }
void NormalizeNbestTTable() { nbest_ttable_.normalize(); }
void ConstrainNbestTTable() { nbest_ttable_.constrain(L_, C_, swf_); }
NbestTTable& GetNbestTTable() { return nbest_ttable_; }
};
#endif /* OBSERVER_H_ */
| [
"hieber@cl.uni-heidelberg.de"
] | hieber@cl.uni-heidelberg.de |
2fadbb01bc22a8bdc354bd4c85d6fbbf492ea9d6 | 7c5d7fb6a64df1a118a64bdf6087ecf395a3a722 | /data/open-Olive/sources/001539-open-2015-256-Olive.cpp | 14fcc311da2bb101aa5c80caaeda0d09cb13baf7 | [] | no_license | alexhein189/code-plagiarism-detector | e66df71c46cc5043b6825ef76a940b658c0e5015 | 68d21639d4b37bb2c801befe6f7ce0007d7eccc5 | refs/heads/master | 2023-03-18T06:02:45.508614 | 2016-05-04T14:29:57 | 2016-05-04T14:54:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,876 | cpp | #include <iostream>
#include <vector>
#include <fstream>
#include <set>
#include <string>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <map>
#include <cstring>
using namespace std;
typedef long long ll;
typedef long double ld;
#define mp make_pair
#define pb push_back
#define pp pop_back
const ll INF = 1LL << 62LL;
struct Point {
ld x, y;
Point(ld=0, ld=0);
Point operator-(const Point &) const;
ld len() const;
};
Point::Point(ld x, ld y): x(x), y(y)
{}
Point Point::operator-(const Point &p) const {
return Point(x - p.x, y - p.y);
}
ld Point::len() const {
return sqrt(x*x + y*y);
}
int n;
vector <int> arr;
int main() {
freopen("input.txt", "r", stdin);
scanf("%d", &n);
arr.resize(n);
for (int i = 0; i < n; ++i)
scanf("%d", &arr[i]);
vector <int> biggerLeft(n, 0), bigger(n, 0), biggerCur(n, 0);
int profit = 1LL << 30LL;
int ans1 = -2, ans2 = -2;
for (int i = 1; i < n; ++i) {
//vector <int> biggerLeft(n, 0), bigger(n, 0), biggerCur(n, 0);
for (int j = 0; j < i; ++j) {
bigger[j] = 0;
for (int g = 0; g < i; ++g)
bigger[j] += arr[g] > arr[j];
}
biggerCur[0] = 0;
for (int j = 1; j < i; ++j) {
biggerCur[j] = biggerCur[j - 1] + (arr[j - 1] > arr[i]);
}
for (int j = 0; j < i; ++j)
biggerLeft[i] += arr[j] > arr[i];
/*
for (int j = 0; j < n; ++j)
printf("%d ", biggerLeft[j]);
printf("\n");
for (int j = 0; j < n; ++j)
printf("%d ", bigger[j]);
printf("\n");
for (int j = 0; j < n; ++j)
printf("%d ", biggerCur[j]);
printf("\n");
printf("\n");*/
for (int j = 0; j < i; ++j) {
int k = biggerCur[j] + bigger[j] - biggerLeft[i];
if (k < profit) {
profit = k;
ans1 = i;
ans2 = j;
}
}
}
//cout << profit << endl;
cout << ans2 + 1 << " " << ans1 + 1 << endl;
} | [
"shk.slava@gmail.com"
] | shk.slava@gmail.com |
3f1ae3eba1c9ef9a0bf8111c1dffb3ff7544382e | 33b08b3036fe3c5921a5b0068eb09b88286e73f1 | /coursework/DSU.h | e27321c5761b1c1865986dba2d2b8f64362078e2 | [] | no_license | rex-gentium/graph-theory | f072bd4ccea438b4046e3028e4466bcf730cf232 | 65ff0e58fdef1a0023769205877d08bb64cf4050 | refs/heads/master | 2021-01-09T06:50:51.446696 | 2017-04-15T14:56:29 | 2017-04-15T14:56:29 | 81,129,457 | 1 | 0 | null | 2017-04-15T11:47:01 | 2017-02-06T20:23:30 | C++ | UTF-8 | C++ | false | false | 2,074 | h | #pragma once
#include <vector>
/*
Система непересекающихся множеств.
Не является полноценной реализацией: возможно только создать систему из N
пронумерованных элементов, каждый из которых образует множество. Добавить
новое множество нельзя.
*/
class DSU {
public:
/* создаёт систему из setCount непересекающихся множеств, id множества является порядковый номер*/
DSU(int setCount);
DSU(const DSU& rhs);
~DSU();
DSU & operator=(const DSU & hrs);
/*создаёт новое множество с указанным лидером*/
//void makeSet(int x); // для реализации потребуется заменить массив предков на карту
/*объединеняет два множества указанных представителей. Амортизированная O(1)*/
void unite(int x, int y);
/*возвращает лидера множества указанного представителя. Амортизированная O(1)*/
int find(int x) const;
/* возвращает количество множеств */
int getSetCount() const { return setCount; }
/* возвращает массив лидеров множеств размера getSetCount(). Массив должен быть уничтожен после использования */
int * getLeaders() const;
private:
int * parent = nullptr; // массив: по номеру элемента лежит номер его предка (лидер множества является предком сам себе)
int * rank = nullptr; // массив: по номеру элемента лежит высота его поддерева
int size; // количество элементов
int setCount; // количество множеств / лидеров
};
| [
"budowniczy.zamyslow@gmail.com"
] | budowniczy.zamyslow@gmail.com |
faebaaf94f4b566ef263baf0f35c8280a36a28c1 | c6149792e471e0badca575c95532a70e7ab3df26 | /DemoDirectX/Scenes/ContinueScene.cpp | c0b8813747ad3f908dfeac7b257d226795441516 | [] | no_license | duyuit/Aladdin2 | b9067432970ce7ee1c134a5b65212b85d8146dbb | c8461bfca48b6de786faea6ebed10d587384e3a4 | refs/heads/master | 2021-10-28T15:03:06.536526 | 2019-04-24T06:51:59 | 2019-04-24T06:51:59 | 109,827,304 | 0 | 0 | null | 2017-12-19T10:20:16 | 2017-11-07T11:35:12 | C++ | UTF-8 | C++ | false | false | 5,130 | cpp | #include "ContinueScene.h"
#include "MenuScene.h"
ContinueScene::ContinueScene(Scene* preSce)
{
this->preScene = preSce;
background = new Sprite("Resources/wish.png", RECT{ 0,0,1920,1080 });
background->SetPosition(GameGlobal::GetWidth() / 2, GameGlobal::GetHeight() / 2);
background->SetScale(D3DXVECTOR2(0.208, 0.209));
RECT rect;
vector<RECT> listSourceRect;
rect.left = 3; rect.top = 9; rect.right = rect.left + 37; rect.bottom = rect.top + 49; listSourceRect.push_back(rect);
rect.left = 47; rect.top = 11; rect.right = rect.left + 41; rect.bottom = rect.top + 46; listSourceRect.push_back(rect);
rect.left = 95; rect.top = 6; rect.right = rect.left + 40; rect.bottom = rect.top + 51; listSourceRect.push_back(rect);
rect.left = 143; rect.top = 3; rect.right = rect.left + 44; rect.bottom = rect.top + 54; listSourceRect.push_back(rect);
rect.left = 143; rect.top = 3; rect.right = rect.left + 44; rect.bottom = rect.top + 54; listSourceRect.push_back(rect);
rect.left = 143; rect.top = 3; rect.right = rect.left + 44; rect.bottom = rect.top + 54; listSourceRect.push_back(rect);
rect.left = 143; rect.top = 3; rect.right = rect.left + 44; rect.bottom = rect.top + 54; listSourceRect.push_back(rect);
rect.left = 143; rect.top = 3; rect.right = rect.left + 44; rect.bottom = rect.top + 54; listSourceRect.push_back(rect);
rect.left = 197; rect.top = 6; rect.right = rect.left + 41; rect.bottom = rect.top + 50; listSourceRect.push_back(rect);
rect.left = 250; rect.top = 5; rect.right = rect.left + 42; rect.bottom = rect.top + 50; listSourceRect.push_back(rect);
rect.left = 303; rect.top = 2; rect.right = rect.left + 44; rect.bottom = rect.top + 52; listSourceRect.push_back(rect);
rect.left = 303; rect.top = 2; rect.right = rect.left + 44; rect.bottom = rect.top + 52; listSourceRect.push_back(rect);
rect.left = 303; rect.top = 2; rect.right = rect.left + 44; rect.bottom = rect.top + 52; listSourceRect.push_back(rect);
rect.left = 303; rect.top = 2; rect.right = rect.left + 44; rect.bottom = rect.top + 52; listSourceRect.push_back(rect);
rect.left = 303; rect.top = 2; rect.right = rect.left + 44; rect.bottom = rect.top + 52; listSourceRect.push_back(rect);
ald = new Animation("Resources/Aladdin.png", 15, listSourceRect, (float)1 / 0.15, D3DXVECTOR2(0.5, 1), D3DCOLOR_XRGB(255, 0, 255), Entity::Entity::EntityTypes::PlayerOne);
ald->SetPosition(GameGlobal::GetWidth() / 2, GameGlobal::GetHeight() - 30);
listSourceRect.clear();
for (int i = 1; i <= 13; i++)
{
rect.top = 1212;
rect.bottom = 1275;
switch (i)
{
case 1:
{
rect.left = 7;
rect.right = 57;
break;
}
case 2:
{
rect.left = 60;
rect.right = 110;
break;
}
case 3:
{
rect.left = 113;
rect.right = 163;
break;
}
case 4:
{
rect.left = 162;
rect.right = 212;
break;
}
case 5:
{
rect.left = 219;
rect.right = 279;
break;
}
case 6:
{
rect.left = 276;
rect.right = 334;
break;
}
case 7:
{
rect.left = 326;
rect.right = 386;
break;
}
case 8:
{
rect.left = 376;
rect.right = 436;
break;
}
case 9:
{
rect.left = 431;
rect.right = 479;
break;
}
case 10:
{
rect.left = 487;
rect.right = 543;
break;
}
case 11:
{
rect.left = 547;
rect.right = 608;
break;
}
case 12:
{
rect.left = 609;
rect.right = 671;
break;
}
case 13:
{
rect.left = 669;
rect.right = 731;
break;
}
}
listSourceRect.push_back(rect);
}
run= new Animation("Resources/Aladdin.png", 13, listSourceRect, (float)1 / 0.3, D3DXVECTOR2(0.5, 1), D3DCOLOR_XRGB(255, 0, 255), Entity::Entity::EntityTypes::PlayerOne);
run->SetPosition(GameGlobal::GetWidth() / 2, GameGlobal::GetHeight() - 30);
}
void ContinueScene::Draw()
{
background->Draw();
if(!active)
ald->Draw();
else
{
if (isLeft)
run->GetSprite()->FlipVertical(true);
run->Draw();
}
}
void ContinueScene::OnKeyDown(int key)
{
if (key == VK_LEFT)
{
if (!active)
{
active = true;
isLeft = true;
}
}
else if (key == VK_RIGHT)
{
if (!active)
{
active = true;
isLeft = false;
}
}
}
void ContinueScene::Update(float dt)
{
if(!active)
ald->Update(1);
else
{
if (isLeft)
run->SetPosition(run->GetSprite()->GetPosition().x - 2, run->GetSprite()->GetPosition().y);
else
run->SetPosition(run->GetSprite()->GetPosition().x + 2, run->GetSprite()->GetPosition().y);
run->Update(1);
}
if (run->GetSprite()->GetPosition().x < 0)
{
SceneManager::GetInstance()->ReplaceScene(new MenuScene());
return;
}
if (run->GetSprite()->GetPosition().x > GameGlobal::GetWidth())
{
GameGlobal::liveCount = 3;
if (GameGlobal::curSong == GameGlobal::Demo)
{
Sound::getInstance()->play("background_market", true, 0);
}
else
if (GameGlobal::curSong == GameGlobal::BossMusic)
{
Sound::getInstance()->play("bosstheme", true, 0);
}
GameGlobal::curSong = GameGlobal::Continuene;
SceneManager::GetInstance()->ReplaceScene(preScene);
return;
}
}
ContinueScene::~ContinueScene()
{
}
| [
"duykkxm92@gmail.com"
] | duykkxm92@gmail.com |
041e62c3e3d612fbe7ee8cf3c6d24019ba25a59c | 805a24e99eb1d68f77fc425b80b1d3960ca9cd3b | /WebKitBrowser/InjectedBundle/Milestone.cpp | 570736f94d94588c39d07cacd0a97f227381221a | [
"Apache-2.0",
"BSD-2-Clause",
"LicenseRef-scancode-generic-cla"
] | permissive | rdkcentral/rdkservices | 9194308a202b5d1e36f9eb900cb3d6d3244ae0f7 | ecf14237d349b4ebffadba7dc871e2b5f2cf52be | refs/heads/sprint/23Q3 | 2023-08-30T18:33:37.176451 | 2023-08-29T16:19:42 | 2023-08-29T16:19:42 | 246,602,796 | 28 | 1,533 | Apache-2.0 | 2023-09-14T19:06:56 | 2020-03-11T15:05:36 | C++ | UTF-8 | C++ | false | false | 2,805 | cpp | /*
* If not stated otherwise in this file or this component's LICENSE file the
* following copyright and licenses apply:
*
* Copyright 2020 RDK Management
*
* 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 "Milestone.h"
#include "Utils.h"
#include <iostream>
#include <sstream>
// Global handle to this bundle.
extern WKBundleRef g_Bundle;
namespace WPEFramework {
namespace JavaScript {
namespace Functions {
Milestone::Milestone()
{
}
JSValueRef Milestone::HandleMessage(JSContextRef context, JSObjectRef,
JSObjectRef, size_t argumentCount, const JSValueRef arguments[], JSValueRef*)
{
const int acceptedArgCount = 3;
const size_t bufferSize = 1500; // Is limited by UDP package size.
if (argumentCount != acceptedArgCount) {
std::cerr << "Milestone only accepts 3 string arguments" << std::endl;
return JSValueMakeNull(context);
}
string argStrings[acceptedArgCount];
for (unsigned int index = 0; index < argumentCount; index++) {
const JSValueRef& argument = arguments[index];
if (!JSValueIsString(context, argument)) {
std::cerr << "Milestone function only accepts string arguments" << std::endl;
return JSValueMakeNull(context);
}
JSStringRef jsString = JSValueToStringCopy(context, argument, nullptr);
char stringBuffer[bufferSize];
// TODO: for now assumption is ASCII, should we also deal with Unicode?
JSStringGetUTF8CString(jsString, stringBuffer, bufferSize);
JSStringRelease(jsString);
argStrings[index] = stringBuffer;
}
std::stringstream ssMessage;
ssMessage << "TEST TRACE:";
for (const string& argString : argStrings) {
ssMessage << " \"" << argString << "\"";
}
std::cerr << ssMessage.str() << std::endl;
TRACE_GLOBAL(Trace::Information, (ssMessage.str()));
return JSValueMakeNull(context);
}
static JavaScriptFunctionType<Milestone> _instance(_T("automation"));
}
}
}
| [
"vijay.selva@hotmail.com"
] | vijay.selva@hotmail.com |
d17d8156f411e4406745f78e9c28cb0746a7a575 | 2a1acfc4553095d08131fab0aa6bf9193a7d6338 | /src/plugins/snails/messagelistactionsmanager.cpp | 0502dc3a71a339a111bb98ec78755bb2df7cae0c | [
"BSL-1.0"
] | permissive | stlcours/leechcraft | df26bf2c9281cc82ea22a629667ef4ca400f5fbf | 8dd8667e0bd81eec9b8b969bc141ceaa3549b911 | refs/heads/master | 2021-03-22T00:55:43.388366 | 2017-10-02T02:36:39 | 2017-10-02T02:36:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,149 | cpp | /**********************************************************************
* LeechCraft - modular cross-platform feature rich internet client.
* Copyright (C) 2006-2014 Georg Rudoy
*
* Boost Software License - Version 1.0 - August 17th, 2003
*
* Permission is hereby granted, free of charge, to any person or organization
* obtaining a copy of the software and accompanying documentation covered by
* this license (the "Software") to use, reproduce, display, distribute,
* execute, and transmit the Software, and to prepare derivative works of the
* Software, and to permit third-parties to whom the Software is furnished to
* do so, all subject to the following:
*
* The copyright notices in the Software and this entire statement, including
* the above license grant, this restriction and the following disclaimer,
* must be included in all copies of the Software, in whole or in part, and
* all derivative works of the Software, unless such copies or derivative
* works are solely in the form of machine-executable object code generated by
* a source language processor.
*
* 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
* SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
* FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
**********************************************************************/
#include "messagelistactionsmanager.h"
#include <QUrl>
#include <QMessageBox>
#include <QTextDocument>
#include <QtDebug>
#include <vmime/messageIdSequence.hpp>
#include <util/xpc/util.h>
#include <util/threads/futures.h>
#include <util/sll/urlaccessor.h>
#include <util/sll/either.h>
#include <util/sll/visitor.h>
#include <interfaces/core/ientitymanager.h>
#include "core.h"
#include "message.h"
#include "vmimeconversions.h"
#include "account.h"
namespace LeechCraft
{
namespace Snails
{
class MessageListActionsProvider
{
public:
virtual QList<MessageListActionInfo> GetMessageActions (const Message_ptr&, Account*) const = 0;
};
namespace
{
vmime::shared_ptr<const vmime::messageId> GetGithubMsgId (const vmime::shared_ptr<const vmime::header>& headers)
{
const auto& referencesField = headers->References ();
if (!referencesField)
{
if (const auto msgId = headers->MessageId ())
return msgId->getValue<vmime::messageId> ();
return {};
}
const auto& refSeq = referencesField->getValue<vmime::messageIdSequence> ();
if (!refSeq)
return {};
if (!refSeq->getMessageIdCount ())
return {};
return refSeq->getMessageIdAt (0);
}
QString GetGithubAddr (const vmime::shared_ptr<const vmime::header>& headers)
{
if (!headers->findField ("X-GitHub-Sender"))
return {};
const auto& ref = GetGithubMsgId (headers);
if (!ref)
return {};
return QString::fromUtf8 (ref->getLeft ().c_str ());
}
class GithubProvider : public MessageListActionsProvider
{
public:
QList<MessageListActionInfo> GetMessageActions (const Message_ptr& msg, Account*) const override
{
const auto& addrReq = GetGithubAddr (msg->GetVmimeHeader ());
if (addrReq.isEmpty ())
return {};
return {
{
QObject::tr ("Open"),
QObject::tr ("Open the page on GitHub."),
QIcon::fromTheme ("document-open"),
[addrReq] (const Message_ptr&)
{
const QUrl fullUrl { "https://github.com/" + addrReq };
const auto& entity = Util::MakeEntity (fullUrl, {}, FromUserInitiated | OnlyHandle);
Core::Instance ().GetProxy ()->GetEntityManager ()->HandleEntity (entity);
},
{}
}
};
}
};
class BugzillaProvider : public MessageListActionsProvider
{
public:
QList<MessageListActionInfo> GetMessageActions (const Message_ptr& msg, Account*) const override
{
const auto& headers = msg->GetVmimeHeader ();
if (!headers)
return {};
const auto header = headers->findField ("X-Bugzilla-URL");
if (!header)
return {};
const auto& urlText = header->getValue<vmime::text> ();
if (!urlText)
return {};
const auto& url = StringizeCT (*urlText);
const auto& referencesField = headers->MessageId ();
if (!referencesField)
return {};
const auto& ref = referencesField->getValue<vmime::messageId> ();
if (!ref)
return {};
const auto& left = QString::fromUtf8 (ref->getLeft ().c_str ());
const auto bugId = left.section ('-', 1, 1);
return {
{
QObject::tr ("Open"),
QObject::tr ("Open the bug page on Bugzilla."),
QIcon::fromTheme ("tools-report-bug"),
[url, bugId] (const Message_ptr&)
{
const QUrl fullUrl { url + "show_bug.cgi?id=" + bugId };
const auto& entity = Util::MakeEntity (fullUrl, {}, FromUserInitiated | OnlyHandle);
Core::Instance ().GetProxy ()->GetEntityManager ()->HandleEntity (entity);
},
{}
}
};
}
};
class RedmineProvider : public MessageListActionsProvider
{
public:
QList<MessageListActionInfo> GetMessageActions (const Message_ptr& msg, Account*) const override
{
const auto& headers = msg->GetVmimeHeader ();
if (!headers)
return {};
const auto header = headers->findField ("X-Redmine-Host");
if (!header)
return {};
const auto& urlText = header->getValue<vmime::text> ();
if (!urlText)
return {};
const auto& url = StringizeCT (*urlText);
const auto issueHeader = headers->findField ("X-Redmine-Issue-Id");
if (!issueHeader)
return {};
const auto& issueText = issueHeader->getValue<vmime::text> ();
if (!issueText)
return {};
const auto& issue = StringizeCT (*issueText);
return {
{
QObject::tr ("Open"),
QObject::tr ("Open the issue page on Redmine."),
QIcon::fromTheme ("tools-report-bug"),
[url, issue] (const Message_ptr&)
{
const QUrl fullUrl { "http://" + url + "/issues/" + issue };
const auto& entity = Util::MakeEntity (fullUrl, {}, FromUserInitiated | OnlyHandle);
Core::Instance ().GetProxy ()->GetEntityManager ()->HandleEntity (entity);
},
{}
}
};
}
};
class ReviewboardProvider : public MessageListActionsProvider
{
public:
QList<MessageListActionInfo> GetMessageActions (const Message_ptr& msg, Account*) const override
{
const auto& headers = msg->GetVmimeHeader ();
if (!headers)
return {};
const auto header = headers->findField ("X-ReviewRequest-URL");
if (!header)
return {};
const auto& urlText = header->getValue<vmime::text> ();
if (!urlText)
return {};
const auto& url = StringizeCT (*urlText);
return {
{
QObject::tr ("Open"),
QObject::tr ("Open the review page on ReviewBoard."),
QIcon::fromTheme ("document-open"),
[url] (const Message_ptr&)
{
const auto& entity = Util::MakeEntity (QUrl { url }, {}, FromUserInitiated | OnlyHandle);
Core::Instance ().GetProxy ()->GetEntityManager ()->HandleEntity (entity);
},
{}
}
};
}
};
QUrl GetUnsubscribeUrl (const QString& text)
{
const auto& parts = text.split (',', QString::SkipEmptyParts);
QUrl email;
QUrl url;
for (auto part : parts)
{
part = part.simplified ();
if (part.startsWith ('<'))
part = part.mid (1, part.size () - 2);
const auto& ascii = part.toLatin1 ();
if (ascii.startsWith ("mailto:"))
{
const auto& testEmail = QUrl::fromEncoded (ascii);
if (testEmail.isValid ())
email = testEmail;
}
else
{
const auto& testUrl = QUrl::fromEncoded (ascii);
if (testUrl.isValid ())
url = testUrl;
}
}
return email.isValid () ? email : url;
}
QString GetListName (const Message_ptr& msg)
{
const auto& addrString = "<em>" + msg->GetAddressString (Message::Address::From).toHtmlEscaped () + "</em>";
const auto& headers = msg->GetVmimeHeader ();
if (!headers)
return addrString;
const auto header = headers->findField ("List-Id");
if (!header)
return addrString;
const auto& vmimeText = header->getValue<vmime::text> ();
if (!vmimeText)
return addrString;
return "<em>" + StringizeCT (*vmimeText).toHtmlEscaped () + "</em>";
}
void HandleUnsubscribeText (const QString& text, const Message_ptr& msg, Account *acc)
{
const auto& url = GetUnsubscribeUrl (text);
const auto& addrString = GetListName (msg);
if (url.scheme () == "mailto")
{
if (QMessageBox::question (nullptr,
QObject::tr ("Unsubscription confirmation"),
QObject::tr ("Are you sure you want to unsubscribe from %1? "
"This will send an email to %2.")
.arg (addrString)
.arg ("<em>" + url.path ().toHtmlEscaped () + "</em>"),
QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes)
return;
const auto& msg = std::make_shared<Message> ();
msg->SetAddress (Message::Address::To, { {}, url.path () });
const auto& subjQuery = Util::UrlAccessor { url } ["subject"];
msg->SetSubject (subjQuery.isEmpty () ? "unsubscribe" : subjQuery);
Util::Sequence (nullptr, acc->SendMessage (msg)) >>
[url] (const auto& result)
{
const auto& entity = Util::Visit (result.AsVariant (),
[url] (Util::Void)
{
return Util::MakeNotification ("Snails",
QObject::tr ("Successfully sent unsubscribe request to %1.")
.arg ("<em>" + url.path () + "</em>"),
PInfo_);
},
[url] (const auto& err)
{
const auto& msg = Util::Visit (err,
[] (const auto& err) { return QString::fromUtf8 (err.what ()); });
return Util::MakeNotification ("Snails",
QObject::tr ("Unable to send unsubscribe request to %1: %2.")
.arg ("<em>" + url.path () + "</em>")
.arg (msg),
PWarning_);
});
Core::Instance ().GetProxy ()->GetEntityManager ()->HandleEntity (entity);
};
}
else
{
if (QMessageBox::question (nullptr,
QObject::tr ("Unsubscription confirmation"),
QObject::tr ("Are you sure you want to unsubscribe from %1? "
"This will open the following web page in your browser: %2")
.arg (addrString)
.arg ("<br/><em>" + url.toString () + "</em>"),
QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes)
return;
const auto& entity = Util::MakeEntity (url, {}, FromUserInitiated | OnlyHandle);
Core::Instance ().GetProxy ()->GetEntityManager ()->HandleEntity (entity);
}
}
class UnsubscribeProvider : public MessageListActionsProvider
{
public:
QList<MessageListActionInfo> GetMessageActions (const Message_ptr& msg, Account *acc) const override
{
const auto& headers = msg->GetVmimeHeader ();
if (!headers)
return {};
const auto header = headers->findField ("List-Unsubscribe");
if (!header)
return {};
return {
{
QObject::tr ("Unsubscribe"),
QObject::tr ("Try canceling receiving further messages like this."),
QIcon::fromTheme ("news-unsubscribe"),
[header, acc] (const Message_ptr& msg)
{
const auto& vmimeText = header->getValue<vmime::text> ();
if (!vmimeText)
return;
HandleUnsubscribeText (StringizeCT (*vmimeText), msg, acc);
},
{}
}
};
}
};
class AttachmentsProvider : public MessageListActionsProvider
{
Account * const Acc_;
public:
AttachmentsProvider (Account *acc)
: Acc_ { acc }
{
}
QList<MessageListActionInfo> GetMessageActions (const Message_ptr& msg, Account *acc) const override
{
if (msg->GetAttachments ().isEmpty ())
return {};
return
{
{
QObject::tr ("Attachments"),
QObject::tr ("Open/save attachments."),
QIcon::fromTheme ("mail-attachment"),
[acc = Acc_] (const Message_ptr& msg)
{
//new MessageAttachmentsDialog { acc, msg };
},
{}
}
};
}
};
}
MessageListActionsManager::MessageListActionsManager (Account *acc, QObject *parent)
: QObject { parent }
, Acc_ { acc }
{
Providers_ << std::make_shared<AttachmentsProvider> (acc);
Providers_ << std::make_shared<GithubProvider> ();
Providers_ << std::make_shared<RedmineProvider> ();
Providers_ << std::make_shared<BugzillaProvider> ();
Providers_ << std::make_shared<ReviewboardProvider> ();
Providers_ << std::make_shared<UnsubscribeProvider> ();
}
QList<MessageListActionInfo> MessageListActionsManager::GetMessageActions (const Message_ptr& msg) const
{
QList<MessageListActionInfo> result;
for (const auto provider : Providers_)
result += provider->GetMessageActions (msg, Acc_);
return result;
}
}
}
| [
"0xd34df00d@gmail.com"
] | 0xd34df00d@gmail.com |
3cf95c31c18a580c744b995048ff732a4d1fd755 | 1ee431728576649b4c1df51e0dcff34f813c7282 | /OS_MAS/OS_MAS.ino | f4e61525198a6bce1a94e6730cd443a88ace96a1 | [] | no_license | Ddh012345dhD/Lora-ESP32-FireBase | 8bcb23e3c979cedba9d56efe4f53d4382ff7b744 | ca8c10131c557716adf5b8f382f475d1dd64f152 | refs/heads/main | 2023-08-28T17:15:02.422133 | 2021-11-05T16:38:57 | 2021-11-05T16:38:57 | 425,015,806 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 22,194 | ino | #include <FirebaseESP32.h>
#include <WiFi.h>
#include <WiFiClient.h>
#include <WebServer.h>
#include <ESPmDNS.h>
#include <Update.h>
#include <EEPROM.h>
#include <SPI.h>
#include <LoRa.h>
#include <WiFiManager.h>
#include "BluetoothSerial.h"
//=======================================================
#define csPin 5
#define resetPin 4
#define irqPin 16
#define SD_CS 13
#define SD_SCK 14
#define SD_MOSI 15
#define SD_MISO 2
#define button_config 25
#define led_config 27
//=======================================================
#define FIREBASE_HOST "lora123-5fffa-default-rtdb.asia-southeast1.firebasedatabase.app"
#define FIREBASE_AUTH "SKOrTgFG49Hs3qqAOXcyXP0lPLLfmESaht5gjlt6"
//lv123-a5177-default-rtdb.firebaseio.com
//nlwHxr8rmVz2FRP7YExSVMhaDD0HLhtSHfKeCbJ9
//const char* ssid = "Tan Phat";//B 0703 //CR7//Tan Phat//Thu Hien//Kidkul2030
//const char* password = "02022021";//kidkul2021//xindelamgi//02022021//199619971998//kidkul@2018
#define gattway_addr 0x00
#define nodeOne_addr 0x01
#define nodeTwo_addr 0x02
#define nodeThree_addr 0x03
#define nodeFourth_addr 0x04
#define fre 433E6
byte destination_addr=0x00;
String cmdR = "RQ";
String cmdS = "S";
String cmd = "";
static String setting ="";
bool wm_nonblocking = false;
bool respons;
String temp,pH,oxy,TDS,level,bat1,bat2,bat3,bat4,Voltage,Cunrrent;
byte Node_addr[4]={nodeOne_addr,nodeTwo_addr,nodeThree_addr,nodeFourth_addr};
TaskHandle_t TaskHandle_1;
TaskHandle_t TaskHandle_2;
TaskHandle_t TaskHandle_3;
TaskHandle_t TaskHandle_4;
TaskHandle_t TaskHandle_5;
TaskHandle_t TaskHandle_6;
TaskHandle_t TaskHandle_7;
WebServer server(80);
const char* loginIndex =
"<form name='loginForm'>"
"<table width='20%' bgcolor='A09F9F' align='center'>"
"<tr>"
"<td colspan=2>"
"<center><font size=4><b>ESP32 Login Page</b></font></center>"
"<br>"
"</td>"
"<br>"
"<br>"
"</tr>"
"<tr>"
"<td>Username:</td>"
"<td><input type='text' size=25 name='userid'><br></td>"
"</tr>"
"<br>"
"<br>"
"<tr>"
"<td>Password:</td>"
"<td><input type='Password' size=25 name='pwd'><br></td>"
"<br>"
"<br>"
"</tr>"
"<tr>"
"<td><input type='submit' onclick='check(this.form)' value='Login'></td>"
"</tr>"
"</table>"
"</form>"
"<script>"
"function check(form)"
"{"
"if(form.userid.value=='admin' && form.pwd.value=='admin')"
"{"
"window.open('/serverIndex')"
"}"
"else"
"{"
" alert('Error Password or Username')/*displays error message*/"
"}"
"}"
"</script>";
/*
* Server Index Page
*/
const char* serverIndex =
"<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>"
"<form method='POST' action='#' enctype='multipart/form-data' id='upload_form'>"
"<input type='file' name='update'>"
"<input type='submit' value='Update'>"
"</form>"
"<div id='prg'>progress: 0%</div>"
"<script>"
"$('form').submit(function(e){"
"e.preventDefault();"
"var form = $('#upload_form')[0];"
"var data = new FormData(form);"
" $.ajax({"
"url: '/update',"
"type: 'POST',"
"data: data,"
"contentType: false,"
"processData:false,"
"xhr: function() {"
"var xhr = new window.XMLHttpRequest();"
"xhr.upload.addEventListener('progress', function(evt) {"
"if (evt.lengthComputable) {"
"var per = evt.loaded / evt.total;"
"$('#prg').html('progress: ' + Math.round(per*100) + '%');"
"}"
"}, false);"
"return xhr;"
"},"
"success:function(d, s) {"
"console.log('success!')"
"},"
"error: function (a, b, c) {"
"}"
"});"
"});"
"</script>";
const char* host = "esp32";
WiFiManager wm;
WiFiManagerParameter custom_field;
IPAddress local_IP(192, 168, 1, 100);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 0, 0);
IPAddress primaryDNS(8, 8, 8, 8);
IPAddress secondaryDNS(8, 8, 4, 4);
SPIClass sd_spi(HSPI);
//=======================================================
float read_eeprom(int addr);
void write_eeprom(int addr,float value);
void firebaseSetup();
uint8_t calc_crc(uint8_t data);
uint8_t crc8(byte data[], byte n);
void sendRequest(byte addr_destination, String message);
void onReceive(int packetSize);
void decode_data(byte addr,String sms);
void loraSetup();
void OTA_config();
String getParam(String name);
void wificonfig();
void saveParamCallback();
void SD_setup();
void appendFile(fs::FS &fs, const char * path, const char * message);
//========================================================
int addrepprom_oxy = 0;
int addrepprom_kp = addrepprom_oxy+4;
int addrepprom_ki = addrepprom_kp+4;
int addrepprom_kd = addrepprom_ki+4;
union {
float fval;
byte bval[4];
} floatAsBytes;
float readfloat;
union u_tag {
byte b[4];
float fval;
} u;
String oxysetup ="";
String last_oxysetup ="";
String kp ="";
String ki="";
String kd="";
String last_kp ="";
String last_ki="";
String last_kd="";
FirebaseData fbdo;
FirebaseJson json;
FirebaseJson json1;
//========================================================
unsigned long t1=0;
int i=0;
int rd=0;
static int iloi1=0;
static int iloi2=0;
static int iloi3=0;
static int iloi4=0;
bool state_request=true;
static bool set_status=false;
static bool task_status=false;
static String node_status="";
static void task_lora_data(void *pvParameters)
{
for(;;)
{
if ((unsigned long)(millis() - t1) >(1000-rd))
{
t1 = millis();
if(state_request && task_status ==false)//
{
state_request=false;
destination_addr =Node_addr[i];
cmd =cmdR;
sendRequest(destination_addr,cmd);
LoRa.receive();
if(state_request==false) {state_request =true;i+=1;if(i>3) i =0;}
}
}
vTaskDelay(10);
}
}
unsigned long time_setting=0;
static void task_setting_lora(void *pvParameters)
{
for(;;)
{
if ((unsigned long)(millis() - time_setting) >(1000-rd))
{
time_setting =millis();
if(task_status)
{
destination_addr =Node_addr[3];
if(set_status)cmd= cmdS+"O"+ (String)read_eeprom(addrepprom_oxy);
else
{
String dta = (String)read_eeprom(addrepprom_kp) + "/"+(String)read_eeprom(addrepprom_ki) +"*"+(String)read_eeprom(addrepprom_kd)+"+";
// Serial.println(dta);
cmd= cmdS+"P"+dta;
}
sendRequest(destination_addr,cmd);
LoRa.receive();
task_status ==false;
}
}
vTaskDelay(10);
}
}
static void task_realtime(void *pvParameters)
{
for(;;)
{
vTaskDelay(1000/ portTICK_PERIOD_MS);
}
}
int countconfig=0;
unsigned long timecheck_config=0;
static void task_button_config(void *pvParameters)
{
digitalWrite(led_config, HIGH);
for(;;)
{
if((unsigned long)(millis() - timecheck_config) >(500+rd))
{
timecheck_config = millis();
if(wm_nonblocking) wm.process();
if(digitalRead(button_config) == 0)
{
countconfig ++;
Serial.println(countconfig);
if(countconfig>10)
{
digitalWrite(led_config,LOW);
wm.resetSettings();
ESP.restart();
}
}
else countconfig=0;
}
vTaskDelay(10/ portTICK_PERIOD_MS);
}
}
static void task_OTA(void *pvParameters)
{
for(;;)
{
server.handleClient();
vTaskDelay(10/ portTICK_PERIOD_MS);
}
}
static void task_blink_offline(void *pvParameters)
{
for(;;)
{
digitalWrite(led_config,1);
vTaskDelay(1000/ portTICK_PERIOD_MS);
digitalWrite(led_config,0);
vTaskDelay(1000/ portTICK_PERIOD_MS);
}
}
void setup() {
Serial.begin(115200);
EEPROM.begin(20);
wificonfig();
OTA_config();
loraSetup();
firebaseSetup();
// SD_setup();
xTaskCreate(task_lora_data,"lora",10000,NULL,1,&TaskHandle_1);
xTaskCreate(task_setting_lora,"setting",5000,NULL,1,&TaskHandle_2);
xTaskCreate(task_realtime,"realtime",1000,NULL,0,&TaskHandle_3);
xTaskCreate(task_button_config,"button",1000,NULL,0,&TaskHandle_4);
if(respons) xTaskCreate(task_OTA,"OTA",10000,NULL,3,&TaskHandle_5);
else xTaskCreate(task_blink_offline,"blink",1000,NULL,0,&TaskHandle_6);
last_oxysetup = read_eeprom(addrepprom_oxy);
Serial.println("last_oxysetup:" + (String)last_oxysetup);
last_kp = read_eeprom(addrepprom_kp);
Serial.println("last_kp:" + (String)last_kp);
pinMode(button_config,INPUT);
pinMode(led_config,OUTPUT);
// appendFile(SD, "/hello1.txt", "World!\n");
}
unsigned long t2=0;
unsigned long t3=0;
void loop() {
rd = random(100);
if(!respons){
Serial.println(111);
delay(100);
}
else
{
if ((unsigned long)(millis() - t2) >(1000-rd))
{
t2 = millis();
json.set("parent_001", "parent 001 text");
Firebase.pushJSON(fbdo, "/test/append", json);
}
if((unsigned long)(millis() - t3) >(2000+rd))
{
t3=millis() ;
if (Firebase.getString(fbdo, "/OxySV")) {
oxysetup= fbdo.stringData();
Serial.println("OxySv:"+oxysetup);
if(oxysetup !=last_oxysetup)
{
last_oxysetup= oxysetup;
write_eeprom (addrepprom_oxy,last_oxysetup.toFloat());
task_status =true;
set_status=true;
}
}
if (Firebase.getString(fbdo, "/kp")) {
kp= fbdo.stringData();
//Serial.println("kp:"+kp);
if(kp !=last_kp)
{
last_kp= kp;
write_eeprom (addrepprom_kp,last_kp.toFloat());
task_status =true;
set_status=false;
}
}
if (Firebase.getString(fbdo, "/ki")) {
ki= fbdo.stringData();
Serial.println("ki:"+ki);
if(ki !=last_ki)
{
last_ki= ki;
write_eeprom (addrepprom_ki,last_ki.toFloat());
task_status =true;
set_status=false;
}
}
if (Firebase.getString(fbdo, "/kd")) {
kd= fbdo.stringData();
Serial.println("kd:"+kd);
if(kd !=last_kd)
{
last_kd=kd;
write_eeprom(addrepprom_kd,last_kd.toFloat());
task_status =true;
set_status=false;
}
}
}
}
}
void firebaseSetup()
{
Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
Firebase.reconnectWiFi(true);
Serial.println("Firebase OK!");
}
float read_eeprom(int addr)
{
float readfloat;
u.b[0] = EEPROM.read(addr);
u.b[1] = EEPROM.read(addr+1);
u.b[2] = EEPROM.read(addr+2);
u.b[3] = EEPROM.read(addr+3);
readfloat = u.fval;
return readfloat;
}
void write_eeprom(int addr,float value)
{
floatAsBytes.fval = value;
EEPROM.write(addr, floatAsBytes.bval[0]);
EEPROM.write(addr+1, floatAsBytes.bval[1]);
EEPROM.write(addr+2, floatAsBytes.bval[2]);
EEPROM.write(addr+3, floatAsBytes.bval[3]);
EEPROM.commit();
Serial.println("save succesfully!");
}
void sendRequest(byte addr_destination, String message)
{
uint8_t data_send[3];
data_send[0] = addr_destination;
data_send[1] = gattway_addr;
data_send[2] = message.length();
uint8_t crc=crc8(data_send, 3);
LoRa.beginPacket();
LoRa.write(data_send[0]);
LoRa.write(data_send[1]);
LoRa.write(data_send[2]);
LoRa.write(crc);
LoRa.print(message);
LoRa.endPacket();
// state_request=false;
}
void onReceive(int packetSize)
{
byte data_rec[4];
String LoRaData="";
if (packetSize == 0) return;
data_rec[0]=LoRa.read(); //Serial.println(data_rec[0]);//addr gatt
data_rec[1]=LoRa.read();//Serial.println(data_rec[1]);// addr node
data_rec[2]=LoRa.read(); //Serial.println(data_rec[2]);
data_rec[3]=LoRa.read();// Serial.println(data_rec[2]);
while (LoRa.available()) LoRaData = LoRa.readString(); //Serial.println(LoRaData);
if ((data_rec[0] != gattway_addr)|| (data_rec[1]!= destination_addr )){ Serial.println("not for me."); return ;}
if(data_rec[3] != crc8(data_rec, 3)){ Serial.println("crc faile"); return;}
if(LoRaData.length() != data_rec[2]){ Serial.println("data length faile"); return;}
//if(data_rec[1] == nodeOne_addr && LoRaData ==NULL )iloi1 +=1;
//Serial.println("iloi1:" +(String)iloi1);
decode_data(data_rec[1],LoRaData);
}
//========================================================
uint8_t calc_crc(uint8_t data) {
int index;
uint8_t temp;
for (index = 0; index < 8; index++) {
temp = data;
data <<= 1;
if (temp & 0x80) {data ^= 0x07;}
}
return data;
}
uint8_t crc8(byte data[], byte n)
{
int i;
uint8_t crc = calc_crc((0x1D << 1) | 1);
for (i = 0; i < n; i++) {
crc = calc_crc(data[i] ^ crc);
}
return crc;
}
unsigned long timeout_setting=0;
void decode_data(byte addr,String sms)
{
int pos1,pos2,pos3,pos4,pos5,pos6,pos7,pos8,pos9,pos10,pos11;
switch(addr)
{
case nodeOne_addr:
{
pos1 = sms.indexOf('a');
pos2 = sms.indexOf('b');
pos3 = sms.indexOf('c');
pos4 = sms.indexOf('/');
temp =sms.substring(0, pos1);
pH = sms.substring(pos1 +1, pos2);
oxy =sms.substring(pos2 +1, pos3);
bat1=sms.substring(pos3 +1, pos4);
node_status = sms.substring(pos4 +1, sms.length());
Serial.println("T:"+temp+ "pH:" +pH + "oxy:"+oxy + "bat1:"+bat1);
if(node_status !="OK1" ||sms ==NULL) iloi1 +=1;
Serial.println("iloi1:" +(String)iloi1);
break;
}
case nodeTwo_addr:
{
pos7 = sms.indexOf('f');
pos8 = sms.indexOf('/');
level=sms.substring(0, pos7);
bat2=sms.substring(pos7 +1, pos8);
node_status = sms.substring(pos8 +1, sms.length());
Serial.println("level:"+level+"bat2:"+bat2);
if(node_status !="OK2" ||sms ==NULL ) iloi2 +=2;
Serial.println("iloi2:" +(String)iloi2);
break;
}
case nodeThree_addr:
{
pos5 = sms.indexOf('d');
pos6 = sms.indexOf('/');
TDS=sms.substring(0, pos5);
bat3=sms.substring(pos5 +1, pos6);
node_status = sms.substring(pos6 +1, sms.length());
Serial.println("TDS:"+TDS+"bat3:"+bat3);
if(node_status !="OK3" ||sms ==NULL ) iloi3 +=1;
Serial.println("iloi3:" +(String)iloi3);
break;
}
case nodeFourth_addr:
{
if(cmd==cmdR)
{
pos9 = sms.indexOf('h');
pos10 = sms.indexOf('j');
pos11 = sms.indexOf('/');//Voltage,Cunrrent
Voltage=sms.substring(0, pos9);
Cunrrent=sms.substring(pos9 +1, pos10);
bat4=sms.substring(pos10 +1, pos11);
node_status = sms.substring(pos11 +1, sms.length());
Serial.println("Voltage:"+Voltage+"Cunrrent:"+Cunrrent+"bat4:"+bat4 + "node_status"+node_status);
if(node_status !="OK4" ||sms ==NULL ) iloi4 +=1;
Serial.println("iloi4:" +(String)iloi4);
}
else //if(cmd==cmdS)
{
setting= sms;
Serial.println("setting:" + setting);
if((unsigned long)(millis() -timeout_setting) >=5000 )
{
timeout_setting= millis();
if(setting =="OKO" && set_status )
{
Serial.println("setting oxy succesfully!");
task_status =false;
setting="";
}
else if(setting !="OKO" && set_status )
{
Serial.println("setting oxy failed");
task_status =false;
setting="";
}
else if(setting =="OKP" && set_status ==false )
{
Serial.println("setting kpid succesfully!");
task_status =false;
setting="";
}
else if(setting !="OKP" && set_status ==false )
{
Serial.println("setting kpid failed!");
task_status =false;
setting="";
}
}
}
break;
}
default : break;
}
}
void loraSetup()
{
LoRa.setPins(csPin, resetPin, irqPin);// set CS, reset, IRQ pin
// override the default CS, reset, and IRQ pins (optional)
if (!LoRa.begin(fre)) { // initialize ratio at 915 MHz
Serial.println("LoRa init failed. Check your connections.");
delay(5000);
//ESP.restart();
}
LoRa.setTxPower(20);
LoRa.onReceive(onReceive);
LoRa.receive();
LoRa.enableCrc();
Serial.println("LoRa init succeeded.");
}
void OTA_config()
{
if (!MDNS.begin(host)) { //http://esp32.local
Serial.println("Error setting up MDNS responder!");
while (1) {
delay(1000);
}
}
Serial.println("mDNS responder started");
/*return index page which is stored in serverIndex */
server.on("/", HTTP_GET, []() {
server.sendHeader("Connection", "close");
server.send(200, "text/html", loginIndex);
});
server.on("/serverIndex", HTTP_GET, []() {
server.sendHeader("Connection", "close");
server.send(200, "text/html", serverIndex);
});
/*handling uploading firmware file */
server.on("/update", HTTP_POST, []() {
server.sendHeader("Connection", "close");
server.send(200, "text/plain", (Update.hasError()) ? "FAIL" : "OK");
ESP.restart();
}, []() {
HTTPUpload& upload = server.upload();
if (upload.status == UPLOAD_FILE_START) {
vTaskSuspend(TaskHandle_1);
vTaskSuspend(TaskHandle_2);
vTaskSuspend(TaskHandle_3);
vTaskSuspend(TaskHandle_4);
Serial.printf("Update: %s\n", upload.filename.c_str());
if (!Update.begin(UPDATE_SIZE_UNKNOWN)) { //start with max available size
Update.printError(Serial);
}
} else if (upload.status == UPLOAD_FILE_WRITE) {
/* flashing firmware to ESP*/
if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) {
Update.printError(Serial);
}
} else if (upload.status == UPLOAD_FILE_END) {
if (Update.end(true)) { //true to set the size to the current progress
Serial.printf("Update Success: %u\nRebooting...\n", upload.totalSize);
} else {
Update.printError(Serial);
}
}
});
server.begin();
}
void wificonfig()
{
WiFi.mode(WIFI_STA);
if(!WiFi.config(local_IP, gateway, subnet, primaryDNS, secondaryDNS)) {
Serial.println("STA Failed to configure");
}
Serial.println("");
Serial.print("Connected to ");
//Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
if(wm_nonblocking) wm.setConfigPortalBlocking(false);
// add a custom input field
int customFieldLength = 40;
// new (&custom_field) WiFiManagerParameter("customfieldid", "Custom Field Label", "Custom Field Value", customFieldLength,"placeholder=\"Custom Field Placeholder\"");
// test custom html input type(checkbox)
// new (&custom_field) WiFiManagerParameter("customfieldid", "Custom Field Label", "Custom Field Value", customFieldLength,"placeholder=\"Custom Field Placeholder\" type=\"checkbox\""); // custom html type
// test custom html(radio)
const char* custom_radio_str = "<br/><label for='customfieldid'>Custom Field Label</label><input type='radio' name='customfieldid' value='1' checked> One<br><input type='radio' name='customfieldid' value='2'> Two<br><input type='radio' name='customfieldid' value='3'> Three";
new (&custom_field) WiFiManagerParameter(custom_radio_str); // custom html input
wm.addParameter(&custom_field);
wm.setSaveParamsCallback(saveParamCallback);
// custom menu via array or vector
//
// menu tokens, "wifi","wifinoscan","info","param","close","sep","erase","restart","exit" (sep is seperator) (if param is in menu, params will not show up in wifi page!)
// const char* menu[] = {"wifi","info","param","sep","restart","exit"};
// wm.setMenu(menu,6);
std::vector<const char *> menu = {"wifi","info","param","sep","restart","exit"};
wm.setMenu(menu);
// set dark theme
wm.setClass("invert");
//set static ip
// wm.setSTAStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); // set static ip,gw,sn
// wm.setShowStaticFields(true); // force show static ip fields
// wm.setShowDnsFields(true); // force show dns field always
// wm.setConnectTimeout(20); // how long to try to connect for before continuing
wm.setConfigPortalTimeout(30); // auto close configportal after n seconds
// wm.setCaptivePortalEnable(false); // disable captive portal redirection
// wm.setAPClientCheck(true); // avoid timeout if client connected to softap
// wifi scan settings
// wm.setRemoveDuplicateAPs(false); // do not remove duplicate ap names (true)
// wm.setMinimumSignalQuality(20); // set min RSSI (percentage) to show in scans, null = 8%
// wm.setShowInfoErase(false); // do not show erase button on info page
// wm.setScanDispPerc(true); // show RSSI as percentage not graph icons
// wm.setBreakAfterConfig(true); // always exit configportal even if wifi save fails
// res = wm.autoConnect(); // auto generated AP name from chipid
// res = wm.autoConnect("AutoConnectAP"); // anonymous ap
respons = wm.autoConnect("ESP_LORA","1234567890"); // password protected ap
if(!respons) {
Serial.println("Failed to connect or hit timeout");
// ESP.restart();
}
else {
//if you get here you have connected to the WiFi
Serial.println("connected...yeey :)");
}
WiFi.reconnect();
}
String getParam(String name){
//read parameter from server, for customhmtl input
String value;
if(wm.server->hasArg(name)) {
value = wm.server->arg(name);
}
return value;
}
void saveParamCallback(){
Serial.println("[CALLBACK] saveParamCallback fired");
Serial.println("PARAM customfieldid = " + getParam("customfieldid"));
}
void SD_setup()
{
// sd_spi.begin(SD_SCK, SD_MISO, SD_MOSI, SD_CS);
// MailClient.sdBegin(SD_SCK, SD_MISO, SD_MOSI, SD_CS);
if (!SD.begin(SD_CS, sd_spi)) Serial.println("SD Card: mounting failed.");
else Serial.println("SD Card: mounted.");
}
void appendFile(fs::FS &fs, const char * path, const char * message){
Serial.printf("Appending to file: %s\n", path);
File file = fs.open(path, FILE_APPEND);
if(!file){
Serial.println("Failed to open file for appending");
return;
}
if(file.print(message)){
Serial.println("Message appended");
} else {
Serial.println("Append failed");
}
file.close();
}
| [
"danghungdang0123@gmail.com"
] | danghungdang0123@gmail.com |
6dcaa1c0dbfb8c0d1ec746c337f8a0bcb7eba1af | 7df18b458cfb76b1c37c62dfcdea12bfbd2566b3 | /Doomenstein/Code/Game/Actor.hpp | 6e892df3ad29bef5fb0f8dc1a9a5dbe7bdad00d2 | [
"MIT"
] | permissive | yixuan-wei/Doomenstein | 43abcdbc28a1fad780b4163eda92c3b4f84b3bf2 | c1c80e5253a002d056b1990abf38e8c567c6e5ad | refs/heads/main | 2023-03-07T15:23:07.838742 | 2021-02-23T04:51:59 | 2021-02-23T04:51:59 | 341,427,215 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 388 | hpp | #pragma once
#include "Game/Entity.hpp"
class Actor : public Entity
{
public:
Actor(Map* map, EntityDef const* definition);
void Update() override;
void OnProjectileHit(Projectile* proje) override;
void SetHealth(float newHealth);
float GetHealth() const {return m_health;}
public:
unsigned short m_lastHealthSeqNo = 0;
private:
float m_health = 0.f;
}; | [
"yixuan_wei@qq.com"
] | yixuan_wei@qq.com |
a7fd920a0f03a75b7eeb06a0dd4287298ee843fa | c2e0e47feb85a9d18d54e84fd1d84467843be44b | /bai4.cpp | d158b12016aaf914fafc456c2b96c4154303d5ac | [] | no_license | thunguyen0810/TTCS3 | 8fcb803ecf249469e235208029fc8a953d79a8b0 | 766241c1d0b21f34a81792969a86fd8f26e4fc69 | refs/heads/master | 2020-04-15T04:54:04.983791 | 2019-01-13T17:11:00 | 2019-01-13T17:11:00 | 164,400,723 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,040 | cpp | #include <iostream>
#include <fstream>
#include <windows.h>
using namespace std;
fstream f;
int n;
void textcolor(int x)
{
HANDLE mau;
mau=GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(mau,x);
}
void DocFile(int a[],int b[],int c[])
{
f.open("dulieu.txt", ios::in);
f >> n;
for(int i = 0; i < n; i++)
f >> a[i];
for(int i = 0; i < n; i++)
f >> b[i];
for(int i = 0; i < n; i++)
f >> c[i];
f.close();
}
void XuatFile(int a[],int b[],int c[])
{
f.open("dulieu.txt", ios::in);
cout << n << endl;
for(int i = 0; i < n; i++)
cout << a[i] << " ";
cout << endl;
for(int i = 0; i < n; i++)
cout << b[i] << " ";
cout << endl;
for(int i = 0; i < n; i++)
cout << c[i] << " ";
cout << endl;
f.close();
}
void SapXep(int a[], int b[], int c[])
{
for(int i = 0; i < n - 1; i++)
for(int j = i + 1; j < n; j++)
if(c[i] > c[j])
{
swap(b[i], b[j]);
swap(a[i], a[j]);
swap(c[i], c[j]);
}
}
void XepLich(int a[], int b[], int c[])
{
f.open("dulieu2.txt", ios::out);
SapXep(a, b, c);
int t = 0;
t = b[0];
f << a[0] << " ";
for(int i = 0; i < n; i++)
{
if(c[i] >= t + b[i])
{
t += b[i];
f << a[i] << " ";
c[i] = 0;
}
}
int dem = 0;
textcolor(10);
cout << "Xe bi tre han : " << endl;
textcolor(15);
for(int i = 1; i < n; i++)
{
if(c[i] != 0)
{
textcolor(11);
cout << a[i] << endl;
textcolor(15);
dem ++;
f << endl << a[i];
}
}
if(dem == 0)
{
textcolor(11);
cout << "Khong co xe bi tre han" << endl;;
textcolor(15);
}
f.close();
}
void XuatThuTu()
{
textcolor(10);
cout << endl;
cout << "Thu tu sua chua oto dung han :" << endl;
textcolor(15);
string s;
ifstream f("dulieu2.txt");
getline(f, s);
do
{
textcolor(11);
cout << s << endl;
textcolor(15);
getline(f, s);
}
while(f.eof()==false);
f.close();
}
int main()
{
int a[20], b[20], c[20];
DocFile(a, b, c);
textcolor(10);
cout << "O to duoc giao sua chua" << endl;
textcolor(15);
XuatFile(a, b, c);
cout << endl;
XepLich(a, b, c);
XuatThuTu();
}
| [
"thunguyen1918@gmail.com"
] | thunguyen1918@gmail.com |
62506c581c6955d750f18d10cdb5743f918ac288 | 22c3c144241485a35c51697ed1188e9adfd1ef97 | /firstLoops/reversedNumber/S001-AC.cc | 6545fe3b6a386091001bf34e914bb05c747bda50 | [] | no_license | pedrompg/jutge | 93d20c61989f9709b1fb978b6c63be79ce56d0f0 | d82eb669ddef87e32bac73d6ec4aba2378daf480 | refs/heads/master | 2020-05-04T19:43:01.202905 | 2016-01-06T20:56:32 | 2016-01-06T20:56:32 | 12,669,556 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 148 | cc | #include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
while(n/10 > 0) {
cout << n%10;
n /= 10;
}
cout << n%10 << endl;
}
| [
"pedrompg@gmail.com"
] | pedrompg@gmail.com |
40cf23e7b6fbd385af85c428d988c952a6221509 | a2c16f7d39cedcc85be0b7e1b77bfcf11102f0d3 | /lib/ogldev-source/Common/ogldev_texture.cpp | abf166b4553c00589363a1be2ef9a727f0b099d4 | [] | no_license | dy-dev/SweepingBird | 47014e7c5e352b7c5d53f4d57e05e2359d958448 | 60d8eed433d305a509e99be90199523fed0e1f46 | refs/heads/master | 2021-04-12T04:19:13.319177 | 2015-03-28T17:52:35 | 2015-03-28T17:52:35 | 30,604,185 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,901 | cpp | /*
Copyright 2011 Etay Meiri
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 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include "ogldev_texture.h"
Texture::Texture(GLenum TextureTarget, const std::string& FileName)
{
m_textureTarget = TextureTarget;
m_fileName = FileName;
}
bool Texture::Load()
{
/* try {
m_image.read(m_fileName);
m_image.write(&m_blob, "RGBA");
}
catch (Magick::Error& Error) {
std::cout << "Error loading texture '" << m_fileName << "': " << Error.what() << std::endl;
return false;
}*/
int x;
int y;
int comp;
unsigned char * image = stbi_load(m_fileName.c_str(), &x, &y, &comp, 4);
glGenTextures(1, &m_textureObj);
glBindTexture(m_textureTarget, m_textureObj);
glTexImage2D(m_textureTarget, 0, GL_RGBA, x, y, 0, GL_RGBA, GL_UNSIGNED_BYTE, image);
//glTexImage2D(m_textureTarget, 0, GL_RGBA, m_image.columns(), m_image.rows(), 0, GL_RGBA, GL_UNSIGNED_BYTE, m_blob.data());
glTexParameterf(m_textureTarget, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(m_textureTarget, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glBindTexture(m_textureTarget, 0);
return true;
}
void Texture::Bind(GLenum TextureUnit)
{
glActiveTexture(TextureUnit);
glBindTexture(m_textureTarget, m_textureObj);
}
| [
"dominique.yolin@free.fr"
] | dominique.yolin@free.fr |
2b8a5647fc1d685124b4cc4a21b38eb3d6e3d782 | 5a63bd6870346aa6593233b990303e743cdb8861 | /SDK/UI_QuickAccessAmount_functions.cpp | 6b8fabfe2e53c35a45c5f9365b6df9bdd76bba02 | [] | no_license | zH4x-SDK/zBlazingSails-SDK | dc486c4893a8aa14f760bdeff51cea11ff1838b5 | 5e6d42df14ac57fb934ec0dabbca88d495db46dd | refs/heads/main | 2023-07-10T12:34:06.824910 | 2021-08-27T13:42:23 | 2021-08-27T13:42:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,134 | cpp |
#include "../SDK.h"
// Name: BS, Version: 1.536.0
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
// Functions
//---------------------------------------------------------------------------
// Function UI_QuickAccessAmount.UI_QuickAccessAmount_C.SetAmountColor
// (Public, HasOutParms, HasDefaults, BlueprintCallable, BlueprintEvent, BlueprintPure)
// Parameters:
// struct FSlateColor ReturnValue (Parm, OutParm, ReturnParm)
struct FSlateColor UUI_QuickAccessAmount_C::SetAmountColor()
{
static auto fn = UObject::FindObject<UFunction>("Function UI_QuickAccessAmount.UI_QuickAccessAmount_C.SetAmountColor");
UUI_QuickAccessAmount_C_SetAmountColor_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function UI_QuickAccessAmount.UI_QuickAccessAmount_C.SetAmount
// (Public, HasOutParms, HasDefaults, BlueprintCallable, BlueprintEvent, BlueprintPure)
// Parameters:
// struct FText ReturnValue (Parm, OutParm, ReturnParm)
struct FText UUI_QuickAccessAmount_C::SetAmount()
{
static auto fn = UObject::FindObject<UFunction>("Function UI_QuickAccessAmount.UI_QuickAccessAmount_C.SetAmount");
UUI_QuickAccessAmount_C_SetAmount_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function UI_QuickAccessAmount.UI_QuickAccessAmount_C.Tick
// (BlueprintCosmetic, Event, Public, BlueprintEvent)
// Parameters:
// struct FGeometry MyGeometry (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData)
// float InDeltaTime (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
void UUI_QuickAccessAmount_C::Tick(const struct FGeometry& MyGeometry, float InDeltaTime)
{
static auto fn = UObject::FindObject<UFunction>("Function UI_QuickAccessAmount.UI_QuickAccessAmount_C.Tick");
UUI_QuickAccessAmount_C_Tick_Params params;
params.MyGeometry = MyGeometry;
params.InDeltaTime = InDeltaTime;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function UI_QuickAccessAmount.UI_QuickAccessAmount_C.ExecuteUbergraph_UI_QuickAccessAmount
// (Final, HasDefaults)
// Parameters:
// int EntryPoint (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
void UUI_QuickAccessAmount_C::ExecuteUbergraph_UI_QuickAccessAmount(int EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function UI_QuickAccessAmount.UI_QuickAccessAmount_C.ExecuteUbergraph_UI_QuickAccessAmount");
UUI_QuickAccessAmount_C_ExecuteUbergraph_UI_QuickAccessAmount_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"zp2kshield@gmail.com"
] | zp2kshield@gmail.com |
21f77f150dea4e60e5014780ca4a3786dc00f2e3 | 4f1134051d2808bf609853cd116ead67a670ca80 | /Gebhard/src/Green.cc | afd96d68a2ad3514e8188f637fd66a5c9f6275d8 | [] | no_license | mhoehle/permtest | 93ddf212855f3c5e7839fe94ccf2e9b5c7bed7e2 | 9b4421b4fd5a34c7f7cd928be33625529cf3d402 | refs/heads/master | 2023-01-23T18:46:22.001249 | 2019-06-02T21:46:04 | 2019-06-02T21:46:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,424 | cc | ///////////////////////////////////////////////////////
//
// Copyright � 1994 Jens Gebhard
//
// DATEI: GREEN.CPP (Green.cc)
//
// ZWECK: Implementierung des Green-Algorithmus
//
///////////////////////////////////////////////////////
#include "green.h"
///////////////////////////////////////////////////////
//
// Permutationstest durchfuehren
// --> nichts
// <-- FoundLowerValues
//
double GreenAlgorithmus::ExecPermutation()
{
Level=0;
Summe=0;
FoundLowerValue=0;
if(NoOptimization)
RekNoOptimization(-1);
else
Rek(-1);
return FoundLowerValue;
}
///////////////////////////////////////////////////////
//
// optimierte Version des Algorithmus (rekursiv)
// --> LastIndex, N1, N2, z[]
// <-- FoundLowerValues
//
void GreenAlgorithmus::Rek(int LastIndex)
{
int i;
if(Stop)return;
Level++;
for(i=LastIndex+1;i<Level+N2;i++)
{
Summe+=z[i];
if(Level<N1)
{
if(Summe+(N1-Level)*z[i+1]>Compare)
{
Summe-=z[i];
break;
}
Rek(i);
}
else if(Level==N1 && Summe <= Compare)
FoundLowerValue++;
Summe-=z[i];
}
Level--;
}
///////////////////////////////////////////////////////
//
// nicht optimierte Version des Algorithmus (rekursiv)
// --> LastIndex, N1, N2, z[]
// <-- FoundLowerValues
//
void GreenAlgorithmus::RekNoOptimization(int LastIndex)
{
int i;
if(Stop)return;
Level++;
for(i=LastIndex+1;i<Level+N2;i++)
{
Summe+=z[i];
if(Level<N1)
RekNoOptimization(i);
else if(Level==N1 && Summe <= Compare)
FoundLowerValue++;
Summe-=z[i];
}
Level--;
}
///////////////////////////////////////////////////////
//
// Optionen auf Gueltigkeit ueberpruefen
// --> Options
// <-- TRUE, fall die Optionen von dieser oder der
// Basisklasse erkannt werden.
// Options wird geaendert
//
BOOL GreenAlgorithmus::DoYouKnowTheseOptions(char *Options)
{
BOOL OK=TRUE;
for(int i=0;i<strlen(Options);i++)
{
switch(Options[i])
{
case '#':
break;
case 'n':
Options[i]='#';
break;
case 'o':
while(Options[++i]!='}'){;}
default:
OK=FALSE;
}
}
return (OK || PermutationTest::DoYouKnowTheseOptions(Options));
}
///////////////////////////////////////////////////////
//
// Optionen bearbeiten
// --> Options
// <-- Precision, NoOptimization
//
void GreenAlgorithmus::SetOptions(char *Options)
{
Precision=6;
for(int i=0;i<strlen(Options);i++)
{
if(Options[i]=='o')
while(Options[++i]!='}'){;}
if(Options[i]=='n')
NoOptimization=TRUE;
}
PermutationTest::SetOptions(Options);
}
///////////////////////////////////////////////////////
//
// kann der Test durchgefuehrt werden?
// --> PermutationCount
// <-- TRUE, falls moeglich, FALSE sonst
//
BOOL GreenAlgorithmus::CanDo()
{
BOOL OK;
if(PermutationCount==0xfffffffful)
{
std::cerr<<"FEHLER: Zu viele Daten!"<<std::endl;
OK=FALSE;
}
else
OK=TRUE;
return OK && PermutationTest::CanDo();
}
///////////////////////////////////////////////////////
//
// Meldung ausgeben
// --> NoOptimization
// <-- nichts
//
void GreenAlgorithmus::PreProcessMessage() const
{
PermutationTest::PreProcessMessage();
if(!Quiet)
std::cerr<<"Algorithmus:\tGreen "<<(NoOptimization ? "ohne " : "mit ")<<"Optimierung"<<std::endl;
}
///////////////////////////////////////////////////////
//
// Meldung ausgeben
// --> nichts
// <-- nichts
//
void GreenAlgorithmus::PostProcessMessage() const
{
PermutationTest::PostProcessMessage();
}
| [
"hoehle@math.su.se"
] | hoehle@math.su.se |
741b5449205afb994beb571b686ece6dd65b4fe3 | ce57e8bf8a5d1c0465ff5e3dd5ce7d5d75fa3c21 | /Gkom/Roombox.h | fe4d904b5ab575b80709f8fce006046aa0c5b947 | [] | no_license | Jimmymax297/Falling-Domino | d96849b65e7783e966cd168c262206b60c6e744d | 4f9b91c4615b83768907af12b7ca0a484b3b9afa | refs/heads/master | 2020-03-20T06:10:30.735375 | 2018-06-13T16:31:17 | 2018-06-13T16:31:17 | 137,240,417 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 281 | h | #pragma once
#include <GL/glew.h>
#include <string>
#include <vector>
class Roombox {
private:
GLuint id;
GLuint VAO;
GLuint VBO;
std::vector<GLfloat> vertices;
public:
Roombox(std::vector<std::string> filenames);
GLuint getID() const { return id; }
void render() const;
}; | [
"jakubpleban297@gmail.com"
] | jakubpleban297@gmail.com |
483cef559be8409d8a04603ad4a70472bb341b7d | 1ec0ccaf8346cca8e2a30e58d84a3d026a5921a2 | /test/Ttranslate.cxx | adc1a75efd43eed58fc91cd830b6419ba37c6c67 | [
"MIT"
] | permissive | kloetzl/libdna | 652f979760b5ddda19dbd62fe9733020fbddf215 | 74698b4e445bbf03134e87608301bfc3d48a926f | refs/heads/master | 2023-04-16T10:59:09.116939 | 2023-04-08T06:08:28 | 2023-04-08T06:08:28 | 136,008,071 | 20 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,463 | cxx | #include "Tcommon.h"
#include <catch2/catch.hpp>
#include <cstring>
#include <dna.h>
#include <string>
template <typename FN>
std::string
make_small_table(FN translate)
{
auto table = std::string();
char triplet[4] = {0};
auto tcag = std::string("TCAG");
for (char n0 : tcag) {
for (char n2 : tcag) {
for (char n1 : tcag) {
triplet[0] = n0;
triplet[1] = n1;
triplet[2] = n2;
char aa;
translate(triplet, triplet + 3, &aa);
table += aa;
}
table += '\n';
}
}
return table;
}
static std::string ref_small_table = {
"FSYC\n" //
"FSYC\n" //
"LS**\n" //
"LS*W\n" //
//
"LPHR\n" //
"LPHR\n" //
"LPQR\n" //
"LPQR\n" //
//
"ITNS\n" //
"ITNS\n" //
"ITKR\n" //
"MTKR\n" //
//
"VADG\n" //
"VADG\n" //
"VAEG\n" //
"VAEG\n" //
};
TEST_CASE("Some simple checks")
{
auto mrna = std::string("AAA-AAC-AAG-AAT-ACAACCACGACT");
char *aa = new char[mrna.size() / 3 + 10];
char *ptr = dnax_translate(mrna.data(), mrna.data() + mrna.size(), aa);
*ptr = 0;
REQUIRE(std::string(aa) == "KNKNTTTT");
INFO("No triplet")
REQUIRE(dnax::translate("A---A") == "");
delete[] aa;
}
TEST_CASE("Some simple checks (lowercase)")
{
auto mrna = std::string("aaa-aac-aag-aat-acaaccacgact");
char *aa = new char[mrna.size() / 3 + 10];
char *ptr = dnax_translate(mrna.data(), mrna.data() + mrna.size(), aa);
*ptr = 0;
REQUIRE(std::string(aa) == "KNKNTTTT");
INFO("No triplet")
REQUIRE(dnax::translate("a---a") == "");
delete[] aa;
}
TEST_CASE("case independance")
{
auto acgt = std::string("acgt");
char triplet[4] = {0};
for (char n0 : acgt) {
for (char n2 : acgt) {
for (char n1 : acgt) {
triplet[0] = n0;
triplet[1] = n1;
triplet[2] = n2;
char aa;
dnax_translate(triplet, triplet + 3, &aa);
std::transform(
std::begin(triplet), std::end(triplet), std::begin(triplet),
[](unsigned char c) { return std::toupper(c); });
char AA;
dnax_translate(triplet, triplet + 3, &AA);
INFO(triplet)
REQUIRE(aa == AA);
}
}
}
}
TEST_CASE("Compact table")
{
// the following table is not exhaustive.
auto table = std::vector<std::tuple<std::string, std::string, std::string>>{
{"Alanine", "A", "GCN"},
{"Arginine", "R", "CGN"},
{"Arginine", "R", "AGR"},
{"Asparagine", "N", "AAY"},
{"Aspartic acid", "D", "GAY"},
{"Aspartic acid or aspraragine", "B", "RAY"},
{"Cysteine", "C", "TGY"},
{"Glutamic acid", "E", "GAR"},
{"Glutamic acid or glutamine", "Z", "SAR"},
{"Glutamine", "Q", "CAR"},
{"Glycine", "G", "GGN"},
{"Histidine", "H", "CAY"},
{"Isoleucine", "I", "ATH"},
{"Leucine", "L", "CTN"},
{"Leucine", "L", "TTR"},
{"Lysine", "K", "AAR"},
{"Methionine", "M", "ATG"},
{"Phenylalanine", "F", "TTY"},
{"Proline", "P", "CCN"},
{"Serine", "S", "TCN"},
{"Serine", "S", "AGY"},
{"Threonine", "T", "ACN"},
{"Tryptophan", "W", "TGG"},
{"Tyrosine", "Y", "TAY"},
{"Valine", "V", "GTN"},
{"Terminator", "*", "TAR"},
{"Terminator", "*", "TGA"},
{"Unknown", "X", "NNN"}};
for (const auto &code : table) {
char buffer[4];
auto amino_acid_end = dnax_translate(
dna::begin(std::get<2>(code)), dna::end(std::get<2>(code)), buffer);
auto amino_acid = std::string(buffer, amino_acid_end - buffer);
INFO(std::get<2>(code));
REQUIRE(amino_acid == std::get<1>(code));
}
}
TEST_CASE("Small table")
{
std::string small_table = make_small_table(dnax_translate);
REQUIRE(ref_small_table == small_table);
}
| [
"fabian@kloetzl.info"
] | fabian@kloetzl.info |
f538845beffbdc0b6cdf436931b32bc53caeb1f8 | 536bcf02361eff8848fb76990135e44aa8b3a513 | /03-inheritanceAndPolymorphism/BaseParticles.cpp | 2bb8a1e54bcc5f5be45ef5b50db9420375a19426 | [] | no_license | JacobLetko/Object-Oriented | 9e6fdb1695b96a71ab8eff9e76f9de3747b59f48 | acdbd6c6ba07c77cc3aeb1e0d9a6567bd146d2f2 | refs/heads/master | 2021-07-07T20:58:33.438053 | 2017-10-04T18:51:36 | 2017-10-04T18:51:36 | 104,774,006 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 262 | cpp | #include "BaseParticles.h"
#include "sfwdraw.h"
void BaseParticle::update()
{
x += speedX;
y += speedY;
if (x < 0)
x = 800;
if (x > 800)
x = 0;
if (y < 0)
y = 800;
if (y > 800)
y = 0;
}
void BaseParticle::draw()
{
sfw::drawCircle(x, y, 10);
}
| [
"s179061@SEA-8FD51C"
] | s179061@SEA-8FD51C |
7d4415162bb352e75975a4b13445d29fcf5768b5 | 7dd73504d783c7ebb0c2e51fa98dea2b25c37a11 | /N64Wasm-master/code/src/mupen64plus-video-paraLLEl/parallel-rdp/util/timer.hpp | bae788cd03a2ffda6224f43996ed443e6f356696 | [
"MIT",
"LicenseRef-scancode-other-permissive"
] | permissive | bagel-man/bagel-man.github.io | 32813dd7ef0b95045f53718a74ae1319dae8c31e | eaccb6c00aa89c449c56a842052b4e24f15a8869 | refs/heads/master | 2023-04-05T10:27:26.743162 | 2023-03-16T04:24:32 | 2023-03-16T04:24:32 | 220,102,442 | 3 | 21 | MIT | 2022-12-14T18:44:43 | 2019-11-06T22:29:24 | C++ | UTF-8 | C++ | false | false | 1,645 | hpp | /* Copyright (c) 2017-2020 Hans-Kristian Arntzen
*
* 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.
*/
#pragma once
#include <stdint.h>
namespace Util
{
class FrameTimer
{
public:
FrameTimer();
void reset();
double frame();
double frame(double frame_time);
double get_elapsed() const;
double get_frame_time() const;
void enter_idle();
void leave_idle();
private:
int64_t start;
int64_t last;
int64_t last_period;
int64_t idle_start;
int64_t idle_time = 0;
int64_t get_time();
};
class Timer
{
public:
void start();
double end();
private:
int64_t t = 0;
};
int64_t get_current_time_nsecs();
} | [
"tom@blowmage.com"
] | tom@blowmage.com |
85df4dba5f9f6c12d45ae6ac3d4e754898e05e52 | f67f0f77370d18400e2ac3a64b5eda85231fbe8b | /of-develop/squareBump/62/h | e171487188887ae2a5bf3cd91f63c57a00fcebfe | [] | no_license | seiyawati/OpenFOAM | 6c3f0a2691e0eeabee6645d7b71c272c2489de03 | 79d770169962cc641f5b386318f210c61b9a8e25 | refs/heads/master | 2023-06-09T18:28:56.170426 | 2021-06-10T15:03:44 | 2021-06-10T15:03:44 | 354,198,942 | 0 | 0 | null | 2021-06-18T06:13:41 | 2021-04-03T04:30:05 | C++ | UTF-8 | C++ | false | false | 5,060 | /*--------------------------------*- C++ -*----------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Version: 7
\\/ M anipulation |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "62";
object h;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 1 0 0 0 0 0];
internalField nonuniform List<scalar>
400
(
0.0100007
0.0100007
0.0100007
0.0100007
0.0100007
0.0100007
0.0100007
0.0100007
0.0100006
0.0100006
0.0100006
0.0100006
0.0100006
0.0100005
0.0100005
0.0100004
0.0100004
0.0100003
0.0100002
0.0100001
0.0100006
0.0100006
0.0100006
0.0100006
0.0100006
0.0100005
0.0100005
0.0100005
0.0100005
0.0100005
0.0100005
0.0100005
0.0100004
0.0100004
0.0100004
0.0100003
0.0100003
0.0100002
0.0100001
0.01
0.0100005
0.0100005
0.0100005
0.0100005
0.0100005
0.0100005
0.0100005
0.0100005
0.0100005
0.0100005
0.0100005
0.0100004
0.0100004
0.0100004
0.0100003
0.0100003
0.0100002
0.0100002
0.0100001
0.01
0.0100004
0.0100004
0.0100004
0.0100004
0.0100004
0.0100004
0.0100004
0.0100004
0.0100004
0.0100004
0.0100004
0.0100003
0.0100003
0.0100003
0.0100003
0.0100002
0.0100002
0.0100001
0.0100001
0.01
0.0100004
0.0100004
0.0100004
0.0100004
0.0100004
0.0100004
0.0100004
0.0100003
0.0100003
0.0100003
0.0100003
0.0100003
0.0100003
0.0100003
0.0100002
0.0100002
0.0100002
0.0100001
0.0100001
0.01
0.0100003
0.0100003
0.0100003
0.0100003
0.0100003
0.0100003
0.0100003
0.0100003
0.0100003
0.0100003
0.0100002
0.0100002
0.0100002
0.0100002
0.0100002
0.0100001
0.0100001
0.0100001
0.0100001
0.01
0.0100002
0.0100002
0.0100002
0.0100002
0.0100002
0.0100002
0.0100002
0.0100002
0.0100002
0.0100002
0.0100002
0.0100002
0.0100002
0.0100002
0.0100001
0.0100001
0.0100001
0.0100001
0.01
0.01
0.0100002
0.0100002
0.0100002
0.0100002
0.0100002
0.0100002
0.0100002
0.0100002
0.0100001
0.0100001
0.0100001
0.0100001
0.0100001
0.0100001
0.0100001
0.0100001
0.0100001
0.01
0.01
0.01
0.0100001
0.0100001
0.0100001
0.0100001
0.0100001
0.0100001
0.0100001
0.0100001
0.0100001
0.0100001
0.0100001
0.0100001
0.0100001
0.0100001
0.0100001
0.01
0.01
0.01
0.01
0.01
0.01
0.01
0.01
0.01
0.01
0.01
0.01
0.01
0.01
0.01
0.01
0.01
0.01
0.01
0.01
0.01
0.01
0.01
0.01
0.01
0.00999997
0.00999997
0.00999997
0.00999997
0.00999997
0.00999997
0.00999997
0.00999997
0.00999997
0.00999997
0.00999997
0.00999997
0.00999998
0.00999998
0.00999998
0.00999998
0.00999999
0.00999999
0.00999999
0.01
0.0099999
0.0099999
0.0099999
0.0099999
0.0099999
0.0099999
0.00999991
0.00999991
0.00999991
0.00999991
0.00999992
0.00999992
0.00999993
0.00999994
0.00999994
0.00999995
0.00999996
0.00999997
0.00999998
0.00999999
0.00999983
0.00999983
0.00999983
0.00999983
0.00999984
0.00999984
0.00999984
0.00999985
0.00999985
0.00999986
0.00999986
0.00999987
0.00999988
0.00999989
0.00999991
0.00999992
0.00999994
0.00999995
0.00999997
0.00999999
0.00999976
0.00999976
0.00999977
0.00999977
0.00999977
0.00999977
0.00999978
0.00999978
0.00999979
0.0099998
0.00999981
0.00999982
0.00999983
0.00999985
0.00999986
0.00999988
0.00999991
0.00999993
0.00999996
0.00999998
0.0099997
0.0099997
0.0099997
0.0099997
0.0099997
0.00999971
0.00999972
0.00999972
0.00999973
0.00999974
0.00999975
0.00999977
0.00999978
0.0099998
0.00999983
0.00999985
0.00999988
0.00999991
0.00999995
0.00999998
0.00999963
0.00999963
0.00999963
0.00999963
0.00999963
0.00999964
0.00999964
0.00999965
0.00999966
0.00999967
0.00999969
0.0099997
0.00999972
0.00999975
0.00999977
0.0099998
0.00999984
0.00999988
0.00999993
0.00999997
0.00999956
0.00999956
0.00999956
0.00999957
0.00999957
0.00999958
0.00999959
0.0099996
0.00999961
0.00999962
0.00999964
0.00999966
0.00999968
0.00999971
0.00999974
0.00999977
0.00999982
0.00999986
0.00999992
0.00999997
0.00999948
0.00999948
0.00999948
0.00999948
0.00999948
0.00999949
0.0099995
0.00999951
0.00999952
0.00999953
0.00999955
0.00999957
0.0099996
0.00999963
0.00999966
0.0099997
0.00999975
0.00999981
0.00999988
0.00999995
0.00999943
0.00999943
0.00999944
0.00999944
0.00999945
0.00999945
0.00999946
0.00999947
0.00999949
0.0099995
0.00999952
0.00999954
0.00999957
0.0099996
0.00999964
0.00999968
0.00999974
0.0099998
0.00999988
0.00999996
0.00999931
0.00999931
0.00999931
0.00999931
0.00999932
0.00999933
0.00999934
0.00999935
0.00999936
0.00999938
0.00999939
0.00999942
0.00999945
0.00999948
0.00999952
0.00999957
0.00999963
0.0099997
0.0099998
0.00999991
)
;
boundaryField
{
sides
{
type zeroGradient;
}
inlet
{
type zeroGradient;
}
outlet
{
type fixedValue;
value uniform 0.01;
}
frontAndBack
{
type empty;
}
}
// ************************************************************************* //
| [
"kid960805@gmail.com"
] | kid960805@gmail.com | |
047b22e4e0d3a9a36c7b78259c383785d5560e48 | fa0305b6aae838cd9b099dc4bb51dbe40ed4df21 | /graphics_examples/lab5/lab5start.cpp | 2f9f78bf8f2d162850903bae48a9d36930a7f1a6 | [] | no_license | JamesTiberiusKirk/graphics_examples | 9f1fda0067c28cd84aa06d5daeb657facabfb623 | b9fa9a50716c5c133e984d006d17b0033ec314c2 | refs/heads/master | 2023-02-01T01:16:08.160121 | 2020-12-20T22:05:24 | 2020-12-20T22:05:24 | 317,273,183 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 10,644 | cpp | /*
Lab5start
This is an starting project for lab5. The goal for you is to apply texture
to both the cube and the sphere
Iain Martin October 2018
*/
/* Link to static libraries, could define these as linker inputs in the project settings instead
if you prefer */
#ifdef _DEBUG
#pragma comment(lib, "glfw3D.lib")
#pragma comment(lib, "glloadD.lib")
#else
#pragma comment(lib, "glfw3.lib")
#pragma comment(lib, "glload.lib")
#endif
#pragma comment(lib, "opengl32.lib")
#pragma comment(lib, "soil.lib")
/* Include the header to the GLFW wrapper class which
also includes the OpenGL extension initialisation*/
#include "wrapper_glfw.h"
#include "cube_tex.h"
#include "sphere_tex.h"
#include <iostream>
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
/* Include GLM core and matrix extensions*/
#include <glm/glm.hpp>
#include "glm/gtc/matrix_transform.hpp"
#include <glm/gtc/type_ptr.hpp>
/* Define buffer object indices */
GLuint positionBufferObject, colourObject, normalsBufferObject;
GLuint sphereBufferObject, sphereNormals, sphereColours, sphereTexCoords;
GLuint elementbuffer;
GLuint program; /* Identifier for the shader prgoram */
GLuint vao; /* Vertex array (Containor) object. This is the index of the VAO that will be the container for
our buffer objects */
GLuint colourmode; /* Index of a uniform to switch the colour mode in the vertex shader
I've included this to show you how to pass in an unsigned integer into
your vertex shader. */
/* Position and view globals */
GLfloat angle_x, angle_inc_x, x, model_scale, z, y;
GLfloat angle_y, angle_inc_y, angle_z, angle_inc_z;
GLuint drawmode; // Defines drawing mode of sphere as points, lines or filled polygons
GLuint numlats, numlongs; //Define the resolution of the sphere object
/* Uniforms*/
GLuint modelID, viewID, projectionID;
GLuint colourmodeID;
GLfloat aspect_ratio; /* Aspect ratio of the window defined in the reshape callback*/
GLuint numspherevertices;
Cube aCube;
Sphere aSphere;
bool mipMapEnable = true;
using namespace std;
using namespace glm;
class Texture {
public:
unsigned int uid;
unsigned char* imageData;
int width, height, nrChannels;
/*
This function is for loading the texture.
*/
void initTexture(const char* filename)
{
// Loading the image
imageData = stbi_load(filename, &width, &height, &nrChannels, 0);
glGenTextures(1, &uid);
glBindTexture(GL_TEXTURE_2D, uid);
if (imageData)
{
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, imageData);
glGenerateMipmap(GL_TEXTURE_2D);
std::cout << "Texture " << filename << " loaded." << std::endl;
// Free it at the end
stbi_image_free(imageData);
}
else
{
std::cout << "Error reaing texture" << std::endl;
}
}
/*
This is to bind the texture to the object.
*/
void bindTexture(const bool genMipMap = true)
{
if (genMipMap)
{
glGenerateMipmap(GL_TEXTURE_2D);
}
else
{
// these are called texture params, controls how the texture is rendered. If not
// defined the texture will not render
// MIN_FILTER = controls how the texture will look when the pixels are larger than the pixel fragments
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
// MAG_FILTER = controls how the texture will look when the pixels are smaller than the pixel fragments
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_LINEAR);
// GL_TEXTURE_WRAP_S(_AND_T) controls how the texture s/t (s = local x, t = local y texture coordinates) is smaller than the
// polygon is repeated or stretched
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
}
glBindTexture(GL_TEXTURE_2D, uid);
}
/*
This is to unbind the texture to the object.
*/
void unbindTexture()
{
glBindTexture(GL_TEXTURE_2D, 0);
}
};
Texture texture[2];
/*
This function is called before entering the main rendering loop.
Use it for all your initialisation stuff
*/
void init(GLWrapper *glw)
{
/* Set the object transformation controls to their initial values */
x = 0.05f;
y = 0;
z = 0;
angle_x = angle_y = angle_z = 0;
angle_inc_x = angle_inc_y = angle_inc_z = 0;
model_scale = 1.f;
aspect_ratio = 1.3333f;
colourmode = 0;
numlats = 60; // Number of latitudes in our sphere
numlongs = 60; // Number of longitudes in our sphere
//initTexture("images\\bark1.png");
// Generate index (name) for one vertex array object
glGenVertexArrays(1, &vao);
// Create the vertex array object and make it current
glBindVertexArray(vao);
texture[0].initTexture("images\\grass.jpg");
/* create the sphere and cube objects */
aCube.makeCube();
texture[1].initTexture("images\\earth_no_clouds_8k.jpg");
aSphere.makeSphere(numlats, numlongs);
/* Load and build the vertex and fragment shaders */
try
{
program = glw->LoadShader("lab5start.vert", "lab5start.frag");
}
catch (exception &e)
{
cout << "Caught exception: " << e.what() << endl;
cin.ignore();
exit(0);
}
/* Define uniforms to send to vertex shader */
modelID = glGetUniformLocation(program, "model");
colourmodeID = glGetUniformLocation(program, "colourmode");
viewID = glGetUniformLocation(program, "view");
projectionID = glGetUniformLocation(program, "projection");
// Enable face culling. This will cull the back faces of all
// triangles. Be careful to ensure that triangles are drawn
// with correct winding.
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
}
/* Called to update the display. Note that this function is called in the event loop in the wrapper
class because we registered display as a callback function */
void display()
{
/* Define the background colour */
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
/* Clear the colour and frame buffers */
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
/* Enable depth test */
glEnable(GL_DEPTH_TEST);
/* Make the compiled shader program current */
glUseProgram(program);
// Define the model transformations for the cube
mat4 model = mat4(1.0f);
model = translate(model, vec3(x+0.5, y, z));
model = scale(model, vec3(model_scale, model_scale, model_scale));//scale equally in all axis
model = rotate(model, -radians(angle_x), vec3(1, 0, 0)); //rotating in clockwise direction around x-axis
model = rotate(model, -radians(angle_y), vec3(0, 1, 0)); //rotating in clockwise direction around y-axis
model = rotate(model, -radians(angle_z), vec3(0, 0, 1)); //rotating in clockwise direction around z-axis
// Projection matrix : 45° Field of View, 4:3 ratio, display range : 0.1 unit <-> 100 units
mat4 projection = perspective(radians(30.0f), aspect_ratio, 0.1f, 100.0f);
// Camera matrix
mat4 view = lookAt(
vec3(0, 0, 4), // Camera is at (0,0,4), in World Space
vec3(0, 0, 0), // and looks at the origin
vec3(0, 1, 0) // Head is up (set to 0,-1,0 to look upside-down)
);
// Send our uniforms variables to the currently bound shader,
glUniformMatrix4fv(modelID, 1, GL_FALSE, &model[0][0]);
glUniform1ui(colourmodeID, colourmode);
glUniformMatrix4fv(viewID, 1, GL_FALSE, &view[0][0]);
glUniformMatrix4fv(projectionID, 1, GL_FALSE, &projection[0][0]);
/* Draw our cube*/
glFrontFace(GL_CW);
texture[0].bindTexture(mipMapEnable);
aCube.drawCube(drawmode);
texture[0].unbindTexture();
/* Define the model transformations for our sphere */
model = mat4(1.0f);
model = translate(model, vec3(-x-0.5, 0, 0));
model = scale(model, vec3(model_scale/3.f, model_scale/3.f, model_scale/3.f));//scale equally in all axis
model = rotate(model, -radians(angle_x), vec3(1, 0, 0)); //rotating in clockwise direction around x-axis
model = rotate(model, -radians(angle_y), vec3(0, 1, 0)); //rotating in clockwise direction around y-axis
model = rotate(model, -radians(angle_z), vec3(0, 0, 1)); //rotating in clockwise direction around z-axis
glUniformMatrix4fv(modelID, 1, GL_FALSE, &model[0][0]);
/* Draw our sphere */
texture[1].bindTexture(mipMapEnable);
aSphere.drawSphere(drawmode);
texture[1].unbindTexture();
glDisableVertexAttribArray(0);
glUseProgram(0);
/* Modify our animation variables */
angle_x += angle_inc_x;
angle_y += angle_inc_y;
angle_z += angle_inc_z;
}
/* Called whenever the window is resized. The new window size is given, in pixels. */
static void reshape(GLFWwindow* window, int w, int h)
{
glViewport(0, 0, (GLsizei)w, (GLsizei)h);
aspect_ratio = ((float)w / 640.f*4.f) / ((float)h / 480.f*3.f);
}
/* change view angle, exit upon ESC */
static void keyCallback(GLFWwindow* window, int key, int s, int action, int mods)
{
/* Enable this call if you want to disable key responses to a held down key*/
//if (action != GLFW_PRESS) return;
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, GL_TRUE);
if (key == 'Q') angle_inc_x -= 0.05f;
if (key == 'W') angle_inc_x += 0.05f;
if (key == 'E') angle_inc_y -= 0.05f;
if (key == 'R') angle_inc_y += 0.05f;
if (key == 'T') angle_inc_z -= 0.05f;
if (key == 'Y') angle_inc_z += 0.05f;
if (key == 'A') model_scale -= 0.02f;
if (key == 'S') model_scale += 0.02f;
if (key == 'Z') x -= 0.05f;
if (key == 'X') x += 0.05f;
if (key == 'C') y -= 0.05f;
if (key == 'V') y += 0.05f;
if (key == 'B') z -= 0.05f;
if (key == 'N') z += 0.05f;
if (key == 'M' && action != GLFW_PRESS)
{
colourmode = !colourmode;
}
// MipMap
if (key == '.' && action != GLFW_PRESS)
{
mipMapEnable = !mipMapEnable;
std::cout << "Changing mipmap to " << mipMapEnable << std::endl;
}
/* Cycle between drawing vertices, mesh and filled polygons */
if (key == ',' && action != GLFW_PRESS)
{
drawmode ++;
if (drawmode > 2) drawmode = 0;
}
}
/* Entry point of program */
int main(int argc, char* argv[])
{
GLWrapper *glw = new GLWrapper(1024, 768, "Lab5: Fun with texture");;
if (!ogl_LoadFunctions())
{
fprintf(stderr, "ogl_LoadFunctions() failed. Exiting\n");
return 0;
}
glw->setRenderer(display);
glw->setKeyCallback(keyCallback);
glw->setReshapeCallback(reshape);
init(glw);
glw->eventLoop();
delete(glw);
return 0;
}
| [
"dumitru.v.dv@gmail.com"
] | dumitru.v.dv@gmail.com |
d6200a13ef20c9378c842c849071c02df4af1da1 | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_5630113748090880_1/C++/rafaeldaigo/b.cpp | 8f9b293fb3846f79263041302c9fafb09128c410 | [] | no_license | alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417992 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 646 | cpp | #include<cstdio>
#include<cstring>
#include<queue>
#include<utility>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
int t, teste;
scanf("%d\n", &teste);
for (int t = 0; t < teste; t++)
{
int n;
int h[3000];
for (int i = 0; i <= 2500; i++)
{
h[i] = 0;
}
scanf("%d\n", &n);
for (int i = 0; i < 2 * n - 1; i++)
{
for (int j = 0; j < n; j++)
{
int a;
scanf("%d", &a);
h[a]++;
}
}
printf("Case #%d:", t + 1);
for (int i = 0; i <= 2500; i++)
{
if (h[i] & 1)
{
printf(" %d", i);
}
}
printf("\n");
}
return 0;
}
| [
"alexandra1.back@gmail.com"
] | alexandra1.back@gmail.com |
b9d0d2ffaf0676efd18d1b7dadb228b82d163513 | 21ef0be38fad85edb2259e1f2804de97da49f69a | /src/util.cpp | 49d63114f471eee19e32f3e48baf9dc87527c6eb | [
"MIT"
] | permissive | mantisnetwork/MANTISCoin | 2fa39fa170d09e534b10a9e4ed93b54a40e23110 | 9e477a70aa7c76f5650b713ef90f80c1b0221ac6 | refs/heads/master | 2023-03-13T00:20:00.370063 | 2021-03-03T09:25:05 | 2021-03-03T09:25:05 | 325,512,895 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21,459 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2020 The PIVX developers
// Copyright (c) 2020 The MANTIS Coin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include "config/MANTIScoin-config.h"
#endif
#include "util.h"
#include "allocators.h"
#include "chainparamsbase.h"
#include "random.h"
#include "sync.h"
#include "utilstrencodings.h"
#include "utiltime.h"
#include <librustzcash.h>
#include <stdarg.h>
#include <thread>
#include <boost/date_time/posix_time/posix_time.hpp>
#ifndef WIN32
// for posix_fallocate
#ifdef __linux__
#ifdef _POSIX_C_SOURCE
#undef _POSIX_C_SOURCE
#endif
#define _POSIX_C_SOURCE 200112L
#endif // __linux__
#include <algorithm>
#include <fcntl.h>
#include <sys/resource.h>
#include <sys/stat.h>
#else
#ifdef _MSC_VER
#pragma warning(disable : 4786)
#pragma warning(disable : 4804)
#pragma warning(disable : 4805)
#pragma warning(disable : 4717)
#endif
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0501
#ifdef _WIN32_IE
#undef _WIN32_IE
#endif
#define _WIN32_IE 0x0501
#define WIN32_LEAN_AND_MEAN 1
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <io.h> /* for _commit */
#include <shlobj.h>
#endif
#ifdef HAVE_SYS_PRCTL_H
#include <sys/prctl.h>
#endif
#include <boost/algorithm/string/case_conv.hpp> // for to_lower()
#include <boost/algorithm/string/join.hpp>
#include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith()
#include <boost/program_options/detail/config_file.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/thread.hpp>
#include <openssl/conf.h>
#include <openssl/crypto.h>
#include <openssl/rand.h>
const char * const MANTISCoin_CONF_FILENAME = "MANTIScoin.conf";
const char * const MANTISCoin_PID_FILENAME = "MANTIScoin.pid";
const char * const MANTISCoin_MASTERNODE_CONF_FILENAME = "masternode.conf";
// MANTISCoin only features
// Masternode
bool fMasterNode = false;
std::string strMasterNodePrivKey = "";
std::string strMasterNodeAddr = "";
bool fLiteMode = false;
// SwiftX
bool fEnableSwiftTX = true;
int nSwiftTXDepth = 5;
/** Spork enforcement enabled time */
int64_t enforceMasternodePaymentsTime = 4085657524;
bool fSucessfullyLoaded = false;
std::string strBudgetMode = "";
std::map<std::string, std::string> mapArgs;
std::map<std::string, std::vector<std::string> > mapMultiArgs;
bool fDaemon = false;
std::string strMiscWarning;
/** Init OpenSSL library multithreading support */
static RecursiveMutex** ppmutexOpenSSL;
void locking_callback(int mode, int i, const char* file, int line) NO_THREAD_SAFETY_ANALYSIS
{
if (mode & CRYPTO_LOCK) {
ENTER_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
} else {
LEAVE_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
}
}
// Init
class CInit
{
public:
CInit()
{
// Init OpenSSL library multithreading support
ppmutexOpenSSL = (RecursiveMutex**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(RecursiveMutex*));
for (int i = 0; i < CRYPTO_num_locks(); i++)
ppmutexOpenSSL[i] = new RecursiveMutex();
CRYPTO_set_locking_callback(locking_callback);
// OpenSSL can optionally load a config file which lists optional loadable modules and engines.
// We don't use them so we don't require the config. However some of our libs may call functions
// which attempt to load the config file, possibly resulting in an exit() or crash if it is missing
// or corrupt. Explicitly tell OpenSSL not to try to load the file. The result for our libs will be
// that the config appears to have been loaded and there are no modules/engines available.
OPENSSL_no_config();
#ifdef WIN32
// Seed OpenSSL PRNG with current contents of the screen
RAND_screen();
#endif
// Seed OpenSSL PRNG with performance counter
RandAddSeed();
}
~CInit()
{
// Securely erase the memory used by the PRNG
RAND_cleanup();
// Shutdown OpenSSL library multithreading support
CRYPTO_set_locking_callback(NULL);
for (int i = 0; i < CRYPTO_num_locks(); i++)
delete ppmutexOpenSSL[i];
OPENSSL_free(ppmutexOpenSSL);
}
} instance_of_cinit;
/** Interpret string as boolean, for argument parsing */
static bool InterpretBool(const std::string& strValue)
{
if (strValue.empty())
return true;
return (atoi(strValue) != 0);
}
/** Turn -noX into -X=0 */
static void InterpretNegativeSetting(std::string& strKey, std::string& strValue)
{
if (strKey.length()>3 && strKey[0]=='-' && strKey[1]=='n' && strKey[2]=='o') {
strKey = "-" + strKey.substr(3);
strValue = InterpretBool(strValue) ? "0" : "1";
}
}
void ParseParameters(int argc, const char* const argv[])
{
mapArgs.clear();
mapMultiArgs.clear();
for (int i = 1; i < argc; i++) {
std::string str(argv[i]);
std::string strValue;
size_t is_index = str.find('=');
if (is_index != std::string::npos) {
strValue = str.substr(is_index + 1);
str = str.substr(0, is_index);
}
#ifdef WIN32
boost::to_lower(str);
if (boost::algorithm::starts_with(str, "/"))
str = "-" + str.substr(1);
#endif
if (str[0] != '-')
break;
// Interpret --foo as -foo.
// If both --foo and -foo are set, the last takes effect.
if (str.length() > 1 && str[1] == '-')
str = str.substr(1);
InterpretNegativeSetting(str, strValue);
mapArgs[str] = strValue;
mapMultiArgs[str].push_back(strValue);
}
}
std::string GetArg(const std::string& strArg, const std::string& strDefault)
{
if (mapArgs.count(strArg))
return mapArgs[strArg];
return strDefault;
}
int64_t GetArg(const std::string& strArg, int64_t nDefault)
{
if (mapArgs.count(strArg))
return atoi64(mapArgs[strArg]);
return nDefault;
}
bool GetBoolArg(const std::string& strArg, bool fDefault)
{
if (mapArgs.count(strArg))
return InterpretBool(mapArgs[strArg]);
return fDefault;
}
bool SoftSetArg(const std::string& strArg, const std::string& strValue)
{
if (mapArgs.count(strArg))
return false;
mapArgs[strArg] = strValue;
return true;
}
bool SoftSetBoolArg(const std::string& strArg, bool fValue)
{
if (fValue)
return SoftSetArg(strArg, std::string("1"));
else
return SoftSetArg(strArg, std::string("0"));
}
static const int screenWidth = 79;
static const int optIndent = 2;
static const int msgIndent = 7;
std::string HelpMessageGroup(const std::string &message) {
return std::string(message) + std::string("\n\n");
}
std::string HelpMessageOpt(const std::string &option, const std::string &message) {
return std::string(optIndent,' ') + std::string(option) +
std::string("\n") + std::string(msgIndent,' ') +
FormatParagraph(message, screenWidth - msgIndent, msgIndent) +
std::string("\n\n");
}
static std::string FormatException(const std::exception* pex, const char* pszThread)
{
#ifdef WIN32
char pszModule[MAX_PATH] = "";
GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
#else
const char* pszModule = "MANTIScoin";
#endif
if (pex)
return strprintf(
"EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
else
return strprintf(
"UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
}
void PrintExceptionContinue(const std::exception* pex, const char* pszThread)
{
std::string message = FormatException(pex, pszThread);
LogPrintf("\n\n************************\n%s\n", message);
fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
strMiscWarning = message;
}
fs::path GetDefaultDataDir()
{
// Windows < Vista: C:\Documents and Settings\Username\Application Data\MANTISCoin
// Windows >= Vista: C:\Users\Username\AppData\Roaming\MANTISCoin
// Mac: ~/Library/Application Support/MANTISCoin
// Unix: ~/.MANTIScoin
#ifdef WIN32
// Windows
return GetSpecialFolderPath(CSIDL_APPDATA) / "MANTISCoin";
#else
fs::path pathRet;
char* pszHome = getenv("HOME");
if (pszHome == NULL || strlen(pszHome) == 0)
pathRet = fs::path("/");
else
pathRet = fs::path(pszHome);
#ifdef MAC_OSX
// Mac
pathRet /= "Library/Application Support";
TryCreateDirectory(pathRet);
return pathRet / "MANTISCoin";
#else
// Unix
return pathRet / ".MANTISCoin";
#endif
#endif
}
static fs::path pathCached;
static fs::path pathCachedNetSpecific;
static fs::path zc_paramsPathCached;
static RecursiveMutex csPathCached;
static fs::path ZC_GetBaseParamsDir()
{
// Copied from GetDefaultDataDir and adapter for zcash params.
// Windows < Vista: C:\Documents and Settings\Username\Application Data\MANTISCoinParams
// Windows >= Vista: C:\Users\Username\AppData\Roaming\MANTISCoinParams
// Mac: ~/Library/Application Support/MANTISCoinParams
// Unix: ~/.MANTIScoin-params
#ifdef WIN32
// Windows
return GetSpecialFolderPath(CSIDL_APPDATA) / "MANTISCoinParams";
#else
fs::path pathRet;
char* pszHome = getenv("HOME");
if (pszHome == NULL || strlen(pszHome) == 0)
pathRet = fs::path("/");
else
pathRet = fs::path(pszHome);
#ifdef MAC_OSX
// Mac
pathRet /= "Library/Application Support";
TryCreateDirectory(pathRet);
return pathRet / "MANTISCoinParams";
#else
// Unix
return pathRet / ".MANTIScoin-params";
#endif
#endif
}
const fs::path &ZC_GetParamsDir()
{
LOCK(csPathCached); // Reuse the same lock as upstream.
fs::path &path = zc_paramsPathCached;
// This can be called during exceptions by LogPrintf(), so we cache the
// value so we don't have to do memory allocations after that.
if (!path.empty())
return path;
#ifdef USE_CUSTOM_PARAMS
path = fs::system_complete(PARAMS_DIR);
#else
if (mapArgs.count("-paramsdir")) {
path = fs::system_complete(mapArgs["-paramsdir"]);
if (!fs::is_directory(path)) {
path = "";
return path;
}
} else {
path = ZC_GetBaseParamsDir();
}
#endif
return path;
}
void initZKSNARKS()
{
const fs::path& path = ZC_GetParamsDir();
fs::path sapling_spend = path / "sapling-spend.params";
fs::path sapling_output = path / "sapling-output.params";
fs::path sprout_groth16 = path / "sprout-groth16.params";
if (!(fs::exists(sapling_spend) &&
fs::exists(sapling_output) &&
fs::exists(sprout_groth16)
)) {
throw std::runtime_error("Sapling params don't exist");
}
static_assert(
sizeof(fs::path::value_type) == sizeof(codeunit),
"librustzcash not configured correctly");
auto sapling_spend_str = sapling_spend.native();
auto sapling_output_str = sapling_output.native();
auto sprout_groth16_str = sprout_groth16.native();
//LogPrintf("Loading Sapling (Spend) parameters from %s\n", sapling_spend.string().c_str());
librustzcash_init_zksnark_params(
reinterpret_cast<const codeunit*>(sapling_spend_str.c_str()),
sapling_spend_str.length(),
"8270785a1a0d0bc77196f000ee6d221c9c9894f55307bd9357c3f0105d31ca63991ab91324160d8f53e2bbd3c2633a6eb8bdf5205d822e7f3f73edac51b2b70c",
reinterpret_cast<const codeunit*>(sapling_output_str.c_str()),
sapling_output_str.length(),
"657e3d38dbb5cb5e7dd2970e8b03d69b4787dd907285b5a7f0790dcc8072f60bf593b32cc2d1c030e00ff5ae64bf84c5c3beb84ddc841d48264b4a171744d028",
reinterpret_cast<const codeunit*>(sprout_groth16_str.c_str()),
sprout_groth16_str.length(),
"e9b238411bd6c0ec4791e9d04245ec350c9c5744f5610dfcce4365d5ca49dfefd5054e371842b3f88fa1b9d7e8e075249b3ebabd167fa8b0f3161292d36c180a"
);
//std::cout << "### Sapling params initialized ###" << std::endl;
}
const fs::path& GetDataDir(bool fNetSpecific)
{
LOCK(csPathCached);
fs::path& path = fNetSpecific ? pathCachedNetSpecific : pathCached;
// This can be called during exceptions by LogPrintf(), so we cache the
// value so we don't have to do memory allocations after that.
if (!path.empty())
return path;
if (mapArgs.count("-datadir")) {
path = fs::system_complete(mapArgs["-datadir"]);
if (!fs::is_directory(path)) {
path = "";
return path;
}
} else {
path = GetDefaultDataDir();
}
if (fNetSpecific)
path /= BaseParams().DataDir();
fs::create_directories(path);
return path;
}
void ClearDatadirCache()
{
pathCached = fs::path();
pathCachedNetSpecific = fs::path();
}
fs::path GetConfigFile()
{
fs::path pathConfigFile(GetArg("-conf", MANTISCoin_CONF_FILENAME));
return AbsPathForConfigVal(pathConfigFile, false);
}
fs::path GetMasternodeConfigFile()
{
fs::path pathConfigFile(GetArg("-mnconf", MANTISCoin_MASTERNODE_CONF_FILENAME));
return AbsPathForConfigVal(pathConfigFile);
}
void ReadConfigFile(std::map<std::string, std::string>& mapSettingsRet,
std::map<std::string, std::vector<std::string> >& mapMultiSettingsRet)
{
fs::ifstream streamConfig(GetConfigFile());
if (!streamConfig.good()) {
// Create empty MANTIScoin.conf if it does not exist
FILE* configFile = fsbridge::fopen(GetConfigFile(), "a");
if (configFile != NULL)
fclose(configFile);
return; // Nothing to read, so just return
}
std::set<std::string> setOptions;
setOptions.insert("*");
for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it) {
// Don't overwrite existing settings so command line settings override MANTIScoin.conf
std::string strKey = std::string("-") + it->string_key;
std::string strValue = it->value[0];
InterpretNegativeSetting(strKey, strValue);
if (mapSettingsRet.count(strKey) == 0)
mapSettingsRet[strKey] = strValue;
mapMultiSettingsRet[strKey].push_back(strValue);
}
// If datadir is changed in .conf file:
ClearDatadirCache();
}
fs::path AbsPathForConfigVal(const fs::path& path, bool net_specific)
{
if (path.is_absolute()) {
return path;
}
return fs::absolute(path, GetDataDir(net_specific));
}
#ifndef WIN32
fs::path GetPidFile()
{
fs::path pathPidFile(GetArg("-pid", MANTISCoin_PID_FILENAME));
return AbsPathForConfigVal(pathPidFile);
}
void CreatePidFile(const fs::path& path, pid_t pid)
{
FILE* file = fsbridge::fopen(path, "w");
if (file) {
fprintf(file, "%d\n", pid);
fclose(file);
}
}
#endif
bool RenameOver(fs::path src, fs::path dest)
{
#ifdef WIN32
return MoveFileExA(src.string().c_str(), dest.string().c_str(),
MOVEFILE_REPLACE_EXISTING) != 0;
#else
int rc = std::rename(src.string().c_str(), dest.string().c_str());
return (rc == 0);
#endif /* WIN32 */
}
/**
* Ignores exceptions thrown by Boost's create_directory if the requested directory exists.
* Specifically handles case where path p exists, but it wasn't possible for the user to
* write to the parent directory.
*/
bool TryCreateDirectory(const fs::path& p)
{
try {
return fs::create_directory(p);
} catch (const fs::filesystem_error&) {
if (!fs::exists(p) || !fs::is_directory(p))
throw;
}
// create_directory didn't create the directory, it had to have existed already
return false;
}
void FileCommit(FILE* fileout)
{
fflush(fileout); // harmless if redundantly called
#ifdef WIN32
HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(fileout));
FlushFileBuffers(hFile);
#else
#if defined(__linux__) || defined(__NetBSD__)
fdatasync(fileno(fileout));
#elif defined(__APPLE__) && defined(F_FULLFSYNC)
fcntl(fileno(fileout), F_FULLFSYNC, 0);
#else
fsync(fileno(fileout));
#endif
#endif
}
bool TruncateFile(FILE* file, unsigned int length)
{
#if defined(WIN32)
return _chsize(_fileno(file), length) == 0;
#else
return ftruncate(fileno(file), length) == 0;
#endif
}
/**
* this function tries to raise the file descriptor limit to the requested number.
* It returns the actual file descriptor limit (which may be more or less than nMinFD)
*/
int RaiseFileDescriptorLimit(int nMinFD)
{
#if defined(WIN32)
return 2048;
#else
struct rlimit limitFD;
if (getrlimit(RLIMIT_NOFILE, &limitFD) != -1) {
if (limitFD.rlim_cur < (rlim_t)nMinFD) {
limitFD.rlim_cur = nMinFD;
if (limitFD.rlim_cur > limitFD.rlim_max)
limitFD.rlim_cur = limitFD.rlim_max;
setrlimit(RLIMIT_NOFILE, &limitFD);
getrlimit(RLIMIT_NOFILE, &limitFD);
}
return limitFD.rlim_cur;
}
return nMinFD; // getrlimit failed, assume it's fine
#endif
}
/**
* this function tries to make a particular range of a file allocated (corresponding to disk space)
* it is advisory, and the range specified in the arguments will never contain live data
*/
void AllocateFileRange(FILE* file, unsigned int offset, unsigned int length)
{
#if defined(WIN32)
// Windows-specific version
HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
LARGE_INTEGER nFileSize;
int64_t nEndPos = (int64_t)offset + length;
nFileSize.u.LowPart = nEndPos & 0xFFFFFFFF;
nFileSize.u.HighPart = nEndPos >> 32;
SetFilePointerEx(hFile, nFileSize, 0, FILE_BEGIN);
SetEndOfFile(hFile);
#elif defined(MAC_OSX)
// OSX specific version
fstore_t fst;
fst.fst_flags = F_ALLOCATECONTIG;
fst.fst_posmode = F_PEOFPOSMODE;
fst.fst_offset = 0;
fst.fst_length = (off_t)offset + length;
fst.fst_bytesalloc = 0;
if (fcntl(fileno(file), F_PREALLOCATE, &fst) == -1) {
fst.fst_flags = F_ALLOCATEALL;
fcntl(fileno(file), F_PREALLOCATE, &fst);
}
ftruncate(fileno(file), fst.fst_length);
#elif defined(__linux__)
// Version using posix_fallocate
off_t nEndPos = (off_t)offset + length;
posix_fallocate(fileno(file), 0, nEndPos);
#else
// Fallback version
// TODO: just write one byte per block
static const char buf[65536] = {};
fseek(file, offset, SEEK_SET);
while (length > 0) {
unsigned int now = 65536;
if (length < now)
now = length;
fwrite(buf, 1, now, file); // allowed to fail; this function is advisory anyway
length -= now;
}
#endif
}
#ifdef WIN32
fs::path GetSpecialFolderPath(int nFolder, bool fCreate)
{
char pszPath[MAX_PATH] = "";
if (SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate)) {
return fs::path(pszPath);
}
LogPrintf("SHGetSpecialFolderPathA() failed, could not obtain requested path.\n");
return fs::path("");
}
#endif
fs::path GetTempPath()
{
return fs::temp_directory_path();
}
double double_safe_addition(double fValue, double fIncrement)
{
double fLimit = std::numeric_limits<double>::max() - fValue;
if (fLimit > fIncrement)
return fValue + fIncrement;
else
return std::numeric_limits<double>::max();
}
double double_safe_multiplication(double fValue, double fmultiplicator)
{
double fLimit = std::numeric_limits<double>::max() / fmultiplicator;
if (fLimit > fmultiplicator)
return fValue * fmultiplicator;
else
return std::numeric_limits<double>::max();
}
void runCommand(std::string strCommand)
{
int nErr = ::system(strCommand.c_str());
if (nErr)
LogPrintf("runCommand error: system(%s) returned %d\n", strCommand, nErr);
}
void SetupEnvironment()
{
// On most POSIX systems (e.g. Linux, but not BSD) the environment's locale
// may be invalid, in which case the "C" locale is used as fallback.
#if !defined(WIN32) && !defined(MAC_OSX) && !defined(__FreeBSD__) && !defined(__OpenBSD__)
try {
std::locale(""); // Raises a runtime error if current locale is invalid
} catch (const std::runtime_error&) {
setenv("LC_ALL", "C", 1);
}
#endif
// The path locale is lazy initialized and to avoid deinitialization errors
// in multithreading environments, it is set explicitly by the main thread.
// A dummy locale is used to extract the internal default locale, used by
// fs::path, which is then used to explicitly imbue the path.
std::locale loc = fs::path::imbue(std::locale::classic());
fs::path::imbue(loc);
}
bool SetupNetworking()
{
#ifdef WIN32
// Initialize Windows Sockets
WSADATA wsadata;
int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
if (ret != NO_ERROR || LOBYTE(wsadata.wVersion ) != 2 || HIBYTE(wsadata.wVersion) != 2)
return false;
#endif
return true;
}
void SetThreadPriority(int nPriority)
{
#ifdef WIN32
SetThreadPriority(GetCurrentThread(), nPriority);
#else // WIN32
#ifdef PRIO_THREAD
setpriority(PRIO_THREAD, 0, nPriority);
#else // PRIO_THREAD
setpriority(PRIO_PROCESS, 0, nPriority);
#endif // PRIO_THREAD
#endif // WIN32
}
int GetNumCores()
{
return std::thread::hardware_concurrency();
}
| [
"75368675+mantisnetwork@users.noreply.github.com"
] | 75368675+mantisnetwork@users.noreply.github.com |
6fbc9f053393a47833ac9521bc34fb917c4c6b1f | 3cdc447ffbd23ed88061a2df7b047a1d5500cdb1 | /Baked Rendering/wraptobaketexture.h | e535c69abd4aab70787f9267f9a417b4662a5116 | [
"CC0-1.0"
] | permissive | Eremiell/Ludum-Dare-42 | a441645b6cac852eb7a77ac3846bb5c84b29d893 | 73d42afe4ae596f5469e20de70c5c18cf494b130 | refs/heads/master | 2020-03-26T08:35:46.884870 | 2018-08-14T02:06:38 | 2018-08-14T02:06:38 | 144,710,288 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 336 | h | #include <Core/Core.h>
#include <Mesh/Mesh.h>
#include <vector>
namespace LDEngine {
namespace Rendering {
namespace Mesh {
struct LightMapData {
std::vector<Vector3f> Vertices, Normals, Tangents, TexCoords, TriangleID, Colors;
};
LightMapData ProjectToBakeTexture(Model & ModelData, unsigned int Resolution);
}
}
} | [
"UglySwedishFish"
] | UglySwedishFish |
817e5a2e15612c186fbcf9ffa79ba6faf8d64e70 | aa7e69f850c322ad981952648eb8d8d9c5e09cc8 | /Peripheral Code/ESP32 Code/BTTest.ino/BTTest.ino.ino | de9c1fba41724c6c24e8a6d453011179b1e8c8be | [] | no_license | raymondhcyu/CyclingDAQ | dce73f6a68ed219064fbb08c3977c47f0c1531c5 | 9dba0f7474b0af8a2c9dde112029239572134e32 | refs/heads/master | 2020-09-11T22:01:29.854683 | 2019-12-09T03:14:09 | 2019-12-09T03:14:09 | 222,202,771 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,195 | ino | //This example code is in the Public Domain (or CC0 licensed, at your option.)
//By Evandro Copercini - 2018
//
//This example creates a bridge between Serial and Classical Bluetooth (SPP)
//and also demonstrate that SerialBT have the same functionalities of a normal Serial
#include "BluetoothSerial.h"
#include "WiFi.h"
#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif
BluetoothSerial SerialBT;
String inMessage = "";
byte buff[] = {255, 50, 100, 150, 200, 50, 100, 150}; // 8 byte message format
void setup() {
Serial.begin(115200);
SerialBT.begin("The_Best_ESP32"); //Bluetooth device name
Serial.println("The device started, now you can pair it with bluetooth!");
WiFi.mode(WIFI_MODE_STA);
Serial.print("MAC address is this - ");
Serial.println(WiFi.macAddress());
}
void loop() {
if (SerialBT.available()) {
char incomingChar = SerialBT.read();
if (incomingChar != '\n') {
inMessage += String(incomingChar);
}
else
inMessage = "";
}
if (inMessage == "Hello") {
Serial.println("Received hello!");
SerialBT.println("Bye!");
}
int j = 0; // counter to change buffer data for testing
if (inMessage == "Send me data") {
while (j < 50) {
// SerialBT.write() sends bytes
Serial.print("Ok sending back data! ");
SerialBT.write(buff[0]);
Serial.print(buff[0]);
SerialBT.write(buff[1] + j);
Serial.print(buff[1] + j);
SerialBT.write(buff[2] + j);
Serial.print(buff[2] + j);
SerialBT.write(buff[3] + j);
Serial.print(buff[3] + j);
SerialBT.write(buff[4] + j);
Serial.print(buff[4] + j);
SerialBT.write(buff[5] + j);
Serial.print(buff[5] + j);
SerialBT.write(buff[6] + j);
Serial.print(buff[6] + j);
SerialBT.write(buff[7] + j);
Serial.print(buff[7] + j);
j++;
delay(100);
}
// for (int i = 0; i < sizeof(buff); i++) {
// if (buff[i] = 0) {
// SerialBT.write(buff[i]);
// }
// else {
// SerialBT.write(buff[i] + j);
// }
// }
}
}
| [
"yuraymond96@gmail.com"
] | yuraymond96@gmail.com |
3e3e1378502f9acf8c039b11649157b696eac49b | 86ab71b59966162cd28d9aaee43a516a768a7298 | /main.cpp | 811d60e78c20efcb5bf899bcfba4638f0690d403 | [] | no_license | bugoodby/linediff | 8119030487b01146e46be5f8ef14921720a23356 | f1903b5a57db285e55fd9bc9e2ddf5fa6a015ddf | refs/heads/master | 2016-09-16T13:03:19.978597 | 2014-07-02T10:28:00 | 2014-07-02T10:28:00 | null | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 3,475 | cpp | // getverinfo.cpp : コンソール アプリケーション用のエントリ ポイントの定義
//
#include "stdafx.h"
#include "main.h"
void usage(void);
bool parse_cmdline( int argc, wchar_t **argv, OPTION &opt );
//--------------------------------------------------------------
// main
//--------------------------------------------------------------
int _tmain(int argc, _TCHAR* argv[])
{
OPTION opt = {0};
int retval = 0;
FILE *console = stderr;
FILE *infp1 = stdin;
FILE *infp2 = stdin;
FILE *outfp = stdout;
setlocale(LC_CTYPE, "japanese");
/* parse */
if ( !parse_cmdline(argc, argv, opt) ) {
goto EXIT;
}
if ( opt.num < 2 ) {
fwprintf(console, L"too few arguments.\n");
}
else {
wchar_t *infile1 = opt.argv[0];
wchar_t *infile2 = opt.argv[1];
/* open files */
infp1 = _wfopen(infile1, L"r");
if ( !infp1 ) {
fwprintf(console, L"[ERROR] cannot open %s.\n", infile1);
GET_ERROR_VAL(retval);
}
infp2 = _wfopen(infile2, L"r");
if ( !infp2 ) {
fwprintf(console, L"[ERROR] cannot open %s.\n", infile2);
GET_ERROR_VAL(retval);
}
/* main */
if ( infp1 && infp2 && outfp ) {
retval = linediff( infp1, infp2, outfp, opt );
if ( retval < 0 ) {
fwprintf(console, L"[ERROR] fail in main routine.\n");
}
}
}
if ( opt.wait_key_input ) {
fputws(L"--- press any key ---\n", outfp);
getwc(stdin);
}
EXIT:
/* close files */
if ( infp1 ) {
fclose(infp1);
}
if ( infp2 ) {
fclose(infp2);
}
return retval;
}
//--------------------------------------------------------------
// show usage
//--------------------------------------------------------------
void usage(void)
{
fwprintf(stderr, L"[ %s Version %s ]\n", MODULENAME_STRING, VERSION_STRING);
fwprintf(stderr, L"compare 2 files.\n");
fwprintf(stderr, L"\n");
fwprintf(stderr, L"Usage : %s [option...] <input file1> <input file2>\n", MODULENAME_STRING);
fwprintf(stderr, L" -b <integer> : set line buffer size (default: 1024)\n");
fwprintf(stderr, L" -c : do not wait a key input\n");
fwprintf(stderr, L" -o <type> : specify output format\n");
fwprintf(stderr, L" <type> = \"csv\" \n");
fwprintf(stderr, L" -s : sort lines\n");
fwprintf(stderr, L" <infput file> : input file path\n");
}
//--------------------------------------------------------------
// parse command line
//--------------------------------------------------------------
bool parse_cmdline( int argc, wchar_t **argv, OPTION &opt )
{
bool ret = true;
wchar_t *s = NULL;
int iSize = 0;
/* initialize */
opt.buffer_size = 1024;
opt.wait_key_input = true;
opt.out_type = TYPE_DEFAULT;
opt.sort = false;
/* parse */
while ( --argc > 0 ) {
s = *++argv;
if ( *s == L'-' || *s == L'/' ) {
switch ( *++s )
{
case L'h':
case L'?':
usage();
ret = false;
break;
case L'b':
if ( --argc > 0 ) {
iSize = _wtol(*++argv);
if ( iSize > 0 ) opt.buffer_size = iSize;
}
break;
case L'c':
opt.wait_key_input = false;
break;
case L'o':
if ( --argc > 0 ) {
++argv;
if ( wcscmp(*argv, L"csv") == 0 ) {
opt.out_type = TYPE_CSV;
}
}
break;
case L's':
opt.sort = true;
break;
default:
fwprintf(stderr, L"Unknown parameter : -%s\n", s);
ret = false;
break;
}
}
else {
opt.num = argc;
opt.argv = argv;
break;
}
}
return ret;
}
| [
"bugoodby@gmail.com"
] | bugoodby@gmail.com |
1650de703921a679926a565517b720a042b1b47c | ea401c3e792a50364fe11f7cea0f35f99e8f4bde | /released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/gui/flyem/zintcuboidcomposition.h | 2092e6dc81fc6c715cb19eb16b163340a91fbf11 | [
"GPL-1.0-or-later",
"LicenseRef-scancode-unknown-license-reference",
"GPL-2.0-only",
"BSD-2-Clause",
"MIT"
] | permissive | Vaa3D/vaa3d_tools | edb696aa3b9b59acaf83d6d27c6ae0a14bf75fe9 | e6974d5223ae70474efaa85e1253f5df1814fae8 | refs/heads/master | 2023-08-03T06:12:01.013752 | 2023-08-02T07:26:01 | 2023-08-02T07:26:01 | 50,527,925 | 107 | 86 | MIT | 2023-05-22T23:43:48 | 2016-01-27T18:19:17 | C++ | UTF-8 | C++ | false | false | 906 | h | #ifndef ZINTCUBOIDCOMPOSITION_H
#define ZINTCUBOIDCOMPOSITION_H
#include "tz_cuboid_i.h"
#include <utility>
#ifdef __GLIBCXX__
#include <tr1/memory>
#else
#include <memory>
#endif
namespace FlyEm {
class ZIntCuboidComposition
{
public:
ZIntCuboidComposition();
enum EOperator {
AND, OR, XOR, SINGULAR
};
bool hitTestF(double x, double y, double z);
bool hitTest(int x, int y, int z);
void setComposition(std::tr1::shared_ptr<ZIntCuboidComposition> firstComponent,
std::tr1::shared_ptr<ZIntCuboidComposition> secondComponent,
EOperator opr);
void setSingular(int x, int y, int z, int width, int height, int depth);
private:
std::tr1::shared_ptr<ZIntCuboidComposition> m_firstComponent;
std::tr1::shared_ptr<ZIntCuboidComposition> m_secondComponent;
Cuboid_I m_cuboid;
EOperator m_operator;
};
}
#endif // ZINTCUBOIDCOMPOSITION_H
| [
"hanchuan.peng@gmail.com"
] | hanchuan.peng@gmail.com |
f01427abc9272c5c2f3fa3931d6149dc4395194a | 2362d3900d20141e854fc30a8001e6f8e3ef9ba3 | /rodos/rodos-tutorials/middleware_distributed/sender14.cpp | 6f7e5f305cdb18a5b574b2d5b5a4741200a8be21 | [] | no_license | art1/FloatSat-Project-G9 | b083b3081d708dc3ef1f11070504b535bf13ef38 | 6c45b4532e505e6e1c82e283ab3c898cccf0b508 | refs/heads/master | 2020-12-26T00:51:38.039821 | 2016-02-24T20:45:56 | 2016-02-24T20:45:56 | 44,930,461 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 435 | cpp | #include "rodos.h"
#include "demo_topics.h"
#include "mask.h"
/******************************/
static Application senderName("Publisher 14", 2014);
class MyPublisher14 : public Thread {
public:
MyPublisher14() : Thread("sender14") { }
void run () {
long cnt = 0;
TIME_LOOP(0, 1900*MILLISECONDS) {
PRINTF("%s%ld", S14, ++cnt);
counter4.publish(cnt);
}
}
} myPublisher14;
| [
"asscience22@gmail.com"
] | asscience22@gmail.com |
e6b8070a31f8cd3674a617b3b1fe447ae58f58ff | da3c59e9e54b5974648828ec76f0333728fa4f0c | /mobilemessaging/smilui/playersrc/SmilPlayerPanic.cpp | 2ef9a7e749056019f356f57a6396a781f4a53b27 | [] | no_license | finding-out/oss.FCL.sf.app.messaging | 552a95b08cbff735d7f347a1e6af69fc427f91e8 | 7ecf4269c53f5b2c6a47f3596e77e2bb75c1700c | refs/heads/master | 2022-01-29T12:14:56.118254 | 2010-11-03T20:32:03 | 2010-11-03T20:32:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,039 | cpp | /*
* Copyright (c) 2003-2005 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description: SmilPlayerPanic implementation
*
*/
// ========== INCLUDE FILES ================================
#include <e32std.h>
#include "SmilPlayerPanic.h"
// ========== FUNCTION PROTOTYPES ==========================
// ---------------------------------------------------------
// Panic implements
// panic handling for SmilPlayer
// Returns: nothing
// ---------------------------------------------------------
//
GLDEF_C void Panic( TSmilPlayerDialogPanic aPanic) // enum for panic codes
{
_LIT( KSmilPlayerPanic, "SmilPlayer" );
User::Panic( KSmilPlayerPanic, aPanic );
}
// End of File
| [
"none@none"
] | none@none |
636570e562088128a9a88b19ce170d581373ba10 | ad2a94df7070d6c5155596ff4fad73976f18c185 | /src/miner.cpp | bfdc1064f4101d820a77072560794d50e5752bea | [
"MIT"
] | permissive | bee7/grain | d90fe15752110b58db8036350fc5ee4e2b84587a | d2c75e033e7a52a584b2fe89f66e162f13ef1192 | refs/heads/master | 2020-12-03T09:26:25.709535 | 2014-06-02T16:17:10 | 2014-06-02T16:17:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21,582 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2013 The NovaCoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "txdb.h"
#include "miner.h"
#include "kernel.h"
using namespace std;
//////////////////////////////////////////////////////////////////////////////
//
// BitcoinMiner
//
string strMintMessage = "Info: Minting suspended due to locked wallet.";
string strMintWarning;
int static FormatHashBlocks(void* pbuffer, unsigned int len)
{
unsigned char* pdata = (unsigned char*)pbuffer;
unsigned int blocks = 1 + ((len + 8) / 64);
unsigned char* pend = pdata + 64 * blocks;
memset(pdata + len, 0, 64 * blocks - len);
pdata[len] = 0x80;
unsigned int bits = len * 8;
pend[-1] = (bits >> 0) & 0xff;
pend[-2] = (bits >> 8) & 0xff;
pend[-3] = (bits >> 16) & 0xff;
pend[-4] = (bits >> 24) & 0xff;
return blocks;
}
static const unsigned int pSHA256InitState[8] =
{0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
void SHA256Transform(void* pstate, void* pinput, const void* pinit)
{
SHA256_CTX ctx;
unsigned char data[64];
SHA256_Init(&ctx);
for (int i = 0; i < 16; i++)
((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
for (int i = 0; i < 8; i++)
ctx.h[i] = ((uint32_t*)pinit)[i];
SHA256_Update(&ctx, data, sizeof(data));
for (int i = 0; i < 8; i++)
((uint32_t*)pstate)[i] = ctx.h[i];
}
// Some explaining would be appreciated
class COrphan
{
public:
CTransaction* ptx;
set<uint256> setDependsOn;
double dPriority;
double dFeePerKb;
COrphan(CTransaction* ptxIn)
{
ptx = ptxIn;
dPriority = dFeePerKb = 0;
}
void print() const
{
printf("COrphan(hash=%s, dPriority=%.1f, dFeePerKb=%.1f)\n",
ptx->GetHash().ToString().substr(0,10).c_str(), dPriority, dFeePerKb);
BOOST_FOREACH(uint256 hash, setDependsOn)
printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
}
};
uint64 nLastBlockTx = 0;
uint64 nLastBlockSize = 0;
int64 nLastCoinStakeSearchInterval = 0;
// We want to sort transactions by priority and fee, so:
typedef boost::tuple<double, double, CTransaction*> TxPriority;
class TxPriorityCompare
{
bool byFee;
public:
TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
bool operator()(const TxPriority& a, const TxPriority& b)
{
if (byFee)
{
if (a.get<1>() == b.get<1>())
return a.get<0>() < b.get<0>();
return a.get<1>() < b.get<1>();
}
else
{
if (a.get<0>() == b.get<0>())
return a.get<1>() < b.get<1>();
return a.get<0>() < b.get<0>();
}
}
};
// CreateNewBlock:
// fProofOfStake: try (best effort) to make a proof-of-stake block
CBlock* CreateNewBlock(CWallet* pwallet, bool fProofOfStake)
{
// Create new block
auto_ptr<CBlock> pblock(new CBlock());
if (!pblock.get())
return NULL;
// Create coinbase tx
CTransaction txNew;
txNew.vin.resize(1);
txNew.vin[0].prevout.SetNull();
txNew.vout.resize(1);
if (!fProofOfStake)
{
CReserveKey reservekey(pwallet);
txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
}
else
txNew.vout[0].SetEmpty();
// Add our coinbase tx as first transaction
pblock->vtx.push_back(txNew);
// Largest block you're willing to create:
unsigned int nBlockMaxSize = GetArg("-blockmaxsize", MAX_BLOCK_SIZE_GEN/2);
// Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));
// How much of the block should be dedicated to high-priority transactions,
// included regardless of the fees they pay
unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", 27000);
nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
// Minimum block size you want to create; block will be filled with free transactions
// until there are no more or the block reaches this size:
unsigned int nBlockMinSize = GetArg("-blockminsize", 0);
nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
// Fee-per-kilobyte amount considered the same as "free"
// Be careful setting this: if you set it to zero then
// a transaction spammer can cheaply fill blocks using
// 1-satoshi-fee transactions. It should be set above the real
// cost to you of processing a transaction.
int64 nMinTxFee = MIN_TX_FEE;
if (mapArgs.count("-mintxfee"))
ParseMoney(mapArgs["-mintxfee"], nMinTxFee);
// ppcoin: if coinstake available add coinstake tx
static int64 nLastCoinStakeSearchTime = GetAdjustedTime(); // only initialized at startup
CBlockIndex* pindexPrev = pindexBest;
if (fProofOfStake) // attempt to find a coinstake
{
pblock->nBits = GetNextTargetRequired(pindexPrev, true);
CTransaction txCoinStake;
int64 nSearchTime = txCoinStake.nTime; // search to current time
if (nSearchTime > nLastCoinStakeSearchTime)
{
if (pwallet->CreateCoinStake(*pwallet, pblock->nBits, nSearchTime-nLastCoinStakeSearchTime, txCoinStake))
{
if (txCoinStake.nTime >= max(pindexPrev->GetMedianTimePast()+1, pindexPrev->GetBlockTime() - nMaxClockDrift))
{ // make sure coinstake would meet timestamp protocol
// as it would be the same as the block timestamp
pblock->vtx[0].nTime = txCoinStake.nTime;
pblock->vtx.push_back(txCoinStake);
}
}
nLastCoinStakeSearchInterval = nSearchTime - nLastCoinStakeSearchTime;
nLastCoinStakeSearchTime = nSearchTime;
}
}
// Check if the previous block was a bonus block and create a reward tx if necessary
// The reward tx will be a copy of the bonus block coinbase tx with the outputs adjusted proportionally
int64 nBonusReward = GetProofOfWorkBlockBonusRewardFactor(pindexPrev);
if (nBonusReward > 0)
{
CBlock prevBlock;
prevBlock.ReadFromDisk(pindexPrev, true);
CTransaction txReward = prevBlock.vtx[0];
for (unsigned i = 0; i < txReward.vout.size(); i++)
txReward.vout[i].nValue *= nBonusReward;
// Add bonus block reward tx
pblock->vtx.push_back(txReward);
}
pblock->nBits = GetNextTargetRequired(pindexPrev, pblock->IsProofOfStake());
// Collect memory pool transactions into the block
int64 nFees = 0;
{
LOCK2(cs_main, mempool.cs);
CBlockIndex* pindexPrev = pindexBest;
CTxDB txdb("r");
// Priority order to process transactions
list<COrphan> vOrphan; // list memory doesn't move
map<uint256, vector<COrphan*> > mapDependers;
// This vector will be sorted into a priority queue:
vector<TxPriority> vecPriority;
vecPriority.reserve(mempool.mapTx.size());
for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi)
{
CTransaction& tx = (*mi).second;
if (tx.IsCoinBase() || tx.IsCoinStake() || !tx.IsFinal())
continue;
COrphan* porphan = NULL;
double dPriority = 0;
int64 nTotalIn = 0;
bool fMissingInputs = false;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
// Read prev transaction
CTransaction txPrev;
CTxIndex txindex;
if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
{
// This should never happen; all transactions in the memory
// pool should connect to either transactions in the chain
// or other transactions in the memory pool.
if (!mempool.mapTx.count(txin.prevout.hash))
{
printf("ERROR: mempool transaction missing input\n");
if (fDebug) assert("mempool transaction missing input" == 0);
fMissingInputs = true;
if (porphan)
vOrphan.pop_back();
break;
}
// Has to wait for dependencies
if (!porphan)
{
// Use list for automatic deletion
vOrphan.push_back(COrphan(&tx));
porphan = &vOrphan.back();
}
mapDependers[txin.prevout.hash].push_back(porphan);
porphan->setDependsOn.insert(txin.prevout.hash);
nTotalIn += mempool.mapTx[txin.prevout.hash].vout[txin.prevout.n].nValue;
continue;
}
int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
nTotalIn += nValueIn;
int nConf = txindex.GetDepthInMainChain();
dPriority += (double)nValueIn * nConf;
}
if (fMissingInputs) continue;
// Priority is sum(valuein * age) / txsize
unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
dPriority /= nTxSize;
// This is a more accurate fee-per-kilobyte than is used by the client code, because the
// client code rounds up the size to the nearest 1K. That's good, because it gives an
// incentive to create smaller transactions.
double dFeePerKb = double(nTotalIn-tx.GetValueOut()) / (double(nTxSize)/1000.0);
if (porphan)
{
porphan->dPriority = dPriority;
porphan->dFeePerKb = dFeePerKb;
}
else
vecPriority.push_back(TxPriority(dPriority, dFeePerKb, &(*mi).second));
}
// Collect transactions into block
map<uint256, CTxIndex> mapTestPool;
uint64 nBlockSize = 1000;
uint64 nBlockTx = 0;
int nBlockSigOps = 100;
bool fSortedByFee = (nBlockPrioritySize <= 0);
TxPriorityCompare comparer(fSortedByFee);
std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
while (!vecPriority.empty())
{
// Take highest priority transaction off the priority queue:
double dPriority = vecPriority.front().get<0>();
double dFeePerKb = vecPriority.front().get<1>();
CTransaction& tx = *(vecPriority.front().get<2>());
std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
vecPriority.pop_back();
// Size limits
unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
if (nBlockSize + nTxSize >= nBlockMaxSize)
continue;
// Legacy limits on sigOps:
unsigned int nTxSigOps = tx.GetLegacySigOpCount();
if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
continue;
// Timestamp limit
if (tx.nTime > GetAdjustedTime() || (pblock->IsProofOfStake() && tx.nTime > pblock->vtx[1].nTime))
continue;
// ppcoin: simplify transaction fee - allow free = false
int64 nMinFee = tx.GetMinFee(nBlockSize, false, GMF_BLOCK);
// Skip free transactions if we're past the minimum block size:
if (fSortedByFee && (dFeePerKb < nMinTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
continue;
// Prioritize by fee once past the priority size or we run out of high-priority
// transactions:
if (!fSortedByFee &&
((nBlockSize + nTxSize >= nBlockPrioritySize) || (dPriority < COIN * 144 / 250)))
{
fSortedByFee = true;
comparer = TxPriorityCompare(fSortedByFee);
std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
}
// Connecting shouldn't fail due to dependency on other memory pool transactions
// because we're already processing them in order of dependency
map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
MapPrevTx mapInputs;
bool fInvalid;
if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs, fInvalid))
continue;
int64 nTxFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
if (nTxFees < nMinFee)
continue;
nTxSigOps += tx.GetP2SHSigOpCount(mapInputs);
if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
continue;
if (!tx.ConnectInputs(txdb, mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, false, true))
continue;
mapTestPoolTmp[tx.GetHash()] = CTxIndex(CDiskTxPos(1,1,1), tx.vout.size());
swap(mapTestPool, mapTestPoolTmp);
// Added
pblock->vtx.push_back(tx);
nBlockSize += nTxSize;
++nBlockTx;
nBlockSigOps += nTxSigOps;
nFees += nTxFees;
if (fDebug && GetBoolArg("-printpriority"))
{
printf("priority %.1f feeperkb %.1f txid %s\n",
dPriority, dFeePerKb, tx.GetHash().ToString().c_str());
}
// Add transactions that depend on this one to the priority queue
uint256 hash = tx.GetHash();
if (mapDependers.count(hash))
{
BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
{
if (!porphan->setDependsOn.empty())
{
porphan->setDependsOn.erase(hash);
if (porphan->setDependsOn.empty())
{
vecPriority.push_back(TxPriority(porphan->dPriority, porphan->dFeePerKb, porphan->ptx));
std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
}
}
}
}
}
nLastBlockTx = nBlockTx;
nLastBlockSize = nBlockSize;
if (fDebug && GetBoolArg("-printpriority"))
printf("CreateNewBlock(): total size %"PRI64u"\n", nBlockSize);
if (pblock->IsProofOfWork())
pblock->vtx[0].vout[0].nValue = GetProofOfWorkReward(pindexPrev->nHeight+1, nFees, pindexPrev->GetBlockHash());
// Fill in header
pblock->hashPrevBlock = pindexPrev->GetBlockHash();
if (pblock->IsProofOfStake())
pblock->nTime = pblock->vtx[1].nTime; //same as coinstake timestamp
pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, pblock->GetMaxTransactionTime());
pblock->nTime = max(pblock->GetBlockTime(), pindexPrev->GetBlockTime() - nMaxClockDrift);
if (pblock->IsProofOfWork())
pblock->UpdateTime(pindexPrev);
pblock->nNonce = 0;
}
return pblock.release();
}
void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
{
// Update nExtraNonce
static uint256 hashPrevBlock;
if (hashPrevBlock != pblock->hashPrevBlock)
{
nExtraNonce = 0;
hashPrevBlock = pblock->hashPrevBlock;
}
++nExtraNonce;
unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
pblock->vtx[0].vin[0].scriptSig = (CScript() << nHeight << CBigNum(nExtraNonce)) + COINBASE_FLAGS;
assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
}
void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
{
//
// Pre-build hash buffers
//
struct
{
struct unnamed2
{
int nVersion;
uint256 hashPrevBlock;
uint256 hashMerkleRoot;
unsigned int nTime;
unsigned int nBits;
unsigned int nNonce;
}
block;
unsigned char pchPadding0[64];
uint256 hash1;
unsigned char pchPadding1[64];
}
tmp;
memset(&tmp, 0, sizeof(tmp));
tmp.block.nVersion = pblock->nVersion;
tmp.block.hashPrevBlock = pblock->hashPrevBlock;
tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
tmp.block.nTime = pblock->nTime;
tmp.block.nBits = pblock->nBits;
tmp.block.nNonce = pblock->nNonce;
FormatHashBlocks(&tmp.block, sizeof(tmp.block));
FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
// Byte swap all the input buffer
for (unsigned int i = 0; i < sizeof(tmp)/4; i++)
((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
// Precalc the first half of the first hash, which stays constant
SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
memcpy(pdata, &tmp.block, 128);
memcpy(phash1, &tmp.hash1, 64);
}
bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
{
uint256 hashBlock = pblock->GetHash();
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
if(!pblock->IsProofOfWork())
return error("CheckWork() : %s is not a proof-of-work block", hashBlock.GetHex().c_str());
if (hashBlock > hashTarget)
return error("CheckWork() : proof-of-work not meeting target");
//// debug print
printf("CheckWork() : new proof-of-work block found \n hash: %s \ntarget: %s\n", hashBlock.GetHex().c_str(), hashTarget.GetHex().c_str());
pblock->print();
printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
// Found a solution
{
LOCK(cs_main);
if (pblock->hashPrevBlock != hashBestChain)
return error("CheckWork() : generated block is stale");
// Remove key from key pool
reservekey.KeepKey();
// Track how many getdata requests this block gets
{
LOCK(wallet.cs_wallet);
wallet.mapRequestCount[hashBlock] = 0;
}
// Process this block the same as if we had received it from another node
if (!ProcessBlock(NULL, pblock))
return error("CheckWork() : ProcessBlock, block not accepted");
}
return true;
}
bool CheckStake(CBlock* pblock, CWallet& wallet)
{
uint256 proofHash = 0, hashTarget = 0;
uint256 hashBlock = pblock->GetHash();
if(!pblock->IsProofOfStake())
return error("CheckStake() : %s is not a proof-of-stake block", hashBlock.GetHex().c_str());
// verify hash target and signature of coinstake tx
if (!CheckProofOfStake(pblock->vtx[1], pblock->nBits, proofHash, hashTarget))
return error("CheckStake() : proof-of-stake checking failed");
//// debug print
printf("CheckStake() : new proof-of-stake block found \n hash: %s \nproofhash: %s \ntarget: %s\n", hashBlock.GetHex().c_str(), proofHash.GetHex().c_str(), hashTarget.GetHex().c_str());
pblock->print();
printf("out %s\n", FormatMoney(pblock->vtx[1].GetValueOut()).c_str());
// Found a solution
{
LOCK(cs_main);
if (pblock->hashPrevBlock != hashBestChain)
return error("CheckStake() : generated block is stale");
// Track how many getdata requests this block gets
{
LOCK(wallet.cs_wallet);
wallet.mapRequestCount[hashBlock] = 0;
}
// Process this block the same as if we had received it from another node
if (!ProcessBlock(NULL, pblock))
return error("CheckStake() : ProcessBlock, block not accepted");
}
return true;
}
void StakeMiner(CWallet *pwallet)
{
SetThreadPriority(THREAD_PRIORITY_LOWEST);
// Make this thread recognisable as the mining thread
RenameThread("novacoin-miner");
// Each thread has its own counter
unsigned int nExtraNonce = 0;
while (true)
{
if (fShutdown)
return;
while (vNodes.empty() || IsInitialBlockDownload())
{
Sleep(1000);
if (fShutdown)
return;
}
while (pwallet->IsLocked())
{
strMintWarning = strMintMessage;
Sleep(1000);
}
strMintWarning = "";
//
// Create new block
//
CBlockIndex* pindexPrev = pindexBest;
auto_ptr<CBlock> pblock(CreateNewBlock(pwallet, true));
if (!pblock.get())
return;
IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce);
if(pblock->IsProofOfStake())
{
// Trying to sign a block
if (!pblock->SignBlock(*pwallet))
{
strMintWarning = strMintMessage;
continue;
}
strMintWarning = "";
SetThreadPriority(THREAD_PRIORITY_NORMAL);
CheckStake(pblock.get(), *pwallet);
SetThreadPriority(THREAD_PRIORITY_LOWEST);
}
Sleep(500);
continue;
}
}
| [
"bee7@github.com"
] | bee7@github.com |
d6647186e85031aa654eccdef3531160bd8beaff | b1320eb7edd285f493a0e4473dc433842aaa9178 | /Blik2D/addon/opencv-3.1.0_for_blik/samples/winrt_universal/VideoCaptureXAML/video_capture_xaml/video_capture_xaml.Shared/main.cpp | 44ce1ce659a81d792c39513239c55856618cca51 | [
"MIT",
"BSD-3-Clause"
] | permissive | BonexGoo/Blik2D-SDK | 2f69765145ef4281ed0cc2532570be42f7ccc2c6 | 8e0592787e5c8e8a28682d0e1826b8223eae5983 | refs/heads/master | 2021-07-09T01:39:48.653968 | 2017-10-06T17:37:49 | 2017-10-06T17:37:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,931 | cpp | // main.cpp
// Copyright (c) Microsoft Open Technologies, Inc.
// All rights reserved.
//
// (3 - clause BSD License)
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that
// the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the
// following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
// following disclaimer in the documentation and/or other materials provided with the distribution.
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or
// promote products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES(INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT(INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include "pch.h"
#include BLIK_OPENCV_V_opencv2__core_hpp //original-code:<opencv2/core.hpp>
#include BLIK_OPENCV_V_opencv2__imgproc_hpp //original-code:<opencv2/imgproc.hpp>
#include <opencv2/objdetect.hpp>
#include <opencv2/features2d.hpp>
#include <opencv2/videoio.hpp>
#include <opencv2/videoio/cap_winrt.hpp>
// Switch definitions below to apply different filters
// TODO: add UX controls to manipulate filters at runtime
//#define COLOR
#define CANNY
//#define FACES
using namespace cv;
namespace video_capture_xaml {
// forward declaration
void cvFilterColor(Mat &frame);
void cvFilterCanny(Mat &frame);
void cvDetectFaces(Mat &frame);
CascadeClassifier face_cascade;
String face_cascade_name = "Assets/haarcascade_frontalface_alt.xml";
void cvMain()
{
//initializing frame counter used by face detection logic
long frameCounter = 0;
// loading classifier for face detection
face_cascade.load(face_cascade_name);
// open the default camera
VideoCapture cam;
cam.open(0);
Mat frame;
// process frames
while (1)
{
// get a new frame from camera - this is non-blocking per spec
cam >> frame;
frameCounter++;
// don't reprocess the same frame again
// if commented then flashing may occur
if (!cam.grab()) continue;
// image processing calculations here
// Mat frame is in RGB24 format (8UC3)
// select processing type
#if defined COLOR
cvFilterColor(frame);
#elif defined CANNY
cvFilterCanny(frame);
#elif defined FACES
// processing every other frame to reduce the load
if (frameCounter % 2 == 0) {
cvDetectFaces(frame);
}
#endif
// important step to get XAML image component updated
winrt_imshow();
}
}
// image processing example #1
// write color bar at row 100 for 200 rows
void cvFilterColor(Mat &frame)
{
auto ar = frame.ptr(100);
int bytesPerPixel = 3;
int adjust = (int)(((float)30 / 100.0f) * 255.0);
for (int i = 0; i < 640 * 100 * bytesPerPixel;)
{
ar[i++] = adjust; // R
i++; // G
ar[i++] = 255 - adjust; // B
}
}
// image processing example #2
// apply edge detection aka 'canny' filter
void cvFilterCanny(Mat &frame)
{
Mat edges;
cvtColor(frame, edges, COLOR_RGB2GRAY);
GaussianBlur(edges, edges, Size(7, 7), 1.5, 1.5);
Canny(edges, edges, 0, 30, 3);
cvtColor(edges, frame, COLOR_GRAY2RGB);
}
// image processing example #3
// detect human faces
void cvDetectFaces(Mat &frame)
{
Mat faces;
std::vector<cv::Rect> facesColl;
cvtColor(frame, faces, COLOR_RGB2GRAY);
equalizeHist(faces, faces);
face_cascade.detectMultiScale(faces, facesColl, 1.1, 2, 0 | CV_HAAR_SCALE_IMAGE, cv::Size(1, 1));
for (unsigned int i = 0; i < facesColl.size(); i++)
{
auto face = facesColl[i];
cv::rectangle(frame, face, cv::Scalar(0, 255, 255), 3);
}
}
} | [
"slacealic@gmail.com"
] | slacealic@gmail.com |
6c955c071af491ee07b931d37654d506f6c64830 | e217eaf05d0dab8dd339032b6c58636841aa8815 | /IfcAlignment/src/OpenInfraPlatform/IfcAlignment/entity/include/IfcAirToAirHeatRecoveryType.h | a277ee10c61a667b1c185addf212ad4f0c9913ac | [] | no_license | bigdoods/OpenInfraPlatform | f7785ebe4cb46e24d7f636e1b4110679d78a4303 | 0266e86a9f25f2ea9ec837d8d340d31a58a83c8e | refs/heads/master | 2021-01-21T03:41:20.124443 | 2016-01-26T23:20:21 | 2016-01-26T23:20:21 | 57,377,206 | 0 | 1 | null | 2016-04-29T10:38:19 | 2016-04-29T10:38:19 | null | UTF-8 | C++ | false | false | 3,802 | h | /*! \verbatim
* \copyright Copyright (c) 2015 Julian Amann. All rights reserved.
* \author Julian Amann <julian.amann@tum.de> (https://www.cms.bgu.tum.de/en/team/amann)
* \brief This file is part of the BlueFramework.
* \endverbatim
*/
#pragma once
#include <vector>
#include <map>
#include <sstream>
#include <string>
#include "OpenInfraPlatform/IfcAlignment/model/shared_ptr.h"
#include "OpenInfraPlatform/IfcAlignment/model/IfcAlignmentP6Object.h"
#include "IfcEnergyConversionDeviceType.h"
namespace OpenInfraPlatform
{
namespace IfcAlignment
{
class IfcAirToAirHeatRecoveryTypeEnum;
//ENTITY
class IfcAirToAirHeatRecoveryType : public IfcEnergyConversionDeviceType
{
public:
IfcAirToAirHeatRecoveryType();
IfcAirToAirHeatRecoveryType( int id );
~IfcAirToAirHeatRecoveryType();
// method setEntity takes over all attributes from another instance of the class
virtual void setEntity( shared_ptr<IfcAlignmentP6Entity> other );
virtual void getStepLine( std::stringstream& stream ) const;
virtual void getStepParameter( std::stringstream& stream, bool is_select_type = false ) const;
virtual void readStepData( std::vector<std::string>& args, const std::map<int,shared_ptr<IfcAlignmentP6Entity> >& map );
virtual void setInverseCounterparts( shared_ptr<IfcAlignmentP6Entity> ptr_self );
virtual void unlinkSelf();
virtual const char* classname() const { return "IfcAirToAirHeatRecoveryType"; }
// IfcRoot -----------------------------------------------------------
// attributes:
// shared_ptr<IfcGloballyUniqueId> m_GlobalId;
// shared_ptr<IfcOwnerHistory> m_OwnerHistory; //optional
// shared_ptr<IfcLabel> m_Name; //optional
// shared_ptr<IfcText> m_Description; //optional
// IfcObjectDefinition -----------------------------------------------------------
// inverse attributes:
// std::vector<weak_ptr<IfcRelAssigns> > m_HasAssignments_inverse;
// std::vector<weak_ptr<IfcRelNests> > m_Nests_inverse;
// std::vector<weak_ptr<IfcRelNests> > m_IsNestedBy_inverse;
// std::vector<weak_ptr<IfcRelDeclares> > m_HasContext_inverse;
// std::vector<weak_ptr<IfcRelAggregates> > m_IsDecomposedBy_inverse;
// std::vector<weak_ptr<IfcRelAggregates> > m_Decomposes_inverse;
// std::vector<weak_ptr<IfcRelAssociates> > m_HasAssociations_inverse;
// IfcTypeObject -----------------------------------------------------------
// attributes:
// shared_ptr<IfcIdentifier> m_ApplicableOccurrence; //optional
// std::vector<shared_ptr<IfcPropertySetDefinition> > m_HasPropertySets; //optional
// inverse attributes:
// std::vector<weak_ptr<IfcRelDefinesByType> > m_Types_inverse;
// IfcTypeProduct -----------------------------------------------------------
// attributes:
// std::vector<shared_ptr<IfcRepresentationMap> > m_RepresentationMaps; //optional
// shared_ptr<IfcLabel> m_Tag; //optional
// inverse attributes:
// std::vector<weak_ptr<IfcRelAssignsToProduct> > m_ReferencedBy_inverse;
// IfcElementType -----------------------------------------------------------
// attributes:
// shared_ptr<IfcLabel> m_ElementType; //optional
// IfcDistributionElementType -----------------------------------------------------------
// IfcDistributionFlowElementType -----------------------------------------------------------
// IfcEnergyConversionDeviceType -----------------------------------------------------------
// IfcAirToAirHeatRecoveryType -----------------------------------------------------------
// attributes:
shared_ptr<IfcAirToAirHeatRecoveryTypeEnum> m_PredefinedType;
};
} // end namespace IfcAlignment
} // end namespace OpenInfraPlatform
| [
"planung.cms.bv@tum.de"
] | planung.cms.bv@tum.de |
cdb54b4a944e3912249df890665d6fbb2e12d062 | a4a7867942fcaa0c24ffbf670df67fdf74dc40e5 | /util/yss_time.cpp | 7cabbb917f11863af4edfcb983907487f50ea868 | [] | no_license | 2thetop/yss | 2de36874dff259b205ad495160684063aaee9aba | ce26c031d818153ee282cff4d2e03f10e4454b56 | refs/heads/master | 2023-01-10T23:38:38.294778 | 2020-11-14T09:11:48 | 2020-11-14T09:11:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,888 | cpp | ////////////////////////////////////////////////////////////////////////////////////////
//
// 저작권 표기 License_ver_2.0
// 본 소스코드의 소유권은 yss Embedded Operating System 네이버 카페 관리자와 운영진에게 있습니다.
// 운영진이 임의로 코드의 권한을 타인에게 양도할 수 없습니다.
// 본 소스코드는 아래 사항에 동의할 경우에 사용 가능합니다.
// 아래 사항에 대해 동의하지 않거나 이해하지 못했을 경우 사용을 금합니다.
// 본 소스코드를 사용하였다면 아래 사항을 모두 동의하는 것으로 자동 간주 합니다.
// 본 소스코드의 상업적 또는 비상업적 이용이 가능합니다.
// 본 소스코드의 내용을 임의로 수정하여 재배포하는 행위를 금합니다.
// 본 소스코드의 내용을 무단 전재하는 행위를 금합니다.
// 본 소스코드의 사용으로 인해 발생하는 모든 사고에 대해서 어떤한 법적 책임을 지지 않습니다.
//
// Home Page : http://cafe.naver.com/yssoperatingsystem
// Copyright 2020. yss Embedded Operating System all right reserved.
//
// 주담당자 : 아이구 (mymy49@nate.com) 2016.04.30 ~ 현재
// 부담당자 : -
//
////////////////////////////////////////////////////////////////////////////////////////
#include <__cross_studio_io.h>
#include <config.h>
#include <drv/peripherals.h>
//#include <thread.h>
unsigned long long gYssTimeSum = (unsigned long long)-60000;
static void isr(void)
{
gYssTimeSum += 60000;
}
void initSystemTime(void)
{
#ifndef YSS_DRV_TIMER_NOT_SUPPORT
YSS_TIMER.setClockEn(true);
YSS_TIMER.initSystemTime();
YSS_TIMER.setUpdateIsr(isr);
YSS_TIMER.setIntEn(true);
#endif
}
namespace time
{
unsigned long long gLastRequestTime;
unsigned long long getRunningSec(void)
{
#ifndef YSS_DRV_TIMER_NOT_SUPPORT
unsigned long long time = gYssTimeSum+YSS_TIMER.getCounterValue();
// 타이머 인터럽트 지연으로 인한 시간 오류 발생 보완용
if(time < gLastRequestTime)
time += 60000;
gLastRequestTime = time;
return time/1000000;
#else
return 0;
#endif
}
unsigned long long getRunningMsec(void)
{
#ifndef YSS_DRV_TIMER_NOT_SUPPORT
unsigned long long time = gYssTimeSum+YSS_TIMER.getCounterValue();
// 타이머 인터럽트 지연으로 인한 시간 오류 발생 보완용
if(time < gLastRequestTime)
time += 60000;
gLastRequestTime = time;
return time/1000;
#else
return 0;
#endif
}
unsigned long long getRunningUsec(void)
{
#ifndef YSS_DRV_TIMER_NOT_SUPPORT
unsigned long long time = gYssTimeSum+YSS_TIMER.getCounterValue();
// 타이머 인터럽트 지연으로 인한 시간 오류 발생 보완용
if(time < gLastRequestTime)
time += 60000;
gLastRequestTime = time;
return time;
#else
return 0;
#endif
}
}
| [
"mymy49@nate.com"
] | mymy49@nate.com |
f5234a1486a6587c740a74adb7b2ce6a1ac519b4 | 1d346f5cf9176a1a6b69925ec5eac969f2a8cc7c | /Src/View/UI/CLI/CLI.h | c8199787f63bbcd4e3a78509f1d2066fb366cac0 | [] | no_license | ginsberger/dna-analyzer-design | ef6cde49405d72da9d4037a23e16aced4af9bda9 | 6c235c7d66ed660095edff0a19d001b82ecf83bb | refs/heads/master | 2023-01-24T07:37:41.391805 | 2020-12-02T10:00:19 | 2020-12-02T10:00:19 | 305,764,925 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 387 | h |
#ifndef DNASEQUENCE_TERMINAL_H
#define DNASEQUENCE_TERMINAL_H
#include "../UI.h"
#include "../../../Utils/SharedPointer/SharedPtr.h"
#include "Parser.h"
class CLI : public UI{
public:
CLI(): m_parser(SharedPtr<Parser>(new Parser)){}
/*virtual*/ void run(const CallBack<Manager>& callBack) const;
private:
SharedPtr<Parser> m_parser;
};
#endif //DNASEQUENCE_TERMINAL_H
| [
"z618149948@gmail.com"
] | z618149948@gmail.com |
f52b8e7ff3d9057c938eb3c0b07eb0f5e73b29b3 | e0f939f08a3aa68a97c81e3c58af77e8370d357a | /src/RedisView/Public/AesEncrypt.cpp | b604dd705301114c965c9476c14c041794f168e8 | [] | no_license | haiyangfenghuo/RedisView | b236323af4e53816f86381daf24cfb1ea0ec566b | 208ef109e761702fe08150f2293a5aa940d37819 | refs/heads/master | 2022-02-24T19:27:11.802774 | 2019-09-08T08:17:45 | 2019-09-08T08:17:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,572 | cpp | /**
* @file AesEncrypt.cpp
* @brief AES加解密工具
* @author 王长春
* @date 2019-05-31
* @version 001
* @copyright Copyright (c) 2018
*/
#include "AesEncrypt.h"
QByteArray AesEncrypt::CBC256Crypt(QString inputStr) {
QaesEncryption encryption(QaesEncryption::AES_256, QaesEncryption::CBC);
return encryption.encode(inputStr.toLocal8Bit(),
_hashKey, _hashIV);
}
QString AesEncrypt::CBC256Decrypt(QByteArray inputStr) {
QaesEncryption encryption(QaesEncryption::AES_256, QaesEncryption::CBC);
return QString(encryption.removePadding(
encryption.decode(inputStr, _hashKey, _hashIV)));
}
QString AesEncrypt::_key =
"@D@6`Ht`T`xPXD|6T``TxDPd|@`7x@p1PPHPXTXX@Lld7D|XdHhdgL3dl|XtL"
"DpdhDdl3h|d|TLL|`lHH3xlTpL@|lH`TPxdh@Ptlh0tpHhtdxDtllhPp@h@xP"
"`l|t`4DtDLht`|`Tdt|tDPDTxtHTHp|lD9t@l|h`LtTl`hx3Ll|P`DXDhtXD|"
"ht@dXx|pxdH1t7|`PlP@HH4HP|@xd|LphllXpLlh32xp@3DhXtxtx@dPTtTXH"
"|x@lTtDTt@Tt@TtpPLPxtX3hX`X`Lhxx1l|Hp@pHdhxTLldpdp|DHxDXpHxLP"
"l|@x3PLhpXHT`t@TXldT5TPXPLt@p@@xDtxhXtXHxxT9pDlxH3l@tx|XpDlDX"
"3t|`txH|8X3hLh`|hdhTHPlDH|T|p@@|`6dhpTxDtPt@||`9X|@@hDptT|pHL"
"hdXhhdTDxHphllX`0xxLd|dDHxXp|LLdplT|HDX@PhpP`xhXP|lptX`D`@`1d"
"hDD3p@X@lhdxPXPDxLDhdlxpXdDLTppxD`|ff0e92h3ddv45245f4vfdhgrar";
QByteArray AesEncrypt::_hashKey = QCryptographicHash::hash(_key.toLocal8Bit(), QCryptographicHash::Sha256);
QByteArray AesEncrypt::_hashIV = QCryptographicHash::hash(_key.toLocal8Bit(), QCryptographicHash::Md5);
| [
"cc20110101@126.com"
] | cc20110101@126.com |
9bef4e6bebce5e97996495a3aa0ecec841f35b90 | 3cf9e141cc8fee9d490224741297d3eca3f5feff | /C++ Benchmark Programs/Benchmark Files 1/classtester/autogen-sources/source-7555.cpp | ebd9539edbf13277df5d13fed96f1bbde3af2693 | [] | 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 | 2,605 | cpp | struct c0;
void __attribute__ ((noinline)) tester0(c0* p);
struct c0
{
bool active0;
c0() : active0(true) {}
virtual ~c0()
{
tester0(this);
active0 = false;
}
virtual void f0(){}
};
void __attribute__ ((noinline)) tester0(c0* p)
{
p->f0();
}
struct c1;
void __attribute__ ((noinline)) tester1(c1* p);
struct c1
{
bool active1;
c1() : active1(true) {}
virtual ~c1()
{
tester1(this);
active1 = false;
}
virtual void f1(){}
};
void __attribute__ ((noinline)) tester1(c1* p)
{
p->f1();
}
struct c2;
void __attribute__ ((noinline)) tester2(c2* p);
struct c2 : virtual c0
{
bool active2;
c2() : active2(true) {}
virtual ~c2()
{
tester2(this);
c0 *p0_0 = (c0*)(c2*)(this);
tester0(p0_0);
active2 = false;
}
virtual void f2(){}
};
void __attribute__ ((noinline)) tester2(c2* p)
{
p->f2();
if (p->active0)
p->f0();
}
struct c3;
void __attribute__ ((noinline)) tester3(c3* p);
struct c3 : virtual c2
{
bool active3;
c3() : active3(true) {}
virtual ~c3()
{
tester3(this);
c0 *p0_0 = (c0*)(c2*)(c3*)(this);
tester0(p0_0);
c2 *p2_0 = (c2*)(c3*)(this);
tester2(p2_0);
active3 = false;
}
virtual void f3(){}
};
void __attribute__ ((noinline)) tester3(c3* p)
{
p->f3();
if (p->active0)
p->f0();
if (p->active2)
p->f2();
}
struct c4;
void __attribute__ ((noinline)) tester4(c4* p);
struct c4 : virtual c2, virtual c0, c1
{
bool active4;
c4() : active4(true) {}
virtual ~c4()
{
tester4(this);
c0 *p0_0 = (c0*)(c2*)(c4*)(this);
tester0(p0_0);
c0 *p0_1 = (c0*)(c4*)(this);
tester0(p0_1);
c1 *p1_0 = (c1*)(c4*)(this);
tester1(p1_0);
c2 *p2_0 = (c2*)(c4*)(this);
tester2(p2_0);
active4 = false;
}
virtual void f4(){}
};
void __attribute__ ((noinline)) tester4(c4* p)
{
p->f4();
if (p->active1)
p->f1();
if (p->active0)
p->f0();
if (p->active2)
p->f2();
}
int __attribute__ ((noinline)) inc(int v) {return ++v;}
int main()
{
c0* ptrs0[25];
ptrs0[0] = (c0*)(new c0());
ptrs0[1] = (c0*)(c2*)(new c2());
ptrs0[2] = (c0*)(c2*)(c3*)(new c3());
ptrs0[3] = (c0*)(c2*)(c4*)(new c4());
ptrs0[4] = (c0*)(c4*)(new c4());
for (int i=0;i<5;i=inc(i))
{
tester0(ptrs0[i]);
delete ptrs0[i];
}
c1* ptrs1[25];
ptrs1[0] = (c1*)(new c1());
ptrs1[1] = (c1*)(c4*)(new c4());
for (int i=0;i<2;i=inc(i))
{
tester1(ptrs1[i]);
delete ptrs1[i];
}
c2* ptrs2[25];
ptrs2[0] = (c2*)(new c2());
ptrs2[1] = (c2*)(c3*)(new c3());
ptrs2[2] = (c2*)(c4*)(new c4());
for (int i=0;i<3;i=inc(i))
{
tester2(ptrs2[i]);
delete ptrs2[i];
}
c3* ptrs3[25];
ptrs3[0] = (c3*)(new c3());
for (int i=0;i<1;i=inc(i))
{
tester3(ptrs3[i]);
delete ptrs3[i];
}
c4* ptrs4[25];
ptrs4[0] = (c4*)(new c4());
for (int i=0;i<1;i=inc(i))
{
tester4(ptrs4[i]);
delete ptrs4[i];
}
return 0;
}
| [
"ga72foq@mytum.de"
] | ga72foq@mytum.de |
be4a5e582b28b15dc02eadb7e49d31e8c42430ce | 2b86548f40b765a7cfc083937bd788db0d3e12db | /fileHandler.h | 8611236a7e54fc13ae04c4a619d3cb8b70ed7f53 | [] | no_license | BoilingT/fileReading | 065ddfd40f79aa0d0188117da0c74add36b5b5de | f70ed656c1e87f9d1c9ef78039d42dee5a14199b | refs/heads/master | 2023-03-07T10:01:07.408464 | 2021-02-16T14:22:42 | 2021-02-16T14:22:42 | 339,366,195 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 486 | h | #pragma once
#include <string>
#include <fstream>
#include <stdio.h>
#include <iostream>
#include <direct.h>
#include <list>
class fileHandler
{
public:
bool writeFile(std::string fileName, std::string content);
bool readFile(std::string fileName, std::string & content);
bool removeFile(const char * fileName);
bool createDir(const char* path);
private:
std::fstream file;
bool openFile(std::string fileName);
bool createFile(std::string fileName);
void closeFile();
};
| [
"tobias.andersson@edu.upplands-bro.se"
] | tobias.andersson@edu.upplands-bro.se |
41289dd7cbc10dfde834fbac2e41091b24def1cf | 66a76b9761fd730fbda64fac92e3fcffa37cfa8f | /include/PrintList.h | 226a42bc7e4fd84f5f1872cff88afa7f34cf6a08 | [] | no_license | JaceRiehl/Council-Of-Jerrys | 699cb618bab89aa2a0fe6bd4149701a68274c078 | 1991b0de7130d642201a46ab94f2189b715f4824 | refs/heads/master | 2021-09-01T04:39:33.385827 | 2017-04-08T05:53:51 | 2017-04-08T05:53:51 | 115,288,568 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,373 | h | #ifndef PRINTLIST_H
#define PRINTLIST_H
#include <map>
#include <string>
#include <vector>
#include <iostream>
#include <ostream>
using namespace std;
/**
*Formats and prints a list of objects
*/
class PrintList
{
public:
/**
*Default constructor with no list initialized
*/
PrintList();
/**
*Default constructor for a map of strings
*@param a map of strings accessed through characters
*/
PrintList(map<char, string>);
/**
*Default constructore for a vector of strings
*@param a vector of strings
*/
PrintList(vector<string>);
/**
*Deconstructor for PrintList
*/
virtual ~PrintList();
/**
*Copy constructor for PrintList
*/
PrintList(PrintList&);
/**
*Prints the formated list
*@param an ostream to print out the list
*/
void print(ostream&);
/**
*Checks weather the object has a list or not
*@param None
*/
bool isEmpty();
/**
*Overloaded assignment operator
*/
void operator=(PrintList&);
void setList(vector<string>);
void setList(map<char,string>);
/**
*Overloaded insertion operator, uses the print function
*/
friend ostream& operator<<(ostream&, PrintList&);
private:
string stringToPrint;
string convert(vector<string>);
string convert(map<char, string>);
};
#endif // PRINTLIST_H
| [
"n.tipper05@gmail.com"
] | n.tipper05@gmail.com |
3085fce07959b2b102aac9459ca946c5391d6e05 | 6c376312457b8af43e372d10bbe6ba29f58cf99d | /DirectX11_BaseSystem/Include/Havok_SDK/Common/Compat/Patches/2013_2/hkPatches_2013_2.cxx | 8eb1751d31bf0ce176443dd4a7ab97c5ce3c87c6 | [] | no_license | kururu-zzz/DirectWrite | f3599ae83c0edefb574ccd9c0026a151a68fbfbf | 19fe366832ec04cbcdb79db799eb8088ced376ad | refs/heads/master | 2021-01-10T08:00:53.148408 | 2015-12-17T04:51:31 | 2015-12-17T04:51:31 | 48,152,937 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,184 | cxx | /*
*
* Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's
* prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok.
* Product and Trade Secret source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2014 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement.
*
*/
// Common specific product patches applied to release 2013_2.
// This file is #included by hkPatches_2013_2.cpp
HK_PATCH_BEGIN("hkPackfileHeader", 1, "hkPackfileHeader", 2)
HK_PATCH_MEMBER_REMOVED("pad", TYPE_ARRAY_INT, HK_NULL, 0)
HK_PATCH_MEMBER_ADDED("maxpredicate", TYPE_INT, HK_NULL, 0)
HK_PATCH_MEMBER_ADDED("predicateArraySizePlusPadding", TYPE_INT, HK_NULL, 0)
HK_PATCH_END()
HK_PATCH_BEGIN("hkAabbHalf", 0, "hkAabbHalf", 1)
HK_PATCH_MEMBER_RENAMED("data","data_old")
HK_PATCH_MEMBER_ADDED("data", TYPE_TUPLE_INT, HK_NULL, 8)
HK_PATCH_FUNCTION(hkAabbHalf_0_to_1)
HK_PATCH_MEMBER_REMOVED("data_old", TYPE_TUPLE_INT, HK_NULL, 6)
HK_PATCH_MEMBER_REMOVED("extras", TYPE_TUPLE_INT, HK_NULL, 2)
HK_PATCH_END()
HK_PATCH_BEGIN(HK_NULL, HK_CLASS_ADDED, "hkUuid", 0)
HK_PATCH_MEMBER_ADDED("data", TYPE_TUPLE_INT, HK_NULL, 4)
HK_PATCH_END()
HK_PATCH_BEGIN("hkUuid", 0, "hkUuid", 1)
HK_PATCH_END()
HK_PATCH_BEGIN("hkUiAttribute", 2, "hkUiAttribute", 3)
HK_PATCH_MEMBER_ADDED_BYTE("editable", 0)
HK_PATCH_END()
/*
* Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20140907)
*
* Confidential Information of Havok. (C) Copyright 1999-2014
* Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok
* Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership
* rights, and intellectual property rights in the Havok software remain in
* Havok and/or its suppliers.
*
* Use of this software for evaluation purposes is subject to and indicates
* acceptance of the End User licence Agreement for this product. A copy of
* the license is included with this software and is also available at www.havok.com/tryhavok.
*
*/
| [
"kurukuru.0844808@gmail.com"
] | kurukuru.0844808@gmail.com |
46deab72bea159e57c4d410e576d617f5455fed4 | 5d83739af703fb400857cecc69aadaf02e07f8d1 | /Archive2/63/be0e97e4399df0/main.cpp | 7369955716d1e72b61c6eaced56925114e6b0372 | [] | 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 | 4,965 | cpp | #include <cassert>
#include <iostream>
#define PRINT() print_impl(__FUNCTION__);
struct circular_buffer
{
circular_buffer() : mStorage(new uint16_t[capacity()])
{
std::cout << "\n***********\n";
PRINT();
}
static constexpr std::size_t capacity()
{
return 32;
}
void push_back(uint16_t value)
{
if (mSize == capacity())
{
mStorage[mBegin++ % capacity()] = value;
}
else
{
mStorage[mSize++ % capacity()] = value;
}
PRINT();
}
uint16_t pop_back()
{
assert(size());
auto result = mStorage[(mBegin + mSize - 1) % capacity()];
mSize--;
PRINT();
return result;
}
void push_front(uint16_t value)
{
mStorage[--mBegin % capacity()] = value;
if (mSize != capacity())
{
mSize++;
}
PRINT();
}
uint16_t pop_front()
{
assert(size());
mSize--;
auto result = mStorage[mBegin++ % capacity()];
PRINT();
return result;
}
std::size_t size() const
{
return mSize >= capacity() ? capacity() : mSize;
}
bool empty()
{
return !mSize;
}
struct iterator
{
iterator(circular_buffer& buf) :
mStorage(buf.mStorage),
mOffset(buf.mBegin)
{
}
iterator(circular_buffer& buf, int) :
mStorage(buf.mStorage),
mOffset(buf.mBegin + buf.mSize)
{
}
uint16_t& operator*()
{
return mStorage[mOffset % circular_buffer::capacity()];
}
bool operator<(iterator rhs)
{
return mOffset < rhs.mOffset;
}
bool operator==(iterator rhs)
{
return mOffset == rhs.mOffset;
}
bool operator!=(iterator rhs)
{
return !(*this == rhs);
}
iterator& operator++()
{
mOffset++;
return *this;
}
uint16_t* mStorage;
uint16_t mOffset = 0;
};
iterator begin()
{
return iterator(*this);
}
iterator end()
{
return iterator(*this, 0);
}
void print_impl(const char* f)
{
std::cout << f
<< ": mSize=" << int(mSize)
<< " mBegin=" << int(mBegin)
<< " size()=" << size()
<< " capacity()=" << capacity()
<< " [";
for (auto el : *this)
{
std::cout << el;
}
std::cout << "]" << std::endl;
}
uint16_t* mStorage; // max-index is 255, capacity is
uint32_t mBegin = 0;
uint32_t mSize = 0;
};
int main()
{
{
circular_buffer buf;
assert(buf.empty());
buf.push_front(1);
buf.push_front(2);
buf.push_front(3);
buf.pop_front();
buf.pop_front();
buf.pop_front();
assert(buf.empty());
}
{
circular_buffer buf;
assert(buf.empty());
buf.push_front(1);
buf.push_front(2);
buf.push_front(3);
buf.pop_back();
buf.pop_back();
buf.pop_back();
assert(buf.empty());
}
{
circular_buffer buf;
assert(buf.empty());
buf.push_back(1);
buf.push_back(2);
buf.push_back(3);
buf.pop_back();
buf.pop_back();
buf.pop_back();
assert(buf.empty());
}
{
circular_buffer buf;
assert(buf.empty());
buf.push_back(1); assert(!buf.empty()); assert(buf.size() == 1);
buf.push_back(2); assert(!buf.empty()); assert(buf.size() == 2);
buf.push_back(3); assert(!buf.empty()); assert(buf.size() == 3);
assert(!buf.empty()); assert(buf.size() == 3); buf.pop_front();
assert(!buf.empty()); assert(buf.size() == 2); buf.pop_front();
assert(!buf.empty()); assert(buf.size() == 1); buf.pop_front();
assert(buf.empty()) ; assert(buf.size() == 0);
}
{
circular_buffer buf;
for (auto i = 0; i != 40; ++i)
{
buf.push_back(i % 10);
}
while (buf.size() >= 2)
{
buf.pop_front();
buf.pop_back();
}
}
{
circular_buffer buf;
for (auto i = 0; i != 40; ++i)
{
buf.push_front(i % 10);
}
while (buf.size() >= 2)
{
buf.pop_front();
buf.pop_back();
}
}
}
| [
"francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df"
] | francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df |
cc4ad2594c90e1e17d40af72b3d631c8a53d505d | 2861f73e536f12e3904093b01b455ec9bc399a31 | /src/itp1_4/itp1_4_c.cpp | 3d001e6dae54ae092086a2e5893116cba506ed3c | [] | no_license | LilKoke/Competitive-Programming | d5e209c6c3ffd18fef752f7176449d6b24890923 | 6b014078e45ec18eca51875aae1cf083746ac888 | refs/heads/master | 2021-11-04T02:24:09.861157 | 2019-04-27T14:57:13 | 2019-04-27T14:57:13 | 159,078,709 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 775 | cpp | #include "bits/stdc++.h"
using namespace std;
#define print(s) cout << (s) << endl;
#define sp(x) cout<<setprecision(x);
#define FOR(i,a,b) for(int i=(a);i<(b);i++)
#define REP(i,n) FOR(i,0,n)
#define all(a) (a).begin(), (a).end()
#define inf 10000000
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
int a, b;
char op;
while(op != '?'){
cin>>a>>op>>b;
int ans;
if(op=='+'){
ans = a+b;
cout<<ans<<endl;
} else if (op=='-'){
ans = a-b;
cout<<ans<<endl;
} else if (op=='*'){
ans = a*b;
cout<<ans<<endl;
} else if (op=='/'){
ans = a/b;
cout<<ans<<endl;
}
}
return 0;
} | [
"44338851+LilKoke@users.noreply.github.com"
] | 44338851+LilKoke@users.noreply.github.com |
5fad77990941281be9ef03a068e7f6d5605b68cb | eae02ef9a47fddbe12cfd8e84b7a475936839e7c | /temp/f00290_wsrequesthandler.hpp | 146bd4c5a3c2f98a60a8741557c87d4ecc914ebf | [] | no_license | ezhangle/voxelquest | d740084dc703b8e8eb08a41b4208b228e7a1c22b | c3cddb3bd3cff21712a5e4b4841b344cd1727092 | refs/heads/master | 2020-12-24T10:39:45.588531 | 2016-05-05T18:21:16 | 2016-11-06T08:45:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,323 | hpp |
class WebSocketRequestHandler: public HTTPRequestHandler {
public:
WebSocketServer* ws_ptr;
WebSocketRequestHandler(WebSocketServer* _ws_ptr) {
ws_ptr = _ws_ptr;
}
~WebSocketRequestHandler() {
}
void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response)
{
int flags;
int n;
//JSONValue *value;
if (ws_ptr->isWorking) {
// drop the request, client should only send one request
// at a time until it receives a response message
return;
}
ws_ptr->isWorking = true;
ws_ptr->dataReady = false;
/*
if (ws_ptr->recMessage != NULL) {
delete ws_ptr->recMessage;
ws_ptr->recMessage = NULL;
}
*/
Application& app = Application::instance();
try
{
WebSocket ws(request, response);
app.logger().information("WebSocket connection established.");
//char buffer[1024];
do
{
n = ws.receiveFrame(ws_ptr->recBuffer.data, ws_ptr->MAX_FRAME_SIZE, flags);
//app.logger().information(Poco::format("Frame received (length=%d, flags=0x%x).", n, unsigned(flags)));
if (n > 0) {
ws_ptr->recBuffer.data[n+1] = '\0';
ws_ptr->recBuffer.size = n;
if (ws_ptr->recBuffer.data[0] == '{') {
ws_ptr->isJSON = true;
ws_ptr->recBuffer.data[n] = '\0';
}
else {
ws_ptr->isJSON = false;
}
ws_ptr->dataReady = true;
}
ws.sendFrame(ws_ptr->okBuffer.data,ws_ptr->okBuffer.size,flags);
}
while ( (n > 0 || (flags & WebSocket::FRAME_OP_BITMASK) != WebSocket::FRAME_OP_CLOSE) && PROG_ACTIVE );
app.logger().information("WebSocket connection closed.");
}
catch (WebSocketException& exc)
{
app.logger().log(exc);
switch (exc.code())
{
case WebSocket::WS_ERR_HANDSHAKE_UNSUPPORTED_VERSION:
response.set("Sec-WebSocket-Version", WebSocket::WEBSOCKET_VERSION);
// fallthrough
case WebSocket::WS_ERR_NO_HANDSHAKE:
case WebSocket::WS_ERR_HANDSHAKE_NO_VERSION:
case WebSocket::WS_ERR_HANDSHAKE_NO_KEY:
response.setStatusAndReason(HTTPResponse::HTTP_BAD_REQUEST);
response.setContentLength(0);
response.send();
break;
}
}
}
};
| [
"simcop2387@simcop2387.info"
] | simcop2387@simcop2387.info |
7c2a27976c26e4d79f7c3b40cc2281625be57612 | b9af0d57dd04ad43c49b5d52a2469a741ba8f2ac | /GRN.cpp | 109930b1487dcfde4a5545096a0078ea5ae95b07 | [] | no_license | 124650924/USTC-Software2013 | c37372767550785d024e169187277227cd48412e | 4340cecd3de61dd50e6add44ba9415d5a206df4f | refs/heads/master | 2021-01-18T05:53:31.166599 | 2013-07-30T09:34:17 | 2013-07-30T09:34:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,514 | cpp | //
// GRN.cpp
// GRN
//
// Created by jinyang on 13-7-26.
// Copyright (c) 2013年 Li Jinyang. All rights reserved.
//
#include "GRN.h"
#include <vector>
#include <string>
void GRN::initializeGRN(double oldGRN[][scale], int mSize){
for (int i = 0; i != scale; ++i) {
for (int j = 0; j != scale; ++j) {
newGRNCorrelation[i][j] = oldGRN[i][j];
}
}
matrixSize = mSize;
}
void GRN::constructNewGRN(Sequence::Sequence seqArry[]){
//insert new correlations to (matrixSize + 1) row;
for (int j_geneNum = 0; j_geneNum != matrixSize; ++j_geneNum) {
newGRNCorrelation[matrixSize + 1][j_geneNum] = aminoASAlignment(seqArry[matrixSize + 1].getAminoAcidSequence(), seqArry[matrixSize + 1].aminoASSize, seqArry[j_geneNum].getAminoAcidSequence(), seqArry[j_geneNum].aminoASSize);
}
//insert new correlations to (matrixSize + 1) column;
for (int i_geneNum = 0; i_geneNum; ++i_geneNum) {
newGRNCorrelation[i_geneNum][matrixSize + 1] = aminoASAlignment(seqArry[matrixSize + 1].getAminoAcidSequence(), seqArry[matrixSize + 1].aminoASSize, seqArry[i_geneNum].getAminoAcidSequence(), seqArry[i_geneNum].aminoASSize);
}
newGRNCorrelation[matrixSize + 1][matrixSize + 1] = 0;
}
double GRN::aminoASAlignment(std::string s, int s_size, std::string t, int t_size){
int G_ = 0;
int _G = 0;
std::vector< std::vector<double> > alignMatrix (t_size, std::vector<double>(s_size));
//initialize alignMatrix;
alignMatrix[0][0] = 0;
for (int i = 1; i != t_size; ++i) {
alignMatrix[i][0] = alignMatrix[i - 1][0] + G_;
}
for (int j = 1; j != s_size; ++j) {
alignMatrix[0][j] = alignMatrix[0][j - 1] + _G;
}
for (int i = 1; i != t_size; ++i) {
for (int j = 1; j != s_size; ++j) {
alignMatrix[i][j] = maxValue(alignMatrix[i-1][j-1] + alignScore(s[j],t[i]), alignMatrix[i-1][j] + alignScore(s[j], ' '), alignMatrix[i][j-1] + alignScore(' ', t[i]));
}
}
return alignMatrix[t_size - 1][s_size - 1];
}
int GRN::alignScore (char s, char t)
{
int score = 0;
int GG = 1;
int _G = 0;
int GT = 0;
if (s == t)
score = GG;
else if (s == ' ')
score = _G;
else if (t == ' ')
score = _G;
else if (s != t)
score = GT;
return score;
}
int GRN::maxValue (int a, int b, int c)
{
if(a<b)
a=b;
if(a<c)
a=c;
return a;
} | [
"jinyangustc@gmail.com"
] | jinyangustc@gmail.com |
79a89f37fd06c5865d5c32ae7551ce4d4662e6cb | 88ae8695987ada722184307301e221e1ba3cc2fa | /third_party/ots/src/src/fvar.h | a469c8cddfadbb0b02ec29f96251bb8477336b2e | [
"Apache-2.0",
"LGPL-2.0-or-later",
"MIT",
"GPL-1.0-or-later",
"BSD-3-Clause"
] | permissive | iridium-browser/iridium-browser | 71d9c5ff76e014e6900b825f67389ab0ccd01329 | 5ee297f53dc7f8e70183031cff62f37b0f19d25f | refs/heads/master | 2023-08-03T16:44:16.844552 | 2023-07-20T15:17:00 | 2023-07-23T16:09:30 | 220,016,632 | 341 | 40 | BSD-3-Clause | 2021-08-13T13:54:45 | 2019-11-06T14:32:31 | null | UTF-8 | C++ | false | false | 1,482 | h | // Copyright (c) 2018 The OTS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef OTS_FVAR_H_
#define OTS_FVAR_H_
#include <vector>
#include "ots.h"
namespace ots {
// -----------------------------------------------------------------------------
// OpenTypeFVAR Interface
// -----------------------------------------------------------------------------
class OpenTypeFVAR : public Table {
public:
explicit OpenTypeFVAR(Font* font, uint32_t tag)
: Table(font, tag, tag) { }
bool Parse(const uint8_t* data, size_t length);
bool Serialize(OTSStream* out);
uint16_t AxisCount() const { return axisCount; }
private:
uint16_t majorVersion;
uint16_t minorVersion;
uint16_t axesArrayOffset;
uint16_t reserved;
uint16_t axisCount;
uint16_t axisSize;
uint16_t instanceCount;
uint16_t instanceSize;
typedef int32_t Fixed; /* 16.16 fixed-point value */
struct VariationAxisRecord {
uint32_t axisTag;
Fixed minValue;
Fixed defaultValue;
Fixed maxValue;
uint16_t flags;
uint16_t axisNameID;
};
std::vector<VariationAxisRecord> axes;
struct InstanceRecord {
uint16_t subfamilyNameID;
uint16_t flags;
std::vector<Fixed> coordinates;
uint16_t postScriptNameID; // optional
};
std::vector<InstanceRecord> instances;
bool instancesHavePostScriptNameID;
};
} // namespace ots
#endif // OTS_FVAR_H_
| [
"jengelh@inai.de"
] | jengelh@inai.de |
e8c506feb36ad54a2988a5825b7222d7d469e517 | 6d2c96c8184ea155bb128d72050be87e10a4163d | /Source/sandbox/animated-mesh.cpp | 9d9144279171de247d9b0fad4669f73fa546c704 | [
"MIT"
] | permissive | karlgluck/Evidyon | 8dc144e3a011930ab1eba19b4c0eddf74339ef65 | 8b545de48a5b77a02c91d4bff7b6d6496a48ebb7 | refs/heads/master | 2023-01-04T08:22:47.493595 | 2022-12-31T18:24:55 | 2022-12-31T18:24:55 | 451,806 | 3 | 1 | NOASSERTION | 2022-12-31T18:24:56 | 2009-12-29T04:12:19 | Logos | WINDOWS-1252 | C++ | false | false | 10,789 | cpp | //---------------------------------------------------------------------------//
// This file is part of Evidyon, a 3d multiplayer online role-playing game //
// Copyright © 2008 - 2013 Karl Gluck //
// //
// 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. //
// //
// Karl Gluck can be reached by email at kwg8@cornell.edu //
//---------------------------------------------------------------------------//
#include <Windows.h>
#include <mmsystem.h>
#include <d3dx9.h>
#pragma warning( disable : 4996 ) // disable deprecated warning
#include <strsafe.h>
#pragma warning( default : 4996 )
#pragma comment(lib, "d3d9.lib")
#if defined(DEBUG) || defined(_DEBUG)
#pragma comment(lib, "d3dx9d.lib")
#pragma comment(lib, "dc_d.lib")
#else
#pragma comment(lib, "d3dx9.lib")
#pragma comment(lib, "dc.lib")
#endif
namespace Evidyon {
namespace AnimatedMesh {
struct AnimatedMeshFrameData;
struct AnimatedMeshBoneData;
struct AnimatedMeshTextureGroup;
//----[ AnimatedMeshData ]---------------------------------------------------
struct AnimatedMeshData {
unsigned int number_of_texture_groups;
unsigned int number_of_frames;
unsigned int number_of_bones;
AnimatedMeshFrameData* frames;
AnimatedMeshBoneData* bones;
AnimatedMeshTextureGroup* texture_groups;
};
static const unsigned int INVALID_FRAME_INDEX = 0xFFFFFFFF;
//----[ AnimatedMeshFrameData ]----------------------------------------------
struct AnimatedMeshFrameData {
// This frame's offset from its parent in the hierarchy
D3DXMATRIX offset;
// This must be less than this frame's index. The only exception is bone 0,
// the root bone, for which this value must be INVALID_FRAME_INDEX.
DWORD parent_frame_index;
};
//----[ AnimatedMeshBoneData ]-----------------------------------------------
struct AnimatedMeshBoneData {
/// Multiply the source frame's adjusted offset by this matrix before setting into the device
D3DXMATRIXA16 inverse_offset;
/// The frame index from which this bone's transformation is derived
DWORD frame_index;
};
//----[ AnimatedMeshVertex ]-------------------------------------------------
struct AnimatedMeshVertex {
float x, y, z;
float bone_weights[4];
unsigned char bone_matrix_indices[4];
float nx, ny, nz;
float u, v;
};
#define D3DFVF_EVIDYON_ANIMATEDMESHVERTEX (D3DFVF_XYZB4|D3DFVF_NORMAL|D3DFVF_TEX1|D3DFVF_LASTBETA_UBYTE4)
//----[ AnimatedMeshIndex ]--------------------------------------------------
typedef unsigned short AnimatedMeshIndex;
#define D3DFFMT_EVIDYON_ANIMATEDMESHINDEX (D3DFMT_INDEX16)
//----[ AnimatedMeshTextureGroup ]-------------------------------------------
struct AnimatedMeshTextureGroup {
AnimatedMeshVertex* vertices;
unsigned int number_of_vertices;
AnimatedMeshIndex* indices;
unsigned int number_of_indices;
};
// loader should bear responsibility of splitting up animated mesh texture
// groups when bringing into memory.
// subsets of animated mesh are (animated mesh, texture group, subset #)
// like mesh renderer! initialize (..., ..., ...) then render-render-render...
// for a subset, the renderer returns array of skeleton indices to set
// such that ARRAY[...] for each i in ARRAY: setTransform(WORLD(i), bones[ARRAY[i]])
/*
algo:
convert mesh to standard format
build frame name -> hierarchy index
build bone table
for each bone, get the set of (vertex index, weight) pairs it affects
clean up all vertex influences
*/
}
}
class D3DRenderingManager {
public:
virtual LPDIRECT3DDEVICE9 acquireDevice() = 0;
private:
};
class D3DRenderingManagerSimple : public D3DRenderingManager {
public:
bool create(HWND hWnd);
void destroy();
LPDIRECT3DDEVICE9 getDevice() { return d3d_device_; }
virtual LPDIRECT3DDEVICE9 acquireDevice() { d3d_device_->AddRef(); return d3d_device_; }
private:
LPDIRECT3D9 d3d_;
LPDIRECT3DDEVICE9 d3d_device_;
};
bool D3DRenderingManagerSimple::create(HWND hWnd) {
// Create the D3D object.
if( NULL == ( d3d_ = Direct3DCreate9( D3D_SDK_VERSION ) ) )
return false;
// Set up the structure used to create the D3DDevice. Since we are now
// using more complex geometry, we will create a device with a zbuffer.
D3DPRESENT_PARAMETERS d3dpp;
ZeroMemory( &d3dpp, sizeof( d3dpp ) );
d3dpp.Windowed = TRUE;
d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;
d3dpp.EnableAutoDepthStencil = TRUE;
d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
// Create the D3DDevice
if( FAILED( d3d_->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
D3DCREATE_SOFTWARE_VERTEXPROCESSING,
&d3dpp, &d3d_device_ ) ) )
{
return false;
}
// Turn on the zbuffer
d3d_device_->SetRenderState( D3DRS_ZENABLE, TRUE );
// Turn on ambient lighting
d3d_device_->SetRenderState( D3DRS_LIGHTING, FALSE );
return true;
}
void D3DRenderingManagerSimple::destroy() {
if( d3d_device_ != NULL )
d3d_device_->Release();
if( d3d_ != NULL )
d3d_->Release();
d3d_device_ = NULL;
d3d_ = NULL;
}
//-----------------------------------------------------------------------------
// Name: MsgProc()
// Desc: The window's message handler
//-----------------------------------------------------------------------------
LRESULT WINAPI MsgProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
switch( msg )
{
case WM_DESTROY:
PostQuitMessage( 0 );
return 0;
}
return DefWindowProc( hWnd, msg, wParam, lParam );
}
//-----------------------------------------------------------------------------
// Name: WinMain()
// Desc: The application's entry point
//-----------------------------------------------------------------------------
INT WINAPI wWinMain( HINSTANCE hInst, HINSTANCE, LPWSTR, INT )
{
// Register the window class
WNDCLASSEX wc =
{
sizeof( WNDCLASSEX ), CS_CLASSDC, MsgProc, 0L, 0L,
GetModuleHandle( NULL ), NULL, NULL, NULL, NULL,
"D3D Tutorial", NULL
};
RegisterClassEx( &wc );
// Create the application's window
HWND hWnd = CreateWindow( "D3D Tutorial", "D3D Tutorial 06: Meshes",
WS_OVERLAPPEDWINDOW, 10, 10, 1000, 1000,
NULL, NULL, wc.hInstance, NULL );
D3DRenderingManagerSimple d3d;
// Initialize Direct3D
if( d3d.create( hWnd ) )
{
Evidyon::EvidyonD3DRenderStateManager renderstate_manager;
Evidyon::TextureDescription td;
Evidyon::Scenery::EvidyonSceneryRenderer scenery_renderer;
td.flip_horizontal = false;
td.flip_vertical = false;
td.animation_type = Evidyon::TextureDescription::STATIC;
td.blend_type = Evidyon::TextureDescription::DISABLE_BLENDING;
renderstate_manager.create(d3d.getDevice());
D3DXCreateTextureFromFile(d3d.getDevice(), "grass.jpg", &td.d3d_texture);
renderstate_manager.addTexture(0, td);
D3DXCreateTextureFromFile(d3d.getDevice(), "dirt.png", &td.d3d_texture);
renderstate_manager.addTexture(1, td);
D3DXCreateTextureFromFile(d3d.getDevice(), "water-transparency.png", &td.d3d_texture);
td.animation_type = Evidyon::TextureDescription::CIRCLING;
td.animation.circling.radius = 0.5f;
td.animation.circling.speed = 0.5f;
td.blend_type = Evidyon::TextureDescription::ALPHABLEND;
renderstate_manager.addTexture(2, td);
Evidyon::EvidyonD3DLightManager light_manager;
light_manager.create(d3d.getDevice());
Evidyon::EvidyonD3DLightManager::PointLight* light =
light_manager.allocateSmallLight(D3DCOLOR_XRGB(255,0,0));
light->h = 0.0f;
light->v = 0.0f;
EvidyonCamera camera;
// Show the window
ShowWindow( hWnd, SW_SHOWDEFAULT );
UpdateWindow( hWnd );
DWORD start = GetTickCount();
// Enter the message loop
MSG msg;
ZeroMemory( &msg, sizeof( msg ) );
while( msg.message != WM_QUIT )
{
if( PeekMessage( &msg, NULL, 0U, 0U, PM_REMOVE ) )
{
TranslateMessage( &msg );
DispatchMessage( &msg );
}
else {
LPDIRECT3DDEVICE9 d3d_device = d3d.getDevice();
camera.initialize3DRendering(d3d_device);
if (SUCCEEDED(d3d_device->BeginScene())) {
d3d_device->Clear(0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(0,0,0), 1.0f, 0);
float x = + 3*sin(GetTickCount()/2000.0);
float y = + 4*cos(GetTickCount()/2000.0);
map.update(x,y+0.5f);
light->h = sinf(GetTickCount() / 250.0f);
light_manager.updateAmbientLight(GetTickCount()/1000.0);
light_manager.beginScene(x, y);
camera.setPosition(x, y);
renderstate_manager.beginScene();
scenery_renderer.beginScene();
d3d_device->EndScene();
d3d_device->Present(NULL, NULL, NULL, NULL);
}
}
}
light_manager.destroy();
renderstate_manager.destroy();
map.destroy();
}
d3d.destroy();
UnregisterClass( "D3D Tutorial", wc.hInstance );
return 0;
}
| [
"karlgluck@gmail.com"
] | karlgluck@gmail.com |
1294d76142fff576d167cb0d34d5992fb30de39c | 5456502f97627278cbd6e16d002d50f1de3da7bb | /base/task_scheduler/task_unittest.cc | 7baf4ce366cf369cfa755e1b6f35721a7a7f6cea | [
"BSD-3-Clause"
] | permissive | TrellixVulnTeam/Chromium_7C66 | 72d108a413909eb3bd36c73a6c2f98de1573b6e5 | c8649ab2a0f5a747369ed50351209a42f59672ee | refs/heads/master | 2023-03-16T12:51:40.231959 | 2017-12-20T10:38:26 | 2017-12-20T10:38:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,735 | cc | // Copyright 2016 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 "base/task_scheduler/task.h"
#include "base/bind.h"
#include "base/location.h"
#include "base/task_scheduler/task_traits.h"
#include "base/time/time.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace base {
namespace internal {
// Verify that the shutdown behavior of a BLOCK_SHUTDOWN delayed task is
// adjusted to SKIP_ON_SHUTDOWN. The shutown behavior of other delayed tasks
// should not change.
TEST(TaskSchedulerTaskTest, ShutdownBehaviorChangeWithDelay) {
Task continue_on_shutdown(FROM_HERE, Bind(&DoNothing),
TaskTraits().WithShutdownBehavior(
TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN),
TimeDelta::FromSeconds(1));
EXPECT_EQ(TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN,
continue_on_shutdown.traits.shutdown_behavior());
Task skip_on_shutdown(
FROM_HERE, Bind(&DoNothing),
TaskTraits().WithShutdownBehavior(TaskShutdownBehavior::SKIP_ON_SHUTDOWN),
TimeDelta::FromSeconds(1));
EXPECT_EQ(TaskShutdownBehavior::SKIP_ON_SHUTDOWN,
skip_on_shutdown.traits.shutdown_behavior());
Task block_shutdown(
FROM_HERE, Bind(&DoNothing),
TaskTraits().WithShutdownBehavior(TaskShutdownBehavior::BLOCK_SHUTDOWN),
TimeDelta::FromSeconds(1));
EXPECT_EQ(TaskShutdownBehavior::SKIP_ON_SHUTDOWN,
block_shutdown.traits.shutdown_behavior());
}
// Verify that the shutdown behavior of undelayed tasks is not adjusted.
TEST(TaskSchedulerTaskTest, NoShutdownBehaviorChangeNoDelay) {
Task continue_on_shutdown(FROM_HERE, Bind(&DoNothing),
TaskTraits().WithShutdownBehavior(
TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN),
TimeDelta());
EXPECT_EQ(TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN,
continue_on_shutdown.traits.shutdown_behavior());
Task skip_on_shutdown(
FROM_HERE, Bind(&DoNothing),
TaskTraits().WithShutdownBehavior(TaskShutdownBehavior::SKIP_ON_SHUTDOWN),
TimeDelta());
EXPECT_EQ(TaskShutdownBehavior::SKIP_ON_SHUTDOWN,
skip_on_shutdown.traits.shutdown_behavior());
Task block_shutdown(
FROM_HERE, Bind(&DoNothing),
TaskTraits().WithShutdownBehavior(TaskShutdownBehavior::BLOCK_SHUTDOWN),
TimeDelta());
EXPECT_EQ(TaskShutdownBehavior::BLOCK_SHUTDOWN,
block_shutdown.traits.shutdown_behavior());
}
} // namespace internal
} // namespace base
| [
"lixiaodonglove7@aliyun.com"
] | lixiaodonglove7@aliyun.com |
c212f4fc3bb1e4eaf98f20ed9756255257244900 | 866bcfa5799811c9ca18466b95b5ea9e78b7e3f8 | /joueur.cpp | 38ed9c94c21e18c00b32090ed750e93bfd850874 | [] | no_license | ElhadjBarry/Jeu_Bataille_Navale | 1532285040efd8a0dbc2a762f11675d2dc62d4bb | 4f8c3354067190e1ec3f100722cee483d4885786 | refs/heads/master | 2022-04-17T06:21:13.769486 | 2020-04-13T13:37:04 | 2020-04-13T13:37:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,133 | cpp | #include "joueur.h"
Joueur::Joueur() {
init(0);
};
void Joueur::init(int windowDim) {
selectionPosition = 0;
for(int i=0; i<5; i++)
selectionState[i] = false;
map.init(-1);
carteTemporaire.init(-1);
mask.init(-1);
score.setValeur(windowDim * windowDim);
}
bool Joueur::validerCarteTempo(int windowDim) {
for(int i=0; i<windowDim; i++) {
for(int j=0; j<windowDim; j++) {
if((carteTemporaire.getCell(i,j)!=-1) && (map.getCell(i, j) != -1)) {
return false;
}
}
}
for(int i=0; i<windowDim; i++) {
for(int j=0; j<windowDim; j++) {
if(carteTemporaire.getCell(i,j)!=-1) {
map.setCell(i,j,carteTemporaire.getCell(i, j));
}
}
}
return true;
}
bool Joueur::selectionPrete() {
for(int i=0; i<5; i++)
if(selectionState[i] == false) { return false; }
return true;
}
void Joueur::genererMask() {
mask.init(0);
}
void Joueur::setNomJouer(std::string nomJoueur) {this->nomJoueur = nomJoueur;}
void Joueur::setSelectionState(int pos, bool value) {selectionState[pos] = value;}
void Joueur::setSelectionPosition(int selectionPosition) { this->selectionPosition = selectionPosition;}
void Joueur::setMap(TerritoireMaritime &map) {this->map = map;}
void Joueur::setCarteTempo(TerritoireMaritime &carteTemporaire) {this->carteTemporaire = carteTemporaire;}
void Joueur::setMask(TerritoireMaritime &mask) {this->mask = mask;}
void Joueur::setControleOrdinateur(bool controleOrdinateur) {this->controleOrdinateur = controleOrdinateur;}
void Joueur::setScore(int value) {score.setValeur(value);}
std::string Joueur::getNomJoueur() {return nomJoueur;}
int Joueur::getSelectionState(int pos) {return selectionState[pos];}
int Joueur::getSelectionPosition() { return selectionPosition;}
TerritoireMaritime& Joueur::getMap() {return map;}
TerritoireMaritime& Joueur::getTempMap() {return carteTemporaire;}
TerritoireMaritime& Joueur::getMask() { return mask;}
bool Joueur::getControleOrdinateur() {return controleOrdinateur;}
int Joueur::getScore() {return score.getValeur();}
| [
"elhadj.barry@primetals.com"
] | elhadj.barry@primetals.com |
8bfc01b6dc98c3564a5bebac8750952e3719743e | de3747ec657322a0b70ebb9c6fc83d736d62e17e | /AtCoder/abc/abc042/b.cpp | e74884559e6c5e9c2d13c2e66cbcaf67b6ce2a69 | [] | no_license | pocket7878/compp | 66434391558817c965c4c7778a3b550d6004a099 | c5d04ec6c23a92f30f0455de53973499b7f62ec3 | refs/heads/master | 2021-05-01T23:45:09.987419 | 2017-01-05T04:39:05 | 2017-01-05T04:39:05 | 77,890,970 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 352 | cpp | #include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
int n, l;
vector<string> lines;
cin >> n >> l;
for(int i = 0; i < n; i++) {
string line;
cin >> line;
lines.push_back(line);
}
sort(lines.begin(), lines.end());
for(int i = 0; i < n; i++) {
cout << lines[i];
}
cout << endl;
}
| [
"poketo7878@gmail.com"
] | poketo7878@gmail.com |
7207cd4bf70f1325321fd9a8044e348bb1a8fe9a | 48da3cf76d6932e643824e8538bfad5529cf335a | /.svn/pristine/72/7207cd4bf70f1325321fd9a8044e348bb1a8fe9a.svn-base | d3e557483d5ec62d2c2a4a4fe6fcb2eac119581a | [] | no_license | daxingyou/sg_server | 932c84317210f7096b97f06c837e9e15e73809bd | 2bd0a812f0baeb31dc09192d0e88d47fde916a2b | refs/heads/master | 2021-09-19T16:01:37.630704 | 2018-07-28T09:27:09 | 2018-07-28T09:27:09 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,375 | #ifndef __COMMON_FAMILY_CODE__
#define __COMMON_FAMILY_CODE__
#include "macros.hpp"
enum family_officer_type : uint32_t
{
family_officer_type_none = 0, // 默认值
family_officer_type_general = 1, // 族长
family_officer_type_vice_general = 2, // 副族长
family_officer_type_elit = 3, // 长老
family_officer_type_member = 4, // 成员
family_officer_type_newbie = 5, // 学徒
};
enum family_privilige_type : uint32_t
{
privilige_type_family_assign_vice_general = 1, // 任命副族长
privilige_type_family_assign_elite = 2, // 任命长老
privilige_type_family_accept_member = 3, // 升为成员
privilige_type_family_accuse_general = 4, // 弹劾族长
privilige_type_family_remove_member = 5, // 开除
privilige_type_family_silent = 6, // 禁言
privilige_type_family_assign_new_general = 7, // 任命新族长
privilige_type_family_member_audit = 8, // 同意
privilige_type_family_modify_name = 9, // 修改家族名称
privilige_type_family_modify_notice = 10, // 修改家族公告
privilige_type_family_modify_declaration = 11, // 修改家族宣言
privilige_type_family_build = 12, // 家族建设
privilige_type_family_quit = 13, // 退出家族
privilige_type_family_fire_activity = 14, // 开启篝火
privilige_type_family_dispatch_case = 15, // 分配宝箱
};
#endif
| [
"major@fun2"
] | major@fun2 | |
8247fc4b5b3a90debabe152e1e98593c92aba767 | 7d1b179386a19c0510807bf506ee5935c243d814 | /qt/serialport/serialWidget.cpp | fdd4325f9cac3c641f42694a2e815fdfb8d8ce99 | [] | no_license | zuokong2006/imx | 880f007b8751a5051a18dda949ad8ac900599240 | 8f1b85b86955c1010442b767bb0e1b76c3de4ec5 | refs/heads/master | 2021-01-16T19:34:09.015279 | 2015-05-24T14:44:48 | 2015-05-24T14:44:48 | 23,056,198 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 708 | cpp | #include "serialWidget.h"
#include <QDebug>
SerialWidget::SerialWidget(QWidget * parent)
: QStackedWidget(parent)
{
setWidget = new SerialSet;
this->addWidget(setWidget);
transWidget = new SerialTrans;
this->addWidget(transWidget);
connect(setWidget, SIGNAL(serialDataSeted(SerialData)), this, SLOT(startTrans(SerialData)));
connect(transWidget, SIGNAL(serialClosed()), this, SLOT(endTrans()));
}
void SerialWidget :: startTrans(SerialData data)
{
transWidget->setSerialData(data);
if (transWidget->openSerial() == false ) {
return ;
}
this->setCurrentWidget(transWidget);
}
void SerialWidget :: endTrans()
{
this->setCurrentWidget(setWidget);
}
| [
"zuokong2006@163.com"
] | zuokong2006@163.com |
88dfe865d530043883df96d858481ebb2912b338 | d664a04decf43ee0905a9f71b5c73a8de1fc2236 | /tests/3-test-move-ctor.cpp | d9cb0334af581e5c2228b7258466133f1e31f5b9 | [] | no_license | akhilkh2000/generic-avl-project | 81061452e9b756952ba2a8c1aedf1485c143ab3c | c3176d70f1fe89ad5c0fd20aa16574442db56060 | refs/heads/main | 2023-04-12T16:26:10.232044 | 2021-05-04T07:14:30 | 2021-05-04T07:14:30 | 363,945,449 | 0 | 0 | null | 2021-05-03T14:10:15 | 2021-05-03T13:50:44 | null | UTF-8 | C++ | false | false | 653 | cpp | #include <bits/stdc++.h>
#include "../generic_avl.h"
using namespace std;
int main()
{
AVL<int> bt = AVL<int>();
vector<int> arr = {80, 51, 95, 29, 66, 89, 99, 6, 40, 71, 94, 98};
for (int ele : arr)
{
bt.insert(ele);
}
cout << "Elements in bt: ";
for (int ele : bt)
{
cout << ele << " ";
}
cout << endl;
AVL<int> new_bt(move(bt));
cout << "After moving\n";
cout << "Elements in bt: ";
for (int ele : bt)
cout << ele << " ";
cout << endl;
cout << "Elements in new_bt: ";
for (int ele : new_bt)
cout << ele << " ";
cout << endl;
return 0;
} | [
"akhilkhubchandani@gmail.com"
] | akhilkhubchandani@gmail.com |
438df28a0af650b52d36ebbd7656fdc5ca06b677 | 6f535f3a4df658aeb0385379dfae9fb6b17004ae | /TP4Depart/TP4Code/PrimitiveAbs.cpp | f11a910d1fb2ee55f1e6ada79522afeaccfcb55c | [] | no_license | nmhjoyal/LOG2410 | c020754a191a5a96ad2da211275d1fddcf9a0edb | 70442d42ab745230384aefb8d5b0d4e4123a8405 | refs/heads/master | 2021-10-03T10:42:30.635189 | 2018-12-02T22:14:22 | 2018-12-02T22:14:22 | 149,922,651 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,469 | cpp | ///////////////////////////////////////////////////////////
// PrimitiveAbs.cpp
// Implementation of the Class PrimitiveAbs
// Created on: 25-oct.-2018 20:47:13
// Original author: p482457
///////////////////////////////////////////////////////////
#include "PrimitiveAbs.h"
// Declaration d'un conteneur vide pour retourner des iterateurs toujours valides
Objet3DContainer PrimitiveAbs::m_emptyContainer;
PrimitiveAbs::PrimitiveAbs(){
}
PrimitiveAbs::PrimitiveAbs(const Point3D& c)
// A Completer...
{
}
PrimitiveAbs::~PrimitiveAbs(){
}
void PrimitiveAbs::addChild(const Objet3DAbs& obj3d){
// Echoue silencieusement
}
Objet3DIterator PrimitiveAbs::begin(){
// A Completer...
return Objet3DBaseIterator();
}
Objet3DIterator_const PrimitiveAbs::cbegin() const {
// A Completer...
return Objet3DBaseIterator();
}
Objet3DIterator_const PrimitiveAbs::cend() const {
// A Completer...
return Objet3DBaseIterator();
}
Objet3DIterator PrimitiveAbs::end(){
// A Completer...
return Objet3DBaseIterator();
}
void PrimitiveAbs::removeChild(Objet3DIterator_const obj3dIt){
// Echoue silencieusement
}
Point3D PrimitiveAbs::getCenter() const {
// A Completer...
return Point3D();
}
void PrimitiveAbs::moveCenter(const Point3D & delta)
{
// A Completer...
}
void PrimitiveAbs::setCenter(const Point3D& center)
{
// A Completer...
}
std::ostream & operator<<(std::ostream & o, const Objet3DAbs& obj3d )
{
return obj3d.toStream(o);
}
| [
"nicole.joyal@oronospolytechnique.com"
] | nicole.joyal@oronospolytechnique.com |
630ecee281c2103a5aaa8ab5a583001b27c2da24 | 166630e79591940c4e960fdac03c99279ad45fdb | /main.cpp | c15657a0ad888b287c4e5806150721e4f73e7160 | [
"MIT"
] | permissive | calculuswhiz/turmite-sandbox | 70cbf4479487e8a8ef425b4b0c401f35bac9ba39 | 0b1b3c9ec28c021e463fd12bd3db345870e88ae0 | refs/heads/master | 2021-01-20T11:14:10.109114 | 2018-09-21T03:49:17 | 2018-09-21T03:49:17 | 83,946,098 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,929 | cpp | #include <cstring>
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <GL/gl.h>
#include <GL/freeglut.h>
#include "Automaton.h"
#include "Statenode.h"
#define GRIDW 2048
#define GRIDH 1024
#define WHEEL_UP 3
#define WHEEL_DOWN 4
int FRAMESPEED = 60000;
int updateTick = 0;
int updatePeriod = FRAMESPEED / 20;
using namespace std;
vector<Automaton *> sandbox;
int selector = 0;
int maxselector = 0;
bool paused = 0;
int alive = 0;
// The 3 is for the colors
GLfloat grid[GRIDH][GRIDW][3];
void display();
void printGrid()
{
for (int x = 0; x < GRIDW; x++)
{
for (int y = 0; y < GRIDH; y++)
{
cout << grid[0][y][x] / 255;
}
cout << endl;
}
cout << endl;
}
bool initGL()
{
//Initialize Projection Matrix
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
//Initialize Modelview Matrix
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
float aspect = (float)GRIDW / (float)GRIDH;
// glOrtho(-aspect, aspect, -1, 1, -1, 1);
glOrtho(0, aspect, aspect, 0, -1, 1);
glRasterPos2f(0, 0);
glPixelZoom(1, -1);
gluLookAt(0, 0, 1, 0, 0, 0, 0, 1, 0);
//Initialize clear color
glClearColor(0.f, 0.f, 0.f, 1.f);
//Check for error
GLenum error = glGetError();
if (error != GL_NO_ERROR)
{
printf( "Error initializing OpenGL! %s\n", gluErrorString( error ) );
return false;
}
return true;
}
void update()
{
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
float aspect = (float)GRIDW / (float)GRIDH;
glOrtho(0, aspect, aspect, 0, -1, 1);
// glOrtho(-aspect, aspect, -1, 1, -1, 1);
if (paused)
{
return;
}
alive = 0;
for(vector<Automaton *>::iterator it = sandbox.begin(); it != sandbox.end(); it += 1)
{
if ((*it)->isDead())
{
continue;
}
if ((*it)->posx >= 0 && (*it)->posy >= 0 && (*it)->posx < GRIDW && (*it)->posy < GRIDH)
{
GLfloat * cache = grid[(*it)->posy][(*it)->posx];
GLfloat inputmode = cache[0] || cache[1] || cache[2];
GLfloat shouldpaint = (GLfloat)(*it)->shouldWrite(inputmode);
GLfloat * wcolor = (*it)->color;
cache[0] = shouldpaint * wcolor[0];
cache[1] = shouldpaint * wcolor[1];
cache[2] = shouldpaint * wcolor[2];
(*it)->transition(inputmode);
alive += 1;
}
else
{
(*it)->kill();
}
}
// Don't touch originally loaded.
for (int i = sandbox.size() - 1; i >= maxselector; i--)
{
if (sandbox[i]->isDead())
{
delete (sandbox[i]);
sandbox.erase(sandbox.begin() + i);
}
}
}
void runMainLoop(int val)
{
//Frame logic
update();
if ((updateTick++) % updatePeriod == 0)
{
display();
}
//Run frame one more time
glutTimerFunc( 1000 / FRAMESPEED, runMainLoop, val );
}
// Totally swiped this from StackOverflow:
void renderText(float x, float y, const char* text)
{
x /= GRIDW;
y /= GRIDH;
glRasterPos2f(x, y);
glutBitmapString(GLUT_BITMAP_8_BY_13, (const unsigned char*)text);
glRasterPos2f(0, 0);
}
#define FONT_WIDTH 16
#define FONT_HEIGHT 20
void display()
{
// glClearColor( 0, 0, 0, 1 );
glClear(GL_COLOR_BUFFER_BIT);
glDrawPixels(GRIDW, GRIDH, GL_RGB, GL_FLOAT, grid);
// Text data
char selectionbuf[255];
char speedbuf[32];
sprintf(selectionbuf, "%s", sandbox[selector]->name.c_str());
sprintf(speedbuf, "Speed %d", FRAMESPEED);
renderText(0, FONT_HEIGHT, "Click will spawn: ");
glColor3f(sandbox[selector]->color[0], sandbox[selector]->color[1], sandbox[selector]->color[2]);
renderText(FONT_WIDTH * 18, FONT_HEIGHT, selectionbuf);
glColor3f(1, 1, 1);
renderText(0, 2 * FONT_HEIGHT, speedbuf);
char alivetext[4];
sprintf(alivetext, "%d", alive);
renderText(0, FONT_HEIGHT * 3, "Alive: ");
renderText(FONT_WIDTH * 7, FONT_HEIGHT * 3, alivetext);
if (paused)
{
char freezu[] = "Za Warudo! Toki yo tomare!";
renderText(0, FONT_HEIGHT * 4, freezu);
}
glutSwapBuffers();
}
void keybd(unsigned char key, int x, int y)
{
switch(key)
{
case 'p':
paused ^= true;
break;
case 'q':
cout << "Terminating..." << endl;
exit(0);
break;
case '+':
// cout << "Speed up?" << endl;
FRAMESPEED *= 1.1;
updatePeriod = FRAMESPEED / 20;
break;
case '-':
if (FRAMESPEED > 100)
{
FRAMESPEED /= 1.1;
updatePeriod = FRAMESPEED / 20;
}
break;
default:
cout << key << " was pressed!" << endl;
break;
}
}
void mouser(int button, int state, int x, int y)
{
switch(button)
{
case GLUT_LEFT_BUTTON:
if (state == GLUT_UP)
{
Automaton * spawn = new Automaton(*sandbox[selector]);
spawn->posx = x;
spawn->posy = y;
spawn->name = sandbox[selector]->name + "_" + to_string((long) spawn);
cout << "Spawning in: " << spawn->name << " at " << x << " " << y << endl;
spawn->raise();
sandbox.push_back(spawn);
}
break;
case WHEEL_UP:
if (state == GLUT_UP)
{
selector = (selector - 1);
if (selector < 0)
{
selector = maxselector - 1;
}
cout << "Now selected: " << sandbox[selector]->name << endl;
}
break;
case WHEEL_DOWN:
if (state == GLUT_UP)
{
selector = ((selector+1)%maxselector);
cout << "Now selected: " << sandbox[selector]->name << endl;
}
break;
default:
break;
}
}
string strip(string str)
{
size_t first = str.find_first_not_of(' ');
if (string::npos == first)
{
return str;
}
size_t last = str.find_last_not_of(' ');
return str.substr(first, last - first + 1);
}
int main(int argc, char *argv[])
{
if (argc == 1)
{
cout << "Need file args. 1st is the automaton file, 2nd is the grid config file." << endl;
return 1;
}
if (argc >= 2)
{
// Parse Automaton file
ifstream automatonFileStream(string(argv[1]), ifstream::in);
string line;
Automaton * addme;
while (getline(automatonFileStream, line))
{
line = strip(line);
if (line[0] == '#' || line.size() == 0)
{
continue;
}
if (line.find("[Automaton]") == 0)
{
addme = new Automaton();
cout << "Constructing Automaton." << endl;
}
else if (line.find("[Name]") == 0)
{
string name = line.substr(line.find(" ") + 2);
name = name.substr(0, name.size() - 1);
cout << "Name found: " << name << endl;
addme->name = name;
}
else if (line.find("[Color]") == 0)
{
stringstream ss;
ss.str(line);
string temp;
float r, g, b;
ss >> temp >> r >> g >> b;
addme->color[0] = r;
addme->color[1] = g;
addme->color[2] = b;
cout << "Float Color (r,g,b): " << r << " " << g << " " << b << endl;
}
else if (line.find("[Start]") == 0)
{
stringstream ss;
ss.str(line);
int x, y, state;
string temp;
string orientation;
ss >> temp >> x >> y >> state >> orientation;
addme->posx = x;
addme->posy = y;
addme->curState = state;
addme->setDirFromString(orientation);
addme->initialOrientation = addme->orientation;
cout << "Start info (x,y,state,orientation): " << x << " " << y << " " << state << " " << orientation << endl;
}
else if (line.find("[State]") == 0)
{
stringstream ss;
ss.str(line);
int nsOff, nsOn, wOff, wOn;
string tOff, tOn;
string temp;
ss >> temp >> nsOff >> nsOn >> tOff >> tOn >> wOff >> wOn;
addme->addState(nsOff, nsOn, addme->getTurnFromString(tOff), addme->getTurnFromString(tOn), wOff, wOn);
cout << "Add state (nsOff, nsOn, tOff, tOn, wOff, wOn): " << nsOff << " " << nsOn << " " << tOff << " " << tOn << " " << wOff << " " << wOn << endl;
}
else if (line.find("[Debug]") == 0)
{
addme->silent = false;
cout << "State debug mode on\n";
}
else if (line.find("[/Automaton]") == 0)
{
sandbox.push_back(addme);
cout << "Automaton constructed\n\n";
}
else
{
cout << "Bad line: " << line << endl;
return 1;
}
}
}
if (argc >= 3)
{
// Clear grid
memset(grid, 0, 3 * GRIDW * GRIDH * sizeof(bool));
cout << "Parsing Grid file...\n";
// Parse grid configuration file
ifstream gridConfigFileStream(string(argv[2]), ifstream::in);
string line;
float red = 1, green = 1, blue = 1;
while (getline(gridConfigFileStream, line))
{
line = strip(line);
if (line[0] == '#' || line.size() == 0)
{
continue;
}
else if (line.find("[Color]") == 0)
{
stringstream ss;
ss.str(line);
string temp;
ss >> temp >> red >> green >> blue;
cout << "Float Color (r,g,b): " << red << " " << green << " " << blue << endl;
}
else if (line.find("[Rect]") == 0)
{
stringstream ss;
ss.str(line);
string temp;
int x, y, w, h;
ss >> temp >> x >> y >> w >> h;
for (int i = 0; i < w; i++)
{
for (int j = 0; j < h; j++)
{
grid[y + j][x + i][0] = red;
grid[y + j][x + i][1] = green;
grid[y + j][x + i][2] = blue;
cout << "Setting Cell: " << (x + i) << " " << (y + j) << endl;
}
}
}
else
{
cout << "Bad line: " << line << endl;
return 1;
}
}
}
maxselector = sandbox.size();
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
glutInitWindowSize(GRIDW, GRIDH);
glutCreateWindow("Turmite Simulator 2017 (2018 edition)");
glutKeyboardFunc(keybd);
glutMouseFunc(mouser);
//Do post window/context creation initialization
if (!initGL())
{
printf("Unable to initialize graphics library!\n");
return 1;
}
glutDisplayFunc(display);
glutTimerFunc(1000 / FRAMESPEED, runMainLoop, 0);
//Set main loop
glutMainLoop();
return 0;
}
| [
"calculuswhiz@gmail.com"
] | calculuswhiz@gmail.com |
9cff47aae38a0bd0bec0dd7a22d11254a798a1cb | d95f4d9c2f8cdd4418586ceb6c8057b71e9c3075 | /src/extended_photo/photographers.cpp | 4c15da051f09177cfaa93c9202601aaa86a10591 | [] | no_license | srpgilles/pict_stock | 8e6a72feaf13e1b6a96efedd0529356552bb86e7 | e72cc0cc00f9d306e6d692295a098957c1bb9628 | refs/heads/master | 2021-01-18T14:09:42.603942 | 2012-10-21T12:36:24 | 2012-10-21T12:36:24 | 4,065,620 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,296 | cpp | #include "photographers.hpp"
#include "../tools/sqlite_wrapper.hpp"
namespace PictStock
{
namespace ExtendedPhoto
{
using namespace TablePhotographers;
Photographers::Photographers(GenericTools::SqliteWrapper& database)
: pDatabase(database)
{
{
// Request from the database
YString command;
{
std::vector<YString> fields;
Private::TupleFields<Tuple>::FieldNames(fields);
std::for_each(fields.begin(), fields.end(), [&command](const YString& elt)
{
command << elt << ',';
});
command.removeLast();
command << " FROM " << TableName() << " ORDER BY " << Abbreviation::FieldName() << ';';
}
{
std::vector<TupleWrappedType> buf;
database.select(buf, command);
pData.reserve(buf.size());
std::for_each(buf.begin(), buf.end(), [&pData](const TupleWrappedType& tuple)
{
pData.push_back(new Photographer(tuple));
}
);
}
}
}
void Photographers::addNewPhotographer(const FirstName::WrappedType& firstName,
const LastName::WrappedType& lastName,
const Abbreviation::WrappedType& abbreviation)
{
// Determine names of the fields in the database
std::vector<YString> fieldNames;
Private::TupleFields<Tuple>::FieldNames(fieldNames);
// Create a tuple with new elements to introduce
TupleWrappedType newTuple;
std::get<GenericTools::IndexOf<FirstName, Tuple>::value>(newTuple) = firstName;
std::get<GenericTools::IndexOf<LastName, Tuple>::value>(newTuple) = lastName;
std::get<GenericTools::IndexOf<Abbreviation, Tuple>::value>(newTuple) = abbreviation;
// Add the photographer in the database (which will check by the way if the insertion is legit or not)
pDatabase.insertData(TableName(), fieldNames, newTuple);
}
bool Photographers::findPhotographer(Photographer::Ptr& photographer,
const TablePhotographers::Abbreviation::WrappedType& abbreviation) const
{
auto end = pData.cend();
auto it = std::find_if(pData.cbegin(), end,
[&abbreviation](const Photographer::Ptr& photographer) -> bool
{
return photographer->abbreviation() == abbreviation;
}
);
if (it == end)
{
photographer = nullptr;
return false;
}
photographer = *it;
assert(!(!photographer));
return true;
}
} // namespace ExtendedPhoto
} // namespace PictStock
| [
"srpgilles@gmail.com"
] | srpgilles@gmail.com |
b309c3502a5aaa0aebdf3833aab75aae76b85769 | b7ded819bc689a97363879e97bd43ca9506c50b2 | /include/TOFPhysicsList.hh | 0d07f58905627a00593af8c044da20202c5b4ea0 | [] | no_license | zuranski/TOFSim | e6b54dbb63738ac75841c7288d45dfba4d1e66c6 | dfa0ad482ebd6845466d4f9c232f556c9792922f | refs/heads/master | 2016-08-04T23:23:29.008998 | 2013-09-07T14:43:57 | 2013-09-07T14:43:57 | 12,547,629 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,090 | hh | #ifndef TOFPhysicsList_h
#define TOFPhysicsList_h 1
#include "globals.hh"
#include "G4VUserPhysicsList.hh"
class G4Cerenkov;
class G4Scintillation;
class G4OpAbsorption;
class G4OpRayleigh;
class G4OpBoundaryProcess;
class TOFPhysicsList : public G4VUserPhysicsList
{
public:
TOFPhysicsList();
~TOFPhysicsList();
public:
void ConstructParticle();
void ConstructProcess();
void SetCuts();
//these methods Construct particles
void ConstructBosons();
void ConstructLeptons();
void ConstructMesons();
void ConstructBaryons();
//these methods Construct physics processes and register them
void ConstructGeneral();
void ConstructEM();
void ConstructOp();
//for the Messenger
void SetVerbose(G4int);
void SetNbOfPhotonsCerenkov(G4int);
private:
G4Cerenkov* theCerenkovProcess;
G4Scintillation* theScintillationProcess;
G4OpAbsorption* theAbsorptionProcess;
G4OpRayleigh* theRayleighScatteringProcess;
G4OpBoundaryProcess* theBoundaryProcess;
};
#endif
| [
"zuranski@princeton.edu"
] | zuranski@princeton.edu |
f54dd245ce41245a5e7417c73f7e80ef9751ae33 | c38297ce87809047243b3e851283e641179312a3 | /src/Storage/Storage.cpp | 0a78cede7b7a48c7e21f5de3f8b7cf7d8d17af59 | [
"MIT"
] | permissive | renowncoder/ChainDB | f208ee67fee81b43c37ed8d3c4559c24378030fd | 41fc13d8e0df776e66554c8eeed5c22e4ac3900e | refs/heads/main | 2023-04-13T10:18:33.819521 | 2021-04-29T10:28:34 | 2021-04-29T10:28:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,193 | cpp | /*
Copyright (c) 2021 Stanislav Yakush (st.yakush@yandex.ru)
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 "Storage/Storage.h"
#include "System/Logger.h"
using namespace Core::Storage;
Storage::KeyValue::KeyValue(const Data& key, const Data& value) :
_key(key),
_value(value)
{
}
Storage::KeyValue::~KeyValue()
{
}
Storage::KeyValue::Data Storage::KeyValue::getKey() const
{
return _key;
}
Storage::KeyValue::Data Storage::KeyValue::getValue() const
{
return _value;
}
Storage::Storage(const std::string& path) :
_path(path),
_db(nullptr)
{
}
Storage::~Storage()
{
if (_db)
{
delete _db;
}
}
bool Storage::create()
{
if (_db)
{
Logger::error("DB already open (Path: {})", _path);
return false;
}
DB::Options options;
options.create_if_missing = true;
options.error_if_exists = true;
options.paranoid_checks = true;
options.compression = DB::kNoCompression;
const DB::Status status = DB::DB::Open(options, _path, &_db);
if (!status.ok())
{
Logger::error("Can\'t create DB ({})", status.ToString());
return false;
}
return true;
}
bool Storage::open()
{
if (_db)
{
Logger::error("DB already open (Path: {})", _path);
return false;
}
DB::Options options;
options.paranoid_checks = true;
options.compression = DB::kNoCompression;
const DB::Status status = DB::DB::Open(options, _path, &_db);
if (!status.ok())
{
Logger::error("Can\'t open DB ({})", status.ToString());
return false;
}
return true;
}
bool Storage::close()
{
if (!_db)
{
Logger::error("DB is not open (Path: {})", _path);
return false;
}
delete _db;
_db = nullptr;
return true;
}
Storage::KeyValue::Ptr Storage::get(const KeyValue::Data& key) const
{
if (!_db)
{
Logger::error("DB is not open (Path: {})", _path);
return nullptr;
}
DB::ReadOptions readOptions;
readOptions.verify_checksums = true;
std::string value;
const DB::Status status = _db->Get(readOptions, key, &value);
if (!status.ok())
{
Logger::error("Can\'t get value ({})", status.ToString());
return nullptr;
}
return std::make_shared<Storage::KeyValue>(key, value);
}
bool Storage::set(const KeyValueList& pairs) const
{
if (!_db)
{
Logger::error("DB is not open (Path: {})", _path);
return false;
}
DB::WriteBatch batch;
for (const KeyValue& pair : pairs)
{
batch.Put(pair.getKey(), pair.getValue());
}
DB::WriteOptions writeOptions;
writeOptions.sync = true;
const DB::Status status = _db->Write(writeOptions, &batch);
if (!status.ok())
{
Logger::error("Can\'t set value ({})", status.ToString());
return false;
}
return true;
}
bool Storage::remove() const
{
const DB::Status status = DB::DestroyDB(_path, DB::Options());
if (!status.ok())
{
Logger::error("Can\'t remove DB ({})", status.ToString());
return false;
}
return true;
} | [
"st.yakush@yandex.ru"
] | st.yakush@yandex.ru |
89384fb720915c73cba3587f61f627eadc58f5fc | 8862e2d170e6eb8c0c58325e01bfc0180245c6b5 | /logger.cpp | 38d9fc620d4495fe02f345840f9afee4e7a35822 | [] | no_license | zhu-ty/FileSaveSimulator | d88487be5b54d65ddefd90989f7af45df90e4097 | 38761060f4246e2f15468d89f64c5a6490620314 | refs/heads/master | 2020-03-21T07:17:07.740889 | 2018-07-05T02:28:51 | 2018-07-05T02:28:51 | 138,271,840 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 64 | cpp | #include "logger.hpp"
std::string CLog::_log_file = "1.txt";
| [
"zhu-ty@outlook.com"
] | zhu-ty@outlook.com |
d151c167d3aff88cec8e7a2123b4c89d9929fd7b | 81ab7ee7f1b44ac3da70d5329301796ac1abd9a7 | /src/core/mini_bmk.hpp | 0accd8be6d08931e71fcabf2f67f762033b9e0ea | [
"MIT"
] | permissive | superestos/flashmob-test | 9d45be271ff995307eefcd9575fd624d5a7128d1 | 8d57be773c0128f8014c62ec94cfcbb73bc307ef | refs/heads/master | 2023-04-14T05:20:34.940424 | 2022-06-08T06:46:39 | 2022-06-08T06:46:39 | 436,540,049 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,505 | hpp | #pragma once
#include <math.h>
#include <sstream>
#include <map>
#include <set>
#include "timer.hpp"
#include "io.hpp"
#include "util.hpp"
#include "graph.hpp"
#include "sampler.hpp"
struct SampleEstimation {
SamplerClass sampler_class;
double step_time;
};
typedef std::map<vertex_id_t, std::map<vertex_id_t, std::vector<SampleEstimation> > > MiniBMKCatMap;
/**
* Manages mini benchmark results.
*
* It will first check ./.fmob/ directory to load previous results.
* Only if a data point has not been stored before, will it be profiled.
* Any new result will be store to files for future reference.
*
*/
class MiniBMKCatManager {
public:
struct MiniBMKItem {
vertex_id_t partition_bits;
vertex_id_t degree;
SamplerClass sampler_class;
double step_time;
bool friend operator < (const MiniBMKItem& a, const MiniBMKItem& b) {
if (a.partition_bits != b.partition_bits) {
return a.partition_bits < b.partition_bits;
}
if (a.degree != b.degree) {
return a.degree < b.degree;
}
return a.sampler_class < b.sampler_class;
}
MiniBMKItem(vertex_id_t _partition_bits, vertex_id_t _degree, SamplerClass _sampler_class, double _step_time = 0) {
partition_bits = _partition_bits;
degree = _degree;
sampler_class = _sampler_class;
step_time = _step_time;
}
MiniBMKItem() {}
};
private:
std::string cfg_name;
std::string cfg_dir;
std::string cfg_file;
std::set<MiniBMKItem> cat_set;
int new_item_num;
public:
MiniBMKCatManager (double walker_per_edge, MultiThreadConfig mtcfg) {
cfg_dir = FMobDir;
std::string cmd = std::string("mkdir -p ") + cfg_dir;
CHECK(0 == system(cmd.c_str()));
// log(walker_per_edge, 1.5) with precision of 0
double wpe_log = log(walker_per_edge) / log(1.5);
std::stringstream cfg_name_ss;
cfg_name_ss << std::fixed << std::setprecision(0) << wpe_log << "_" << mtcfg.socket_num << "_" << mtcfg.thread_num << ".txt";
cfg_name = cfg_name_ss.str();
cfg_file = cfg_dir + "/" + cfg_name;
LOG(WARNING) << block_mid_str(1) << "Mini-benchmark file: " << cfg_file;
FILE* f = fopen(cfg_file.c_str(), "r");
if (f != NULL) {
MiniBMKItem item;
uint32_t sampler_class;
while (4 == fscanf(f, "%u %u %u %lf", &item.partition_bits, &item.degree, &sampler_class, &item.step_time)) {
item.sampler_class = static_cast<SamplerClass>(sampler_class);
cat_set.insert(item);
}
fclose(f);
}
new_item_num = 0;
}
void get_catalogue(MiniBMKCatMap *cat_map) {
for (auto &item : cat_set) {
SampleEstimation est;
est.sampler_class = item.sampler_class;
est.step_time = item.step_time;
(*cat_map)[item.partition_bits][item.degree].push_back(est);
}
}
bool has_item(MiniBMKItem item) {
return cat_set.find(item) != cat_set.end();
}
void add_item(MiniBMKItem item) {
CHECK(cat_set.find(item) == cat_set.end());
cat_set.insert(item);
new_item_num ++;
}
void save_catalogue() {
LOG(WARNING) << block_mid_str(1) << "New mini benchmarks: " << new_item_num;
if (new_item_num != 0) {
FILE* f = fopen(cfg_file.c_str(), "w");
for (auto &item : cat_set) {
fprintf(f, "%u %u %u %lf\n", item.partition_bits, item.degree, item.sampler_class, item.step_time);
}
fclose(f);
}
}
};
/**
* A mocker of walk_message in WalkManager.
*
* Mini benchmark only tests partitions where #vertices, #edges, #walkers fall into
* certan ranges. The performance of partitions with too many/few vertices/edgtes/walkers
* could be inferred from the performance of other partitions.
*
*/
template<typename sampler_t>
void walk_message_mock(sampler_t *sampler, vertex_id_t *message_begin, vertex_id_t *message_end, vertex_id_t bitmask, default_rand_t *rd) {
for (vertex_id_t *msg = message_begin; msg < message_end; msg ++) {
*msg = sampler->sample((*msg) & bitmask, rd);
}
}
void mini_benchmark(
double walker_per_edge,
vertex_id_t max_degree,
vertex_id_t min_partition_vertex_bit,
vertex_id_t max_partition_vertex_bit,
MultiThreadConfig mtcfg,
std::map<vertex_id_t, std::map<vertex_id_t, std::vector<SampleEstimation> > > &results
) {
LOG(WARNING) << block_begin_str(1) << "Mini benchmarks";
struct BmkTask {
vertex_id_t ptn_bits;
SamplerClass sclass;
};
Timer benchmark_timer;
MiniBMKCatManager cat_manager(walker_per_edge, mtcfg);
const vertex_id_t internal_max_pt_bit = std::min(max_partition_vertex_bit, std::max(20u, min_partition_vertex_bit));
const edge_id_t thread_edge_num = 1ull << 24;
const vertex_id_t max_thread_vertex_num = 1 << internal_max_pt_bit;
const uint64_t max_thread_walker_num = thread_edge_num * walker_per_edge;
const vertex_id_t max_value = max_thread_vertex_num;
std::vector<vertex_id_t> test_degrees;
for (vertex_id_t d_i = 1; d_i <= max_degree;) {
test_degrees.push_back(d_i);
d_i = std::max(d_i + 1, (vertex_id_t) (d_i * 1.05));
}
std::map<vertex_id_t, std::vector<BmkTask> > bmk_tasks;
for (auto degree : test_degrees) {
for (vertex_id_t partition_bits = min_partition_vertex_bit; partition_bits <= internal_max_pt_bit; partition_bits++) {
vertex_id_t partition_vertex_num = 1 << partition_bits;
if ((uint64_t) partition_vertex_num * degree > thread_edge_num \
|| (uint64_t) partition_vertex_num * degree * walker_per_edge > max_thread_walker_num) {
continue;
}
uint64_t partition_walker_num = (uint64_t) partition_vertex_num * degree * walker_per_edge;
if (partition_walker_num < 1) {
continue;
}
BmkTask task;
task.ptn_bits = partition_bits;
if (!cat_manager.has_item(MiniBMKCatManager::MiniBMKItem(partition_bits, degree, ClassUniformDegreeDirectSampler))) {
task.sclass = ClassUniformDegreeDirectSampler;
bmk_tasks[degree].push_back(task);
}
if (degree > 4 && !cat_manager.has_item(MiniBMKCatManager::MiniBMKItem(partition_bits, degree, ClassExclusiveBufferSampler))) {
task.sclass = ClassExclusiveBufferSampler;
bmk_tasks[degree].push_back(task);
}
}
}
// Only allocate resources for mini benchmarks when there are new tests to run
if (bmk_tasks.size() > 0) {
MemoryPool mpool(mtcfg);
default_rand_t *rands[mtcfg.thread_num];
for (int t_i = 0; t_i < mtcfg.thread_num; t_i++) {
rands[t_i] = mpool.alloc_new<default_rand_t>(1, mtcfg.socket_id(t_i));
}
AdjList *adjlists[mtcfg.thread_num];
for (int t_i = 0; t_i < mtcfg.thread_num; t_i++) {
adjlists[t_i] = mpool.alloc_new<AdjList>(max_thread_vertex_num, mtcfg.socket_id(t_i));
}
AdjUnit *adjunits[mtcfg.thread_num];
for (int t_i = 0; t_i < mtcfg.thread_num; t_i++) {
adjunits[t_i] = mpool.alloc_new<AdjUnit>(thread_edge_num, mtcfg.socket_id(t_i));
}
vertex_id_t *walkers[mtcfg.thread_num];
for (int t_i = 0; t_i < mtcfg.thread_num; t_i++) {
walkers[t_i] = mpool.alloc_new<vertex_id_t>(max_thread_walker_num, mtcfg.socket_id(t_i));
}
#pragma omp parallel
{
int thread = omp_get_thread_num();
auto *rd = rands[thread];
for (edge_id_t e_i = 0; e_i < thread_edge_num; e_i++) {
adjunits[thread][e_i].neighbor = rd->gen(max_value);
}
for (walker_id_t w_i = 0; w_i < max_thread_walker_num; w_i++) {
walkers[thread][w_i] = rd->gen(max_value);
}
}
vertex_id_t progress = 0;
uint64_t rand_sum = 0;
volatile int finished_thread_num = 0;
std::mutex cat_manager_lock;
#pragma omp parallel reduction (+: rand_sum)
{
Timer thread_timer;
int thread = omp_get_thread_num();
int socket = mtcfg.socket_id(thread);
auto *rd = rands[thread];
vertex_id_t progress_i;
while((progress_i = __sync_fetch_and_add(&progress, 1)) < test_degrees.size()) {
vertex_id_t degree = test_degrees[progress_i];
if (bmk_tasks.find(degree) == bmk_tasks.end()) {
continue;
}
MemoryPool local_mpool(mtcfg);
for (vertex_id_t v_i = 0; v_i < max_thread_vertex_num; v_i++) {
adjlists[thread][v_i].begin = adjunits[thread] + v_i * degree;
adjlists[thread][v_i].degree = degree;
}
for (auto &task : bmk_tasks[degree]) {
vertex_id_t partition_vertex_num = 1 << task.ptn_bits;
uint64_t partition_walker_num = (uint64_t) partition_vertex_num * degree * walker_per_edge;
if (task.sclass == ClassUniformDegreeDirectSampler) {
UniformDegreeDirectSampler sampler;
sampler.init(0, partition_vertex_num, adjlists[thread]);
Timer timer;
uint64_t work = 0;
double work_time = 0;
uint32_t iter_num = std::max(4ul, (1ul << 20) / partition_walker_num);
for (vertex_id_t iter_i = 0; iter_i < iter_num; iter_i++) {
sampler.reset(0, partition_vertex_num, adjlists[thread]);
timer.restart();
walk_message_mock(&sampler, walkers[thread], walkers[thread] + partition_walker_num, partition_vertex_num - 1, rd);
work_time += timer.duration();
work += partition_walker_num;
}
double time = get_step_cost(work_time, work, 1);
cat_manager_lock.lock();
cat_manager.add_item(MiniBMKCatManager::MiniBMKItem(task.ptn_bits, degree, ClassUniformDegreeDirectSampler, time));
cat_manager_lock.unlock();
} else if (task.sclass == ClassExclusiveBufferSampler) {
ExclusiveBufferSampler sampler;
sampler.init(0, partition_vertex_num, adjlists[thread], &local_mpool, socket);
uint64_t work = 0;
double work_time = 0;
Timer timer;
vertex_id_t iter_num = std::max(4ul, std::max(1ul << 20, 4ul * sampler.buffer_unit_num) / partition_walker_num);
for (vertex_id_t iter_i = 0; iter_i < iter_num; iter_i++) {
sampler.reset(0, partition_vertex_num, adjlists[thread]);
timer.restart();
walk_message_mock(&sampler, walkers[thread], walkers[thread] + partition_walker_num, partition_vertex_num - 1, rd);
work_time += timer.duration();
work += partition_walker_num;
}
double time = get_step_cost(work_time, work, 1);
cat_manager_lock.lock();
cat_manager.add_item(MiniBMKCatManager::MiniBMKItem(task.ptn_bits, degree, ClassExclusiveBufferSampler, time));
cat_manager_lock.unlock();
}
}
}
__sync_fetch_and_add(&finished_thread_num, 1);
while (finished_thread_num != mtcfg.thread_num) {
for (int i = 0; i < 1024; i++) {
rand_sum += adjunits[thread][rd->gen(thread_edge_num)].neighbor;
}
}
//printf("Thread %d: %.3lf sec\n", thread, thread_timer.duration());
}
// To avoid rand_sum been optimized by compiler.
if ((rand_sum & 0xFFFFFF) == 0) {
LOG(INFO) << "Lucky";
}
}
cat_manager.save_catalogue();
cat_manager.get_catalogue(&results);
for (vertex_id_t pt_bit = internal_max_pt_bit + 1; pt_bit <= max_partition_vertex_bit; pt_bit++) {
results[pt_bit] = results[internal_max_pt_bit];
}
LOG(WARNING) << block_end_str(1) << "Mini benchmarks in " << benchmark_timer.duration() << " sec";
/*
for (auto iter : results) {
printf("partition_bits %u\n", iter.first);
for (auto &iter_deg: iter.second) {
printf("\tdegree %u: ", iter_deg.first);
for (auto res : iter_deg.second) {
if (res.sampler_class == ClassExclusiveBufferSampler) {
printf(" (PS, %.3lf ns),", res.step_time);
}
if (res.sampler_class == ClassUniformDegreeDirectSampler) {
printf(" (DS, %.3lf ns),", res.step_time);
}
}
printf("\n");
}
}
exit(0);
*/
}
| [
"oneday117@qq.com"
] | oneday117@qq.com |
bed1e5e85d3baa7e70b4e0eac0da528a7925891c | b30b65994865ce9212da5b30834b15ea9dbb9103 | /Code_Monk/Basics_IO/palindromic_string.cpp | 20ba2806db73aa989a6ee9d16d2081f540b58234 | [] | no_license | uthantvicentin/Competitive-Programming | 3d06b9cac1bf76a166f8009b7898fafdbca726bf | 6072753df64da0fa76a95fd30c9c65d89cd30a73 | refs/heads/master | 2021-09-08T19:54:18.510359 | 2021-09-05T13:14:12 | 2021-09-05T13:14:12 | 178,067,690 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 336 | cpp | #include <bits/stdc++.h>
using namespace std;
int main(){
stack <char> p;
string palindrome;
cin >> palindrome;
for(int i = 0 ; i < palindrome.size() ; ++i) p.push(palindrome[i]);
int i = 0;
while(p.top() == palindrome[i++]){
p.pop();
if(p.empty())
break;
}
cout << ( !p.empty() ? "NO" : "YES") << '\n';
return 0;
}
| [
"uthantvicentin@gmail.com"
] | uthantvicentin@gmail.com |
ca76afe3db82b7ba33dc48c689d52c08afbd522e | d3e0066099d616c6bb27e37c7c5d20e37ca971e4 | /src/enumeration/Statemachine.cpp | df44f0f1c8ee65b44b0d612e4b7d2450855d44f5 | [
"MIT"
] | permissive | PeterSommerlad/CPPCourseIntroduction | 91e429cf41fba2240928d83860f0761779f03480 | 048e074e030d06e064e65a9282706f764d78fc3f | refs/heads/main | 2023-06-08T08:34:06.216157 | 2023-05-26T16:11:34 | 2023-05-26T16:12:05 | 456,890,345 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 497 | cpp | #include "Statemachine.h"
#include <cctype>
enum Statemachine::State: unsigned short {
begin, middle, end // only usable in .cpp
};
Statemachine::Statemachine() : theState{begin} {}
void Statemachine::processInput(char const c) {
switch(theState){
case begin :
if (! isspace(c))
theState = middle;
break;
case middle :
if (isspace(c))
theState = end;
break;
case end : break;// ignore input
}
}
bool Statemachine::isDone()const{
return theState == end;
}
| [
"peter.cpp@sommerlad.ch"
] | peter.cpp@sommerlad.ch |
91966fdc5eaba2a9abfc3fc3e0fdbd946ae6dd9b | 51135e6255bacd43dbebf3d646e5fb46a769c9f8 | /tools/utils/DataResource.cpp | 3a8ab236ffffa3b5a05cdd6c8fe82d8aaca2aa19 | [
"MIT"
] | permissive | dbpotato/common | ccf1f9127f13dd64b4907e4cd96142259626e508 | dac4a8fa24fb473f291771af2456b48675b17aca | refs/heads/master | 2023-09-01T08:28:38.289029 | 2023-08-22T20:02:22 | 2023-08-22T20:07:45 | 137,592,051 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,785 | cpp | /*
Copyright (c) 2023 Adam Kaniewski
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 "DataResource.h"
#include "FileUtils.h"
const uint32_t MAX_MEM_CACHE_SIZE = 1024*1024*4;
DataResource::DataResource(bool enable_drive_cache)
: _loaded_size(0)
, _expected_size(0)
, _enable_drive_cache(enable_drive_cache) {
_mem_cached_data = std::make_shared<Data>();
}
DataResource::DataResource(std::shared_ptr<Data> data, bool enable_drive_cache)
: _loaded_size(data->GetCurrentSize())
, _expected_size(data->GetCurrentSize())
, _enable_drive_cache(enable_drive_cache)
, _mem_cached_data(data) {
}
DataResource::~DataResource() {
if(!_cache_file_name.empty() && FileUtils::FileExists(_cache_file_name)){
FileUtils::DeleteFile(_cache_file_name);
}
}
std::shared_ptr<DataResource> DataResource::CreateFromFile(std::string file_name) {
std::shared_ptr<DataResource> result = std::make_shared<DataResource>();
std::fstream& stream = result->GetDriveCache();
stream.open(file_name, std::ios::binary | std::ios::in | std::ios::ate);
if(!stream.is_open()) {
return nullptr;
}
stream.seekg(0, std::ios::end);
uint32_t size = (uint32_t)stream.tellg();
stream.seekg(0, std::ios::beg);
result->SetCompletedSize(size);
return result;
}
void DataResource::SetCompletedSize(uint32_t size) {
_loaded_size = _expected_size = size;
}
bool DataResource::IsCompleted() {
return (_loaded_size == _expected_size);
}
uint32_t DataResource::GetSize() {
return _loaded_size;
}
uint32_t DataResource::GetExpectedSize() {
return _expected_size;
}
void DataResource::SetExpectedSize(uint32_t expected_size) {
_expected_size = expected_size;
}
bool DataResource::UseDriveCache() {
return _drive_cached_data.is_open();
}
bool DataResource::AddData(std::shared_ptr<Data> data) {
_last_received_data = Data::MakeShallowCopy(data);
_loaded_size += data->GetCurrentSize();
if(UseDriveCache()) {
return WriteToDrive(data);
} else if(_mem_cached_data->GetCurrentSize() + data->GetCurrentSize() > MAX_MEM_CACHE_SIZE) {
if(!_enable_drive_cache) {
return true;
}
_cache_file_name = FileUtils::CreateTempFileName();
if(_cache_file_name.empty()){
return false;
}
bool res = false;
if(_mem_cached_data->GetCurrentSize()) {
res = WriteToDrive(_mem_cached_data);
_mem_cached_data = std::make_shared<Data>();
if(res) {
res = WriteToDrive(data);
}
return res;
} else {
return WriteToDrive(data);
}
} else {
_mem_cached_data->Add(data);
}
return true;
}
bool DataResource::AddData(std::shared_ptr<DataResource> resource) {
if(resource->UseDriveCache()) {
if(!UseDriveCache()) {
_cache_file_name = FileUtils::CreateTempFileName();
if(_cache_file_name.empty()){
return false;
}
if(!WriteToDrive(_mem_cached_data)){
return false;
}
}
_loaded_size += resource->GetSize();
std::fstream& res_stream = resource->GetDriveCache();
res_stream.seekg(0, res_stream.beg);
size_t buff_length = 1024*64;
char buff[buff_length];
do {
size_t read_len = buff_length;
res_stream.read(buff, buff_length);
if(!res_stream) {
read_len = res_stream.gcount();
}
_drive_cached_data.write(buff, read_len);
} while(res_stream);
} else {
AddData(resource->GetMemCache());
}
return true;
}
bool DataResource::WriteToDrive(std::shared_ptr<Data> data) {
if(!_drive_cached_data.is_open()) {
_drive_cached_data.open(_cache_file_name, std::ios::in | std::ios::out | std::ios::binary | std::ios::trunc);
if(!_drive_cached_data.is_open()) {
return false;
}
}
if(!_drive_cached_data.write((const char*)data->GetCurrentDataRaw(), data->GetCurrentSize())) {
return false;
}
return true;
}
std::shared_ptr<Data> DataResource::GetMemCache() {
return _mem_cached_data;
}
std::shared_ptr<Data> DataResource::GetLastRecivedData() {
return _last_received_data;
}
std::fstream& DataResource::GetDriveCache() {
return _drive_cached_data;
}
std::string DataResource::GetDriveCacheFileName() {
return _cache_file_name;
}
bool DataResource::SaveToFile(std::string file_name) {
if(UseDriveCache()) {
_drive_cached_data.flush();
return FileUtils::MoveFile(_cache_file_name, file_name);
} else {
return FileUtils::SaveFile(file_name, _mem_cached_data);
}
return true;
}
void DataResource::CopyToBuff(unsigned char* buff, size_t buff_size, size_t offset) {
if(UseDriveCache()) {
_drive_cached_data.seekg(offset);
_drive_cached_data.read((char*)buff, buff_size); //TODO return val check
} else {
std::memcpy(buff, _mem_cached_data->GetCurrentDataRaw() + offset, buff_size);
}
}
| [
"ghoel@dbpotato.net"
] | ghoel@dbpotato.net |
b8f83cf7b696f2c53f6dad8a872de98d0a2c3e08 | 00a6fd064e0432e69a5ff6d2f8e5788385f024e9 | /src/exec/VariableConflictSet.cc | 2e05e00e2141a9430c53f83742b85a7a0fd6d846 | [] | no_license | morxa/plexil-4 | 83524458462b066639874736604876d10bef16e1 | 890e92aa259881dd944d573d6ec519341782a5f2 | refs/heads/master | 2020-03-26T18:28:28.913603 | 2018-08-07T19:40:36 | 2018-08-07T19:40:36 | 145,214,882 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,034 | cc | /* Copyright (c) 2006-2016, Universities Space Research Association (USRA).
* 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 Universities Space Research Association 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 USRA ``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 USRA 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 "VariableConflictSet.hh"
#include "Node.hh"
#include "lifecycle-utils.h"
#include <algorithm> // std::find()
namespace PLEXIL
{
VariableConflictSet::VariableConflictSet()
: m_next(NULL),
m_variable(NULL)
{
m_nodes.reserve(1);
}
VariableConflictSet::~VariableConflictSet()
{
}
Expression const *VariableConflictSet::getVariable() const
{
return m_variable;
}
void VariableConflictSet::setVariable(Expression *a)
{
m_variable = a;
}
VariableConflictSet *VariableConflictSet::next() const
{
return m_next;
}
void VariableConflictSet::setNext(VariableConflictSet *nxt)
{
m_next = nxt;
}
size_t VariableConflictSet::size() const
{
return m_nodes.size();
}
bool VariableConflictSet::empty() const
{
return m_nodes.empty();
}
void VariableConflictSet::push(Node *node)
{
// Most common case first
if (m_nodes.empty()) {
m_nodes.push_back(node);
return;
}
int32_t prio = node->getPriority();
for (std::vector<Node *>::iterator it = m_nodes.begin(); it != m_nodes.end(); ++it) {
if (node == *it)
return;
if (prio < (*it)->getPriority()) {
m_nodes.insert(it, node);
return;
}
}
// If we got here, has worse priority than everything already in the list
m_nodes.push_back(node);
}
Node *VariableConflictSet::front()
{
if (m_nodes.empty())
return NULL;
return m_nodes.front();
}
void VariableConflictSet::remove(Node *node)
{
std::vector<Node *>::iterator it =
std::find(m_nodes.begin(), m_nodes.end(), node);
if (it != m_nodes.end())
m_nodes.erase(it);
}
size_t VariableConflictSet::front_count() const
{
// Expected most common case first
if (m_nodes.size() == 1)
return 1;
if (m_nodes.empty())
return 0;
size_t result = 1;
int32_t prio = m_nodes.front()->getPriority();
for (size_t i = 1;
i < m_nodes.size() && m_nodes[i]->getPriority() == prio;
++i, ++result)
{}
return result;
}
VariableConflictSet::iterator VariableConflictSet::begin()
{
return m_nodes.begin();
}
VariableConflictSet::const_iterator VariableConflictSet::begin() const
{
return m_nodes.begin();
}
VariableConflictSet::iterator VariableConflictSet::end()
{
return m_nodes.end();
}
VariableConflictSet::const_iterator VariableConflictSet::end() const
{
return m_nodes.end();
}
//
// Homegrown allocator
//
static VariableConflictSet *s_freeList = NULL;
VariableConflictSet *VariableConflictSet::allocate()
{
if (s_freeList) {
VariableConflictSet *result = s_freeList;
s_freeList = s_freeList->m_next;
// Wipe clean
result->m_next = NULL;
result->m_variable = NULL;
result->m_nodes.clear();
return result;
}
else {
return new VariableConflictSet();
}
}
extern "C"
void cleanupVariableConflictSets()
{
while (s_freeList) {
VariableConflictSet *temp = s_freeList;
s_freeList = s_freeList->next();
delete temp;
}
}
void VariableConflictSet::release(VariableConflictSet *v)
{
static bool sl_cleanupInstalled = false;
v->m_next = s_freeList;
s_freeList = v;
if (sl_cleanupInstalled)
return;
plexilAddFinalizer(&cleanupVariableConflictSets);
sl_cleanupInstalled = true;
}
} // namespace PLEXIL
| [
"plexilcrf@d2be67b0-814c-0410-949f-d215b6b29573"
] | plexilcrf@d2be67b0-814c-0410-949f-d215b6b29573 |
962ba8bb5de5c7af7fef31c7a2a40d21739e4c42 | 4fc62c002219b2cd14496579c4ecbc66a8fa7fe8 | /base/trace_event/memory_dump_manager_unittest.cc | 5c47721d71149f0c74e585ba1df4ace470499761 | [] | no_license | TheTypoMaster/dingler | 7475367e10926194c0d50e63f3a26914799e30ca | 7d1fbdc0450eac1a2b3f8c08e97522a9490a6834 | refs/heads/master | 2020-04-10T13:30:55.813142 | 2015-09-02T14:56:05 | 2015-09-02T14:56:05 | 41,807,566 | 0 | 0 | null | 2015-09-02T14:55:48 | 2015-09-02T14:55:47 | null | UTF-8 | C++ | false | false | 13,241 | 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 "base/trace_event/memory_dump_manager.h"
#include "base/bind_helpers.h"
#include "base/memory/scoped_vector.h"
#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "base/thread_task_runner_handle.h"
#include "base/threading/thread.h"
#include "base/trace_event/memory_dump_provider.h"
#include "base/trace_event/process_memory_dump.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using testing::_;
using testing::Between;
using testing::Invoke;
using testing::Return;
namespace base {
namespace trace_event {
// Testing MemoryDumpManagerDelegate which short-circuits dump requests locally
// instead of performing IPC dances.
class MemoryDumpManagerDelegateForTesting : public MemoryDumpManagerDelegate {
public:
void RequestGlobalMemoryDump(const MemoryDumpRequestArgs& args,
const MemoryDumpCallback& callback) override {
CreateProcessDump(args, callback);
}
bool IsCoordinatorProcess() const override { return false; }
};
class MemoryDumpManagerTest : public testing::Test {
public:
void SetUp() override {
last_callback_success_ = false;
message_loop_.reset(new MessageLoop());
mdm_.reset(new MemoryDumpManager());
MemoryDumpManager::SetInstanceForTesting(mdm_.get());
ASSERT_EQ(mdm_, MemoryDumpManager::GetInstance());
MemoryDumpManager::GetInstance()->Initialize();
MemoryDumpManager::GetInstance()->SetDelegate(&delegate_);
}
void TearDown() override {
MemoryDumpManager::SetInstanceForTesting(nullptr);
mdm_.reset();
message_loop_.reset();
TraceLog::DeleteForTesting();
}
void DumpCallbackAdapter(scoped_refptr<SingleThreadTaskRunner> task_runner,
Closure closure,
uint64 dump_guid,
bool success) {
last_callback_success_ = success;
task_runner->PostTask(FROM_HERE, closure);
}
protected:
const char* kTraceCategory = MemoryDumpManager::kTraceCategoryForTesting;
void EnableTracing(const char* category) {
TraceLog::GetInstance()->SetEnabled(
TraceConfig(category, ""), TraceLog::RECORDING_MODE);
}
void DisableTracing() { TraceLog::GetInstance()->SetDisabled(); }
scoped_ptr<MemoryDumpManager> mdm_;
bool last_callback_success_;
private:
scoped_ptr<MessageLoop> message_loop_;
MemoryDumpManagerDelegateForTesting delegate_;
// We want our singleton torn down after each test.
ShadowingAtExitManager at_exit_manager_;
};
class MockDumpProvider : public MemoryDumpProvider {
public:
MockDumpProvider()
: dump_provider_to_register_or_unregister(nullptr),
last_session_state_(nullptr) {}
// Ctor used by the RespectTaskRunnerAffinity test.
explicit MockDumpProvider(
const scoped_refptr<SingleThreadTaskRunner>& task_runner)
: last_session_state_(nullptr), task_runner_(task_runner) {}
virtual ~MockDumpProvider() {}
MOCK_METHOD1(OnMemoryDump, bool(ProcessMemoryDump* pmd));
// OnMemoryDump() override for the RespectTaskRunnerAffinity test.
bool OnMemoryDump_CheckTaskRunner(ProcessMemoryDump* pmd) {
EXPECT_TRUE(task_runner_->RunsTasksOnCurrentThread());
return true;
}
// OnMemoryDump() override for the SharedSessionState test.
bool OnMemoryDump_CheckSessionState(ProcessMemoryDump* pmd) {
MemoryDumpSessionState* cur_session_state = pmd->session_state().get();
if (last_session_state_)
EXPECT_EQ(last_session_state_, cur_session_state);
last_session_state_ = cur_session_state;
return true;
}
// OnMemoryDump() override for the RegisterDumperWhileDumping test.
bool OnMemoryDump_RegisterExtraDumpProvider(ProcessMemoryDump* pmd) {
MemoryDumpManager::GetInstance()->RegisterDumpProvider(
dump_provider_to_register_or_unregister);
return true;
}
// OnMemoryDump() override for the UnegisterDumperWhileDumping test.
bool OnMemoryDump_UnregisterDumpProvider(ProcessMemoryDump* pmd) {
MemoryDumpManager::GetInstance()->UnregisterDumpProvider(
dump_provider_to_register_or_unregister);
return true;
}
// Used by OnMemoryDump_(Un)RegisterExtraDumpProvider.
MemoryDumpProvider* dump_provider_to_register_or_unregister;
private:
MemoryDumpSessionState* last_session_state_;
scoped_refptr<SingleThreadTaskRunner> task_runner_;
};
TEST_F(MemoryDumpManagerTest, SingleDumper) {
MockDumpProvider mdp;
mdm_->RegisterDumpProvider(&mdp);
// Check that the dumper is not called if the memory category is not enabled.
EnableTracing("foo-and-bar-but-not-memory");
EXPECT_CALL(mdp, OnMemoryDump(_)).Times(0);
mdm_->RequestGlobalDump(MemoryDumpType::EXPLICITLY_TRIGGERED);
DisableTracing();
// Now repeat enabling the memory category and check that the dumper is
// invoked this time.
EnableTracing(kTraceCategory);
EXPECT_CALL(mdp, OnMemoryDump(_)).Times(3).WillRepeatedly(Return(true));
for (int i = 0; i < 3; ++i)
mdm_->RequestGlobalDump(MemoryDumpType::EXPLICITLY_TRIGGERED);
DisableTracing();
mdm_->UnregisterDumpProvider(&mdp);
// Finally check the unregister logic (no calls to the mdp after unregister).
EnableTracing(kTraceCategory);
EXPECT_CALL(mdp, OnMemoryDump(_)).Times(0);
mdm_->RequestGlobalDump(MemoryDumpType::EXPLICITLY_TRIGGERED);
TraceLog::GetInstance()->SetDisabled();
}
TEST_F(MemoryDumpManagerTest, SharedSessionState) {
MockDumpProvider mdp1;
MockDumpProvider mdp2;
mdm_->RegisterDumpProvider(&mdp1);
mdm_->RegisterDumpProvider(&mdp2);
EnableTracing(kTraceCategory);
EXPECT_CALL(mdp1, OnMemoryDump(_))
.Times(2)
.WillRepeatedly(
Invoke(&mdp1, &MockDumpProvider::OnMemoryDump_CheckSessionState));
EXPECT_CALL(mdp2, OnMemoryDump(_))
.Times(2)
.WillRepeatedly(
Invoke(&mdp2, &MockDumpProvider::OnMemoryDump_CheckSessionState));
for (int i = 0; i < 2; ++i)
mdm_->RequestGlobalDump(MemoryDumpType::EXPLICITLY_TRIGGERED);
DisableTracing();
}
TEST_F(MemoryDumpManagerTest, MultipleDumpers) {
MockDumpProvider mdp1;
MockDumpProvider mdp2;
// Enable only mdp1.
mdm_->RegisterDumpProvider(&mdp1);
EnableTracing(kTraceCategory);
EXPECT_CALL(mdp1, OnMemoryDump(_)).Times(1).WillRepeatedly(Return(true));
EXPECT_CALL(mdp2, OnMemoryDump(_)).Times(0);
mdm_->RequestGlobalDump(MemoryDumpType::EXPLICITLY_TRIGGERED);
DisableTracing();
// Invert: enable mdp1 and disable mdp2.
mdm_->UnregisterDumpProvider(&mdp1);
mdm_->RegisterDumpProvider(&mdp2);
EnableTracing(kTraceCategory);
EXPECT_CALL(mdp1, OnMemoryDump(_)).Times(0);
EXPECT_CALL(mdp2, OnMemoryDump(_)).Times(1).WillRepeatedly(Return(true));
mdm_->RequestGlobalDump(MemoryDumpType::EXPLICITLY_TRIGGERED);
DisableTracing();
// Enable both mdp1 and mdp2.
mdm_->RegisterDumpProvider(&mdp1);
EnableTracing(kTraceCategory);
EXPECT_CALL(mdp1, OnMemoryDump(_)).Times(1).WillRepeatedly(Return(true));
EXPECT_CALL(mdp2, OnMemoryDump(_)).Times(1).WillRepeatedly(Return(true));
mdm_->RequestGlobalDump(MemoryDumpType::EXPLICITLY_TRIGGERED);
DisableTracing();
}
// Checks that the MemoryDumpManager respects the thread affinity when a
// MemoryDumpProvider specifies a task_runner(). The test starts creating 8
// threads and registering a MemoryDumpProvider on each of them. At each
// iteration, one thread is removed, to check the live unregistration logic.
TEST_F(MemoryDumpManagerTest, RespectTaskRunnerAffinity) {
const uint32 kNumInitialThreads = 8;
ScopedVector<Thread> threads;
ScopedVector<MockDumpProvider> mdps;
// Create the threads and setup the expectations. Given that at each iteration
// we will pop out one thread/MemoryDumpProvider, each MDP is supposed to be
// invoked a number of times equal to its index.
for (uint32 i = kNumInitialThreads; i > 0; --i) {
threads.push_back(new Thread("test thread"));
threads.back()->Start();
mdps.push_back(new MockDumpProvider(threads.back()->task_runner()));
MockDumpProvider* mdp = mdps.back();
mdm_->RegisterDumpProvider(mdp, threads.back()->task_runner());
EXPECT_CALL(*mdp, OnMemoryDump(_))
.Times(i)
.WillRepeatedly(
Invoke(mdp, &MockDumpProvider::OnMemoryDump_CheckTaskRunner));
}
EnableTracing(kTraceCategory);
while (!threads.empty()) {
last_callback_success_ = false;
{
RunLoop run_loop;
MemoryDumpCallback callback =
Bind(&MemoryDumpManagerTest::DumpCallbackAdapter, Unretained(this),
MessageLoop::current()->task_runner(), run_loop.QuitClosure());
mdm_->RequestGlobalDump(MemoryDumpType::EXPLICITLY_TRIGGERED, callback);
// This nested message loop (|run_loop|) will be quit if and only if
// the RequestGlobalDump callback is invoked.
run_loop.Run();
}
EXPECT_TRUE(last_callback_success_);
// Unregister a MDP and destroy one thread at each iteration to check the
// live unregistration logic. The unregistration needs to happen on the same
// thread the MDP belongs to.
{
RunLoop run_loop;
Closure unregistration =
Bind(&MemoryDumpManager::UnregisterDumpProvider,
Unretained(mdm_.get()), Unretained(mdps.back()));
threads.back()->task_runner()->PostTaskAndReply(FROM_HERE, unregistration,
run_loop.QuitClosure());
run_loop.Run();
}
mdps.pop_back();
threads.back()->Stop();
threads.pop_back();
}
DisableTracing();
}
// Enable both dump providers, make sure that mdp gets disabled after 3 failures
// and not disabled after 1.
TEST_F(MemoryDumpManagerTest, DisableFailingDumpers) {
MockDumpProvider mdp1;
MockDumpProvider mdp2;
mdm_->RegisterDumpProvider(&mdp1);
mdm_->RegisterDumpProvider(&mdp2);
EnableTracing(kTraceCategory);
EXPECT_CALL(mdp1, OnMemoryDump(_))
.Times(MemoryDumpManager::kMaxConsecutiveFailuresCount)
.WillRepeatedly(Return(false));
EXPECT_CALL(mdp2, OnMemoryDump(_))
.Times(1 + MemoryDumpManager::kMaxConsecutiveFailuresCount)
.WillOnce(Return(false))
.WillRepeatedly(Return(true));
for (int i = 0; i < 1 + MemoryDumpManager::kMaxConsecutiveFailuresCount;
i++) {
mdm_->RequestGlobalDump(MemoryDumpType::EXPLICITLY_TRIGGERED);
}
DisableTracing();
}
// Sneakily register an extra memory dump provider while an existing one is
// dumping and expect it to take part in the already active tracing session.
TEST_F(MemoryDumpManagerTest, RegisterDumperWhileDumping) {
MockDumpProvider mdp1;
MockDumpProvider mdp2;
mdp1.dump_provider_to_register_or_unregister = &mdp2;
mdm_->RegisterDumpProvider(&mdp1);
EnableTracing(kTraceCategory);
EXPECT_CALL(mdp1, OnMemoryDump(_))
.Times(4)
.WillOnce(Return(true))
.WillOnce(Invoke(
&mdp1, &MockDumpProvider::OnMemoryDump_RegisterExtraDumpProvider))
.WillRepeatedly(Return(true));
// Depending on the insertion order (before or after mdp1), mdp2 might be
// called also immediately after it gets registered.
EXPECT_CALL(mdp2, OnMemoryDump(_))
.Times(Between(2, 3))
.WillRepeatedly(Return(true));
for (int i = 0; i < 4; i++) {
mdm_->RequestGlobalDump(MemoryDumpType::EXPLICITLY_TRIGGERED);
}
DisableTracing();
}
// Like the above, but suddenly unregister the dump provider.
TEST_F(MemoryDumpManagerTest, UnregisterDumperWhileDumping) {
MockDumpProvider mdp1;
MockDumpProvider mdp2;
mdm_->RegisterDumpProvider(&mdp1, ThreadTaskRunnerHandle::Get());
mdm_->RegisterDumpProvider(&mdp2, ThreadTaskRunnerHandle::Get());
mdp1.dump_provider_to_register_or_unregister = &mdp2;
EnableTracing(kTraceCategory);
EXPECT_CALL(mdp1, OnMemoryDump(_))
.Times(4)
.WillOnce(Return(true))
.WillOnce(Invoke(&mdp1,
&MockDumpProvider::OnMemoryDump_UnregisterDumpProvider))
.WillRepeatedly(Return(true));
// Depending on the insertion order (before or after mdp1), mdp2 might have
// been already called when OnMemoryDump_UnregisterDumpProvider happens.
EXPECT_CALL(mdp2, OnMemoryDump(_))
.Times(Between(1, 2))
.WillRepeatedly(Return(true));
for (int i = 0; i < 4; i++) {
mdm_->RequestGlobalDump(MemoryDumpType::EXPLICITLY_TRIGGERED);
}
DisableTracing();
}
// Ensures that a NACK callback is invoked if RequestGlobalDump is called when
// tracing is not enabled.
TEST_F(MemoryDumpManagerTest, CallbackCalledOnFailure) {
MockDumpProvider mdp1;
mdm_->RegisterDumpProvider(&mdp1);
EXPECT_CALL(mdp1, OnMemoryDump(_)).Times(0);
last_callback_success_ = true;
{
RunLoop run_loop;
MemoryDumpCallback callback =
Bind(&MemoryDumpManagerTest::DumpCallbackAdapter, Unretained(this),
MessageLoop::current()->task_runner(), run_loop.QuitClosure());
mdm_->RequestGlobalDump(MemoryDumpType::EXPLICITLY_TRIGGERED, callback);
run_loop.Run();
}
EXPECT_FALSE(last_callback_success_);
}
} // namespace trace_event
} // namespace base
| [
"brainloop0@gmail.com"
] | brainloop0@gmail.com |
0ffede0f7178f0ea422f67c84791336f1fbf31f2 | 74f5c2a94d82195d05be257ad1ac57fb81b6edb7 | /Problem/FunctionOpt/MOP/MOEA-F/F.cpp | ad43ddd2568be866dbe27a8d1858c3d7c80e1d66 | [] | no_license | dcshen/OFEC | d3324fd301005edba88c9dbc1ab3d39c62d480bc | a1b725a3052bb01de6c1e0151200dfde0dbebc0a | refs/heads/master | 2021-01-18T12:45:52.455025 | 2015-12-02T03:21:58 | 2015-12-02T03:21:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,757 | cpp | #include "F.h"
F_Base::F_Base(int ID, int numDim, const string &proName, int numObj):BenchmarkFunction(ID,numDim,proName,numObj)
{
setSearchRange(0.,1.);
vector<ProTag> p_tag(1,MOP);
p_tag.push_back(CONT);
setProTag(p_tag);
setOptType(MIN_OPT,-1);
m_popInitialMode=POP_INIT_UNIFORM;
}
void F_Base::evaluate__(double const *x,vector<double>& obj)
{
calObjective(x,obj);
}
void F_Base::LoadPF()
{
ifstream infile;
stringstream os;
os<<Global::msp_global->g_arg[param_workingDir]<<"Problem/FunctionOpt/Data/pf_P"<<m_ptype<<"D"<<m_dtype<<"L"<<m_ltype<<".dat";
infile.open(os.str());
if(!infile)
return ;
int lines=0;
string str;
while(getline(infile,str))
++lines;
m_globalOpt.setNumOpts(lines);
m_originalGlobalOpt.setNumOpts(lines);
m_originalGlobalOpt.setFlagLocTrue();
infile.close();
infile.clear();
infile.open(os.str());
for(int i=0;i<lines;i++)
for(int j=0;j<m_numObj;j++)
infile>>m_originalGlobalOpt[i].data().m_obj[j];
m_globalOpt=m_originalGlobalOpt;
infile.close();
}
// control the PF shape
void F_Base::alphafunction(double alpha[],double const *x, int dim, int type)
{
if(dim==2)
{
if(type==21){
alpha[0] = x[0];
alpha[1] = 1 - sqrt(x[0]);
}
if(type==22){
alpha[0] = x[0];
alpha[1] = 1 - x[0]*x[0];
}
if(type==23){
alpha[0] = x[0];
alpha[1] = 1 - sqrt(alpha[0]) - alpha[0]*sin(10*alpha[0]*alpha[0]*OFEC_PI);
}
if(type==24){
alpha[0] = x[0];
alpha[1] = 1 - x[0] - 0.05*sin(4*OFEC_PI*x[0]);
}
}
else
{
if(type==31){
alpha[0] = cos(x[0]*OFEC_PI/2)*cos(x[1]*OFEC_PI/2);
alpha[1] = cos(x[0]*OFEC_PI/2)*sin(x[1]*OFEC_PI/2);
alpha[2] = sin(x[0]*OFEC_PI/2);
}
if(type==32){
alpha[0] = 1 - cos(x[0]*OFEC_PI/2)*cos(x[1]*OFEC_PI/2);
alpha[1] = 1 - cos(x[0]*OFEC_PI/2)*sin(x[1]*OFEC_PI/2);
alpha[2] = 1 - sin(x[0]*OFEC_PI/2);
}
if(type==33){
alpha[0] = x[0];
alpha[1] = x[1];
alpha[2] = 3 - (sin(3*OFEC_PI*x[0]) + sin(3*OFEC_PI*x[1])) - 2*(x[0] + x[1]);
}
if(type==34){
alpha[0] = x[0]*x[1];
alpha[1] = x[0]*(1 - x[1]);
alpha[2] = (1 - x[0]);
}
}
}
// control the distance
double F_Base::betafunction(const vector<double> &x, int type)
{
double beta;
int dim = x.size();
if (dim == 0){
// a bug here when dim=0
//beta = 0;
return 0;
}
if(type==1){
beta = 0;
for(int i=0; i<dim; i++){
beta+= x[i]*x[i];
}
beta = 2.0*beta/dim;
}
if(type==2){
beta = 0;
for(int i=0; i<dim; i++){
beta+= sqrt(i+1)*x[i]*x[i];
}
beta = 2.0*beta/dim;
}
if(type==3){
double sum = 0, xx;
for(int i=0; i<dim; i++){
xx = 2*x[i];
sum+= (xx*xx - cos(4*OFEC_PI*xx) + 1);
}
beta = 2.0*sum/dim;
}
if(type==4){
double sum = 0, prod = 1, xx;
for(int i=0; i<dim; i++){
xx = 2*x[i];
sum+= xx*xx;
prod*=cos(10*OFEC_PI*xx/sqrt(i+1));
}
beta = 2.0*(sum - 2*prod + 2)/dim;
}
return beta;
}
// control the PS shape of 2-d instances
double F_Base::psfunc2(const double &x,const double &t1, int dim, int type, int css){
// type: the type of curve
// css: the class of index
double beta;
int numDim=Global::msp_global->mp_problem->getNumDim();
dim++;
if(type==21){
double xy = 2*(x - 0.5);
// a bug here when numDim=2
if (numDim == 2) beta = xy - pow(t1, 2.0);
else beta = xy - pow(t1, 0.5*(numDim + 3*dim - 8)/(numDim - 2));
}
if(type==22){
double theta = 6*OFEC_PI*t1 + dim*OFEC_PI/numDim;
double xy = 2*(x - 0.5);
beta = xy - sin(theta);
}
if(type==23){
double theta = 6*OFEC_PI*t1 + dim*OFEC_PI/numDim;
double ra = 0.8*t1;
double xy = 2*(x - 0.5);
if(css==1)
beta = xy - ra*cos(theta);
else{
beta = xy - ra*sin(theta);
}
}
if(type==24){
double theta = 6*OFEC_PI*t1 + dim*OFEC_PI/numDim;
double xy = 2*(x - 0.5);
double ra = 0.8*t1;
if(css==1)
beta = xy - ra*cos(theta/3);
else{
beta = xy - ra*sin(theta);
}
}
if(type==25){
double rho = 0.8;
double phi = OFEC_PI*t1;
double theta = 6*OFEC_PI*t1 + dim*OFEC_PI/numDim;
double xy = 2*(x - 0.5);
if(css==1)
beta = xy - rho*sin(phi)*sin(theta);
else if(css==2)
beta = xy - rho*sin(phi)*cos(theta);
else
beta = xy - rho*cos(phi);
}
if(type==26){
double theta = 6*OFEC_PI*t1 + dim*OFEC_PI/numDim;
double ra = 0.3*t1*(t1*cos(4*theta) + 2);
double xy = 2*(x - 0.5);
if(css==1)
beta = xy - ra*cos(theta);
else{
beta = xy - ra*sin(theta);
}
}
return beta;
}
// control the PS shapes of 3-D instances
double F_Base::psfunc3(const double &x,const double &t1,const double &t2, int dim, int type){
// type: the type of curve
// css: the class of index
double beta;
int numDim=Global::msp_global->mp_problem->getNumDim();
dim++;
if(type==31){
double xy = 4*(x - 0.5);
double rate = 1.0*dim/numDim;
beta = xy - 4*(t1*t1*rate + t2*(1.0-rate)) + 2;
}
if(type==32){
double theta = 2*OFEC_PI*t1 + dim*OFEC_PI/numDim;
double xy = 4*(x - 0.5);
beta = xy - 2*t2*sin(theta);
}
return beta;
}
void F_Base::calObjective(double const *x_var, vector <double> &y_obj)
{
// 2-objective case
int nobj=Global::msp_global->mp_problem->getNumObj();
int nDim=Global::msp_global->mp_problem->getNumDim();
if(nobj==2)
{
if(m_ltype==21||m_ltype==22||m_ltype==23||m_ltype==24||m_ltype==26)
{
double g = 0, h = 0, a, b;
vector <double> aa;
vector <double> bb;
for(int n=1;n<nDim;n++)
{
if(n%2==0){
a = psfunc2(x_var[n],x_var[0],n,m_ltype,1); // linkage
aa.push_back(a);
}
else
{
b = psfunc2(x_var[n],x_var[0],n,m_ltype,2);
bb.push_back(b);
}
}
g = betafunction(aa,m_dtype);
h = betafunction(bb,m_dtype);
double alpha[2];
alphafunction(alpha,x_var,2,m_ptype); // shape function
y_obj[0] = alpha[0] + h;
y_obj[1] = alpha[1] + g;
aa.clear();
bb.clear();
}
if(m_ltype==25)
{
double g = 0, h = 0, a, b;
double e = 0, c;
vector <double> aa;
vector <double> bb;
for(int n=1;n<nDim;n++){
if(n%3==0){
a = psfunc2(x_var[n],x_var[0],n,m_ltype,1);
aa.push_back(a);
}
else if(n%3==1)
{
b = psfunc2(x_var[n],x_var[0],n,m_ltype,2);
bb.push_back(b);
}
else{
c = psfunc2(x_var[n],x_var[0],n,m_ltype,3);
if(n%2==0) aa.push_back(c);
else bb.push_back(c);
}
}
g = betafunction(aa,m_dtype); // distance function
h = betafunction(bb,m_dtype);
double alpha[2];
alphafunction(alpha,x_var,2,m_ptype); // shape function
y_obj[0] = alpha[0] + h;
y_obj[1] = alpha[1] + g;
aa.clear();
bb.clear();
}
}
// 3-objective case
if(nobj==3)
{
if(m_ltype==31||m_ltype==32)
{
double g = 0, h = 0, e = 0, a;
vector <double> aa;
vector <double> bb;
vector <double> cc;
for(int n=2;n<nDim;n++)
{
a = psfunc3(x_var[n],x_var[0],x_var[1],n,m_ltype);
if(n%3==0) aa.push_back(a);
else if(n%3==1) bb.push_back(a);
else cc.push_back(a);
}
g = betafunction(aa,m_dtype);
h = betafunction(bb,m_dtype);
e = betafunction(cc,m_dtype);
double alpha[3];
alphafunction(alpha,x_var,3,m_ptype); // shape function
y_obj[0] = alpha[0] + h;
y_obj[1] = alpha[1] + g;
y_obj[2] = alpha[2] + e;
aa.clear();
bb.clear();
cc.clear();
}
}
}
| [
"changhe.lw@gmail.com"
] | changhe.lw@gmail.com |
ef70a0851654877731f9845c1f29de1f8c54c233 | 7fa734062e925da0dc4f59164ef40fd2fe7d50da | /src/components/application_manager/test/command_holder_test.cc | e10cd5d008bf1192a4c9542c546194bc03935e57 | [] | permissive | lixiaozhang/sdl_core | bc54970a117aa4637c608415c2a66dd95e233568 | c439661b160172676eff0f154049cf8cea50596a | refs/heads/master | 2020-03-21T22:34:47.554462 | 2018-12-21T03:22:19 | 2018-12-21T03:22:19 | 139,135,233 | 0 | 0 | BSD-3-Clause | 2018-06-29T10:16:59 | 2018-06-29T10:16:58 | null | UTF-8 | C++ | false | false | 6,262 | cc | /*
* Copyright (c) 2017, Ford Motor Company
* 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 Ford Motor Company nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <gmock/gmock.h>
#include "application_manager/command_holder_impl.h"
#include "application_manager/commands/command.h"
#include "smart_objects/smart_object.h"
#include "utils/shared_ptr.h"
#include "utils/make_shared.h"
#include "application_manager/mock_application_manager.h"
#include "application_manager/mock_application.h"
namespace test {
namespace components {
namespace application_manager_test {
using testing::_;
using testing::Return;
namespace am = application_manager;
class CommandHolderImplTest : public testing::Test {
public:
CommandHolderImplTest()
: kPolicyAppId_("p_app_id")
, kHmiApplicationId_(123)
, kConnectionKey_(56789)
, cmd_ptr_(new smart_objects::SmartObject)
, mock_app_ptr_(new MockApplication) {}
void SetUp() OVERRIDE {
ON_CALL(*mock_app_ptr_, app_id()).WillByDefault(Return(kConnectionKey_));
ON_CALL(*mock_app_ptr_, hmi_app_id())
.WillByDefault(Return(kHmiApplicationId_));
ON_CALL(*mock_app_ptr_, policy_app_id())
.WillByDefault(Return(kPolicyAppId_));
}
MockApplicationManager mock_app_manager_;
const std::string kPolicyAppId_;
const uint32_t kHmiApplicationId_;
const uint32_t kConnectionKey_;
utils::SharedPtr<smart_objects::SmartObject> cmd_ptr_;
utils::SharedPtr<MockApplication> mock_app_ptr_;
};
TEST_F(CommandHolderImplTest, HoldOne_ExpectReleaseOne) {
am::CommandHolderImpl cmd_holder(mock_app_manager_);
cmd_holder.Suspend(
mock_app_ptr_, am::CommandHolder::CommandType::kHmiCommand, cmd_ptr_);
// Act
EXPECT_CALL(mock_app_manager_, ManageHMICommand(cmd_ptr_));
cmd_holder.Resume(mock_app_ptr_, am::CommandHolder::CommandType::kHmiCommand);
}
TEST_F(CommandHolderImplTest, HoldMany_ExpectReleaseSame) {
am::CommandHolderImpl cmd_holder(mock_app_manager_);
int32_t iterations = 0;
do {
cmd_holder.Suspend(
mock_app_ptr_, am::CommandHolder::CommandType::kHmiCommand, cmd_ptr_);
++iterations;
} while (iterations < 5);
// Act
EXPECT_CALL(mock_app_manager_, ManageHMICommand(cmd_ptr_)).Times(iterations);
cmd_holder.Resume(mock_app_ptr_, am::CommandHolder::CommandType::kHmiCommand);
}
TEST_F(CommandHolderImplTest, Hold_Drop_ExpectNoReleased) {
am::CommandHolderImpl cmd_holder(mock_app_manager_);
cmd_holder.Suspend(
mock_app_ptr_, am::CommandHolder::CommandType::kHmiCommand, cmd_ptr_);
cmd_holder.Suspend(
mock_app_ptr_, am::CommandHolder::CommandType::kHmiCommand, cmd_ptr_);
// Act
cmd_holder.Clear(mock_app_ptr_);
EXPECT_CALL(mock_app_manager_, ManageHMICommand(cmd_ptr_)).Times(0);
cmd_holder.Resume(mock_app_ptr_, am::CommandHolder::CommandType::kHmiCommand);
}
TEST_F(CommandHolderImplTest, Hold_ReleaseAnotherId_ExpectNoReleased) {
am::CommandHolderImpl cmd_holder(mock_app_manager_);
cmd_holder.Suspend(
mock_app_ptr_, am::CommandHolder::CommandType::kHmiCommand, cmd_ptr_);
cmd_holder.Suspend(
mock_app_ptr_, am::CommandHolder::CommandType::kHmiCommand, cmd_ptr_);
// Act
utils::SharedPtr<MockApplication> another_app =
utils::MakeShared<MockApplication>();
EXPECT_CALL(mock_app_manager_, ManageHMICommand(cmd_ptr_)).Times(0);
cmd_holder.Resume(another_app, am::CommandHolder::CommandType::kHmiCommand);
}
TEST_F(CommandHolderImplTest, Hold_DropAnotherId_ExpectReleased) {
am::CommandHolderImpl cmd_holder(mock_app_manager_);
int32_t iterations = 0;
do {
cmd_holder.Suspend(
mock_app_ptr_, am::CommandHolder::CommandType::kHmiCommand, cmd_ptr_);
++iterations;
} while (iterations < 3);
// Act
utils::SharedPtr<MockApplication> another_app =
utils::MakeShared<MockApplication>();
cmd_holder.Clear(another_app);
EXPECT_CALL(mock_app_manager_, ManageHMICommand(cmd_ptr_)).Times(iterations);
cmd_holder.Resume(mock_app_ptr_, am::CommandHolder::CommandType::kHmiCommand);
}
TEST_F(CommandHolderImplTest, Hold_Mobile_and_HMI_commands_ExpectReleased) {
am::CommandHolderImpl cmd_holder(mock_app_manager_);
cmd_holder.Suspend(
mock_app_ptr_, am::CommandHolder::CommandType::kHmiCommand, cmd_ptr_);
cmd_holder.Suspend(
mock_app_ptr_, am::CommandHolder::CommandType::kMobileCommand, cmd_ptr_);
// Act
EXPECT_CALL(mock_app_manager_, ManageHMICommand(cmd_ptr_));
cmd_holder.Resume(mock_app_ptr_, am::CommandHolder::CommandType::kHmiCommand);
EXPECT_CALL(
mock_app_manager_,
ManageMobileCommand(cmd_ptr_,
am::commands::Command::CommandOrigin::ORIGIN_MOBILE));
cmd_holder.Resume(mock_app_ptr_,
am::CommandHolder::CommandType::kMobileCommand);
}
} // application_manager_test
} // components
} // test
| [
"AByzhynar@luxoft.com"
] | AByzhynar@luxoft.com |
efdc4d5e445e17fab15826522675c081473e0bbd | 24ccbc841f56ab3c85ad9b8bc5f04f3cdf5700db | /DesignModel/BuilderModel.h | 46eb9013f091db86ebeffd0d5d31407bccbd28dc | [] | no_license | chongjibo/DesignPatterns | 141b0dd1b236e678bda3471e4b226b90d37c04f3 | b649a8fd34306c9f4461664866ae8c10fe211868 | refs/heads/master | 2022-12-27T01:12:21.752233 | 2020-10-14T02:16:21 | 2020-10-14T02:16:21 | 296,855,119 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 1,159 | h | #pragma once
#include <string>
//
class Meal
{
public:
void setDrink(std::string drink)
{
_drink = drink;
}
std::string getDrink()
{
return _drink;
}
void setFood(std::string food)
{
_food = food;
}
std::string getFood()
{
return _food;
}
private:
std::string _drink;
std::string _food;
};
class Builder
{
public:
Builder()
{
_meal = new Meal();
}
virtual void buildFoot() = 0;
virtual void buildDrink() = 0;
Meal* getMeal()
{
return _meal;
}
protected:
Meal *_meal;
};
class KFCBuilder : public Builder
{
public:
void buildFoot()
{
_meal->setFood("ºº±¤");
}
void buildDrink()
{
_meal->setDrink("¿ÉÀÖ");
}
};
class HLSBuilder : public Builder
{
public:
void buildFoot()
{
_meal->setFood("¼¦Èâ¾í");
}
void buildDrink()
{
_meal->setDrink("Ä̲è");
}
};
class Director
{
public:
void setBuilder(Builder *builder)
{
_builder = builder;
}
Meal *construct()
{
_builder->buildDrink();
_builder->buildFoot();
return _builder->getMeal();
}
private:
Builder *_builder;
}; | [
"348875231@qq.com"
] | 348875231@qq.com |
da6498b977f6fe8f87d36a1a4bb6cb7721bd734a | b7c505dcef43c0675fd89d428e45f3c2850b124f | /Src/SimulatorQt/Util/qt/Win32/include/QtGui/qprintpreviewwidget.h | 7b849a0d85f2e959ba5e2f00643dfb0318f798cb | [
"BSD-2-Clause"
] | permissive | pranet/bhuman2009fork | 14e473bd6e5d30af9f1745311d689723bfc5cfdb | 82c1bd4485ae24043aa720a3aa7cb3e605b1a329 | refs/heads/master | 2021-01-15T17:55:37.058289 | 2010-02-28T13:52:56 | 2010-02-28T13:52:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,976 | h | /****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QPRINTPREVIEWWIDGET_H
#define QPRINTPREVIEWWIDGET_H
#include <QtGui/qwidget.h>
#include <QtGui/qprinter.h>
#ifndef QT_NO_PRINTPREVIEWWIDGET
QT_BEGIN_HEADER
QT_BEGIN_NAMESPACE
QT_MODULE(Gui)
class QPrintPreviewWidgetPrivate;
class Q_GUI_EXPORT QPrintPreviewWidget : public QWidget
{
Q_OBJECT
Q_DECLARE_PRIVATE(QPrintPreviewWidget)
public:
enum ViewMode {
SinglePageView,
FacingPagesView,
AllPagesView
};
enum ZoomMode {
CustomZoom,
FitToWidth,
FitInView
};
explicit QPrintPreviewWidget(QPrinter *printer, QWidget *parent = 0, Qt::WindowFlags flags = 0);
explicit QPrintPreviewWidget(QWidget *parent = 0, Qt::WindowFlags flags = 0);
~QPrintPreviewWidget();
qreal zoomFactor() const;
QPrinter::Orientation orientation() const;
ViewMode viewMode() const;
ZoomMode zoomMode() const;
int currentPage() const;
int numPages() const;
void setVisible(bool visible);
public Q_SLOTS:
void print();
void zoomIn(qreal zoom = 1.1);
void zoomOut(qreal zoom = 1.1);
void setZoomFactor(qreal zoomFactor);
void setOrientation(QPrinter::Orientation orientation);
void setViewMode(ViewMode viewMode);
void setZoomMode(ZoomMode zoomMode);
void setCurrentPage(int pageNumber);
void fitToWidth();
void fitInView();
void setLandscapeOrientation();
void setPortraitOrientation();
void setSinglePageViewMode();
void setFacingPagesViewMode();
void setAllPagesViewMode();
void updatePreview();
Q_SIGNALS:
void paintRequested(QPrinter *printer);
void previewChanged();
private:
QPrintPreviewWidgetPrivate *d_ptr;
Q_PRIVATE_SLOT(d_func(), void _q_fit())
Q_PRIVATE_SLOT(d_func(), void _q_updateCurrentPage())
};
QT_END_NAMESPACE
QT_END_HEADER
#endif // QT_NO_PRINTPREVIEWWIDGET
#endif // QPRINTPREVIEWWIDGET_H
| [
"alon@rogue.(none)"
] | alon@rogue.(none) |
9f9449b22337c36cc603e72db3c7d563e1a6d8fb | 7f87c5665f78768a4d8bc452781cb6fe4920da86 | /Alicorn.ino | 1a32cc02fb9e2ae7fd55a2f3bef411bf23b20716 | [
"MIT"
] | permissive | Thorinair/Alicorn | 064b2f805fbfaea921aebe957c480600743385f7 | 1580f54fef849ab699a17b5e7d3936d71c9f65cb | refs/heads/master | 2021-01-19T18:35:41.520669 | 2019-03-23T19:38:31 | 2019-03-23T19:38:31 | 88,366,683 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 46,892 | ino | #include "ESP8266WiFi.h"
#include <EEPROM.h>
#include <VariPass.h>
#include <DHT.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <IRremoteESP8266.h>
#include <SFE_BMP180.h>
#include <RtcDS3231.h>
#include <HMC5883L.h>
#include "wifi.h"
#include "vpid.h"
extern "C" {
#include "user_interface.h"
}
// Pins
#define PIN_RELAY_GEIG 0
#define PIN_DHT 12
#define PIN_GEIGER 13
#define PIN_IR 14
#define PIN_BUZZER 15
#define PIN_RELAY_GAS 16
#define PIN_MQ A0
// I2C Addresses
#define I2C_LCD 0x27
#define I2C_RTC 0x57
#define I2C_BMP 0x77
// Default Settings
#define DEFAULT_LCD_BACKLIGHT 1
#define DEFAULT_SCREEN_MAIN 0
#define DEFAULT_SCREEN_SETT 0
#define DEFAULT_REMOTE_BEEPS 1
#define DEFAULT_GAS_SENSOR 1
#define DEFAULT_GEIG_CLICKS 1
#define DEFAULT_GEIG_ALARM 1
#define DEFAULT_GEIG_SENSITIVITY 1000
#define DEFAULT_INT_MEASURE 10000
#define DEFAULT_INT_PUSH 60000
#define DEFAULT_INT_PULL 1000
#define DEFAULT_INT_SYNC 1000
#define DEFAULT_WIFI 0
// MinMaxStep Settings
#define MIN_GEIG_SENSITIVITY 100
#define MIN_INT_MEASURE 2000
#define MIN_INT_PUSH 1000
#define MIN_INT_PULL 1000
#define MIN_INT_SYNC 1000
#define MAX_GEIG_SENSITIVITY 10000
#define MAX_INT_MEASURE 60000
#define MAX_INT_PUSH 60000
#define MAX_INT_PULL 60000
#define MAX_INT_SYNC 60000
#define STP_GEIG_SENSITIVITY 100
#define STP_INT_MEASURE 1000
#define STP_INT_PUSH 1000
#define STP_INT_PULL 1000
#define STP_INT_SYNC 1000
// EEPROM Addresses
#define EEPROM_SAVED 0
#define EEPROM_LCD_BACKLIGHT 1
#define EEPROM_SCREEN_MAIN 2
#define EEPROM_SCREEN_SETT 3
#define EEPROM_REMOTE_BEEPS 4
#define EEPROM_GAS_SENSOR 5
#define EEPROM_GEIG_CLICKS 6
#define EEPROM_GEIG_ALARM 7
#define EEPROM_GEIG_SENSITIVITY 8
#define EEPROM_INT_MEASURE 9
#define EEPROM_INT_PUSH 10
#define EEPROM_INT_PULL 11
#define EEPROM_INT_SYNC 12
#define EEPROM_WIFI 13
// Screens
#define SCREENS_MAIN 8
#define SCREENS_SETT 11
// Main Screens
#define SCREEN_MAIN_TIME 0
#define SCREEN_MAIN_DHT 1
#define SCREEN_MAIN_BMPMQ 2
#define SCREEN_MAIN_MAG 3
#define SCREEN_MAIN_GEIGER 4
#define SCREEN_MAIN_CORE 5
#define SCREEN_MAIN_BULLETIN 6
#define SCREEN_MAIN_WIFI 7
// Settings Screens
#define SCREEN_SETT_REMOTE_BEEPS 0
#define SCREEN_SETT_GAS_SENSOR 1
#define SCREEN_SETT_GEIG_CLICKS 2
#define SCREEN_SETT_GEIG_ALARM 3
#define SCREEN_SETT_GEIG_SENSITIVITY 4
#define SCREEN_SETT_INT_MEASURE 5
#define SCREEN_SETT_INT_PUSH 6
#define SCREEN_SETT_INT_PULL 7
#define SCREEN_SETT_INT_SYNC 8
#define SCREEN_SETT_WIFI 9
#define SCREEN_SETT_DATETIME 10
// Intervals
#define INTERVAL_CYCLE 100
#define INTERVAL_TIMER 100
#define INTERVAL_ALARM 250
#define INTERVAL_LCD 1000
#define INTERVAL_GEIGER 60000
#define INTERVAL_CLOCK 1000
// Compact Levels
#define COMPACT_NONE 0
#define COMPACT_LONG 1
#define COMPACT_MEDIUM 2
#define COMPACT_SHORT 3
// Buzzer
#define BUZZER_REMOTE_TONE 3000
#define BUZZER_REMOTE_DURATION 100
#define BUZZER_ALARM_TONE 4000
// DHT22
DHT dht(PIN_DHT, DHT22);
// BMP180
#define ALTITUDE 123
SFE_BMP180 bmp;
// HMC5883L
HMC5883L mag;
// RTC
#define DATETIME_HOURS 0
#define DATETIME_MINUTES 1
#define DATETIME_SECONDS 2
#define DATETIME_YEAR 3
#define DATETIME_MONTH 4
#define DATETIME_DAY 5
RtcDS3231<TwoWire> rtc(Wire);
RtcDateTime now;
// Geiger
#define DOSE_MULTI 0.0057
// LCD
LiquidCrystal_I2C lcd(I2C_LCD, 16, 2);
// Remote
#define IR_BACKLIGHT 0xFF629D // CH
#define IR_PREV 0xFF22DD // <<
#define IR_NEXT 0xFF02FD // >>
#define IR_SETTINGS 0xFFC23D // >||
#define IR_DECREASE 0xFFE01F // -
#define IR_INCREASE 0xFFA857 // +
#define IR_DATETIME 0xFF906F // EQ
#define IR_S0 0xFF6897 // 0
#define IR_S1 0xFF30CF // 1
#define IR_S2 0xFF18E7 // 2
#define IR_S3 0xFF7A85 // 3
#define IR_S4 0xFF10EF // 4
#define IR_S5 0xFF38C7 // 5
#define IR_S6 0xFF5AA5 // 6
#define IR_S7 0xFF42BD // 7
#define IR_S8 0xFF4AB5 // 8
#define IR_S9 0xFF52AD // 9
#define IR_S10 0xFF9867 // 100+
#define IR_S11 0xFFB04F // 200+
IRrecv irrecv(PIN_IR);
decode_results results;
// WiFi
char* host;
char* ssid[COUNT_WIFI];
char* pass[COUNT_WIFI];
char* conf[COUNT_WIFI];
// Timers
os_timer_t timer;
os_timer_t timerAlarm;
// Structures
struct SETTINGS {
bool lcdBacklight;
int screenMain;
int screenSett;
bool remoteBeeps;
bool gasSensor;
bool geigerClicks;
bool geigerAlarm;
int geigerSensitivity;
int intervalMeasure;
long intervalGeiger;
int intervalPush;
int intervalPull;
int intervalSync;
int wifi;
} settings;
struct STATES {
bool screenSettings;
bool alarm;
bool alarmOn;
bool pushSync;
int datePage;
int wifi;
} states;
struct COUNTERS {
int measure;
int geiger;
int cclock;
int push;
int pull;
int sync;
int lcd;
} counters;
struct INTERVALS {
bool measure;
bool geiger;
bool cclock;
bool push;
bool pull;
bool sync;
bool lcd;
} intervals;
struct DATA {
float temperature;
float humidity;
float pressure;
float gas;
float magnitude;
float inclination;
int cpmNow;
int cpm;
float dose;
long core;
long gain;
String bulletin;
} data;
struct AVERAGE {
float temperature;
int temperatureCount;
float humidity;
int humidityCount;
float pressure;
int pressureCount;
float gas;
int gasCount;
float magnitude;
int magnitudeCount;
float inclination;
int inclinationCount;
} average;
// Utilities
void resetLCD();
void setRelays();
void drawScreen(String top, String bot);
bool checkInterval(int *counter, int interval);
void resetAverage();
void geigerClick();
IPAddress getIPFromString(char* addressString, int id);
// String Manipulation
String formatNumbers(long number, int compact, bool usePrefix, bool useSuffix, String suffix);
String splitData(String data, char separator, int index);
String boolToOnOff(bool value);
// Setups
void setupSettings();
void setupStates();
void setupCounters();
void setupWiFi();
void setupDevices();
void setupClock();
void setupTimer();
// Settings
void saveSettings();
void loadSettings();
// WiFi
void connectWiFi();
// Processes
void processTimer(void *pArg);
void processAlarm(void *pArg);
void processRemote();
void processSensors();
void processGeiger();
void processClock();
void processPush();
void processPull();
void processSync();
void processLCD();
// VariPass
void pullVariPass();
void pushVariPass();
void syncVariPass();
// Remote
void screenPrev();
void screenNext();
void screenSet(int page);
void valueDecrease();
void valueIncrease();
// Beeps
void beepRemote();
/* ===========
* Utilities
* =========== */
void resetLCD() {
pullVariPass();
counters.lcd = 0;
beepRemote();
}
void setRelays() {
if (settings.geigerClicks)
digitalWrite(PIN_RELAY_GEIG, LOW);
else
digitalWrite(PIN_RELAY_GEIG, HIGH);
if (settings.gasSensor)
digitalWrite(PIN_RELAY_GAS, HIGH);
else
digitalWrite(PIN_RELAY_GAS, LOW);
}
void drawScreen(String top, String bot) {
lcd.clear();
lcd.setCursor(0,0);
lcd.print(top);
lcd.setCursor(0,1);
lcd.print(bot);
}
bool checkInterval(int *counter, int interval) {
if (*counter <= 0) {
*counter = interval / INTERVAL_TIMER;
return true;
}
else {
(*counter)--;
return false;
}
}
void resetAverage() {
average.temperature = 0;
average.humidity = 0;
average.pressure = 0;
average.gas = 0;
average.magnitude = 0;
average.inclination = 0;
average.temperatureCount = 0;
average.humidityCount = 0;
average.pressureCount = 0;
average.gasCount = 0;
average.magnitudeCount = 0;
average.inclinationCount = 0;
}
void geigerClick() {
data.cpmNow++;
}
IPAddress getIPFromString(char* addressString, int id) {
String address = splitData(String(addressString), '|', id);
return IPAddress(splitData(address, '.', 0).toInt(), splitData(address, '.', 1).toInt(), splitData(address, '.', 2).toInt(), splitData(address, '.', 3).toInt());
}
/* =====================
* String Manipulation
* ===================== */
String formatNumbers(long number, int compact, bool usePrefix, bool useSuffix, String suffix) {
String out;
if (compact == COMPACT_LONG) {
if (number >= 1000000000) {
number = number / 1000;
if (useSuffix)
out = " M" + suffix;
}
else {
if (useSuffix)
out = " K" + suffix;
}
}
else if (compact == COMPACT_SHORT) {
if (number >= 1000000000) {
number = number / 1000000000;
if (useSuffix)
out = " T" + suffix;
}
else if (number >= 1000000) {
number = number / 1000000;
if (useSuffix)
out = " G" + suffix;
}
else if (number >= 1000) {
number = number / 1000;
if (useSuffix)
out = " M" + suffix;
}
else {
if (useSuffix)
out = " K" + suffix;
}
}
String data = String(abs(number));
int i, j;
for (i = 0; i < 4; i++) {
for (j = 0; j < 3; j++) {
if ((i*3 + j) < data.length())
out = data.charAt(data.length() - 1 - (i*3 + j)) + out;
else
out = " " + out;
}
out = " " + out;
}
out.trim();
if (number < 0)
out = "-" + out;
else if (usePrefix)
out = "+" + out;
return out;
}
String splitData(String data, char separator, int index) {
int found = 0;
int strIndex[] = {0, -1};
int maxIndex = data.length() - 1;
for(int i = 0; i <= maxIndex && found <= index; i++) {
if(data.charAt(i) == separator || i == maxIndex) {
found++;
strIndex[0] = strIndex[1] + 1;
strIndex[1] = (i == maxIndex) ? i + 1 : i;
}
}
return found > index ? data.substring(strIndex[0], strIndex[1]) : "";
}
String boolToOnOff(bool value) {
if (value)
return "ON";
else
return "OFF";
}
/* ========
* Setups
* ======== */
void setupSettings() {
EEPROM.begin(512);
int saved = EEPROM.read(EEPROM_SAVED);
EEPROM.end();
if (saved == 1) {
Serial.println("\nSettings already exist. Loading...");
loadSettings();
}
else {
settings.lcdBacklight = DEFAULT_LCD_BACKLIGHT;
settings.screenMain = DEFAULT_SCREEN_MAIN;
settings.screenSett = DEFAULT_SCREEN_SETT;
settings.remoteBeeps = DEFAULT_REMOTE_BEEPS;
settings.gasSensor = DEFAULT_GAS_SENSOR;
settings.geigerClicks = DEFAULT_GEIG_CLICKS;
settings.geigerAlarm = DEFAULT_GEIG_ALARM;
settings.geigerSensitivity = DEFAULT_GEIG_SENSITIVITY;
settings.intervalMeasure = DEFAULT_INT_MEASURE;
settings.intervalPush = DEFAULT_INT_PUSH;
settings.intervalPull = DEFAULT_INT_PULL;
settings.intervalSync = DEFAULT_INT_SYNC;
settings.wifi = DEFAULT_WIFI;
Serial.println("\nCreated new settings. Saving...");
saveSettings();
}
lcd.setBacklight(settings.lcdBacklight);
}
void setupStates() {
states.screenSettings = false;
states.alarm = false;
states.alarmOn = false;
states.datePage = 0;
states.wifi = settings.wifi;
}
void setupCounters() {
counters.measure = 0;
counters.push = 0;
counters.pull = 0;
counters.sync = 0;
}
void setupWiFi() {
host = WIFI_HOST;
ssid[0] = WIFI_0_SSID;
pass[0] = WIFI_0_PASS;
conf[0] = WIFI_0_CONF;
ssid[1] = WIFI_1_SSID;
pass[1] = WIFI_1_PASS;
conf[1] = WIFI_1_CONF;
ssid[2] = WIFI_2_SSID;
pass[2] = WIFI_2_PASS;
conf[2] = WIFI_2_CONF;
}
void setupDevices() {
dht.begin();
bmp.begin();
irrecv.enableIRIn();
mag.begin();
mag.setRange(HMC5883L_RANGE_1_3GA);
mag.setMeasurementMode(HMC5883L_CONTINOUS);
mag.setDataRate(HMC5883L_DATARATE_30HZ);
mag.setSamples(HMC5883L_SAMPLES_8);
pinMode(PIN_RELAY_GEIG, OUTPUT);
pinMode(PIN_RELAY_GAS, OUTPUT);
pinMode(PIN_GEIGER, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(PIN_GEIGER), geigerClick, CHANGE);
setRelays();
}
void setupClock() {
rtc.Begin();
if (!rtc.IsDateTimeValid()) {
RtcDateTime compiled = RtcDateTime(__DATE__, __TIME__);
Serial.println("RTC lost confidence in the DateTime!");
rtc.SetDateTime(compiled);
}
if (!rtc.GetIsRunning()) {
Serial.println("RTC was not actively running, starting now");
rtc.SetIsRunning(true);
}
rtc.Enable32kHzPin(false);
rtc.SetSquareWavePin(DS3231SquareWavePin_ModeNone);
}
void setupTimer() {
os_timer_setfn(&timer, processTimer, NULL);
os_timer_arm(&timer, INTERVAL_TIMER, true);
os_timer_setfn(&timerAlarm, processAlarm, NULL);
os_timer_arm(&timerAlarm, INTERVAL_ALARM, true);
}
/* ==========
* Settings
* ========== */
void saveSettings() {
EEPROM.begin(512);
EEPROM.write(EEPROM_SAVED, 1);
EEPROM.write(EEPROM_LCD_BACKLIGHT, settings.lcdBacklight);
EEPROM.write(EEPROM_SCREEN_MAIN, settings.screenMain);
EEPROM.write(EEPROM_SCREEN_SETT, settings.screenSett);
EEPROM.write(EEPROM_REMOTE_BEEPS, settings.remoteBeeps);
EEPROM.write(EEPROM_GAS_SENSOR, settings.gasSensor);
EEPROM.write(EEPROM_GEIG_CLICKS, settings.geigerClicks);
EEPROM.write(EEPROM_GEIG_ALARM, settings.geigerAlarm);
EEPROM.write(EEPROM_GEIG_SENSITIVITY, settings.geigerSensitivity / 100);
EEPROM.write(EEPROM_INT_MEASURE, settings.intervalMeasure / 1000);
EEPROM.write(EEPROM_INT_PUSH, settings.intervalPush / 1000);
EEPROM.write(EEPROM_INT_PULL, settings.intervalPull / 1000);
EEPROM.write(EEPROM_INT_SYNC, settings.intervalSync / 1000);
EEPROM.write(EEPROM_WIFI, settings.wifi);
EEPROM.end();
Serial.println("Saved settings to EEPROM.");
}
void loadSettings() {
EEPROM.begin(512);
settings.lcdBacklight = (bool) EEPROM.read(EEPROM_LCD_BACKLIGHT);
settings.screenMain = (int) EEPROM.read(EEPROM_SCREEN_MAIN);
settings.screenSett = (int) EEPROM.read(EEPROM_SCREEN_SETT);
settings.remoteBeeps = (bool) EEPROM.read(EEPROM_REMOTE_BEEPS);
settings.gasSensor = (bool) EEPROM.read(EEPROM_GAS_SENSOR);
settings.geigerClicks = (bool) EEPROM.read(EEPROM_GEIG_CLICKS);
settings.geigerAlarm = (bool) EEPROM.read(EEPROM_GEIG_ALARM);
settings.geigerSensitivity = (int) EEPROM.read(EEPROM_GEIG_SENSITIVITY) * 100;
settings.intervalMeasure = (int) EEPROM.read(EEPROM_INT_MEASURE) * 1000;
settings.intervalPush = (int) EEPROM.read(EEPROM_INT_PUSH) * 1000;
settings.intervalPull = (int) EEPROM.read(EEPROM_INT_PULL) * 1000;
settings.intervalSync = (int) EEPROM.read(EEPROM_INT_SYNC) * 1000;
settings.wifi = (int) EEPROM.read(EEPROM_WIFI);
EEPROM.end();
Serial.println("Loaded settings from EEPROM.");
}
/* ======
* WiFi
* ====== */
void connectWiFi() {
WiFi.mode(WIFI_STA);
WiFi.hostname(host);
if (settings.wifi < COUNT_WIFI) {
if (conf[settings.wifi] != "DHCP") {
String address;
IPAddress ipLocal = getIPFromString(conf[settings.wifi], 0);
IPAddress ipGateway = getIPFromString(conf[settings.wifi], 1);
IPAddress ipSubnet = getIPFromString(conf[settings.wifi], 2);
IPAddress ipDNS1 = getIPFromString(conf[settings.wifi], 3);
IPAddress ipDNS2 = getIPFromString(conf[settings.wifi], 4);
WiFi.config(ipLocal, ipGateway, ipSubnet, ipDNS1, ipDNS2);
}
WiFi.begin(ssid[settings.wifi], pass[settings.wifi]);
}
}
/* ===========
* Processes
* =========== */
void processTimer(void *pArg) {
//Serial.println("Timer tick!");
if (checkInterval(&counters.measure, settings.intervalMeasure))
intervals.measure = true;
if (checkInterval(&counters.geiger, INTERVAL_GEIGER))
intervals.geiger = true;
if (checkInterval(&counters.cclock, INTERVAL_CLOCK))
intervals.cclock = true;
if (checkInterval(&counters.push, settings.intervalPush))
intervals.push = true;
if (checkInterval(&counters.pull, settings.intervalPull))
intervals.pull = true;
if (checkInterval(&counters.sync, settings.intervalSync))
intervals.sync = true;
if (checkInterval(&counters.lcd, INTERVAL_LCD))
intervals.lcd = true;
}
void processAlarm(void *pArg) {
if (settings.geigerAlarm && states.alarm) {
if (states.alarmOn) {
noTone(PIN_BUZZER);
states.alarmOn = false;
}
else {
tone(PIN_BUZZER, BUZZER_ALARM_TONE);
states.alarmOn = true;
}
}
}
void processRemote() {
if (irrecv.decode(&results)) {
if (irrecv.decode(&results)) {
if (((results.value & 0xFF0000) == 0xFF0000) && (results.value != 0xFFFFFFFF)) {
//Serial.println(results.value, HEX);
switch(results.value) {
case IR_BACKLIGHT:
settings.lcdBacklight = !settings.lcdBacklight;
saveSettings();
counters.lcd = 0;
lcd.setBacklight(settings.lcdBacklight);
if (!settings.lcdBacklight)
lcd.clear();
beepRemote();
break;
case IR_SETTINGS:
if (settings.lcdBacklight) {
states.screenSettings = !states.screenSettings;
if (!states.screenSettings) {
if (states.wifi != settings.wifi)
ESP.restart();
if (data.dose >= (float) settings.geigerSensitivity / 1000) {
states.alarm = true;
}
else {
states.alarm = false;
states.alarmOn = false;
noTone(PIN_BUZZER);
}
}
resetLCD();
}
break;
case IR_DATETIME:
if (settings.lcdBacklight && states.screenSettings && settings.screenSett == SCREEN_SETT_DATETIME) {
if (states.datePage >= 5)
states.datePage = 0;
else
states.datePage++;
resetLCD();
}
break;
case IR_PREV: screenPrev(); break;
case IR_NEXT: screenNext(); break;
case IR_S0: screenSet(0); break;
case IR_S1: screenSet(1); break;
case IR_S2: screenSet(2); break;
case IR_S3: screenSet(3); break;
case IR_S4: screenSet(4); break;
case IR_S5: screenSet(5); break;
case IR_S6: screenSet(6); break;
case IR_S7: screenSet(7); break;
case IR_S8: screenSet(8); break;
case IR_S9: screenSet(9); break;
case IR_S10: screenSet(10); break;
//case IR_S11: screenSet(11); break;
case IR_DECREASE: valueDecrease(); break;
case IR_INCREASE: valueIncrease(); break;
}
}
irrecv.resume();
}
}
}
void processSensors() {
if (intervals.measure) {
intervals.measure = false;
float readValue;
readValue = dht.readTemperature();
if (String(readValue) != "nan") {
data.temperature = readValue;
average.temperature += readValue;
}
else {
Serial.println("Error reading Temperature.");
average.temperature += data.temperature;
}
average.temperatureCount++;
readValue = dht.readHumidity();
if (String(readValue) != "nan") {
data.humidity = readValue;
average.humidity += readValue;
}
else {
Serial.println("Error reading Humidity.");
average.humidity += data.humidity;
}
average.humidityCount++;
char stat;
double temp, pres,p0,a;
stat = bmp.startTemperature();
if (stat != 0) {
delay(stat);
stat = bmp.getTemperature(temp);
if (stat != 0) {
stat = bmp.startPressure(3);
if (stat != 0) {
delay(stat);
stat = bmp.getPressure(pres, temp);
if (stat != 0) {
readValue = (float) bmp.sealevel(pres, ALTITUDE);
data.pressure = readValue;
average.pressure += readValue;
average.pressureCount++;
}
}
}
}
if (settings.gasSensor) {
readValue = ((1023 - (float) analogRead(PIN_MQ)) / 1023) * 100;
data.gas = readValue;
average.gas += readValue;
average.gasCount++;
}
Vector raw = mag.readRaw();
float magX = (float) raw.XAxis / 10;
float magY = (float) raw.YAxis / 10;
float magZ = (float) raw.ZAxis / 10;
readValue = sqrt(magX * magX + magY * magY + magZ * magZ);
data.magnitude = readValue;
average.magnitude += readValue;
average.magnitudeCount++;
readValue = 90 - (acos(magZ / readValue) * (180 / PI));
data.inclination = readValue;
average.inclination += readValue;
average.inclinationCount++;
}
}
void processGeiger() {
if (intervals.geiger) {
intervals.geiger = false;
data.cpm = data.cpmNow;
data.dose = ((float) data.cpm * DOSE_MULTI);
data.cpmNow = 0;
if (data.dose >= (float) settings.geigerSensitivity / 1000) {
states.alarm = true;
}
else {
states.alarm = false;
states.alarmOn = false;
noTone(PIN_BUZZER);
}
}
}
void processClock() {
if (intervals.cclock) {
intervals.cclock = false;
if (!rtc.IsDateTimeValid())
Serial.println("RTC lost confidence in the DateTime!");
now = rtc.GetDateTime();
}
}
void processPush() {
if (intervals.push) {
intervals.push = false;
pushVariPass();
}
}
void processPull() {
if (intervals.pull) {
intervals.pull = false;
pullVariPass();
}
}
void processSync() {
if (intervals.sync) {
intervals.sync = false;
syncVariPass();
}
}
void processLCD() {
if (intervals.lcd) {
intervals.lcd = false;
if (states.screenSettings) {
switch (settings.screenSett) {
case SCREEN_SETT_REMOTE_BEEPS:
drawScreen(
"> Remote Beeps",
"Value: " + boolToOnOff(settings.remoteBeeps)
);
break;
case SCREEN_SETT_GAS_SENSOR:
drawScreen(
"> Gas Sensor",
"Value: " + boolToOnOff(settings.gasSensor)
);
break;
case SCREEN_SETT_GEIG_CLICKS:
drawScreen(
"> Geiger Clicks",
"Value: " + boolToOnOff(settings.geigerClicks)
);
break;
case SCREEN_SETT_GEIG_ALARM:
drawScreen(
"> Geiger Alarm",
"Value: " + boolToOnOff(settings.geigerAlarm)
);
break;
case SCREEN_SETT_GEIG_SENSITIVITY:
drawScreen(
"> Geiger Sensit.",
"Value: " + String((float) settings.geigerSensitivity / 1000, 2) + " uSv"
);
break;
case SCREEN_SETT_INT_MEASURE:
drawScreen(
"> Measure Inter.",
"Value: " + String(settings.intervalMeasure / 1000) + " s"
);
break;
case SCREEN_SETT_INT_PUSH:
drawScreen(
"> Pushing Inter.",
"Value: " + String(settings.intervalPush / 1000) + " s"
);
break;
case SCREEN_SETT_INT_PULL:
drawScreen(
"> Pulling Inter.",
"Value: " + String(settings.intervalPull / 1000) + " s"
);
break;
case SCREEN_SETT_INT_SYNC:
drawScreen(
"> Syncing Inter.",
"Value: " + String(settings.intervalSync / 1000) + " s"
);
break;
case SCREEN_SETT_WIFI: {
String wifi = "0: DISABLED";
if (settings.wifi < COUNT_WIFI)
wifi = String(settings.wifi + 1) + ": " + ssid[settings.wifi];
drawScreen(
"> WiFi Network",
wifi
);
break;
}
case SCREEN_SETT_DATETIME: {
String title = "> Date and Time";
String value = "";
char shortString[3];
char longString[5];
switch (states.datePage) {
case DATETIME_HOURS:
snprintf_P(shortString, 3, PSTR("%02u"), now.Hour());
value = "Hours: " + String(shortString);
break;
case DATETIME_MINUTES:
snprintf_P(shortString, 3, PSTR("%02u"), now.Minute());
value = "Minutes: " + String(shortString);
break;
case DATETIME_SECONDS:
snprintf_P(shortString, 3, PSTR("%02u"), now.Second());
value = "Seconds: " + String(shortString);
break;
case DATETIME_YEAR:
snprintf_P(longString, 5, PSTR("%02u"), now.Year());
value = "Year: " + String(longString);
break;
case DATETIME_MONTH:
snprintf_P(shortString, 3, PSTR("%02u"), now.Month());
value = "Month: " + String(shortString);
break;
case DATETIME_DAY:
snprintf_P(shortString, 3, PSTR("%02u"), now.Day());
value = "Day: " + String(shortString);
break;
}
drawScreen(
title,
value
);
break;
}
}
}
else {
switch (settings.screenMain) {
case SCREEN_MAIN_TIME:
char timeString[6];
char dateString[11];
snprintf_P(timeString, 6, PSTR("%02u:%02u"), now.Hour(), now.Minute());
snprintf_P(dateString, 11, PSTR("%04u-%02u-%02u"), now.Year(), now.Month(), now.Day());
drawScreen(
" " + String(timeString),
" " + String(dateString)
);
break;
case SCREEN_MAIN_DHT:
drawScreen(
"Tmp: " + String(data.temperature, 1) + " " + (char)223 + "C",
"Hmi: " + String(data.humidity, 1) + " %"
);
break;
case SCREEN_MAIN_BMPMQ: {
String gas = "N/A";
if (settings.gasSensor)
gas = String(data.gas, 2) + " %";
drawScreen(
"Prs: " + String(data.pressure, 2) + " hPa",
"Air: " + gas
);
break;
}
case SCREEN_MAIN_MAG:
drawScreen(
"Mag: " + String(data.magnitude, 2) + " uT",
"Inc: " + String(data.inclination, 2) + " " + (char)223
);
break;
case SCREEN_MAIN_GEIGER:
drawScreen(
"CPM: " + String(data.cpm) + " [" + String(data.cpmNow) + "]",
"Dos: " + String(data.dose, 2) + " uSv/h"
);
break;
case SCREEN_MAIN_CORE:
if (WiFi.status() != WL_CONNECTED || settings.wifi == COUNT_WIFI)
drawScreen(
"WiFi Unavailable",
""
);
else
drawScreen(
formatNumbers(data.core, COMPACT_LONG, false, true, "RF"),
formatNumbers(data.gain, COMPACT_SHORT, true, true, "RF/t")
);
break;
case SCREEN_MAIN_BULLETIN:
if (WiFi.status() != WL_CONNECTED || settings.wifi == COUNT_WIFI)
drawScreen(
"WiFi Unavailable",
""
);
else {
String bullA = data.bulletin;
String bullB = "";
if (bullA.length() > 16)
bullB = bullA.substring(16);
drawScreen(
bullA,
bullB
);
}
break;
case SCREEN_MAIN_WIFI: {
String wifi = " Connecting...";
if (settings.wifi == COUNT_WIFI)
wifi = " Disabled";
else if (WiFi.status() == WL_CONNECTED)
wifi = " Connected";
drawScreen(
"WiFi Status:",
wifi
);
break;
}
}
}
}
}
/* ==========
* VariPass
* ========== */
void pullVariPass() {
if (WiFi.status() == WL_CONNECTED && !states.screenSettings)
switch (settings.screenMain) {
int result;
case SCREEN_MAIN_CORE:
long value1;
value1 = varipassReadInt(KEY2, ID_CORE, &result);
if (result == VARIPASS_RESULT_SUCCESS)
data.core = value1;
else
Serial.println("An error has occured reading Core data! " + varipassGetResultDescription(result));
value1 = varipassReadInt(KEY2, ID_GAIN, &result);
if (result == VARIPASS_RESULT_SUCCESS)
data.gain = value1;
else
Serial.println("An error has occured reading Gain data! " + varipassGetResultDescription(result));
break;
case SCREEN_MAIN_BULLETIN:
String value2;
value2 = varipassReadString(KEY1, ID_BULLETIN, &result);
if (result == VARIPASS_RESULT_SUCCESS)
data.bulletin = value2;
else
Serial.println("An error has occured reading Bulletin data! " + varipassGetResultDescription(result));
break;
}
}
void pushVariPass() {
if (WiFi.status() == WL_CONNECTED) {
int result;
varipassWriteFloat(KEY1, ID_TEMPERATURE, average.temperature / average.temperatureCount, &result);
varipassWriteFloat(KEY1, ID_HUMIDITY, average.humidity / average.humidityCount, &result);
varipassWriteFloat(KEY1, ID_PRESSURE, average.pressure / average.pressureCount, &result);
if (settings.gasSensor)
varipassWriteFloat(KEY1, ID_GAS, average.gas / average.gasCount, &result);
varipassWriteFloat(KEY1, ID_MAGNITUDE, average.magnitude / average.magnitudeCount, &result);
varipassWriteFloat(KEY1, ID_INCLINATION, average.inclination / average.inclinationCount, &result);
}
resetAverage();
}
void syncVariPass() {
if (WiFi.status() == WL_CONNECTED) {
int result;
if (states.pushSync) {
Serial.println("Syncing data to VariPass...");
varipassWriteBool(KEY1, ID_TGL_CLICKS, settings.geigerClicks, &result);
if (result == VARIPASS_RESULT_SUCCESS)
states.pushSync = false;
else
Serial.println("An error has occured writing geiger click settings! " + varipassGetResultDescription(result));
}
else {
bool value;
value = varipassReadBool(KEY1, ID_TGL_CLICKS, &result);
if (result == VARIPASS_RESULT_SUCCESS) {
if (value != settings.geigerClicks) {
settings.geigerClicks = value;
setRelays();
saveSettings();
counters.lcd = 0;
}
}
else {
Serial.println("An error has occured reading geiger click settings! " + varipassGetResultDescription(result));
}
}
}
}
/* ========
* Remote
* ======== */
void screenPrev() {
if (settings.lcdBacklight) {
if (states.screenSettings) {
if (settings.screenSett <= 0)
settings.screenSett = SCREENS_SETT - 1;
else
settings.screenSett--;
}
else {
if (settings.screenMain <= 0)
settings.screenMain = SCREENS_MAIN - 1;
else
settings.screenMain--;
}
saveSettings();
resetLCD();
}
}
void screenNext() {
if (settings.lcdBacklight) {
if (states.screenSettings) {
if (settings.screenSett >= SCREENS_SETT - 1)
settings.screenSett = 0;
else
settings.screenSett++;
}
else {
if (settings.screenMain >= SCREENS_MAIN - 1)
settings.screenMain = 0;
else
settings.screenMain++;
}
saveSettings();
resetLCD();
}
}
void screenSet(int page) {
if (settings.lcdBacklight) {
if (states.screenSettings) {
if (page < SCREENS_SETT)
settings.screenSett = page;
}
else {
if (page < SCREENS_MAIN)
settings.screenMain = page;
}
saveSettings();
resetLCD();
}
}
void valueDecrease() {
if (states.screenSettings && settings.lcdBacklight) {
bool process = false;
switch (settings.screenSett) {
case SCREEN_SETT_REMOTE_BEEPS:
settings.remoteBeeps = !settings.remoteBeeps;
process = true;
break;
case SCREEN_SETT_GAS_SENSOR:
settings.gasSensor = !settings.gasSensor;
setRelays();
process = true;
break;
case SCREEN_SETT_GEIG_CLICKS:
settings.geigerClicks = !settings.geigerClicks;
setRelays();
states.pushSync = true;
process = true;
break;
case SCREEN_SETT_GEIG_ALARM:
settings.geigerAlarm = !settings.geigerAlarm;
process = true;
break;
case SCREEN_SETT_GEIG_SENSITIVITY:
settings.geigerSensitivity -= STP_GEIG_SENSITIVITY;
if (settings.geigerSensitivity < MIN_GEIG_SENSITIVITY)
settings.geigerSensitivity = MIN_GEIG_SENSITIVITY;
process = true;
break;
case SCREEN_SETT_INT_MEASURE:
settings.intervalMeasure -= STP_INT_MEASURE;
if (settings.intervalMeasure < MIN_INT_MEASURE)
settings.intervalMeasure = MIN_INT_MEASURE;
process = true;
break;
case SCREEN_SETT_INT_PUSH:
settings.intervalPush -= STP_INT_PUSH;
if (settings.intervalPush < MIN_INT_PUSH)
settings.intervalPush = MIN_INT_PUSH;
process = true;
break;
case SCREEN_SETT_INT_PULL:
settings.intervalPull -= STP_INT_PULL;
if (settings.intervalPull < MIN_INT_PULL)
settings.intervalPull = MIN_INT_PULL;
process = true;
break;
case SCREEN_SETT_INT_SYNC:
settings.intervalSync -= STP_INT_SYNC;
if (settings.intervalSync < MIN_INT_SYNC)
settings.intervalSync = MIN_INT_SYNC;
process = true;
break;
case SCREEN_SETT_WIFI:
if (settings.wifi <= 0)
settings.wifi = COUNT_WIFI;
else
settings.wifi--;
process = true;
break;
case SCREEN_SETT_DATETIME: {
RtcDateTime newTime;
switch (states.datePage) {
case DATETIME_HOURS:
newTime = now - 1 * 60 * 60;
break;
case DATETIME_MINUTES:
newTime = now - 1 * 60;
break;
case DATETIME_SECONDS:
newTime = now - 1;
break;
case DATETIME_YEAR:
if (now.Year() > 1970)
newTime = RtcDateTime(now.Year() - 1, now.Month(), now.Day(), now.Hour(), now.Minute(), now.Second());
break;
case DATETIME_MONTH:
if (now.Month() > 1)
newTime = RtcDateTime(now.Year(), now.Month() - 1, now.Day(), now.Hour(), now.Minute(), now.Second());
else
newTime = RtcDateTime(now.Year() - 1, 12, now.Day(), now.Hour(), now.Minute(), now.Second());
break;
case DATETIME_DAY:
newTime = now - 1 * 60 * 60 * 24;
break;
}
rtc.SetDateTime(newTime);
now = rtc.GetDateTime();
resetLCD();
break;
}
}
if (process) {
resetLCD();
saveSettings();
}
}
}
void valueIncrease() {
if (states.screenSettings && settings.lcdBacklight) {
bool process = false;
switch (settings.screenSett) {
case SCREEN_SETT_REMOTE_BEEPS:
settings.remoteBeeps = !settings.remoteBeeps;
process = true;
break;
case SCREEN_SETT_GAS_SENSOR:
settings.gasSensor = !settings.gasSensor;
setRelays();
process = true;
break;
case SCREEN_SETT_GEIG_CLICKS:
settings.geigerClicks = !settings.geigerClicks;
setRelays();
states.pushSync = true;
process = true;
break;
case SCREEN_SETT_GEIG_ALARM:
settings.geigerAlarm = !settings.geigerAlarm;
process = true;
break;
case SCREEN_SETT_GEIG_SENSITIVITY:
settings.geigerSensitivity += STP_GEIG_SENSITIVITY;
if (settings.geigerSensitivity > MAX_GEIG_SENSITIVITY)
settings.geigerSensitivity = MAX_GEIG_SENSITIVITY;
process = true;
break;
case SCREEN_SETT_INT_MEASURE:
settings.intervalMeasure += STP_INT_MEASURE;
if (settings.intervalMeasure > MAX_INT_MEASURE)
settings.intervalMeasure = MAX_INT_MEASURE;
process = true;
break;
case SCREEN_SETT_INT_PUSH:
settings.intervalPush += STP_INT_PUSH;
if (settings.intervalPush > MAX_INT_PUSH)
settings.intervalPush = MAX_INT_PUSH;
process = true;
break;
case SCREEN_SETT_INT_PULL:
settings.intervalPull += STP_INT_PULL;
if (settings.intervalPull > MAX_INT_PULL)
settings.intervalPull = MAX_INT_PULL;
process = true;
break;
case SCREEN_SETT_INT_SYNC:
settings.intervalSync += STP_INT_SYNC;
if (settings.intervalSync > MAX_INT_SYNC)
settings.intervalSync = MAX_INT_SYNC;
process = true;
break;
case SCREEN_SETT_WIFI:
if (settings.wifi >= COUNT_WIFI)
settings.wifi = 0;
else
settings.wifi++;
process = true;
break;
case SCREEN_SETT_DATETIME: {
RtcDateTime newTime;
switch (states.datePage) {
case DATETIME_HOURS:
newTime = now + 1 * 60 * 60;
break;
case DATETIME_MINUTES:
newTime = now + 1 * 60;
break;
case DATETIME_SECONDS:
newTime = now + 1;
break;
case DATETIME_YEAR:
if (now.Year() < 2100)
newTime = RtcDateTime(now.Year() + 1, now.Month(), now.Day(), now.Hour(), now.Minute(), now.Second());
break;
case DATETIME_MONTH:
if (now.Month() < 12)
newTime = RtcDateTime(now.Year(), now.Month() + 1, now.Day(), now.Hour(), now.Minute(), now.Second());
else
newTime = RtcDateTime(now.Year() + 1, 1, now.Day(), now.Hour(), now.Minute(), now.Second());
break;
case DATETIME_DAY:
newTime = now + 1 * 60 * 60 * 24;
break;
}
rtc.SetDateTime(newTime);
now = rtc.GetDateTime();
resetLCD();
break;
}
}
if (process) {
resetLCD();
saveSettings();
}
}
}
/* =======
* Beeps
* ======= */
void beepRemote() {
if (settings.remoteBeeps) {
tone(PIN_BUZZER, BUZZER_REMOTE_TONE, BUZZER_REMOTE_DURATION);
}
}
void setup() {
Serial.begin(115200);
lcd.init();
lcd.setBacklight(true);
drawScreen(" == Alicorn ==", " Starting...");
setupSettings();
setupStates();
setupCounters();
setupWiFi();
setupDevices();
setupClock();
resetAverage();
connectWiFi();
drawScreen("", "");
setupTimer();
}
void loop() {
processRemote();
processSensors();
processGeiger();
processSync();
processPush();
if (settings.lcdBacklight) {
processPull();
processClock();
processLCD();
}
delay(INTERVAL_CYCLE);
}
| [
"thorinair@yahoo.com"
] | thorinair@yahoo.com |
33f4b2ba59f7e0d0ff39be4cdb09e8ae8111b984 | d97082ea4d8b7f8771141c50a0fbf611267afbee | /LogMacro.cpp | 348b7c39cd18bfbcd3be0db38deb6cba387fefac | [
"MIT"
] | permissive | Zaita/Coffee-Time | ecd436ed5f62c138879804f9aac0d46b9e7912e6 | d410fb8dacc53bb600c71584624d86818772e2dc | refs/heads/master | 2021-01-20T09:12:40.892738 | 2020-10-22T22:49:52 | 2020-10-22T22:49:52 | 22,824,317 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 677 | cpp | /*
* Problem:
* Create a macro that allows you to log out lines using a stream format.
*
* The macro must allow you to continue the streaming on the returned object and automatically
* handle flushing and new lines at the end of each statement. For simplicity you can use
* cout as the stream to print directly to stdout
*
* Expected output:
* [WARNING] - Hello World
* [ERROR] - The quick brown fox
*/
#include <iostream>
#include <string>
using std::string;
using std::cout;
using std::endl;
// Add LOG macro here
#define LOG()
int main(int, char*[]) {
LOG("WARNING") << "Hello" << " World";
LOG("ERROR") << "The quick" << " brown " << "fox";
return 0;
}
| [
"scott@zaita.com"
] | scott@zaita.com |
09f16b448a2cd1f217d0e7618c485301b61af072 | 70c00133e353a5555514327f0a3a20e9bd3de737 | /Problem-1202.cpp | e790e13357a6f7f96ebf06505cc1b3020b5f82e0 | [] | no_license | VikasKumarRoy/Leetcode | 536d33a67d5448d75171682d82be7518648f39af | 953fe0380c0e64077fb2943d06b4ec0638a3c688 | refs/heads/master | 2021-06-25T16:18:47.367509 | 2021-03-21T16:58:45 | 2021-03-21T16:58:45 | 200,166,984 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,108 | cpp | //Problem - 1202
// https://leetcode.com/problems/smallest-string-with-swaps/
// O(nlogn) time complexity and O(n) space complexity sol using disjoint set
class Solution {
public:
int find(vector <int> &ds, int i) {
if(ds[i] < 0)
return i;
else
return ds[i] = find(ds, ds[i]);
}
string smallestStringWithSwaps(string s, vector<vector<int>>& pairs) {
vector <int> ds(s.length(), -1);
for(int i = 0 ; i < pairs.size(); i++){
int j = find(ds, pairs[i][0]);
int k = find(ds, pairs[i][1]);
if(j != k)
ds[j] = k;
}
unordered_map <int, vector <int>> m;
for(int i = 0; i < s.length(); i++)
m[find(ds, i)].push_back(i);
for(auto itr : m) {
string str = "";
vector <int> t = itr.second;
for(auto val : t) {
str += s[val];
}
sort(str.begin(), str.end());
for(int i = 0; i < t.size(); i++)
s[t[i]] = str[i];
}
return s;
}
}; | [
"vikas.vr8@gmail.com"
] | vikas.vr8@gmail.com |
a2f0730103fc83d3026d46a661b088b6db78655b | 48113249b9c24b965a55cd8cef98d9a6edc0bb31 | /sidescroller/player.cpp | 7ff457aa497054760be096f9c7d228f6937dd589 | [] | no_license | janww/sidescroller | f2d6e16784be5585f16334119b35be28f8e79abb | caac450f92272b8b13710236cde73322a558755c | refs/heads/master | 2020-12-24T13:28:59.400165 | 2011-10-06T18:59:13 | 2011-10-06T18:59:13 | 2,528,012 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,918 | cpp | #include "player.h"
player::player(SDL_Surface* img)
{
image = img;
box.x = 0;
box.y = 0;
box.w = 50;
box.h = 100;
xvel = 0;
yvel = 0;
ground = false;
for(int i=0; i < player::FRAMES; i++)
{
frames[i].x = baseclass::TILE_BORDER_SIZE + i * 50;
frames[i].y = 0;
frames[i].w = 50;
frames[i].h = 100;
}
}
player::~player()
{
SDL_FreeSurface(image);
}
SDL_Rect* player::getRect()
{
return &box;
}
int player::getXvel()
{
return xvel;
}
void player::setXvel(int vel)
{
xvel = vel;
}
void player::show(SDL_Surface* screen)
{
SDL_BlitSurface(image, &frames[0], screen, &box);
}
void player::move(const std::vector<std::vector<int>>&map)
{
int start = (baseclass::coord.x - (baseclass::coord.x % baseclass::TILE_SIZE)) / baseclass::TILE_SIZE;
int end = (baseclass::coord.x + baseclass::coord.w + (baseclass::TILE_SIZE - (baseclass::coord.x + baseclass::coord.w) % baseclass::TILE_SIZE)) / baseclass::TILE_SIZE;
if(start < 0)
start = 0;
if(end > map[0].size())
end = map[0].size();
bool nocollision = false;
for(int i = 0; i < map.size(); i++)
for(int j = start; j < end; j++)
{
if(map[i][j] == 0)
continue;
SDL_Rect destrect = {j * 50 - baseclass::coord.x, i * 50, 50, 50};
if(collision(&box, &destrect))
{
nocollision = true;
if(destrect.y >= box.y + box.h - 11)
{
ground = true;
yvel = 0;
} else if(destrect.y + destrect.h <= box.y + 11)
{
box.x++;
yvel = 5;
}
if(box.x + box.w >= destrect.x - 5 && box.y + box.h >= destrect.y + 6 && box.x + box.w <= destrect.x + 20)
{
xvel = 0;
box.x--;
} else if(box.x <= destrect.x + destrect.w && box.y + box.h >= destrect.y + 6)
{
xvel = 0;
box.x++;
}
}
}
if(!nocollision)
{
yvel = 5;
}
box.x += xvel;
box.y += yvel;
} | [
"mail@janwiemer.de"
] | mail@janwiemer.de |
fea6e78903784d11164174c169f7a3e24bfbab73 | db05479d0cf14716ecab32fe4b3cd4af424492f7 | /src/frontend/network.h | 2320a782ca14b7cf3c6f8b1d0c42d9bbfff05531 | [
"Zlib"
] | permissive | AquaFlyRat/PotatoAdventure | 8ddb4c2d7c5f152a630561e713992f6171e0289f | f673d8f520ba88b7ff73888b5871aae99f1ab6b6 | refs/heads/master | 2020-04-05T14:34:09.495576 | 2017-07-28T14:52:41 | 2017-07-28T14:52:41 | 94,682,563 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,776 | h | #ifndef NETWORK_H_INCLUDED
#define NETWORK_H_INCLUDED
#include "lib/sdl.h"
#include "lib/sdlnet.h"
#include "system.h"
#include "utils.h"
#include <cstdint>
namespace Network
{
#ifdef E0INTERNAL_NETWORK_H_SPECIAL_ACCESS
void Initialize();
void Cleanup();
#endif
struct Address : IPaddress
{
operator std::string() const
{
if (Utils::big_endian)
return Str((host & 0xff000000) >> 24, '.',
(host & 0xff0000) >> 16, '.',
(host & 0xff00) >> 8, '.',
(host & 0xff), ':',
port);
else
return Str((host & 0xff), '.',
(host & 0xff00) >> 8, '.',
(host & 0xff0000) >> 16, '.',
(host & 0xff000000) >> 24, ':',
SDL_Swap16(port));
}
Address()
{
host = 0;
port = 0;
}
Address(IPaddress o)
{
host = o.host;
port = o.port;
}
Address(std::string host, uint16_t port)
{
if (SDLNet_ResolveHost(this, host.c_str(), port))
Exceptions::Network::CantResolve(Str("Unable to resolve a host name: ", (host[0] ? host : "<null>"), ':', port));
}
};
class Server
{
TCPsocket socket;
SDLNet_SocketSet set;
bool connection_pending;
uint16_t port;
public:
Server()
{
socket = 0;
// set = 0 // This is not needed.
connection_pending = 0;
port = 0;
}
Server(uint16_t server_port)
{
socket = 0;
// set = 0 // This is not needed.
connection_pending = 0;
port = server_port;
Open(port);
}
Server(const Server &) = delete;
Server(Server &&o)
{
socket = o.socket;
set = o.set;
connection_pending = o.connection_pending;
port = o.port;
o.socket = 0;
// o.set = 0 // This is not needed.
o.connection_pending = 0;
o.port = 0;
}
Server &operator=(const Server &) = delete;
Server &operator=(Server &&o)
{
if (&o == this)
return *this;
Close();
socket = o.socket;
set = o.set;
connection_pending = o.connection_pending;
port = o.port;
o.socket = 0;
// o.set = 0 // This is not needed.
o.connection_pending = 0;
o.port = 0;
return *this;
}
~Server()
{
Close();
}
void Open(uint16_t server_port)
{
Address address;
address.host = INADDR_NONE;
if (Utils::big_endian)
address.port = server_port;
else
address.port = SDL_Swap16(server_port);
port = 0;
if (socket)
{
connection_pending = 0;
SDLNet_TCP_DelSocket(set, socket);
SDLNet_TCP_Close(socket);
socket = SDLNet_TCP_Open(&address);
if (!socket)
{
SDLNet_FreeSocketSet(set);
Exceptions::Network::CantCreateServer(Str(server_port));
}
if (!SDLNet_TCP_AddSocket(set, socket))
Sys::Error("Can't add a server socket to a set.");
}
else
{
socket = SDLNet_TCP_Open(&address);
if (!socket)
Exceptions::Network::CantCreateServer(Str(server_port));
set = SDLNet_AllocSocketSet(1);
if (!set)
Sys::Error("Can't allocate a socket set.");
if (!SDLNet_TCP_AddSocket(set, socket))
Sys::Error("Can't add a server socket to a set.");
}
port = server_port;
}
void Close()
{
if (socket)
{
connection_pending = 0;
port = 0;
SDLNet_TCP_DelSocket(set, socket);
SDLNet_FreeSocketSet(set);
SDLNet_TCP_Close(socket);
socket = 0;
}
}
operator bool() const
{
return socket;
}
uint16_t Port() const
{
return port;
}
bool ConnectionPending(int ms_timeout = 0)
{
if (!socket)
return 0;
if (connection_pending)
return 1;
int result = SDLNet_CheckSockets(set, ms_timeout);
if (result == -1)
Sys::Error("Can't check a socket set.");
connection_pending = result;
return connection_pending;
}
friend class Connection;
};
class Connection
{
TCPsocket socket;
SDLNet_SocketSet set;
bool has_data;
Address address;
public:
Connection()
{
socket = 0;
// set = 0 // This is not needed.
has_data = 0;
address = {};
}
Connection(Address ip)
{
socket = 0;
// set = 0 // This is not needed.
has_data = 0;
Open(ip);
}
Connection(const Connection &) = delete;
Connection(Connection &&o)
{
socket = o.socket;
set = o.set;
has_data = o.has_data;
address = o.address;
o.socket = 0;
// o.set = 0 // This is not needed.
o.has_data = 0;
o.address = {};
}
Connection &operator=(const Connection &) = delete;
Connection &operator=(Connection &&o)
{
if (&o == this)
return *this;
Close();
socket = o.socket;
set = o.set;
has_data = o.has_data;
address = o.address;
o.socket = 0;
// o.set = 0 // This is not needed.
o.has_data = 0;
o.address = {};
return *this;
}
~Connection()
{
Close();
}
void Open(Address ip)
{
if (ip.host == INADDR_NONE || ip.host == INADDR_ANY)
Exceptions::Network::CantConnect("Invalid IP.");
address = {};
if (socket)
{
has_data = 0;
SDLNet_TCP_DelSocket(set, socket);
SDLNet_TCP_Close(socket);
socket = SDLNet_TCP_Open(&ip);
if (!socket)
{
SDLNet_FreeSocketSet(set);
Exceptions::Network::CantConnect(ip);
}
if (!SDLNet_TCP_AddSocket(set, socket))
Sys::Error("Can't add a socket to a set.");
}
else
{
socket = SDLNet_TCP_Open(&ip);
if (!socket)
Exceptions::Network::CantConnect(ip);
set = SDLNet_AllocSocketSet(1);
if (!set)
Sys::Error("Can't allocate a socket set.");
if (!SDLNet_TCP_AddSocket(set, socket))
Sys::Error("Can't add a socket to a set.");
}
address = ip;
}
void Open(Server &server, int ms_timeout = 0)
{
if (!server.ConnectionPending(ms_timeout))
return;
address = {};
if (socket)
{
has_data = 0;
SDLNet_TCP_DelSocket(set, socket);
SDLNet_TCP_Close(socket);
socket = SDLNet_TCP_Accept(server.socket);
if (!socket)
{
SDLNet_FreeSocketSet(set);
return;
}
if (!SDLNet_TCP_AddSocket(set, socket))
Sys::Error("Can't add a socket to a set.");
}
else
{
socket = SDLNet_TCP_Accept(server.socket);
if (!socket)
return;
set = SDLNet_AllocSocketSet(1);
if (!set)
Sys::Error("Can't allocate a socket set.");
if (!SDLNet_TCP_AddSocket(set, socket))
Sys::Error("Can't add a socket to a set.");
}
address = *SDLNet_TCP_GetPeerAddress(socket);
}
void Close()
{
if (socket)
{
has_data = 0;
address = {};
SDLNet_TCP_DelSocket(set, socket);
SDLNet_FreeSocketSet(set);
SDLNet_TCP_Close(socket);
socket = 0;
}
}
operator bool() const
{
return socket;
}
Address Address()
{
return address;
}
bool DataAvailable(int ms_timeout = 0)
{
if (!socket)
return 0;
if (has_data)
return 1;
int result = SDLNet_CheckSockets(set, ms_timeout);
if (result == -1)
Sys::Error("Can't check a socket set.");
has_data = result;
return has_data;
}
int Receive(ArrayProxy<uint8_t> arr, int ms_timeout = 0) // Returns an amount of received bytes (or 0 if no data is available or if the socket was closed.).
{
if (!socket)
return 0;
if (!DataAvailable(ms_timeout))
return 0;
has_data = 0;
int result = SDLNet_TCP_Recv(socket, arr, arr.size());
if (result <= 0)
{
// A error has occured. We silently close the socket.
Close();
}
return (result > 0 ? result : 0);
}
bool Send(ArrayView<uint8_t> arr) // Returns 1 on success.
{
if (!socket)
return 0;
int result = SDLNet_TCP_Send(socket, arr, arr.size());
if (result < int(arr.size()))
{
// We can't send a data, so we assume a error has occured and we silently close the socket.
Close();
return 0;
}
return 1;
}
};
}
#endif
| [
"barneywilks1@gmail.com"
] | barneywilks1@gmail.com |
443e484c17569400347c8c054c5fa4251f4a5b71 | 02f26889b75b9605154cb3caf45a45ea9d01c0b9 | /include/start_goal_generator.h | 9a7f018d10d57ba1c76f824b15bbd38806007693 | [] | no_license | shivamvats/learning_egraphs2d | 74f3049b4ac0332dededc4bb933ed1e2a10aa2b8 | e21cb24c678b58d6c715a99975ee858ebdb6ca28 | refs/heads/master | 2021-01-23T06:19:57.957213 | 2017-06-04T03:47:43 | 2017-06-04T03:47:43 | 93,018,721 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 306 | h | #include "utils.h"
#include <stdlib.h>
class StartGoalGenerator {
public:
StartGoalGenerator(int seed = 23534);
void generateStartGoalOnCircle(smpl::RobotState &start_state,
smpl::RobotState &goal_state, Vector3d center, double radius);
private:
};
| [
"shivamvats.iitkgp@gmail.com"
] | shivamvats.iitkgp@gmail.com |
a11fb71dc3411fc0d68960d798cf1eb46b5294a0 | 178b352eec30579989c1d433dcb4826a4075894e | /Bomb.cpp | d9c73fe7b1f1e4cef99887787272b068c56d1f13 | [
"Unlicense"
] | permissive | catinapoke/opengl-1-intermediate-mode | bb95d282e7bea689247f4ece5f90fab9c5ee1c71 | 9562f258024408625688c52d349738ba9dfb83e4 | refs/heads/master | 2020-08-08T04:30:49.049451 | 2019-12-13T18:40:48 | 2019-12-13T18:40:48 | 213,713,636 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 746 | cpp | #include "Bomb.h"
int Bomb::fuseTime = 5000;
Bomb::Bomb():currentFuse(fuseTime)
{
}
Bomb::Bomb(ivec2 position, GameObjectType type):GameObject(position, type), currentFuse(fuseTime)
{
}
Bomb::~Bomb()
{
glm::ivec2 pos = this->getPosition();
printf("Bomb exploded in position %i %i", pos.x, pos.y);
}
void Bomb::Update(int milliseconds)
{
currentFuse -= milliseconds;
if (currentFuse <= 0)
{
Explode();
currentFuse = 0;
}
//printf("Fuse is %i\n Rate is %f\n", currentFuse, GetFuseRate());
}
void Bomb::SetCallbackExplodeEvent(void(*eventMethod)(Bomb* bomb))
{
ExplodeEvent = eventMethod;
}
float Bomb::GetFuseRate()
{
float rate = (currentFuse * 1.0f) / fuseTime;
return rate;
}
void Bomb::Explode()
{
ExplodeEvent(this);
} | [
"mihansp1@gmail.com"
] | mihansp1@gmail.com |
8f0edbb6a8af83325d016519f5b68e7c757fc51b | f0be8b268cb4405a9d40a1ea943a5352018173bb | /A 044 BST next node.cpp | bded82ff9bd53766c1b9c461a8eb04d939fca5f7 | [] | no_license | iroot900/Algorithm-Practice-300-Plus | 1b2cdce48104dec540e045dfcab6290fefe60e4b | 5b97c69c991d2b2f330d7b667e79dd32b53e44f5 | refs/heads/master | 2020-07-10T21:34:39.125332 | 2015-09-01T21:40:20 | 2015-09-01T21:40:20 | 36,990,843 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,139 | cpp | #include <iostream>
using namespace std;
struct node
{
node(int x):val(x){}
int val;
node* left=nullptr;
node* right=nullptr;
};
void travel(node* root)
{
if(!root) return;
travel(root->left);
cout<<root->val<<" ";
travel(root->right);
}
void add(node* &root, int x)
{
if(root==nullptr) {root=new node(x); return ;}
if(root->val>x) add(root->left,x);
else add(root->right,x);
}
void next(node* root, int val, int& nxt)
{
if(!root) return ;
if(root->val<=val) next(root->right,val,nxt);
else
{
nxt=min(nxt,root->val);
next(root->left,val,nxt);
}
}
bool find(node* root,int val)
{
auto cur=root;
while(cur)
{
if(cur->val==val) return true;
else if(cur->val>val) cur=cur->left;
else cur=cur->right;
}
return false;
}
int main()
{
node* root=nullptr;
for(int i=0;i<10;++i)
add(root,i*2);
travel(root);
cout<<endl;
for(int i=0;i<9;++i)
{
int nxt=INT_MAX;
next(root,i*2, nxt);
cout<<i*2<<"-next->"<<(nxt==INT_MAX?INT_MIN:nxt)<<endl;
}
for(int i=0;i<5;++i)
cout<<"find->" <<i*2<<" : "<<find(root,i*2)<<endl;
for(int i=0;i<5;++i)
cout<<"find->" <<i*2+1<<" : "<<find(root,i*2+1)<<endl;
}
| [
"iroot@gmail.com"
] | iroot@gmail.com |
ca3ff12fa0f2905d703fc812a128cdf8dd24bcdd | 4f398422d28ef17f492382603d9282cab148c357 | /tensorflow/compiler/xla/service/buffer_assignment_test.cc | 56138a7ee6c6b112d81239351c204865d132a7f4 | [
"Apache-2.0"
] | permissive | udacity/tensorflow | a57352c81edff9d04728934565e27b3aa62d2236 | 6a149df6722c7fc516966e1b6291bd459cec9ce0 | refs/heads/master | 2022-07-26T01:51:28.696064 | 2022-06-28T07:39:58 | 2022-06-28T07:39:58 | 79,862,441 | 9 | 11 | null | 2017-01-24T00:12:40 | 2017-01-24T00:12:39 | null | UTF-8 | C++ | false | false | 48,202 | cc | /* Copyright 2017 The TensorFlow Authors. 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 "tensorflow/compiler/xla/service/buffer_assignment.h"
#include <memory>
#include <set>
#include <string>
#include <vector>
#include "tensorflow/compiler/xla/literal_util.h"
#include "tensorflow/compiler/xla/ptr_util.h"
#include "tensorflow/compiler/xla/service/computation_tracker.h"
#include "tensorflow/compiler/xla/service/dfs_hlo_visitor_with_default.h"
#include "tensorflow/compiler/xla/service/hlo_computation.h"
#include "tensorflow/compiler/xla/service/hlo_instruction.h"
#include "tensorflow/compiler/xla/service/hlo_opcode.h"
#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/compiler/xla/tests/hlo_test_base.h"
#include "tensorflow/compiler/xla/types.h"
#include "tensorflow/compiler/xla/xla_data.pb.h"
#include "tensorflow/core/platform/macros.h"
namespace xla {
namespace {
// DFS visitor that collects the instructions referenced by a computation
// without descending into nested computations, i.e., only from the operands.
class InstructionListVisitor : public DfsHloVisitorWithDefault {
public:
explicit InstructionListVisitor(const HloInstruction* root) : root_(root) {}
Status DefaultAction(HloInstruction* hlo) override {
// For each instruction, just push it on the list after walking the
// operands.
instructions_.push_back(hlo);
VLOG(0) << "List instruction " << hlo->ToString();
return Status::OK();
}
std::vector<const HloInstruction*> GetInstructions() { return instructions_; }
private:
// The instruction root of the computation.
const HloInstruction* root_;
// The full set of instructions found (may be duplicates, e.g., kParameter).
std::vector<const HloInstruction*> instructions_;
TF_DISALLOW_COPY_AND_ASSIGN(InstructionListVisitor);
};
const std::vector<const HloInstruction*> GetInstructions(HloInstruction* root) {
InstructionListVisitor main_list(root);
TF_CHECK_OK(root->Accept(&main_list));
return main_list.GetInstructions();
}
class BufferAssignmentTest : public HloTestBase {
protected:
BufferAssignmentTest() : computation_tracker_() {}
~BufferAssignmentTest() override {}
// Builds an x+1.0 computation to use in a Map.
std::unique_ptr<HloComputation> BuildMapComputationPlus1(const string& name) {
auto builder = HloComputation::Builder(name);
auto param =
builder.AddInstruction(HloInstruction::CreateParameter(0, r0f32_, "x"));
auto value = builder.AddInstruction(
HloInstruction::CreateConstant(LiteralUtil::CreateR0<float>(1.0)));
builder.AddInstruction(
HloInstruction::CreateBinary(r0f32_, HloOpcode::kAdd, param, value));
return builder.Build();
}
// Builds a simple compare-to-limit (x < 4) computation for a While.
//
// condition:
// const4[s32] -----------------------------------\
// \
// param[(s32,f32[4])] --- get-tuple-element[0] --- less-than
//
std::unique_ptr<HloComputation> BuildWhileConditionComputation(
const string& name) {
auto builder = HloComputation::Builder(name);
auto const4 = builder.AddInstruction(
HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(4)));
auto param = builder.AddInstruction(
HloInstruction::CreateParameter(0, t_s32_f32v4_, "x"));
auto index = builder.AddInstruction(
HloInstruction::CreateGetTupleElement(const4->shape(), param, 0));
builder.AddInstruction(
HloInstruction::CreateBinary(r0f32_, HloOpcode::kLt, index, const4));
return builder.Build();
}
// Builds a simple body computation for a While.
//
// body:
// constv[f32[4]] --------------------------------------\
// \
// /--- get-tuple-elementv[1] --- addv ---\
// param[(s32,f32[4])] ---| tuple
// \--- get-tuple-elementc[0] --- addc ---/
// /
// const1[s32] -----------------------------------------/
//
std::unique_ptr<HloComputation> BuildWhileBodyComputation(
const string& name) {
auto builder = HloComputation::Builder(name);
auto const1 = builder.AddInstruction(
HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(1)));
auto constv = builder.AddInstruction(HloInstruction::CreateConstant(
LiteralUtil::CreateR1<float>({1.1f, 2.2f, 3.3f, 4.4f})));
auto param = builder.AddInstruction(
HloInstruction::CreateParameter(0, t_s32_f32v4_, "x"));
auto indexc = builder.AddInstruction(
HloInstruction::CreateGetTupleElement(const1->shape(), param, 0));
auto addc = builder.AddInstruction(HloInstruction::CreateBinary(
indexc->shape(), HloOpcode::kAdd, indexc, const1));
auto indexv = builder.AddInstruction(
HloInstruction::CreateGetTupleElement(constv->shape(), param, 1));
auto addv = builder.AddInstruction(HloInstruction::CreateBinary(
constv->shape(), HloOpcode::kAdd, indexv, constv));
builder.AddInstruction(HloInstruction::CreateTuple({addc, addv}));
return builder.Build();
}
// Verifies that the given instruction hlo has a valid input buffer assigned,
// i.e., the parameter number matches the op's.
const BufferAllocation& GetAssignedInputAllocation(
const BufferAssignment& buffers, HloInstruction* hlo) {
LOG(INFO) << "Checking input: " << hlo->ToString();
const BufferAllocation& buffer =
*buffers.GetUniqueTopLevelAllocation(hlo).ConsumeValueOrDie();
EXPECT_EQ(hlo->parameter_number(), buffer.parameter_number());
return buffer;
}
// Verifies that the given instruction hlo has a valid output buffer
// assigned, and returns it.
const BufferAllocation& GetAssignedOutputAllocation(
const BufferAssignment& buffers, HloInstruction* hlo) {
LOG(INFO) << "Checking output: " << hlo->ToString();
const BufferAllocation& buffer = GetTopLevelAllocation(buffers, hlo);
return buffer;
}
// Returns the allocation for the given instruction.
const BufferAllocation& GetAllocation(const BufferAssignment& buffers,
const HloInstruction* hlo,
const ShapeIndex& index) {
return *buffers.GetUniqueAllocation(hlo, index).ConsumeValueOrDie();
}
const BufferAllocation& GetTopLevelAllocation(const BufferAssignment& buffers,
const HloInstruction* hlo) {
return *buffers.GetUniqueTopLevelAllocation(hlo).ConsumeValueOrDie();
}
// Verifies that all instructions in the given instruction list except
// kConstant have assigned buffers, and returns their total size. If min_index
// and max_index are not nullptr, the minimum and maximum buffer indices in
// the assignment are written into them.
int64 ValidateBuffers(const std::vector<const HloInstruction*>& instructions,
const BufferAssignment& buffers) {
// Verifies all instructions have buffers, and gets the index ranges.
for (const HloInstruction* hlo : instructions) {
if (!buffers.HasTopLevelAllocation(hlo)) {
// If `hlo` has no assigned buffer, it is either a constant or a nested
// parameter.
EXPECT_TRUE(HloOpcode::kConstant == hlo->opcode() ||
HloOpcode::kParameter == hlo->opcode());
continue;
}
}
// Gets the total size of all buffers assigned.
int64 total_size = 0;
for (auto& allocation : buffers.Allocations()) {
total_size += allocation.size();
}
return total_size;
}
// Returns true if the buffers assigned to instructions in "a" are distinct
// from the buffers assigned to those in "b" (ie, intersection is empty).
bool BuffersDistinct(const std::vector<const HloInstruction*>& a,
const std::vector<const HloInstruction*>& b,
const BufferAssignment& assignment) {
std::set<BufferAllocation::Index> a_buffers;
for (const HloInstruction* instruction : a) {
if (assignment.HasTopLevelAllocation(instruction)) {
a_buffers.insert(assignment.GetUniqueTopLevelAllocation(instruction)
.ConsumeValueOrDie()
->index());
}
}
for (const HloInstruction* instruction : b) {
if (assignment.HasTopLevelAllocation(instruction)) {
if (a_buffers.count(assignment.GetUniqueTopLevelAllocation(instruction)
.ConsumeValueOrDie()
->index())) {
return false;
}
}
}
return true;
}
// Computation tracker for nested computations.
ComputationTracker computation_tracker_;
// Shapes for use in the examples.
Shape s32_ = ShapeUtil::MakeShape(xla::S32, {});
Shape r0f32_ = ShapeUtil::MakeShape(xla::F32, {});
Shape f32vec4_ = ShapeUtil::MakeShape(F32, {4});
Shape f32vec10_ = ShapeUtil::MakeShape(F32, {10});
Shape f32vec100_ = ShapeUtil::MakeShape(F32, {100});
Shape f32a100x10_ = ShapeUtil::MakeShape(F32, {100, 10});
Shape t_s32_f32v4_ = ShapeUtil::MakeTupleShape({s32_, f32vec4_});
Shape t_s32_f32v10_ = ShapeUtil::MakeTupleShape({s32_, f32vec10_});
};
namespace {
std::unique_ptr<BufferAssignment> RunBufferAssignment(HloModule* module) {
return BufferAssigner::Run(module, MakeUnique<DependencyHloOrdering>(module),
/*pointer_size=*/sizeof(void*))
.ConsumeValueOrDie();
}
}
// Tests a computation consisting of a single scalar constant node.
TEST_F(BufferAssignmentTest, ScalarConstant) {
auto builder = HloComputation::Builder(TestName());
auto const0 = builder.AddInstruction(
HloInstruction::CreateConstant(LiteralUtil::CreateR0<float>(1.0)));
auto module = MakeUnique<HloModule>(TestName());
module->AddEntryComputation(builder.Build());
auto buffers = RunBufferAssignment(module.get());
// Check that the constant does not have a buffer assigned.
EXPECT_FALSE(buffers->HasTopLevelAllocation(const0));
}
TEST_F(BufferAssignmentTest, BufferForConst) {
// Addition of two vector constants: checks that internal constant nodes have
// no buffers assigned, and their consumer has a buffer.
auto builder = HloComputation::Builder(TestName());
auto const0 = builder.AddInstruction(HloInstruction::CreateConstant(
LiteralUtil::CreateR1<float>({1.1f, 2.2f, 3.3f, 4.4f})));
auto const1 = builder.AddInstruction(HloInstruction::CreateConstant(
LiteralUtil::CreateR1<float>({4.1f, 4.2f, 4.3f, 4.4f})));
auto add = builder.AddInstruction(
HloInstruction::CreateBinary(f32vec4_, HloOpcode::kAdd, const0, const1));
auto module = MakeUnique<HloModule>(TestName());
module->AddEntryComputation(builder.Build());
auto buffers = RunBufferAssignment(module.get());
// The two constant nodes have no buffers assigned.
EXPECT_FALSE(buffers->HasTopLevelAllocation(const0));
EXPECT_FALSE(buffers->HasTopLevelAllocation(const1));
// The add node has an output buffer.
GetAssignedOutputAllocation(*buffers, add);
}
TEST_F(BufferAssignmentTest, BufferForOutputConst) {
// This computation copies a constant to output.
auto builder = HloComputation::Builder(TestName());
auto const0 = builder.AddInstruction(HloInstruction::CreateConstant(
LiteralUtil::CreateR1<float>({1.1f, 2.2f, 3.3f, 4.4f})));
auto copy = builder.AddInstruction(
HloInstruction::CreateUnary(const0->shape(), HloOpcode::kCopy, const0));
auto module = MakeUnique<HloModule>(TestName());
module->AddEntryComputation(builder.Build());
auto buffers = RunBufferAssignment(module.get());
// The copy node now has an output buffer.
GetAssignedOutputAllocation(*buffers, copy);
}
TEST_F(BufferAssignmentTest, Basic) {
// paramscalar ------- (mul) -- (add) -- (sub)
// / / /
// param0[100] -------/ / /
// / /
// param1[100] --------------/--------/
auto builder = HloComputation::Builder(TestName());
auto paramscalar =
builder.AddInstruction(HloInstruction::CreateParameter(0, r0f32_, ""));
auto param0 = builder.AddInstruction(
HloInstruction::CreateParameter(1, f32vec100_, ""));
auto param1 = builder.AddInstruction(
HloInstruction::CreateParameter(2, f32vec100_, ""));
auto mul = builder.AddInstruction(HloInstruction::CreateBinary(
f32vec100_, HloOpcode::kMultiply, paramscalar, param0));
auto add = builder.AddInstruction(
HloInstruction::CreateBinary(f32vec100_, HloOpcode::kAdd, mul, param1));
auto sub = builder.AddInstruction(HloInstruction::CreateBinary(
f32vec100_, HloOpcode::kSubtract, add, param1));
auto module = MakeUnique<HloModule>(TestName());
module->AddEntryComputation(builder.Build());
auto buffers = RunBufferAssignment(module.get());
// Distinct input buffers were assigned for parameters.
BufferAllocation paramscalar_buffer =
GetAssignedInputAllocation(*buffers, paramscalar);
BufferAllocation param0_buffer = GetAssignedInputAllocation(*buffers, param0);
BufferAllocation param1_buffer = GetAssignedInputAllocation(*buffers, param1);
EXPECT_NE(paramscalar_buffer.index(), param0_buffer.index());
EXPECT_NE(paramscalar_buffer.index(), param1_buffer.index());
EXPECT_NE(param0_buffer.index(), param1_buffer.index());
// The mul node has a valid buffer assigned, doesn't share with input.
const BufferAllocation& mul_buffer = GetTopLevelAllocation(*buffers, mul);
EXPECT_NE(mul_buffer.index(), param0_buffer.index());
// The add node can reuse the mul node's buffer.
const BufferAllocation& add_buffer = GetTopLevelAllocation(*buffers, add);
EXPECT_EQ(add_buffer.index(), add_buffer.index());
// The sub node has a valid output buffer assigned.
GetAssignedOutputAllocation(*buffers, sub);
}
TEST_F(BufferAssignmentTest, MultipleUsersForNode) {
// This is similar to the Basic test, with the difference that (sub) is
// another user of (mul)'s result, so (mul)'s buffer cannot be reused for
// (add)'s output.
//
// paramscalar -------\ /-----------\
// \ / \
// param0[100] ------- (mul) -- (add) -- (sub)
// /
// param1[100] ----------------/
//
auto builder = HloComputation::Builder(TestName());
auto paramscalar =
builder.AddInstruction(HloInstruction::CreateParameter(0, r0f32_, ""));
auto param0 = builder.AddInstruction(
HloInstruction::CreateParameter(1, f32vec100_, ""));
auto param1 = builder.AddInstruction(
HloInstruction::CreateParameter(2, f32vec100_, ""));
auto mul = builder.AddInstruction(HloInstruction::CreateBinary(
f32vec100_, HloOpcode::kMultiply, paramscalar, param0));
auto add = builder.AddInstruction(
HloInstruction::CreateBinary(f32vec100_, HloOpcode::kAdd, mul, param1));
auto sub = builder.AddInstruction(
HloInstruction::CreateBinary(f32vec100_, HloOpcode::kSubtract, add, mul));
auto module = MakeUnique<HloModule>(TestName());
module->AddEntryComputation(builder.Build());
auto buffers = RunBufferAssignment(module.get());
// Input buffers were assigned for parameters.
BufferAllocation paramscalar_buffer =
GetAssignedInputAllocation(*buffers, paramscalar);
BufferAllocation param0_buffer = GetAssignedInputAllocation(*buffers, param0);
BufferAllocation param1_index = GetAssignedInputAllocation(*buffers, param1);
EXPECT_NE(paramscalar_buffer.index(), param0_buffer.index());
EXPECT_NE(paramscalar_buffer.index(), param1_index.index());
EXPECT_NE(param0_buffer.index(), param1_index.index());
// The mul node had a buffer allocated.
const BufferAllocation& mul_buffer = GetTopLevelAllocation(*buffers, mul);
// Now the add node can't reuse the mul node's buffer.
const BufferAllocation& add_buffer = GetTopLevelAllocation(*buffers, add);
EXPECT_NE(add_buffer.index(), mul_buffer.index());
// Log size information for inspection.
const std::vector<const HloInstruction*> level0 = GetInstructions(sub);
int64 size0 = ValidateBuffers(level0, *buffers);
LOG(INFO) << "LogicalBuffer count " << buffers->Allocations().size()
<< " for " << level0.size() << " instructions; "
<< "total buffer size " << size0;
}
TEST_F(BufferAssignmentTest, TrivialMap) {
// This tests a trivial x+1 map as the only operation.
//
// param0[100x10] ---> (map x+1)
//
// Builds the map function.
auto module = MakeUnique<HloModule>(TestName());
auto map_computation =
module->AddEmbeddedComputation(BuildMapComputationPlus1("f32+1"));
auto inner_last = map_computation->root_instruction();
// Creates the main kernel and verifies instruction counts.
auto builder = HloComputation::Builder(TestName());
auto param0 = builder.AddInstruction(
HloInstruction::CreateParameter(0, f32a100x10_, ""));
auto map = builder.AddInstruction(
HloInstruction::CreateMap(f32a100x10_, {param0}, map_computation));
const std::vector<const HloInstruction*> level0 = GetInstructions(map);
EXPECT_EQ(2, level0.size()) << "Invalid main kernel size";
const std::vector<const HloInstruction*> level1 = GetInstructions(inner_last);
EXPECT_EQ(3, level1.size()) << "Invalid nested add+1 size";
module->AddEntryComputation(builder.Build());
// Assigns buffers and fetches sizes.
auto buffers = RunBufferAssignment(module.get());
int64 size0 = ValidateBuffers(level0, *buffers);
int64 size1 = ValidateBuffers(level1, *buffers);
// Both algorithms assign the map's buffer before processing the embedded
// computation, so we can verify that the buffers aren't shared between them
// by checking:
EXPECT_TRUE(BuffersDistinct(level0, level1, *buffers))
<< "Reuse between main kernel and embedded mapping.";
// An input buffer was assigned for the parameter.
BufferAllocation param0_buffer = GetAssignedInputAllocation(*buffers, param0);
// An output buffer was assigned for the map.
BufferAllocation map_buffer = GetAssignedOutputAllocation(*buffers, map);
EXPECT_NE(param0_buffer.index(), map_buffer.index());
// The final computation node of the map is an add of an f32 parm and a
// constant.
EXPECT_EQ(HloOpcode::kAdd, inner_last->opcode());
const BufferAllocation& inner_add_buffer =
GetTopLevelAllocation(*buffers, inner_last);
EXPECT_NE(inner_add_buffer.index(), map_buffer.index());
// Log size information for inspection.
LOG(INFO) << "LogicalBuffer count " << buffers->Allocations().size()
<< " for " << level0.size() + level1.size() << " instructions; "
<< "total buffer size " << size0 + size1;
}
TEST_F(BufferAssignmentTest, CannotReuseInputBufferOfReduce) {
// Make sure that the input buffer of a reduce cannot be reused for its
// output. (Reuse is not safe in the general case, as it reshapes and some
// out-of-order reductions could overwrite an element before a use.)
//
// param0[100] --- (exp1) --- (exp2) --- (reduce x+1) --- (exp3)
auto module = MakeUnique<HloModule>(TestName());
auto reduce_computation =
module->AddEmbeddedComputation(BuildMapComputationPlus1("f32+1"));
auto builder = HloComputation::Builder(TestName());
auto param0 = builder.AddInstruction(
HloInstruction::CreateParameter(0, f32a100x10_, ""));
auto exp1 = builder.AddInstruction(
HloInstruction::CreateUnary(f32a100x10_, HloOpcode::kExp, param0));
auto exp2 = builder.AddInstruction(
HloInstruction::CreateUnary(f32a100x10_, HloOpcode::kExp, exp1));
auto const0 = builder.AddInstruction(
HloInstruction::CreateConstant(LiteralUtil::CreateR0<float>(0.0f)));
auto reduce = builder.AddInstruction(HloInstruction::CreateReduce(
/*shape=*/f32vec10_,
/*operand=*/exp2,
/*init_value=*/const0,
/*dimensions_to_reduce=*/{0}, reduce_computation));
auto exp3 = builder.AddInstruction(
HloInstruction::CreateUnary(f32vec10_, HloOpcode::kExp, reduce));
module->AddEntryComputation(builder.Build());
auto buffers = RunBufferAssignment(module.get());
const std::vector<const HloInstruction*> instrs = GetInstructions(exp3);
ValidateBuffers(instrs, *buffers);
const BufferAllocation& exp1_buffer = GetTopLevelAllocation(*buffers, exp1);
const BufferAllocation& exp2_buffer = GetTopLevelAllocation(*buffers, exp2);
const BufferAllocation& reduce_buffer =
GetTopLevelAllocation(*buffers, reduce);
// The buffer of exp1 is trivially reusable for exp2 - this is just for sanity
// checking.
EXPECT_EQ(exp1_buffer.index(), exp2_buffer.index());
// The buffer of exp2 cannot be used for reduce, even though it's the only
// operand.
EXPECT_NE(exp2_buffer.index(), reduce_buffer.index());
}
TEST_F(BufferAssignmentTest, ExampleWhile) {
// This tests a While loop example from the ir_semantics document.
//
// condition (s32,f32[4]) -> bool -- see BuildWhileConditionComputation.
// body: (s32,f32[4]) -> (s32,f32[4]) -- see BuildWhileBodyComputation.
//
// const3[s32] -------\
// const4[f32[4]] --- tuple --- while[condition, body]
//
// Builds the nested condition and body.
auto module = MakeUnique<HloModule>(TestName());
auto condition_computation =
module->AddEmbeddedComputation(BuildWhileConditionComputation("if<4"));
auto body_computation =
module->AddEmbeddedComputation(BuildWhileBodyComputation("add-update"));
// Creates the main kernel and verifies instruction counts.
auto builder = HloComputation::Builder(TestName());
auto const3 = builder.AddInstruction(
HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(0)));
auto const4 = builder.AddInstruction(HloInstruction::CreateConstant(
LiteralUtil::CreateR1<float>({1.1f, 2.2f, 3.3f, 4.4f})));
auto tuple =
builder.AddInstruction(HloInstruction::CreateTuple({const3, const4}));
auto while_op = builder.AddInstruction(HloInstruction::CreateWhile(
t_s32_f32v4_, condition_computation, body_computation, tuple));
const std::vector<const HloInstruction*> level0 = GetInstructions(while_op);
EXPECT_EQ(4, level0.size()) << "Invalid while kernel size";
const std::vector<const HloInstruction*> levelc =
GetInstructions(condition_computation->root_instruction());
EXPECT_EQ(4, levelc.size()) << "Invalid nested condition size";
const std::vector<const HloInstruction*> levelb =
GetInstructions(body_computation->root_instruction());
EXPECT_EQ(8, levelb.size()) << "Invalid nested body size";
module->AddEntryComputation(builder.Build());
// Assigns buffers and fetches sizes.
auto buffers = RunBufferAssignment(module.get());
int64 size0 = ValidateBuffers(level0, *buffers);
int64 sizec = ValidateBuffers(levelc, *buffers);
int64 sizeb = ValidateBuffers(levelb, *buffers);
// BufferAssignment will assign a single allocation for the following
// instructions: while, while.cond.param, while.body.param, while.body.result.
EXPECT_FALSE(BuffersDistinct(level0, levelc, *buffers))
<< "Should be reuse between main kernel and embedded condition.";
EXPECT_FALSE(BuffersDistinct(levelb, levelc, *buffers))
<< "Should be reuse between embedded condition and body.";
// Expect buffer reuse between main kernel and body computation.
EXPECT_FALSE(BuffersDistinct(level0, levelb, *buffers))
<< "Should be reuse between main kernel and embedded body.";
// The final computation node of the while body is a tuple of s32 and
// f32[4] adds.
HloInstruction* body_root = body_computation->root_instruction();
EXPECT_EQ(HloOpcode::kTuple, body_root->opcode());
// Check that buffer for each subshape of 'while_op' shares allocation with
// corresponding buffer from while body computation at same index.
TF_CHECK_OK(ShapeUtil::ForEachSubshape(
while_op->shape(),
[this, &buffers, while_op, body_root](const Shape& /*subshape*/,
const ShapeIndex& index) {
auto while_op_allocation = GetAllocation(*buffers, while_op, index);
auto body_root_allocation = GetAllocation(*buffers, body_root, index);
EXPECT_EQ(while_op_allocation.index(), body_root_allocation.index());
return Status::OK();
}));
// Log size information for inspection.
LOG(INFO) << "LogicalBuffer count " << buffers->Allocations().size()
<< " for " << level0.size() + levelc.size() + levelb.size()
<< " instructions; total buffer size " << size0 + sizec + sizeb;
}
TEST_F(BufferAssignmentTest, UnaryOpReuseChain) {
// param0[100] ---> (exp) ---> (tanh) ---> (exp) ---> (neg)
auto builder = HloComputation::Builder(TestName());
auto param0 = builder.AddInstruction(
HloInstruction::CreateParameter(0, f32vec100_, ""));
auto exp1 = builder.AddInstruction(
HloInstruction::CreateUnary(f32vec100_, HloOpcode::kExp, param0));
auto tanh = builder.AddInstruction(
HloInstruction::CreateUnary(f32vec100_, HloOpcode::kTanh, exp1));
auto exp2 = builder.AddInstruction(
HloInstruction::CreateUnary(f32vec100_, HloOpcode::kExp, tanh));
auto neg = builder.AddInstruction(
HloInstruction::CreateUnary(f32vec100_, HloOpcode::kNegate, exp2));
auto module = MakeUnique<HloModule>(TestName());
module->AddEntryComputation(builder.Build());
auto assignment = RunBufferAssignment(module.get());
// tanh and exp2 can reuse exp1's buffer
EXPECT_TRUE(assignment->HasTopLevelAllocation(exp1));
auto& buffer_for_exp1 = GetTopLevelAllocation(*assignment, exp1);
EXPECT_EQ(buffer_for_exp1, GetTopLevelAllocation(*assignment, tanh));
EXPECT_EQ(buffer_for_exp1, GetTopLevelAllocation(*assignment, exp2));
EXPECT_EQ(buffer_for_exp1, GetTopLevelAllocation(*assignment, neg));
}
TEST_F(BufferAssignmentTest, ReuseNonOperandBuffer) {
// This computation is a chain of operations which decreases in buffer size
// (via slice) then increases in size (via broadcast):
//
// param ---> (negate) ---> (slice) ---> (broadcast)
//
// The negate should share a buffer with broadcast.
auto builder = HloComputation::Builder(TestName());
auto param0 = builder.AddInstruction(
HloInstruction::CreateParameter(0, f32vec100_, "param0"));
auto negate = builder.AddInstruction(
HloInstruction::CreateUnary(f32vec100_, HloOpcode::kNegate, param0));
auto slice = builder.AddInstruction(
HloInstruction::CreateSlice(f32vec10_, negate, {0}, {10}));
auto broadcast = builder.AddInstruction(
HloInstruction::CreateBroadcast(f32a100x10_, slice, {1}));
auto module = MakeUnique<HloModule>(TestName());
module->AddEntryComputation(builder.Build());
auto assignment = RunBufferAssignment(module.get());
// negate and broadcast should share a buffer.
EXPECT_TRUE(assignment->HasTopLevelAllocation(broadcast));
auto& buffer_for_bcast = GetTopLevelAllocation(*assignment, broadcast);
EXPECT_EQ(buffer_for_bcast, GetTopLevelAllocation(*assignment, negate));
// Slice should have its own buffer.
EXPECT_NE(buffer_for_bcast, GetTopLevelAllocation(*assignment, slice));
}
TEST_F(BufferAssignmentTest, NoReuseLiveBuffer) {
// This computation is identical to that in ReuseNonOperandBuffer, but the
// negate value is live until the end of the computation (due to it being an
// operand of the output tuple) preventing reuse.
//
// param ---> (negate) ---> (slice) ---> (broadcast)-> (tuple)
// \-----------------------------------/
//
// The negate should not share a buffer with broadcast.
auto builder = HloComputation::Builder(TestName());
auto param0 = builder.AddInstruction(
HloInstruction::CreateParameter(0, f32vec100_, "param0"));
auto negate = builder.AddInstruction(
HloInstruction::CreateUnary(f32vec100_, HloOpcode::kNegate, param0));
auto slice = builder.AddInstruction(
HloInstruction::CreateSlice(f32vec10_, negate, {0}, {10}));
auto broadcast = builder.AddInstruction(
HloInstruction::CreateBroadcast(f32a100x10_, slice, {1}));
builder.AddInstruction(HloInstruction::CreateTuple({negate, broadcast}));
auto module = MakeUnique<HloModule>(TestName());
module->AddEntryComputation(builder.Build());
auto assignment = RunBufferAssignment(module.get());
// The instructions should not share buffers.
EXPECT_NE(GetTopLevelAllocation(*assignment, broadcast),
GetTopLevelAllocation(*assignment, negate));
EXPECT_NE(GetTopLevelAllocation(*assignment, broadcast),
GetTopLevelAllocation(*assignment, slice));
EXPECT_NE(GetTopLevelAllocation(*assignment, negate),
GetTopLevelAllocation(*assignment, slice));
}
TEST_F(BufferAssignmentTest, NoReuseAliasedBuffer) {
// This computation is identical to that in ReuseNonOperandBuffer, but the
// negate value is placed into a tuple which lives to the end of the
// computation. This extends the live range of negate's buffer preventing
// reuse due to buffer aliasing.
//
// param ---> (negate) ---> (tuple) -> (slice) ---> (broadcast)-> (tuple)
// \-----------------------------------/
//
// The negate should not share a buffer with broadcast.
auto builder = HloComputation::Builder(TestName());
auto param0 = builder.AddInstruction(
HloInstruction::CreateParameter(0, f32vec100_, "param0"));
auto negate = builder.AddInstruction(
HloInstruction::CreateUnary(f32vec100_, HloOpcode::kNegate, param0));
auto tuple = builder.AddInstruction(HloInstruction::CreateTuple({negate}));
auto tuple_element = builder.AddInstruction(
HloInstruction::CreateGetTupleElement(f32vec100_, tuple, 0));
auto slice = builder.AddInstruction(
HloInstruction::CreateSlice(f32vec10_, tuple_element, {0}, {10}));
auto broadcast = builder.AddInstruction(
HloInstruction::CreateBroadcast(f32a100x10_, slice, {1}));
builder.AddInstruction(HloInstruction::CreateTuple({tuple, broadcast}));
auto module = MakeUnique<HloModule>(TestName());
module->AddEntryComputation(builder.Build());
auto assignment = RunBufferAssignment(module.get());
// The instructions should not share buffers.
EXPECT_NE(GetTopLevelAllocation(*assignment, broadcast),
GetTopLevelAllocation(*assignment, negate));
EXPECT_NE(GetTopLevelAllocation(*assignment, broadcast),
GetTopLevelAllocation(*assignment, slice));
EXPECT_NE(GetTopLevelAllocation(*assignment, negate),
GetTopLevelAllocation(*assignment, slice));
}
TEST_F(BufferAssignmentTest, DoNotReuseOversizedOutputBuffer) {
// This computation is very similar to ReuseNonOperandBuffer except the
// broadcast has a smaller output than the negate. This should block reuse of
// negate's buffer by broadcast because the output buffer(s) of a computation
// should be exactly sized for the value.
//
// param ---> (negate) ---> (slice) ---> (broadcast)
//
// The negate should *not* share a buffer with broadcast.
auto builder = HloComputation::Builder(TestName());
auto param0 = builder.AddInstruction(
HloInstruction::CreateParameter(0, f32vec100_, "param0"));
// Negate output is 100 elements.
auto negate = builder.AddInstruction(
HloInstruction::CreateUnary(f32vec100_, HloOpcode::kNegate, param0));
auto slice = builder.AddInstruction(
HloInstruction::CreateSlice(f32vec10_, negate, {0}, {10}));
// Broadcast output is 40 elements.
auto broadcast = builder.AddInstruction(HloInstruction::CreateBroadcast(
ShapeUtil::MakeShape(F32, {10, 4}), slice, {0}));
auto module = MakeUnique<HloModule>(TestName());
module->AddEntryComputation(builder.Build());
auto assignment = RunBufferAssignment(module.get());
// The instructions should not share buffers.
EXPECT_NE(GetTopLevelAllocation(*assignment, broadcast),
GetTopLevelAllocation(*assignment, negate));
EXPECT_NE(GetTopLevelAllocation(*assignment, broadcast),
GetTopLevelAllocation(*assignment, slice));
EXPECT_NE(GetTopLevelAllocation(*assignment, negate),
GetTopLevelAllocation(*assignment, slice));
}
TEST_F(BufferAssignmentTest, ReuseOutputBufferIfExactlySized) {
// This is identical to DoNotReuseOversizedOutputBuffer except the broadcast
// output is exactly the same size as the negate (rather than being
// smaller). This enables reuse of negate's buffer by the broadcast because
// the output buffer will be sized exactly to its value.
//
// param ---> (negate) ---> (slice) ---> (broadcast)
//
// The negate should *not* share a buffer with broadcast.
auto builder = HloComputation::Builder(TestName());
auto param0 = builder.AddInstruction(
HloInstruction::CreateParameter(0, f32vec100_, "param0"));
// Negate output is 100 elements.
auto negate = builder.AddInstruction(
HloInstruction::CreateUnary(f32vec100_, HloOpcode::kNegate, param0));
auto slice = builder.AddInstruction(
HloInstruction::CreateSlice(f32vec10_, negate, {0}, {10}));
// Broadcast output is 40 elements.
auto broadcast = builder.AddInstruction(HloInstruction::CreateBroadcast(
ShapeUtil::MakeShape(F32, {10, 10}), slice, {0}));
auto module = MakeUnique<HloModule>(TestName());
module->AddEntryComputation(builder.Build());
auto assignment = RunBufferAssignment(module.get());
// negate and broadcast should share a buffer.
EXPECT_TRUE(assignment->HasTopLevelAllocation(broadcast));
auto& buffer_for_bcast = GetTopLevelAllocation(*assignment, broadcast);
EXPECT_EQ(buffer_for_bcast, GetTopLevelAllocation(*assignment, negate));
// Slice should have its own buffer.
EXPECT_NE(buffer_for_bcast, GetTopLevelAllocation(*assignment, slice));
}
TEST_F(BufferAssignmentTest, DoNotReuseOversizedOutputBufferInTuple) {
// This computation is very similar to ReuseNonOperandBuffer except the
// broadcast has a smaller output than the negate, and the broadcast is
// contained in the computation output as a tuple element. This should block
// reuse of the negate's buffer by the broadcast because the output buffer(s)
// of a computation should be exactly sized for the value. This includes those
// buffers aliased in the output (eg, contained as tuple elements).
//
// param ---> (negate) ---> (slice) ---> (broadcast) --> (tuple)
//
// The negate should *not* share a buffer with broadcast.
auto builder = HloComputation::Builder(TestName());
auto param0 = builder.AddInstruction(
HloInstruction::CreateParameter(0, f32vec100_, "param0"));
// Negate output is 100 elements.
auto negate = builder.AddInstruction(
HloInstruction::CreateUnary(f32vec100_, HloOpcode::kNegate, param0));
auto slice = builder.AddInstruction(
HloInstruction::CreateSlice(f32vec10_, negate, {0}, {10}));
// Broadcast output is 40 elements.
auto broadcast = builder.AddInstruction(HloInstruction::CreateBroadcast(
ShapeUtil::MakeShape(F32, {10, 4}), slice, {0}));
builder.AddInstruction(HloInstruction::CreateTuple({broadcast}));
auto module = MakeUnique<HloModule>(TestName());
module->AddEntryComputation(builder.Build());
auto assignment = RunBufferAssignment(module.get());
// The instructions should not share buffers.
EXPECT_NE(GetTopLevelAllocation(*assignment, broadcast),
GetTopLevelAllocation(*assignment, negate));
EXPECT_NE(GetTopLevelAllocation(*assignment, broadcast),
GetTopLevelAllocation(*assignment, slice));
EXPECT_NE(GetTopLevelAllocation(*assignment, negate),
GetTopLevelAllocation(*assignment, slice));
}
TEST_F(BufferAssignmentTest, EmbeddedComputationBuffers) {
// Verify that buffers for embedded computations are properly marked as
// thread-local and that embedded parameters are not marked as
// is_entry_computation_parameter.
auto module = MakeUnique<HloModule>(TestName());
auto vec_shape = ShapeUtil::MakeShape(F32, {42});
auto scalar_shape = ShapeUtil::MakeShape(F32, {});
// Create a scalar computation to use in a map.
auto map_builder = HloComputation::Builder(TestName() + "_map");
auto map_param = map_builder.AddInstruction(
HloInstruction::CreateParameter(0, scalar_shape, "map_param"));
auto map_root = map_builder.AddInstruction(
HloInstruction::CreateUnary(scalar_shape, HloOpcode::kNegate, map_param));
auto map_computation = module->AddEmbeddedComputation(map_builder.Build());
// Create a vector computation to use in a kCall.
auto call_builder = HloComputation::Builder(TestName() + "_call");
auto call_param = call_builder.AddInstruction(
HloInstruction::CreateParameter(0, vec_shape, "vec_param"));
auto call_root = call_builder.AddInstruction(
HloInstruction::CreateUnary(vec_shape, HloOpcode::kExp, call_param));
auto call_computation = module->AddEmbeddedComputation(call_builder.Build());
// Create entry computation which kCalls call_computation and then calls map
// with map_computation on the result.
auto builder = HloComputation::Builder(TestName());
auto param = builder.AddInstruction(
HloInstruction::CreateParameter(0, vec_shape, "param"));
auto call = builder.AddInstruction(
HloInstruction::CreateCall(vec_shape, {param}, call_computation));
auto map = builder.AddInstruction(
HloInstruction::CreateMap(vec_shape, {call}, map_computation));
module->AddEntryComputation(builder.Build());
auto assignment = RunBufferAssignment(module.get());
// Allocations for the map computation should be thread-local and not
// live-out.
auto& map_param_alloc = GetTopLevelAllocation(*assignment, map_param);
EXPECT_FALSE(map_param_alloc.is_entry_computation_parameter());
EXPECT_FALSE(map_param_alloc.maybe_live_out());
EXPECT_TRUE(map_param_alloc.is_thread_local());
auto& map_root_alloc = GetTopLevelAllocation(*assignment, map_root);
EXPECT_FALSE(map_root_alloc.is_entry_computation_parameter());
EXPECT_FALSE(map_root_alloc.maybe_live_out());
EXPECT_TRUE(map_root_alloc.is_thread_local());
// Allocations for the call computation should not be thread-local and not
// live-out.
auto& call_param_alloc = GetTopLevelAllocation(*assignment, call_param);
EXPECT_FALSE(call_param_alloc.is_entry_computation_parameter());
EXPECT_FALSE(call_param_alloc.maybe_live_out());
EXPECT_FALSE(call_param_alloc.is_thread_local());
auto& call_root_alloc = GetTopLevelAllocation(*assignment, call_root);
EXPECT_FALSE(call_root_alloc.is_entry_computation_parameter());
EXPECT_FALSE(call_root_alloc.maybe_live_out());
EXPECT_FALSE(call_root_alloc.is_thread_local());
// Entry computation allocations can be marked liveout and
// is_entry_computation_parameter.
auto& param_alloc = GetTopLevelAllocation(*assignment, param);
EXPECT_TRUE(param_alloc.is_entry_computation_parameter());
EXPECT_FALSE(param_alloc.maybe_live_out());
EXPECT_FALSE(param_alloc.is_thread_local());
auto& map_alloc = GetTopLevelAllocation(*assignment, map);
EXPECT_FALSE(map_alloc.is_entry_computation_parameter());
EXPECT_TRUE(map_alloc.maybe_live_out());
EXPECT_FALSE(map_alloc.is_thread_local());
}
TEST_F(BufferAssignmentTest, TupleParameterAsOutput) {
// Test a computation that returns a tuple parameter.
auto builder = HloComputation::Builder(TestName());
auto tuple_param = builder.AddInstruction(HloInstruction::CreateParameter(
0, ShapeUtil::MakeTupleShape({ShapeUtil::MakeShape(PRED, {1, 2, 3, 4}),
ShapeUtil::MakeShape(F32, {}),
ShapeUtil::MakeShape(S32, {42})}),
"param0"));
auto module = MakeUnique<HloModule>(TestName());
module->AddEntryComputation(builder.Build());
auto assignment = RunBufferAssignment(module.get());
// There should be four allocations: one for vector of pointers, and one for
// each tuple element.
EXPECT_EQ(4, assignment->Allocations().size());
// Verify each buffer allocation is marked as an entry computation parameter
// and is liveout.
TF_CHECK_OK(ShapeUtil::ForEachSubshape(
tuple_param->shape(),
[this, &assignment, tuple_param](const Shape& /*subshape*/,
const ShapeIndex& index) {
auto allocation = GetAllocation(*assignment, tuple_param, index);
EXPECT_TRUE(allocation.is_entry_computation_parameter());
EXPECT_EQ(0, allocation.parameter_number());
EXPECT_TRUE(allocation.maybe_live_out());
return Status::OK();
}));
}
TEST_F(BufferAssignmentTest, ElementOfNestedTupleParameterAsOutput) {
// Test a computation which returns a GetElementTuple of a nested tuple
// parameter.
auto builder = HloComputation::Builder(TestName());
auto tuple_param = builder.AddInstruction(HloInstruction::CreateParameter(
0, ShapeUtil::MakeTupleShape(
{ShapeUtil::MakeShape(PRED, {1, 2, 3, 4}),
ShapeUtil::MakeTupleShape({ShapeUtil::MakeShape(S32, {42}),
ShapeUtil::MakeShape(S32, {101})})}),
"param0"));
auto tuple_element =
builder.AddInstruction(HloInstruction::CreateGetTupleElement(
ShapeUtil::GetSubshape(tuple_param->shape(), {1}), tuple_param, 1));
auto module = MakeUnique<HloModule>(TestName());
module->AddEntryComputation(builder.Build());
auto assignment = RunBufferAssignment(module.get());
// Only some of the elements of the input param are liveout.
EXPECT_FALSE(
GetAllocation(*assignment, tuple_param, /*index=*/{}).maybe_live_out());
// Tuple element at index={1} is live out because GetTupleElement({1})
// forwards a pointer to this allocation (instead of defining its own buffer).
EXPECT_TRUE(
GetAllocation(*assignment, tuple_param, /*index=*/{1}).maybe_live_out());
EXPECT_TRUE(GetAllocation(*assignment, tuple_param, /*index=*/{1, 0})
.maybe_live_out());
EXPECT_TRUE(GetAllocation(*assignment, tuple_param, /*index=*/{1, 1})
.maybe_live_out());
// The GetTupleElement output is liveout.
EXPECT_TRUE(
GetTopLevelAllocation(*assignment, tuple_element).maybe_live_out());
// Verify that the GetTupleElement allocations of its elements match the
// corresponding tuple parameter allocations because they alias.
EXPECT_EQ(GetAllocation(*assignment, tuple_param, /*index=*/{1, 0}),
GetAllocation(*assignment, tuple_element, /*index=*/{0}));
EXPECT_EQ(GetAllocation(*assignment, tuple_param, /*index=*/{1, 1}),
GetAllocation(*assignment, tuple_element, /*index=*/{1}));
// GetTupleElement forwards a pointer to its underlying buffer, so verify
// that it has the same allocation than the corresponding parameter element.
EXPECT_EQ(GetAllocation(*assignment, tuple_param, /*index=*/{1}),
GetTopLevelAllocation(*assignment, tuple_element));
}
// TODO(b/32248867): Enable when buffer assignment gives allocations to
// constants.
TEST_F(BufferAssignmentTest, DISABLED_TupleConstantAsOutput) {
// Test that a tuple constant which is forwarded to the computation output is
// properly handled.
auto builder = HloComputation::Builder(TestName());
builder.AddInstruction(HloInstruction::CreateConstant(
LiteralUtil::MakeTuple({LiteralUtil::CreateR0<int64>(0).get(),
LiteralUtil::CreateR0<int64>(1).get()})));
auto module = MakeUnique<HloModule>(TestName());
module->AddEntryComputation(builder.Build());
auto assignment = RunBufferAssignment(module.get());
EXPECT_EQ(3, assignment->Allocations().size());
}
TEST_F(BufferAssignmentTest, TupleCustomCallAsOutput) {
// Test a computation which returns a tuple custom call value.
auto builder = HloComputation::Builder(TestName());
auto custom_call = builder.AddInstruction(HloInstruction::CreateCustomCall(
ShapeUtil::MakeTupleShape({ShapeUtil::MakeShape(PRED, {1, 2, 3, 4}),
ShapeUtil::MakeShape(S32, {101})}),
/*operands=*/{}, /*custom_call_target=*/"foo_function"));
auto module = MakeUnique<HloModule>(TestName());
module->AddEntryComputation(builder.Build());
auto assignment = RunBufferAssignment(module.get());
EXPECT_EQ(3, assignment->Allocations().size());
EXPECT_TRUE(
GetAllocation(*assignment, custom_call, /*index=*/{}).maybe_live_out());
EXPECT_TRUE(
GetAllocation(*assignment, custom_call, /*index=*/{0}).maybe_live_out());
EXPECT_TRUE(
GetAllocation(*assignment, custom_call, /*index=*/{1}).maybe_live_out());
}
TEST_F(BufferAssignmentTest, BitcastAsOutput) {
// Test a computation which returns a bitcast value.
auto builder = HloComputation::Builder(TestName());
auto param = builder.AddInstruction(HloInstruction::CreateParameter(
0, ShapeUtil::MakeShape(F32, {42}), "param"));
auto bitcast = builder.AddInstruction(
HloInstruction::CreateUnary(param->shape(), HloOpcode::kBitcast, param));
auto module = MakeUnique<HloModule>(TestName());
module->AddEntryComputation(builder.Build());
auto assignment = RunBufferAssignment(module.get());
// Bitcast should get the same allocation as the param.
EXPECT_EQ(1, assignment->Allocations().size());
EXPECT_EQ(GetTopLevelAllocation(*assignment, param),
GetTopLevelAllocation(*assignment, bitcast));
}
TEST_F(BufferAssignmentTest, AmbiguousBufferAsOutput) {
// Test a computation with an output that has an ambiguous points-to set. This
// is constructed using a select among tuple shapes.
auto builder = HloComputation::Builder(TestName());
auto tuple_shape =
ShapeUtil::MakeTupleShape({ShapeUtil::MakeShape(PRED, {1, 2, 3, 4})});
auto tuple_param0 = builder.AddInstruction(
HloInstruction::CreateParameter(0, tuple_shape, "param0"));
auto tuple_param1 = builder.AddInstruction(
HloInstruction::CreateParameter(1, tuple_shape, "param1"));
auto pred_param = builder.AddInstruction(HloInstruction::CreateParameter(
2, ShapeUtil::MakeShape(PRED, {}), "param1"));
auto select = builder.AddInstruction(HloInstruction::CreateTernary(
tuple_shape, HloOpcode::kSelect, pred_param, tuple_param0, tuple_param1));
auto module = MakeUnique<HloModule>(TestName());
module->AddEntryComputation(builder.Build());
auto assignment = RunBufferAssignment(module.get());
// Select shallow copies one of its operands so it defines its own top-level
// buffer and receives its own allocation.
auto select_alloc = GetTopLevelAllocation(*assignment, select);
EXPECT_EQ(1, select_alloc.assigned_buffers().size());
EXPECT_EQ(select, select_alloc.assigned_buffers()[0]->instruction());
// The buffer for the tuple element of the select is forwarded from one its
// operands which cannot be determined statically. Therefore its allocation
// should include the allocations of both of the elements in the parameters.
auto element_allocations = assignment->GetAllocations(select, /*index=*/{0});
EXPECT_EQ(2, element_allocations.size());
EXPECT_MATCH(testing::SetToVec<BufferAllocation>(element_allocations),
testing::UnorderedMatcher<BufferAllocation>(
*assignment->GetUniqueAllocation(tuple_param0, /*index=*/{0})
.ConsumeValueOrDie(),
*assignment->GetUniqueAllocation(tuple_param1, /*index=*/{0})
.ConsumeValueOrDie()));
}
} // namespace
} // namespace xla
| [
"gardener@tensorflow.org"
] | gardener@tensorflow.org |
1427dd3d43ce765497d3eb3782695532d2c07e5f | 5d83739af703fb400857cecc69aadaf02e07f8d1 | /Archive2/f1/44cdd6a3f90e24/main.cpp | 8e43ced6046b39513d990d6f1964f9b355104154 | [] | 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,363 | cpp | // Ensure two vector<int>s are equivalent sizes first, then add them together.
// Author: LLD!5DeRpYLOvE
// Respin of: http://coliru.stacked-crooked.com/a/34542cba6c40b27b
#include <iostream>
#include <vector>
using namespace std;
int main(void)
{
// Initialize a pair of different length vectors for example data.
vector<int> v1{21, 31, 41, 51, 9};
vector<int> v2{8, 7, 6, 5, 4, 3, 2, 1};
const size_t s1{v1.size()};
const size_t s2{v2.size()};
cout << "Original sizes:\n V1 equals " << s1 << "\n V2 equals " << s2 << endl;
size_t sizediff{9001};
// First case: v1 is bigger.
if(s1 > s2) {
sizediff = s1 - s2;
while(sizediff--) // while() ends once sizediff reaches 0
v2.push_back(0);
}
// Second case: v2 is bigger.
else
if(s2 > s1) {
sizediff = s2 - s1;
while(sizediff--) // while() ends once sizediff reaches 0
v1.push_back(0);
}
cout << "New sizes:\n V1 equals " << v1.size()
<< "\n V2 equals " << v2.size()
<< "\n\nVector sums:\n";
// Now add the vectors and print the results.
const size_t sz{v1.size()};
vector<int> datsumdoe(sz);
for(size_t idy{0}; idy < sz; ++idy) {
datsumdoe[idy] = v1[idy] + v2[idy];
cout << datsumdoe[idy] << endl;
}
} | [
"francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df"
] | francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df |
4f8d16aed225a014866cffba0f9e6248286a3f96 | e6a7743bcee28fbc39e495c4fdf005f1a2ff446f | /export/windows/cpp/obj/src/haxe/xml/_Fast/NodeListAccess.cpp | b6296e9a4d41149d1145c2aedde471a8ce0505be | [] | no_license | jwat445/DungeonCrawler | 56fd0b91d44793802e87097eb52d740709a10ffa | 5f60dbe509ec73dc9aa0cf8f38cf53ba486fdad2 | refs/heads/master | 2020-04-05T13:08:31.562552 | 2017-12-07T02:42:41 | 2017-12-07T02:42:41 | 95,114,406 | 0 | 0 | null | 2017-12-07T03:20:53 | 2017-06-22T12:41:59 | C++ | UTF-8 | C++ | false | true | 5,918 | cpp | // Generated by Haxe 3.4.2 (git build master @ 890f8c7)
#include <hxcpp.h>
#ifndef INCLUDED_List
#include <List.h>
#endif
#ifndef INCLUDED_Xml
#include <Xml.h>
#endif
#ifndef INCLUDED_haxe_xml_Fast
#include <haxe/xml/Fast.h>
#endif
#ifndef INCLUDED_haxe_xml__Fast_NodeListAccess
#include <haxe/xml/_Fast/NodeListAccess.h>
#endif
HX_DEFINE_STACK_FRAME(_hx_pos_10a3b7f702bd6cce_97_new,"haxe.xml._Fast.NodeListAccess","new",0x22c8c708,"haxe.xml._Fast.NodeListAccess.new","C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx",97,0x60a2153a)
HX_LOCAL_STACK_FRAME(_hx_pos_10a3b7f702bd6cce_100_resolve,"haxe.xml._Fast.NodeListAccess","resolve",0x21d97d94,"haxe.xml._Fast.NodeListAccess.resolve","C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx",100,0x60a2153a)
namespace haxe{
namespace xml{
namespace _Fast{
void NodeListAccess_obj::__construct( ::Xml x){
HX_STACKFRAME(&_hx_pos_10a3b7f702bd6cce_97_new)
HXDLIN( 97) this->_hx___x = x;
}
Dynamic NodeListAccess_obj::__CreateEmpty() { return new NodeListAccess_obj; }
void *NodeListAccess_obj::_hx_vtable = 0;
Dynamic NodeListAccess_obj::__Create(hx::DynamicArray inArgs)
{
hx::ObjectPtr< NodeListAccess_obj > _hx_result = new NodeListAccess_obj();
_hx_result->__construct(inArgs[0]);
return _hx_result;
}
bool NodeListAccess_obj::_hx_isInstanceOf(int inClassId) {
return inClassId==(int)0x00000001 || inClassId==(int)0x6bbbf3b6;
}
::List NodeListAccess_obj::resolve(::String name){
HX_GC_STACKFRAME(&_hx_pos_10a3b7f702bd6cce_100_resolve)
HXLINE( 101) ::List l = ::List_obj::__alloc( HX_CTX );
HXLINE( 102) {
HXLINE( 102) ::Dynamic x = this->_hx___x->elementsNamed(name);
HXDLIN( 102) while(( (bool)(x->__Field(HX_("hasNext",6d,a5,46,18),hx::paccDynamic)()) )){
HXLINE( 102) ::Xml x1 = ( ( ::Xml)(x->__Field(HX_("next",f3,84,02,49),hx::paccDynamic)()) );
HXLINE( 103) l->add( ::haxe::xml::Fast_obj::__alloc( HX_CTX ,x1));
}
}
HXLINE( 104) return l;
}
HX_DEFINE_DYNAMIC_FUNC1(NodeListAccess_obj,resolve,return )
hx::ObjectPtr< NodeListAccess_obj > NodeListAccess_obj::__new( ::Xml x) {
hx::ObjectPtr< NodeListAccess_obj > __this = new NodeListAccess_obj();
__this->__construct(x);
return __this;
}
hx::ObjectPtr< NodeListAccess_obj > NodeListAccess_obj::__alloc(hx::Ctx *_hx_ctx, ::Xml x) {
NodeListAccess_obj *__this = (NodeListAccess_obj*)(hx::Ctx::alloc(_hx_ctx, sizeof(NodeListAccess_obj), true, "haxe.xml._Fast.NodeListAccess"));
*(void **)__this = NodeListAccess_obj::_hx_vtable;
__this->__construct(x);
return __this;
}
NodeListAccess_obj::NodeListAccess_obj()
{
}
void NodeListAccess_obj::__Mark(HX_MARK_PARAMS)
{
HX_MARK_BEGIN_CLASS(NodeListAccess);
HX_MARK_DYNAMIC;
HX_MARK_MEMBER_NAME(_hx___x,"__x");
HX_MARK_END_CLASS();
}
void NodeListAccess_obj::__Visit(HX_VISIT_PARAMS)
{
HX_VISIT_DYNAMIC;
HX_VISIT_MEMBER_NAME(_hx___x,"__x");
}
hx::Val NodeListAccess_obj::__Field(const ::String &inName,hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 3:
if (HX_FIELD_EQ(inName,"__x") ) { return hx::Val( _hx___x ); }
break;
case 7:
if (HX_FIELD_EQ(inName,"resolve") ) { return hx::Val( resolve_dyn() ); }
}
HX_CHECK_DYNAMIC_GET_FIELD(inName);
return super::__Field(inName,inCallProp);
}
hx::Val NodeListAccess_obj::__SetField(const ::String &inName,const hx::Val &inValue,hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 3:
if (HX_FIELD_EQ(inName,"__x") ) { _hx___x=inValue.Cast< ::Xml >(); return inValue; }
}
try { return super::__SetField(inName,inValue,inCallProp); }
catch(Dynamic e) { HX_DYNAMIC_SET_FIELD(inName,inValue); }
return inValue;
}
void NodeListAccess_obj::__GetFields(Array< ::String> &outFields)
{
outFields->push(HX_HCSTRING("__x","\x58","\x69","\x48","\x00"));
HX_APPEND_DYNAMIC_FIELDS(outFields);
super::__GetFields(outFields);
};
#if HXCPP_SCRIPTABLE
static hx::StorageInfo NodeListAccess_obj_sMemberStorageInfo[] = {
{hx::fsObject /*::Xml*/ ,(int)offsetof(NodeListAccess_obj,_hx___x),HX_HCSTRING("__x","\x58","\x69","\x48","\x00")},
{ hx::fsUnknown, 0, null()}
};
static hx::StaticInfo *NodeListAccess_obj_sStaticStorageInfo = 0;
#endif
static ::String NodeListAccess_obj_sMemberFields[] = {
HX_HCSTRING("__x","\x58","\x69","\x48","\x00"),
HX_HCSTRING("resolve","\xec","\x12","\x60","\x67"),
::String(null()) };
static void NodeListAccess_obj_sMarkStatics(HX_MARK_PARAMS) {
HX_MARK_MEMBER_NAME(NodeListAccess_obj::__mClass,"__mClass");
};
#ifdef HXCPP_VISIT_ALLOCS
static void NodeListAccess_obj_sVisitStatics(HX_VISIT_PARAMS) {
HX_VISIT_MEMBER_NAME(NodeListAccess_obj::__mClass,"__mClass");
};
#endif
hx::Class NodeListAccess_obj::__mClass;
void NodeListAccess_obj::__register()
{
hx::Object *dummy = new NodeListAccess_obj;
NodeListAccess_obj::_hx_vtable = *(void **)dummy;
hx::Static(__mClass) = new hx::Class_obj();
__mClass->mName = HX_HCSTRING("haxe.xml._Fast.NodeListAccess","\x16","\xe3","\x8e","\x04");
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &hx::Class_obj::GetNoStaticField;
__mClass->mSetStaticField = &hx::Class_obj::SetNoStaticField;
__mClass->mMarkFunc = NodeListAccess_obj_sMarkStatics;
__mClass->mStatics = hx::Class_obj::dupFunctions(0 /* sStaticFields */);
__mClass->mMembers = hx::Class_obj::dupFunctions(NodeListAccess_obj_sMemberFields);
__mClass->mCanCast = hx::TCanCast< NodeListAccess_obj >;
#ifdef HXCPP_VISIT_ALLOCS
__mClass->mVisitFunc = NodeListAccess_obj_sVisitStatics;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = NodeListAccess_obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = NodeListAccess_obj_sStaticStorageInfo;
#endif
hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
} // end namespace haxe
} // end namespace xml
} // end namespace _Fast
| [
"jwat445@gmail.com"
] | jwat445@gmail.com |
2300ff7df7ad7149a15bf226abd890cceca25d0a | f49af15675a8528de1f7d929e16ded0463cb88e6 | /C++/C++ Advanced/TestProjects/CPPAdvancedExam18Nov2018)/04Terran/ProducerBase.h | a7945d5afba55287ea7e31a4c4236eb9e37cf91a | [] | no_license | genadi1980/SoftUni | 0a5e207e0038fb7855fed7cddc088adbf4cec301 | 6562f7e6194c53d1e24b14830f637fea31375286 | refs/heads/master | 2021-01-11T18:57:36.163116 | 2019-05-18T13:37:19 | 2019-05-18T13:37:19 | 79,638,550 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 348 | h | #ifndef PRODUCER_BASE_H
#include <list>
#include "Producer.h"
class ProducerBase : public Producer {
protected:
std::list<UnitPtr> produced;
public:
std::list<UnitPtr> extractProduced() override {
std::list<UnitPtr> result = this->produced;
this->produced.clear();
return result;
}
};
#define PRODUCER_BASE_H
#endif // !PRODUCER_BASE_H
| [
"genadi_georgiev@abv.bg"
] | genadi_georgiev@abv.bg |
c71804fcd351d91fbabee209bb50fdf113a8a0f0 | d8ff86a305915f522cc54692d03893de25790d63 | /Source/WebKit2/UIProcess/API/efl/ewk_view_find_client.cpp | 1edc3cbfd327cfdaac09e9af8b2f812df8f983c4 | [] | no_license | vishalbandre/webkit | 9e91646c0bb0308f9ef013b11a909ee39b88e580 | 31650b0517127cb2c0d06053f144c8c955ab7c11 | refs/heads/master | 2021-01-16T19:39:29.623978 | 2012-10-24T01:57:10 | 2012-10-24T01:57:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,556 | cpp | /*
* Copyright (C) 2012 Samsung Electronics. 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 INC. AND ITS 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 APPLE INC. OR ITS 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 "WKPage.h"
#include "ewk_view_find_client_private.h"
#include "ewk_view_private.h"
static inline Evas_Object* toEwkView(const void* clientInfo)
{
return static_cast<Evas_Object*>(const_cast<void*>(clientInfo));
}
static void didFindString(WKPageRef, WKStringRef, unsigned matchCount, const void* clientInfo)
{
ewk_view_text_found(toEwkView(clientInfo), matchCount);
}
static void didFailToFindString(WKPageRef, WKStringRef, const void* clientInfo)
{
ewk_view_text_found(toEwkView(clientInfo), 0);
}
static void didCountStringMatches(WKPageRef, WKStringRef, unsigned matchCount, const void* clientInfo)
{
ewk_view_text_found(toEwkView(clientInfo), matchCount);
}
void ewk_view_find_client_attach(WKPageRef pageRef, Evas_Object* ewkView)
{
WKPageFindClient findClient;
memset(&findClient, 0, sizeof(WKPageFindClient));
findClient.version = kWKPageFindClientCurrentVersion;
findClient.clientInfo = ewkView;
findClient.didFindString = didFindString;
findClient.didFailToFindString = didFailToFindString;
findClient.didCountStringMatches = didCountStringMatches;
WKPageSetPageFindClient(pageRef, &findClient);
}
| [
"commit-queue@webkit.org"
] | commit-queue@webkit.org |
0987a72e155385ba9f8c2e07ea58bb1bc89865f3 | 7f5fc2bf08684c2b38e09874be1cd4db0a3330f7 | /stockManagement/LoginForm.h | abaa5e18902fbc22331d48595d4860158d10dca0 | [] | no_license | Hichami-ilyass/stockManagement-cpp-win-app | 341dd074f003ed465a485656b706b70e891bcfcc | 78d07459449c7d3b415d7ade806fa6f218a53055 | refs/heads/master | 2022-09-22T02:58:35.897193 | 2020-05-25T14:34:19 | 2020-05-25T14:34:19 | 265,579,603 | 0 | 0 | null | 2020-05-22T22:25:17 | 2020-05-20T13:47:23 | C++ | UTF-8 | C++ | false | false | 7,877 | h | #pragma once
#include "mainForm.h"
namespace stockManagement {
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Data::Sql;
using namespace System::Data::SqlClient;
using namespace System::Drawing;
/// <summary>
/// Summary for LoginForm
/// </summary>
public ref class LoginForm : public System::Windows::Forms::Form
{
public:
LoginForm(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
/// <summary>
/// Clean up any resources being used.
/// </summary>
~LoginForm()
{
if (components)
{
delete components;
}
}
private: Bunifu::Framework::UI::BunifuTextbox^ login_txt;
private: Bunifu::Framework::UI::BunifuTextbox^ password_txt;
protected:
private: Bunifu::Framework::UI::BunifuFlatButton^ bunifuFlatButton1;
protected:
private:
/// <summary>
/// Required designer variable.
/// </summary>
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
void InitializeComponent(void)
{
System::ComponentModel::ComponentResourceManager^ resources = (gcnew System::ComponentModel::ComponentResourceManager(LoginForm::typeid));
this->login_txt = (gcnew Bunifu::Framework::UI::BunifuTextbox());
this->password_txt = (gcnew Bunifu::Framework::UI::BunifuTextbox());
this->bunifuFlatButton1 = (gcnew Bunifu::Framework::UI::BunifuFlatButton());
this->SuspendLayout();
//
// login_txt
//
this->login_txt->BackColor = System::Drawing::Color::White;
this->login_txt->BackgroundImage = (cli::safe_cast<System::Drawing::Image^>(resources->GetObject(L"login_txt.BackgroundImage")));
this->login_txt->BackgroundImageLayout = System::Windows::Forms::ImageLayout::Stretch;
this->login_txt->ForeColor = System::Drawing::Color::Firebrick;
this->login_txt->Icon = (cli::safe_cast<System::Drawing::Image^>(resources->GetObject(L"login_txt.Icon")));
this->login_txt->Location = System::Drawing::Point(281, 132);
this->login_txt->Margin = System::Windows::Forms::Padding(4, 4, 4, 4);
this->login_txt->Name = L"login_txt";
this->login_txt->Size = System::Drawing::Size(333, 52);
this->login_txt->TabIndex = 0;
this->login_txt->text = L"";
//
// password_txt
//
this->password_txt->BackColor = System::Drawing::Color::White;
this->password_txt->BackgroundImage = (cli::safe_cast<System::Drawing::Image^>(resources->GetObject(L"password_txt.BackgroundImage")));
this->password_txt->BackgroundImageLayout = System::Windows::Forms::ImageLayout::Stretch;
this->password_txt->ForeColor = System::Drawing::Color::Firebrick;
this->password_txt->Icon = (cli::safe_cast<System::Drawing::Image^>(resources->GetObject(L"password_txt.Icon")));
this->password_txt->Location = System::Drawing::Point(281, 209);
this->password_txt->Margin = System::Windows::Forms::Padding(4, 4, 4, 4);
this->password_txt->Name = L"password_txt";
this->password_txt->Size = System::Drawing::Size(333, 52);
this->password_txt->TabIndex = 1;
this->password_txt->text = L"";
//
// bunifuFlatButton1
//
this->bunifuFlatButton1->Activecolor = System::Drawing::Color::FromArgb(static_cast<System::Int32>(static_cast<System::Byte>(46)),
static_cast<System::Int32>(static_cast<System::Byte>(139)), static_cast<System::Int32>(static_cast<System::Byte>(87)));
this->bunifuFlatButton1->BackColor = System::Drawing::Color::FromArgb(static_cast<System::Int32>(static_cast<System::Byte>(46)),
static_cast<System::Int32>(static_cast<System::Byte>(139)), static_cast<System::Int32>(static_cast<System::Byte>(87)));
this->bunifuFlatButton1->BackgroundImageLayout = System::Windows::Forms::ImageLayout::Stretch;
this->bunifuFlatButton1->BorderRadius = 0;
this->bunifuFlatButton1->ButtonText = L"Login";
this->bunifuFlatButton1->Cursor = System::Windows::Forms::Cursors::Hand;
this->bunifuFlatButton1->DisabledColor = System::Drawing::Color::Gray;
this->bunifuFlatButton1->Iconcolor = System::Drawing::Color::Transparent;
this->bunifuFlatButton1->Iconimage = (cli::safe_cast<System::Drawing::Image^>(resources->GetObject(L"bunifuFlatButton1.Iconimage")));
this->bunifuFlatButton1->Iconimage_right = nullptr;
this->bunifuFlatButton1->Iconimage_right_Selected = nullptr;
this->bunifuFlatButton1->Iconimage_Selected = nullptr;
this->bunifuFlatButton1->IconMarginLeft = 0;
this->bunifuFlatButton1->IconMarginRight = 0;
this->bunifuFlatButton1->IconRightVisible = true;
this->bunifuFlatButton1->IconRightZoom = 0;
this->bunifuFlatButton1->IconVisible = true;
this->bunifuFlatButton1->IconZoom = 90;
this->bunifuFlatButton1->IsTab = false;
this->bunifuFlatButton1->Location = System::Drawing::Point(281, 295);
this->bunifuFlatButton1->Margin = System::Windows::Forms::Padding(4, 4, 4, 4);
this->bunifuFlatButton1->Name = L"bunifuFlatButton1";
this->bunifuFlatButton1->Normalcolor = System::Drawing::Color::FromArgb(static_cast<System::Int32>(static_cast<System::Byte>(46)),
static_cast<System::Int32>(static_cast<System::Byte>(139)), static_cast<System::Int32>(static_cast<System::Byte>(87)));
this->bunifuFlatButton1->OnHovercolor = System::Drawing::Color::FromArgb(static_cast<System::Int32>(static_cast<System::Byte>(36)),
static_cast<System::Int32>(static_cast<System::Byte>(129)), static_cast<System::Int32>(static_cast<System::Byte>(77)));
this->bunifuFlatButton1->OnHoverTextColor = System::Drawing::Color::White;
this->bunifuFlatButton1->selected = false;
this->bunifuFlatButton1->Size = System::Drawing::Size(333, 74);
this->bunifuFlatButton1->TabIndex = 2;
this->bunifuFlatButton1->Text = L"Login";
this->bunifuFlatButton1->TextAlign = System::Drawing::ContentAlignment::MiddleLeft;
this->bunifuFlatButton1->Textcolor = System::Drawing::Color::White;
this->bunifuFlatButton1->TextFont = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 9.75F, System::Drawing::FontStyle::Regular,
System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0)));
this->bunifuFlatButton1->Click += gcnew System::EventHandler(this, &LoginForm::bunifuFlatButton1_Click);
//
// LoginForm
//
this->AutoScaleDimensions = System::Drawing::SizeF(8, 16);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(901, 517);
this->Controls->Add(this->bunifuFlatButton1);
this->Controls->Add(this->password_txt);
this->Controls->Add(this->login_txt);
this->Name = L"LoginForm";
this->Text = L"LoginForm";
this->Load += gcnew System::EventHandler(this, &LoginForm::LoginForm_Load);
this->ResumeLayout(false);
}
#pragma endregion
private: System::Void LoginForm_Load(System::Object^ sender, System::EventArgs^ e) {
}
private: System::Void bunifuFlatButton1_Click(System::Object^ sender, System::EventArgs^ e) {
//String^ login = login_txt->text;
/*String^ password = password_txt->text;
SqlConnection^ cnx = gcnew SqlConnection("Data Source=.;Initial Catalog=ProjetCpp; Integrated Security=True");
cnx->Open();
SqlCommand^ cmd = gcnew SqlCommand("select * from users where login=@login and password=@password",cnx);
cmd->Parameters->AddWithValue("login", login_txt->text);
cmd->Parameters->AddWithValue("password", password_txt->text);
SqlDataReader^ dr = cmd->ExecuteReader();
if (dr->Read())
{*/
this->Hide();
mainForm^ main = gcnew mainForm();
main->ShowDialog();
/*}
else
{
MessageBox::Show("something's wrong");
}
cnx->Close();*/
}
};
}
| [
"motassimothman@gmail.com"
] | motassimothman@gmail.com |
9be37ead7b968fbd1939f23b8733f2115af7e8f2 | 51e7743fcd0c5ae9d3a08bddee3a22448839b957 | /Objects/CombinedMesh.h | f42a1aba08069e7833944797c4816bf6be89d01e | [] | no_license | sethhope/Project-Foxclaw | 63ae2461da2aeb3dcf441a07dab02a2829d530a5 | d0a1c57468debcd126abcf18ecb85d9a3cc596be | refs/heads/master | 2020-05-21T12:45:37.024272 | 2016-06-28T20:36:34 | 2016-06-28T20:36:34 | 25,419,000 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 719 | h | #ifndef COMBINEDMESH_H_INCLUDED
#define COMBINEDMESH_H_INCLUDED
#include "stdafx.h"
#include "Object.h"
#include "Misc/Logger.h"
#include "Mesh.h"
#include "Misc/CMeshCombiner.h"
namespace FCE
{
class COMBINEDMESH
{
public:
COMBINEDMESH(scene::ISceneManager* manager, u32 bufferSize, LOGGER* log);
~COMBINEDMESH();
void onInit();
void onUpdate();
void onRender();
void addMesh(MESH* mesh);
scene::IMesh* getMesh();
std::vector<u32> meshIDs;
private:
CMeshCombiner* combiner;
core::array<scene::IMeshSceneNode*> nodes;
scene::ISceneManager* manager;
LOGGER* log;
};
}
#endif // COMBINEDMESH_H_INCLUDED
| [
"support@jcamtech.com"
] | support@jcamtech.com |
e7871271a1d16420886df224293e49ba9d2dda28 | 385cb811d346a4d7a285fc087a50aaced1482851 | /Quora/RelatedQuestions/RelatedQuestions.cpp | 2c2ce0b8b1388d9f8661347c35a05a7e87e14418 | [] | no_license | NoureldinYosri/competitive-programming | aa19f0479420d8d1b10605536e916f0f568acaec | 7739344404bdf4709c69a97f61dc3c0b9deb603c | refs/heads/master | 2022-11-22T23:38:12.853482 | 2022-11-10T20:32:28 | 2022-11-10T20:32:28 | 40,174,513 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,992 | cpp | #include <bits/stdc++.h>
#define loop(i,n) for(int i = 0;i < (n);i++)
#define range(i,a,b) for(int i = (a);i <= (b);i++)
#define rrep(i,n) for(int i = (n);i >= 0;i--)
#define rran(i,a,b) for(int i = (b);i >= (a);i--)
#define step(i,a,b,d) for(int i = (a);i <= (b); i += d)
#define all(A) A.begin(),A.end()
#define pb push_back
#define mp make_pair
#define sz(A) A.size()
#define len(A) A.length()
#define print(A,t) cout << #A << ": "; copy(all(A),ostream_iterator<t>(cout," " )); cout << endl
#define pi pair<int,int>
#define point pi
#define vi vector<int>
#define ll long long
#define pl pair<ll,ll>
#define pre() cin.tie(0),cout.tie(0),ios_base::sync_with_stdio(0)
#define popcnt(x) __builtin_popcount(x)
#define LSOne(x) ((x) & (-(x)))
#define xx first
#define yy second
#define prp(p) cout << "(" << (p).first << " ," << (p).second << ")";
#define prArr(A,n,t) cout << #A << ": "; copy(A,A + n,ostream_iterator<t>(cout," " )); cout << endl
using namespace std;
int T[1 << 20],N;
vi G[1 << 20];
double dp[1 << 20];
vector<double> V[1 << 20];
double dfs1(int u,int p){
int ctr = 0;
for(int v : G[u]) ctr += v != p;
dp[u] = T[u];
loop(i,sz(G[u])){
int v = G[u][i];
if(v != p) {
double t = dfs1(v,u);
V[u][i] = t;
dp[u] += t/ctr;
}
}
return dp[u];
}
void dfs2(int u,int p,double value){
int ctr = max((int)sz(G[u]) - 1,1);
double tmp = dp[u] = T[u];
loop(i,sz(G[u]))
if(G[u][i] == p) V[u][i] = value;
loop(i,sz(G[u])) {
dp[u] += V[u][i] / sz(G[u]);
tmp += V[u][i]/ctr;
}
loop(i,sz(G[u]))
if(G[u][i] != p){
int v = G[u][i];
dfs2(v,u,tmp - V[u][i]/ctr);
}
}
int main(){
int a,b;
scanf("%d",&N);
range(i,1,N) scanf("%d",T + i);
loop(i,N - 1){
scanf("%d %d",&a,&b);
G[a].pb(b);
G[b].pb(a);
V[a].pb(b);
V[b].pb(a);
}
int s = 1;
dfs1(1,0);
dfs2(1,0,0);
double t = dp[1];
range(i,1,N){
cerr << i << " " << dp[i] << endl;
double ti = dp[i];
if(ti < t) {
t = ti;
s = i;
}
}
printf("%d\n",s);
return 0;
}
| [
"noureldinyosri@gmail.com"
] | noureldinyosri@gmail.com |
8f888707d16c074702653a84c629a006b97e5d58 | 104117d91b20e208f0a0d4eacb9640d024edbdbb | /src/RenderingSystem/PushConstants.hh | b67a56220328f1da7db8f32857d8aea3ef9bb89e | [
"MIT"
] | permissive | Sondro/Dreamroam | 82894c38e4695c41b7db1a37cbe9008829f6f4c0 | 1975c990b2362b9472e5ee19a98c63f49b8124bc | refs/heads/master | 2023-04-09T22:20:00.186017 | 2020-08-12T19:04:08 | 2020-08-12T19:04:08 | 288,040,963 | 0 | 0 | MIT | 2023-04-03T23:01:15 | 2020-08-16T23:24:16 | null | UTF-8 | C++ | false | false | 1,047 | hh | #pragma once
#include <glm/mat4x4.hpp>
#include <lava/createinfos/PipelineVertexInputStateCreateInfo.hh>
namespace DCore {
namespace Rendering {
struct PushConstants {
glm::mat4 modelMatrix;
glm::mat4 normalMatrix;
float alpha = 1.0;
};
struct CameraDataPrePass {
glm::mat4 view;
glm::mat4 proj;
};
struct CameraDataForwardPass {
glm::mat4 view;
glm::mat4 proj;
glm::mat4 depthViewProj;
};
struct VertexAttributes {
glm::vec3 position;
glm::vec3 normal;
glm::vec3 tangent;
glm::vec2 texCoord;
glm::vec4 color = glm::vec4(1, 0, 0, 1);
static void putAttributes(lava::PipelineVertexInputStateCreateInfo& info) {
info.binding(0, //
&VertexAttributes::position, //
&VertexAttributes::normal, //
&VertexAttributes::tangent, //
&VertexAttributes::texCoord, //
&VertexAttributes::color);
};
};
} // namespace Rendering
} // namespace DCore | [
"peter.esser@uhs-computer.de"
] | peter.esser@uhs-computer.de |
9e36237c06fcde4bf1a00928f320af00f1e216bf | abf76051fbf5319aebd0945225481a9c137b363f | /ArduinoAbasApi/ArduinoAbasApi.ino | 54090bc1a2e0ca5ac3021065b5bc88496ab78aaa | [] | no_license | amotiqOS/IoT-FAB | b2d9f7c67ca7d646ab9be4ad4cf20010c9755fb1 | 518485a40c5242ed7c86db875da65b10a9b9b028 | refs/heads/master | 2021-01-18T02:05:06.242753 | 2015-12-14T14:30:53 | 2015-12-14T14:30:53 | 39,121,022 | 0 | 1 | null | 2015-12-14T14:30:53 | 2015-07-15T06:44:30 | Arduino | UTF-8 | C++ | false | false | 4,545 | ino | #include <Bridge.h>
#include <YunServer.h>
#include <YunClient.h>
#include <Console.h>
#include <Process.h>
#include <FileIO.h>
String key = "/root/.ssh/db_key";
String passw = " ... ";
YunServer server;
void prepareScripts(String key) {
//Priprava scriptu exportu
Console.println("Preparing first script ....\n");
File script1 = FileSystem.open("/tmp/abasexport.sh", FILE_WRITE);
script1.print("#!/bin/sh\n");
script1.print("cd /u/abas/s3\n");
script1.print("eval `sh denv.sh`\n");
script1.print("edpinfosys.sh -m erp5 -p '"+passw+"' -n AQ.ARDUINO -s bstart -k - -f tprompt,tvalue > ~/datard\n");
script1.print("exit\n");
script1.close();
//Priprava scriptu prenosu
Console.println("Preparing sec. script .." + key + "..\n");
File script2 = FileSystem.open("/tmp/abasexportstart.sh", FILE_WRITE);
script2.print("rm -f /tmp/datard\n");
// There is part of script responsible to transfer scrips to server and move data from server and cleanup
//------
script2.print("scp -i '" + key + "' /tmp/abasexport.sh root@zlin.amotiq.cz:\n");
script2.print("ssh -i '" + key + "' root@zlin.amotiq.cz 'scp abasexport.sh root@debian6:'\n");
script2.print("ssh -i '" + key + "' root@zlin.amotiq.cz 'ssh root@debian6 ./abasexport.sh'\n");
script2.print("ssh -i '" + key + "' root@zlin.amotiq.cz 'scp root@debian6:datard ./'\n");
script2.print("scp -i '" + key + "' root@zlin.amotiq.cz:datard /tmp/datard\n");
// cleanup
script2.print("ssh -i '" + key + "' root@zlin.amotiq.cz 'ssh root@debian6 rm -f abasexport.sh'\n");
script2.print("ssh -i '" + key + "' root@zlin.amotiq.cz 'ssh root@debian6 rm -f datard'\n");
script2.print("ssh -i '" + key + "' root@zlin.amotiq.cz 'rm -f abasexport.sh'\n");
script2.print("ssh -i '" + key + "' root@zlin.amotiq.cz 'rm -f datard'\n");
//------
script2.close();
// Make the script executable
Console.println("Change attrib of an script ....\n");
Process chmod;
chmod.begin("chmod");
chmod.addParameter("+x");
chmod.addParameter("/tmp/abasexport.sh");
chmod.addParameter("/tmp/abasexportstart.sh");
chmod.run();
//Setup crontab
Console.println("Setup crontab ....\n");
Process cron;
cron.runShellCommand("crontab -ru root");
cron.runShellCommand("echo '0 * * * * /tmp/abasexportstart.sh' | crontab -u root -");
// cron.runShellCommand("/tmp/abasexportstart.sh");
Console.println(cron.runShellCommand("/tmp/abasexportstart.sh"));
}
String readValue(String param) {
String prompt = "";
String value = "";
String hodnota = "";
String msg = "";
byte znak = 0;
int idxfrst;
int idxscnd;
//Nacte soubor a ulozi potrebne hodnoty do promennych
Console.println("Read data ....\n");
msg = "Runtime:" + (String)(millis() / 1000) + " sec";
File datard = FileSystem.open("/tmp/datard", FILE_READ);
if (datard) {
digitalWrite(13, HIGH);
while (datard.available()) {
znak = (byte)datard.read();
if (znak != 10) {
//Nacte cely radek
hodnota += (char)znak;
} else {
Console.println("Line..." + hodnota + "\n");
if (hodnota.startsWith(param)) {
//Posklada zpravu
idxfrst = hodnota.indexOf(";");
idxscnd = hodnota.indexOf(";", idxfrst + 1);
prompt = hodnota.substring(0, idxfrst);
value = hodnota.substring(idxfrst + 1, idxscnd);
prompt.trim();
value.trim();
msg += "\n$" + prompt + ":" + value;
}
hodnota = "";
}
}
datard.close();
Console.println("Data ....\n" + msg + "\n");
} else {
digitalWrite(13, LOW);
}
return msg;
}
void checkStatus() {
//Zmeni stav diody pokud neni datard - neni navazano spojeni s abasem
if (FileSystem.exists("/tmp/datard")) {
digitalWrite(13, HIGH);
} else {
digitalWrite(13, LOW);
}
}
void setup() {
Bridge.begin();
Console.begin();
// debug while (!Console);
FileSystem.begin();
// initialize digital pin 13 as an output.
pinMode(13, OUTPUT);
// Listen for incoming connection only from localhost
// (no one from the external network could connect)
server.listenOnLocalhost();
server.begin();
// Prepare scripts and cron + first start scr.
prepareScripts(key);
}
void loop() {
YunClient client = server.accept();
if (client) {
String command = client.readString();
command.trim();
client.print(readValue(command));
Console.println("Waiting...");
client.stop();
}
//Provadi kazdou 1/20 sec
checkStatus();
delay(50);
}
| [
"os@amotiq.cz"
] | os@amotiq.cz |
2dde0125b5e0b0245fa619624c727968305b6887 | b69d4964e7b5d3452357ba65b26ee89a2735e859 | /src/server/game/Achievements/AchievementMgr.cpp | 43ae67ccf0dd5004614b4f8bfa1883462ef7342d | [] | no_license | grsgs/Adcore4 | 26bfde88edac2b676b892bbe8748751bf5a083f6 | 06fc23da7ebc20de8fb7d37bf8ab6efe64349943 | refs/heads/master | 2020-04-26T16:06:30.621714 | 2013-07-26T20:58:12 | 2013-07-26T20:58:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 149,497 | cpp | /*
*
* Copyright (C) 2011-2013 DepthsCore <http://www.mist-of-depths.com/>
*
* Copyright (C) 2008-2013 TrinityCore <http://www.trinitycore.org/>
*
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "AchievementMgr.h"
#include "ArenaTeam.h"
#include "ArenaTeamMgr.h"
#include "BattlegroundAB.h"
#include "Battleground.h"
#include "CellImpl.h"
#include "Common.h"
#include "DatabaseEnv.h"
#include "DBCEnums.h"
#include "DisableMgr.h"
#include "GameEventMgr.h"
#include "GridNotifiersImpl.h"
#include "Group.h"
#include "Guild.h"
#include "GuildMgr.h"
#include "InstanceScript.h"
#include "Language.h"
#include "Map.h"
#include "MapManager.h"
#include "ObjectMgr.h"
#include "Player.h"
#include "ReputationMgr.h"
#include "ScriptMgr.h"
#include "SpellMgr.h"
#include "World.h"
#include "WorldPacket.h"
namespace Trinity
{
class AchievementChatBuilder
{
public:
AchievementChatBuilder(Player const& player, ChatMsg msgtype, int32 textId, uint32 ach_id)
: i_player(player), i_msgtype(msgtype), i_textId(textId), i_achievementId(ach_id) {}
void operator()(WorldPacket& data, LocaleConstant loc_idx)
{
char const* text = sObjectMgr->GetTrinityString(i_textId, loc_idx);
data << uint8(i_msgtype);
data << uint32(LANG_UNIVERSAL);
data << uint64(i_player.GetGUID());
data << uint32(5);
data << uint64(i_player.GetGUID());
data << uint32(strlen(text)+1);
data << text;
data << uint8(0);
data << uint32(i_achievementId);
}
private:
Player const& i_player;
ChatMsg i_msgtype;
int32 i_textId;
uint32 i_achievementId;
};
} // namespace Trinity
bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria)
{
if (dataType >= MAX_ACHIEVEMENT_CRITERIA_DATA_TYPE)
{
TC_LOG_ERROR(LOG_FILTER_SQL, "Table `achievement_criteria_data` for criteria (Entry: %u) has wrong data type (%u), ignored.", criteria->ID, dataType);
return false;
}
switch (criteria->type)
{
case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE:
case ACHIEVEMENT_CRITERIA_TYPE_WIN_BG:
case ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST: // only hardcoded list
case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL:
case ACHIEVEMENT_CRITERIA_TYPE_WIN_RATED_ARENA:
case ACHIEVEMENT_CRITERIA_TYPE_DO_EMOTE:
case ACHIEVEMENT_CRITERIA_TYPE_SPECIAL_PVP_KILL:
case ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL:
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_TYPE:
case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL2:
case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET:
case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2:
case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM:
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED_ON_LOOT:
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_GREED_ON_LOOT:
case ACHIEVEMENT_CRITERIA_TYPE_BG_OBJECTIVE_CAPTURE:
case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST: // only Children's Week achievements
case ACHIEVEMENT_CRITERIA_TYPE_USE_ITEM: // only Children's Week achievements
case ACHIEVEMENT_CRITERIA_TYPE_GET_KILLING_BLOWS:
case ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL:
break;
default:
if (dataType != ACHIEVEMENT_CRITERIA_DATA_TYPE_SCRIPT)
{
TC_LOG_ERROR(LOG_FILTER_SQL, "Table `achievement_criteria_data` has data for non-supported criteria type (Entry: %u Type: %u), ignored.", criteria->ID, criteria->type);
return false;
}
break;
}
switch (dataType)
{
case ACHIEVEMENT_CRITERIA_DATA_TYPE_NONE:
case ACHIEVEMENT_CRITERIA_DATA_TYPE_VALUE:
case ACHIEVEMENT_CRITERIA_DATA_INSTANCE_SCRIPT:
return true;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_CREATURE:
if (!creature.id || !sObjectMgr->GetCreatureTemplate(creature.id))
{
TC_LOG_ERROR(LOG_FILTER_SQL, "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_CREATURE (%u) has non-existing creature id in value1 (%u), ignored.",
criteria->ID, criteria->type, dataType, creature.id);
return false;
}
return true;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_CLASS_RACE:
if (!classRace.class_id && !classRace.race_id)
{
TC_LOG_ERROR(LOG_FILTER_SQL, "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_CLASS_RACE (%u) must not have 0 in either value field, ignored.",
criteria->ID, criteria->type, dataType);
return false;
}
if (classRace.class_id && ((1 << (classRace.class_id-1)) & CLASSMASK_ALL_PLAYABLE) == 0)
{
TC_LOG_ERROR(LOG_FILTER_SQL, "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_CLASS_RACE (%u) has non-existing class in value1 (%u), ignored.",
criteria->ID, criteria->type, dataType, classRace.class_id);
return false;
}
if (classRace.race_id && ((1 << (classRace.race_id-1)) & RACEMASK_ALL_PLAYABLE) == 0)
{
TC_LOG_ERROR(LOG_FILTER_SQL, "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_CLASS_RACE (%u) has non-existing race in value2 (%u), ignored.",
criteria->ID, criteria->type, dataType, classRace.race_id);
return false;
}
return true;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_LESS_HEALTH:
if (health.percent < 1 || health.percent > 100)
{
TC_LOG_ERROR(LOG_FILTER_SQL, "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_PLAYER_LESS_HEALTH (%u) has wrong percent value in value1 (%u), ignored.",
criteria->ID, criteria->type, dataType, health.percent);
return false;
}
return true;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA:
case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_AURA:
{
SpellInfo const* spellEntry = sSpellMgr->GetSpellInfo(aura.spell_id);
if (!spellEntry)
{
TC_LOG_ERROR(LOG_FILTER_SQL, "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type %s (%u) has wrong spell id in value1 (%u), ignored.",
criteria->ID, criteria->type, (dataType == ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA?"ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA":"ACHIEVEMENT_CRITERIA_DATA_TYPE_T_AURA"), dataType, aura.spell_id);
return false;
}
if (aura.effect_idx >= 3)
{
TC_LOG_ERROR(LOG_FILTER_SQL, "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type %s (%u) has wrong spell effect index in value2 (%u), ignored.",
criteria->ID, criteria->type, (dataType == ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA?"ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA":"ACHIEVEMENT_CRITERIA_DATA_TYPE_T_AURA"), dataType, aura.effect_idx);
return false;
}
if (!spellEntry->Effects[aura.effect_idx].ApplyAuraName)
{
TC_LOG_ERROR(LOG_FILTER_SQL, "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type %s (%u) has non-aura spell effect (ID: %u Effect: %u), ignores.",
criteria->ID, criteria->type, (dataType == ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA?"ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA":"ACHIEVEMENT_CRITERIA_DATA_TYPE_T_AURA"), dataType, aura.spell_id, aura.effect_idx);
return false;
}
return true;
}
case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_LEVEL:
if (level.minlevel > STRONG_MAX_LEVEL)
{
TC_LOG_ERROR(LOG_FILTER_SQL, "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_LEVEL (%u) has wrong minlevel in value1 (%u), ignored.",
criteria->ID, criteria->type, dataType, level.minlevel);
return false;
}
return true;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_GENDER:
if (gender.gender > GENDER_NONE)
{
TC_LOG_ERROR(LOG_FILTER_SQL, "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_GENDER (%u) has wrong gender in value1 (%u), ignored.",
criteria->ID, criteria->type, dataType, gender.gender);
return false;
}
return true;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_SCRIPT:
if (!ScriptId)
{
TC_LOG_ERROR(LOG_FILTER_SQL, "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_SCRIPT (%u) does not have ScriptName set, ignored.",
criteria->ID, criteria->type, dataType);
return false;
}
return true;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_MAP_PLAYER_COUNT:
if (map_players.maxcount <= 0)
{
TC_LOG_ERROR(LOG_FILTER_SQL, "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_MAP_PLAYER_COUNT (%u) has wrong max players count in value1 (%u), ignored.",
criteria->ID, criteria->type, dataType, map_players.maxcount);
return false;
}
return true;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_TEAM:
if (team.team != ALLIANCE && team.team != HORDE)
{
TC_LOG_ERROR(LOG_FILTER_SQL, "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_TEAM (%u) has unknown team in value1 (%u), ignored.",
criteria->ID, criteria->type, dataType, team.team);
return false;
}
return true;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_DRUNK:
if (drunk.state >= MAX_DRUNKEN)
{
TC_LOG_ERROR(LOG_FILTER_SQL, "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_S_DRUNK (%u) has unknown drunken state in value1 (%u), ignored.",
criteria->ID, criteria->type, dataType, drunk.state);
return false;
}
return true;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_HOLIDAY:
if (!sHolidaysStore.LookupEntry(holiday.id))
{
TC_LOG_ERROR(LOG_FILTER_SQL, "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_HOLIDAY (%u) has unknown holiday in value1 (%u), ignored.",
criteria->ID, criteria->type, dataType, holiday.id);
return false;
}
return true;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_BG_LOSS_TEAM_SCORE:
return true; // not check correctness node indexes
case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_EQUIPED_ITEM:
if (equipped_item.item_quality >= MAX_ITEM_QUALITY)
{
TC_LOG_ERROR(LOG_FILTER_SQL, "Table `achievement_criteria_requirement` (Entry: %u Type: %u) for requirement ACHIEVEMENT_CRITERIA_REQUIRE_S_EQUIPED_ITEM (%u) has unknown quality state in value1 (%u), ignored.",
criteria->ID, criteria->type, dataType, equipped_item.item_quality);
return false;
}
return true;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_PLAYER_CLASS_RACE:
if (!classRace.class_id && !classRace.race_id)
{
TC_LOG_ERROR(LOG_FILTER_SQL, "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_S_PLAYER_CLASS_RACE (%u) must not have 0 in either value field, ignored.",
criteria->ID, criteria->type, dataType);
return false;
}
if (classRace.class_id && ((1 << (classRace.class_id-1)) & CLASSMASK_ALL_PLAYABLE) == 0)
{
TC_LOG_ERROR(LOG_FILTER_SQL, "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_S_PLAYER_CLASS_RACE (%u) has non-existing class in value1 (%u), ignored.",
criteria->ID, criteria->type, dataType, classRace.class_id);
return false;
}
if (classRace.race_id && ((1 << (classRace.race_id-1)) & RACEMASK_ALL_PLAYABLE) == 0)
{
TC_LOG_ERROR(LOG_FILTER_SQL, "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_S_PLAYER_CLASS_RACE (%u) has non-existing race in value2 (%u), ignored.",
criteria->ID, criteria->type, dataType, classRace.race_id);
return false;
}
return true;
default:
TC_LOG_ERROR(LOG_FILTER_SQL, "Table `achievement_criteria_data` (Entry: %u Type: %u) has data for non-supported data type (%u), ignored.", criteria->ID, criteria->type, dataType);
return false;
}
}
bool AchievementCriteriaData::Meets(uint32 criteria_id, Player const* source, Unit const* target, uint32 miscValue1 /*= 0*/) const
{
switch (dataType)
{
case ACHIEVEMENT_CRITERIA_DATA_TYPE_NONE:
return true;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_CREATURE:
if (!target || target->GetTypeId() != TYPEID_UNIT)
return false;
return target->GetEntry() == creature.id;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_CLASS_RACE:
if (!target || target->GetTypeId() != TYPEID_PLAYER)
return false;
if (classRace.class_id && classRace.class_id != target->ToPlayer()->getClass())
return false;
if (classRace.race_id && classRace.race_id != target->ToPlayer()->getRace())
return false;
return true;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_PLAYER_CLASS_RACE:
if (!source || source->GetTypeId() != TYPEID_PLAYER)
return false;
if (classRace.class_id && classRace.class_id != source->ToPlayer()->getClass())
return false;
if (classRace.race_id && classRace.race_id != source->ToPlayer()->getRace())
return false;
return true;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_LESS_HEALTH:
if (!target || target->GetTypeId() != TYPEID_PLAYER)
return false;
return !target->HealthAbovePct(health.percent);
case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA:
return source->HasAuraEffect(aura.spell_id, aura.effect_idx);
case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_AURA:
return target && target->HasAuraEffect(aura.spell_id, aura.effect_idx);
case ACHIEVEMENT_CRITERIA_DATA_TYPE_VALUE:
return miscValue1 >= value.minvalue;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_LEVEL:
if (!target)
return false;
return target->getLevel() >= level.minlevel;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_GENDER:
if (!target)
return false;
return target->getGender() == gender.gender;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_SCRIPT:
return sScriptMgr->OnCriteriaCheck(ScriptId, const_cast<Player*>(source), const_cast<Unit*>(target));
case ACHIEVEMENT_CRITERIA_DATA_TYPE_MAP_PLAYER_COUNT:
return source->GetMap()->GetPlayersCountExceptGMs() <= map_players.maxcount;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_TEAM:
if (!target || target->GetTypeId() != TYPEID_PLAYER)
return false;
return target->ToPlayer()->GetTeam() == team.team;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_DRUNK:
return Player::GetDrunkenstateByValue(source->GetDrunkValue()) >= DrunkenState(drunk.state);
case ACHIEVEMENT_CRITERIA_DATA_TYPE_HOLIDAY:
return IsHolidayActive(HolidayIds(holiday.id));
case ACHIEVEMENT_CRITERIA_DATA_TYPE_BG_LOSS_TEAM_SCORE:
{
Battleground* bg = source->GetBattleground();
if (!bg)
return false;
uint32 score = bg->GetTeamScore(source->GetTeamId() == TEAM_ALLIANCE ? TEAM_HORDE : TEAM_ALLIANCE);
return score >= bg_loss_team_score.min_score && score <= bg_loss_team_score.max_score;
}
case ACHIEVEMENT_CRITERIA_DATA_INSTANCE_SCRIPT:
{
if (!source->IsInWorld())
return false;
Map* map = source->GetMap();
if (!map->IsDungeon())
{
TC_LOG_ERROR(LOG_FILTER_ACHIEVEMENTSYS, "Achievement system call ACHIEVEMENT_CRITERIA_DATA_INSTANCE_SCRIPT (%u) for achievement criteria %u for non-dungeon/non-raid map %u",
ACHIEVEMENT_CRITERIA_DATA_INSTANCE_SCRIPT, criteria_id, map->GetId());
return false;
}
InstanceScript* instance = ((InstanceMap*)map)->GetInstanceScript();
if (!instance)
{
TC_LOG_ERROR(LOG_FILTER_ACHIEVEMENTSYS, "Achievement system call ACHIEVEMENT_CRITERIA_DATA_INSTANCE_SCRIPT (%u) for achievement criteria %u for map %u but map does not have a instance script",
ACHIEVEMENT_CRITERIA_DATA_INSTANCE_SCRIPT, criteria_id, map->GetId());
return false;
}
return instance->CheckAchievementCriteriaMeet(criteria_id, source, target, miscValue1);
}
case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_EQUIPED_ITEM:
{
ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(miscValue1);
if (!pProto)
return false;
return pProto->ItemLevel >= equipped_item.item_level && pProto->Quality >= equipped_item.item_quality;
}
default:
break;
}
return false;
}
bool AchievementCriteriaDataSet::Meets(Player const* source, Unit const* target, uint32 miscValue /*= 0*/) const
{
for (Storage::const_iterator itr = storage.begin(); itr != storage.end(); ++itr)
if (!itr->Meets(criteria_id, source, target, miscValue))
return false;
return true;
}
template<class T>
AchievementMgr<T>::AchievementMgr(T* owner): _owner(owner), _achievementPoints(0) {}
template<class T>
AchievementMgr<T>::~AchievementMgr()
{
}
template<class T>
void AchievementMgr<T>::SendPacket(WorldPacket* data) const
{
}
template<>
void AchievementMgr<Guild>::SendPacket(WorldPacket* data) const
{
GetOwner()->BroadcastPacket(data);
}
template<>
void AchievementMgr<Player>::SendPacket(WorldPacket* data) const
{
GetOwner()->GetSession()->SendPacket(data);
}
template<class T>
void AchievementMgr<T>::RemoveCriteriaProgress(AchievementCriteriaEntry const* entry)
{
if (!entry)
return;
CriteriaProgressMap::iterator criteriaProgress = m_criteriaProgress.find(entry->ID);
if (criteriaProgress == m_criteriaProgress.end())
return;
WorldPacket data(SMSG_CRITERIA_DELETED, 4);
data << uint32(entry->ID);
SendPacket(&data);
m_criteriaProgress.erase(criteriaProgress);
}
template<>
void AchievementMgr<Guild>::RemoveCriteriaProgress(AchievementCriteriaEntry const* entry)
{
if (!entry)
return;
CriteriaProgressMap::iterator criteriaProgress = m_criteriaProgress.find(entry->ID);
if (criteriaProgress == m_criteriaProgress.end())
return;
ObjectGuid guid = GetOwner()->GetGUID();
WorldPacket data(SMSG_GUILD_CRITERIA_DELETED, 4 + 8);
data.WriteBit(guid[6]);
data.WriteBit(guid[5]);
data.WriteBit(guid[7]);
data.WriteBit(guid[0]);
data.WriteBit(guid[1]);
data.WriteBit(guid[3]);
data.WriteBit(guid[2]);
data.WriteBit(guid[4]);
data.WriteByteSeq(guid[2]);
data.WriteByteSeq(guid[3]);
data.WriteByteSeq(guid[4]);
data.WriteByteSeq(guid[1]);
data.WriteByteSeq(guid[7]);
data << uint32(entry->ID);
data.WriteByteSeq(guid[5]);
data.WriteByteSeq(guid[0]);
data.WriteByteSeq(guid[6]);
SendPacket(&data);
m_criteriaProgress.erase(criteriaProgress);
}
template<class T>
void AchievementMgr<T>::ResetAchievementCriteria(AchievementCriteriaTypes type, uint64 miscValue1, uint64 miscValue2, bool evenIfCriteriaComplete)
{
TC_LOG_DEBUG(LOG_FILTER_ACHIEVEMENTSYS, "ResetAchievementCriteria(%u, " UI64FMTD ", " UI64FMTD ")", type, miscValue1, miscValue2);
// disable for gamemasters with GM-mode enabled
if (GetOwner()->IsGameMaster())
return;
AchievementCriteriaEntryList const& achievementCriteriaList = sAchievementMgr->GetAchievementCriteriaByType(type);
for (AchievementCriteriaEntryList::const_iterator i = achievementCriteriaList.begin(); i != achievementCriteriaList.end(); ++i)
{
AchievementCriteriaEntry const* achievementCriteria = (*i);
AchievementEntry const* achievement = sAchievementMgr->GetAchievement(achievementCriteria->achievement);
if (!achievement)
continue;
// don't update already completed criteria if not forced or achievement already complete
if ((IsCompletedCriteria(achievementCriteria, achievement) && !evenIfCriteriaComplete) || HasAchieved(achievement->ID))
continue;
for (uint8 j = 0; j < MAX_CRITERIA_REQUIREMENTS; ++j)
if (achievementCriteria->additionalRequirements[j].additionalRequirement_type == miscValue1 &&
(!achievementCriteria->additionalRequirements[j].additionalRequirement_value ||
achievementCriteria->additionalRequirements[j].additionalRequirement_value == miscValue2))
{
RemoveCriteriaProgress(achievementCriteria);
break;
}
}
}
template<>
void AchievementMgr<Guild>::ResetAchievementCriteria(AchievementCriteriaTypes /*type*/, uint64 /*miscValue1*/, uint64 /*miscValue2*/, bool /*evenIfCriteriaComplete*/)
{
// Not needed
}
template<class T>
void AchievementMgr<T>::DeleteFromDB(uint32 /*lowguid*/)
{
}
template<>
void AchievementMgr<Player>::DeleteFromDB(uint32 lowguid)
{
SQLTransaction trans = CharacterDatabase.BeginTransaction();
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_ACHIEVEMENT);
stmt->setUInt32(0, lowguid);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_ACHIEVEMENT_PROGRESS);
stmt->setUInt32(0, lowguid);
trans->Append(stmt);
CharacterDatabase.CommitTransaction(trans);
}
template<>
void AchievementMgr<Guild>::DeleteFromDB(uint32 lowguid)
{
SQLTransaction trans = CharacterDatabase.BeginTransaction();
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ALL_GUILD_ACHIEVEMENTS);
stmt->setUInt32(0, lowguid);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ALL_GUILD_ACHIEVEMENT_CRITERIA);
stmt->setUInt32(0, lowguid);
trans->Append(stmt);
CharacterDatabase.CommitTransaction(trans);
}
template<class T>
void AchievementMgr<T>::SaveToDB(SQLTransaction& /*trans*/)
{
}
template<>
void AchievementMgr<Player>::SaveToDB(SQLTransaction& trans)
{
if (!m_completedAchievements.empty())
{
bool need_execute = false;
std::ostringstream ssdel;
std::ostringstream ssins;
for (CompletedAchievementMap::iterator iter = m_completedAchievements.begin(); iter != m_completedAchievements.end(); ++iter)
{
if (!iter->second.changed)
continue;
/// first new/changed record prefix
if (!need_execute)
{
ssdel << "DELETE FROM character_achievement WHERE guid = " << GetOwner()->GetGUIDLow() << " AND achievement IN (";
ssins << "INSERT INTO character_achievement (guid, achievement, date) VALUES ";
need_execute = true;
}
/// next new/changed record prefix
else
{
ssdel << ',';
ssins << ',';
}
// new/changed record data
ssdel << iter->first;
ssins << '(' << GetOwner()->GetGUIDLow() << ',' << iter->first << ',' << uint64(iter->second.date) << ')';
/// mark as saved in db
iter->second.changed = false;
}
if (need_execute)
{
ssdel << ')';
trans->Append(ssdel.str().c_str());
trans->Append(ssins.str().c_str());
}
}
if (!m_criteriaProgress.empty())
{
/// prepare deleting and insert
bool need_execute_del = false;
bool need_execute_ins = false;
std::ostringstream ssdel;
std::ostringstream ssins;
for (CriteriaProgressMap::iterator iter = m_criteriaProgress.begin(); iter != m_criteriaProgress.end(); ++iter)
{
if (!iter->second.changed)
continue;
// deleted data (including 0 progress state)
{
/// first new/changed record prefix (for any counter value)
if (!need_execute_del)
{
ssdel << "DELETE FROM character_achievement_progress WHERE guid = " << GetOwner()->GetGUIDLow() << " AND criteria IN (";
need_execute_del = true;
}
/// next new/changed record prefix
else
ssdel << ',';
// new/changed record data
ssdel << iter->first;
}
// store data only for real progress
if (iter->second.counter != 0)
{
/// first new/changed record prefix
if (!need_execute_ins)
{
ssins << "INSERT INTO character_achievement_progress (guid, criteria, counter, date) VALUES ";
need_execute_ins = true;
}
/// next new/changed record prefix
else
ssins << ',';
// new/changed record data
ssins << '(' << GetOwner()->GetGUIDLow() << ',' << iter->first << ',' << iter->second.counter << ',' << iter->second.date << ')';
}
/// mark as updated in db
iter->second.changed = false;
}
if (need_execute_del) // DELETE ... IN (.... _)_
ssdel << ')';
if (need_execute_del || need_execute_ins)
{
if (need_execute_del)
trans->Append(ssdel.str().c_str());
if (need_execute_ins)
trans->Append(ssins.str().c_str());
}
}
}
template<>
void AchievementMgr<Guild>::SaveToDB(SQLTransaction& trans)
{
PreparedStatement* stmt;
std::ostringstream guidstr;
for (CompletedAchievementMap::const_iterator itr = m_completedAchievements.begin(); itr != m_completedAchievements.end(); ++itr)
{
if (!itr->second.changed)
continue;
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_ACHIEVEMENT);
stmt->setUInt32(0, GetOwner()->GetId());
stmt->setUInt16(1, itr->first);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_GUILD_ACHIEVEMENT);
stmt->setUInt32(0, GetOwner()->GetId());
stmt->setUInt16(1, itr->first);
stmt->setUInt32(2, itr->second.date);
for (std::set<uint64>::const_iterator gItr = itr->second.guids.begin(); gItr != itr->second.guids.end(); ++gItr)
guidstr << GUID_LOPART(*gItr) << ',';
stmt->setString(3, guidstr.str());
trans->Append(stmt);
guidstr.str("");
}
for (CriteriaProgressMap::const_iterator itr = m_criteriaProgress.begin(); itr != m_criteriaProgress.end(); ++itr)
{
if (!itr->second.changed)
continue;
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_ACHIEVEMENT_CRITERIA);
stmt->setUInt32(0, GetOwner()->GetId());
stmt->setUInt16(1, itr->first);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_GUILD_ACHIEVEMENT_CRITERIA);
stmt->setUInt32(0, GetOwner()->GetId());
stmt->setUInt16(1, itr->first);
stmt->setUInt64(2, itr->second.counter);
stmt->setUInt32(3, itr->second.date);
stmt->setUInt32(4, GUID_LOPART(itr->second.CompletedGUID));
trans->Append(stmt);
}
}
template<class T>
void AchievementMgr<T>::LoadFromDB(PreparedQueryResult achievementResult, PreparedQueryResult criteriaResult)
{
}
template<>
void AchievementMgr<Player>::LoadFromDB(PreparedQueryResult achievementResult, PreparedQueryResult criteriaResult)
{
if (achievementResult)
{
do
{
Field* fields = achievementResult->Fetch();
uint32 achievementid = fields[0].GetUInt16();
// must not happen: cleanup at server startup in sAchievementMgr->LoadCompletedAchievements()
AchievementEntry const* achievement = sAchievementMgr->GetAchievement(achievementid);
if (!achievement)
continue;
CompletedAchievementData& ca = m_completedAchievements[achievementid];
ca.date = time_t(fields[1].GetUInt32());
ca.changed = false;
_achievementPoints += achievement->points;
// title achievement rewards are retroactive
if (AchievementReward const* reward = sAchievementMgr->GetAchievementReward(achievement))
if (uint32 titleId = reward->titleId[Player::TeamForRace(GetOwner()->getRace()) == ALLIANCE ? 0 : 1])
if (CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(titleId))
GetOwner()->SetTitle(titleEntry);
}
while (achievementResult->NextRow());
}
if (criteriaResult)
{
time_t now = time(NULL);
do
{
Field* fields = criteriaResult->Fetch();
uint32 id = fields[0].GetUInt16();
uint64 counter = fields[1].GetUInt64();
time_t date = time_t(fields[2].GetUInt32());
AchievementCriteriaEntry const* criteria = sAchievementMgr->GetAchievementCriteria(id);
if (!criteria)
{
// we will remove not existed criteria for all characters
TC_LOG_ERROR(LOG_FILTER_ACHIEVEMENTSYS, "Non-existing achievement criteria %u data removed from table `character_achievement_progress`.", id);
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_INVALID_ACHIEV_PROGRESS_CRITERIA);
stmt->setUInt16(0, uint16(id));
CharacterDatabase.Execute(stmt);
continue;
}
if (criteria->timeLimit && time_t(date + criteria->timeLimit) < now)
continue;
CriteriaProgress& progress = m_criteriaProgress[id];
progress.counter = counter;
progress.date = date;
progress.changed = false;
}
while (criteriaResult->NextRow());
}
}
template<>
void AchievementMgr<Guild>::LoadFromDB(PreparedQueryResult achievementResult, PreparedQueryResult criteriaResult)
{
if (achievementResult)
{
do
{
Field* fields = achievementResult->Fetch();
uint32 achievementid = fields[0].GetUInt16();
// must not happen: cleanup at server startup in sAchievementMgr->LoadCompletedAchievements()
AchievementEntry const* achievement = sAchievementMgr->GetAchievement(achievementid);
if (!achievement)
continue;
CompletedAchievementData& ca = m_completedAchievements[achievementid];
ca.date = time_t(fields[1].GetUInt32());
Tokenizer guids(fields[2].GetString(), ' ');
for (uint32 i = 0; i < guids.size(); ++i)
ca.guids.insert(MAKE_NEW_GUID(atol(guids[i]), 0, HIGHGUID_PLAYER));
ca.changed = false;
_achievementPoints += achievement->points;
}
while (achievementResult->NextRow());
}
if (criteriaResult)
{
time_t now = time(NULL);
do
{
Field* fields = criteriaResult->Fetch();
uint32 id = fields[0].GetUInt16();
uint32 counter = fields[1].GetUInt32();
time_t date = time_t(fields[2].GetUInt32());
uint64 guid = fields[3].GetUInt32();
AchievementCriteriaEntry const* criteria = sAchievementMgr->GetAchievementCriteria(id);
if (!criteria)
{
// we will remove not existed criteria for all guilds
TC_LOG_ERROR(LOG_FILTER_ACHIEVEMENTSYS, "Non-existing achievement criteria %u data removed from table `guild_achievement_progress`.", id);
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_INVALID_ACHIEV_PROGRESS_CRITERIA_GUILD);
stmt->setUInt16(0, uint16(id));
CharacterDatabase.Execute(stmt);
continue;
}
if (criteria->timeLimit && time_t(date + criteria->timeLimit) < now)
continue;
CriteriaProgress& progress = m_criteriaProgress[id];
progress.counter = counter;
progress.date = date;
progress.CompletedGUID = MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER);
progress.changed = false;
} while (criteriaResult->NextRow());
}
}
template<class T>
void AchievementMgr<T>::Reset()
{
}
template<>
void AchievementMgr<Player>::Reset()
{
for (CompletedAchievementMap::const_iterator iter = m_completedAchievements.begin(); iter != m_completedAchievements.end(); ++iter)
{
WorldPacket data(SMSG_ACHIEVEMENT_DELETED, 4);
data << uint32(iter->first);
SendPacket(&data);
}
for (CriteriaProgressMap::const_iterator iter = m_criteriaProgress.begin(); iter != m_criteriaProgress.end(); ++iter)
{
WorldPacket data(SMSG_CRITERIA_DELETED, 4);
data << uint32(iter->first);
SendPacket(&data);
}
m_completedAchievements.clear();
_achievementPoints = 0;
m_criteriaProgress.clear();
DeleteFromDB(GetOwner()->GetGUIDLow());
// re-fill data
CheckAllAchievementCriteria(GetOwner());
}
template<>
void AchievementMgr<Guild>::Reset()
{
ObjectGuid guid = GetOwner()->GetGUID();
for (CompletedAchievementMap::const_iterator iter = m_completedAchievements.begin(); iter != m_completedAchievements.end(); ++iter)
{
WorldPacket data(SMSG_GUILD_ACHIEVEMENT_DELETED, 4);
data.WriteBit(guid[4]);
data.WriteBit(guid[1]);
data.WriteBit(guid[2]);
data.WriteBit(guid[3]);
data.WriteBit(guid[0]);
data.WriteBit(guid[7]);
data.WriteBit(guid[5]);
data.WriteBit(guid[6]);
data << uint32(iter->first);
data.WriteByteSeq(guid[5]);
data.WriteByteSeq(guid[1]);
data.WriteByteSeq(guid[3]);
data.WriteByteSeq(guid[6]);
data.WriteByteSeq(guid[0]);
data.WriteByteSeq(guid[7]);
data.AppendPackedTime(iter->second.date);
data.WriteByteSeq(guid[4]);
data.WriteByteSeq(guid[2]);
SendPacket(&data);
}
while (!m_criteriaProgress.empty())
if (AchievementCriteriaEntry const* criteria = sAchievementMgr->GetAchievementCriteria(m_criteriaProgress.begin()->first))
RemoveCriteriaProgress(criteria);
_achievementPoints = 0;
m_completedAchievements.clear();
DeleteFromDB(GetOwner()->GetId());
}
template<class T>
void AchievementMgr<T>::SendAchievementEarned(AchievementEntry const* achievement) const
{
// Don't send for achievements with ACHIEVEMENT_FLAG_HIDDEN
if (achievement->flags & ACHIEVEMENT_FLAG_HIDDEN)
return;
TC_LOG_DEBUG(LOG_FILTER_ACHIEVEMENTSYS, "AchievementMgr::SendAchievementEarned(%u)", achievement->ID);
if (Guild* guild = sGuildMgr->GetGuildById(GetOwner()->GetGuildId()))
{
Trinity::AchievementChatBuilder say_builder(*GetOwner(), CHAT_MSG_GUILD_ACHIEVEMENT, LANG_ACHIEVEMENT_EARNED, achievement->ID);
Trinity::LocalizedPacketDo<Trinity::AchievementChatBuilder> say_do(say_builder);
guild->BroadcastWorker(say_do);
}
if (achievement->flags & (ACHIEVEMENT_FLAG_REALM_FIRST_KILL | ACHIEVEMENT_FLAG_REALM_FIRST_REACH))
{
// broadcast realm first reached
WorldPacket data(SMSG_SERVER_FIRST_ACHIEVEMENT, GetOwner()->GetName().size() + 1 + 8 + 4 + 4);
data << GetOwner()->GetName();
data << uint64(GetOwner()->GetGUID());
data << uint32(achievement->ID);
data << uint32(0); // 1=link supplied string as player name, 0=display plain string
sWorld->SendGlobalMessage(&data);
}
// if player is in world he can tell his friends about new achievement
else if (GetOwner()->IsInWorld())
{
Trinity::AchievementChatBuilder say_builder(*GetOwner(), CHAT_MSG_ACHIEVEMENT, LANG_ACHIEVEMENT_EARNED, achievement->ID);
CellCoord p = Trinity::ComputeCellCoord(GetOwner()->GetPositionX(), GetOwner()->GetPositionY());
Cell cell(p);
cell.SetNoCreate();
Trinity::LocalizedPacketDo<Trinity::AchievementChatBuilder> say_do(say_builder);
Trinity::PlayerDistWorker<Trinity::LocalizedPacketDo<Trinity::AchievementChatBuilder> > say_worker(GetOwner(), sWorld->getFloatConfig(CONFIG_LISTEN_RANGE_SAY), say_do);
TypeContainerVisitor<Trinity::PlayerDistWorker<Trinity::LocalizedPacketDo<Trinity::AchievementChatBuilder> >, WorldTypeMapContainer > message(say_worker);
cell.Visit(p, message, *GetOwner()->GetMap(), *GetOwner(), sWorld->getFloatConfig(CONFIG_LISTEN_RANGE_SAY));
}
WorldPacket data(SMSG_ACHIEVEMENT_EARNED, 8+4+8);
data.append(GetOwner()->GetPackGUID());
data << uint32(achievement->ID);
data.AppendPackedTime(time(NULL));
data << uint32(0); // does not notify player ingame
GetOwner()->SendMessageToSetInRange(&data, sWorld->getFloatConfig(CONFIG_LISTEN_RANGE_SAY), true);
}
template<>
void AchievementMgr<Guild>::SendAchievementEarned(AchievementEntry const* achievement) const
{
ObjectGuid guid = GetOwner()->GetGUID();
WorldPacket data(SMSG_GUILD_ACHIEVEMENT_EARNED, 8+4+8);
data.WriteBit(guid[3]);
data.WriteBit(guid[1]);
data.WriteBit(guid[0]);
data.WriteBit(guid[7]);
data.WriteBit(guid[4]);
data.WriteBit(guid[6]);
data.WriteBit(guid[2]);
data.WriteBit(guid[5]);
data.WriteByteSeq(guid[2]);
data.AppendPackedTime(time(NULL));
data.WriteByteSeq(guid[0]);
data.WriteByteSeq(guid[4]);
data.WriteByteSeq(guid[1]);
data.WriteByteSeq(guid[3]);
data << uint32(achievement->ID);
data.WriteByteSeq(guid[7]);
data.WriteByteSeq(guid[5]);
data.WriteByteSeq(guid[6]);
SendPacket(&data);
}
template<class T>
void AchievementMgr<T>::SendCriteriaUpdate(AchievementCriteriaEntry const* /*entry*/, CriteriaProgress const* /*progress*/, uint32 /*timeElapsed*/, bool /*timedCompleted*/) const
{
}
template<>
void AchievementMgr<Player>::SendCriteriaUpdate(AchievementCriteriaEntry const* entry, CriteriaProgress const* progress, uint32 timeElapsed, bool timedCompleted) const
{
WorldPacket data(SMSG_CRITERIA_UPDATE, 8 + 4 + 8);
data << uint32(entry->ID);
// the counter is packed like a packed Guid
data.appendPackGUID(progress->counter);
data.appendPackGUID(GetOwner()->GetGUID());
if (!entry->timeLimit)
data << uint32(0);
else
data << uint32(timedCompleted ? 0 : 1); // this are some flags, 1 is for keeping the counter at 0 in client
data.AppendPackedTime(progress->date);
data << uint32(timeElapsed); // time elapsed in seconds
data << uint32(0); // unk
SendPacket(&data);
}
template<>
void AchievementMgr<Guild>::SendCriteriaUpdate(AchievementCriteriaEntry const* entry, CriteriaProgress const* progress, uint32 /*timeElapsed*/, bool /*timedCompleted*/) const
{
//will send response to criteria progress request
WorldPacket data(SMSG_GUILD_CRITERIA_DATA, 3 + 1 + 1 + 8 + 8 + 4 + 4 + 4 + 4 + 4);
ObjectGuid counter = progress->counter; // for accessing every byte individually
ObjectGuid guid = progress->CompletedGUID;
data.WriteBits(1, 21);
data.WriteBit(counter[4]);
data.WriteBit(counter[1]);
data.WriteBit(guid[2]);
data.WriteBit(counter[3]);
data.WriteBit(guid[1]);
data.WriteBit(counter[5]);
data.WriteBit(counter[0]);
data.WriteBit(guid[3]);
data.WriteBit(counter[2]);
data.WriteBit(guid[7]);
data.WriteBit(guid[5]);
data.WriteBit(guid[0]);
data.WriteBit(counter[6]);
data.WriteBit(guid[6]);
data.WriteBit(counter[7]);
data.WriteBit(guid[4]);
data.FlushBits();
data.WriteByteSeq(guid[5]);
data << uint32(progress->date); // unknown date
data.WriteByteSeq(counter[3]);
data.WriteByteSeq(counter[7]);
data << uint32(progress->date); // unknown date
data.WriteByteSeq(counter[6]);
data.WriteByteSeq(guid[4]);
data.WriteByteSeq(guid[1]);
data.WriteByteSeq(counter[4]);
data.WriteByteSeq(guid[3]);
data.WriteByteSeq(counter[0]);
data.WriteByteSeq(guid[2]);
data.WriteByteSeq(counter[1]);
data.WriteByteSeq(guid[6]);
data << uint32(progress->date); // last update time (not packed!)
data << uint32(entry->ID);
data.WriteByteSeq(counter[5]);
data << uint32(0);
data.WriteByteSeq(guid[7]);
data.WriteByteSeq(counter[2]);
data.WriteByteSeq(guid[0]);
SendPacket(&data);
}
/**
* called at player login. The player might have fulfilled some achievements when the achievement system wasn't working yet
*/
template<class T>
void AchievementMgr<T>::CheckAllAchievementCriteria(Player* referencePlayer)
{
// suppress sending packets
for (uint32 i=0; i<ACHIEVEMENT_CRITERIA_TYPE_TOTAL; ++i)
UpdateAchievementCriteria(AchievementCriteriaTypes(i), 0, 0, 0, NULL, referencePlayer);
}
static const uint32 achievIdByArenaSlot[MAX_ARENA_SLOT] = {1057, 1107, 1108};
static const uint32 achievIdForDungeon[][4] =
{
// ach_cr_id, is_dungeon, is_raid, is_heroic_dungeon
{ 321, true, true, true },
{ 916, false, true, false },
{ 917, false, true, false },
{ 918, true, false, false },
{ 2219, false, false, true },
{ 0, false, false, false }
};
// Helper function to avoid having to specialize template for a 800 line long function
template <typename T> static bool IsGuild() { return false; }
template<> bool IsGuild<Guild>() { return true; }
/**
* this function will be called whenever the user might have done a criteria relevant action
*/
template<class T>
void AchievementMgr<T>::UpdateAchievementCriteria(AchievementCriteriaTypes type, uint64 miscValue1 /*= 0*/, uint64 miscValue2 /*= 0*/, uint64 miscValue3 /*= 0*/, Unit const* unit /*= NULL*/, Player* referencePlayer /*= NULL*/)
{
if (type >= ACHIEVEMENT_CRITERIA_TYPE_TOTAL)
{
TC_LOG_DEBUG(LOG_FILTER_ACHIEVEMENTSYS, "UpdateAchievementCriteria: Wrong criteria type %u", type);
return;
}
if (!referencePlayer)
{
TC_LOG_DEBUG(LOG_FILTER_ACHIEVEMENTSYS, "UpdateAchievementCriteria: Player is NULL! Cant update criteria");
return;
}
// disable for gamemasters with GM-mode enabled
if (referencePlayer->IsGameMaster())
{
TC_LOG_DEBUG(LOG_FILTER_ACHIEVEMENTSYS, "UpdateAchievementCriteria: [Player %s GM mode on] %s, %s (%u), " UI64FMTD ", " UI64FMTD ", " UI64FMTD
, referencePlayer->GetName().c_str(), GetLogNameForGuid(GetOwner()->GetGUID()), AchievementGlobalMgr::GetCriteriaTypeString(type), type, miscValue1, miscValue2, miscValue3);
return;
}
TC_LOG_DEBUG(LOG_FILTER_ACHIEVEMENTSYS, "UpdateAchievementCriteria: %s, %s (%u), " UI64FMTD ", " UI64FMTD ", " UI64FMTD
, GetLogNameForGuid(GetOwner()->GetGUID()), AchievementGlobalMgr::GetCriteriaTypeString(type), type, miscValue1, miscValue2, miscValue3);
// Lua_GetGuildLevelEnabled() is checked in achievement UI to display guild tab
if (IsGuild<T>() && !sWorld->getBoolConfig(CONFIG_GUILD_LEVELING_ENABLED))
return;
AchievementCriteriaEntryList const& achievementCriteriaList = sAchievementMgr->GetAchievementCriteriaByType(type, IsGuild<T>());
for (AchievementCriteriaEntryList::const_iterator i = achievementCriteriaList.begin(); i != achievementCriteriaList.end(); ++i)
{
AchievementCriteriaEntry const* achievementCriteria = (*i);
AchievementEntry const* achievement = sAchievementMgr->GetAchievement(achievementCriteria->achievement);
if (!achievement)
{
TC_LOG_ERROR(LOG_FILTER_ACHIEVEMENTSYS, "UpdateAchievementCriteria: Achievement %u not found!", achievementCriteria->achievement);
continue;
}
if (!CanUpdateCriteria(achievementCriteria, achievement, miscValue1, miscValue2, miscValue3, unit, referencePlayer))
continue;
// requirements not found in the dbc
if (AchievementCriteriaDataSet const* data = sAchievementMgr->GetCriteriaDataSet(achievementCriteria))
if (!data->Meets(referencePlayer, unit, miscValue1))
continue;
switch (type)
{
// std. case: increment at 1
case ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS:
case ACHIEVEMENT_CRITERIA_TYPE_LOSE_DUEL:
case ACHIEVEMENT_CRITERIA_TYPE_CREATE_AUCTION:
case ACHIEVEMENT_CRITERIA_TYPE_WON_AUCTIONS: /* FIXME: for online player only currently */
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED:
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_GREED:
case ACHIEVEMENT_CRITERIA_TYPE_QUEST_ABANDONED:
case ACHIEVEMENT_CRITERIA_TYPE_FLIGHT_PATHS_TAKEN:
case ACHIEVEMENT_CRITERIA_TYPE_ACCEPTED_SUMMONINGS:
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_EPIC_ITEM:
case ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM:
case ACHIEVEMENT_CRITERIA_TYPE_DEATH:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST:
case ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP:
case ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON:
case ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_CREATURE:
case ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_PLAYER:
case ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM:
case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET:
case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2:
case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL:
case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL2:
case ACHIEVEMENT_CRITERIA_TYPE_WIN_RATED_ARENA:
case ACHIEVEMENT_CRITERIA_TYPE_USE_ITEM:
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED_ON_LOOT:
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_GREED_ON_LOOT:
case ACHIEVEMENT_CRITERIA_TYPE_DO_EMOTE:
case ACHIEVEMENT_CRITERIA_TYPE_USE_GAMEOBJECT:
case ACHIEVEMENT_CRITERIA_TYPE_FISH_IN_GAMEOBJECT:
case ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL:
case ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS:
case ACHIEVEMENT_CRITERIA_TYPE_HK_RACE:
case ACHIEVEMENT_CRITERIA_TYPE_BG_OBJECTIVE_CAPTURE:
case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL:
case ACHIEVEMENT_CRITERIA_TYPE_SPECIAL_PVP_KILL:
case ACHIEVEMENT_CRITERIA_TYPE_GET_KILLING_BLOWS:
case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL_AT_AREA:
case ACHIEVEMENT_CRITERIA_TYPE_WIN_ARENA: // This also behaves like ACHIEVEMENT_CRITERIA_TYPE_WIN_RATED_ARENA
SetCriteriaProgress(achievementCriteria, 1, referencePlayer, PROGRESS_ACCUMULATE);
break;
// std case: increment at miscValue1
case ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_VENDORS:
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS:
case ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD:
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING:
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_AT_BARBER:
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_MAIL:
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_MONEY:
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_EARNED_BY_AUCTIONS:/* FIXME: for online player only currently */
case ACHIEVEMENT_CRITERIA_TYPE_TOTAL_DAMAGE_RECEIVED:
case ACHIEVEMENT_CRITERIA_TYPE_TOTAL_HEALING_RECEIVED:
case ACHIEVEMENT_CRITERIA_TYPE_USE_LFD_TO_GROUP_WITH_PLAYERS:
case ACHIEVEMENT_CRITERIA_TYPE_WIN_BG:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_BATTLEGROUND:
case ACHIEVEMENT_CRITERIA_TYPE_DAMAGE_DONE:
case ACHIEVEMENT_CRITERIA_TYPE_HEALING_DONE:
SetCriteriaProgress(achievementCriteria, miscValue1, referencePlayer, PROGRESS_ACCUMULATE);
break;
case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE:
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_TYPE:
case ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM:
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_ITEM:
case ACHIEVEMENT_CRITERIA_TYPE_CURRENCY:
SetCriteriaProgress(achievementCriteria, miscValue2, referencePlayer, PROGRESS_ACCUMULATE);
break;
// std case: high value at miscValue1
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_AUCTION_BID:
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_AUCTION_SOLD: /* FIXME: for online player only currently */
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_DEALT:
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_RECEIVED:
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEAL_CASTED:
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEALING_RECEIVED:
SetCriteriaProgress(achievementCriteria, miscValue1, referencePlayer, PROGRESS_HIGHEST);
break;
case ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL:
SetCriteriaProgress(achievementCriteria, referencePlayer->getLevel(), referencePlayer);
break;
case ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL:
if (uint32 skillvalue = referencePlayer->GetBaseSkillValue(achievementCriteria->reach_skill_level.skillID))
SetCriteriaProgress(achievementCriteria, skillvalue, referencePlayer);
break;
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL:
if (uint32 maxSkillvalue = referencePlayer->GetPureMaxSkillValue(achievementCriteria->learn_skill_level.skillID))
SetCriteriaProgress(achievementCriteria, maxSkillvalue, referencePlayer);
break;
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT:
SetCriteriaProgress(achievementCriteria, referencePlayer->GetRewardedQuestCount(), referencePlayer);
break;
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST_DAILY:
{
time_t nextDailyResetTime = sWorld->GetNextDailyQuestsResetTime();
CriteriaProgress *progress = GetCriteriaProgress(achievementCriteria);
if (!miscValue1) // Login case.
{
// reset if player missed one day.
if (progress && progress->date < (nextDailyResetTime - 2 * DAY))
SetCriteriaProgress(achievementCriteria, 0, referencePlayer, PROGRESS_SET);
continue;
}
ProgressType progressType;
if (!progress)
// 1st time. Start count.
progressType = PROGRESS_SET;
else if (progress->date < (nextDailyResetTime - 2 * DAY))
// last progress is older than 2 days. Player missed 1 day => Restart count.
progressType = PROGRESS_SET;
else if (progress->date < (nextDailyResetTime - DAY))
// last progress is between 1 and 2 days. => 1st time of the day.
progressType = PROGRESS_ACCUMULATE;
else
// last progress is within the day before the reset => Already counted today.
continue;
SetCriteriaProgress(achievementCriteria, 1, referencePlayer, progressType);
break;
}
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE:
{
uint32 counter = 0;
const RewardedQuestSet &rewQuests = referencePlayer->getRewardedQuests();
for (RewardedQuestSet::const_iterator itr = rewQuests.begin(); itr != rewQuests.end(); ++itr)
{
Quest const* quest = sObjectMgr->GetQuestTemplate(*itr);
if (quest && quest->GetZoneOrSort() >= 0 && uint32(quest->GetZoneOrSort()) == achievementCriteria->complete_quests_in_zone.zoneID)
++counter;
}
SetCriteriaProgress(achievementCriteria, counter, referencePlayer);
break;
}
case ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING:
// miscValue1 is the ingame fallheight*100 as stored in dbc
SetCriteriaProgress(achievementCriteria, miscValue1, referencePlayer);
break;
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST:
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL:
case ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA:
case ACHIEVEMENT_CRITERIA_TYPE_VISIT_BARBER_SHOP:
case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM:
case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_ACHIEVEMENT:
SetCriteriaProgress(achievementCriteria, 1, referencePlayer);
break;
case ACHIEVEMENT_CRITERIA_TYPE_BUY_BANK_SLOT:
SetCriteriaProgress(achievementCriteria, referencePlayer->GetBankBagSlotCount(), referencePlayer);
break;
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION:
{
int32 reputation = referencePlayer->GetReputationMgr().GetReputation(achievementCriteria->gain_reputation.factionID);
if (reputation > 0)
SetCriteriaProgress(achievementCriteria, reputation, referencePlayer);
break;
}
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION:
SetCriteriaProgress(achievementCriteria, referencePlayer->GetReputationMgr().GetExaltedFactionCount(), referencePlayer);
break;
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS:
{
uint32 spellCount = 0;
for (PlayerSpellMap::const_iterator spellIter = referencePlayer->GetSpellMap().begin();
spellIter != referencePlayer->GetSpellMap().end();
++spellIter)
{
SkillLineAbilityMapBounds bounds = sSpellMgr->GetSkillLineAbilityMapBounds(spellIter->first);
for (SkillLineAbilityMap::const_iterator skillIter = bounds.first; skillIter != bounds.second; ++skillIter)
{
if (skillIter->second->skillId == achievementCriteria->learn_skillline_spell.skillLine)
spellCount++;
}
}
SetCriteriaProgress(achievementCriteria, spellCount, referencePlayer);
break;
}
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_REVERED_REPUTATION:
SetCriteriaProgress(achievementCriteria, referencePlayer->GetReputationMgr().GetReveredFactionCount(), referencePlayer);
break;
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_HONORED_REPUTATION:
SetCriteriaProgress(achievementCriteria, referencePlayer->GetReputationMgr().GetHonoredFactionCount(), referencePlayer);
break;
case ACHIEVEMENT_CRITERIA_TYPE_KNOWN_FACTIONS:
SetCriteriaProgress(achievementCriteria, referencePlayer->GetReputationMgr().GetVisibleFactionCount(), referencePlayer);
break;
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE:
{
uint32 spellCount = 0;
for (PlayerSpellMap::const_iterator spellIter = referencePlayer->GetSpellMap().begin();
spellIter != referencePlayer->GetSpellMap().end();
++spellIter)
{
SkillLineAbilityMapBounds bounds = sSpellMgr->GetSkillLineAbilityMapBounds(spellIter->first);
for (SkillLineAbilityMap::const_iterator skillIter = bounds.first; skillIter != bounds.second; ++skillIter)
if (skillIter->second->skillId == achievementCriteria->learn_skill_line.skillLine)
spellCount++;
}
SetCriteriaProgress(achievementCriteria, spellCount, referencePlayer);
break;
}
case ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL:
SetCriteriaProgress(achievementCriteria, referencePlayer->GetUInt32Value(PLAYER_FIELD_LIFETIME_HONORABLE_KILLS), referencePlayer);
break;
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_GOLD_VALUE_OWNED:
SetCriteriaProgress(achievementCriteria, referencePlayer->GetMoney(), referencePlayer, PROGRESS_HIGHEST);
break;
case ACHIEVEMENT_CRITERIA_TYPE_EARN_ACHIEVEMENT_POINTS:
if (!miscValue1)
SetCriteriaProgress(achievementCriteria, _achievementPoints, referencePlayer, PROGRESS_SET);
else
SetCriteriaProgress(achievementCriteria, miscValue1, referencePlayer, PROGRESS_ACCUMULATE);
break;
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_TEAM_RATING:
{
uint32 reqTeamType = achievementCriteria->highest_team_rating.teamtype;
if (miscValue1)
{
if (miscValue2 != reqTeamType)
continue;
SetCriteriaProgress(achievementCriteria, miscValue1, referencePlayer, PROGRESS_HIGHEST);
}
else // login case
{
for (uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot)
{
uint32 teamId = referencePlayer->GetArenaTeamId(arena_slot);
if (!teamId)
continue;
ArenaTeam* team = sArenaTeamMgr->GetArenaTeamById(teamId);
if (!team || team->GetType() != reqTeamType)
continue;
SetCriteriaProgress(achievementCriteria, team->GetStats().Rating, referencePlayer, PROGRESS_HIGHEST);
break;
}
}
break;
}
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_PERSONAL_RATING:
{
uint32 reqTeamType = achievementCriteria->highest_personal_rating.teamtype;
if (miscValue1)
{
if (miscValue2 != reqTeamType)
continue;
SetCriteriaProgress(achievementCriteria, miscValue1, referencePlayer, PROGRESS_HIGHEST);
}
else // login case
{
for (uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot)
{
uint32 teamId = referencePlayer->GetArenaTeamId(arena_slot);
if (!teamId)
continue;
ArenaTeam* team = sArenaTeamMgr->GetArenaTeamById(teamId);
if (!team || team->GetType() != reqTeamType)
continue;
if (ArenaTeamMember const* member = team->GetMember(referencePlayer->GetGUID()))
{
SetCriteriaProgress(achievementCriteria, member->PersonalRating, referencePlayer, PROGRESS_HIGHEST);
break;
}
}
}
break;
}
case ACHIEVEMENT_CRITERIA_TYPE_REACH_GUILD_LEVEL:
SetCriteriaProgress(achievementCriteria, miscValue1, referencePlayer);
break;
// FIXME: not triggered in code as result, need to implement
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_RAID:
case ACHIEVEMENT_CRITERIA_TYPE_PLAY_ARENA:
case ACHIEVEMENT_CRITERIA_TYPE_OWN_RANK:
case ACHIEVEMENT_CRITERIA_TYPE_EARNED_PVP_TITLE:
case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE_TYPE:
case ACHIEVEMENT_CRITERIA_TYPE_SPENT_GOLD_GUILD_REPAIRS:
case ACHIEVEMENT_CRITERIA_TYPE_CRAFT_ITEMS_GUILD:
case ACHIEVEMENT_CRITERIA_TYPE_CATCH_FROM_POOL:
case ACHIEVEMENT_CRITERIA_TYPE_BUY_GUILD_BANK_SLOTS:
case ACHIEVEMENT_CRITERIA_TYPE_EARN_GUILD_ACHIEVEMENT_POINTS:
case ACHIEVEMENT_CRITERIA_TYPE_WIN_RATED_BATTLEGROUND:
case ACHIEVEMENT_CRITERIA_TYPE_REACH_BG_RATING:
case ACHIEVEMENT_CRITERIA_TYPE_BUY_GUILD_TABARD:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_GUILD:
case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILLS_GUILD:
case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE_TYPE_GUILD:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_ARCHAEOLOGY_PROJECTS:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_GUILD_CHALLENGE_TYPE:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_GUILD_CHALLENGE:
break; // Not implemented yet :(
}
if (IsCompletedCriteria(achievementCriteria, achievement))
CompletedCriteriaFor(achievement, referencePlayer);
// check again the completeness for SUMM and REQ COUNT achievements,
// as they don't depend on the completed criteria but on the sum of the progress of each individual criteria
if (achievement->flags & ACHIEVEMENT_FLAG_SUMM)
if (IsCompletedAchievement(achievement))
CompletedAchievement(achievement, referencePlayer);
if (AchievementEntryList const* achRefList = sAchievementMgr->GetAchievementByReferencedId(achievement->ID))
for (AchievementEntryList::const_iterator itr = achRefList->begin(); itr != achRefList->end(); ++itr)
if (IsCompletedAchievement(*itr))
CompletedAchievement(*itr, referencePlayer);
}
}
template<class T>
bool AchievementMgr<T>::IsCompletedCriteria(AchievementCriteriaEntry const* achievementCriteria, AchievementEntry const* achievement)
{
if (!achievement)
return false;
// counter can never complete
if (achievement->flags & ACHIEVEMENT_FLAG_COUNTER)
return false;
if (achievement->flags & (ACHIEVEMENT_FLAG_REALM_FIRST_REACH | ACHIEVEMENT_FLAG_REALM_FIRST_KILL))
{
// someone on this realm has already completed that achievement
if (sAchievementMgr->IsRealmCompleted(achievement))
return false;
}
CriteriaProgress const* progress = GetCriteriaProgress(achievementCriteria);
if (!progress)
return false;
switch (AchievementCriteriaTypes(achievementCriteria->type))
{
case ACHIEVEMENT_CRITERIA_TYPE_WIN_BG:
return progress->counter >= achievementCriteria->win_bg.winCount;
case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE:
return progress->counter >= achievementCriteria->kill_creature.creatureCount;
case ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL:
case ACHIEVEMENT_CRITERIA_TYPE_REACH_GUILD_LEVEL:
return progress->counter >= achievementCriteria->reach_level.level;
case ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL:
return progress->counter >= achievementCriteria->reach_skill_level.skillLevel;
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_ACHIEVEMENT:
return progress->counter >= 1;
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT:
return progress->counter >= achievementCriteria->complete_quest_count.totalQuestCount;
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST_DAILY:
return progress->counter >= achievementCriteria->complete_daily_quest_daily.numberOfDays;
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE:
return progress->counter >= achievementCriteria->complete_quests_in_zone.questCount;
case ACHIEVEMENT_CRITERIA_TYPE_DAMAGE_DONE:
case ACHIEVEMENT_CRITERIA_TYPE_HEALING_DONE:
return progress->counter >= achievementCriteria->healing_done.count;
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST:
return progress->counter >= achievementCriteria->complete_daily_quest.questCount;
case ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING:
return progress->counter >= achievementCriteria->fall_without_dying.fallHeight;
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST:
return progress->counter >= 1;
case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET:
case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2:
return progress->counter >= achievementCriteria->be_spell_target.spellCount;
case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL:
case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL2:
return progress->counter >= achievementCriteria->cast_spell.castCount;
case ACHIEVEMENT_CRITERIA_TYPE_BG_OBJECTIVE_CAPTURE:
return progress->counter >= achievementCriteria->bg_objective.completeCount;
case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL_AT_AREA:
return progress->counter >= achievementCriteria->honorable_kill_at_area.killCount;
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL:
return progress->counter >= 1;
case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL:
case ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL:
return progress->counter >= achievementCriteria->honorable_kill.killCount;
case ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM:
return progress->counter >= achievementCriteria->own_item.itemCount;
case ACHIEVEMENT_CRITERIA_TYPE_WIN_RATED_ARENA:
return progress->counter >= achievementCriteria->win_rated_arena.count;
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_PERSONAL_RATING:
return progress->counter >= achievementCriteria->highest_personal_rating.PersonalRating;
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL:
return progress->counter >= (achievementCriteria->learn_skill_level.skillLevel * 75);
case ACHIEVEMENT_CRITERIA_TYPE_USE_ITEM:
return progress->counter >= achievementCriteria->use_item.itemCount;
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_ITEM:
return progress->counter >= achievementCriteria->loot_item.itemCount;
case ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA:
return progress->counter >= 1;
case ACHIEVEMENT_CRITERIA_TYPE_BUY_BANK_SLOT:
return progress->counter >= achievementCriteria->buy_bank_slot.numberOfSlots;
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION:
return progress->counter >= achievementCriteria->gain_reputation.reputationAmount;
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION:
return progress->counter >= achievementCriteria->gain_exalted_reputation.numberOfExaltedFactions;
case ACHIEVEMENT_CRITERIA_TYPE_VISIT_BARBER_SHOP:
return progress->counter >= achievementCriteria->visit_barber.numberOfVisits;
case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM:
return progress->counter >= achievementCriteria->equip_epic_item.count;
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED_ON_LOOT:
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_GREED_ON_LOOT:
return progress->counter >= achievementCriteria->roll_greed_on_loot.count;
case ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS:
return progress->counter >= achievementCriteria->hk_class.count;
case ACHIEVEMENT_CRITERIA_TYPE_HK_RACE:
return progress->counter >= achievementCriteria->hk_race.count;
case ACHIEVEMENT_CRITERIA_TYPE_DO_EMOTE:
return progress->counter >= achievementCriteria->do_emote.count;
case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM:
return progress->counter >= achievementCriteria->equip_item.count;
case ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD:
return progress->counter >= achievementCriteria->quest_reward_money.goldInCopper;
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_MONEY:
return progress->counter >= achievementCriteria->loot_money.goldInCopper;
case ACHIEVEMENT_CRITERIA_TYPE_USE_GAMEOBJECT:
return progress->counter >= achievementCriteria->use_gameobject.useCount;
case ACHIEVEMENT_CRITERIA_TYPE_SPECIAL_PVP_KILL:
return progress->counter >= achievementCriteria->special_pvp_kill.killCount;
case ACHIEVEMENT_CRITERIA_TYPE_FISH_IN_GAMEOBJECT:
return progress->counter >= achievementCriteria->fish_in_gameobject.lootCount;
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS:
return progress->counter >= achievementCriteria->learn_skillline_spell.spellCount;
case ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL:
return progress->counter >= achievementCriteria->win_duel.duelCount;
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_TYPE:
return progress->counter >= achievementCriteria->loot_type.lootTypeCount;
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE:
return progress->counter >= achievementCriteria->learn_skill_line.spellCount;
case ACHIEVEMENT_CRITERIA_TYPE_EARN_ACHIEVEMENT_POINTS:
return progress->counter >= 9000;
case ACHIEVEMENT_CRITERIA_TYPE_USE_LFD_TO_GROUP_WITH_PLAYERS:
return progress->counter >= achievementCriteria->use_lfg.dungeonsComplete;
case ACHIEVEMENT_CRITERIA_TYPE_GET_KILLING_BLOWS:
return progress->counter >= achievementCriteria->get_killing_blow.killCount;
case ACHIEVEMENT_CRITERIA_TYPE_CURRENCY:
return progress->counter >= achievementCriteria->currencyGain.count;
case ACHIEVEMENT_CRITERIA_TYPE_WIN_ARENA:
return achievementCriteria->win_arena.count && progress->counter >= achievementCriteria->win_arena.count;
// handle all statistic-only criteria here
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_BATTLEGROUND:
case ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP:
case ACHIEVEMENT_CRITERIA_TYPE_DEATH:
case ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON:
case ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_CREATURE:
case ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_PLAYER:
case ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM:
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_TEAM_RATING:
case ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_VENDORS:
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS:
case ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS:
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_AT_BARBER:
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_MAIL:
case ACHIEVEMENT_CRITERIA_TYPE_LOSE_DUEL:
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_EARNED_BY_AUCTIONS:
case ACHIEVEMENT_CRITERIA_TYPE_CREATE_AUCTION:
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_AUCTION_BID:
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_AUCTION_SOLD:
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_GOLD_VALUE_OWNED:
case ACHIEVEMENT_CRITERIA_TYPE_WON_AUCTIONS:
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_REVERED_REPUTATION:
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_HONORED_REPUTATION:
case ACHIEVEMENT_CRITERIA_TYPE_KNOWN_FACTIONS:
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_EPIC_ITEM:
case ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM:
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED:
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_GREED:
case ACHIEVEMENT_CRITERIA_TYPE_QUEST_ABANDONED:
case ACHIEVEMENT_CRITERIA_TYPE_FLIGHT_PATHS_TAKEN:
case ACHIEVEMENT_CRITERIA_TYPE_ACCEPTED_SUMMONINGS:
default:
break;
}
return false;
}
template<class T>
void AchievementMgr<T>::CompletedCriteriaFor(AchievementEntry const* achievement, Player* referencePlayer)
{
// counter can never complete
if (achievement->flags & ACHIEVEMENT_FLAG_COUNTER)
return;
// already completed and stored
if (HasAchieved(achievement->ID))
return;
if (IsCompletedAchievement(achievement))
CompletedAchievement(achievement, referencePlayer);
}
template<class T>
bool AchievementMgr<T>::IsCompletedAchievement(AchievementEntry const* entry)
{
// counter can never complete
if (entry->flags & ACHIEVEMENT_FLAG_COUNTER)
return false;
// for achievement with referenced achievement criterias get from referenced and counter from self
uint32 achievementForTestId = entry->refAchievement ? entry->refAchievement : entry->ID;
uint32 achievementForTestCount = entry->count;
AchievementCriteriaEntryList const* cList = sAchievementMgr->GetAchievementCriteriaByAchievement(achievementForTestId);
if (!cList)
return false;
uint64 count = 0;
// For SUMM achievements, we have to count the progress of each criteria of the achievement.
// Oddly, the target count is NOT contained in the achievement, but in each individual criteria
if (entry->flags & ACHIEVEMENT_FLAG_SUMM)
{
for (AchievementCriteriaEntryList::const_iterator itr = cList->begin(); itr != cList->end(); ++itr)
{
AchievementCriteriaEntry const* criteria = *itr;
CriteriaProgress const* progress = GetCriteriaProgress(criteria);
if (!progress)
continue;
count += progress->counter;
// for counters, field4 contains the main count requirement
if (count >= criteria->raw.count)
return true;
}
return false;
}
// Default case - need complete all or
bool completed_all = true;
for (AchievementCriteriaEntryList::const_iterator itr = cList->begin(); itr != cList->end(); ++itr)
{
AchievementCriteriaEntry const* criteria = *itr;
bool completed = IsCompletedCriteria(criteria, entry);
// found an uncompleted criteria, but DONT return false yet - there might be a completed criteria with ACHIEVEMENT_CRITERIA_COMPLETE_FLAG_ALL
if (completed)
++count;
else
completed_all = false;
// completed as have req. count of completed criterias
if (achievementForTestCount > 0 && achievementForTestCount <= count)
return true;
}
// all criterias completed requirement
if (completed_all && achievementForTestCount == 0)
return true;
return false;
}
template<class T>
CriteriaProgress* AchievementMgr<T>::GetCriteriaProgress(AchievementCriteriaEntry const* entry)
{
CriteriaProgressMap::iterator iter = m_criteriaProgress.find(entry->ID);
if (iter == m_criteriaProgress.end())
return NULL;
return &(iter->second);
}
template<class T>
void AchievementMgr<T>::SetCriteriaProgress(AchievementCriteriaEntry const* entry, uint64 changeValue, Player* referencePlayer, ProgressType ptype)
{
// Don't allow to cheat - doing timed achievements without timer active
TimedAchievementMap::iterator timedIter = m_timedAchievements.find(entry->ID);
if (entry->timeLimit && timedIter == m_timedAchievements.end())
return;
TC_LOG_DEBUG(LOG_FILTER_ACHIEVEMENTSYS, "SetCriteriaProgress(%u, " UI64FMTD ") for (%s GUID: %u)",
entry->ID, changeValue, GetLogNameForGuid(GetOwner()->GetGUID()), GUID_LOPART(GetOwner()->GetGUID()));
CriteriaProgress* progress = GetCriteriaProgress(entry);
if (!progress)
{
// not create record for 0 counter but allow it for timed achievements
// we will need to send 0 progress to client to start the timer
if (changeValue == 0 && !entry->timeLimit)
return;
progress = &m_criteriaProgress[entry->ID];
progress->counter = changeValue;
}
else
{
uint64 newValue = 0;
switch (ptype)
{
case PROGRESS_SET:
newValue = changeValue;
break;
case PROGRESS_ACCUMULATE:
{
// avoid overflow
uint64 max_value = std::numeric_limits<uint64>::max();
newValue = max_value - progress->counter > changeValue ? progress->counter + changeValue : max_value;
break;
}
case PROGRESS_HIGHEST:
newValue = progress->counter < changeValue ? changeValue : progress->counter;
break;
}
// not update (not mark as changed) if counter will have same value
if (progress->counter == newValue && !entry->timeLimit)
return;
progress->counter = newValue;
}
progress->changed = true;
progress->date = time(NULL); // set the date to the latest update.
AchievementEntry const* achievement = sAchievementMgr->GetAchievement(entry->achievement);
uint32 timeElapsed = 0;
bool criteriaComplete = IsCompletedCriteria(entry, achievement);
if (entry->timeLimit)
{
// Client expects this in packet
timeElapsed = entry->timeLimit - (timedIter->second/IN_MILLISECONDS);
// Remove the timer, we wont need it anymore
if (criteriaComplete)
m_timedAchievements.erase(timedIter);
}
if (criteriaComplete && achievement->flags & ACHIEVEMENT_FLAG_SHOW_CRITERIA_MEMBERS && !progress->CompletedGUID)
progress->CompletedGUID = referencePlayer->GetGUID();
SendCriteriaUpdate(entry, progress, timeElapsed, criteriaComplete);
}
template<class T>
void AchievementMgr<T>::UpdateTimedAchievements(uint32 timeDiff)
{
if (!m_timedAchievements.empty())
{
for (TimedAchievementMap::iterator itr = m_timedAchievements.begin(); itr != m_timedAchievements.end();)
{
// Time is up, remove timer and reset progress
if (itr->second <= timeDiff)
{
AchievementCriteriaEntry const* entry = sAchievementMgr->GetAchievementCriteria(itr->first);
RemoveCriteriaProgress(entry);
m_timedAchievements.erase(itr++);
}
else
{
itr->second -= timeDiff;
++itr;
}
}
}
}
template<class T>
void AchievementMgr<T>::StartTimedAchievement(AchievementCriteriaTimedTypes /*type*/, uint32 /*entry*/, uint32 /*timeLost = 0*/)
{
}
template<>
void AchievementMgr<Player>::StartTimedAchievement(AchievementCriteriaTimedTypes type, uint32 entry, uint32 timeLost /* = 0 */)
{
AchievementCriteriaEntryList const& achievementCriteriaList = sAchievementMgr->GetTimedAchievementCriteriaByType(type);
for (AchievementCriteriaEntryList::const_iterator i = achievementCriteriaList.begin(); i != achievementCriteriaList.end(); ++i)
{
if ((*i)->timedCriteriaMiscId != entry)
continue;
AchievementEntry const* achievement = sAchievementMgr->GetAchievement((*i)->achievement);
if (m_timedAchievements.find((*i)->ID) == m_timedAchievements.end() && !IsCompletedCriteria(*i, achievement))
{
// Start the timer
if ((*i)->timeLimit * IN_MILLISECONDS > timeLost)
{
m_timedAchievements[(*i)->ID] = (*i)->timeLimit * IN_MILLISECONDS - timeLost;
// and at client too
SetCriteriaProgress(*i, 0, GetOwner(), PROGRESS_SET);
}
}
}
}
template<class T>
void AchievementMgr<T>::RemoveTimedAchievement(AchievementCriteriaTimedTypes type, uint32 entry)
{
AchievementCriteriaEntryList const& achievementCriteriaList = sAchievementMgr->GetTimedAchievementCriteriaByType(type);
for (AchievementCriteriaEntryList::const_iterator i = achievementCriteriaList.begin(); i != achievementCriteriaList.end(); ++i)
{
if ((*i)->timedCriteriaMiscId != entry)
continue;
TimedAchievementMap::iterator timedIter = m_timedAchievements.find((*i)->ID);
// We don't have timer for this achievement
if (timedIter == m_timedAchievements.end())
continue;
// remove progress
RemoveCriteriaProgress(*i);
// Remove the timer
m_timedAchievements.erase(timedIter);
}
}
template<>
void AchievementMgr<Player>::CompletedAchievement(AchievementEntry const* achievement, Player* referencePlayer)
{
// disable for gamemasters with GM-mode enabled
if (GetOwner()->IsGameMaster())
return;
if (achievement->flags & ACHIEVEMENT_FLAG_COUNTER || HasAchieved(achievement->ID))
return;
if (achievement->flags & ACHIEVEMENT_FLAG_SHOW_IN_GUILD_NEWS)
if (Guild* guild = referencePlayer->GetGuild())
guild->AddGuildNews(GUILD_NEWS_PLAYER_ACHIEVEMENT, referencePlayer->GetGUID(), achievement->flags & ACHIEVEMENT_FLAG_SHOW_IN_GUILD_HEADER, achievement->ID);
if (!GetOwner()->GetSession()->PlayerLoading())
SendAchievementEarned(achievement);
TC_LOG_INFO(LOG_FILTER_ACHIEVEMENTSYS, "AchievementMgr::CompletedAchievement(%u). Player: %s (%u)",
achievement->ID, GetOwner()->GetName().c_str(), GetOwner()->GetGUIDLow());
CompletedAchievementData& ca = m_completedAchievements[achievement->ID];
ca.date = time(NULL);
ca.changed = true;
// don't insert for ACHIEVEMENT_FLAG_REALM_FIRST_KILL since otherwise only the first group member would reach that achievement
/// @todo where do set this instead?
if (!(achievement->flags & ACHIEVEMENT_FLAG_REALM_FIRST_KILL))
sAchievementMgr->SetRealmCompleted(achievement);
_achievementPoints += achievement->points;
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_ACHIEVEMENT, 0, 0, 0, NULL, referencePlayer);
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EARN_ACHIEVEMENT_POINTS, achievement->points, 0, 0, NULL, referencePlayer);
// reward items and titles if any
AchievementReward const* reward = sAchievementMgr->GetAchievementReward(achievement);
// no rewards
if (!reward)
return;
// titles
//! Currently there's only one achievement that deals with gender-specific titles.
//! Since no common attributes were found, (not even in titleRewardFlags field)
//! we explicitly check by ID. Maybe in the future we could move the achievement_reward
//! condition fields to the condition system.
if (uint32 titleId = reward->titleId[achievement->ID == 1793 ? GetOwner()->getGender() : (GetOwner()->GetTeam() == ALLIANCE ? 0 : 1)])
if (CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(titleId))
GetOwner()->SetTitle(titleEntry);
// mail
if (reward->sender)
{
Item* item = reward->itemId ? Item::CreateItem(reward->itemId, 1, GetOwner()) : NULL;
int loc_idx = GetOwner()->GetSession()->GetSessionDbLocaleIndex();
// subject and text
std::string subject = reward->subject;
std::string text = reward->text;
if (loc_idx >= 0)
{
if (AchievementRewardLocale const* loc = sAchievementMgr->GetAchievementRewardLocale(achievement))
{
ObjectMgr::GetLocaleString(loc->subject, loc_idx, subject);
ObjectMgr::GetLocaleString(loc->text, loc_idx, text);
}
}
MailDraft draft(subject, text);
SQLTransaction trans = CharacterDatabase.BeginTransaction();
if (item)
{
// save new item before send
item->SaveToDB(trans); // save for prevent lost at next mail load, if send fail then item will deleted
// item
draft.AddItem(item);
}
draft.SendMailTo(trans, GetOwner(), MailSender(MAIL_CREATURE, reward->sender));
CharacterDatabase.CommitTransaction(trans);
}
}
template<>
void AchievementMgr<Guild>::CompletedAchievement(AchievementEntry const* achievement, Player* referencePlayer)
{
TC_LOG_DEBUG(LOG_FILTER_ACHIEVEMENTSYS, "AchievementMgr<Guild>::CompletedAchievement(%u)", achievement->ID);
if (achievement->flags & ACHIEVEMENT_FLAG_COUNTER || HasAchieved(achievement->ID))
return;
if (achievement->flags & ACHIEVEMENT_FLAG_SHOW_IN_GUILD_NEWS)
if (Guild* guild = referencePlayer->GetGuild())
guild->AddGuildNews(GUILD_NEWS_GUILD_ACHIEVEMENT, 0, achievement->flags & ACHIEVEMENT_FLAG_SHOW_IN_GUILD_HEADER, achievement->ID);
SendAchievementEarned(achievement);
CompletedAchievementData& ca = m_completedAchievements[achievement->ID];
ca.date = time(NULL);
ca.changed = true;
if (achievement->flags & ACHIEVEMENT_FLAG_SHOW_GUILD_MEMBERS)
{
if (referencePlayer->GetGuildId() == GetOwner()->GetId())
ca.guids.insert(referencePlayer->GetGUID());
if (Group const* group = referencePlayer->GetGroup())
for (GroupReference const* ref = group->GetFirstMember(); ref != NULL; ref = ref->next())
if (Player const* groupMember = ref->GetSource())
if (groupMember->GetGuildId() == GetOwner()->GetId())
ca.guids.insert(groupMember->GetGUID());
}
sAchievementMgr->SetRealmCompleted(achievement);
_achievementPoints += achievement->points;
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_ACHIEVEMENT, 0, 0, 0, NULL, referencePlayer);
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EARN_ACHIEVEMENT_POINTS, achievement->points, 0, 0, NULL, referencePlayer);
}
struct VisibleAchievementPred
{
bool operator()(CompletedAchievementMap::value_type const& val)
{
AchievementEntry const* achievement = sAchievementMgr->GetAchievement(val.first);
return achievement && !(achievement->flags & ACHIEVEMENT_FLAG_HIDDEN);
}
};
template<class T>
void AchievementMgr<T>::SendAllAchievementData(Player* /*receiver*/) const
{
VisibleAchievementPred isVisible;
size_t numCriteria = m_criteriaProgress.size();
size_t numAchievements = std::count_if(m_completedAchievements.begin(), m_completedAchievements.end(), isVisible);
ByteBuffer criteriaData(numCriteria * (4 + 4 + 4 + 4 + 8 + 8));
ObjectGuid guid = GetOwner()->GetGUID();
ObjectGuid counter;
WorldPacket data(SMSG_ALL_ACHIEVEMENT_DATA, 4 + numAchievements * (4 + 4) + 4 + numCriteria * (4 + 4 + 4 + 4 + 8 + 8));
data.WriteBits(numCriteria, 21);
for (CriteriaProgressMap::const_iterator itr = m_criteriaProgress.begin(); itr != m_criteriaProgress.end(); ++itr)
{
counter = itr->second.counter;
data.WriteBit(guid[4]);
data.WriteBit(counter[3]);
data.WriteBit(guid[5]);
data.WriteBit(counter[0]);
data.WriteBit(counter[6]);
data.WriteBit(guid[3]);
data.WriteBit(guid[0]);
data.WriteBit(counter[4]);
data.WriteBit(guid[2]);
data.WriteBit(counter[7]);
data.WriteBit(guid[7]);
data.WriteBits(0u, 2);
data.WriteBit(guid[6]);
data.WriteBit(counter[2]);
data.WriteBit(counter[1]);
data.WriteBit(counter[5]);
data.WriteBit(guid[1]);
criteriaData.WriteByteSeq(guid[3]);
criteriaData.WriteByteSeq(counter[5]);
criteriaData.WriteByteSeq(counter[6]);
criteriaData.WriteByteSeq(guid[4]);
criteriaData.WriteByteSeq(guid[6]);
criteriaData.WriteByteSeq(counter[2]);
criteriaData << uint32(0); // timer 2
criteriaData.WriteByteSeq(guid[2]);
criteriaData << uint32(itr->first); // criteria id
criteriaData.WriteByteSeq(guid[5]);
criteriaData.WriteByteSeq(counter[0]);
criteriaData.WriteByteSeq(counter[3]);
criteriaData.WriteByteSeq(counter[1]);
criteriaData.WriteByteSeq(counter[4]);
criteriaData.WriteByteSeq(guid[0]);
criteriaData.WriteByteSeq(guid[7]);
criteriaData.WriteByteSeq(counter[7]);
criteriaData << uint32(0); // timer 1
criteriaData.AppendPackedTime(itr->second.date); // criteria date
criteriaData.WriteByteSeq(guid[1]);
}
data.WriteBits(numAchievements, 23);
data.FlushBits();
data.append(criteriaData);
for (CompletedAchievementMap::const_iterator itr = m_completedAchievements.begin(); itr != m_completedAchievements.end(); ++itr)
{
if (!isVisible(*itr))
continue;
data << uint32(itr->first);
data.AppendPackedTime(itr->second.date);
}
SendPacket(&data);
}
template<>
void AchievementMgr<Guild>::SendAllAchievementData(Player* receiver) const
{
VisibleAchievementPred isVisible;
WorldPacket data(SMSG_GUILD_ACHIEVEMENT_DATA, m_completedAchievements.size() * (4 + 4) + 3);
data.WriteBits(std::count_if(m_completedAchievements.begin(), m_completedAchievements.end(), isVisible), 23);
for (CompletedAchievementMap::const_iterator itr = m_completedAchievements.begin(); itr != m_completedAchievements.end(); ++itr)
{
if (!isVisible(*itr))
continue;
data.AppendPackedTime(itr->second.date);
data << uint32(itr->first);
}
receiver->GetSession()->SendPacket(&data);
}
template<>
void AchievementMgr<Player>::SendAchievementInfo(Player* receiver, uint32 /*achievementId = 0 */) const
{
ObjectGuid guid = GetOwner()->GetGUID();
ObjectGuid counter;
VisibleAchievementPred isVisible;
size_t numCriteria = m_criteriaProgress.size();
size_t numAchievements = std::count_if(m_completedAchievements.begin(), m_completedAchievements.end(), isVisible);
ByteBuffer criteriaData(numCriteria * 16);
WorldPacket data(SMSG_RESPOND_INSPECT_ACHIEVEMENTS, 1 + 8 + 3 + 3 + numAchievements * (4 + 4) + numCriteria * (0));
data.WriteBit(guid[7]);
data.WriteBit(guid[4]);
data.WriteBit(guid[1]);
data.WriteBits(numAchievements, 23);
data.WriteBit(guid[0]);
data.WriteBit(guid[3]);
data.WriteBits(numCriteria, 21);
data.WriteBit(guid[2]);
for (CriteriaProgressMap::const_iterator itr = m_criteriaProgress.begin(); itr != m_criteriaProgress.end(); ++itr)
{
counter = itr->second.counter;
data.WriteBit(counter[5]);
data.WriteBit(counter[3]);
data.WriteBit(guid[1]);
data.WriteBit(guid[4]);
data.WriteBit(guid[2]);
data.WriteBit(counter[6]);
data.WriteBit(guid[0]);
data.WriteBit(counter[4]);
data.WriteBit(counter[1]);
data.WriteBit(counter[2]);
data.WriteBit(guid[3]);
data.WriteBit(guid[7]);
data.WriteBits(0, 2); // criteria progress flags
data.WriteBit(counter[0]);
data.WriteBit(guid[5]);
data.WriteBit(guid[6]);
data.WriteBit(counter[7]);
criteriaData.WriteByteSeq(guid[3]);
criteriaData.WriteByteSeq(counter[4]);
criteriaData << uint32(0); // timer 1
criteriaData.WriteByteSeq(guid[1]);
criteriaData.AppendPackedTime(itr->second.date);
criteriaData.WriteByteSeq(counter[3]);
criteriaData.WriteByteSeq(counter[7]);
criteriaData.WriteByteSeq(guid[5]);
criteriaData.WriteByteSeq(counter[0]);
criteriaData.WriteByteSeq(guid[4]);
criteriaData.WriteByteSeq(guid[2]);
criteriaData.WriteByteSeq(guid[6]);
criteriaData.WriteByteSeq(guid[7]);
criteriaData.WriteByteSeq(counter[6]);
criteriaData << uint32(itr->first);
criteriaData << uint32(0); // timer 2
criteriaData.WriteByteSeq(counter[1]);
criteriaData.WriteByteSeq(counter[5]);
criteriaData.WriteByteSeq(guid[0]);
criteriaData.WriteByteSeq(counter[2]);
}
data.WriteBit(guid[6]);
data.WriteBit(guid[5]);
data.FlushBits();
data.append(criteriaData);
data.WriteByteSeq(guid[1]);
data.WriteByteSeq(guid[6]);
data.WriteByteSeq(guid[3]);
data.WriteByteSeq(guid[0]);
data.WriteByteSeq(guid[2]);
for (CompletedAchievementMap::const_iterator itr = m_completedAchievements.begin(); itr != m_completedAchievements.end(); ++itr)
{
if (!isVisible(*itr))
continue;
data << uint32(itr->first);
data.AppendPackedTime(itr->second.date);
}
data.WriteByteSeq(guid[7]);
data.WriteByteSeq(guid[4]);
data.WriteByteSeq(guid[5]);
receiver->GetSession()->SendPacket(&data);
}
template<>
void AchievementMgr<Guild>::SendAchievementInfo(Player* receiver, uint32 achievementId /*= 0*/) const
{
//will send response to criteria progress request
AchievementCriteriaEntryList const* criteria = sAchievementMgr->GetAchievementCriteriaByAchievement(achievementId);
if (!criteria)
{
// send empty packet
WorldPacket data(SMSG_GUILD_CRITERIA_DATA, 3);
data.WriteBits(0, 21);
receiver->GetSession()->SendPacket(&data);
return;
}
ObjectGuid counter;
ObjectGuid guid;
uint32 numCriteria = 0;
ByteBuffer criteriaData(criteria->size() * (8 + 8 + 4 + 4 + 4));
ByteBuffer criteriaBits(criteria->size() * (8 + 8) / 8);
for (AchievementCriteriaEntryList::const_iterator itr = criteria->begin(); itr != criteria->end(); ++itr)
{
uint32 criteriaId = (*itr)->ID;
CriteriaProgressMap::const_iterator progress = m_criteriaProgress.find(criteriaId);
if (progress == m_criteriaProgress.end())
continue;
++numCriteria;
}
criteriaBits.WriteBits(numCriteria, 21);
for (AchievementCriteriaEntryList::const_iterator itr = criteria->begin(); itr != criteria->end(); ++itr)
{
uint32 criteriaId = (*itr)->ID;
CriteriaProgressMap::const_iterator progress = m_criteriaProgress.find(criteriaId);
if (progress == m_criteriaProgress.end())
continue;
counter = progress->second.counter;
guid = progress->second.CompletedGUID;
criteriaBits.WriteBit(counter[4]);
criteriaBits.WriteBit(counter[1]);
criteriaBits.WriteBit(guid[2]);
criteriaBits.WriteBit(counter[3]);
criteriaBits.WriteBit(guid[1]);
criteriaBits.WriteBit(counter[5]);
criteriaBits.WriteBit(counter[0]);
criteriaBits.WriteBit(guid[3]);
criteriaBits.WriteBit(counter[2]);
criteriaBits.WriteBit(guid[7]);
criteriaBits.WriteBit(guid[5]);
criteriaBits.WriteBit(guid[0]);
criteriaBits.WriteBit(counter[6]);
criteriaBits.WriteBit(guid[6]);
criteriaBits.WriteBit(counter[7]);
criteriaBits.WriteBit(guid[4]);
criteriaData.WriteByteSeq(guid[5]);
criteriaData << uint32(progress->second.date); // unknown date
criteriaData.WriteByteSeq(counter[3]);
criteriaData.WriteByteSeq(counter[7]);
criteriaData << uint32(progress->second.date); // unknown date
criteriaData.WriteByteSeq(counter[6]);
criteriaData.WriteByteSeq(guid[4]);
criteriaData.WriteByteSeq(guid[1]);
criteriaData.WriteByteSeq(counter[4]);
criteriaData.WriteByteSeq(guid[3]);
criteriaData.WriteByteSeq(counter[0]);
criteriaData.WriteByteSeq(guid[2]);
criteriaData.WriteByteSeq(counter[1]);
criteriaData.WriteByteSeq(guid[6]);
criteriaData << uint32(progress->second.date); // last update time (not packed!)
criteriaData << uint32(criteriaId);
criteriaData.WriteByteSeq(counter[5]);
criteriaData << uint32(0);
criteriaData.WriteByteSeq(guid[7]);
criteriaData.WriteByteSeq(counter[2]);
criteriaData.WriteByteSeq(guid[0]);
}
WorldPacket data(SMSG_GUILD_CRITERIA_DATA, criteriaBits.size() + criteriaData.size());
data.append(criteriaBits);
if (numCriteria)
data.append(criteriaData);
receiver->GetSession()->SendPacket(&data);
}
template<class T>
bool AchievementMgr<T>::HasAchieved(uint32 achievementId) const
{
return m_completedAchievements.find(achievementId) != m_completedAchievements.end();
}
template<class T>
bool AchievementMgr<T>::CanUpdateCriteria(AchievementCriteriaEntry const* criteria, AchievementEntry const* achievement, uint64 miscValue1, uint64 miscValue2, uint64 miscValue3, Unit const* unit, Player* referencePlayer)
{
if (DisableMgr::IsDisabledFor(DISABLE_TYPE_ACHIEVEMENT_CRITERIA, criteria->ID, NULL))
{
TC_LOG_TRACE(LOG_FILTER_ACHIEVEMENTSYS, "CanUpdateCriteria: %s (Id: %u Type %s) Disabled",
criteria->name, criteria->ID, AchievementGlobalMgr::GetCriteriaTypeString(criteria->type));
return false;
}
if (achievement->mapID != -1 && referencePlayer->GetMapId() != uint32(achievement->mapID))
{
TC_LOG_TRACE(LOG_FILTER_ACHIEVEMENTSYS, "CanUpdateCriteria: %s (Id: %u Type %s) Wrong map",
criteria->name, criteria->ID, AchievementGlobalMgr::GetCriteriaTypeString(criteria->type));
return false;
}
if ((achievement->requiredFaction == ACHIEVEMENT_FACTION_HORDE && referencePlayer->GetTeam() != HORDE) ||
(achievement->requiredFaction == ACHIEVEMENT_FACTION_ALLIANCE && referencePlayer->GetTeam() != ALLIANCE))
{
TC_LOG_TRACE(LOG_FILTER_ACHIEVEMENTSYS, "CanUpdateCriteria: %s (Id: %u Type %s) Wrong faction",
criteria->name, criteria->ID, AchievementGlobalMgr::GetCriteriaTypeString(criteria->type));
return false;
}
if (IsCompletedCriteria(criteria, achievement))
{
TC_LOG_TRACE(LOG_FILTER_ACHIEVEMENTSYS, "CanUpdateCriteria: %s (Id: %u Type %s) Is Completed",
criteria->name, criteria->ID, AchievementGlobalMgr::GetCriteriaTypeString(criteria->type));
return false;
}
if (!RequirementsSatisfied(criteria, miscValue1, miscValue2, miscValue3, unit, referencePlayer))
{
TC_LOG_TRACE(LOG_FILTER_ACHIEVEMENTSYS, "CanUpdateCriteria: %s (Id: %u Type %s) Requirements not satisfied",
criteria->name, criteria->ID, AchievementGlobalMgr::GetCriteriaTypeString(criteria->type));
return false;
}
if (!AdditionalRequirementsSatisfied(criteria, miscValue1, miscValue2, unit, referencePlayer))
{
TC_LOG_TRACE(LOG_FILTER_ACHIEVEMENTSYS, "CanUpdateCriteria: %s (Id: %u Type %s) Additional requirements not satisfied",
criteria->name, criteria->ID, AchievementGlobalMgr::GetCriteriaTypeString(criteria->type));
return false;
}
if (!ConditionsSatisfied(criteria, referencePlayer))
{
TC_LOG_TRACE(LOG_FILTER_ACHIEVEMENTSYS, "CanUpdateCriteria: %s (Id: %u Type %s) Conditions not satisfied",
criteria->name, criteria->ID, AchievementGlobalMgr::GetCriteriaTypeString(criteria->type));
return false;
}
return true;
}
template<class T>
bool AchievementMgr<T>::ConditionsSatisfied(AchievementCriteriaEntry const* criteria, Player* referencePlayer) const
{
for (uint32 i = 0; i < MAX_CRITERIA_REQUIREMENTS; ++i)
{
if (!criteria->additionalRequirements[i].additionalRequirement_type)
continue;
switch (criteria->additionalRequirements[i].additionalRequirement_type)
{
case ACHIEVEMENT_CRITERIA_CONDITION_BG_MAP:
if (referencePlayer->GetMapId() != criteria->additionalRequirements[i].additionalRequirement_value)
return false;
break;
case ACHIEVEMENT_CRITERIA_CONDITION_NOT_IN_GROUP:
if (referencePlayer->GetGroup())
return false;
break;
default:
break;
}
}
return true;
}
template<class T>
bool AchievementMgr<T>::RequirementsSatisfied(AchievementCriteriaEntry const* achievementCriteria, uint64 miscValue1, uint64 miscValue2, uint64 miscValue3, Unit const* unit, Player* referencePlayer) const
{
switch (AchievementCriteriaTypes(achievementCriteria->type))
{
case ACHIEVEMENT_CRITERIA_TYPE_ACCEPTED_SUMMONINGS:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST:
case ACHIEVEMENT_CRITERIA_TYPE_CREATE_AUCTION:
case ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING:
case ACHIEVEMENT_CRITERIA_TYPE_FLIGHT_PATHS_TAKEN:
case ACHIEVEMENT_CRITERIA_TYPE_GET_KILLING_BLOWS:
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_EARNED_BY_AUCTIONS:
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_AT_BARBER:
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_MAIL:
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS:
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING:
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_AUCTION_BID:
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_AUCTION_SOLD:
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEALING_RECEIVED:
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEAL_CASTED:
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_DEALT:
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_RECEIVED:
case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL:
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_MONEY:
case ACHIEVEMENT_CRITERIA_TYPE_LOSE_DUEL:
case ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD:
case ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_VENDORS:
case ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS:
case ACHIEVEMENT_CRITERIA_TYPE_QUEST_ABANDONED:
case ACHIEVEMENT_CRITERIA_TYPE_REACH_GUILD_LEVEL:
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_GREED:
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED:
case ACHIEVEMENT_CRITERIA_TYPE_SPECIAL_PVP_KILL:
case ACHIEVEMENT_CRITERIA_TYPE_TOTAL_DAMAGE_RECEIVED:
case ACHIEVEMENT_CRITERIA_TYPE_TOTAL_HEALING_RECEIVED:
case ACHIEVEMENT_CRITERIA_TYPE_USE_LFD_TO_GROUP_WITH_PLAYERS:
case ACHIEVEMENT_CRITERIA_TYPE_VISIT_BARBER_SHOP:
case ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL:
case ACHIEVEMENT_CRITERIA_TYPE_WIN_RATED_ARENA:
case ACHIEVEMENT_CRITERIA_TYPE_WON_AUCTIONS:
if (!miscValue1)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_BUY_BANK_SLOT:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST_DAILY:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT:
case ACHIEVEMENT_CRITERIA_TYPE_EARNED_PVP_TITLE:
case ACHIEVEMENT_CRITERIA_TYPE_EARN_ACHIEVEMENT_POINTS:
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION:
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_HONORED_REPUTATION:
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_REVERED_REPUTATION:
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_GOLD_VALUE_OWNED:
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_PERSONAL_RATING:
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_TEAM_RATING:
case ACHIEVEMENT_CRITERIA_TYPE_KNOWN_FACTIONS:
case ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL:
break;
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_ACHIEVEMENT:
if (m_completedAchievements.find(achievementCriteria->complete_achievement.linkedAchievement) == m_completedAchievements.end())
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_WIN_BG:
if (!miscValue1 || achievementCriteria->win_bg.bgMapID != referencePlayer->GetMapId())
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE:
if (!miscValue1 || achievementCriteria->kill_creature.creatureID != miscValue1)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL:
// update at loading or specific skill update
if (miscValue1 && miscValue1 != achievementCriteria->reach_skill_level.skillID)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL:
// update at loading or specific skill update
if (miscValue1 && miscValue1 != achievementCriteria->learn_skill_level.skillID)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE:
if (miscValue1 && miscValue1 != achievementCriteria->complete_quests_in_zone.zoneID)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_BATTLEGROUND:
if (!miscValue1 || referencePlayer->GetMapId() != achievementCriteria->complete_battleground.mapID)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP:
if (!miscValue1 || referencePlayer->GetMapId() != achievementCriteria->death_at_map.mapID)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_DEATH:
{
if (!miscValue1)
return false;
// skip wrong arena achievements, if not achievIdByArenaSlot then normal total death counter
bool notfit = false;
for (int j = 0; j < MAX_ARENA_SLOT; ++j)
{
if (achievIdByArenaSlot[j] == achievementCriteria->achievement)
{
Battleground* bg = referencePlayer->GetBattleground();
if (!bg || !bg->isArena() || ArenaTeam::GetSlotByType(bg->GetArenaType()) != j)
notfit = true;
break;
}
}
if (notfit)
return false;
break;
}
case ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON:
{
if (!miscValue1)
return false;
Map const* map = referencePlayer->IsInWorld() ? referencePlayer->GetMap() : sMapMgr->FindMap(referencePlayer->GetMapId(), referencePlayer->GetInstanceId());
if (!map || !map->IsDungeon())
return false;
// search case
bool found = false;
for (int j = 0; achievIdForDungeon[j][0]; ++j)
{
if (achievIdForDungeon[j][0] == achievementCriteria->achievement)
{
if (map->IsRaid())
{
// if raid accepted (ignore difficulty)
if (!achievIdForDungeon[j][2])
break; // for
}
else if (referencePlayer->GetDungeonDifficulty() == DUNGEON_DIFFICULTY_NORMAL)
{
// dungeon in normal mode accepted
if (!achievIdForDungeon[j][1])
break; // for
}
else
{
// dungeon in heroic mode accepted
if (!achievIdForDungeon[j][3])
break; // for
}
found = true;
break; // for
}
}
if (!found)
return false;
//FIXME: work only for instances where max == min for players
if (((InstanceMap*)map)->GetMaxPlayers() != achievementCriteria->death_in_dungeon.manLimit)
return false;
break;
}
case ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_CREATURE:
if (!miscValue1 || miscValue1 != achievementCriteria->killed_by_creature.creatureEntry)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_PLAYER:
if (!miscValue1 || !unit || unit->GetTypeId() != TYPEID_PLAYER)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM:
if (!miscValue1 || miscValue2 != achievementCriteria->death_from.type)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST:
{
// if miscValues != 0, it contains the questID.
if (miscValue1)
{
if (miscValue1 != achievementCriteria->complete_quest.questID)
return false;
}
else
{
// login case.
if (!referencePlayer->GetQuestRewardStatus(achievementCriteria->complete_quest.questID))
return false;
}
if (AchievementCriteriaDataSet const* data = sAchievementMgr->GetCriteriaDataSet(achievementCriteria))
if (!data->Meets(referencePlayer, unit))
return false;
break;
}
case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET:
case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2:
if (!miscValue1 || miscValue1 != achievementCriteria->be_spell_target.spellID)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL:
case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL2:
if (!miscValue1 || miscValue1 != achievementCriteria->cast_spell.spellID)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL:
if (miscValue1 && miscValue1 != achievementCriteria->learn_spell.spellID)
return false;
if (!referencePlayer->HasSpell(achievementCriteria->learn_spell.spellID))
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_TYPE:
// miscValue1 = itemId - miscValue2 = count of item loot
// miscValue3 = loot_type (note: 0 = LOOT_CORPSE and then it ignored)
if (!miscValue1 || !miscValue2 || !miscValue3 || miscValue3 != achievementCriteria->loot_type.lootType)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM:
if (miscValue1 && achievementCriteria->own_item.itemID != miscValue1)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_USE_ITEM:
if (!miscValue1 || achievementCriteria->use_item.itemID != miscValue1)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_ITEM:
if (!miscValue1 || miscValue1 != achievementCriteria->own_item.itemID)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA:
{
WorldMapOverlayEntry const* worldOverlayEntry = sWorldMapOverlayStore.LookupEntry(achievementCriteria->explore_area.areaReference);
if (!worldOverlayEntry)
break;
bool matchFound = false;
for (int j = 0; j < MAX_WORLD_MAP_OVERLAY_AREA_IDX; ++j)
{
uint32 area_id = worldOverlayEntry->areatableID[j];
if (!area_id) // array have 0 only in empty tail
break;
int32 exploreFlag = GetAreaFlagByAreaID(area_id);
if (exploreFlag < 0)
continue;
uint32 playerIndexOffset = uint32(exploreFlag) / 32;
uint32 mask = 1 << (uint32(exploreFlag) % 32);
if (referencePlayer->GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + playerIndexOffset) & mask)
{
matchFound = true;
break;
}
}
if (!matchFound)
return false;
break;
}
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION:
if (miscValue1 && miscValue1 != achievementCriteria->gain_reputation.factionID)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM:
// miscValue1 = itemid miscValue2 = itemSlot
if (!miscValue1 || miscValue2 != achievementCriteria->equip_epic_item.itemSlot)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED_ON_LOOT:
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_GREED_ON_LOOT:
{
// miscValue1 = itemid miscValue2 = diced value
if (!miscValue1 || miscValue2 != achievementCriteria->roll_greed_on_loot.rollValue)
return false;
ItemTemplate const* proto = sObjectMgr->GetItemTemplate(uint32(miscValue1));
if (!proto)
return false;
break;
}
case ACHIEVEMENT_CRITERIA_TYPE_DO_EMOTE:
if (!miscValue1 || miscValue1 != achievementCriteria->do_emote.emoteID)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_DAMAGE_DONE:
case ACHIEVEMENT_CRITERIA_TYPE_HEALING_DONE:
if (!miscValue1)
return false;
if (achievementCriteria->additionalRequirements[0].additionalRequirement_type == ACHIEVEMENT_CRITERIA_CONDITION_BG_MAP)
{
if (referencePlayer->GetMapId() != achievementCriteria->additionalRequirements[0].additionalRequirement_value)
return false;
// map specific case (BG in fact) expected player targeted damage/heal
if (!unit || unit->GetTypeId() != TYPEID_PLAYER)
return false;
}
break;
case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM:
// miscValue1 = item_id
if (!miscValue1 || miscValue1 != achievementCriteria->equip_item.itemID)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_USE_GAMEOBJECT:
if (!miscValue1 || miscValue1 != achievementCriteria->use_gameobject.goEntry)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_FISH_IN_GAMEOBJECT:
if (!miscValue1 || miscValue1 != achievementCriteria->fish_in_gameobject.goEntry)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS:
if (miscValue1 && miscValue1 != achievementCriteria->learn_skillline_spell.skillLine)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_EPIC_ITEM:
case ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM:
{
if (!miscValue1)
return false;
ItemTemplate const* proto = sObjectMgr->GetItemTemplate(uint32(miscValue1));
if (!proto || proto->Quality < ITEM_QUALITY_EPIC)
return false;
break;
}
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE:
if (miscValue1 && miscValue1 != achievementCriteria->learn_skill_line.skillLine)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS:
if (!miscValue1 || miscValue1 != achievementCriteria->hk_class.classID)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_HK_RACE:
if (!miscValue1 || miscValue1 != achievementCriteria->hk_race.raceID)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_BG_OBJECTIVE_CAPTURE:
if (!miscValue1 || miscValue1 != achievementCriteria->bg_objective.objectiveId)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL_AT_AREA:
if (!miscValue1 || miscValue1 != achievementCriteria->honorable_kill_at_area.areaID)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_CURRENCY:
if (!miscValue1 || !miscValue2 || int64(miscValue2) < 0
|| miscValue1 != achievementCriteria->currencyGain.currency)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_WIN_ARENA:
if (miscValue1 != achievementCriteria->win_arena.mapID)
return false;
break;
default:
break;
}
return true;
}
template<class T>
bool AchievementMgr<T>::AdditionalRequirementsSatisfied(AchievementCriteriaEntry const* criteria, uint64 miscValue1, uint64 /*miscValue2*/, Unit const* unit, Player* referencePlayer) const
{
for (uint8 i = 0; i < MAX_ADDITIONAL_CRITERIA_CONDITIONS; ++i)
{
uint32 reqType = criteria->additionalConditionType[i];
///@TODO Extract additionalConditionValue[2] column from an older dbc and store it in database
/// This column is not present in 4.3.4 Achievement_Criteria.dbc
/// so for now, just return as failed condition to prevent invalid memory access
if (i == 2 && reqType)
return false;
uint32 reqValue = criteria->additionalConditionValue[i];
switch (AchievementCriteriaAdditionalCondition(reqType))
{
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_CREATURE_ENTRY: // 4
if (!unit || unit->GetEntry() != reqValue)
return false;
break;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_MUST_BE_PLAYER: // 5
if (!unit || unit->GetTypeId() != TYPEID_PLAYER)
return false;
break;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_MUST_BE_DEAD: // 6
if (!unit || unit->IsAlive())
return false;
break;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_MUST_BE_ENEMY: // 7
if (!unit || !referencePlayer->IsHostileTo(unit))
return false;
break;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_HAS_AURA: // 8
if (!referencePlayer->HasAura(reqValue))
return false;
break;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_HAS_AURA: // 10
if (!unit || !unit->HasAura(reqValue))
return false;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_HAS_AURA_TYPE: // 11
if (!unit || !unit->HasAuraType(AuraType(reqValue)))
return false;
break;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_ITEM_QUALITY_MIN: // 14
{
// miscValue1 is itemid
ItemTemplate const* const item = sObjectMgr->GetItemTemplate(uint32(miscValue1));
if (!item || item->Quality < reqValue)
return false;
break;
}
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_ITEM_QUALITY_EQUALS: // 15
{
// miscValue1 is itemid
ItemTemplate const* const item = sObjectMgr->GetItemTemplate(uint32(miscValue1));
if (!item || item->Quality != reqValue)
return false;
break;
}
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_AREA_OR_ZONE: // 17
{
uint32 zoneId, areaId;
referencePlayer->GetZoneAndAreaId(zoneId, areaId);
if (zoneId != reqValue && areaId != reqValue)
return false;
break;
}
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_AREA_OR_ZONE: // 18
{
if (!unit)
return false;
uint32 zoneId, areaId;
unit->GetZoneAndAreaId(zoneId, areaId);
if (zoneId != reqValue && areaId != reqValue)
return false;
break;
}
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_MAP_DIFFICULTY: // 20
if (uint32(referencePlayer->GetMap()->GetDifficulty()) != reqValue)
return false;
break;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_RACE: // 25
if (referencePlayer->getRace() != reqValue)
return false;
break;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_CLASS: // 26
if (referencePlayer->getClass() != reqValue)
return false;
break;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_RACE: // 27
if (!unit || unit->GetTypeId() != TYPEID_PLAYER || unit->getRace() != reqValue)
return false;
break;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_CLASS: // 28
if (!unit || unit->GetTypeId() != TYPEID_PLAYER || unit->getClass() != reqValue)
return false;
break;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_MAX_GROUP_MEMBERS: // 29
if (referencePlayer->GetGroup() && referencePlayer->GetGroup()->GetMembersCount() >= reqValue)
return false;
break;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_CREATURE_TYPE: // 30
{
if (!unit)
return false;
Creature const* const creature = unit->ToCreature();
if (!creature || creature->GetCreatureType() != reqValue)
return false;
break;
}
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_MAP: // 32
if (referencePlayer->GetMapId() != reqValue)
return false;
break;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TITLE_BIT_INDEX: // 38
// miscValue1 is title's bit index
if (miscValue1 != reqValue)
return false;
break;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_LEVEL: // 39
if (referencePlayer->getLevel() != reqValue)
return false;
break;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_LEVEL: // 40
if (!unit || unit->getLevel() != reqValue)
return false;
break;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_ZONE: // 41
if (!unit || unit->GetZoneId() != reqValue)
return false;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_HEALTH_PERCENT_BELOW: // 46
if (!unit || unit->GetHealthPct() >= reqValue)
return false;
break;
default:
break;
}
}
return true;
}
char const* AchievementGlobalMgr::GetCriteriaTypeString(uint32 type)
{
return GetCriteriaTypeString(AchievementCriteriaTypes(type));
}
char const* AchievementGlobalMgr::GetCriteriaTypeString(AchievementCriteriaTypes type)
{
switch (type)
{
case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE:
return "KILL_CREATURE";
case ACHIEVEMENT_CRITERIA_TYPE_WIN_BG:
return "TYPE_WIN_BG";
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_ARCHAEOLOGY_PROJECTS:
return "COMPLETE_RESEARCH";
case ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL:
return "REACH_LEVEL";
case ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL:
return "REACH_SKILL_LEVEL";
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_ACHIEVEMENT:
return "COMPLETE_ACHIEVEMENT";
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT:
return "COMPLETE_QUEST_COUNT";
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST_DAILY:
return "COMPLETE_DAILY_QUEST_DAILY";
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE:
return "COMPLETE_QUESTS_IN_ZONE";
case ACHIEVEMENT_CRITERIA_TYPE_CURRENCY:
return "CURRENCY";
case ACHIEVEMENT_CRITERIA_TYPE_DAMAGE_DONE:
return "DAMAGE_DONE";
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST:
return "COMPLETE_DAILY_QUEST";
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_BATTLEGROUND:
return "COMPLETE_BATTLEGROUND";
case ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP:
return "DEATH_AT_MAP";
case ACHIEVEMENT_CRITERIA_TYPE_DEATH:
return "DEATH";
case ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON:
return "DEATH_IN_DUNGEON";
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_RAID:
return "COMPLETE_RAID";
case ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_CREATURE:
return "KILLED_BY_CREATURE";
case ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_PLAYER:
return "KILLED_BY_PLAYER";
case ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING:
return "FALL_WITHOUT_DYING";
case ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM:
return "DEATHS_FROM";
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST:
return "COMPLETE_QUEST";
case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET:
return "BE_SPELL_TARGET";
case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL:
return "CAST_SPELL";
case ACHIEVEMENT_CRITERIA_TYPE_BG_OBJECTIVE_CAPTURE:
return "BG_OBJECTIVE_CAPTURE";
case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL_AT_AREA:
return "HONORABLE_KILL_AT_AREA";
case ACHIEVEMENT_CRITERIA_TYPE_WIN_ARENA:
return "WIN_ARENA";
case ACHIEVEMENT_CRITERIA_TYPE_PLAY_ARENA:
return "PLAY_ARENA";
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL:
return "LEARN_SPELL";
case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL:
return "HONORABLE_KILL";
case ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM:
return "OWN_ITEM";
case ACHIEVEMENT_CRITERIA_TYPE_WIN_RATED_ARENA:
return "WIN_RATED_ARENA";
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_TEAM_RATING:
return "HIGHEST_TEAM_RATING";
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_PERSONAL_RATING:
return "HIGHEST_PERSONAL_RATING";
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL:
return "LEARN_SKILL_LEVEL";
case ACHIEVEMENT_CRITERIA_TYPE_USE_ITEM:
return "USE_ITEM";
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_ITEM:
return "LOOT_ITEM";
case ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA:
return "EXPLORE_AREA";
case ACHIEVEMENT_CRITERIA_TYPE_OWN_RANK:
return "OWN_RANK";
case ACHIEVEMENT_CRITERIA_TYPE_BUY_BANK_SLOT:
return "BUY_BANK_SLOT";
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION:
return "GAIN_REPUTATION";
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION:
return "GAIN_EXALTED_REPUTATION";
case ACHIEVEMENT_CRITERIA_TYPE_VISIT_BARBER_SHOP:
return "VISIT_BARBER_SHOP";
case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM:
return "EQUIP_EPIC_ITEM";
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED_ON_LOOT:
return "ROLL_NEED_ON_LOOT";
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_GREED_ON_LOOT:
return "GREED_ON_LOOT";
case ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS:
return "HK_CLASS";
case ACHIEVEMENT_CRITERIA_TYPE_HK_RACE:
return "HK_RACE";
case ACHIEVEMENT_CRITERIA_TYPE_DO_EMOTE:
return "DO_EMOTE";
case ACHIEVEMENT_CRITERIA_TYPE_HEALING_DONE:
return "HEALING_DONE";
case ACHIEVEMENT_CRITERIA_TYPE_GET_KILLING_BLOWS:
return "GET_KILLING_BLOWS";
case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM:
return "EQUIP_ITEM";
case ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_VENDORS:
return "MONEY_FROM_VENDORS";
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS:
return "GOLD_SPENT_FOR_TALENTS";
case ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS:
return "NUMBER_OF_TALENT_RESETS";
case ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD:
return "MONEY_FROM_QUEST_REWARD";
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING:
return "GOLD_SPENT_FOR_TRAVELLING";
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_AT_BARBER:
return "GOLD_SPENT_AT_BARBER";
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_MAIL:
return "GOLD_SPENT_FOR_MAIL";
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_MONEY:
return "LOOT_MONEY";
case ACHIEVEMENT_CRITERIA_TYPE_USE_GAMEOBJECT:
return "USE_GAMEOBJECT";
case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2:
return "BE_SPELL_TARGET2";
case ACHIEVEMENT_CRITERIA_TYPE_SPECIAL_PVP_KILL:
return "SPECIAL_PVP_KILL";
case ACHIEVEMENT_CRITERIA_TYPE_FISH_IN_GAMEOBJECT:
return "FISH_IN_GAMEOBJECT";
case ACHIEVEMENT_CRITERIA_TYPE_EARNED_PVP_TITLE:
return "EARNED_PVP_TITLE";
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS:
return "LEARN_SKILLLINE_SPELLS";
case ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL:
return "WIN_DUEL";
case ACHIEVEMENT_CRITERIA_TYPE_LOSE_DUEL:
return "LOSE_DUEL";
case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE_TYPE:
return "KILL_CREATURE_TYPE";
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_EARNED_BY_AUCTIONS:
return "GOLD_EARNED_BY_AUCTIONS";
case ACHIEVEMENT_CRITERIA_TYPE_CREATE_AUCTION:
return "CREATE_AUCTION";
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_AUCTION_BID:
return "HIGHEST_AUCTION_BID";
case ACHIEVEMENT_CRITERIA_TYPE_WON_AUCTIONS:
return "WON_AUCTIONS";
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_AUCTION_SOLD:
return "HIGHEST_AUCTION_SOLD";
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_GOLD_VALUE_OWNED:
return "HIGHEST_GOLD_VALUE_OWNED";
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_REVERED_REPUTATION:
return "GAIN_REVERED_REPUTATION";
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_HONORED_REPUTATION:
return "GAIN_HONORED_REPUTATION";
case ACHIEVEMENT_CRITERIA_TYPE_KNOWN_FACTIONS:
return "KNOWN_FACTIONS";
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_EPIC_ITEM:
return "LOOT_EPIC_ITEM";
case ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM:
return "RECEIVE_EPIC_ITEM";
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED:
return "ROLL_NEED";
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_GREED:
return "ROLL_GREED";
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_DEALT:
return "HIT_DEALT";
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_RECEIVED:
return "HIT_RECEIVED";
case ACHIEVEMENT_CRITERIA_TYPE_TOTAL_DAMAGE_RECEIVED:
return "TOTAL_DAMAGE_RECEIVED";
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEAL_CASTED:
return "HIGHEST_HEAL_CASTED";
case ACHIEVEMENT_CRITERIA_TYPE_TOTAL_HEALING_RECEIVED:
return "TOTAL_HEALING_RECEIVED";
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEALING_RECEIVED:
return "HIGHEST_HEALING_RECEIVED";
case ACHIEVEMENT_CRITERIA_TYPE_QUEST_ABANDONED:
return "QUEST_ABANDONED";
case ACHIEVEMENT_CRITERIA_TYPE_FLIGHT_PATHS_TAKEN:
return "FLIGHT_PATHS_TAKEN";
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_TYPE:
return "LOOT_TYPE";
case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL2:
return "CAST_SPELL2";
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE:
return "LEARN_SKILL_LINE";
case ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL:
return "EARN_HONORABLE_KILL";
case ACHIEVEMENT_CRITERIA_TYPE_ACCEPTED_SUMMONINGS:
return "ACCEPTED_SUMMONINGS";
case ACHIEVEMENT_CRITERIA_TYPE_EARN_ACHIEVEMENT_POINTS:
return "EARN_ACHIEVEMENT_POINTS";
case ACHIEVEMENT_CRITERIA_TYPE_USE_LFD_TO_GROUP_WITH_PLAYERS:
return "USE_LFD_TO_GROUP_WITH_PLAYERS";
case ACHIEVEMENT_CRITERIA_TYPE_SPENT_GOLD_GUILD_REPAIRS:
return "SPENT_GOLD_GUILD_REPAIRS";
case ACHIEVEMENT_CRITERIA_TYPE_REACH_GUILD_LEVEL:
return "REACH_GUILD_LEVEL";
case ACHIEVEMENT_CRITERIA_TYPE_CRAFT_ITEMS_GUILD:
return "CRAFT_ITEMS_GUILD";
case ACHIEVEMENT_CRITERIA_TYPE_CATCH_FROM_POOL:
return "CATCH_FROM_POOL";
case ACHIEVEMENT_CRITERIA_TYPE_BUY_GUILD_BANK_SLOTS:
return "BUY_GUILD_BANK_SLOTS";
case ACHIEVEMENT_CRITERIA_TYPE_EARN_GUILD_ACHIEVEMENT_POINTS:
return "EARN_GUILD_ACHIEVEMENT_POINTS";
case ACHIEVEMENT_CRITERIA_TYPE_WIN_RATED_BATTLEGROUND:
return "WIN_RATED_BATTLEGROUND";
case ACHIEVEMENT_CRITERIA_TYPE_REACH_BG_RATING:
return "REACH_BG_RATING";
case ACHIEVEMENT_CRITERIA_TYPE_BUY_GUILD_TABARD:
return "BUY_GUILD_TABARD";
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_GUILD:
return "COMPLETE_QUESTS_GUILD";
case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILLS_GUILD:
return "HONORABLE_KILLS_GUILD";
case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE_TYPE_GUILD:
return "KILL_CREATURE_TYPE_GUILD";
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_GUILD_CHALLENGE_TYPE:
return "GUILD_CHALLENGE_TYPE";
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_GUILD_CHALLENGE:
return "GUILD_CHALLENGE";
}
return "MISSING_TYPE";
}
template class AchievementMgr<Guild>;
template class AchievementMgr<Player>;
//==========================================================
void AchievementGlobalMgr::LoadAchievementCriteriaList()
{
uint32 oldMSTime = getMSTime();
if (sAchievementCriteriaStore.GetNumRows() == 0)
{
TC_LOG_ERROR(LOG_FILTER_SERVER_LOADING, ">> Loaded 0 achievement criteria.");
return;
}
uint32 criterias = 0;
uint32 guildCriterias = 0;
for (uint32 entryId = 0; entryId < sAchievementCriteriaStore.GetNumRows(); ++entryId)
{
AchievementCriteriaEntry const* criteria = sAchievementMgr->GetAchievementCriteria(entryId);
if (!criteria)
continue;
AchievementEntry const* achievement = sAchievementMgr->GetAchievement(criteria->achievement);
m_AchievementCriteriaListByAchievement[criteria->achievement].push_back(criteria);
if (achievement && achievement->flags & ACHIEVEMENT_FLAG_GUILD)
++guildCriterias, m_GuildAchievementCriteriasByType[criteria->type].push_back(criteria);
else
++criterias, m_AchievementCriteriasByType[criteria->type].push_back(criteria);
if (criteria->timeLimit)
m_AchievementCriteriasByTimedType[criteria->timedCriteriaStartType].push_back(criteria);
}
TC_LOG_INFO(LOG_FILTER_SERVER_LOADING, ">> Loaded %u achievement criteria and %u guild achievement crieteria in %u ms", criterias, guildCriterias, GetMSTimeDiffToNow(oldMSTime));
}
void AchievementGlobalMgr::LoadAchievementReferenceList()
{
uint32 oldMSTime = getMSTime();
if (sAchievementStore.GetNumRows() == 0)
{
TC_LOG_INFO(LOG_FILTER_SERVER_LOADING, ">> Loaded 0 achievement references.");
return;
}
uint32 count = 0;
for (uint32 entryId = 0; entryId < sAchievementStore.GetNumRows(); ++entryId)
{
AchievementEntry const* achievement = sAchievementMgr->GetAchievement(entryId);
if (!achievement || !achievement->refAchievement)
continue;
m_AchievementListByReferencedId[achievement->refAchievement].push_back(achievement);
++count;
}
// Once Bitten, Twice Shy (10 player) - Icecrown Citadel
if (AchievementEntry const* achievement = sAchievementMgr->GetAchievement(4539))
const_cast<AchievementEntry*>(achievement)->mapID = 631; // Correct map requirement (currently has Ulduar)
TC_LOG_INFO(LOG_FILTER_SERVER_LOADING, ">> Loaded %u achievement references in %u ms", count, GetMSTimeDiffToNow(oldMSTime));
}
void AchievementGlobalMgr::LoadAchievementCriteriaData()
{
uint32 oldMSTime = getMSTime();
m_criteriaDataMap.clear(); // need for reload case
QueryResult result = WorldDatabase.Query("SELECT criteria_id, type, value1, value2, ScriptName FROM achievement_criteria_data");
if (!result)
{
TC_LOG_INFO(LOG_FILTER_SERVER_LOADING, ">> Loaded 0 additional achievement criteria data. DB table `achievement_criteria_data` is empty.");
return;
}
uint32 count = 0;
do
{
Field* fields = result->Fetch();
uint32 criteria_id = fields[0].GetUInt32();
AchievementCriteriaEntry const* criteria = sAchievementMgr->GetAchievementCriteria(criteria_id);
if (!criteria)
{
TC_LOG_ERROR(LOG_FILTER_SQL, "Table `achievement_criteria_data` has data for non-existing criteria (Entry: %u), ignore.", criteria_id);
continue;
}
uint32 dataType = fields[1].GetUInt8();
std::string scriptName = fields[4].GetString();
uint32 scriptId = 0;
if (scriptName.length()) // not empty
{
if (dataType != ACHIEVEMENT_CRITERIA_DATA_TYPE_SCRIPT)
TC_LOG_ERROR(LOG_FILTER_SQL, "Table `achievement_criteria_data` has ScriptName set for non-scripted data type (Entry: %u, type %u), useless data.", criteria_id, dataType);
else
scriptId = sObjectMgr->GetScriptId(scriptName.c_str());
}
AchievementCriteriaData data(dataType, fields[2].GetUInt32(), fields[3].GetUInt32(), scriptId);
if (!data.IsValid(criteria))
continue;
// this will allocate empty data set storage
AchievementCriteriaDataSet& dataSet = m_criteriaDataMap[criteria_id];
dataSet.SetCriteriaId(criteria_id);
// add real data only for not NONE data types
if (data.dataType != ACHIEVEMENT_CRITERIA_DATA_TYPE_NONE)
dataSet.Add(data);
// counting data by and data types
++count;
}
while (result->NextRow());
TC_LOG_INFO(LOG_FILTER_SERVER_LOADING, ">> Loaded %u additional achievement criteria data in %u ms", count, GetMSTimeDiffToNow(oldMSTime));
}
void AchievementGlobalMgr::LoadCompletedAchievements()
{
uint32 oldMSTime = getMSTime();
QueryResult result = CharacterDatabase.Query("SELECT achievement FROM character_achievement GROUP BY achievement");
if (!result)
{
TC_LOG_INFO(LOG_FILTER_SERVER_LOADING, ">> Loaded 0 realm first completed achievements. DB table `character_achievement` is empty.");
return;
}
do
{
Field* fields = result->Fetch();
uint16 achievementId = fields[0].GetUInt16();
const AchievementEntry* achievement = sAchievementMgr->GetAchievement(achievementId);
if (!achievement)
{
// Remove non existent achievements from all characters
TC_LOG_ERROR(LOG_FILTER_ACHIEVEMENTSYS, "Non-existing achievement %u data removed from table `character_achievement`.", achievementId);
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_INVALID_ACHIEVMENT);
stmt->setUInt16(0, uint16(achievementId));
CharacterDatabase.Execute(stmt);
continue;
}
else if (achievement->flags & (ACHIEVEMENT_FLAG_REALM_FIRST_REACH | ACHIEVEMENT_FLAG_REALM_FIRST_KILL))
m_allCompletedAchievements.insert(achievementId);
}
while (result->NextRow());
TC_LOG_INFO(LOG_FILTER_SERVER_LOADING, ">> Loaded %lu realm first completed achievements in %u ms", (unsigned long)m_allCompletedAchievements.size(), GetMSTimeDiffToNow(oldMSTime));
}
void AchievementGlobalMgr::LoadRewards()
{
uint32 oldMSTime = getMSTime();
m_achievementRewards.clear(); // need for reload case
// 0 1 2 3 4 5 6
QueryResult result = WorldDatabase.Query("SELECT entry, title_A, title_H, item, sender, subject, text FROM achievement_reward");
if (!result)
{
TC_LOG_ERROR(LOG_FILTER_SERVER_LOADING, ">> Loaded 0 achievement rewards. DB table `achievement_reward` is empty.");
return;
}
uint32 count = 0;
do
{
Field* fields = result->Fetch();
uint32 entry = fields[0].GetUInt32();
const AchievementEntry* pAchievement = GetAchievement(entry);
if (!pAchievement)
{
TC_LOG_ERROR(LOG_FILTER_SQL, "Table `achievement_reward` has wrong achievement (Entry: %u), ignored.", entry);
continue;
}
AchievementReward reward;
reward.titleId[0] = fields[1].GetUInt32();
reward.titleId[1] = fields[2].GetUInt32();
reward.itemId = fields[3].GetUInt32();
reward.sender = fields[4].GetUInt32();
reward.subject = fields[5].GetString();
reward.text = fields[6].GetString();
// must be title or mail at least
if (!reward.titleId[0] && !reward.titleId[1] && !reward.sender)
{
TC_LOG_ERROR(LOG_FILTER_SQL, "Table `achievement_reward` (Entry: %u) does not have title or item reward data, ignored.", entry);
continue;
}
if (pAchievement->requiredFaction == ACHIEVEMENT_FACTION_ANY && ((reward.titleId[0] == 0) != (reward.titleId[1] == 0)))
TC_LOG_ERROR(LOG_FILTER_SQL, "Table `achievement_reward` (Entry: %u) has title (A: %u H: %u) for only one team.", entry, reward.titleId[0], reward.titleId[1]);
if (reward.titleId[0])
{
CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(reward.titleId[0]);
if (!titleEntry)
{
TC_LOG_ERROR(LOG_FILTER_SQL, "Table `achievement_reward` (Entry: %u) has invalid title id (%u) in `title_A`, set to 0", entry, reward.titleId[0]);
reward.titleId[0] = 0;
}
}
if (reward.titleId[1])
{
CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(reward.titleId[1]);
if (!titleEntry)
{
TC_LOG_ERROR(LOG_FILTER_SQL, "Table `achievement_reward` (Entry: %u) has invalid title id (%u) in `title_H`, set to 0", entry, reward.titleId[1]);
reward.titleId[1] = 0;
}
}
//check mail data before item for report including wrong item case
if (reward.sender)
{
if (!sObjectMgr->GetCreatureTemplate(reward.sender))
{
TC_LOG_ERROR(LOG_FILTER_SQL, "Table `achievement_reward` (Entry: %u) has invalid creature entry %u as sender, mail reward skipped.", entry, reward.sender);
reward.sender = 0;
}
}
else
{
if (reward.itemId)
TC_LOG_ERROR(LOG_FILTER_SQL, "Table `achievement_reward` (Entry: %u) does not have sender data but has item reward, item will not be rewarded.", entry);
if (!reward.subject.empty())
TC_LOG_ERROR(LOG_FILTER_SQL, "Table `achievement_reward` (Entry: %u) does not have sender data but has mail subject.", entry);
if (!reward.text.empty())
TC_LOG_ERROR(LOG_FILTER_SQL, "Table `achievement_reward` (Entry: %u) does not have sender data but has mail text.", entry);
}
if (reward.itemId)
{
if (!sObjectMgr->GetItemTemplate(reward.itemId))
{
TC_LOG_ERROR(LOG_FILTER_SQL, "Table `achievement_reward` (Entry: %u) has invalid item id %u, reward mail will not contain item.", entry, reward.itemId);
reward.itemId = 0;
}
}
m_achievementRewards[entry] = reward;
++count;
}
while (result->NextRow());
TC_LOG_INFO(LOG_FILTER_SERVER_LOADING, ">> Loaded %u achievement rewards in %u ms", count, GetMSTimeDiffToNow(oldMSTime));
}
void AchievementGlobalMgr::LoadRewardLocales()
{
uint32 oldMSTime = getMSTime();
m_achievementRewardLocales.clear(); // need for reload case
QueryResult result = WorldDatabase.Query("SELECT entry, subject_loc1, text_loc1, subject_loc2, text_loc2, subject_loc3, text_loc3, subject_loc4, text_loc4, "
"subject_loc5, text_loc5, subject_loc6, text_loc6, subject_loc7, text_loc7, subject_loc8, text_loc8"
" FROM locales_achievement_reward");
if (!result)
{
TC_LOG_INFO(LOG_FILTER_SERVER_LOADING, ">> Loaded 0 achievement reward locale strings. DB table `locales_achievement_reward` is empty");
return;
}
do
{
Field* fields = result->Fetch();
uint32 entry = fields[0].GetUInt32();
if (m_achievementRewards.find(entry) == m_achievementRewards.end())
{
TC_LOG_ERROR(LOG_FILTER_SQL, "Table `locales_achievement_reward` (Entry: %u) has locale strings for non-existing achievement reward.", entry);
continue;
}
AchievementRewardLocale& data = m_achievementRewardLocales[entry];
for (int i = 1; i < TOTAL_LOCALES; ++i)
{
LocaleConstant locale = (LocaleConstant) i;
ObjectMgr::AddLocaleString(fields[1 + 2 * (i - 1)].GetString(), locale, data.subject);
ObjectMgr::AddLocaleString(fields[1 + 2 * (i - 1) + 1].GetString(), locale, data.text);
}
}
while (result->NextRow());
TC_LOG_INFO(LOG_FILTER_SERVER_LOADING, ">> Loaded %lu achievement reward locale strings in %u ms", (unsigned long)m_achievementRewardLocales.size(), GetMSTimeDiffToNow(oldMSTime));
}
AchievementEntry const* AchievementGlobalMgr::GetAchievement(uint32 achievementId) const
{
return sAchievementStore.LookupEntry(achievementId);
}
AchievementCriteriaEntry const* AchievementGlobalMgr::GetAchievementCriteria(uint32 criteriaId) const
{
return sAchievementCriteriaStore.LookupEntry(criteriaId);
}
| [
"jorjescu@ymai.com"
] | jorjescu@ymai.com |
2d63327f3a8d060a7b79d0d7d68056116ed80e35 | 47b71ff8a12367c10573e58289d6abbd41c2436f | /android/frameworks/av/services/audioflinger/Threads.cpp | 3e45f3cc596abeb70b663bc2e3f405b459df0064 | [
"LicenseRef-scancode-unicode",
"Apache-2.0"
] | permissive | BPI-SINOVOIP/BPI-A31S-Android | d567fcefb8881bcca67f9401c5a4cfa875df5640 | ed63ae00332d2fdab22efc45a4a9a46ff31b8180 | refs/heads/master | 2022-11-05T15:39:21.895636 | 2017-04-27T16:58:45 | 2017-04-27T16:58:45 | 48,844,096 | 2 | 4 | null | 2022-10-28T10:10:24 | 2015-12-31T09:34:31 | null | UTF-8 | C++ | false | false | 198,902 | cpp | /*
**
** Copyright 2012, The Android Open Source 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 "AudioFlinger"
//#define LOG_NDEBUG 0
#define ATRACE_TAG ATRACE_TAG_AUDIO
#include "Configuration.h"
#include <math.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <cutils/properties.h>
#include <media/AudioParameter.h>
#include <utils/Log.h>
#include <utils/Trace.h>
#include <private/media/AudioTrackShared.h>
#include <hardware/audio.h>
#include <audio_effects/effect_ns.h>
#include <audio_effects/effect_aec.h>
#include <audio_utils/primitives.h>
// NBAIO implementations
#include <media/nbaio/AudioStreamOutSink.h>
#include <media/nbaio/MonoPipe.h>
#include <media/nbaio/MonoPipeReader.h>
#include <media/nbaio/Pipe.h>
#include <media/nbaio/PipeReader.h>
#include <media/nbaio/SourceAudioBufferProvider.h>
#include <powermanager/PowerManager.h>
#include <common_time/cc_helper.h>
#include <common_time/local_clock.h>
#include "AudioFlinger.h"
#include "AudioMixer.h"
#include "FastMixer.h"
#include "ServiceUtilities.h"
#include "SchedulingPolicyService.h"
#ifdef ADD_BATTERY_DATA
#include <media/IMediaPlayerService.h>
#include <media/IMediaDeathNotifier.h>
#endif
#ifdef DEBUG_CPU_USAGE
#include <cpustats/CentralTendencyStatistics.h>
#include <cpustats/ThreadCpuUsage.h>
#endif
// ----------------------------------------------------------------------------
// Note: the following macro is used for extremely verbose logging message. In
// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
// 0; but one side effect of this is to turn all LOGV's as well. Some messages
// are so verbose that we want to suppress them even when we have ALOG_ASSERT
// turned on. Do not uncomment the #def below unless you really know what you
// are doing and want to see all of the extremely verbose messages.
//#define VERY_VERY_VERBOSE_LOGGING
#ifdef VERY_VERY_VERBOSE_LOGGING
#define ALOGVV ALOGV
#else
#define ALOGVV(a...) do { } while(0)
#endif
namespace android {
// retry counts for buffer fill timeout
// 50 * ~20msecs = 1 second
static const int8_t kMaxTrackRetries = 50;
static const int8_t kMaxTrackStartupRetries = 50;
// allow less retry attempts on direct output thread.
// direct outputs can be a scarce resource in audio hardware and should
// be released as quickly as possible.
static const int8_t kMaxTrackRetriesDirect = 2;
// don't warn about blocked writes or record buffer overflows more often than this
static const nsecs_t kWarningThrottleNs = seconds(5);
// RecordThread loop sleep time upon application overrun or audio HAL read error
static const int kRecordThreadSleepUs = 5000;
// maximum time to wait for setParameters to complete
static const nsecs_t kSetParametersTimeoutNs = seconds(2);
// minimum sleep time for the mixer thread loop when tracks are active but in underrun
static const uint32_t kMinThreadSleepTimeUs = 5000;
// maximum divider applied to the active sleep time in the mixer thread loop
static const uint32_t kMaxThreadSleepTimeShift = 2;
// minimum normal mix buffer size, expressed in milliseconds rather than frames
static const uint32_t kMinNormalMixBufferSizeMs = 20;
// maximum normal mix buffer size
static const uint32_t kMaxNormalMixBufferSizeMs = 24;
// Offloaded output thread standby delay: allows track transition without going to standby
static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
// Whether to use fast mixer
static const enum {
FastMixer_Never, // never initialize or use: for debugging only
FastMixer_Always, // always initialize and use, even if not needed: for debugging only
// normal mixer multiplier is 1
FastMixer_Static, // initialize if needed, then use all the time if initialized,
// multiplier is calculated based on min & max normal mixer buffer size
FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
// multiplier is calculated based on min & max normal mixer buffer size
// FIXME for FastMixer_Dynamic:
// Supporting this option will require fixing HALs that can't handle large writes.
// For example, one HAL implementation returns an error from a large write,
// and another HAL implementation corrupts memory, possibly in the sample rate converter.
// We could either fix the HAL implementations, or provide a wrapper that breaks
// up large writes into smaller ones, and the wrapper would need to deal with scheduler.
} kUseFastMixer = FastMixer_Static;
// Priorities for requestPriority
static const int kPriorityAudioApp = 2;
static const int kPriorityFastMixer = 3;
// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
// for the track. The client then sub-divides this into smaller buffers for its use.
// Currently the client uses double-buffering by default, but doesn't tell us about that.
// So for now we just assume that client is double-buffered.
// FIXME It would be better for client to tell AudioFlinger whether it wants double-buffering or
// N-buffering, so AudioFlinger could allocate the right amount of memory.
// See the client's minBufCount and mNotificationFramesAct calculations for details.
static const int kFastTrackMultiplier = 1;
// ----------------------------------------------------------------------------
#ifdef ADD_BATTERY_DATA
// To collect the amplifier usage
static void addBatteryData(uint32_t params) {
sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
if (service == NULL) {
// it already logged
return;
}
service->addBatteryData(params);
}
#endif
// ----------------------------------------------------------------------------
// CPU Stats
// ----------------------------------------------------------------------------
class CpuStats {
public:
CpuStats();
void sample(const String8 &title);
#ifdef DEBUG_CPU_USAGE
private:
ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
int mCpuNum; // thread's current CPU number
int mCpukHz; // frequency of thread's current CPU in kHz
#endif
};
CpuStats::CpuStats()
#ifdef DEBUG_CPU_USAGE
: mCpuNum(-1), mCpukHz(-1)
#endif
{
}
void CpuStats::sample(const String8 &title) {
#ifdef DEBUG_CPU_USAGE
// get current thread's delta CPU time in wall clock ns
double wcNs;
bool valid = mCpuUsage.sampleAndEnable(wcNs);
// record sample for wall clock statistics
if (valid) {
mWcStats.sample(wcNs);
}
// get the current CPU number
int cpuNum = sched_getcpu();
// get the current CPU frequency in kHz
int cpukHz = mCpuUsage.getCpukHz(cpuNum);
// check if either CPU number or frequency changed
if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
mCpuNum = cpuNum;
mCpukHz = cpukHz;
// ignore sample for purposes of cycles
valid = false;
}
// if no change in CPU number or frequency, then record sample for cycle statistics
if (valid && mCpukHz > 0) {
double cycles = wcNs * cpukHz * 0.000001;
mHzStats.sample(cycles);
}
unsigned n = mWcStats.n();
// mCpuUsage.elapsed() is expensive, so don't call it every loop
if ((n & 127) == 1) {
long long elapsed = mCpuUsage.elapsed();
if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
double perLoop = elapsed / (double) n;
double perLoop100 = perLoop * 0.01;
double perLoop1k = perLoop * 0.001;
double mean = mWcStats.mean();
double stddev = mWcStats.stddev();
double minimum = mWcStats.minimum();
double maximum = mWcStats.maximum();
double meanCycles = mHzStats.mean();
double stddevCycles = mHzStats.stddev();
double minCycles = mHzStats.minimum();
double maxCycles = mHzStats.maximum();
mCpuUsage.resetElapsed();
mWcStats.reset();
mHzStats.reset();
ALOGD("CPU usage for %s over past %.1f secs\n"
" (%u mixer loops at %.1f mean ms per loop):\n"
" us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
" %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
" MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
title.string(),
elapsed * .000000001, n, perLoop * .000001,
mean * .001,
stddev * .001,
minimum * .001,
maximum * .001,
mean / perLoop100,
stddev / perLoop100,
minimum / perLoop100,
maximum / perLoop100,
meanCycles / perLoop1k,
stddevCycles / perLoop1k,
minCycles / perLoop1k,
maxCycles / perLoop1k);
}
}
#endif
};
// ----------------------------------------------------------------------------
// ThreadBase
// ----------------------------------------------------------------------------
AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
audio_devices_t outDevice, audio_devices_t inDevice, type_t type)
: Thread(false /*canCallJava*/),
mType(type),
mAudioFlinger(audioFlinger),
// mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, and mFormat are
// set by PlaybackThread::readOutputParameters() or RecordThread::readInputParameters()
mParamStatus(NO_ERROR),
//FIXME: mStandby should be true here. Is this some kind of hack?
mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
// mName will be set by concrete (non-virtual) subclass
mDeathRecipient(new PMDeathRecipient(this))
{
}
AudioFlinger::ThreadBase::~ThreadBase()
{
// mConfigEvents should be empty, but just in case it isn't, free the memory it owns
for (size_t i = 0; i < mConfigEvents.size(); i++) {
delete mConfigEvents[i];
}
mConfigEvents.clear();
mParamCond.broadcast();
// do not lock the mutex in destructor
releaseWakeLock_l();
if (mPowerManager != 0) {
sp<IBinder> binder = mPowerManager->asBinder();
binder->unlinkToDeath(mDeathRecipient);
}
}
void AudioFlinger::ThreadBase::exit()
{
ALOGV("ThreadBase::exit");
// do any cleanup required for exit to succeed
preExit();
{
// This lock prevents the following race in thread (uniprocessor for illustration):
// if (!exitPending()) {
// // context switch from here to exit()
// // exit() calls requestExit(), what exitPending() observes
// // exit() calls signal(), which is dropped since no waiters
// // context switch back from exit() to here
// mWaitWorkCV.wait(...);
// // now thread is hung
// }
AutoMutex lock(mLock);
requestExit();
mWaitWorkCV.broadcast();
}
// When Thread::requestExitAndWait is made virtual and this method is renamed to
// "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
requestExitAndWait();
}
status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
{
status_t status;
ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mutex::Autolock _l(mLock);
mNewParameters.add(keyValuePairs);
mWaitWorkCV.signal();
// wait condition with timeout in case the thread loop has exited
// before the request could be processed
if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
status = mParamStatus;
mWaitWorkCV.signal();
} else {
status = TIMED_OUT;
}
return status;
}
void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param)
{
Mutex::Autolock _l(mLock);
sendIoConfigEvent_l(event, param);
}
// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param)
{
IoConfigEvent *ioEvent = new IoConfigEvent(event, param);
mConfigEvents.add(static_cast<ConfigEvent *>(ioEvent));
ALOGV("sendIoConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event,
param);
mWaitWorkCV.signal();
}
// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
{
PrioConfigEvent *prioEvent = new PrioConfigEvent(pid, tid, prio);
mConfigEvents.add(static_cast<ConfigEvent *>(prioEvent));
ALOGV("sendPrioConfigEvent_l() num events %d pid %d, tid %d prio %d",
mConfigEvents.size(), pid, tid, prio);
mWaitWorkCV.signal();
}
void AudioFlinger::ThreadBase::processConfigEvents()
{
mLock.lock();
while (!mConfigEvents.isEmpty()) {
ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
ConfigEvent *event = mConfigEvents[0];
mConfigEvents.removeAt(0);
// release mLock before locking AudioFlinger mLock: lock order is always
// AudioFlinger then ThreadBase to avoid cross deadlock
mLock.unlock();
switch(event->type()) {
case CFG_EVENT_PRIO: {
PrioConfigEvent *prioEvent = static_cast<PrioConfigEvent *>(event);
// FIXME Need to understand why this has be done asynchronously
int err = requestPriority(prioEvent->pid(), prioEvent->tid(), prioEvent->prio(),
true /*asynchronous*/);
if (err != 0) {
ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; "
"error %d",
prioEvent->prio(), prioEvent->pid(), prioEvent->tid(), err);
}
} break;
case CFG_EVENT_IO: {
IoConfigEvent *ioEvent = static_cast<IoConfigEvent *>(event);
mAudioFlinger->mLock.lock();
audioConfigChanged_l(ioEvent->event(), ioEvent->param());
mAudioFlinger->mLock.unlock();
} break;
default:
ALOGE("processConfigEvents() unknown event type %d", event->type());
break;
}
delete event;
mLock.lock();
}
mLock.unlock();
}
void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
{
const size_t SIZE = 256;
char buffer[SIZE];
String8 result;
bool locked = AudioFlinger::dumpTryLock(mLock);
if (!locked) {
snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
write(fd, buffer, strlen(buffer));
}
snprintf(buffer, SIZE, "io handle: %d\n", mId);
result.append(buffer);
snprintf(buffer, SIZE, "TID: %d\n", getTid());
result.append(buffer);
snprintf(buffer, SIZE, "standby: %d\n", mStandby);
result.append(buffer);
snprintf(buffer, SIZE, "Sample rate: %u\n", mSampleRate);
result.append(buffer);
snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
result.append(buffer);
snprintf(buffer, SIZE, "Channel Count: %u\n", mChannelCount);
result.append(buffer);
snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
result.append(buffer);
snprintf(buffer, SIZE, "Format: %d\n", mFormat);
result.append(buffer);
snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
result.append(buffer);
snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
result.append(buffer);
result.append(" Index Command");
for (size_t i = 0; i < mNewParameters.size(); ++i) {
snprintf(buffer, SIZE, "\n %02d ", i);
result.append(buffer);
result.append(mNewParameters[i]);
}
snprintf(buffer, SIZE, "\n\nPending config events: \n");
result.append(buffer);
for (size_t i = 0; i < mConfigEvents.size(); i++) {
mConfigEvents[i]->dump(buffer, SIZE);
result.append(buffer);
}
result.append("\n");
write(fd, result.string(), result.size());
if (locked) {
mLock.unlock();
}
}
void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
{
const size_t SIZE = 256;
char buffer[SIZE];
String8 result;
snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
write(fd, buffer, strlen(buffer));
for (size_t i = 0; i < mEffectChains.size(); ++i) {
sp<EffectChain> chain = mEffectChains[i];
if (chain != 0) {
chain->dump(fd, args);
}
}
}
void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
{
Mutex::Autolock _l(mLock);
acquireWakeLock_l(uid);
}
String16 AudioFlinger::ThreadBase::getWakeLockTag()
{
switch (mType) {
case MIXER:
return String16("AudioMix");
case DIRECT:
return String16("AudioDirectOut");
case DUPLICATING:
return String16("AudioDup");
case RECORD:
return String16("AudioIn");
case OFFLOAD:
return String16("AudioOffload");
default:
ALOG_ASSERT(false);
return String16("AudioUnknown");
}
}
void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
{
getPowerManager_l();
if (mPowerManager != 0) {
sp<IBinder> binder = new BBinder();
status_t status;
if (uid >= 0) {
status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
binder,
getWakeLockTag(),
String16("media"),
uid);
} else {
status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
binder,
getWakeLockTag(),
String16("media"));
}
if (status == NO_ERROR) {
mWakeLockToken = binder;
}
ALOGV("acquireWakeLock_l() %s status %d", mName, status);
}
}
void AudioFlinger::ThreadBase::releaseWakeLock()
{
Mutex::Autolock _l(mLock);
releaseWakeLock_l();
}
void AudioFlinger::ThreadBase::releaseWakeLock_l()
{
if (mWakeLockToken != 0) {
ALOGV("releaseWakeLock_l() %s", mName);
if (mPowerManager != 0) {
mPowerManager->releaseWakeLock(mWakeLockToken, 0);
}
mWakeLockToken.clear();
}
}
void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
Mutex::Autolock _l(mLock);
updateWakeLockUids_l(uids);
}
void AudioFlinger::ThreadBase::getPowerManager_l() {
if (mPowerManager == 0) {
// use checkService() to avoid blocking if power service is not up yet
sp<IBinder> binder =
defaultServiceManager()->checkService(String16("power"));
if (binder == 0) {
ALOGW("Thread %s cannot connect to the power manager service", mName);
} else {
mPowerManager = interface_cast<IPowerManager>(binder);
binder->linkToDeath(mDeathRecipient);
}
}
}
void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
getPowerManager_l();
if (mWakeLockToken == NULL) {
ALOGE("no wake lock to update!");
return;
}
if (mPowerManager != 0) {
sp<IBinder> binder = new BBinder();
status_t status;
status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array());
ALOGV("acquireWakeLock_l() %s status %d", mName, status);
}
}
void AudioFlinger::ThreadBase::clearPowerManager()
{
Mutex::Autolock _l(mLock);
releaseWakeLock_l();
mPowerManager.clear();
}
void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
{
sp<ThreadBase> thread = mThread.promote();
if (thread != 0) {
thread->clearPowerManager();
}
ALOGW("power manager service died !!!");
}
void AudioFlinger::ThreadBase::setEffectSuspended(
const effect_uuid_t *type, bool suspend, int sessionId)
{
Mutex::Autolock _l(mLock);
setEffectSuspended_l(type, suspend, sessionId);
}
void AudioFlinger::ThreadBase::setEffectSuspended_l(
const effect_uuid_t *type, bool suspend, int sessionId)
{
sp<EffectChain> chain = getEffectChain_l(sessionId);
if (chain != 0) {
if (type != NULL) {
chain->setEffectSuspended_l(type, suspend);
} else {
chain->setEffectSuspendedAll_l(suspend);
}
}
updateSuspendedSessions_l(type, suspend, sessionId);
}
void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
{
ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
if (index < 0) {
return;
}
const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
mSuspendedSessions.valueAt(index);
for (size_t i = 0; i < sessionEffects.size(); i++) {
sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
for (int j = 0; j < desc->mRefCount; j++) {
if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
chain->setEffectSuspendedAll_l(true);
} else {
ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
desc->mType.timeLow);
chain->setEffectSuspended_l(&desc->mType, true);
}
}
}
}
void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
bool suspend,
int sessionId)
{
ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
if (suspend) {
if (index >= 0) {
sessionEffects = mSuspendedSessions.valueAt(index);
} else {
mSuspendedSessions.add(sessionId, sessionEffects);
}
} else {
if (index < 0) {
return;
}
sessionEffects = mSuspendedSessions.valueAt(index);
}
int key = EffectChain::kKeyForSuspendAll;
if (type != NULL) {
key = type->timeLow;
}
index = sessionEffects.indexOfKey(key);
sp<SuspendedSessionDesc> desc;
if (suspend) {
if (index >= 0) {
desc = sessionEffects.valueAt(index);
} else {
desc = new SuspendedSessionDesc();
if (type != NULL) {
desc->mType = *type;
}
sessionEffects.add(key, desc);
ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
}
desc->mRefCount++;
} else {
if (index < 0) {
return;
}
desc = sessionEffects.valueAt(index);
if (--desc->mRefCount == 0) {
ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
sessionEffects.removeItemsAt(index);
if (sessionEffects.isEmpty()) {
ALOGV("updateSuspendedSessions_l() restore removing session %d",
sessionId);
mSuspendedSessions.removeItem(sessionId);
}
}
}
if (!sessionEffects.isEmpty()) {
mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
}
}
void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
bool enabled,
int sessionId)
{
Mutex::Autolock _l(mLock);
checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
}
void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
bool enabled,
int sessionId)
{
if (mType != RECORD) {
// suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
// another session. This gives the priority to well behaved effect control panels
// and applications not using global effects.
// Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
// global effects
if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
}
}
sp<EffectChain> chain = getEffectChain_l(sessionId);
if (chain != 0) {
chain->checkSuspendOnEffectEnabled(effect, enabled);
}
}
// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
const sp<AudioFlinger::Client>& client,
const sp<IEffectClient>& effectClient,
int32_t priority,
int sessionId,
effect_descriptor_t *desc,
int *enabled,
status_t *status
)
{
sp<EffectModule> effect;
sp<EffectHandle> handle;
status_t lStatus;
sp<EffectChain> chain;
bool chainCreated = false;
bool effectCreated = false;
bool effectRegistered = false;
lStatus = initCheck();
if (lStatus != NO_ERROR) {
ALOGW("createEffect_l() Audio driver not initialized.");
goto Exit;
}
// Allow global effects only on offloaded and mixer threads
if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
switch (mType) {
case MIXER:
case OFFLOAD:
break;
case DIRECT:
case DUPLICATING:
case RECORD:
default:
ALOGW("createEffect_l() Cannot add global effect %s on thread %s", desc->name, mName);
lStatus = BAD_VALUE;
goto Exit;
}
}
// Only Pre processor effects are allowed on input threads and only on input threads
if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
desc->name, desc->flags, mType);
lStatus = BAD_VALUE;
goto Exit;
}
ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
{ // scope for mLock
Mutex::Autolock _l(mLock);
// check for existing effect chain with the requested audio session
chain = getEffectChain_l(sessionId);
if (chain == 0) {
// create a new chain for this session
ALOGV("createEffect_l() new effect chain for session %d", sessionId);
chain = new EffectChain(this, sessionId);
addEffectChain_l(chain);
chain->setStrategy(getStrategyForSession_l(sessionId));
chainCreated = true;
} else {
effect = chain->getEffectFromDesc_l(desc);
}
ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
if (effect == 0) {
int id = mAudioFlinger->nextUniqueId();
// Check CPU and memory usage
lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
if (lStatus != NO_ERROR) {
goto Exit;
}
effectRegistered = true;
// create a new effect module if none present in the chain
effect = new EffectModule(this, chain, desc, id, sessionId);
lStatus = effect->status();
if (lStatus != NO_ERROR) {
goto Exit;
}
effect->setOffloaded(mType == OFFLOAD, mId);
lStatus = chain->addEffect_l(effect);
if (lStatus != NO_ERROR) {
goto Exit;
}
effectCreated = true;
effect->setDevice(mOutDevice);
effect->setDevice(mInDevice);
effect->setMode(mAudioFlinger->getMode());
effect->setAudioSource(mAudioSource);
}
// create effect handle and connect it to effect module
handle = new EffectHandle(effect, client, effectClient, priority);
lStatus = effect->addHandle(handle.get());
if (enabled != NULL) {
*enabled = (int)effect->isEnabled();
}
}
Exit:
if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Mutex::Autolock _l(mLock);
if (effectCreated) {
chain->removeEffect_l(effect);
}
if (effectRegistered) {
AudioSystem::unregisterEffect(effect->id());
}
if (chainCreated) {
removeEffectChain_l(chain);
}
handle.clear();
}
if (status != NULL) {
*status = lStatus;
}
return handle;
}
sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
{
Mutex::Autolock _l(mLock);
return getEffect_l(sessionId, effectId);
}
sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
{
sp<EffectChain> chain = getEffectChain_l(sessionId);
return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
}
// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
// PlaybackThread::mLock held
status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
{
// check for existing effect chain with the requested audio session
int sessionId = effect->sessionId();
sp<EffectChain> chain = getEffectChain_l(sessionId);
bool chainCreated = false;
ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
"addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
this, effect->desc().name, effect->desc().flags);
if (chain == 0) {
// create a new chain for this session
ALOGV("addEffect_l() new effect chain for session %d", sessionId);
chain = new EffectChain(this, sessionId);
addEffectChain_l(chain);
chain->setStrategy(getStrategyForSession_l(sessionId));
chainCreated = true;
}
ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
if (chain->getEffectFromId_l(effect->id()) != 0) {
ALOGW("addEffect_l() %p effect %s already present in chain %p",
this, effect->desc().name, chain.get());
return BAD_VALUE;
}
effect->setOffloaded(mType == OFFLOAD, mId);
status_t status = chain->addEffect_l(effect);
if (status != NO_ERROR) {
if (chainCreated) {
removeEffectChain_l(chain);
}
return status;
}
effect->setDevice(mOutDevice);
effect->setDevice(mInDevice);
effect->setMode(mAudioFlinger->getMode());
effect->setAudioSource(mAudioSource);
return NO_ERROR;
}
void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
ALOGV("removeEffect_l() %p effect %p", this, effect.get());
effect_descriptor_t desc = effect->desc();
if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
detachAuxEffect_l(effect->id());
}
sp<EffectChain> chain = effect->chain().promote();
if (chain != 0) {
// remove effect chain if removing last effect
if (chain->removeEffect_l(effect) == 0) {
removeEffectChain_l(chain);
}
} else {
ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
}
}
void AudioFlinger::ThreadBase::lockEffectChains_l(
Vector< sp<AudioFlinger::EffectChain> >& effectChains)
{
effectChains = mEffectChains;
for (size_t i = 0; i < mEffectChains.size(); i++) {
mEffectChains[i]->lock();
}
}
void AudioFlinger::ThreadBase::unlockEffectChains(
const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
{
for (size_t i = 0; i < effectChains.size(); i++) {
effectChains[i]->unlock();
}
}
sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
{
Mutex::Autolock _l(mLock);
return getEffectChain_l(sessionId);
}
sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
{
size_t size = mEffectChains.size();
for (size_t i = 0; i < size; i++) {
if (mEffectChains[i]->sessionId() == sessionId) {
return mEffectChains[i];
}
}
return 0;
}
void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
{
Mutex::Autolock _l(mLock);
size_t size = mEffectChains.size();
for (size_t i = 0; i < size; i++) {
mEffectChains[i]->setMode_l(mode);
}
}
void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
EffectHandle *handle,
bool unpinIfLast) {
Mutex::Autolock _l(mLock);
ALOGV("disconnectEffect() %p effect %p", this, effect.get());
// delete the effect module if removing last handle on it
if (effect->removeHandle(handle) == 0) {
if (!effect->isPinned() || unpinIfLast) {
removeEffect_l(effect);
AudioSystem::unregisterEffect(effect->id());
}
}
}
// ----------------------------------------------------------------------------
// Playback
// ----------------------------------------------------------------------------
AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
AudioStreamOut* output,
audio_io_handle_t id,
audio_devices_t device,
type_t type)
: ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
mNormalFrameCount(0), mMixBuffer(NULL),
mAllocMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
mActiveTracksGeneration(0),
// mStreamTypes[] initialized in constructor body
mOutput(output),
mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
mMixerStatus(MIXER_IDLE),
mMixerStatusIgnoringFastTracks(MIXER_IDLE),
standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
mBytesRemaining(0),
mCurrentWriteLength(0),
mUseAsyncWrite(false),
mWriteAckSequence(0),
mDrainSequence(0),
mSignalPending(false),
mScreenState(AudioFlinger::mScreenState),
// index 0 is reserved for normal mixer's submix
mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
// mLatchD, mLatchQ,
mLatchDValid(false), mLatchQValid(false)
{
snprintf(mName, kNameLength, "AudioOut_%X", id);
mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
// Assumes constructor is called by AudioFlinger with it's mLock held, but
// it would be safer to explicitly pass initial masterVolume/masterMute as
// parameter.
//
// If the HAL we are using has support for master volume or master mute,
// then do not attenuate or mute during mixing (just leave the volume at 1.0
// and the mute set to false).
mMasterVolume = audioFlinger->masterVolume_l();
mMasterMute = audioFlinger->masterMute_l();
if (mOutput && mOutput->audioHwDev) {
if (mOutput->audioHwDev->canSetMasterVolume()) {
mMasterVolume = 1.0;
}
if (mOutput->audioHwDev->canSetMasterMute()) {
mMasterMute = false;
}
}
readOutputParameters();
// mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
// There is no AUDIO_STREAM_MIN, and ++ operator does not compile
for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
stream = (audio_stream_type_t) (stream + 1)) {
mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
}
// mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
// because mAudioFlinger doesn't have one to copy from
}
AudioFlinger::PlaybackThread::~PlaybackThread()
{
mAudioFlinger->unregisterWriter(mNBLogWriter);
delete [] mAllocMixBuffer;
}
void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
{
dumpInternals(fd, args);
dumpTracks(fd, args);
dumpEffectChains(fd, args);
}
void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
{
const size_t SIZE = 256;
char buffer[SIZE];
String8 result;
result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
const stream_type_t *st = &mStreamTypes[i];
if (i > 0) {
result.appendFormat(", ");
}
result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
if (st->mute) {
result.append("M");
}
}
result.append("\n");
write(fd, result.string(), result.length());
result.clear();
snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
result.append(buffer);
Track::appendDumpHeader(result);
for (size_t i = 0; i < mTracks.size(); ++i) {
sp<Track> track = mTracks[i];
if (track != 0) {
track->dump(buffer, SIZE);
result.append(buffer);
}
}
snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
result.append(buffer);
Track::appendDumpHeader(result);
for (size_t i = 0; i < mActiveTracks.size(); ++i) {
sp<Track> track = mActiveTracks[i].promote();
if (track != 0) {
track->dump(buffer, SIZE);
result.append(buffer);
}
}
write(fd, result.string(), result.size());
// These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
FastTrackUnderruns underruns = getFastTrackUnderruns(0);
fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
}
void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
{
const size_t SIZE = 256;
char buffer[SIZE];
String8 result;
snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
result.append(buffer);
snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
result.append(buffer);
snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n",
ns2ms(systemTime() - mLastWriteTime));
result.append(buffer);
snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
result.append(buffer);
snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
result.append(buffer);
snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
result.append(buffer);
snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
result.append(buffer);
snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
result.append(buffer);
write(fd, result.string(), result.size());
fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
dumpBase(fd, args);
}
// Thread virtuals
status_t AudioFlinger::PlaybackThread::readyToRun()
{
status_t status = initCheck();
if (status == NO_ERROR) {
ALOGI("AudioFlinger's thread %p ready to run", this);
} else {
ALOGE("No working audio driver found.");
}
return status;
}
void AudioFlinger::PlaybackThread::onFirstRef()
{
run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
}
// ThreadBase virtuals
void AudioFlinger::PlaybackThread::preExit()
{
ALOGV(" preExit()");
// FIXME this is using hard-coded strings but in the future, this functionality will be
// converted to use audio HAL extensions required to support tunneling
mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
}
// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
const sp<AudioFlinger::Client>& client,
audio_stream_type_t streamType,
uint32_t sampleRate,
audio_format_t format,
audio_channel_mask_t channelMask,
size_t frameCount,
const sp<IMemory>& sharedBuffer,
int sessionId,
IAudioFlinger::track_flags_t *flags,
pid_t tid,
int uid,
status_t *status)
{
sp<Track> track;
status_t lStatus;
bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
// client expresses a preference for FAST, but we get the final say
if (*flags & IAudioFlinger::TRACK_FAST) {
if (
// not timed
(!isTimed) &&
// either of these use cases:
(
// use case 1: shared buffer with any frame count
(
(sharedBuffer != 0)
) ||
// use case 2: callback handler and frame count is default or at least as large as HAL
(
(tid != -1) &&
((frameCount == 0) ||
(frameCount >= (mFrameCount * kFastTrackMultiplier)))
)
) &&
// PCM data
audio_is_linear_pcm(format) &&
// mono or stereo
( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
(channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
// hardware sample rate
(sampleRate == mSampleRate) &&
#endif
// normal mixer has an associated fast mixer
hasFastMixer() &&
// there are sufficient fast track slots available
(mFastTrackAvailMask != 0)
// FIXME test that MixerThread for this fast track has a capable output HAL
// FIXME add a permission test also?
) {
// if frameCount not specified, then it defaults to fast mixer (HAL) frame count
if (frameCount == 0) {
frameCount = mFrameCount * kFastTrackMultiplier;
}
ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
frameCount, mFrameCount);
} else {
ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
"mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
"hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
audio_is_linear_pcm(format),
channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
*flags &= ~IAudioFlinger::TRACK_FAST;
// For compatibility with AudioTrack calculation, buffer depth is forced
// to be at least 2 x the normal mixer frame count and cover audio hardware latency.
// This is probably too conservative, but legacy application code may depend on it.
// If you change this calculation, also review the start threshold which is related.
uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
if (minBufCount < 2) {
minBufCount = 2;
}
if (minBufCount > 4) {
minBufCount = 4;
}
size_t minFrameCount = mNormalFrameCount * minBufCount;
if (frameCount < minFrameCount) {
frameCount = minFrameCount;
}
}
}
if (mType == DIRECT) {
if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
ALOGE("createTrack_l() Bad parameter: sampleRate %u format %d, channelMask 0x%08x "
"for output %p with format %d",
sampleRate, format, channelMask, mOutput, mFormat);
lStatus = BAD_VALUE;
goto Exit;
}
}
} else if (mType == OFFLOAD) {
if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
"for output %p with format %d",
sampleRate, format, channelMask, mOutput, mFormat);
lStatus = BAD_VALUE;
goto Exit;
}
} else {
if ((format & AUDIO_FORMAT_MAIN_MASK) != AUDIO_FORMAT_PCM) {
ALOGE("createTrack_l() Bad parameter: format %d \""
"for output %p with format %d",
format, mOutput, mFormat);
lStatus = BAD_VALUE;
goto Exit;
}
// Resampler implementation limits input sampling rate to 2 x output sampling rate.
if (sampleRate > 96000) {
ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
lStatus = BAD_VALUE;
goto Exit;
}
}
lStatus = initCheck();
if (lStatus != NO_ERROR) {
ALOGE("Audio driver not initialized.");
goto Exit;
}
{ // scope for mLock
Mutex::Autolock _l(mLock);
// all tracks in same audio session must share the same routing strategy otherwise
// conflicts will happen when tracks are moved from one output to another by audio policy
// manager
uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
for (size_t i = 0; i < mTracks.size(); ++i) {
sp<Track> t = mTracks[i];
if (t != 0 && !t->isOutputTrack()) {
uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
if (sessionId == t->sessionId() && strategy != actual) {
ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
strategy, actual);
lStatus = BAD_VALUE;
goto Exit;
}
}
}
if (!isTimed) {
track = new Track(this, client, streamType, sampleRate, format,
channelMask, frameCount, sharedBuffer, sessionId, uid, *flags);
} else {
track = TimedTrack::create(this, client, streamType, sampleRate, format,
channelMask, frameCount, sharedBuffer, sessionId, uid);
}
if (track == 0 || track->getCblk() == NULL || track->name() < 0) {
lStatus = NO_MEMORY;
goto Exit;
}
mTracks.add(track);
sp<EffectChain> chain = getEffectChain_l(sessionId);
if (chain != 0) {
ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
track->setMainBuffer(chain->inBuffer());
chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
chain->incTrackCnt();
}
if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
pid_t callingPid = IPCThreadState::self()->getCallingPid();
// we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
// so ask activity manager to do this on our behalf
sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
}
}
lStatus = NO_ERROR;
Exit:
if (status) {
*status = lStatus;
}
return track;
}
uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
{
return latency;
}
uint32_t AudioFlinger::PlaybackThread::latency() const
{
Mutex::Autolock _l(mLock);
return latency_l();
}
uint32_t AudioFlinger::PlaybackThread::latency_l() const
{
if (initCheck() == NO_ERROR) {
return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
} else {
return 0;
}
}
void AudioFlinger::PlaybackThread::setMasterVolume(float value)
{
Mutex::Autolock _l(mLock);
// Don't apply master volume in SW if our HAL can do it for us.
if (mOutput && mOutput->audioHwDev &&
mOutput->audioHwDev->canSetMasterVolume()) {
mMasterVolume = 1.0;
} else {
mMasterVolume = value;
}
}
void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
{
Mutex::Autolock _l(mLock);
// Don't apply master mute in SW if our HAL can do it for us.
if (mOutput && mOutput->audioHwDev &&
mOutput->audioHwDev->canSetMasterMute()) {
mMasterMute = false;
} else {
mMasterMute = muted;
}
}
void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
{
Mutex::Autolock _l(mLock);
mStreamTypes[stream].volume = value;
broadcast_l();
}
void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
{
Mutex::Autolock _l(mLock);
mStreamTypes[stream].mute = muted;
broadcast_l();
}
float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
{
Mutex::Autolock _l(mLock);
return mStreamTypes[stream].volume;
}
// addTrack_l() must be called with ThreadBase::mLock held
status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
{
status_t status = ALREADY_EXISTS;
// set retry count for buffer fill
track->mRetryCount = kMaxTrackStartupRetries;
if (mActiveTracks.indexOf(track) < 0) {
// the track is newly added, make sure it fills up all its
// buffers before playing. This is to ensure the client will
// effectively get the latency it requested.
if (!track->isOutputTrack()) {
TrackBase::track_state state = track->mState;
mLock.unlock();
status = AudioSystem::startOutput(mId, track->streamType(), track->sessionId());
mLock.lock();
// abort track was stopped/paused while we released the lock
if (state != track->mState) {
if (status == NO_ERROR) {
mLock.unlock();
AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
mLock.lock();
}
return INVALID_OPERATION;
}
// abort if start is rejected by audio policy manager
if (status != NO_ERROR) {
return PERMISSION_DENIED;
}
#ifdef ADD_BATTERY_DATA
// to track the speaker usage
addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
#endif
}
track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
track->mResetDone = false;
track->mPresentationCompleteFrames = 0;
mActiveTracks.add(track);
mWakeLockUids.add(track->uid());
mActiveTracksGeneration++;
mLatestActiveTrack = track;
sp<EffectChain> chain = getEffectChain_l(track->sessionId());
if (chain != 0) {
ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
track->sessionId());
chain->incActiveTrackCnt();
}
status = NO_ERROR;
}
ALOGV("signal playback thread");
broadcast_l();
return status;
}
bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
{
track->terminate();
// active tracks are removed by threadLoop()
bool trackActive = (mActiveTracks.indexOf(track) >= 0);
track->mState = TrackBase::STOPPED;
if (!trackActive) {
removeTrack_l(track);
} else if (track->isFastTrack() || track->isOffloaded()) {
track->mState = TrackBase::STOPPING_1;
}
return trackActive;
}
void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
{
track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
mTracks.remove(track);
deleteTrackName_l(track->name());
// redundant as track is about to be destroyed, for dumpsys only
track->mName = -1;
if (track->isFastTrack()) {
int index = track->mFastIndex;
ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
mFastTrackAvailMask |= 1 << index;
// redundant as track is about to be destroyed, for dumpsys only
track->mFastIndex = -1;
}
sp<EffectChain> chain = getEffectChain_l(track->sessionId());
if (chain != 0) {
chain->decTrackCnt();
}
}
void AudioFlinger::PlaybackThread::broadcast_l()
{
// Thread could be blocked waiting for async
// so signal it to handle state changes immediately
// If threadLoop is currently unlocked a signal of mWaitWorkCV will
// be lost so we also flag to prevent it blocking on mWaitWorkCV
mSignalPending = true;
mWaitWorkCV.broadcast();
}
String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
{
Mutex::Autolock _l(mLock);
if (initCheck() != NO_ERROR) {
return String8();
}
char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
const String8 out_s8(s);
free(s);
return out_s8;
}
// audioConfigChanged_l() must be called with AudioFlinger::mLock held
void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
AudioSystem::OutputDescriptor desc;
void *param2 = NULL;
ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event,
param);
switch (event) {
case AudioSystem::OUTPUT_OPENED:
case AudioSystem::OUTPUT_CONFIG_CHANGED:
desc.channelMask = mChannelMask;
desc.samplingRate = mSampleRate;
desc.format = mFormat;
desc.frameCount = mNormalFrameCount; // FIXME see
// AudioFlinger::frameCount(audio_io_handle_t)
desc.latency = latency();
param2 = &desc;
break;
case AudioSystem::STREAM_CONFIG_CHANGED:
param2 = ¶m;
case AudioSystem::OUTPUT_CLOSED:
default:
break;
}
mAudioFlinger->audioConfigChanged_l(event, mId, param2);
}
void AudioFlinger::PlaybackThread::writeCallback()
{
ALOG_ASSERT(mCallbackThread != 0);
mCallbackThread->resetWriteBlocked();
}
void AudioFlinger::PlaybackThread::drainCallback()
{
ALOG_ASSERT(mCallbackThread != 0);
mCallbackThread->resetDraining();
}
void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
{
Mutex::Autolock _l(mLock);
// reject out of sequence requests
if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
mWriteAckSequence &= ~1;
mWaitWorkCV.signal();
}
}
void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
{
Mutex::Autolock _l(mLock);
// reject out of sequence requests
if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
mDrainSequence &= ~1;
mWaitWorkCV.signal();
}
}
// static
int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
void *param,
void *cookie)
{
AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
ALOGV("asyncCallback() event %d", event);
switch (event) {
case STREAM_CBK_EVENT_WRITE_READY:
me->writeCallback();
break;
case STREAM_CBK_EVENT_DRAIN_READY:
me->drainCallback();
break;
default:
ALOGW("asyncCallback() unknown event %d", event);
break;
}
return 0;
}
void AudioFlinger::PlaybackThread::readOutputParameters()
{
// unfortunately we have no way of recovering from errors here, hence the LOG_FATAL
mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
if (!audio_is_output_channel(mChannelMask)) {
LOG_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
}
if ((mType == MIXER || mType == DUPLICATING) && mChannelMask != AUDIO_CHANNEL_OUT_STEREO) {
LOG_FATAL("HAL channel mask %#x not supported for mixed output; "
"must be AUDIO_CHANNEL_OUT_STEREO", mChannelMask);
}
mChannelCount = popcount(mChannelMask);
mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
if (!audio_is_valid_format(mFormat)) {
LOG_FATAL("HAL format %d not valid for output", mFormat);
}
if ((mType == MIXER || mType == DUPLICATING) && mFormat != AUDIO_FORMAT_PCM_16_BIT) {
LOG_FATAL("HAL format %d not supported for mixed output; must be AUDIO_FORMAT_PCM_16_BIT",
mFormat);
}
mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
if (mFrameCount & 15) {
ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
mFrameCount);
}
if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
(mOutput->stream->set_callback != NULL)) {
if (mOutput->stream->set_callback(mOutput->stream,
AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
mUseAsyncWrite = true;
mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
}
}
// Calculate size of normal mix buffer relative to the HAL output buffer size
double multiplier = 1.0;
if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
kUseFastMixer == FastMixer_Dynamic)) {
size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
// round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
maxNormalFrameCount = maxNormalFrameCount & ~15;
if (maxNormalFrameCount < minNormalFrameCount) {
maxNormalFrameCount = minNormalFrameCount;
}
multiplier = (double) minNormalFrameCount / (double) mFrameCount;
if (multiplier <= 1.0) {
multiplier = 1.0;
} else if (multiplier <= 2.0) {
if (2 * mFrameCount <= maxNormalFrameCount) {
multiplier = 2.0;
} else {
multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
}
} else {
// prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
// SRC (it would be unusual for the normal mix buffer size to not be a multiple of fast
// track, but we sometimes have to do this to satisfy the maximum frame count
// constraint)
// FIXME this rounding up should not be done if no HAL SRC
uint32_t truncMult = (uint32_t) multiplier;
if ((truncMult & 1)) {
if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
++truncMult;
}
}
multiplier = (double) truncMult;
}
}
mNormalFrameCount = multiplier * mFrameCount;
// round up to nearest 16 frames to satisfy AudioMixer
mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount,
mNormalFrameCount);
delete[] mAllocMixBuffer;
size_t align = (mFrameSize < sizeof(int16_t)) ? sizeof(int16_t) : mFrameSize;
mAllocMixBuffer = new int8_t[mNormalFrameCount * mFrameSize + align - 1];
mMixBuffer = (int16_t *) ((((size_t)mAllocMixBuffer + align - 1) / align) * align);
memset(mMixBuffer, 0, mNormalFrameCount * mFrameSize);
// force reconfiguration of effect chains and engines to take new buffer size and audio
// parameters into account
// Note that mLock is not held when readOutputParameters() is called from the constructor
// but in this case nothing is done below as no audio sessions have effect yet so it doesn't
// matter.
// create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
Vector< sp<EffectChain> > effectChains = mEffectChains;
for (size_t i = 0; i < effectChains.size(); i ++) {
mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
}
}
status_t AudioFlinger::PlaybackThread::getRenderPosition(size_t *halFrames, size_t *dspFrames)
{
if (halFrames == NULL || dspFrames == NULL) {
return BAD_VALUE;
}
Mutex::Autolock _l(mLock);
if (initCheck() != NO_ERROR) {
return INVALID_OPERATION;
}
size_t framesWritten = mBytesWritten / mFrameSize;
*halFrames = framesWritten;
if (isSuspended()) {
// return an estimation of rendered frames when the output is suspended
size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
*dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
return NO_ERROR;
} else {
return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
}
}
uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
{
Mutex::Autolock _l(mLock);
uint32_t result = 0;
if (getEffectChain_l(sessionId) != 0) {
result = EFFECT_SESSION;
}
for (size_t i = 0; i < mTracks.size(); ++i) {
sp<Track> track = mTracks[i];
if (sessionId == track->sessionId() && !track->isInvalid()) {
result |= TRACK_SESSION;
break;
}
}
return result;
}
uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
{
// session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
// it is moved to correct output by audio policy manager when A2DP is connected or disconnected
if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
}
for (size_t i = 0; i < mTracks.size(); i++) {
sp<Track> track = mTracks[i];
if (sessionId == track->sessionId() && !track->isInvalid()) {
return AudioSystem::getStrategyForStream(track->streamType());
}
}
return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
}
AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
{
Mutex::Autolock _l(mLock);
return mOutput;
}
AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
{
Mutex::Autolock _l(mLock);
AudioStreamOut *output = mOutput;
mOutput = NULL;
// FIXME FastMixer might also have a raw ptr to mOutputSink;
// must push a NULL and wait for ack
mOutputSink.clear();
mPipeSink.clear();
mNormalSink.clear();
return output;
}
// this method must always be called either with ThreadBase mLock held or inside the thread loop
audio_stream_t* AudioFlinger::PlaybackThread::stream() const
{
if (mOutput == NULL) {
return NULL;
}
return &mOutput->stream->common;
}
uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
{
return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
}
status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
{
if (!isValidSyncEvent(event)) {
return BAD_VALUE;
}
Mutex::Autolock _l(mLock);
for (size_t i = 0; i < mTracks.size(); ++i) {
sp<Track> track = mTracks[i];
if (event->triggerSession() == track->sessionId()) {
(void) track->setSyncEvent(event);
return NO_ERROR;
}
}
return NAME_NOT_FOUND;
}
bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
{
return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
}
void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
const Vector< sp<Track> >& tracksToRemove)
{
size_t count = tracksToRemove.size();
if (count) {
for (size_t i = 0 ; i < count ; i++) {
const sp<Track>& track = tracksToRemove.itemAt(i);
if (!track->isOutputTrack()) {
AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
#ifdef ADD_BATTERY_DATA
// to track the speaker usage
addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
#endif
if (track->isTerminated()) {
AudioSystem::releaseOutput(mId);
}
}
}
}
}
void AudioFlinger::PlaybackThread::checkSilentMode_l()
{
if (!mMasterMute) {
char value[PROPERTY_VALUE_MAX];
if (property_get("ro.audio.silent", value, "0") > 0) {
char *endptr;
unsigned long ul = strtoul(value, &endptr, 0);
if (*endptr == '\0' && ul != 0) {
ALOGD("Silence is golden");
// The setprop command will not allow a property to be changed after
// the first time it is set, so we don't have to worry about un-muting.
setMasterMute_l(true);
}
}
}
}
// shared by MIXER and DIRECT, overridden by DUPLICATING
ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
{
// FIXME rewrite to reduce number of system calls
mLastWriteTime = systemTime();
mInWrite = true;
ssize_t bytesWritten;
// If an NBAIO sink is present, use it to write the normal mixer's submix
if (mNormalSink != 0) {
#define mBitShift 2 // FIXME
size_t count = mBytesRemaining >> mBitShift;
size_t offset = (mCurrentWriteLength - mBytesRemaining) >> 1;
ATRACE_BEGIN("write");
// update the setpoint when AudioFlinger::mScreenState changes
uint32_t screenState = AudioFlinger::mScreenState;
if (screenState != mScreenState) {
mScreenState = screenState;
MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
if (pipe != NULL) {
pipe->setAvgFrames((mScreenState & 1) ?
(pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
}
}
ssize_t framesWritten = mNormalSink->write(mMixBuffer + offset, count);
ATRACE_END();
if (framesWritten > 0) {
bytesWritten = framesWritten << mBitShift;
} else {
bytesWritten = framesWritten;
}
status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
if (status == NO_ERROR) {
size_t totalFramesWritten = mNormalSink->framesWritten();
if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
mLatchDValid = true;
}
}
// otherwise use the HAL / AudioStreamOut directly
} else {
// Direct output and offload threads
size_t offset = (mCurrentWriteLength - mBytesRemaining) / sizeof(int16_t);
if (mUseAsyncWrite) {
ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
mWriteAckSequence += 2;
mWriteAckSequence |= 1;
ALOG_ASSERT(mCallbackThread != 0);
mCallbackThread->setWriteBlocked(mWriteAckSequence);
}
// FIXME We should have an implementation of timestamps for direct output threads.
// They are used e.g for multichannel PCM playback over HDMI.
bytesWritten = mOutput->stream->write(mOutput->stream,
mMixBuffer + offset, mBytesRemaining);
if (mUseAsyncWrite &&
((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
// do not wait for async callback in case of error of full write
mWriteAckSequence &= ~1;
ALOG_ASSERT(mCallbackThread != 0);
mCallbackThread->setWriteBlocked(mWriteAckSequence);
}
}
mNumWrites++;
mInWrite = false;
mStandby = false;
return bytesWritten;
}
void AudioFlinger::PlaybackThread::threadLoop_drain()
{
if (mOutput->stream->drain) {
ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
if (mUseAsyncWrite) {
ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
mDrainSequence |= 1;
ALOG_ASSERT(mCallbackThread != 0);
mCallbackThread->setDraining(mDrainSequence);
}
mOutput->stream->drain(mOutput->stream,
(mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
: AUDIO_DRAIN_ALL);
}
}
void AudioFlinger::PlaybackThread::threadLoop_exit()
{
// Default implementation has nothing to do
}
/*
The derived values that are cached:
- mixBufferSize from frame count * frame size
- activeSleepTime from activeSleepTimeUs()
- idleSleepTime from idleSleepTimeUs()
- standbyDelay from mActiveSleepTimeUs (DIRECT only)
- maxPeriod from frame count and sample rate (MIXER only)
The parameters that affect these derived values are:
- frame count
- frame size
- sample rate
- device type: A2DP or not
- device latency
- format: PCM or not
- active sleep time
- idle sleep time
*/
void AudioFlinger::PlaybackThread::cacheParameters_l()
{
mixBufferSize = mNormalFrameCount * mFrameSize;
activeSleepTime = activeSleepTimeUs();
idleSleepTime = idleSleepTimeUs();
}
void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
{
ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
this, streamType, mTracks.size());
Mutex::Autolock _l(mLock);
size_t size = mTracks.size();
for (size_t i = 0; i < size; i++) {
sp<Track> t = mTracks[i];
if (t->streamType() == streamType) {
t->invalidate();
}
}
}
status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
{
int session = chain->sessionId();
int16_t *buffer = mMixBuffer;
bool ownsBuffer = false;
ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
if (session > 0) {
// Only one effect chain can be present in direct output thread and it uses
// the mix buffer as input
if (mType != DIRECT) {
size_t numSamples = mNormalFrameCount * mChannelCount;
buffer = new int16_t[numSamples];
memset(buffer, 0, numSamples * sizeof(int16_t));
ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
ownsBuffer = true;
}
// Attach all tracks with same session ID to this chain.
for (size_t i = 0; i < mTracks.size(); ++i) {
sp<Track> track = mTracks[i];
if (session == track->sessionId()) {
ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
buffer);
track->setMainBuffer(buffer);
chain->incTrackCnt();
}
}
// indicate all active tracks in the chain
for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
sp<Track> track = mActiveTracks[i].promote();
if (track == 0) {
continue;
}
if (session == track->sessionId()) {
ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
chain->incActiveTrackCnt();
}
}
}
chain->setInBuffer(buffer, ownsBuffer);
chain->setOutBuffer(mMixBuffer);
// Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
// chains list in order to be processed last as it contains output stage effects
// Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
// session AUDIO_SESSION_OUTPUT_STAGE to be processed
// after track specific effects and before output stage
// It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
// that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
// Effect chain for other sessions are inserted at beginning of effect
// chains list to be processed before output mix effects. Relative order between other
// sessions is not important
size_t size = mEffectChains.size();
size_t i = 0;
for (i = 0; i < size; i++) {
if (mEffectChains[i]->sessionId() < session) {
break;
}
}
mEffectChains.insertAt(chain, i);
checkSuspendOnAddEffectChain_l(chain);
return NO_ERROR;
}
size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
{
int session = chain->sessionId();
ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
for (size_t i = 0; i < mEffectChains.size(); i++) {
if (chain == mEffectChains[i]) {
mEffectChains.removeAt(i);
// detach all active tracks from the chain
for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
sp<Track> track = mActiveTracks[i].promote();
if (track == 0) {
continue;
}
if (session == track->sessionId()) {
ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
chain.get(), session);
chain->decActiveTrackCnt();
}
}
// detach all tracks with same session ID from this chain
for (size_t i = 0; i < mTracks.size(); ++i) {
sp<Track> track = mTracks[i];
if (session == track->sessionId()) {
track->setMainBuffer(mMixBuffer);
chain->decTrackCnt();
}
}
break;
}
}
return mEffectChains.size();
}
status_t AudioFlinger::PlaybackThread::attachAuxEffect(
const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
{
Mutex::Autolock _l(mLock);
return attachAuxEffect_l(track, EffectId);
}
status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
{
status_t status = NO_ERROR;
if (EffectId == 0) {
track->setAuxBuffer(0, NULL);
} else {
// Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
if (effect != 0) {
if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
} else {
status = INVALID_OPERATION;
}
} else {
status = BAD_VALUE;
}
}
return status;
}
void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
{
for (size_t i = 0; i < mTracks.size(); ++i) {
sp<Track> track = mTracks[i];
if (track->auxEffectId() == effectId) {
attachAuxEffect_l(track, 0);
}
}
}
bool AudioFlinger::PlaybackThread::threadLoop()
{
Vector< sp<Track> > tracksToRemove;
standbyTime = systemTime();
// MIXER
nsecs_t lastWarning = 0;
// DUPLICATING
// FIXME could this be made local to while loop?
writeFrames = 0;
int lastGeneration = 0;
cacheParameters_l();
sleepTime = idleSleepTime;
if (mType == MIXER) {
sleepTimeShift = 0;
}
CpuStats cpuStats;
const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
acquireWakeLock();
// mNBLogWriter->log can only be called while thread mutex mLock is held.
// So if you need to log when mutex is unlocked, set logString to a non-NULL string,
// and then that string will be logged at the next convenient opportunity.
const char *logString = NULL;
checkSilentMode_l();
while (!exitPending())
{
cpuStats.sample(myName);
Vector< sp<EffectChain> > effectChains;
processConfigEvents();
{ // scope for mLock
Mutex::Autolock _l(mLock);
if (logString != NULL) {
mNBLogWriter->logTimestamp();
mNBLogWriter->log(logString);
logString = NULL;
}
if (mLatchDValid) {
mLatchQ = mLatchD;
mLatchDValid = false;
mLatchQValid = true;
}
if (checkForNewParameters_l()) {
cacheParameters_l();
}
saveOutputTracks();
if (mSignalPending) {
// A signal was raised while we were unlocked
mSignalPending = false;
} else if (waitingAsyncCallback_l()) {
if (exitPending()) {
break;
}
releaseWakeLock_l();
mWakeLockUids.clear();
mActiveTracksGeneration++;
ALOGV("wait async completion");
mWaitWorkCV.wait(mLock);
ALOGV("async completion/wake");
acquireWakeLock_l();
standbyTime = systemTime() + standbyDelay;
sleepTime = 0;
continue;
}
if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
isSuspended()) {
// put audio hardware into standby after short delay
if (shouldStandby_l()) {
threadLoop_standby();
mStandby = true;
}
if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
// we're about to wait, flush the binder command buffer
IPCThreadState::self()->flushCommands();
clearOutputTracks();
if (exitPending()) {
break;
}
releaseWakeLock_l();
mWakeLockUids.clear();
mActiveTracksGeneration++;
// wait until we have something to do...
ALOGV("%s going to sleep", myName.string());
mWaitWorkCV.wait(mLock);
ALOGV("%s waking up", myName.string());
acquireWakeLock_l();
mMixerStatus = MIXER_IDLE;
mMixerStatusIgnoringFastTracks = MIXER_IDLE;
mBytesWritten = 0;
mBytesRemaining = 0;
checkSilentMode_l();
standbyTime = systemTime() + standbyDelay;
sleepTime = idleSleepTime;
if (mType == MIXER) {
sleepTimeShift = 0;
}
continue;
}
}
// mMixerStatusIgnoringFastTracks is also updated internally
mMixerStatus = prepareTracks_l(&tracksToRemove);
// compare with previously applied list
if (lastGeneration != mActiveTracksGeneration) {
// update wakelock
updateWakeLockUids_l(mWakeLockUids);
lastGeneration = mActiveTracksGeneration;
}
// prevent any changes in effect chain list and in each effect chain
// during mixing and effect process as the audio buffers could be deleted
// or modified if an effect is created or deleted
lockEffectChains_l(effectChains);
} // mLock scope ends
if (mBytesRemaining == 0) {
mCurrentWriteLength = 0;
if (mMixerStatus == MIXER_TRACKS_READY) {
// threadLoop_mix() sets mCurrentWriteLength
threadLoop_mix();
} else if ((mMixerStatus != MIXER_DRAIN_TRACK)
&& (mMixerStatus != MIXER_DRAIN_ALL)) {
// threadLoop_sleepTime sets sleepTime to 0 if data
// must be written to HAL
threadLoop_sleepTime();
if (sleepTime == 0) {
mCurrentWriteLength = mixBufferSize;
}
}
mBytesRemaining = mCurrentWriteLength;
if (isSuspended()) {
sleepTime = suspendSleepTimeUs();
// simulate write to HAL when suspended
mBytesWritten += mixBufferSize;
mBytesRemaining = 0;
}
// only process effects if we're going to write
if (sleepTime == 0 && mType != OFFLOAD) {
for (size_t i = 0; i < effectChains.size(); i ++) {
effectChains[i]->process_l();
}
}
}
// Process effect chains for offloaded thread even if no audio
// was read from audio track: process only updates effect state
// and thus does have to be synchronized with audio writes but may have
// to be called while waiting for async write callback
if (mType == OFFLOAD) {
for (size_t i = 0; i < effectChains.size(); i ++) {
effectChains[i]->process_l();
}
}
// enable changes in effect chain
unlockEffectChains(effectChains);
if (!waitingAsyncCallback()) {
// sleepTime == 0 means we must write to audio hardware
if (sleepTime == 0) {
if (mBytesRemaining) {
ssize_t ret = threadLoop_write();
if (ret < 0) {
mBytesRemaining = 0;
} else {
mBytesWritten += ret;
mBytesRemaining -= ret;
}
} else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
(mMixerStatus == MIXER_DRAIN_ALL)) {
threadLoop_drain();
}
if (mType == MIXER) {
// write blocked detection
nsecs_t now = systemTime();
nsecs_t delta = now - mLastWriteTime;
if (!mStandby && delta > maxPeriod) {
mNumDelayedWrites++;
if ((now - lastWarning) > kWarningThrottleNs) {
ATRACE_NAME("underrun");
ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
ns2ms(delta), mNumDelayedWrites, this);
lastWarning = now;
}
}
}
} else {
usleep(sleepTime);
}
}
// Finally let go of removed track(s), without the lock held
// since we can't guarantee the destructors won't acquire that
// same lock. This will also mutate and push a new fast mixer state.
threadLoop_removeTracks(tracksToRemove);
tracksToRemove.clear();
// FIXME I don't understand the need for this here;
// it was in the original code but maybe the
// assignment in saveOutputTracks() makes this unnecessary?
clearOutputTracks();
// Effect chains will be actually deleted here if they were removed from
// mEffectChains list during mixing or effects processing
effectChains.clear();
// FIXME Note that the above .clear() is no longer necessary since effectChains
// is now local to this block, but will keep it for now (at least until merge done).
}
threadLoop_exit();
// for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
if (mType == MIXER || mType == DIRECT || mType == OFFLOAD) {
// put output stream into standby mode
if (!mStandby) {
mOutput->stream->common.standby(&mOutput->stream->common);
}
}
releaseWakeLock();
mWakeLockUids.clear();
mActiveTracksGeneration++;
ALOGV("Thread %p type %d exiting", this, mType);
return false;
}
// removeTracks_l() must be called with ThreadBase::mLock held
void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
{
size_t count = tracksToRemove.size();
if (count) {
for (size_t i=0 ; i<count ; i++) {
const sp<Track>& track = tracksToRemove.itemAt(i);
mActiveTracks.remove(track);
mWakeLockUids.remove(track->uid());
mActiveTracksGeneration++;
ALOGV("removeTracks_l removing track on session %d", track->sessionId());
sp<EffectChain> chain = getEffectChain_l(track->sessionId());
if (chain != 0) {
ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
track->sessionId());
chain->decActiveTrackCnt();
}
if (track->isTerminated()) {
removeTrack_l(track);
}
}
}
}
status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
{
if (mNormalSink != 0) {
return mNormalSink->getTimestamp(timestamp);
}
if (mType == OFFLOAD && mOutput->stream->get_presentation_position) {
uint64_t position64;
int ret = mOutput->stream->get_presentation_position(
mOutput->stream, &position64, ×tamp.mTime);
if (ret == 0) {
timestamp.mPosition = (uint32_t)position64;
return NO_ERROR;
}
}
return INVALID_OPERATION;
}
// ----------------------------------------------------------------------------
AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
audio_io_handle_t id, audio_devices_t device, type_t type)
: PlaybackThread(audioFlinger, output, id, device, type),
// mAudioMixer below
// mFastMixer below
mFastMixerFutex(0)
// mOutputSink below
// mPipeSink below
// mNormalSink below
{
ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
"mFrameCount=%d, mNormalFrameCount=%d",
mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
mNormalFrameCount);
mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
// FIXME - Current mixer implementation only supports stereo output
if (mChannelCount != FCC_2) {
ALOGE("Invalid audio hardware channel count %d", mChannelCount);
}
// create an NBAIO sink for the HAL output stream, and negotiate
mOutputSink = new AudioStreamOutSink(output->stream);
size_t numCounterOffers = 0;
const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
ALOG_ASSERT(index == 0);
// initialize fast mixer depending on configuration
bool initFastMixer;
switch (kUseFastMixer) {
case FastMixer_Never:
initFastMixer = false;
break;
case FastMixer_Always:
initFastMixer = true;
break;
case FastMixer_Static:
case FastMixer_Dynamic:
initFastMixer = mFrameCount < mNormalFrameCount;
break;
}
if (initFastMixer) {
// create a MonoPipe to connect our submix to FastMixer
NBAIO_Format format = mOutputSink->format();
// This pipe depth compensates for scheduling latency of the normal mixer thread.
// When it wakes up after a maximum latency, it runs a few cycles quickly before
// finally blocking. Note the pipe implementation rounds up the request to a power of 2.
MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
const NBAIO_Format offers[1] = {format};
size_t numCounterOffers = 0;
ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
ALOG_ASSERT(index == 0);
monoPipe->setAvgFrames((mScreenState & 1) ?
(monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
mPipeSink = monoPipe;
#ifdef TEE_SINK
if (mTeeSinkOutputEnabled) {
// create a Pipe to archive a copy of FastMixer's output for dumpsys
Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, format);
numCounterOffers = 0;
index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
ALOG_ASSERT(index == 0);
mTeeSink = teeSink;
PipeReader *teeSource = new PipeReader(*teeSink);
numCounterOffers = 0;
index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
ALOG_ASSERT(index == 0);
mTeeSource = teeSource;
}
#endif
// create fast mixer and configure it initially with just one fast track for our submix
mFastMixer = new FastMixer();
FastMixerStateQueue *sq = mFastMixer->sq();
#ifdef STATE_QUEUE_DUMP
sq->setObserverDump(&mStateQueueObserverDump);
sq->setMutatorDump(&mStateQueueMutatorDump);
#endif
FastMixerState *state = sq->begin();
FastTrack *fastTrack = &state->mFastTracks[0];
// wrap the source side of the MonoPipe to make it an AudioBufferProvider
fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
fastTrack->mVolumeProvider = NULL;
fastTrack->mGeneration++;
state->mFastTracksGen++;
state->mTrackMask = 1;
// fast mixer will use the HAL output sink
state->mOutputSink = mOutputSink.get();
state->mOutputSinkGen++;
state->mFrameCount = mFrameCount;
state->mCommand = FastMixerState::COLD_IDLE;
// already done in constructor initialization list
//mFastMixerFutex = 0;
state->mColdFutexAddr = &mFastMixerFutex;
state->mColdGen++;
state->mDumpState = &mFastMixerDumpState;
#ifdef TEE_SINK
state->mTeeSink = mTeeSink.get();
#endif
mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
state->mNBLogWriter = mFastMixerNBLogWriter.get();
sq->end();
sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
// start the fast mixer
mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
pid_t tid = mFastMixer->getTid();
int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
if (err != 0) {
ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
kPriorityFastMixer, getpid_cached, tid, err);
}
#ifdef AUDIO_WATCHDOG
// create and start the watchdog
mAudioWatchdog = new AudioWatchdog();
mAudioWatchdog->setDump(&mAudioWatchdogDump);
mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
tid = mAudioWatchdog->getTid();
err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
if (err != 0) {
ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
kPriorityFastMixer, getpid_cached, tid, err);
}
#endif
} else {
mFastMixer = NULL;
}
switch (kUseFastMixer) {
case FastMixer_Never:
case FastMixer_Dynamic:
mNormalSink = mOutputSink;
break;
case FastMixer_Always:
mNormalSink = mPipeSink;
break;
case FastMixer_Static:
mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
break;
}
}
AudioFlinger::MixerThread::~MixerThread()
{
if (mFastMixer != NULL) {
FastMixerStateQueue *sq = mFastMixer->sq();
FastMixerState *state = sq->begin();
if (state->mCommand == FastMixerState::COLD_IDLE) {
int32_t old = android_atomic_inc(&mFastMixerFutex);
if (old == -1) {
__futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
}
}
state->mCommand = FastMixerState::EXIT;
sq->end();
sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
mFastMixer->join();
// Though the fast mixer thread has exited, it's state queue is still valid.
// We'll use that extract the final state which contains one remaining fast track
// corresponding to our sub-mix.
state = sq->begin();
ALOG_ASSERT(state->mTrackMask == 1);
FastTrack *fastTrack = &state->mFastTracks[0];
ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
delete fastTrack->mBufferProvider;
sq->end(false /*didModify*/);
delete mFastMixer;
#ifdef AUDIO_WATCHDOG
if (mAudioWatchdog != 0) {
mAudioWatchdog->requestExit();
mAudioWatchdog->requestExitAndWait();
mAudioWatchdog.clear();
}
#endif
}
mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
delete mAudioMixer;
}
uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
{
if (mFastMixer != NULL) {
MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
}
return latency;
}
void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
{
PlaybackThread::threadLoop_removeTracks(tracksToRemove);
}
ssize_t AudioFlinger::MixerThread::threadLoop_write()
{
// FIXME we should only do one push per cycle; confirm this is true
// Start the fast mixer if it's not already running
if (mFastMixer != NULL) {
FastMixerStateQueue *sq = mFastMixer->sq();
FastMixerState *state = sq->begin();
if (state->mCommand != FastMixerState::MIX_WRITE &&
(kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
if (state->mCommand == FastMixerState::COLD_IDLE) {
int32_t old = android_atomic_inc(&mFastMixerFutex);
if (old == -1) {
__futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
}
#ifdef AUDIO_WATCHDOG
if (mAudioWatchdog != 0) {
mAudioWatchdog->resume();
}
#endif
}
state->mCommand = FastMixerState::MIX_WRITE;
mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
sq->end();
sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
if (kUseFastMixer == FastMixer_Dynamic) {
mNormalSink = mPipeSink;
}
} else {
sq->end(false /*didModify*/);
}
}
return PlaybackThread::threadLoop_write();
}
void AudioFlinger::MixerThread::threadLoop_standby()
{
// Idle the fast mixer if it's currently running
if (mFastMixer != NULL) {
FastMixerStateQueue *sq = mFastMixer->sq();
FastMixerState *state = sq->begin();
if (!(state->mCommand & FastMixerState::IDLE)) {
state->mCommand = FastMixerState::COLD_IDLE;
state->mColdFutexAddr = &mFastMixerFutex;
state->mColdGen++;
mFastMixerFutex = 0;
sq->end();
// BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
if (kUseFastMixer == FastMixer_Dynamic) {
mNormalSink = mOutputSink;
}
#ifdef AUDIO_WATCHDOG
if (mAudioWatchdog != 0) {
mAudioWatchdog->pause();
}
#endif
} else {
sq->end(false /*didModify*/);
}
}
PlaybackThread::threadLoop_standby();
}
// Empty implementation for standard mixer
// Overridden for offloaded playback
void AudioFlinger::PlaybackThread::flushOutput_l()
{
}
bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
{
return false;
}
bool AudioFlinger::PlaybackThread::shouldStandby_l()
{
return !mStandby;
}
bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
{
Mutex::Autolock _l(mLock);
return waitingAsyncCallback_l();
}
// shared by MIXER and DIRECT, overridden by DUPLICATING
void AudioFlinger::PlaybackThread::threadLoop_standby()
{
ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
mOutput->stream->common.standby(&mOutput->stream->common);
if (mUseAsyncWrite != 0) {
// discard any pending drain or write ack by incrementing sequence
mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
mDrainSequence = (mDrainSequence + 2) & ~1;
ALOG_ASSERT(mCallbackThread != 0);
mCallbackThread->setWriteBlocked(mWriteAckSequence);
mCallbackThread->setDraining(mDrainSequence);
}
}
void AudioFlinger::MixerThread::threadLoop_mix()
{
// obtain the presentation timestamp of the next output buffer
int64_t pts;
status_t status = INVALID_OPERATION;
if (mNormalSink != 0) {
status = mNormalSink->getNextWriteTimestamp(&pts);
} else {
status = mOutputSink->getNextWriteTimestamp(&pts);
}
if (status != NO_ERROR) {
pts = AudioBufferProvider::kInvalidPTS;
}
// mix buffers...
mAudioMixer->process(pts);
mCurrentWriteLength = mixBufferSize;
// increase sleep time progressively when application underrun condition clears.
// Only increase sleep time if the mixer is ready for two consecutive times to avoid
// that a steady state of alternating ready/not ready conditions keeps the sleep time
// such that we would underrun the audio HAL.
if ((sleepTime == 0) && (sleepTimeShift > 0)) {
sleepTimeShift--;
}
sleepTime = 0;
standbyTime = systemTime() + standbyDelay;
//TODO: delay standby when effects have a tail
}
void AudioFlinger::MixerThread::threadLoop_sleepTime()
{
// If no tracks are ready, sleep once for the duration of an output
// buffer size, then write 0s to the output
if (sleepTime == 0) {
if (mMixerStatus == MIXER_TRACKS_ENABLED) {
sleepTime = activeSleepTime >> sleepTimeShift;
if (sleepTime < kMinThreadSleepTimeUs) {
sleepTime = kMinThreadSleepTimeUs;
}
// reduce sleep time in case of consecutive application underruns to avoid
// starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
// duration we would end up writing less data than needed by the audio HAL if
// the condition persists.
if (sleepTimeShift < kMaxThreadSleepTimeShift) {
sleepTimeShift++;
}
} else {
sleepTime = idleSleepTime;
}
} else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
memset (mMixBuffer, 0, mixBufferSize);
sleepTime = 0;
ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
"anticipated start");
}
// TODO add standby time extension fct of effect tail
}
// prepareTracks_l() must be called with ThreadBase::mLock held
AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Vector< sp<Track> > *tracksToRemove)
{
mixer_state mixerStatus = MIXER_IDLE;
// find out which tracks need to be processed
size_t count = mActiveTracks.size();
size_t mixedTracks = 0;
size_t tracksWithEffect = 0;
// counts only _active_ fast tracks
size_t fastTracks = 0;
uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
float masterVolume = mMasterVolume;
bool masterMute = mMasterMute;
if (masterMute) {
masterVolume = 0;
}
// Delegate master volume control to effect in output mix effect chain if needed
sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
if (chain != 0) {
uint32_t v = (uint32_t)(masterVolume * (1 << 24));
chain->setVolume_l(&v, &v);
masterVolume = (float)((v + (1 << 23)) >> 24);
chain.clear();
}
// prepare a new state to push
FastMixerStateQueue *sq = NULL;
FastMixerState *state = NULL;
bool didModify = false;
FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
if (mFastMixer != NULL) {
sq = mFastMixer->sq();
state = sq->begin();
}
for (size_t i=0 ; i<count ; i++) {
const sp<Track> t = mActiveTracks[i].promote();
if (t == 0) {
continue;
}
// this const just means the local variable doesn't change
Track* const track = t.get();
// process fast tracks
if (track->isFastTrack()) {
// It's theoretically possible (though unlikely) for a fast track to be created
// and then removed within the same normal mix cycle. This is not a problem, as
// the track never becomes active so it's fast mixer slot is never touched.
// The converse, of removing an (active) track and then creating a new track
// at the identical fast mixer slot within the same normal mix cycle,
// is impossible because the slot isn't marked available until the end of each cycle.
int j = track->mFastIndex;
ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
FastTrack *fastTrack = &state->mFastTracks[j];
// Determine whether the track is currently in underrun condition,
// and whether it had a recent underrun.
FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
FastTrackUnderruns underruns = ftDump->mUnderruns;
uint32_t recentFull = (underruns.mBitFields.mFull -
track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
uint32_t recentPartial = (underruns.mBitFields.mPartial -
track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
uint32_t recentUnderruns = recentPartial + recentEmpty;
track->mObservedUnderruns = underruns;
// don't count underruns that occur while stopping or pausing
// or stopped which can occur when flush() is called while active
if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
recentUnderruns > 0) {
// FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
}
// This is similar to the state machine for normal tracks,
// with a few modifications for fast tracks.
bool isActive = true;
switch (track->mState) {
case TrackBase::STOPPING_1:
// track stays active in STOPPING_1 state until first underrun
if (recentUnderruns > 0 || track->isTerminated()) {
track->mState = TrackBase::STOPPING_2;
}
break;
case TrackBase::PAUSING:
// ramp down is not yet implemented
track->setPaused();
break;
case TrackBase::RESUMING:
// ramp up is not yet implemented
track->mState = TrackBase::ACTIVE;
break;
case TrackBase::ACTIVE:
if (recentFull > 0 || recentPartial > 0) {
// track has provided at least some frames recently: reset retry count
track->mRetryCount = kMaxTrackRetries;
}
if (recentUnderruns == 0) {
// no recent underruns: stay active
break;
}
// there has recently been an underrun of some kind
if (track->sharedBuffer() == 0) {
// were any of the recent underruns "empty" (no frames available)?
if (recentEmpty == 0) {
// no, then ignore the partial underruns as they are allowed indefinitely
break;
}
// there has recently been an "empty" underrun: decrement the retry counter
if (--(track->mRetryCount) > 0) {
break;
}
// indicate to client process that the track was disabled because of underrun;
// it will then automatically call start() when data is available
android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
// remove from active list, but state remains ACTIVE [confusing but true]
isActive = false;
break;
}
// fall through
case TrackBase::STOPPING_2:
case TrackBase::PAUSED:
case TrackBase::STOPPED:
case TrackBase::FLUSHED: // flush() while active
// Check for presentation complete if track is inactive
// We have consumed all the buffers of this track.
// This would be incomplete if we auto-paused on underrun
{
size_t audioHALFrames =
(mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
size_t framesWritten = mBytesWritten / mFrameSize;
if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
// track stays in active list until presentation is complete
break;
}
}
if (track->isStopping_2()) {
track->mState = TrackBase::STOPPED;
}
if (track->isStopped()) {
// Can't reset directly, as fast mixer is still polling this track
// track->reset();
// So instead mark this track as needing to be reset after push with ack
resetMask |= 1 << i;
}
isActive = false;
break;
case TrackBase::IDLE:
default:
LOG_FATAL("unexpected track state %d", track->mState);
}
if (isActive) {
// was it previously inactive?
if (!(state->mTrackMask & (1 << j))) {
ExtendedAudioBufferProvider *eabp = track;
VolumeProvider *vp = track;
fastTrack->mBufferProvider = eabp;
fastTrack->mVolumeProvider = vp;
fastTrack->mSampleRate = track->mSampleRate;
fastTrack->mChannelMask = track->mChannelMask;
fastTrack->mGeneration++;
state->mTrackMask |= 1 << j;
didModify = true;
// no acknowledgement required for newly active tracks
}
// cache the combined master volume and stream type volume for fast mixer; this
// lacks any synchronization or barrier so VolumeProvider may read a stale value
track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
++fastTracks;
} else {
// was it previously active?
if (state->mTrackMask & (1 << j)) {
fastTrack->mBufferProvider = NULL;
fastTrack->mGeneration++;
state->mTrackMask &= ~(1 << j);
didModify = true;
// If any fast tracks were removed, we must wait for acknowledgement
// because we're about to decrement the last sp<> on those tracks.
block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
} else {
LOG_FATAL("fast track %d should have been active", j);
}
tracksToRemove->add(track);
// Avoids a misleading display in dumpsys
track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
}
continue;
}
{ // local variable scope to avoid goto warning
audio_track_cblk_t* cblk = track->cblk();
// The first time a track is added we wait
// for all its buffers to be filled before processing it
int name = track->name();
// make sure that we have enough frames to mix one full buffer.
// enforce this condition only once to enable draining the buffer in case the client
// app does not call stop() and relies on underrun to stop:
// hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
// during last round
size_t desiredFrames;
uint32_t sr = track->sampleRate();
if (sr == mSampleRate) {
desiredFrames = mNormalFrameCount;
} else {
// +1 for rounding and +1 for additional sample needed for interpolation
desiredFrames = (mNormalFrameCount * sr) / mSampleRate + 1 + 1;
// add frames already consumed but not yet released by the resampler
// because cblk->framesReady() will include these frames
desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
// the minimum track buffer size is normally twice the number of frames necessary
// to fill one buffer and the resampler should not leave more than one buffer worth
// of unreleased frames after each pass, but just in case...
ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
}
uint32_t minFrames = 1;
if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
(mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
minFrames = desiredFrames;
}
// It's not safe to call framesReady() for a static buffer track, so assume it's ready
size_t framesReady;
if (track->sharedBuffer() == 0) {
framesReady = track->framesReady();
} else if (track->isStopped()) {
framesReady = 0;
} else {
framesReady = 1;
}
if ((framesReady >= minFrames) && track->isReady() &&
!track->isPaused() && !track->isTerminated())
{
ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
mixedTracks++;
// track->mainBuffer() != mMixBuffer means there is an effect chain
// connected to the track
chain.clear();
if (track->mainBuffer() != mMixBuffer) {
chain = getEffectChain_l(track->sessionId());
// Delegate volume control to effect in track effect chain if needed
if (chain != 0) {
tracksWithEffect++;
} else {
ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
"session %d",
name, track->sessionId());
}
}
int param = AudioMixer::VOLUME;
if (track->mFillingUpStatus == Track::FS_FILLED) {
// no ramp for the first volume setting
track->mFillingUpStatus = Track::FS_ACTIVE;
if (track->mState == TrackBase::RESUMING) {
track->mState = TrackBase::ACTIVE;
param = AudioMixer::RAMP_VOLUME;
}
mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
// FIXME should not make a decision based on mServer
} else if (cblk->mServer != 0) {
// If the track is stopped before the first frame was mixed,
// do not apply ramp
param = AudioMixer::RAMP_VOLUME;
}
// compute volume for this track
uint32_t vl, vr, va;
if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
vl = vr = va = 0;
if (track->isPausing()) {
track->setPaused();
}
} else {
// read original volumes with volume control
float typeVolume = mStreamTypes[track->streamType()].volume;
float v = masterVolume * typeVolume;
AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
uint32_t vlr = proxy->getVolumeLR();
vl = vlr & 0xFFFF;
vr = vlr >> 16;
// track volumes come from shared memory, so can't be trusted and must be clamped
if (vl > MAX_GAIN_INT) {
ALOGV("Track left volume out of range: %04X", vl);
vl = MAX_GAIN_INT;
}
if (vr > MAX_GAIN_INT) {
ALOGV("Track right volume out of range: %04X", vr);
vr = MAX_GAIN_INT;
}
// now apply the master volume and stream type volume
vl = (uint32_t)(v * vl) << 12;
vr = (uint32_t)(v * vr) << 12;
// assuming master volume and stream type volume each go up to 1.0,
// vl and vr are now in 8.24 format
uint16_t sendLevel = proxy->getSendLevel_U4_12();
// send level comes from shared memory and so may be corrupt
if (sendLevel > MAX_GAIN_INT) {
ALOGV("Track send level out of range: %04X", sendLevel);
sendLevel = MAX_GAIN_INT;
}
va = (uint32_t)(v * sendLevel);
}
// Delegate volume control to effect in track effect chain if needed
if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
// Do not ramp volume if volume is controlled by effect
param = AudioMixer::VOLUME;
track->mHasVolumeController = true;
} else {
// force no volume ramp when volume controller was just disabled or removed
// from effect chain to avoid volume spike
if (track->mHasVolumeController) {
param = AudioMixer::VOLUME;
}
track->mHasVolumeController = false;
}
// Convert volumes from 8.24 to 4.12 format
// This additional clamping is needed in case chain->setVolume_l() overshot
vl = (vl + (1 << 11)) >> 12;
if (vl > MAX_GAIN_INT) {
vl = MAX_GAIN_INT;
}
vr = (vr + (1 << 11)) >> 12;
if (vr > MAX_GAIN_INT) {
vr = MAX_GAIN_INT;
}
if (va > MAX_GAIN_INT) {
va = MAX_GAIN_INT; // va is uint32_t, so no need to check for -
}
// XXX: these things DON'T need to be done each time
mAudioMixer->setBufferProvider(name, track);
mAudioMixer->enable(name);
mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
mAudioMixer->setParameter(
name,
AudioMixer::TRACK,
AudioMixer::FORMAT, (void *)track->format());
mAudioMixer->setParameter(
name,
AudioMixer::TRACK,
AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
// limit track sample rate to 2 x output sample rate, which changes at re-configuration
uint32_t maxSampleRate = 96000;//mSampleRate * 2;
uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
if (reqSampleRate == 0) {
reqSampleRate = mSampleRate;
} else if (reqSampleRate > maxSampleRate) {
reqSampleRate = maxSampleRate;
}
mAudioMixer->setParameter(
name,
AudioMixer::RESAMPLE,
AudioMixer::SAMPLE_RATE,
(void *)reqSampleRate);
mAudioMixer->setParameter(
name,
AudioMixer::TRACK,
AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
mAudioMixer->setParameter(
name,
AudioMixer::TRACK,
AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
// reset retry count
track->mRetryCount = kMaxTrackRetries;
// If one track is ready, set the mixer ready if:
// - the mixer was not ready during previous round OR
// - no other track is not ready
if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
mixerStatus != MIXER_TRACKS_ENABLED) {
mixerStatus = MIXER_TRACKS_READY;
}
} else {
if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
}
// clear effect chain input buffer if an active track underruns to avoid sending
// previous audio buffer again to effects
chain = getEffectChain_l(track->sessionId());
if (chain != 0) {
chain->clearInputBuffer();
}
ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
if ((track->sharedBuffer() != 0) || track->isTerminated() ||
track->isStopped() || track->isPaused()) {
// We have consumed all the buffers of this track.
// Remove it from the list of active tracks.
// TODO: use actual buffer filling status instead of latency when available from
// audio HAL
size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
size_t framesWritten = mBytesWritten / mFrameSize;
if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
if (track->isStopped()) {
track->reset();
}
tracksToRemove->add(track);
}
} else {
// No buffers for this track. Give it a few chances to
// fill a buffer, then remove it from active list.
if (--(track->mRetryCount) <= 0) {
ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
tracksToRemove->add(track);
// indicate to client process that the track was disabled because of underrun;
// it will then automatically call start() when data is available
android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
// If one track is not ready, mark the mixer also not ready if:
// - the mixer was ready during previous round OR
// - no other track is ready
} else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
mixerStatus != MIXER_TRACKS_READY) {
mixerStatus = MIXER_TRACKS_ENABLED;
}
}
mAudioMixer->disable(name);
}
} // local variable scope to avoid goto warning
track_is_ready: ;
}
// Push the new FastMixer state if necessary
bool pauseAudioWatchdog = false;
if (didModify) {
state->mFastTracksGen++;
// if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
if (kUseFastMixer == FastMixer_Dynamic &&
state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
state->mCommand = FastMixerState::COLD_IDLE;
state->mColdFutexAddr = &mFastMixerFutex;
state->mColdGen++;
mFastMixerFutex = 0;
if (kUseFastMixer == FastMixer_Dynamic) {
mNormalSink = mOutputSink;
}
// If we go into cold idle, need to wait for acknowledgement
// so that fast mixer stops doing I/O.
block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
pauseAudioWatchdog = true;
}
}
if (sq != NULL) {
sq->end(didModify);
sq->push(block);
}
#ifdef AUDIO_WATCHDOG
if (pauseAudioWatchdog && mAudioWatchdog != 0) {
mAudioWatchdog->pause();
}
#endif
// Now perform the deferred reset on fast tracks that have stopped
while (resetMask != 0) {
size_t i = __builtin_ctz(resetMask);
ALOG_ASSERT(i < count);
resetMask &= ~(1 << i);
sp<Track> t = mActiveTracks[i].promote();
if (t == 0) {
continue;
}
Track* track = t.get();
ALOG_ASSERT(track->isFastTrack() && track->isStopped());
track->reset();
}
// remove all the tracks that need to be...
removeTracks_l(*tracksToRemove);
// mix buffer must be cleared if all tracks are connected to an
// effect chain as in this case the mixer will not write to
// mix buffer and track effects will accumulate into it
if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
(mixedTracks == 0 && fastTracks > 0))) {
// FIXME as a performance optimization, should remember previous zero status
memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
}
// if any fast tracks, then status is ready
mMixerStatusIgnoringFastTracks = mixerStatus;
if (fastTracks > 0) {
mixerStatus = MIXER_TRACKS_READY;
}
return mixerStatus;
}
// getTrackName_l() must be called with ThreadBase::mLock held
int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId)
{
return mAudioMixer->getTrackName(channelMask, sessionId);
}
// deleteTrackName_l() must be called with ThreadBase::mLock held
void AudioFlinger::MixerThread::deleteTrackName_l(int name)
{
ALOGV("remove track (%d) and delete from mixer", name);
mAudioMixer->deleteTrackName(name);
}
// checkForNewParameters_l() must be called with ThreadBase::mLock held
bool AudioFlinger::MixerThread::checkForNewParameters_l()
{
// if !&IDLE, holds the FastMixer state to restore after new parameters processed
FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
bool reconfig = false;
while (!mNewParameters.isEmpty()) {
if (mFastMixer != NULL) {
FastMixerStateQueue *sq = mFastMixer->sq();
FastMixerState *state = sq->begin();
if (!(state->mCommand & FastMixerState::IDLE)) {
previousCommand = state->mCommand;
state->mCommand = FastMixerState::HOT_IDLE;
sq->end();
sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
} else {
sq->end(false /*didModify*/);
}
}
status_t status = NO_ERROR;
String8 keyValuePair = mNewParameters[0];
AudioParameter param = AudioParameter(keyValuePair);
int value;
if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
reconfig = true;
}
if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
status = BAD_VALUE;
} else {
reconfig = true;
}
}
if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
if ((audio_channel_mask_t) value != AUDIO_CHANNEL_OUT_STEREO) {
status = BAD_VALUE;
} else {
reconfig = true;
}
}
if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
// do not accept frame count changes if tracks are open as the track buffer
// size depends on frame count and correct behavior would not be guaranteed
// if frame count is changed after track creation
if (!mTracks.isEmpty()) {
status = INVALID_OPERATION;
} else {
reconfig = true;
}
}
if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
#ifdef ADD_BATTERY_DATA
// when changing the audio output device, call addBatteryData to notify
// the change
if (mOutDevice != value) {
uint32_t params = 0;
// check whether speaker is on
if (value & AUDIO_DEVICE_OUT_SPEAKER) {
params |= IMediaPlayerService::kBatteryDataSpeakerOn;
}
audio_devices_t deviceWithoutSpeaker
= AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
// check if any other device (except speaker) is on
if (value & deviceWithoutSpeaker ) {
params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
}
if (params != 0) {
addBatteryData(params);
}
}
#endif
// forward device change to effects that have requested to be
// aware of attached audio device.
if (value != AUDIO_DEVICE_NONE) {
mOutDevice = value;
for (size_t i = 0; i < mEffectChains.size(); i++) {
mEffectChains[i]->setDevice_l(mOutDevice);
}
}
}
if (status == NO_ERROR) {
status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
keyValuePair.string());
if (!mStandby && status == INVALID_OPERATION) {
mOutput->stream->common.standby(&mOutput->stream->common);
mStandby = true;
mBytesWritten = 0;
status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
keyValuePair.string());
}
if (status == NO_ERROR && reconfig) {
readOutputParameters();
delete mAudioMixer;
mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
for (size_t i = 0; i < mTracks.size() ; i++) {
int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId);
if (name < 0) {
break;
}
mTracks[i]->mName = name;
}
sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
}
}
mNewParameters.removeAt(0);
mParamStatus = status;
mParamCond.signal();
// wait for condition with time out in case the thread calling ThreadBase::setParameters()
// already timed out waiting for the status and will never signal the condition.
mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
}
if (!(previousCommand & FastMixerState::IDLE)) {
ALOG_ASSERT(mFastMixer != NULL);
FastMixerStateQueue *sq = mFastMixer->sq();
FastMixerState *state = sq->begin();
ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
state->mCommand = previousCommand;
sq->end();
sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
}
return reconfig;
}
void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
{
const size_t SIZE = 256;
char buffer[SIZE];
String8 result;
PlaybackThread::dumpInternals(fd, args);
snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
result.append(buffer);
write(fd, result.string(), result.size());
// Make a non-atomic copy of fast mixer dump state so it won't change underneath us
const FastMixerDumpState copy(mFastMixerDumpState);
copy.dump(fd);
#ifdef STATE_QUEUE_DUMP
// Similar for state queue
StateQueueObserverDump observerCopy = mStateQueueObserverDump;
observerCopy.dump(fd);
StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
mutatorCopy.dump(fd);
#endif
#ifdef TEE_SINK
// Write the tee output to a .wav file
dumpTee(fd, mTeeSource, mId);
#endif
#ifdef AUDIO_WATCHDOG
if (mAudioWatchdog != 0) {
// Make a non-atomic copy of audio watchdog dump so it won't change underneath us
AudioWatchdogDump wdCopy = mAudioWatchdogDump;
wdCopy.dump(fd);
}
#endif
}
uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
{
return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
}
uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
{
return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
}
void AudioFlinger::MixerThread::cacheParameters_l()
{
PlaybackThread::cacheParameters_l();
// FIXME: Relaxed timing because of a certain device that can't meet latency
// Should be reduced to 2x after the vendor fixes the driver issue
// increase threshold again due to low power audio mode. The way this warning
// threshold is calculated and its usefulness should be reconsidered anyway.
maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
}
// ----------------------------------------------------------------------------
AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
: PlaybackThread(audioFlinger, output, id, device, DIRECT)
// mLeftVolFloat, mRightVolFloat
{
}
AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
ThreadBase::type_t type)
: PlaybackThread(audioFlinger, output, id, device, type)
// mLeftVolFloat, mRightVolFloat
{
}
AudioFlinger::DirectOutputThread::~DirectOutputThread()
{
}
void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
{
audio_track_cblk_t* cblk = track->cblk();
float left, right;
if (mMasterMute || mStreamTypes[track->streamType()].mute) {
left = right = 0;
} else {
float typeVolume = mStreamTypes[track->streamType()].volume;
float v = mMasterVolume * typeVolume;
AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
uint32_t vlr = proxy->getVolumeLR();
float v_clamped = v * (vlr & 0xFFFF);
if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
left = v_clamped/MAX_GAIN;
v_clamped = v * (vlr >> 16);
if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
right = v_clamped/MAX_GAIN;
}
if (lastTrack) {
if (left != mLeftVolFloat || right != mRightVolFloat) {
mLeftVolFloat = left;
mRightVolFloat = right;
// Convert volumes from float to 8.24
uint32_t vl = (uint32_t)(left * (1 << 24));
uint32_t vr = (uint32_t)(right * (1 << 24));
// Delegate volume control to effect in track effect chain if needed
// only one effect chain can be present on DirectOutputThread, so if
// there is one, the track is connected to it
if (!mEffectChains.isEmpty()) {
mEffectChains[0]->setVolume_l(&vl, &vr);
left = (float)vl / (1 << 24);
right = (float)vr / (1 << 24);
}
if (mOutput->stream->set_volume) {
mOutput->stream->set_volume(mOutput->stream, left, right);
}
}
}
}
AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
Vector< sp<Track> > *tracksToRemove
)
{
size_t count = mActiveTracks.size();
mixer_state mixerStatus = MIXER_IDLE;
// find out which tracks need to be processed
for (size_t i = 0; i < count; i++) {
sp<Track> t = mActiveTracks[i].promote();
// The track died recently
if (t == 0) {
continue;
}
Track* const track = t.get();
audio_track_cblk_t* cblk = track->cblk();
// Only consider last track started for volume and mixer state control.
// In theory an older track could underrun and restart after the new one starts
// but as we only care about the transition phase between two tracks on a
// direct output, it is not a problem to ignore the underrun case.
sp<Track> l = mLatestActiveTrack.promote();
bool last = l.get() == track;
// The first time a track is added we wait
// for all its buffers to be filled before processing it
uint32_t minFrames;
if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
minFrames = mNormalFrameCount;
} else {
minFrames = 1;
}
if ((track->framesReady() >= minFrames) && track->isReady() &&
!track->isPaused() && !track->isTerminated())
{
ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
if (track->mFillingUpStatus == Track::FS_FILLED) {
track->mFillingUpStatus = Track::FS_ACTIVE;
// make sure processVolume_l() will apply new volume even if 0
mLeftVolFloat = mRightVolFloat = -1.0;
if (track->mState == TrackBase::RESUMING) {
track->mState = TrackBase::ACTIVE;
}
}
// compute volume for this track
processVolume_l(track, last);
if (last) {
// reset retry count
track->mRetryCount = kMaxTrackRetriesDirect;
mActiveTrack = t;
mixerStatus = MIXER_TRACKS_READY;
}
} else {
// clear effect chain input buffer if the last active track started underruns
// to avoid sending previous audio buffer again to effects
if (!mEffectChains.isEmpty() && last) {
mEffectChains[0]->clearInputBuffer();
}
ALOGVV("track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
if ((track->sharedBuffer() != 0) || track->isTerminated() ||
track->isStopped() || track->isPaused()) {
// We have consumed all the buffers of this track.
// Remove it from the list of active tracks.
// TODO: implement behavior for compressed audio
size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
size_t framesWritten = mBytesWritten / mFrameSize;
if (mStandby || !last ||
track->presentationComplete(framesWritten, audioHALFrames)) {
if (track->isStopped()) {
track->reset();
}
tracksToRemove->add(track);
}
} else {
// No buffers for this track. Give it a few chances to
// fill a buffer, then remove it from active list.
// Only consider last track started for mixer state control
if (--(track->mRetryCount) <= 0) {
ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
tracksToRemove->add(track);
// indicate to client process that the track was disabled because of underrun;
// it will then automatically call start() when data is available
android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
} else if (last) {
mixerStatus = MIXER_TRACKS_ENABLED;
}
}
}
}
// remove all the tracks that need to be...
removeTracks_l(*tracksToRemove);
return mixerStatus;
}
void AudioFlinger::DirectOutputThread::threadLoop_mix()
{
size_t frameCount = mFrameCount;
int8_t *curBuf = (int8_t *)mMixBuffer;
// output audio to hardware
while (frameCount) {
AudioBufferProvider::Buffer buffer;
buffer.frameCount = frameCount;
mActiveTrack->getNextBuffer(&buffer);
if (buffer.raw == NULL) {
memset(curBuf, 0, frameCount * mFrameSize);
break;
}
memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
frameCount -= buffer.frameCount;
curBuf += buffer.frameCount * mFrameSize;
mActiveTrack->releaseBuffer(&buffer);
}
mCurrentWriteLength = curBuf - (int8_t *)mMixBuffer;
sleepTime = 0;
standbyTime = systemTime() + standbyDelay;
mActiveTrack.clear();
}
void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
{
if (sleepTime == 0) {
if (mMixerStatus == MIXER_TRACKS_ENABLED) {
sleepTime = activeSleepTime;
} else {
sleepTime = idleSleepTime;
}
} else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
memset(mMixBuffer, 0, mFrameCount * mFrameSize);
sleepTime = 0;
}
}
// getTrackName_l() must be called with ThreadBase::mLock held
int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask,
int sessionId)
{
return 0;
}
// deleteTrackName_l() must be called with ThreadBase::mLock held
void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
{
}
// checkForNewParameters_l() must be called with ThreadBase::mLock held
bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
{
bool reconfig = false;
while (!mNewParameters.isEmpty()) {
status_t status = NO_ERROR;
String8 keyValuePair = mNewParameters[0];
AudioParameter param = AudioParameter(keyValuePair);
int value;
if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
// do not accept frame count changes if tracks are open as the track buffer
// size depends on frame count and correct behavior would not be garantied
// if frame count is changed after track creation
if (!mTracks.isEmpty()) {
status = INVALID_OPERATION;
} else {
reconfig = true;
}
}
if (status == NO_ERROR) {
status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
keyValuePair.string());
if (!mStandby && status == INVALID_OPERATION) {
mOutput->stream->common.standby(&mOutput->stream->common);
mStandby = true;
mBytesWritten = 0;
status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
keyValuePair.string());
}
if (status == NO_ERROR && reconfig) {
readOutputParameters();
sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
}
}
mNewParameters.removeAt(0);
mParamStatus = status;
mParamCond.signal();
// wait for condition with time out in case the thread calling ThreadBase::setParameters()
// already timed out waiting for the status and will never signal the condition.
mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
}
return reconfig;
}
uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
{
uint32_t time;
if (audio_is_linear_pcm(mFormat)) {
time = PlaybackThread::activeSleepTimeUs();
} else {
time = 10000;
}
return time;
}
uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
{
uint32_t time;
if (audio_is_linear_pcm(mFormat)) {
time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
} else {
time = 10000;
}
return time;
}
uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
{
uint32_t time;
if (audio_is_linear_pcm(mFormat)) {
time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
} else {
time = 10000;
}
return time;
}
void AudioFlinger::DirectOutputThread::cacheParameters_l()
{
PlaybackThread::cacheParameters_l();
// use shorter standby delay as on normal output to release
// hardware resources as soon as possible
if (audio_is_linear_pcm(mFormat)) {
standbyDelay = microseconds(activeSleepTime*2);
} else {
standbyDelay = kOffloadStandbyDelayNs;
}
}
// ----------------------------------------------------------------------------
AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
const wp<AudioFlinger::PlaybackThread>& playbackThread)
: Thread(false /*canCallJava*/),
mPlaybackThread(playbackThread),
mWriteAckSequence(0),
mDrainSequence(0)
{
}
AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
{
}
void AudioFlinger::AsyncCallbackThread::onFirstRef()
{
run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
}
bool AudioFlinger::AsyncCallbackThread::threadLoop()
{
while (!exitPending()) {
uint32_t writeAckSequence;
uint32_t drainSequence;
{
Mutex::Autolock _l(mLock);
mWaitWorkCV.wait(mLock);
if (exitPending()) {
break;
}
ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
mWriteAckSequence, mDrainSequence);
writeAckSequence = mWriteAckSequence;
mWriteAckSequence &= ~1;
drainSequence = mDrainSequence;
mDrainSequence &= ~1;
}
{
sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
if (playbackThread != 0) {
if (writeAckSequence & 1) {
playbackThread->resetWriteBlocked(writeAckSequence >> 1);
}
if (drainSequence & 1) {
playbackThread->resetDraining(drainSequence >> 1);
}
}
}
}
return false;
}
void AudioFlinger::AsyncCallbackThread::exit()
{
ALOGV("AsyncCallbackThread::exit");
Mutex::Autolock _l(mLock);
requestExit();
mWaitWorkCV.broadcast();
}
void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
{
Mutex::Autolock _l(mLock);
// bit 0 is cleared
mWriteAckSequence = sequence << 1;
}
void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
{
Mutex::Autolock _l(mLock);
// ignore unexpected callbacks
if (mWriteAckSequence & 2) {
mWriteAckSequence |= 1;
mWaitWorkCV.signal();
}
}
void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
{
Mutex::Autolock _l(mLock);
// bit 0 is cleared
mDrainSequence = sequence << 1;
}
void AudioFlinger::AsyncCallbackThread::resetDraining()
{
Mutex::Autolock _l(mLock);
// ignore unexpected callbacks
if (mDrainSequence & 2) {
mDrainSequence |= 1;
mWaitWorkCV.signal();
}
}
// ----------------------------------------------------------------------------
AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
: DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
mHwPaused(false),
mFlushPending(false),
mPausedBytesRemaining(0),
mPreviousTrack(NULL)
{
//FIXME: mStandby should be set to true by ThreadBase constructor
mStandby = true;
}
void AudioFlinger::OffloadThread::threadLoop_exit()
{
if (mFlushPending || mHwPaused) {
// If a flush is pending or track was paused, just discard buffered data
flushHw_l();
} else {
mMixerStatus = MIXER_DRAIN_ALL;
threadLoop_drain();
}
mCallbackThread->exit();
PlaybackThread::threadLoop_exit();
}
AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
Vector< sp<Track> > *tracksToRemove
)
{
size_t count = mActiveTracks.size();
mixer_state mixerStatus = MIXER_IDLE;
bool doHwPause = false;
bool doHwResume = false;
ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
// find out which tracks need to be processed
for (size_t i = 0; i < count; i++) {
sp<Track> t = mActiveTracks[i].promote();
// The track died recently
if (t == 0) {
continue;
}
Track* const track = t.get();
audio_track_cblk_t* cblk = track->cblk();
// Only consider last track started for volume and mixer state control.
// In theory an older track could underrun and restart after the new one starts
// but as we only care about the transition phase between two tracks on a
// direct output, it is not a problem to ignore the underrun case.
sp<Track> l = mLatestActiveTrack.promote();
bool last = l.get() == track;
if (track->isPausing()) {
track->setPaused();
if (last) {
if (!mHwPaused) {
doHwPause = true;
mHwPaused = true;
}
// If we were part way through writing the mixbuffer to
// the HAL we must save this until we resume
// BUG - this will be wrong if a different track is made active,
// in that case we want to discard the pending data in the
// mixbuffer and tell the client to present it again when the
// track is resumed
mPausedWriteLength = mCurrentWriteLength;
mPausedBytesRemaining = mBytesRemaining;
mBytesRemaining = 0; // stop writing
}
tracksToRemove->add(track);
} else if (track->framesReady() && track->isReady() &&
!track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
if (track->mFillingUpStatus == Track::FS_FILLED) {
track->mFillingUpStatus = Track::FS_ACTIVE;
// make sure processVolume_l() will apply new volume even if 0
mLeftVolFloat = mRightVolFloat = -1.0;
if (track->mState == TrackBase::RESUMING) {
track->mState = TrackBase::ACTIVE;
if (last) {
if (mPausedBytesRemaining) {
// Need to continue write that was interrupted
mCurrentWriteLength = mPausedWriteLength;
mBytesRemaining = mPausedBytesRemaining;
mPausedBytesRemaining = 0;
}
if (mHwPaused) {
doHwResume = true;
mHwPaused = false;
// threadLoop_mix() will handle the case that we need to
// resume an interrupted write
}
// enable write to audio HAL
sleepTime = 0;
}
}
}
if (last) {
sp<Track> previousTrack = mPreviousTrack.promote();
if (previousTrack != 0) {
if (track != previousTrack.get()) {
// Flush any data still being written from last track
mBytesRemaining = 0;
if (mPausedBytesRemaining) {
// Last track was paused so we also need to flush saved
// mixbuffer state and invalidate track so that it will
// re-submit that unwritten data when it is next resumed
mPausedBytesRemaining = 0;
// Invalidate is a bit drastic - would be more efficient
// to have a flag to tell client that some of the
// previously written data was lost
previousTrack->invalidate();
}
// flush data already sent to the DSP if changing audio session as audio
// comes from a different source. Also invalidate previous track to force a
// seek when resuming.
if (previousTrack->sessionId() != track->sessionId()) {
previousTrack->invalidate();
mFlushPending = true;
}
}
}
mPreviousTrack = track;
// reset retry count
track->mRetryCount = kMaxTrackRetriesOffload;
mActiveTrack = t;
mixerStatus = MIXER_TRACKS_READY;
}
} else {
ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
if (track->isStopping_1()) {
// Hardware buffer can hold a large amount of audio so we must
// wait for all current track's data to drain before we say
// that the track is stopped.
if (mBytesRemaining == 0) {
// Only start draining when all data in mixbuffer
// has been written
ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
// do not drain if no data was ever sent to HAL (mStandby == true)
if (last && !mStandby) {
// do not modify drain sequence if we are already draining. This happens
// when resuming from pause after drain.
if ((mDrainSequence & 1) == 0) {
sleepTime = 0;
standbyTime = systemTime() + standbyDelay;
mixerStatus = MIXER_DRAIN_TRACK;
mDrainSequence += 2;
}
if (mHwPaused) {
// It is possible to move from PAUSED to STOPPING_1 without
// a resume so we must ensure hardware is running
doHwResume = true;
mHwPaused = false;
}
}
}
} else if (track->isStopping_2()) {
// Drain has completed or we are in standby, signal presentation complete
if (!(mDrainSequence & 1) || !last || mStandby) {
track->mState = TrackBase::STOPPED;
size_t audioHALFrames =
(mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
size_t framesWritten =
mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
track->presentationComplete(framesWritten, audioHALFrames);
track->reset();
tracksToRemove->add(track);
}
} else {
// No buffers for this track. Give it a few chances to
// fill a buffer, then remove it from active list.
if (--(track->mRetryCount) <= 0) {
ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
track->name());
tracksToRemove->add(track);
// indicate to client process that the track was disabled because of underrun;
// it will then automatically call start() when data is available
android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
} else if (last){
mixerStatus = MIXER_TRACKS_ENABLED;
}
}
}
// compute volume for this track
processVolume_l(track, last);
}
// make sure the pause/flush/resume sequence is executed in the right order.
// If a flush is pending and a track is active but the HW is not paused, force a HW pause
// before flush and then resume HW. This can happen in case of pause/flush/resume
// if resume is received before pause is executed.
if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
mOutput->stream->pause(mOutput->stream);
if (!doHwPause) {
doHwResume = true;
}
}
if (mFlushPending) {
flushHw_l();
mFlushPending = false;
}
if (!mStandby && doHwResume) {
mOutput->stream->resume(mOutput->stream);
}
// remove all the tracks that need to be...
removeTracks_l(*tracksToRemove);
return mixerStatus;
}
void AudioFlinger::OffloadThread::flushOutput_l()
{
mFlushPending = true;
}
// must be called with thread mutex locked
bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
{
ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
mWriteAckSequence, mDrainSequence);
if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
return true;
}
return false;
}
// must be called with thread mutex locked
bool AudioFlinger::OffloadThread::shouldStandby_l()
{
bool TrackPaused = false;
// do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
// after a timeout and we will enter standby then.
if (mTracks.size() > 0) {
TrackPaused = mTracks[mTracks.size() - 1]->isPaused();
}
return !mStandby && !TrackPaused;
}
bool AudioFlinger::OffloadThread::waitingAsyncCallback()
{
Mutex::Autolock _l(mLock);
return waitingAsyncCallback_l();
}
void AudioFlinger::OffloadThread::flushHw_l()
{
mOutput->stream->flush(mOutput->stream);
// Flush anything still waiting in the mixbuffer
mCurrentWriteLength = 0;
mBytesRemaining = 0;
mPausedWriteLength = 0;
mPausedBytesRemaining = 0;
if (mUseAsyncWrite) {
// discard any pending drain or write ack by incrementing sequence
mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
mDrainSequence = (mDrainSequence + 2) & ~1;
ALOG_ASSERT(mCallbackThread != 0);
mCallbackThread->setWriteBlocked(mWriteAckSequence);
mCallbackThread->setDraining(mDrainSequence);
}
}
// ----------------------------------------------------------------------------
AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
: MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
DUPLICATING),
mWaitTimeMs(UINT_MAX)
{
addOutputTrack(mainThread);
}
AudioFlinger::DuplicatingThread::~DuplicatingThread()
{
for (size_t i = 0; i < mOutputTracks.size(); i++) {
mOutputTracks[i]->destroy();
}
}
void AudioFlinger::DuplicatingThread::threadLoop_mix()
{
// mix buffers...
if (outputsReady(outputTracks)) {
mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
} else {
memset(mMixBuffer, 0, mixBufferSize);
}
sleepTime = 0;
writeFrames = mNormalFrameCount;
mCurrentWriteLength = mixBufferSize;
standbyTime = systemTime() + standbyDelay;
}
void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
{
if (sleepTime == 0) {
if (mMixerStatus == MIXER_TRACKS_ENABLED) {
sleepTime = activeSleepTime;
} else {
sleepTime = idleSleepTime;
}
} else if (mBytesWritten != 0) {
if (mMixerStatus == MIXER_TRACKS_ENABLED) {
writeFrames = mNormalFrameCount;
memset(mMixBuffer, 0, mixBufferSize);
} else {
// flush remaining overflow buffers in output tracks
writeFrames = 0;
}
sleepTime = 0;
}
}
ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
{
for (size_t i = 0; i < outputTracks.size(); i++) {
outputTracks[i]->write(mMixBuffer, writeFrames);
}
mStandby = false;
return (ssize_t)mixBufferSize;
}
void AudioFlinger::DuplicatingThread::threadLoop_standby()
{
// DuplicatingThread implements standby by stopping all tracks
for (size_t i = 0; i < outputTracks.size(); i++) {
outputTracks[i]->stop();
}
}
void AudioFlinger::DuplicatingThread::saveOutputTracks()
{
outputTracks = mOutputTracks;
}
void AudioFlinger::DuplicatingThread::clearOutputTracks()
{
outputTracks.clear();
}
void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
{
Mutex::Autolock _l(mLock);
// FIXME explain this formula
size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
OutputTrack *outputTrack = new OutputTrack(thread,
this,
mSampleRate,
mFormat,
mChannelMask,
frameCount,
IPCThreadState::self()->getCallingUid());
if (outputTrack->cblk() != NULL) {
thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
mOutputTracks.add(outputTrack);
ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
updateWaitTime_l();
}
}
void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
{
Mutex::Autolock _l(mLock);
for (size_t i = 0; i < mOutputTracks.size(); i++) {
if (mOutputTracks[i]->thread() == thread) {
mOutputTracks[i]->destroy();
mOutputTracks.removeAt(i);
updateWaitTime_l();
return;
}
}
ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
}
// caller must hold mLock
void AudioFlinger::DuplicatingThread::updateWaitTime_l()
{
mWaitTimeMs = UINT_MAX;
for (size_t i = 0; i < mOutputTracks.size(); i++) {
sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
if (strong != 0) {
uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
if (waitTimeMs < mWaitTimeMs) {
mWaitTimeMs = waitTimeMs;
}
}
}
}
bool AudioFlinger::DuplicatingThread::outputsReady(
const SortedVector< sp<OutputTrack> > &outputTracks)
{
for (size_t i = 0; i < outputTracks.size(); i++) {
sp<ThreadBase> thread = outputTracks[i]->thread().promote();
if (thread == 0) {
ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
outputTracks[i].get());
return false;
}
PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
// see note at standby() declaration
if (playbackThread->standby() && !playbackThread->isSuspended()) {
ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
thread.get());
return false;
}
}
return true;
}
uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
{
return (mWaitTimeMs * 1000) / 2;
}
void AudioFlinger::DuplicatingThread::cacheParameters_l()
{
// updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
updateWaitTime_l();
MixerThread::cacheParameters_l();
}
// ----------------------------------------------------------------------------
// Record
// ----------------------------------------------------------------------------
AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
AudioStreamIn *input,
uint32_t sampleRate,
audio_channel_mask_t channelMask,
audio_io_handle_t id,
audio_devices_t outDevice,
audio_devices_t inDevice
#ifdef TEE_SINK
, const sp<NBAIO_Sink>& teeSink
#endif
) :
ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
mInput(input), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
// mRsmpInIndex and mBufferSize set by readInputParameters()
mReqChannelCount(popcount(channelMask)),
mReqSampleRate(sampleRate)
// mBytesRead is only meaningful while active, and so is cleared in start()
// (but might be better to also clear here for dump?)
#ifdef TEE_SINK
, mTeeSink(teeSink)
#endif
{
snprintf(mName, kNameLength, "AudioIn_%X", id);
readInputParameters();
}
AudioFlinger::RecordThread::~RecordThread()
{
delete[] mRsmpInBuffer;
delete mResampler;
delete[] mRsmpOutBuffer;
}
void AudioFlinger::RecordThread::onFirstRef()
{
run(mName, PRIORITY_URGENT_AUDIO);
}
status_t AudioFlinger::RecordThread::readyToRun()
{
status_t status = initCheck();
ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
return status;
}
bool AudioFlinger::RecordThread::threadLoop()
{
AudioBufferProvider::Buffer buffer;
sp<RecordTrack> activeTrack;
Vector< sp<EffectChain> > effectChains;
nsecs_t lastWarning = 0;
inputStandBy();
{
Mutex::Autolock _l(mLock);
activeTrack = mActiveTrack;
acquireWakeLock_l(activeTrack != 0 ? activeTrack->uid() : -1);
}
// used to verify we've read at least once before evaluating how many bytes were read
bool readOnce = false;
// start recording
while (!exitPending()) {
processConfigEvents();
{ // scope for mLock
Mutex::Autolock _l(mLock);
checkForNewParameters_l();
if (mActiveTrack != 0 && activeTrack != mActiveTrack) {
SortedVector<int> tmp;
tmp.add(mActiveTrack->uid());
updateWakeLockUids_l(tmp);
}
activeTrack = mActiveTrack;
if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
standby();
if (exitPending()) {
break;
}
releaseWakeLock_l();
ALOGV("RecordThread: loop stopping");
// go to sleep
mWaitWorkCV.wait(mLock);
ALOGV("RecordThread: loop starting");
acquireWakeLock_l(mActiveTrack != 0 ? mActiveTrack->uid() : -1);
continue;
}
if (mActiveTrack != 0) {
if (mActiveTrack->isTerminated()) {
removeTrack_l(mActiveTrack);
mActiveTrack.clear();
} else if (mActiveTrack->mState == TrackBase::PAUSING) {
standby();
mActiveTrack.clear();
mStartStopCond.broadcast();
} else if (mActiveTrack->mState == TrackBase::RESUMING) {
if (mReqChannelCount != mActiveTrack->channelCount()) {
mActiveTrack.clear();
mStartStopCond.broadcast();
} else if (readOnce) {
// record start succeeds only if first read from audio input
// succeeds
if (mBytesRead >= 0) {
mActiveTrack->mState = TrackBase::ACTIVE;
} else {
mActiveTrack.clear();
}
mStartStopCond.broadcast();
}
mStandby = false;
}
}
lockEffectChains_l(effectChains);
}
if (mActiveTrack != 0) {
if (mActiveTrack->mState != TrackBase::ACTIVE &&
mActiveTrack->mState != TrackBase::RESUMING) {
unlockEffectChains(effectChains);
usleep(kRecordThreadSleepUs);
continue;
}
for (size_t i = 0; i < effectChains.size(); i ++) {
effectChains[i]->process_l();
}
buffer.frameCount = mFrameCount;
status_t status = mActiveTrack->getNextBuffer(&buffer);
if (status == NO_ERROR) {
readOnce = true;
size_t framesOut = buffer.frameCount;
if (mResampler == NULL) {
// no resampling
while (framesOut) {
size_t framesIn = mFrameCount - mRsmpInIndex;
if (framesIn) {
int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) *
mActiveTrack->mFrameSize;
if (framesIn > framesOut)
framesIn = framesOut;
mRsmpInIndex += framesIn;
framesOut -= framesIn;
if (mChannelCount == mReqChannelCount) {
memcpy(dst, src, framesIn * mFrameSize);
} else {
if (mChannelCount == 1) {
upmix_to_stereo_i16_from_mono_i16((int16_t *)dst,
(int16_t *)src, framesIn);
} else {
downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
(int16_t *)src, framesIn);
}
}
}
if (framesOut && mFrameCount == mRsmpInIndex) {
void *readInto;
if (framesOut == mFrameCount && mChannelCount == mReqChannelCount) {
readInto = buffer.raw;
framesOut = 0;
} else {
readInto = mRsmpInBuffer;
mRsmpInIndex = 0;
}
mBytesRead = mInput->stream->read(mInput->stream, readInto,
mBufferSize);
if (mBytesRead <= 0) {
if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE))
{
ALOGE("Error reading audio input");
// Force input into standby so that it tries to
// recover at next read attempt
inputStandBy();
usleep(kRecordThreadSleepUs);
}
mRsmpInIndex = mFrameCount;
framesOut = 0;
buffer.frameCount = 0;
}
#ifdef TEE_SINK
else if (mTeeSink != 0) {
(void) mTeeSink->write(readInto,
mBytesRead >> Format_frameBitShift(mTeeSink->format()));
}
#endif
}
}
} else {
// resampling
// resampler accumulates, but we only have one source track
memset(mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
// alter output frame count as if we were expecting stereo samples
if (mChannelCount == 1 && mReqChannelCount == 1) {
framesOut >>= 1;
}
mResampler->resample(mRsmpOutBuffer, framesOut,
this /* AudioBufferProvider* */);
// ditherAndClamp() works as long as all buffers returned by
// mActiveTrack->getNextBuffer() are 32 bit aligned which should be always true.
if (mChannelCount == 2 && mReqChannelCount == 1) {
// temporarily type pun mRsmpOutBuffer from Q19.12 to int16_t
ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
// the resampler always outputs stereo samples:
// do post stereo to mono conversion
downmix_to_mono_i16_from_stereo_i16(buffer.i16, (int16_t *)mRsmpOutBuffer,
framesOut);
} else {
ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
}
// now done with mRsmpOutBuffer
}
if (mFramestoDrop == 0) {
mActiveTrack->releaseBuffer(&buffer);
} else {
if (mFramestoDrop > 0) {
mFramestoDrop -= buffer.frameCount;
if (mFramestoDrop <= 0) {
clearSyncStartEvent();
}
} else {
mFramestoDrop += buffer.frameCount;
if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
mSyncStartEvent->isCancelled()) {
ALOGW("Synced record %s, session %d, trigger session %d",
(mFramestoDrop >= 0) ? "timed out" : "cancelled",
mActiveTrack->sessionId(),
(mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
clearSyncStartEvent();
}
}
}
mActiveTrack->clearOverflow();
}
// client isn't retrieving buffers fast enough
else {
if (!mActiveTrack->setOverflow()) {
nsecs_t now = systemTime();
if ((now - lastWarning) > kWarningThrottleNs) {
ALOGW("RecordThread: buffer overflow");
lastWarning = now;
}
}
// Release the processor for a while before asking for a new buffer.
// This will give the application more chance to read from the buffer and
// clear the overflow.
usleep(kRecordThreadSleepUs);
}
}
// enable changes in effect chain
unlockEffectChains(effectChains);
effectChains.clear();
}
standby();
{
Mutex::Autolock _l(mLock);
for (size_t i = 0; i < mTracks.size(); i++) {
sp<RecordTrack> track = mTracks[i];
track->invalidate();
}
mActiveTrack.clear();
mStartStopCond.broadcast();
}
releaseWakeLock();
ALOGV("RecordThread %p exiting", this);
return false;
}
void AudioFlinger::RecordThread::standby()
{
if (!mStandby) {
inputStandBy();
mStandby = true;
}
}
void AudioFlinger::RecordThread::inputStandBy()
{
mInput->stream->common.standby(&mInput->stream->common);
}
sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
const sp<AudioFlinger::Client>& client,
uint32_t sampleRate,
audio_format_t format,
audio_channel_mask_t channelMask,
size_t frameCount,
int sessionId,
int uid,
IAudioFlinger::track_flags_t *flags,
pid_t tid,
status_t *status)
{
sp<RecordTrack> track;
status_t lStatus;
lStatus = initCheck();
if (lStatus != NO_ERROR) {
ALOGE("createRecordTrack_l() audio driver not initialized");
goto Exit;
}
// client expresses a preference for FAST, but we get the final say
if (*flags & IAudioFlinger::TRACK_FAST) {
if (
// use case: callback handler and frame count is default or at least as large as HAL
(
(tid != -1) &&
((frameCount == 0) ||
(frameCount >= (mFrameCount * kFastTrackMultiplier)))
) &&
// FIXME when record supports non-PCM data, also check for audio_is_linear_pcm(format)
// mono or stereo
( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
(channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
// hardware sample rate
(sampleRate == mSampleRate) &&
// record thread has an associated fast recorder
hasFastRecorder()
// FIXME test that RecordThread for this fast track has a capable output HAL
// FIXME add a permission test also?
) {
// if frameCount not specified, then it defaults to fast recorder (HAL) frame count
if (frameCount == 0) {
frameCount = mFrameCount * kFastTrackMultiplier;
}
ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
frameCount, mFrameCount);
} else {
ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%d "
"mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
"hasFastRecorder=%d tid=%d",
frameCount, mFrameCount, format,
audio_is_linear_pcm(format),
channelMask, sampleRate, mSampleRate, hasFastRecorder(), tid);
*flags &= ~IAudioFlinger::TRACK_FAST;
// For compatibility with AudioRecord calculation, buffer depth is forced
// to be at least 2 x the record thread frame count and cover audio hardware latency.
// This is probably too conservative, but legacy application code may depend on it.
// If you change this calculation, also review the start threshold which is related.
uint32_t latencyMs = 50; // FIXME mInput->stream->get_latency(mInput->stream);
size_t mNormalFrameCount = 2048; // FIXME
uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
if (minBufCount < 2) {
minBufCount = 2;
}
size_t minFrameCount = mNormalFrameCount * minBufCount;
if (frameCount < minFrameCount) {
frameCount = minFrameCount;
}
}
}
// FIXME use flags and tid similar to createTrack_l()
{ // scope for mLock
Mutex::Autolock _l(mLock);
track = new RecordTrack(this, client, sampleRate,
format, channelMask, frameCount, sessionId, uid);
if (track->getCblk() == 0) {
ALOGE("createRecordTrack_l() no control block");
lStatus = NO_MEMORY;
track.clear();
goto Exit;
}
mTracks.add(track);
// disable AEC and NS if the device is a BT SCO headset supporting those pre processings
bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
mAudioFlinger->btNrecIsOff();
setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
pid_t callingPid = IPCThreadState::self()->getCallingPid();
// we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
// so ask activity manager to do this on our behalf
sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
}
}
lStatus = NO_ERROR;
Exit:
if (status) {
*status = lStatus;
}
return track;
}
status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
AudioSystem::sync_event_t event,
int triggerSession)
{
ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
sp<ThreadBase> strongMe = this;
status_t status = NO_ERROR;
if (event == AudioSystem::SYNC_EVENT_NONE) {
clearSyncStartEvent();
} else if (event != AudioSystem::SYNC_EVENT_SAME) {
mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
triggerSession,
recordTrack->sessionId(),
syncStartEventCallback,
this);
// Sync event can be cancelled by the trigger session if the track is not in a
// compatible state in which case we start record immediately
if (mSyncStartEvent->isCancelled()) {
clearSyncStartEvent();
} else {
// do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
}
}
{
AutoMutex lock(mLock);
if (mActiveTrack != 0) {
if (recordTrack != mActiveTrack.get()) {
status = -EBUSY;
} else if (mActiveTrack->mState == TrackBase::PAUSING) {
mActiveTrack->mState = TrackBase::ACTIVE;
}
return status;
}
recordTrack->mState = TrackBase::IDLE;
mActiveTrack = recordTrack;
mLock.unlock();
status_t status = AudioSystem::startInput(mId);
mLock.lock();
if (status != NO_ERROR) {
mActiveTrack.clear();
clearSyncStartEvent();
return status;
}
mRsmpInIndex = mFrameCount;
mBytesRead = 0;
if (mResampler != NULL) {
mResampler->reset();
}
mActiveTrack->mState = TrackBase::RESUMING;
// signal thread to start
ALOGV("Signal record thread");
mWaitWorkCV.broadcast();
// do not wait for mStartStopCond if exiting
if (exitPending()) {
mActiveTrack.clear();
status = INVALID_OPERATION;
goto startError;
}
mStartStopCond.wait(mLock);
if (mActiveTrack == 0) {
ALOGV("Record failed to start");
status = BAD_VALUE;
goto startError;
}
ALOGV("Record started OK");
return status;
}
startError:
AudioSystem::stopInput(mId);
clearSyncStartEvent();
return status;
}
void AudioFlinger::RecordThread::clearSyncStartEvent()
{
if (mSyncStartEvent != 0) {
mSyncStartEvent->cancel();
}
mSyncStartEvent.clear();
mFramestoDrop = 0;
}
void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
{
sp<SyncEvent> strongEvent = event.promote();
if (strongEvent != 0) {
RecordThread *me = (RecordThread *)strongEvent->cookie();
me->handleSyncStartEvent(strongEvent);
}
}
void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
{
if (event == mSyncStartEvent) {
// TODO: use actual buffer filling status instead of 2 buffers when info is available
// from audio HAL
mFramestoDrop = mFrameCount * 2;
}
}
bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
ALOGV("RecordThread::stop");
AutoMutex _l(mLock);
if (recordTrack != mActiveTrack.get() || recordTrack->mState == TrackBase::PAUSING) {
return false;
}
recordTrack->mState = TrackBase::PAUSING;
// do not wait for mStartStopCond if exiting
if (exitPending()) {
return true;
}
mStartStopCond.wait(mLock);
// if we have been restarted, recordTrack == mActiveTrack.get() here
if (exitPending() || recordTrack != mActiveTrack.get()) {
ALOGV("Record stopped OK");
return true;
}
return false;
}
bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event) const
{
return false;
}
status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
{
#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
if (!isValidSyncEvent(event)) {
return BAD_VALUE;
}
int eventSession = event->triggerSession();
status_t ret = NAME_NOT_FOUND;
Mutex::Autolock _l(mLock);
for (size_t i = 0; i < mTracks.size(); i++) {
sp<RecordTrack> track = mTracks[i];
if (eventSession == track->sessionId()) {
(void) track->setSyncEvent(event);
ret = NO_ERROR;
}
}
return ret;
#else
return BAD_VALUE;
#endif
}
// destroyTrack_l() must be called with ThreadBase::mLock held
void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
{
track->terminate();
track->mState = TrackBase::STOPPED;
// active tracks are removed by threadLoop()
if (mActiveTrack != track) {
removeTrack_l(track);
}
}
void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
{
mTracks.remove(track);
// need anything related to effects here?
}
void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
{
dumpInternals(fd, args);
dumpTracks(fd, args);
dumpEffectChains(fd, args);
}
void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
{
const size_t SIZE = 256;
char buffer[SIZE];
String8 result;
snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
result.append(buffer);
if (mActiveTrack != 0) {
snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
result.append(buffer);
snprintf(buffer, SIZE, "Buffer size: %u bytes\n", mBufferSize);
result.append(buffer);
snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
result.append(buffer);
snprintf(buffer, SIZE, "Out channel count: %u\n", mReqChannelCount);
result.append(buffer);
snprintf(buffer, SIZE, "Out sample rate: %u\n", mReqSampleRate);
result.append(buffer);
} else {
result.append("No active record client\n");
}
write(fd, result.string(), result.size());
dumpBase(fd, args);
}
void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args)
{
const size_t SIZE = 256;
char buffer[SIZE];
String8 result;
snprintf(buffer, SIZE, "Input thread %p tracks\n", this);
result.append(buffer);
RecordTrack::appendDumpHeader(result);
for (size_t i = 0; i < mTracks.size(); ++i) {
sp<RecordTrack> track = mTracks[i];
if (track != 0) {
track->dump(buffer, SIZE);
result.append(buffer);
}
}
if (mActiveTrack != 0) {
snprintf(buffer, SIZE, "\nInput thread %p active tracks\n", this);
result.append(buffer);
RecordTrack::appendDumpHeader(result);
mActiveTrack->dump(buffer, SIZE);
result.append(buffer);
}
write(fd, result.string(), result.size());
}
// AudioBufferProvider interface
status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
{
size_t framesReq = buffer->frameCount;
size_t framesReady = mFrameCount - mRsmpInIndex;
int channelCount;
if (framesReady == 0) {
mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mBufferSize);
if (mBytesRead <= 0) {
if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE)) {
ALOGE("RecordThread::getNextBuffer() Error reading audio input");
// Force input into standby so that it tries to
// recover at next read attempt
inputStandBy();
usleep(kRecordThreadSleepUs);
}
buffer->raw = NULL;
buffer->frameCount = 0;
return NOT_ENOUGH_DATA;
}
mRsmpInIndex = 0;
framesReady = mFrameCount;
}
if (framesReq > framesReady) {
framesReq = framesReady;
}
if (mChannelCount == 1 && mReqChannelCount == 2) {
channelCount = 1;
} else {
channelCount = 2;
}
buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
buffer->frameCount = framesReq;
return NO_ERROR;
}
// AudioBufferProvider interface
void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
{
mRsmpInIndex += buffer->frameCount;
buffer->frameCount = 0;
}
bool AudioFlinger::RecordThread::checkForNewParameters_l()
{
bool reconfig = false;
while (!mNewParameters.isEmpty()) {
status_t status = NO_ERROR;
String8 keyValuePair = mNewParameters[0];
AudioParameter param = AudioParameter(keyValuePair);
int value;
audio_format_t reqFormat = mFormat;
uint32_t reqSamplingRate = mReqSampleRate;
uint32_t reqChannelCount = mReqChannelCount;
if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
reqSamplingRate = value;
reconfig = true;
}
if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
status = BAD_VALUE;
} else {
reqFormat = (audio_format_t) value;
reconfig = true;
}
}
if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
reqChannelCount = popcount(value);
reconfig = true;
}
if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
// do not accept frame count changes if tracks are open as the track buffer
// size depends on frame count and correct behavior would not be guaranteed
// if frame count is changed after track creation
if (mActiveTrack != 0) {
status = INVALID_OPERATION;
} else {
reconfig = true;
}
}
if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
// forward device change to effects that have requested to be
// aware of attached audio device.
for (size_t i = 0; i < mEffectChains.size(); i++) {
mEffectChains[i]->setDevice_l(value);
}
// store input device and output device but do not forward output device to audio HAL.
// Note that status is ignored by the caller for output device
// (see AudioFlinger::setParameters()
if (audio_is_output_devices(value)) {
mOutDevice = value;
status = BAD_VALUE;
} else {
mInDevice = value;
// disable AEC and NS if the device is a BT SCO headset supporting those
// pre processings
if (mTracks.size() > 0) {
bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
mAudioFlinger->btNrecIsOff();
for (size_t i = 0; i < mTracks.size(); i++) {
sp<RecordTrack> track = mTracks[i];
setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
}
}
}
}
if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
mAudioSource != (audio_source_t)value) {
// forward device change to effects that have requested to be
// aware of attached audio device.
for (size_t i = 0; i < mEffectChains.size(); i++) {
mEffectChains[i]->setAudioSource_l((audio_source_t)value);
}
mAudioSource = (audio_source_t)value;
}
if (status == NO_ERROR) {
status = mInput->stream->common.set_parameters(&mInput->stream->common,
keyValuePair.string());
if (status == INVALID_OPERATION) {
inputStandBy();
status = mInput->stream->common.set_parameters(&mInput->stream->common,
keyValuePair.string());
}
if (reconfig) {
if (status == BAD_VALUE &&
reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
(mInput->stream->common.get_sample_rate(&mInput->stream->common)
<= (2 * reqSamplingRate)) &&
popcount(mInput->stream->common.get_channels(&mInput->stream->common))
<= FCC_2 &&
(reqChannelCount <= FCC_2)) {
status = NO_ERROR;
}
if (status == NO_ERROR) {
readInputParameters();
sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
}
}
}
mNewParameters.removeAt(0);
mParamStatus = status;
mParamCond.signal();
// wait for condition with time out in case the thread calling ThreadBase::setParameters()
// already timed out waiting for the status and will never signal the condition.
mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
}
return reconfig;
}
String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
{
Mutex::Autolock _l(mLock);
if (initCheck() != NO_ERROR) {
return String8();
}
char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
const String8 out_s8(s);
free(s);
return out_s8;
}
void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
AudioSystem::OutputDescriptor desc;
void *param2 = NULL;
switch (event) {
case AudioSystem::INPUT_OPENED:
case AudioSystem::INPUT_CONFIG_CHANGED:
desc.channelMask = mChannelMask;
desc.samplingRate = mSampleRate;
desc.format = mFormat;
desc.frameCount = mFrameCount;
desc.latency = 0;
param2 = &desc;
break;
case AudioSystem::INPUT_CLOSED:
default:
break;
}
mAudioFlinger->audioConfigChanged_l(event, mId, param2);
}
void AudioFlinger::RecordThread::readInputParameters()
{
delete[] mRsmpInBuffer;
// mRsmpInBuffer is always assigned a new[] below
delete[] mRsmpOutBuffer;
mRsmpOutBuffer = NULL;
delete mResampler;
mResampler = NULL;
mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
mChannelCount = popcount(mChannelMask);
mFormat = mInput->stream->common.get_format(&mInput->stream->common);
if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
ALOGE("HAL format %d not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
}
mFrameSize = audio_stream_frame_size(&mInput->stream->common);
mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
mFrameCount = mBufferSize / mFrameSize;
mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
{
int channelCount;
// optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
// stereo to mono post process as the resampler always outputs stereo.
if (mChannelCount == 1 && mReqChannelCount == 2) {
channelCount = 1;
} else {
channelCount = 2;
}
mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
mResampler->setSampleRate(mSampleRate);
mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
mRsmpOutBuffer = new int32_t[mFrameCount * FCC_2];
// optmization: if mono to mono, alter input frame count as if we were inputing
// stereo samples
if (mChannelCount == 1 && mReqChannelCount == 1) {
mFrameCount >>= 1;
}
}
mRsmpInIndex = mFrameCount;
}
unsigned int AudioFlinger::RecordThread::getInputFramesLost()
{
Mutex::Autolock _l(mLock);
if (initCheck() != NO_ERROR) {
return 0;
}
return mInput->stream->get_input_frames_lost(mInput->stream);
}
uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
{
Mutex::Autolock _l(mLock);
uint32_t result = 0;
if (getEffectChain_l(sessionId) != 0) {
result = EFFECT_SESSION;
}
for (size_t i = 0; i < mTracks.size(); ++i) {
if (sessionId == mTracks[i]->sessionId()) {
result |= TRACK_SESSION;
break;
}
}
return result;
}
KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
{
KeyedVector<int, bool> ids;
Mutex::Autolock _l(mLock);
for (size_t j = 0; j < mTracks.size(); ++j) {
sp<RecordThread::RecordTrack> track = mTracks[j];
int sessionId = track->sessionId();
if (ids.indexOfKey(sessionId) < 0) {
ids.add(sessionId, true);
}
}
return ids;
}
AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
{
Mutex::Autolock _l(mLock);
AudioStreamIn *input = mInput;
mInput = NULL;
return input;
}
// this method must always be called either with ThreadBase mLock held or inside the thread loop
audio_stream_t* AudioFlinger::RecordThread::stream() const
{
if (mInput == NULL) {
return NULL;
}
return &mInput->stream->common;
}
status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
{
// only one chain per input thread
if (mEffectChains.size() != 0) {
return INVALID_OPERATION;
}
ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
chain->setInBuffer(NULL);
chain->setOutBuffer(NULL);
checkSuspendOnAddEffectChain_l(chain);
mEffectChains.add(chain);
return NO_ERROR;
}
size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
{
ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
ALOGW_IF(mEffectChains.size() != 1,
"removeEffectChain_l() %p invalid chain size %d on thread %p",
chain.get(), mEffectChains.size(), this);
if (mEffectChains.size() == 1) {
mEffectChains.removeAt(0);
}
return 0;
}
}; // namespace android
| [
"mingxin.android@gmail.com"
] | mingxin.android@gmail.com |
14e344ff5c8dd155282d88c1d3d6dbd626a48949 | ffef5c3e6c3ddb681e0bb61d30970433f146c4b6 | /ds/Lab3/main.cc | 75c2b597b04e410d34c9bd424af000c9f5bb703b | [] | no_license | calebfaruki/school | 6c7c50630cedbd8340ac9eabfaca1635cf3acc52 | 6835fdec86dd6fb97f498e02191a2e007f4007b6 | refs/heads/master | 2021-01-23T18:10:00.628153 | 2013-12-09T06:31:54 | 2013-12-09T06:31:54 | 14,323,713 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 3,637 | cc | /**********************************************************************
* Name: Caleb Faruki
* Lab3: Template Array
* Course: Data Structures
* Date: July 3, 2013
* File: Template Main Function File
*********************************************************************/
#include "Template.h"
int main () {
int arrSize;
cout << "Specify size of arrays intOne & intTwo: ";
cin >> arrSize;
cout << endl;
/***************************Integer Template**************************/
cout << "~~~TEMPLATE<INT>~~~\n" << endl;
Template<int> intOne(arrSize); // New constructor called for intOne
Template<int> intTwo(intOne); // Copy constructor called for intTwo
// Print contents of both arrays (all elements == DEFAULTVALUE).
cout << "Printing contents of both arrays: " << endl
<< "intOne[size==" << arrSize << "]: " << intOne
<< "intTwo[size==" << arrSize << "]: " << intTwo;
// Show that copy constructor works.
if (intOne == intTwo)
cout << "intOne == intTwo.\n" << endl;
// Set value of 1st element to arrSize.
intOne[0] = arrSize;
cout << "Now, intOne[0] == " << intOne[0] << endl << endl;
// Manually set all values for arrTwo.
cout << "Now enter elements for intTwo." << endl;
cin >> intTwo;
cout << endl;
// Print contents of both arrays.
cout << "Printing contents of both arrays:\n" << "intOne: "
<< intOne << "intTwo: " << intTwo;
// Check equality of arrOne & arrTwo.
if (intOne == intTwo)
cout << "intOne == intTwo.\n" << endl;
else
cout << "intOne != intTwo.\n" << endl;
/*************************Character Template**************************/
cout << "~~~TEMPLATE<CHAR>~~~\n" << endl;
Template<char> charOne; // Default constructor called for charOne
// All values default set to ' '.
cout << "Now specify size of array charTwo: ";
cin >> arrSize;
cout << endl;
Template<char> charTwo(arrSize); // New constructor call
// Print contents of both arrays.
cout << "Printing contents of both arrays:\n" << "charOne: "
<< charOne << "charTwo: " << charTwo;
// Check equality of charOne & charTwo.
if (charOne == charTwo)
cout << "charOne == charTwo.\n" << endl;
else
cout << "charOne != charTwo.\n" << endl;
// Set value of 1st element to '%'.
charOne[0] = '%';
cout << "Now, charOne[0] == " << charOne[0] << endl << endl;
// Manually set all values for charTwo.
cout << "Now enter elements for charTwo." << endl;
cin >> charTwo;
cout << endl;
cout << "Printing contents of both arrays:\n" << "charOne: "
<< charOne << "charTwo: " << charTwo;
/**************************Double Template***************************/
cout << "\n~~~TEMPLATE<DOUBLE>~~~\n" << endl;
Template<double> dblOne;
cout << "Now specify size of array dblTwo: ";
cin >> arrSize;
cout << endl;
Template<double> dblTwo(arrSize);
cout << "Printing contents of both arrays:\n" << "dblOne: "
<< dblOne << "dblTwo: " << dblTwo;
if (dblOne == dblTwo)
cout << "dblOne == dblTwo.\n" << endl;
else
cout << "dblOne != dblTwo.\n" << endl;
// Set value of 1st element to '%'.
dblOne[0] = 6.54321;
cout << "Now, dblOne[0] == " << dblOne[0] << endl << endl;
cout << "Now enter elements for dblTwo." << endl;
cin >> dblTwo;
cout << endl;
cout << "Printing contents of both arrays:\n" << "dblOne: "
<< dblOne << "dblTwo: " << dblTwo;
return 0;
}
| [
"calebfaruki@gmail.com"
] | calebfaruki@gmail.com |
3d63634989b6e7f27f31db8b91c04837fef05bb8 | 746bf4dedfe6e2f9ef5d430c3be6e14629d7dbff | /AmethystEngine/cLightObject.cpp | 2abfeceea9572bbf9996cd98f7e7d28c0f00931a | [] | no_license | KirkbyD/edu-Phys2-Bullet | e87909fc17e92ed2bd4c297f7d242e7ccdc2d070 | e82172a43189e4232fd3ba356659238201189b5a | refs/heads/main | 2023-04-15T23:18:38.022602 | 2021-04-15T01:38:42 | 2021-04-15T01:38:42 | 358,092,685 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,894 | cpp | #define _CRTDBG_MAP_ALLOC
#include <cstdlib>
#include <crtdbg.h>
#include <memory>
#ifdef _DEBUG
#define DEBUG_NEW new (_NORMAL_BLOCK , __FILE__ , __LINE__)
#define new DEBUG_NEW
#else
#define DBG_NEW
#endif
#include "cLightObject.hpp"
#include "sData.hpp"
#include "cLightManager.hpp"
cLightObject::cLightObject(std::vector<cLightObject*> &vLights) {
/*Interface*/
this->friendlyIDNumber = 0;
this->friendlyName = "";
this->isVisible = true;
this->isControl = false;
this->m_uniqueID = next_uniqueID;
// Then increment the static variable
++cLightObject::next_uniqueID;
parentObject = NULL;
////////////////////////////////////////////////
/*Light Object*/
position = glm::vec4(0.0f, 0.0f, 0.0f, 0.0f);
diffuse = glm::vec4(0.0f, 0.0f, 0.0f, 0.0f);
specular = glm::vec4(0.0f, 0.0f, 0.0f, 1.0f);
atten = glm::vec4(0.0f, 0.0f, 0.0f, 1.0f);
direction = glm::vec4(0.0f, 0.0f, 0.0f, 1.0f);
param1 = glm::vec4(0.0f, 0.0f, 0.0f, 1.0f);
param2 = glm::vec4(0.0f, 0.0f, 0.0f, 1.0f);
// add the "factory" settings light to the array of lights
vLights.push_back(this);
};
cLightObject::cLightObject(std::vector<cLightObject*>& vLights, std::string fObjectName) {
/*Interface*/
this->friendlyIDNumber = 0;
this->friendlyName = fObjectName;
this->isVisible = true;
this->isControl = false;
this->m_uniqueID = next_uniqueID;
// Then increment the static variable
++cLightObject::next_uniqueID;
////////////////////////////////////////////////
/*Light Object*/
position = glm::vec4(0.0f, 0.0f, 0.0f, 0.0f);
diffuse = glm::vec4(0.0f, 0.0f, 0.0f, 0.0f);
specular = glm::vec4(0.0f, 0.0f, 0.0f, 1.0f);
atten = glm::vec4(0.0f, 0.0f, 0.0f, 1.0f);
direction = glm::vec4(0.0f, 0.0f, 0.0f, 1.0f);
param1 = glm::vec4(0.0f, 0.0f, 0.0f, 1.0f);
param2 = glm::vec4(0.0f, 0.0f, 0.0f, 1.0f);
parentObject = NULL;
// add the "factory" settings light to the array of lights
vLights.push_back(this);
}
cLightObject::cLightObject(std::vector<cLightObject*>& vLights, sData data) {
/*Interface*/
this->friendlyIDNumber = 0;
this->friendlyName = data.getSource();
this->isVisible = true;
this->isControl = false;
this->m_uniqueID = next_uniqueID;
// Then increment the static variable
++cLightObject::next_uniqueID;
////////////////////////////////////////////////
/*Light Object*/
std::vector<glm::vec4> vec4s = data.getVec4Data();
position = vec4s[0];
diffuse = vec4s[1];
specular = vec4s[2];
atten = vec4s[3];
direction = vec4s[4];
param1 = vec4s[5];
param2 = vec4s[6];
parentObject = NULL;
// add the "factory" settings light to the array of lights
vLights.push_back(this);
cLightManager* pLightManager = cLightManager::GetLightManager();
}
unsigned int cLightObject::getUniqueID(void) { return this->m_uniqueID; }
glm::vec3 cLightObject::getPosition(void) {
return glm::vec3(this->position.x, this->position.y, this->position.z);
}
| [
"kirkby.dylan@gmail.com"
] | kirkby.dylan@gmail.com |
3f2de2380177babb3b9b400c1e92396c0b6d3542 | 4335d9af0080c4c322505d13caf760f8109ce666 | /include/FeatureTracker.h | d79301606ba972240eebadfbfca0eddcc92fdcaa | [] | no_license | cishenpinpan/VisualSLAM | 24108702befae59f25617b0158b86edcdb508e00 | b525e648b4c946abc06fdc31dfa93d1c97fde1f5 | refs/heads/master | 2020-05-18T14:27:19.344714 | 2017-05-24T18:12:03 | 2017-05-24T18:12:03 | 84,248,134 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,021 | h | //
// FeatureTracker.hpp
// VisualSLAM
//
// Created by Rong Yuan on 2/28/17.
// Copyright © 2017 Rong Yuan. All rights reserved.
//
#ifndef FeatureTracker_h
#define FeatureTracker_h
#include <time.h>
#include "View.h"
#include "Canvas.h"
#include "FeatureCandidateExtractor.h"
#include "FeatureExtractor.h"
namespace blindfind
{
class View;
class FeatureTracker
{
public:
// when tracking or matching, only the last view is modified
void kltTrack(const Mat img1, const Mat img2, const FeatureSet& featureSet1,FeatureSet& featureSet2);
void refineTrackedFeatures(Mat img1, Mat img2, const FeatureSet& featureSet1, FeatureSet& featureSet2);
// trackAndMatch locks tracked feature in real corners
// when passing in a single view, it is matching within a stereo
void trackAndMatch(vector<View*> views);
void trackAndMatch(View *v);
void track(vector<View*> views);
void track(View *v);
};
}
#endif /* FeatureTracker_h */
| [
"orangechicken@Rongs-MacBook-Pro.local"
] | orangechicken@Rongs-MacBook-Pro.local |
e7aa01b5113e621245584c40c73cf2d8b28393ce | 6e4f8d2ba4097ac1078403b6e3816dd7c9bd7553 | /CodingPractice/ThreadPool.h | b302d643bc30efcfff2d29dbc41affba755e0ee4 | [] | no_license | shuaisilun/CodingPractice | 771f2bcc29ef25cff2a93124846a739a53e49d9b | 582a7300960fae84e4da6ab5d1f5bb0b3d8e55f0 | refs/heads/master | 2021-07-24T18:28:52.493092 | 2017-11-02T07:57:02 | 2017-11-02T07:57:02 | 107,639,542 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,397 | h | #pragma once
#include <set>
#include <mutex>
#include <vector>
#include <unordered_map>
#include <thread>
using namespace std;
class ThreadPool
{
public:
ThreadPool() {};
~ThreadPool()
{
for (auto &it : m_Threads)
{
delete it.second;
}
};
ThreadPool(ThreadPool const&) = delete;
ThreadPool& operator=(ThreadPool const&) = delete;
//is this thread in
bool is_this_thread_in()
{
auto it = m_Threads.find(this_thread::get_id());
return it != m_Threads.end();
}
//is thread in
bool is_thread_in(thread* a_thread)
{
if (!a_thread) return false;
auto it = m_Threads.find(a_thread->get_id());
return it != m_Threads.end();
}
//create thread
template<typename F>
thread* create_thread(F threadfunc)
{
thread *new_thread = new thread(threadfunc);
m_Threads[new_thread->get_id()] = new_thread;
return new_thread;
}
//add thread
void add_thread(thread* a_thread)
{
if (a_thread) {
if (is_thread_in(a_thread))
{
throw runtime_error(
"thread_group: trying to add a duplicated thread");
}
m_Threads[a_thread->get_id()] = a_thread;
}
}
// remove thread
void remove_thread(thread* a_thread)
{
auto it = m_Threads.find(a_thread->get_id());
if (it != m_Threads.end())
{
m_Threads.erase(it);
}
}
//size
size_t size()
{
return m_Threads.size();
}
private:
unordered_map<thread::id,thread*> m_Threads;
}; | [
"shuaisilun@virtuos.com.cn"
] | shuaisilun@virtuos.com.cn |
70d45edb5b6993b5ab4ff7f0f7e215bde11cc7aa | bcafdb36f915d7223e0ece0cab593db7bed34f85 | /src/nikkei2019-qual-A.cpp | ac081ef1c14fe094ad62b41ee140ef985a504810 | [] | no_license | kuno4n/AtCoder | 1f823089356b40b0e14521577e4173ed56f08f11 | 0f443caffff0192d128276136370258b4bec8c77 | refs/heads/master | 2021-01-19T08:30:53.300327 | 2019-07-25T04:57:50 | 2019-07-25T04:57:50 | 10,724,117 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,360 | cpp | #include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <numeric>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <cmath>
#include <cassert>
#include <cstdarg>
#include <sys/time.h>
#include <fstream>
//#include "cout.h"
using namespace std;
#define SZ(x) ((int)x.size())
#define MSET(x,a) memset(x, a, (int)sizeof(x))
#define PB push_back
#define VI vector < int >
#define PII pair < int, int >
#define LL long long
#define FOR(i,a,b) for (int i = (a); i < (b); i++)
#define REP(i,n) FOR(i,0,n)
#define ALL(v) (v).begin(), (v).end()
#define FIT(it,v) for (__typeof((v).begin()) it = (v).begin(); it != (v).end(); it++)
#define OUT(A) cout << #A << " = "<< (A) << endl
#define OUT2(A, B) cout << "(" << #A << ", " << #B << ") = (" << (A) << ", "<< (B) << ")" << endl
template<class T> void chmin(T &t, T f) { if (t > f) t = f; }
template<class T> void chmax(T &t, T f) { if (t < f) t = f; }
#define present(c, e) ((c).find((e)) != (c).end())
#define cpresent(c, e) (find(ALL(c), (e)) != (c).end())
void init() {
}
void input() {
}
void solve() {
int n, a, b;
cin >> n >> a >> b;
cout << min(a,b) << " ";
cout << max(0, a+b-n) << endl;
}
int main() {
init();
input();
solve();
return 0;
}
| [
"kuno4n@gmail.com"
] | kuno4n@gmail.com |
519e15a37a5ec45d70c11b44ceb31b7521e24d3f | d42675fc0fa37759acd8bfa8707530102c80eb1c | /CvGameCoreDLL/Boost-1.32.0/include/boost/regex/v3/regex_fwd.hpp | ef817f70779ed3008e1d70d866c76ed6d57b3619 | [] | no_license | bptato/RFC-Greek-World | 26028f9188ca9e277aaf55f49ba26c5fc17004c8 | ac1d814ad46066b567f86a52a67279b83f63d665 | refs/heads/master | 2023-06-22T15:10:33.252772 | 2023-06-10T11:46:12 | 2023-06-10T11:46:41 | 255,673,818 | 4 | 6 | null | 2023-06-10T09:41:09 | 2020-04-14T17:12:02 | C++ | UTF-8 | C++ | false | false | 1,621 | hpp | /*
*
* Copyright (c) 1998-2002
* Dr John Maddock
*
* Use, modification and distribution are subject to the
* Boost Software License, Version 1.0. (See accompanying file
* LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*
*/
/*
* LOCATION: see http://www.boost.org for most recent version.
* FILE regex_fwd.cpp
* VERSION see <boost/version.hpp>
* DESCRIPTION: Forward declares boost::reg_expression<> and
* associated typedefs.
*/
#ifndef BOOST_REGEX_FWD_HPP_INCLUDED
#define BOOST_REGEX_FWD_HPP_INCLUDED
#ifndef BOOST_REGEX_CONFIG_HPP
#include <boost/config.hpp>
#endif
#include <boost/regex/config/allocator.hpp>
//
// define BOOST_REGEX_NO_FWD if this
// header doesn't work!
//
#ifdef BOOST_REGEX_NO_FWD
# ifndef BOOST_RE_REGEX_HPP
# include <boost/regex.hpp>
# endif
#else
//
// If there isn't good enough wide character support then there will
// be no wide character regular expressions:
//
#if (defined(BOOST_NO_CWCHAR) || defined(BOOST_NO_CWCTYPE) || defined(BOOST_NO_STD_WSTRING)) && !defined(BOOST_NO_WREGEX)
# define BOOST_NO_WREGEX
#endif
namespace boost{
template <class charT>
class regex_traits;
template <class charT, class traits = regex_traits<charT>, class Allocator = BOOST_DEFAULT_ALLOCATOR(charT) >
class reg_expression;
typedef reg_expression<char, regex_traits<char>, BOOST_DEFAULT_ALLOCATOR(char) > regex;
#ifndef BOOST_NO_WREGEX
typedef reg_expression<wchar_t, regex_traits<wchar_t>, BOOST_DEFAULT_ALLOCATOR(wchar_t) > wregex;
#endif
} // namespace boost
#endif // BOOST_REGEX_NO_FWD
#endif
| [
"nincsnevem662@gmail.com"
] | nincsnevem662@gmail.com |
d015de36c40f4f5ea3c41df32ab3888f106690b5 | 2946a6f84ee4f3e1a464f315a3270ff1a638116a | /file1.cpp | 47c5ef37b4b8bc8ceebeef061e4a841a2655dd09 | [] | no_license | vedantlodha/gitsample | 4fe6f52edf6f9d2f101e34eea3ad7c8668b14452 | 287572c9aba26bd7ceff329613926e68d5b8815f | refs/heads/master | 2020-05-03T01:38:59.468968 | 2019-03-30T11:56:32 | 2019-03-30T11:56:32 | 178,343,806 | 0 | 0 | null | 2019-03-29T06:55:47 | 2019-03-29T06:13:52 | C++ | UTF-8 | C++ | false | false | 203 | cpp | #include<iostream>
int first(){
cout << "This is the first feature" << endl;
}
int second(){
cout<<"This is the second feature" << endl;
}
int third(){
cout << "This is the third feaure";
| [
"ivedantlodha@gmail.com"
] | ivedantlodha@gmail.com |
71bd13b2d4a2d54377946ab1c9b6579169535361 | 0eeca52aada4f91602e14c2c27c4fbb0e7ea8b40 | /test/cairo-network.cpp | 5164f5f073d4bc307afe6b2c1d7fc626953bd743 | [] | no_license | SonSang/diff-traffic-baseline-libroad | 7cada8eca977840106966e7a92b9bfff82a21573 | b12c66360cb843eec25cdc95933f68feae83ccaf | refs/heads/master | 2023-07-31T06:06:37.080248 | 2021-09-26T05:50:59 | 2021-09-26T05:50:59 | 409,357,946 | 0 | 1 | null | 2021-09-26T05:43:14 | 2021-09-22T21:13:13 | C++ | UTF-8 | C++ | false | false | 17,355 | cpp | #include <Magick++.h>
#include <GL/glew.h>
#include <FL/Fl.H>
#include <FL/Fl_Gl_Window.H>
#include <FL/Fl_Menu_Button.H>
#include <FL/gl.h>
#include <FL/glu.h>
#include <FL/glut.H>
#undef None // Stupid X11/X.h defines this!
#include "libroad/hwm_network.hpp"
#include "libroad/geometric.hpp"
#include "visual_geometric.hpp"
class fltkview : public Fl_Gl_Window
{
public:
fltkview(int x, int y, int w, int h, const char *l) : Fl_Gl_Window(x, y, w, h, l),
lastpick(0),
net(0),
netaux(0),
glew_state(GLEW_OK+1),
road_tex_(0),
background_tex_(0),
back_image(0),
back_image_center(0),
back_image_scale(1),
back_image_yscale(1),
overlay_tex_(0),
drawing(false)
{
this->resizable(this);
}
void init_glew()
{
glew_state = glewInit();
if (GLEW_OK != glew_state)
{
/* Problem: glewInit failed, something is seriously wrong. */
std::cerr << "Error: " << glewGetErrorString(glew_state) << std::endl;
}
std::cerr << "Status: Using GLEW " << glewGetString(GLEW_VERSION) << std::endl;
}
void init_textures()
{
if(!glIsTexture(road_tex_))
{
glGenTextures(1, &road_tex_);
glBindTexture (GL_TEXTURE_2D, road_tex_);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
retex_roads(center, scale, make_v2(w(), h()));
}
if(back_image && !glIsTexture(background_tex_))
{
glGenTextures(1, &background_tex_);
glBindTexture (GL_TEXTURE_2D, background_tex_);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
Magick::Image im(*back_image);
im.flip();
back_image_dim = make_v2(im.columns(), im.rows());
unsigned char *pix = new unsigned char[back_image_dim[0]*back_image_dim[1]*4];
im.write(0, 0, back_image_dim[0], back_image_dim[1], "RGBA", Magick::CharPixel, pix);
glTexImage2D (GL_TEXTURE_2D,
0,
GL_RGBA,
back_image_dim[0],
back_image_dim[1],
0,
GL_RGBA,
GL_UNSIGNED_BYTE,
pix);
delete[] pix;
}
if(!glIsTexture(overlay_tex_))
{
glGenTextures(1, &overlay_tex_);
glBindTexture (GL_TEXTURE_2D, overlay_tex_);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
retex_overlay(center, scale, make_v2(w(), h()));
}
}
void retex_roads(const vec2f &my_center, const float my_scale, const vec2i &im_res)
{
cairo_surface_t *cs = cairo_image_surface_create(CAIRO_FORMAT_ARGB32,
im_res[0],
im_res[1]);
cairo_t *cr = cairo_create(cs);
cairo_set_source_rgba(cr, 0.0, 0, 0, 0.0);
cairo_set_operator(cr, CAIRO_OPERATOR_SOURCE);
cairo_paint(cr);
cairo_set_operator(cr, CAIRO_OPERATOR_OVER);
cairo_translate(cr,
im_res[0]/2,
im_res[1]/2);
cairo_scale(cr,
im_res[0]/my_scale,
im_res[1]/my_scale);
if(im_res[0] > im_res[1])
cairo_scale(cr,
static_cast<float>(im_res[1])/im_res[0],
1.0);
else
cairo_scale(cr,
1.0,
static_cast<float>(im_res[0])/im_res[1]);
cairo_translate(cr,
-my_center[0],
-my_center[1]);
cairo_set_line_width(cr, 0.5);
netaux->cairo_roads(cr);
cairo_destroy(cr);
glBindTexture (GL_TEXTURE_2D, road_tex_);
glTexImage2D (GL_TEXTURE_2D,
0,
GL_RGBA,
im_res[0],
im_res[1],
0,
GL_BGRA,
GL_UNSIGNED_BYTE,
cairo_image_surface_get_data(cs));
cairo_surface_destroy(cs);
cscale_to_box(tex_low, tex_high, my_center, my_scale, im_res);
}
void retex_overlay(const vec2f &my_center, const float my_scale, const vec2i &im_res)
{
cairo_surface_t *cs = cairo_image_surface_create(CAIRO_FORMAT_ARGB32,
im_res[0],
im_res[1]);
cairo_t *cr = cairo_create(cs);
cairo_set_source_rgba(cr, 0.0, 0, 0, 0.0);
cairo_set_operator(cr, CAIRO_OPERATOR_SOURCE);
cairo_paint(cr);
cairo_set_line_cap(cr, CAIRO_LINE_CAP_ROUND);
cairo_set_operator(cr, CAIRO_OPERATOR_SOURCE);
cairo_translate(cr,
im_res[0]/2,
im_res[1]/2);
cairo_scale(cr,
im_res[0]/my_scale,
im_res[1]/my_scale);
if(im_res[0] > im_res[1])
cairo_scale(cr,
static_cast<float>(im_res[1])/im_res[0],
1.0);
else
cairo_scale(cr,
1.0,
static_cast<float>(im_res[0])/im_res[1]);
cairo_translate(cr,
-my_center[0],
-my_center[1]);
cairo_matrix_t cmat;
cairo_get_matrix(cr, &cmat);
BOOST_FOREACH(const aabb2d &r, rectangles)
{
cairo_set_matrix(cr, &cmat);
cairo_rectangle(cr, r.bounds[0][0], r.bounds[0][1], r.bounds[1][0]-r.bounds[0][0], r.bounds[1][1]-r.bounds[0][1]);
cairo_set_source_rgba(cr, 67/255.0, 127/255.0, 195/255.0, 0.5);
cairo_fill_preserve(cr);
cairo_set_source_rgba(cr, 17/255.0, 129/255.0, 255/255.0, 0.7);
cairo_identity_matrix(cr);
cairo_set_line_width(cr, 2.0);
cairo_stroke(cr);
}
if(drawing)
{
const vec2f low(std::min(first_point[0], second_point[0]),
std::min(first_point[1], second_point[1]));
const vec2f high(std::max(first_point[0], second_point[0]),
std::max(first_point[1], second_point[1]));
cairo_set_matrix(cr, &cmat);
cairo_rectangle(cr, low[0], low[1], high[0]-low[0], high[1]-low[1]);
cairo_set_source_rgba(cr, 67/255.0, 127/255.0, 195/255.0, 0.5);
cairo_fill_preserve(cr);
cairo_set_source_rgba(cr, 17/255.0, 129/255.0, 255/255.0, 0.7);
cairo_identity_matrix(cr);
cairo_set_line_width(cr, 2.0);
cairo_stroke(cr);
}
BOOST_FOREACH(const hwm::network_aux::road_spatial::entry &e, query_results)
{
cairo_set_matrix(cr, &cmat);
cairo_rectangle(cr, e.rect.bounds[0][0], e.rect.bounds[0][1], e.rect.bounds[1][0]-e.rect.bounds[0][0], e.rect.bounds[1][1]-e.rect.bounds[0][1]);
cairo_set_source_rgba(cr, 195/255.0, 127/255.0, 67/255.0, 0.5);
cairo_fill_preserve(cr);
cairo_set_source_rgba(cr, 255/255.0, 129/255.0, 217/255.0, 0.7);
cairo_identity_matrix(cr);
cairo_set_line_width(cr, 2.0);
cairo_stroke(cr);
}
cairo_destroy(cr);
glBindTexture(GL_TEXTURE_2D, overlay_tex_);
glTexImage2D (GL_TEXTURE_2D,
0,
GL_RGBA,
im_res[0],
im_res[1],
0,
GL_BGRA,
GL_UNSIGNED_BYTE,
cairo_image_surface_get_data(cs));
cairo_surface_destroy(cs);
}
void draw()
{
if (!valid())
{
glViewport(0, 0, w(), h());
glClearColor(0.0, 0.0, 0.0, 0.0);
if(GLEW_OK != glew_state)
init_glew();
init_textures();
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
vec2f lo, hi;
cscale_to_box(lo, hi, center, scale, make_v2(w(), h()));
gluOrtho2D(lo[0], hi[0], lo[1], hi[1]);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glEnable(GL_TEXTURE_2D);
if(back_image)
{
glBindTexture (GL_TEXTURE_2D, background_tex_);
glPushMatrix();
glTranslatef(-back_image_center[0], -back_image_center[1], 0);
glScalef (back_image_scale, back_image_yscale*back_image_scale, 1);
glTranslatef(-back_image_dim[0]/2, -back_image_dim[1]/2, 0);
glBegin(GL_QUADS);
glTexCoord2f(0.0, 0.0);
glVertex2i(0, 0);
glTexCoord2f(1.0, 0.0);
glVertex2i(back_image_dim[0], 0);
glTexCoord2f(1.0, 1.0);
glVertex2iv(back_image_dim.data());
glTexCoord2f(0.0, 1.0);
glVertex2i(0, back_image_dim[1]);
glEnd();
glPopMatrix();
}
glBindTexture (GL_TEXTURE_2D, road_tex_);
glPushMatrix();
glBegin(GL_QUADS);
glTexCoord2f(0.0, 0.0);
glVertex2fv(tex_low.data());
glTexCoord2f(1.0, 0.0);
glVertex2f(tex_high[0], tex_low[1]);
glTexCoord2f(1.0, 1.0);
glVertex2fv(tex_high.data());
glTexCoord2f(0.0, 1.0);
glVertex2f(tex_low[0], tex_high[1]);
glEnd();
glPopMatrix();
glBindTexture (GL_TEXTURE_2D, overlay_tex_);
retex_overlay(center, scale, make_v2(w(), h()));
glPushMatrix();
glBegin(GL_QUADS);
glTexCoord2f(0.0, 0.0);
glVertex2fv(lo.data());
glTexCoord2f(1.0, 0.0);
glVertex2f(hi[0], lo[1]);
glTexCoord2f(1.0, 1.0);
glVertex2fv(hi.data());
glTexCoord2f(0.0, 1.0);
glVertex2f(lo[0], hi[1]);
glEnd();
glPopMatrix();
glDisable(GL_TEXTURE_2D);
glFlush();
glFinish();
}
int handle(int event)
{
switch(event)
{
case FL_PUSH:
{
const vec2i xy(make_v2(Fl::event_x(),
Fl::event_y()));
const vec2f world(world_point(make_v2(xy[0], h()-xy[1]), center, scale, make_v2(w(), h())));
if(Fl::event_button() == FL_LEFT_MOUSE)
first_point = world;
lastpick = world;
}
take_focus();
return 1;
case FL_RELEASE:
{
if(Fl::event_button() == FL_LEFT_MOUSE)
{
if(drawing)
{
rectangles.clear();
rectangles.push_back(aabb2d());
rectangles.back().enclose_point(first_point[0], first_point[1]);
rectangles.back().enclose_point(second_point[0], second_point[1]);
drawing = false;
query_results = netaux->road_space.query(rectangles.back());
redraw();
}
}
}
return 1;
case FL_DRAG:
{
const vec2i xy(make_v2(Fl::event_x(),
Fl::event_y()));
const vec2f world(world_point(make_v2(xy[0], h()-xy[1]), center, scale, make_v2(w(), h())));
vec2f dvec(0);
if(Fl::event_button() == FL_LEFT_MOUSE)
{
drawing = true;
second_point = world;
redraw();
}
else if(Fl::event_button() == FL_MIDDLE_MOUSE)
{
dvec = vec2f(world - lastpick);
center -= dvec;
redraw();
}
else if(Fl::event_button() == FL_RIGHT_MOUSE)
{
dvec = vec2f(world - lastpick);
back_image_center -= dvec;
redraw();
}
lastpick = world-dvec;
}
take_focus();
return 1;
case FL_KEYBOARD:
switch(Fl::event_key())
{
case ' ':
retex_roads(center, scale, make_v2(w(), h()));
redraw();
break;
}
return 1;
case FL_MOUSEWHEEL:
{
const vec2i xy(make_v2(Fl::event_x(),
Fl::event_y()));
const vec2i dxy(make_v2(Fl::event_dx(),
Fl::event_dy()));
const float fy = copysign(0.5, dxy[1]);
if(Fl::event_state() & FL_SHIFT)
{
if(Fl::event_state() & FL_CTRL)
back_image_yscale *= std::pow(2.0f, 0.1f*fy);
else
back_image_scale *= std::pow(2.0f, 0.5f*fy);
}
else
scale *= std::pow(2.0f, fy);
redraw();
}
take_focus();
return 1;
default:
// pass other events to the base class...
return Fl_Gl_Window::handle(event);
}
}
vec2f lastpick;
hwm::network *net;
hwm::network_aux *netaux;
vec2f tex_low;
vec2f tex_high;
vec2f center;
float scale;
GLuint glew_state;
GLuint road_tex_;
GLuint background_tex_;
char **back_image;
vec2i back_image_dim;
vec2f back_image_center;
float back_image_scale;
float back_image_yscale;
GLuint overlay_tex_;
std::vector<aabb2d> rectangles;
bool drawing;
vec2f first_point;
vec2f second_point;
std::vector<hwm::network_aux::road_spatial::entry> query_results;
};
int main(int argc, char *argv[])
{
std::cout << libroad_package_string() << std::endl;
if(argc < 2)
{
std::cerr << "Usage: " << argv[0] << " <input network> [background image]" << std::endl;
return 1;
}
hwm::network net(hwm::load_xml_network(argv[1], vec3f(1.0, 1.0, 1.0f)));
net.build_intersections();
net.build_fictitious_lanes();
net.auto_scale_memberships();
net.center();
std::cerr << "HWM net loaded successfully" << std::endl;
try
{
net.check();
std::cerr << "HWM net checks out" << std::endl;
}
catch(std::runtime_error &e)
{
std::cerr << "HWM net doesn't check out: " << e.what() << std::endl;
exit(1);
}
hwm::network_aux neta(net);
fltkview mv(0, 0, 500, 500, "fltk View");
mv.net = &net;
mv.netaux = &neta;
if(argc == 3)
mv.back_image = argv+2;
vec3f low(FLT_MAX);
vec3f high(-FLT_MAX);
net.bounding_box(low, high);
box_to_cscale(mv.center, mv.scale, sub<0,2>::vector(low), sub<0,2>::vector(high), vec2i(500,500));
mv.take_focus();
Fl::visual(FL_DOUBLE|FL_DEPTH);
mv.show(1, argv);
return Fl::run();
}
| [
"jasonsewall@gmail.com"
] | jasonsewall@gmail.com |
6128af14e26f49d2c14200fbadd1165e70acd235 | 11c42600d2472713aa35abc675d109d29f772b3a | /Undirected/UndirectedGraph/UndirectedGraph.cpp | 6799837da06512b6c3f7a381a8d850adfbeb384e | [] | no_license | daviddoria/BGLExamples | 65427b95be9cef8cbdca5c8158d37f5546f0b694 | ff223930ea6a76d90508dfd08df2889401ce189a | refs/heads/master | 2021-01-21T22:26:10.367813 | 2012-02-05T01:50:56 | 2012-02-05T01:50:56 | 3,277,497 | 10 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 94 | cpp | // Moved to here https://svn.boost.org/svn/boost/trunk/libs/graph/example/undirected_graph.cpp | [
"daviddoria@gmail.com"
] | daviddoria@gmail.com |
b6b92ecd9cd2719472b1ba6dad46408ebee2fb89 | 240bf2cdc61fd94b48818ed0ad94e081b4b0278d | /core/DebugOut.cpp | d60ffc2af8dc0d73a998e96ab58a97a80a9981b1 | [] | no_license | The-Griffin-White/APlusPlusEngine | ffcb38aa6c0585c4732f94f45178d8ecd6fcb445 | 80b26112d157b7e4d904a09716a7a847d97f75f4 | refs/heads/master | 2020-12-30T09:49:50.533392 | 2018-06-16T23:04:01 | 2018-06-16T23:04:01 | 123,399,471 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 498 | cpp | #include "DebugOut.h"
#include <Windows.h>
#include <stdio.h>
#include <stdarg.h>
char DebugMsg::DebugBuff[256] = { "no" };
void DebugMsg::out(char* A, ...)
{
va_list args;
va_start(args, A);
vsprintf_s(DebugBuff, A, args);
// convert the char* to a wchar_t*
size_t newsize = strlen(DebugBuff) + 1;
wchar_t * newText = new wchar_t[newsize];
size_t convertedChars = 0;
mbstowcs_s(&convertedChars, newText, newsize, DebugBuff, _TRUNCATE);
OutputDebugString(newText);
delete[] newText;
}; | [
"White7Griffin@gmail.com"
] | White7Griffin@gmail.com |
9af6521b89ad15c473789f92d1d19d5071a0c8e1 | 2f74b7f9ff3afe7e61fa4d4d96072bd7aa2c090b | /Engine/src/Oyl3D/AssetPaths.h | de8c6f5de69bbb999718fa062428a3121e5854c1 | [] | no_license | EstonianMuskrat/Oyl3D | 16f589706fc6ffa4137c9fe8e5cf064b0ab98627 | d556ad57ca2ec5e908cd4f530ad60f4f098d6630 | refs/heads/master | 2020-09-25T03:56:48.490939 | 2019-10-30T21:42:08 | 2019-10-30T21:42:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,441 | h | #pragma once
#include "Oyl3D/Typedefs.h"
namespace oyl
{
// vvv Universal vvv //
const CacheAlias INVALID_ALIAS = "_invalid";
// ^^^ Universal ^^^ //
// vvv Shaders vvv //
const std::string ENGINE_RES = "../Engine/res/";
const CacheAlias LIGHTING_SHADER_ALIAS = "_lighting";
const std::string LIGHTING_SHADER_VERTEX_PATH = "shaders/lighting.vert";
const std::string LIGHTING_SHADER_FRAGMENT_PATH = "shaders/lighting.frag";
const CacheAlias TEXTURE_SHADER_ALIAS = "_texture";
const std::string TEXTURE_SHADER_VERTEX_PATH = "shaders/meshShader.vert";
const std::string TEXTURE_SHADER_FRAGMENT_PATH = "shaders/meshShader.frag";
// ^^^ Shaders ^^^ //
// vvv Meshes vvv //
const std::string INVALID_MESH_PATH = "models/invalid.obj";
const CacheAlias CUBE_MESH_ALIAS = "_cube";
const std::string CUBE_MESH_PATH = "models/cube.obj";
const CacheAlias MONKEY_MESH_ALIAS = "_monkey";
const std::string MONKEY_MESH_PATH = "models/monkey.obj";
// ^^^ Shaders ^^^ //
// vvv Textures vvv //
const std::string INVALID_TEXTURE_PATH = "textures/invalid.png";
const CacheAlias WHITE_TEXTURE_ALIAS = "_white";
const std::string WHITE_TEXTURE_PATH = "textures/white.png";
const CacheAlias UV_TEXTURE_ALIAS = "_uvgrid";
const std::string UV_TEXTURE_PATH = "textures/uvgrid.png";
// ^^^ Textures ^^^ //
}
| [
"cragg.myles@gmail.com"
] | cragg.myles@gmail.com |
20f91a2c67b8105184b1264a448425e8278ae2e9 | d8d5b8c8bf1f5b15d6701367d09fa093ec60d0f2 | /src/BVHBuilder.hpp | 6be115e8abb7fb0b85e8fba3037e1460f0bbab03 | [
"MIT"
] | permissive | asterycs/cuWave | 5afc6c7e754d615a392972ff9f3e8eecdfdf6f29 | e1630950aaac50e789745ad0f1af19e67168ad22 | refs/heads/master | 2021-03-27T16:04:58.164291 | 2018-11-16T09:34:13 | 2018-11-16T09:34:13 | 122,977,371 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,660 | hpp | #ifndef BVHBUILDER_HPP
#define BVHBUILDER_HPP
#include <vector>
#include <string>
#include "Utils.hpp"
#include "Triangle.hpp"
#define MAX_TRIS_PER_LEAF 2
enum SplitType
{
SAH,
SPATIAL
};
struct SplitCandidate
{
enum SplitType type;
float cost;
unsigned int splitAxis;
Node leftChild;
Node rightChild;
SplitCandidate() : type(SAH), cost(0.f), splitAxis(0), leftChild(), rightChild() {};
};
class BVHBuilder
{
public:
struct TriangleHolder {
Triangle triangle;
uint32_t materialIdx;
uint32_t triangleIdx;
TriangleHolder(const Triangle& t, const uint32_t mIdx, const uint32_t tIdx) : triangle(t), materialIdx(mIdx), triangleIdx(tIdx) {};
};
BVHBuilder();
~BVHBuilder();
std::vector<Node> getBVH() const;
std::vector<Triangle> getTriangles() const;
std::vector<uint32_t> getTriangleMaterialIds() const;
std::vector<uint32_t> getLightTriangleIds() const;
void build(const std::vector<Triangle>& triangles, const std::vector<uint32_t>& triangleMaterialIds, const std::vector<uint32_t>& lightTriangles);
AABB computeBB(const Node node);
void sortTrisOnAxis(const Node& node, const unsigned int axis);
bool splitNode(const Node& node, Node& leftChild, Node& rightChild);
private:
SplitCandidate proposeSAHSplit(const Node& node);
SplitCandidate proposeSpatialSplit(const Node& node);
void performSplit(const SplitCandidate& split, const Node& node, Node& leftChild, Node& rightChild);
std::vector<Node> bvh_;
std::vector<TriangleHolder> triangles_;
std::vector<uint32_t> lightTriangleIds_;
std::vector<Material> bvhBoxMaterials_;
};
#endif // BVHBUILDER_HPP
| [
"jimmyenvall@gmail.com"
] | jimmyenvall@gmail.com |
aa8f2d85d396e0abcec9e5c32f559317889299e0 | 85afb13a42bac7a8d97596adb10dd75fb4740c57 | /bc2443885/2D_Structure_Edit/main.cpp | aeca846b7494a42b3285dbc4af99d25188548818 | [] | no_license | Riverside-City-College-Computer-Science/CSC17a_Spring_2014_42448 | d5af3276e8448c2f7246d0502d9c63fb420b8ab8 | 00eb8ae546d7b1885157b14ca6351268d8612d4e | refs/heads/master | 2016-08-08T15:27:03.511134 | 2014-06-27T05:53:00 | 2014-06-27T05:53:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,512 | cpp | /*
* File: main.cpp
* Author: Dr. Mark E. Lehr
* Created on September 23, 2013, 8:22 PM
*/
//System Libraries
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
//Our Libraries
#include "Array.h"
#include "Array2d.h"
//Global Constants
const int ROW = 10;
//Function Prototypes
Array *filStrct(int);
void prntStrc(Array *,int);
void dstrStr(Array *);
//Create and implement
Array2d *filStrc2(int,int);
void prntStrc(Array2d *,int);
void dstrStr(Array2d *);
int main(int argc, char** argv) {
//Initialize random number seed
srand(static_cast<unsigned int>(time(0)));
//1D Arrays
cout<<"1D Array: "<<endl;
//Allocate the array structure
Array *array1=filStrct(100);
//Print the structure
prntStrc(array1,10);
//Deallocate memory
dstrStr(array1);
//2D Arrays
cout<<"2D Array: "<<endl;
Array2d *d2Arr = filStrc2(10,10);
prntStrc(d2Arr,10);
//Deallocate memory
dstrStr(d2Arr);
//Exit stage right
return 0;
}
//1D functions
void dstrStr(Array *a){
//Deallocate the data first
delete [] a->data;
//Deallocate the array structure
delete a;
}
void prntStrc(Array *a,int colPRow){
//Output the array
cout<<endl;
for(int i=0;i<a->size;i++){
cout<<a->data[i]<<" ";
if(i%colPRow==(colPRow-1))
cout<<endl;
}
cout<<endl;
}
Array *filStrct(int n){
//Create the pointer to a structure
Array *a=new Array;
//Set the size of the array in the structure
a->size=n;
//Allocate the array
a->data=new int[n];
//Fill the array
for(int i=0;i<n;i++){
a->data[i]=rand()%90+10;
}
//Return the structure
return a;
}
//2D functions
Array2d *filStrc2(int c,int r){
//Create pointer
Array2d *a = new Array2d;
//Set sizes
a->col = c;
a->row = r;
//Allocate
int **temp = new int *[c];
for(int i=0;i<c;i++){
temp[i] = new int [r];
}
//Fill
for(int i=0;i<r;i++)
for(int j=0;j<c;j++)
temp[i][j]=rand()%90+10;
//Return structure
a->data = temp;
return a;
}
void prntStrc(Array2d *a,int l){
cout<<endl;
for(int i=0;i<a->row;i++){
for(int j=0;j<a->col;j++){
cout<<a->data[i][j]<<" ";
if(j%l==(l-1))
cout<<endl;
}
}
}
void dstrStr(Array2d *a){
//Deallocate the data first
delete [] a->data;
//Deallocate the array structure
delete a;
} | [
"braddley.carey@gmail.com"
] | braddley.carey@gmail.com |
a6cefc2a823b6bacad577f448242dc97294f2cf1 | 18b69a7cffa025d815ac765f07dd13e897536994 | /include/trajectory_optimization/mapModuleOctomap.h | 710cb37addc495668264ff2eba1b0d2a49044f84 | [] | no_license | Forrest-Z/trajectory_optimization | b45f990c3d49b6be1e7899c3bb4438442791561e | 5a3a08fea0521206d5a017f20d8f876721abf604 | refs/heads/main | 2023-06-29T03:05:49.782740 | 2021-08-04T11:32:01 | 2021-08-04T11:32:01 | 392,894,150 | 1 | 0 | null | 2021-08-05T03:46:50 | 2021-08-05T03:46:50 | null | UTF-8 | C++ | false | false | 1,277 | h | #ifndef MAPMODULEOCTOMAP_H
#define MAPMODULEOCTOMAP_H
#include<ros/ros.h>
#include<trajectory_optimization/utils.h>
#include<octomap/OcTree.h>
#include<octomap_msgs/GetOctomap.h>
#include<octomap_msgs/Octomap.h>
#include<octomap_msgs/conversions.h>
using namespace octomap;
using namespace std;
class mapModule{
private:
ros::NodeHandle nh;
ros::ServiceClient octomap_client;
OcTree* tree_ptr;
AbstractOcTree* abtree;
double res;
// Robot paramters
double xsize, ysize, zsize; // robot size
public:
mapModule(const ros::NodeHandle& _nh);
mapModule(const ros::NodeHandle& _nh, double _res);
mapModule(const ros::NodeHandle& _nh, double _res, double _xsize, double _ysize, double _zsize);
void updateMap(); // update tree_ptr
bool checkCollision(point3d p); // check point collision
bool checkCollision(pose p); //check point collision
bool checkCollisionRobot(point3d p); // collision check for robot
bool checkCollisionRobot(pose p); // collision check for robot
bool checkCollisionTrajectory(std::vector<pose> trajectory, std::vector<int>& collision_idx);
bool checkCollisionLine(point3d p1, point3d p2);
bool checkCollisionLine(pose p1, pose p2);
std::vector<pose> shortcutWaypointPath(std::vector<pose> path);
double getMapResolution();
};
#endif | [
"zhefanx@andrew.cmu.edu"
] | zhefanx@andrew.cmu.edu |
8888c428f14e12cca8501bd671098ad1c3da79bb | a29c13fa4c58d566270fb640a4d1f184f92c1223 | /04_Data/01_Measured_Data/01_Testing_of_WECS/2019 05 12 11 58 23/_20190510_Control_v13.6_ohneSD_6040/_20190510_Control_v13.6_ohneSD_6040.ino | 53bb0f9bc481e3004ff2bf1e02a9958fc28c3623 | [] | no_license | li-bre/li-bre-wind | e15bc80f955d02731fe6e7eb255f24478a2395ae | d65584798c48461484e3a3531797612e3ba18c32 | refs/heads/master | 2022-02-28T15:32:22.893410 | 2022-02-08T15:54:47 | 2022-02-08T15:54:47 | 232,623,593 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,270 | ino | // High Speed (32kHz) PWM MOSFET-Ansteuerung mit Poti Regelung der PWM Anzeioge über LCD
// MS (Motorsteuerung als PWM ebenfalls über Poti
// Analog Digital Wandler zur Spannungsmessung mit ADS1115 _v8 = Mit Dumpload
#include <LiquidCrystal_I2C.h>
#include <Wire.h>
#include <Adafruit_ADS1015.h>
#include <DS3231.h>
#include <SPI.h>
#include <SD.h>
// PINS /////////////
const int MS_RPM_interrupt_PIN=2;
const int Gen_PWM_interrupt_PIN = 3;
const int MS_outputPin = 4;
const int Relais_FET_PIN=5;
const int MS_Sensor_pulsewidth_PIN=7;
const int Dumpload_FET=8;
const int Short_Break_FET=9;
const int DCDC_Treiber_SD_Quer=10;
const int DCDC_PWM_PIN = 11;
const int wind_interrupt_PIN = 18;
const int Sec_interrupt_PIN=19;
const int Status_LED_red=22;
const int Status_LED_yellow=23;
const int Status_LED_blue=24;
const int Status_LED_green=25;
const int SU_LED_Pin=6;
const int SU_Gen_Start_PIN=35;
const int SD_Card_CS = 53;
#define DS3231_ADDRESSE 0x68
DS3231 clock;
RTCDateTime dt;
int Sec=0;
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); // Set the LCD I2C address// PINS /////////////
int Battery_full=0;
const float Battery_V2_High=14;
const float Battery_V2_Low=12.5;
byte LED_yellow = 0; //0=Off, 1=blink, 2=on;
byte LED_blue = 0;
byte LED_red = 0;
byte LED_green = 0;
bool LED_blink_yellow_stat = false;
bool LED_blink_blue_stat = false;
bool LED_blink_red_stat = false;
bool LED_blink_green_stat = false;
int Dumpload=0; //0=OFF, 1=ON;
int Short_Break=0; //0=OFF, 1=ON;
int MS_V1_target=38; //Voltage for Motor Start Up
const int MS_DCDC_PWM_0=240; //starting DCDC PWM to reach MS_V1_target
int MS_DCDC_PWM=240; //DCDC PWM during Start_Up
int MS_DCDC_PWM_P=2; //P-Value for Voltage V1 Control
int MS_DCDC_Delta_PWM;
int MS_RPM=0;
int MS_RPM_target=225;
int MS_tick = 0; //Counter for Motor RPM
int MS_tick_fin=0; //Counter for Motor RPM
const int MS_RPM_m_time=1; // Zeit der RMP-Messung in Sekunden
int MS_RPM_frac=75; // Anzahl der Signale des "Signal" PIN der Motorsteuerung pro Umdrehung (experimentell ermittelt)
int MS_sensorValue = 0; // variable to store the value coming from the sensor
byte Relais_state=0;
const int wind_m_time = 3; //Meassuretime in Seconds
int wind_ct = 0; // Wind counter
int wind_ct_fin = 0; // Wind counter
float wind_v1 = 0.0; // V1 in m/s
const float wind_v1_factor = 0.66; // V1 in m/s
int wind_status=0; //1: Low, 2:Intermediate, 3: Too high
const int wind_v1_cut_in=1;
float wind_v1_mean=0;
String now_st;
unsigned long now;
// int SU=0;
unsigned long SU_start_time=0;
unsigned long SU_step_time=0;
unsigned long SU_start_time_max=1000;
int SU_MS=0;
int SU_MS_stepsize=0;
int SU_MS_P=1; //P-Value for MS P_controller
const int SU_stable_tryouts = 6; //Wie viele Durchläufe = gleichzeitig max. Stabilitätszahl
const int SU_Signal_tests=5; //Wie viele Proben pro Durchlauf die verglichen werden
unsigned int SU_Signal_length[SU_Signal_tests]; //Länge der Signal HIGHs aus dem Controller
unsigned int SU_Signal_length_min;
unsigned int SU_Signal_length_max;
int SU_stable = 0; //Stabilitätszahl
int SU_i=0; //Durchlaufvariable
float SU_P_1_target= 0;
const int SU_P_1_max= 75; //Maximale Leistung
int SU_Gen_Start_Counter=0;
int SU_finished=0;
int Gen_RPM_frac=26;
int Gen_RPM=0;
int Gen_RPM_A=0; // _A -> for MPPT Step -1
int Gen_tick = 0;
int Gen_tick_fin=0;
float V_1=0;
float V_2=0;
float V_2_A=0;
float I_1=0;
float I_2=0;
float I_2_A=0;
float P_1 = 0;
float P_2 = 0;
float P_2_A = 0;
Adafruit_ADS1115 ads; /* Use this for the 16-bit version */
// Adafruit_ADS1015 ads; // Use this for the 12-bit version
const int samplelength=20;
int32_t adc0_mean;
int32_t adc1_mean;
int32_t adc2_mean;
int32_t adc3_mean;
int i;
int j;
File dataFile;
String filename;
String dataString = "";
const int MPPT_wind_v1_epsilon=10; // <- experimentally derived, if bigger than this, change in v1 is detected
const int MPPT_delta_DCDC_PWM_0=2;
const int MPPT_delta_omega_epsilon=4;
const int MPPT_delta_P_2_epsilon=2;
const int MPPT_delta_omega_stern_epsilon=8;
int MPPT_delta_DCDC_PWM=MPPT_delta_DCDC_PWM_0;
int MPPT_DCDC_PWM=200;
int MPPT_DCDC_PWM_A=0;
float MPPT_omega=0;
float MPPT_omega_stern=0;
float MPPT_omega_A=0;
float MPPT_omega_opt=0;
float MPPT_delta_Omega=0;
float MPPT_kopt=0;
float MPPT_P_2_opt=0;
float MPPT_delta_P_2=0;
float MPPT_delta_P_2_A=0;
byte MPPT_delta_wind_v1=0;
byte MPPT_delta_wind_v1_A=0;
int MPPT_delta_wind_v1_Reason=0;
byte MPPT_MODE=0;
float MPPT_beta=0.35;
const int V_1_cut_out=80;
float wind_v1_cut_out=8;
const int Gen_RPM_cut_out=500;
const int P_1_cut_out=100;
void setup() {
Serial.begin(9600);
// Initialize DS3231
Serial.println("Initialize DS3231");;
Wire.begin();
Wire.beginTransmission(DS3231_ADDRESSE);
Wire.write(0x0e); // DS3231 Register zu 0Eh
Wire.write(B01100011); // Register schreiben
Wire.endTransmission();
clock.begin();
//clock.setDateTime(__DATE__, __TIME__); // Set clock to sketch compiling time: only for first start then remove and compile again
delay(20);
// Serial.print("Initializing SD card...");
// if (!SD.begin(SD_Card_CS)) { // see if the card is present and can be initialized:
// Serial.println("Card failed, or not present"); // don't do anything more:
// return;
// }
// Serial.println("card initialized.");
dt = clock.getDateTime();
filename += String(clock.dateFormat("mdHi", dt));
filename += ".txt";
dataFile = SD.open(filename, FILE_WRITE);
if (dataFile) { // if the file is available, write to it
dataFile.println(" ");
Serial.print(filename);
Serial.println(" open");
} else { // if the file isn't open, pop up an error:
Serial.print("error opening ");
Serial.println(filename);
}
// set up the LCD's number of columns and rows:
lcd.begin(20, 4);
lcd.setCursor(0,0);
lcd.print("Buenas Dias Julian");
pinMode(MS_outputPin, OUTPUT);
pinMode(Relais_FET_PIN, OUTPUT);
pinMode(MS_Sensor_pulsewidth_PIN, INPUT);
pinMode(DCDC_Treiber_SD_Quer, OUTPUT); //SD_Q Sicherheit des MOSFET-Treibers
pinMode(DCDC_PWM_PIN, OUTPUT);
pinMode(Status_LED_yellow, OUTPUT);
pinMode(Status_LED_blue, OUTPUT);
pinMode(Status_LED_red, OUTPUT);
pinMode(Status_LED_green, OUTPUT);
pinMode(Dumpload_FET, OUTPUT);
pinMode(Short_Break_FET, OUTPUT);
pinMode(SU_LED_Pin, OUTPUT);
pinMode(SU_Gen_Start_PIN, OUTPUT);
pinMode(SD_Card_CS, OUTPUT);
TCCR0B = (TCCR0B & 0b11111000) | 0x03;
TCCR1B = (TCCR1B & 0b11111000) | 0x01;
TCCR2B = (TCCR2B & 0b11111000) | 0x03;
// Auflösung des ADC einstellen
ads.setGain(GAIN_ONE); const float ADC_faktor=0.125; // 1x gain +/- 4.096V 1 bit = 2mV 0.125mV 6 MOhm
ads.begin();
// //////////////// Interrupts /////////////////////////////////////////
attachInterrupt(digitalPinToInterrupt(Gen_PWM_interrupt_PIN), Gen_RPM_count, RISING);
attachInterrupt(digitalPinToInterrupt(Sec_interrupt_PIN), Sec_count, RISING);
attachInterrupt(digitalPinToInterrupt(wind_interrupt_PIN), wind_count, RISING);
attachInterrupt(digitalPinToInterrupt(MS_RPM_interrupt_PIN), MS_RPM_count, RISING);
Serial.println ("Year Month Day Hour Minute Second V1 V2 I1 I2 P1 P2 SU_MS SU_Stability MS MS_RPM Gen_RPM SU_P_1_target SU_Gen_Start_Counter Relais_state wind_v1 wind_v1_mean wind_v1_cut_out wind_status Battery_full MS_DCDC_PWM Dumpload Short_Break MPPT_MODE MPPT_delta_wind_v1 MPPT_delta_wind_v1_Reason MPPT_DCDC_PWM MPPT_omega_stern MPPT_omega_opt MPPT_kopt*10^6 MPPT_P_2_opt MPPT_delta_P_2 MPPT_delta_Omega Codepoint");
dataFile.println("Year Month Day Hour Minute Second V1 V2 I1 I2 P1 P2 SU_MS SU_Stability MS MS_RPM Gen_RPM SU_P_1_target SU_Gen_Start_Counter Relais_state wind_v1 wind_v1_mean wind_v1_cut_out wind_status Battery_full MS_DCDC_PWM Dumpload Short_Break MPPT_MODE MPPT_delta_wind_v1 MPPT_delta_wind_v1_Reason MPPT_DCDC_PWM MPPT_omega_stern MPPT_omega_opt MPPT_kopt*10^6 MPPT_P_2_opt MPPT_delta_P_2 MPPT_delta_Omega Codepoint");
dataFile.flush();
delay(2000);
}
void loop() {
Measure();
Print_data_Serial("1");
LCD_print();
if (V_2 >= Battery_V2_High) Battery_full=1;
else if (V_2 <= Battery_V2_Low) Battery_full=0;
if (Battery_full==0) {
if (Gen_RPM == 0) {
while (MS_DCDC_PWM<(MS_DCDC_PWM_0-10)) {
MS_DCDC_PWM=MS_DCDC_PWM+10;
analogWrite(DCDC_PWM_PIN,MS_DCDC_PWM);
delay(500);
}
MS_DCDC_PWM=MS_DCDC_PWM_0;
analogWrite(DCDC_PWM_PIN,MS_DCDC_PWM);
MPPT_reset();
clearLED();
LED_yellow=1;
wind_check();
Measure();
Print_data_Serial("2");
LCD_print();
switch (wind_status) {
case 1:
clearLED();
LED_yellow=1;
delay (10000); //Lange warten + Energie sparen
break;
case 2:
clearLED();
LED_green=1;
Start_Up();
break;
case 3:
clearLED();
LED_red=1;
decelerate();
delay (10000); //Lange warten + Energie sparen
break;
}
}
else if (Gen_RPM > 0) {
if (wind_v1 >= wind_v1_cut_out ) {
MPPT_reset();
clearLED();
LED_red=1;
decelerate();
} else {
if (P_1 > P_1_cut_out || V_1 > V_1_cut_out || Gen_RPM > Gen_RPM_cut_out) {
//Maybe include an average calculation here to avoid false decrease of wind_v1_cut_out
MPPT_reset();
clearLED();
LED_red=1;
wind_v1_cut_out=wind_v1;
decelerate();
} else {
clearLED();
LED_green=2;
MPPT();
}
}
}
} else if (Battery_full==1) {
clearLED();
LED_red=2;
decelerate();
delay (10000); //Lange warten + Energie sparen
}
// Print_data_Serial("20");
}
///////////////////// END OF LOOP ///////////////////////////////////////////////////
| [
"samz@gmx.de"
] | samz@gmx.de |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.