blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
9d53111dc1d3ab953f7bdfb9be75e7384004fa2f
3a86586871b35b1ad4f19c64ea3d9e7f10ba382f
/u2/engine/include/core/U2GameObject.h
418679b0b7a5e234968296870154c3a17cbf13e8
[ "MIT" ]
permissive
jrsnail/u2project_logic
598c631caf76d9fa53ad66d7e7e8e801d649ee3c
099647bb5f999831532d846776781f5ee05a8971
refs/heads/master
2020-04-16T10:56:53.035031
2016-09-16T05:25:53
2016-09-16T05:25:53
51,911,880
0
0
null
null
null
null
UTF-8
C++
false
false
8,444
h
#ifndef __U2GameObject__ #define __U2GameObject__ #include "U2Prerequisites.h" #include "U2STLRedefined.h" #include "U2Prototype.h" #include "U2ResourceManager.h" #include "U2TypedObjectManager.h" #include "U2Singleton.h" class TiXmlElement; U2EG_NAMESPACE_BEGIN class Component; class GameObject : public Resource, public Prototype<GameObject> { public: class Listener { public: virtual void onAttachComponent(GameObject* gameObj, Component* comp) = 0; virtual void onDetachComponent(GameObject* gameObj, Component* comp) = 0; }; public: // <type, u2::Component*> typedef std::multimap<String, u2::Component*> TypedComponentMap; typedef std::pair<TypedComponentMap::iterator, TypedComponentMap::iterator> ComponentPair; // <type, GameObject*> typedef std::multimap<String, GameObject*> TypedGameObjectMap; typedef std::pair<TypedGameObjectMap::iterator, TypedGameObjectMap::iterator> GameObjectPair; public: GameObject(ResourceManager* creator, const String& type, ResourceHandle handle, const String& group, bool isManual = false, ManualResourceLoader* loader = 0); GameObject(const String& type, const String& name = BLANK, const String& guid = BLANK); virtual ~GameObject(); virtual void copy(const GameObject& src); virtual GameObject* cloneFromPrototype(const String& name = BLANK, const String& guid = BLANK) override; virtual GameObject* cloneFromInstance(const String& name = BLANK, const String& guid = BLANK) override; virtual void resetFromPrototype() override; virtual void applyToPrototype() override; u2::Component* createComponent(const String& type, const String& name = BLANK, const String& guid = BLANK); void destroyComponent(u2::Component* comp); void destroyAllComponents(); void addComponent(u2::Component* comp); void removeComponent(u2::Component* comp); typedef MapIterator<TypedComponentMap> ComponentMapIterator; typedef ConstMapIterator<TypedComponentMap> ConstComponentMapIterator; ComponentMapIterator retrieveComponentsByType(const String& type) { ComponentPair p = m_ComponentMap.equal_range(type); return ComponentMapIterator(p.first, p.second); } u2::Component* retrieveComponentByType(const String& type) const { TypedComponentMap::const_iterator it = m_ComponentMap.find(type); if (it == m_ComponentMap.end()) { return nullptr; } else { return it->second; } } ComponentMapIterator retrieveAllComponents() { return ComponentMapIterator(m_ComponentMap.begin(), m_ComponentMap.end()); } ConstComponentMapIterator retrieveConstAllComponents() const { return ConstComponentMapIterator(m_ComponentMap.begin(), m_ComponentMap.end()); } u2::Component* retrieveComponentByGuid(const String& guid); GameObject* createChildGameObject(const String& type, const String& name = BLANK, const String& guid = BLANK); void destroyChildGameObject(GameObject* gameObj); void destroyAllChildGameObjects(); void addChildGameObject(GameObject* gameObj); void removeChildGameObject(GameObject* gameObj); typedef MapIterator<TypedGameObjectMap> GameObjectMapIterator; typedef ConstMapIterator<TypedGameObjectMap> ConstGameObjectMapIterator; GameObjectMapIterator retrieveAllChildGameObjects() { return GameObjectMapIterator(m_GameObjMap.begin(), m_GameObjMap.end()); } ConstGameObjectMapIterator retrieveConstAllChildGameObjects() const { return ConstGameObjectMapIterator(m_GameObjMap.begin(), m_GameObjMap.end()); } GameObject* retrieveChildGameObjectByGuid(const String& guid); GameObject* retrieveParentGameObject(); void addListener(Listener* listener); void removeListener(Listener* listener); virtual bool _loadFromXml(const TiXmlElement* gameObjElem, String& error); protected: /// @copydoc Resource::loadImpl virtual void loadImpl(void) override; /// @copydoc Resource::unloadImpl virtual void unloadImpl(void) override; protected: TypedComponentMap m_ComponentMap; TypedGameObjectMap m_GameObjMap; GameObject* m_pParentGameObj; typedef vector<Listener*>::type ListenerList; ListenerList m_Listeners; }; typedef std::shared_ptr<GameObject> GameObjectPtr; class GameObjectManager : public ResourceManager, public GameObject::Listener, public Singleton < GameObjectManager > { friend GameObject; public: struct StGameObjRef { GameObject* pGameObj; size_t uRefCount; StGameObjRef(GameObject* gameObj, size_t refCount) : pGameObj(gameObj) , uRefCount(refCount) { } }; // <Component type, StGameObjRef> typedef std::multimap<String, StGameObjRef> CompRefMap; typedef std::pair<CompRefMap::iterator, CompRefMap::iterator> CompRefPair; public: GameObjectManager(); virtual ~GameObjectManager(); /// @copydoc ScriptLoader::parseScript virtual void parseScript(InStreamPtr& stream, const String& groupName) override; virtual Resource* createImpl(const String& name, ResourceHandle handle, const String& group, bool isManual, ManualResourceLoader* loader, const NameValuePairList* createParams) override; /// @see ResourceManager::createResource GameObjectPtr create(const String& name, const String& group, bool isManual = false, ManualResourceLoader* loader = 0, const NameValuePairList* createParams = 0); GameObject* createObject(const String& type, const String& name = BLANK, const String& guid = BLANK); void destoryObject(GameObject* obj); GameObject* retrieveObjectByTN(const String& type, const String& name); TypedObjectManager<GameObject>::ObjectMapIterator retrieveAllObjectsByType(const String& type); GameObject* retrieveObjectByGuid(const String& guid); GameObject* retrieveObjectByType(const String& type); virtual void onAttachComponent(GameObject* gameObj, Component* comp) override; virtual void onDetachComponent(GameObject* gameObj, Component* comp) override; typedef MapIterator<CompRefMap> CompRefMapIterator; typedef ConstMapIterator<CompRefMap> ConstCompRefMapIterator; CompRefMapIterator retrieveAllGameObjectsByCompType(const String& type) { CompRefPair p = m_CompRefMap.equal_range(type); return CompRefMapIterator(p.first, p.second); } protected: GameObject* _createObject(const String& type, const String& name = BLANK, const String& guid = BLANK); public: /** Override standard Singleton retrieval. @remarks Why do we do this? Well, it's because the Singleton implementation is in a .h file, which means it gets compiled into anybody who includes it. This is needed for the Singleton template to work, but we actually only want it compiled into the implementation of the class based on the Singleton, not all of them. If we don't change this, we get link errors when trying to use the Singleton-based class from an outside dll. @par This method just delegates to the template version anyway, but the implementation stays in this single compilation unit, preventing link errors. */ static GameObjectManager& getSingleton(void); /** Override standard Singleton retrieval. @remarks Why do we do this? Well, it's because the Singleton implementation is in a .h file, which means it gets compiled into anybody who includes it. This is needed for the Singleton template to work, but we actually only want it compiled into the implementation of the class based on the Singleton, not all of them. If we don't change this, we get link errors when trying to use the Singleton-based class from an outside dll. @par This method just delegates to the template version anyway, but the implementation stays in this single compilation unit, preventing link errors. */ static GameObjectManager* getSingletonPtr(void); protected: TypedObjectManager<GameObject> m_InstanceCollection; CompRefMap m_CompRefMap; }; U2EG_NAMESPACE_END #endif /* defined(__U2Entity__) */
[ "jr19841227@gmail.com" ]
jr19841227@gmail.com
004198bfeb00de19c3b5b79a7dcfa8f664330d70
639e676638bcfef43c7eae49c4e2ab4a6085d69b
/ExamplesMain/src/main.cpp
c8c5da5898366adafc3652eac74c8f76bd9bf7ec
[]
no_license
99lives/UltraTinyHttp
a502bc2fff42a7fedd174acff659fdc217fb6660
cc36a27f826891222d4a879b23f2e95d2c2808cb
refs/heads/master
2021-01-13T01:46:07.262444
2011-09-16T16:45:28
2011-09-16T16:45:28
2,279,497
2
1
null
null
null
null
UTF-8
C++
false
false
899
cpp
/* * This file is part of the Marmalade SDK Code Samples. * * Copyright (C) 2001-2011 Ideaworks3D Ltd. * All Rights Reserved. * * This source code is intended only as a supplement to Ideaworks Labs * Development Tools and/or on-line documentation. * * THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY * KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A * PARTICULAR PURPOSE. */ #include "ExamplesMain.h" //----------------------------------------------------------------------------- // Main global function //----------------------------------------------------------------------------- int main() { ExamplesMainInit(); // Example main loop while (!ExampleCheckQuit()) { if (!ExamplesMainUpdate()) break; } ExamplesMainTerm(); return 0; }
[ "petehobo@gmail.com" ]
petehobo@gmail.com
7381fc3bbff71db184d6060dbc2ccf81b96913d7
bd593920c0a9a06cbf9b20d5499498285d08dcf8
/project2/Movie.hpp
99b11a9840cc23b6ceef7f5d8840d57f1e4e7e66
[]
no_license
wy7318/C-stuff
a3549198edfda4ce82e1530bebc516a72a71b2b0
306a99d32942f1d7ad28ffa9d70f402294fec6da
refs/heads/master
2020-04-19T15:03:04.817490
2019-01-30T02:17:46
2019-01-30T02:17:46
168,263,027
0
0
null
null
null
null
UTF-8
C++
false
false
483
hpp
#include <string> #include <iostream> using namespace std; class Movie { private: string title; string director; int year; string rating; public: Movie(); Movie(string, string, int, string); void setTitle(string); void setDirector(string); void setYear(int); void setRating(string); string getTitle(); string getDirector(); int getYear(); string getRating(); void get_movie(); void print_movie(); bool same_year(Movie); ~Movie(); };
[ "noreply@github.com" ]
noreply@github.com
f03664ff9743d081048e6b36a792b93bdb946bb1
7268f845ea8cd66d443212d20dc13dcfe840219e
/剑指 Offer 59 - I. 滑动窗口的最大值.cpp
93842398d828f378883eb9093e62639606299fd0
[]
no_license
watermelonyip/leetcode
5cb02bc7f0531fc31304cab32a66aa2ee8aa7a54
b7e59bfb76258f76973e3e0d7ed27d5762731c9e
refs/heads/main
2023-03-22T22:18:19.936557
2021-03-17T07:50:54
2021-03-17T07:50:54
318,970,710
0
0
null
null
null
null
UTF-8
C++
false
false
1,633
cpp
/* 给定一个数组 nums 和滑动窗口的大小 k,请找出所有滑动窗口里的最大值。提示:你可以假设 k 总是有效的,在输入数组不为空的情况下,1 ≤ k ≤ 输入数组的大小。 思路:用双端队列来辅助,新窗口即将输入的值从队列末尾开始比较,如果大于队列的值,那么队列的值pop_back;否则push_back到队列末尾(因为可能是以后窗口的最大值)。 然后需要判断位于队列前端的数字是否还在当前窗口内,如果不在则pop_front;否则位于队列最前面的数字就是当前窗口的最大值。注意的是为了方便比较,队列里面存放的是数字在数组里的下标。 时间复杂度O(n),空间复杂度O(k),其中n为数组大小,k为滑动窗口大小。 */ class Solution { public: vector<int> maxSlidingWindow(vector<int>& nums, int k) { vector<int> result; if(nums.size() <= 0 || k <= 0) return result; deque<int> index; for(int i = 0; i < k && i < nums.size(); i++){ while(!index.empty() && nums[i] >= nums[index.back()]) index.pop_back(); index.push_back(i); } for(int i = k; i < nums.size(); i++){ result.push_back(nums[index.front()]); while(!index.empty() && nums[i] >= nums[index.back()]) index.pop_back(); index.push_back(i); if(!index.empty() && index.front() <= (i - k)) index.pop_front(); } result.push_back(nums[index.front()]); return result; } };
[ "noreply@github.com" ]
noreply@github.com
8103fd1700531f01cb9c051c7b3adcab881fd241
af2d27c5eea582210d1ce65166f7b0211d6519f3
/3rd year, 2nd semester/Bluetooth Controlled Car - Design with Microprocessors/mbed.com Sources/motorsWrap/motorsWrap.h
e705b3fea908eb35f4f31806862200667c882c74
[]
no_license
dragosprju/academic-projects
8ac0679dac38b7df59ef177181d7bc6f6f85905a
d3aeecf8958e467d8fff755823d9fd22aab0b6d4
refs/heads/master
2022-11-28T05:04:11.661799
2020-08-06T11:24:01
2020-08-06T11:25:23
78,030,086
0
0
null
null
null
null
UTF-8
C++
false
false
675
h
#ifndef MOTORS_WRAP #define MOTORS_WRAP #include "mbed.h" #include "rtos.h" #include "leds.h" #include "motors.h" enum MotorsCommand { Hold, Accelerate, Decelerate, Brake, TiltLeft, TiltRight, RotateLeft, RotateRight }; class MotorsWrap { private: static Motors motors; static Leds leds; static MemoryPool<MotorsCommand, 16> cmdMPool; static Queue<MotorsCommand, 16> cmdQueue; static MotorsCommand cmd; static Mutex cmdMutex; static MotorsCommand getCmd(); public: static void putCmd(MotorsCommand cmd); static void run(void const* args); }; #endif
[ "drgprj@gmail.com" ]
drgprj@gmail.com
cf442421ad8e76ec97d137ee66e776aeb3b0f958
d8aa7ddfbec886b243cd59a9c6e3c7df3c9d5f14
/dlib/cpp_tokenizer/cpp_tokenizer_kernel_1.h
de7bf2f67c41a3fdeabe89096a0047cac27bdfce
[ "BSL-1.0", "BSD-2-Clause" ]
permissive
loran4d/mud
64e0840bc707141caeb16f8cb2dddb018e1fac27
2e0bbae7e4ca242f075f2b31b41a3856ad8469dd
refs/heads/main
2023-08-22T00:19:46.136790
2021-11-01T21:31:03
2021-11-01T21:31:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
23,790
h
// Copyright (C) 2005 Davis E. King (davisking@users.sourceforge.net) // License: Boost Software License See LICENSE.txt for the full license. #ifndef DLIB_CPP_TOKENIZER_KERNEl_1_ #define DLIB_CPP_TOKENIZER_KERNEl_1_ #include <string> #include <iostream> #include "cpp_tokenizer_kernel_abstract.h" #include "../algs.h" namespace dlib { namespace cpp_tok_kernel_1_helper { struct token_text_pair { std::string token; int type; }; } template < typename tok, typename queue, typename set > class cpp_tokenizer_kernel_1 { /*! REQUIREMENTS ON tok tok must be an implementation of tokenizer/tokenizer_kernel_abstract.h REQUIREMENTS ON queue queue must be an implementation of queue/queue_kernel_abstract.h and must have T==cpp_tok_kernel_1_helper::token_text_pair REQUIREMENTS ON set set must be an implemention of set/set_kernel_abstract.h or hash_set/hash_set_kernel_abstract.h and must have T==std::string. INITIAL VALUE - keywords == a set of all the C++ keywords - tokenizer.stream_is_set() == false - buffer.size() == 0 - tokenizer.get_identifier_head() == "$_" + tokenizer.lowercase_letters() + tokenizer.uppercase_letters() - tokenizer.get_identifier_body() == "$_" + tokenizer.lowercase_letters() + tokenizer.uppercase_letters() + tokenizer.numbers() - have_peeked == false CONVENTION - tokenizer.stream_is_set() == stream_is_set() - tokenizer.get_stream() == get_stream() - keywords == a set of all the C++ keywords - tokenizer.get_identifier_head() == "$_" + tokenizer.lowercase_letters() + tokenizer.uppercase_letters() - tokenizer.get_identifier_body() == "$_" + tokenizer.lowercase_letters() + tokenizer.uppercase_letters() + tokenizer.numbers() - buffer == a queue of tokens. This is where we put tokens we gathered early due to looking ahead. - if (have_peeked) then - next_token == the next token to be returned from get_token() - next_type == the type of token in peek_token !*/ typedef cpp_tok_kernel_1_helper::token_text_pair token_text_pair; public: enum { END_OF_FILE, KEYWORD, COMMENT, SINGLE_QUOTED_TEXT, DOUBLE_QUOTED_TEXT, IDENTIFIER, OTHER, NUMBER, WHITE_SPACE }; cpp_tokenizer_kernel_1 ( ); virtual ~cpp_tokenizer_kernel_1 ( ); void clear( ); void set_stream ( std::istream& in ); bool stream_is_set ( ) const; std::istream& get_stream ( ) const; void get_token ( int& type, std::string& token ); int peek_type ( ) const; const std::string& peek_token ( ) const; void swap ( cpp_tokenizer_kernel_1<tok,queue,set>& item ); private: void buffer_token( int type, const std::string& token ) /*! ensures - stores the token and its type into buffer !*/ { token_text_pair temp; temp.token = token; temp.type = type; buffer.enqueue(temp); } void buffer_token( int type, char token ) /*! ensures - stores the token and its type into buffer !*/ { token_text_pair temp; temp.token = token; temp.type = type; buffer.enqueue(temp); } // restricted functions cpp_tokenizer_kernel_1(const cpp_tokenizer_kernel_1<tok,queue,set>&); // copy constructor cpp_tokenizer_kernel_1<tok,queue,set>& operator=(const cpp_tokenizer_kernel_1<tok,queue,set>&); // assignment operator // data members set keywords; queue buffer; tok tokenizer; mutable std::string next_token; mutable int next_type; mutable bool have_peeked; }; template < typename tok, typename queue, typename set > inline void swap ( cpp_tokenizer_kernel_1<tok,queue,set>& a, cpp_tokenizer_kernel_1<tok,queue,set>& b ) { a.swap(b); } // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- // member function definitions // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- template < typename tok, typename queue, typename set > cpp_tokenizer_kernel_1<tok,queue,set>:: cpp_tokenizer_kernel_1( ) : have_peeked(false) { // add C++ keywords to keywords std::string temp; temp = "#include"; keywords.add(temp); temp = "__asm"; keywords.add(temp); temp = "_asm"; keywords.add(temp); temp = "if"; keywords.add(temp); temp = "int"; keywords.add(temp); temp = "else"; keywords.add(temp); temp = "template"; keywords.add(temp); temp = "void"; keywords.add(temp); temp = "false"; keywords.add(temp); temp = "class"; keywords.add(temp); temp = "public"; keywords.add(temp); temp = "while"; keywords.add(temp); temp = "bool"; keywords.add(temp); temp = "new"; keywords.add(temp); temp = "delete"; keywords.add(temp); temp = "true"; keywords.add(temp); temp = "typedef"; keywords.add(temp); temp = "const"; keywords.add(temp); temp = "virtual"; keywords.add(temp); temp = "inline"; keywords.add(temp); temp = "for"; keywords.add(temp); temp = "break"; keywords.add(temp); temp = "struct"; keywords.add(temp); temp = "float"; keywords.add(temp); temp = "case"; keywords.add(temp); temp = "enum"; keywords.add(temp); temp = "this"; keywords.add(temp); temp = "typeid"; keywords.add(temp); temp = "double"; keywords.add(temp); temp = "char"; keywords.add(temp); temp = "typename"; keywords.add(temp); temp = "signed"; keywords.add(temp); temp = "friend"; keywords.add(temp); temp = "wint_t"; keywords.add(temp); temp = "default"; keywords.add(temp); temp = "asm"; keywords.add(temp); temp = "reinterpret_cast"; keywords.add(temp); temp = "#define"; keywords.add(temp); temp = "do"; keywords.add(temp); temp = "continue"; keywords.add(temp); temp = "auto"; keywords.add(temp); temp = "unsigned"; keywords.add(temp); temp = "size_t"; keywords.add(temp); temp = "#undef"; keywords.add(temp); temp = "#pragma"; keywords.add(temp); temp = "namespace"; keywords.add(temp); temp = "private"; keywords.add(temp); temp = "#endif"; keywords.add(temp); temp = "catch"; keywords.add(temp); temp = "#else"; keywords.add(temp); temp = "register"; keywords.add(temp); temp = "volatile"; keywords.add(temp); temp = "const_cast"; keywords.add(temp); temp = "#end"; keywords.add(temp); temp = "mutable"; keywords.add(temp); temp = "static_cast"; keywords.add(temp); temp = "wchar_t"; keywords.add(temp); temp = "#if"; keywords.add(temp); temp = "protected"; keywords.add(temp); temp = "throw"; keywords.add(temp); temp = "using"; keywords.add(temp); temp = "dynamic_cast"; keywords.add(temp); temp = "#ifdef"; keywords.add(temp); temp = "return"; keywords.add(temp); temp = "short"; keywords.add(temp); temp = "#error"; keywords.add(temp); temp = "#line"; keywords.add(temp); temp = "explicit"; keywords.add(temp); temp = "union"; keywords.add(temp); temp = "#ifndef"; keywords.add(temp); temp = "try"; keywords.add(temp); temp = "sizeof"; keywords.add(temp); temp = "goto"; keywords.add(temp); temp = "long"; keywords.add(temp); temp = "#elif"; keywords.add(temp); temp = "static"; keywords.add(temp); temp = "operator"; keywords.add(temp); temp = "switch"; keywords.add(temp); temp = "extern"; keywords.add(temp); // set the tokenizer's IDENTIFIER token for C++ identifiers tokenizer.set_identifier_token( "$_" + tokenizer.lowercase_letters() + tokenizer.uppercase_letters(), "$_" + tokenizer.lowercase_letters() + tokenizer.uppercase_letters() + tokenizer.numbers() ); } // ---------------------------------------------------------------------------------------- template < typename tok, typename queue, typename set > cpp_tokenizer_kernel_1<tok,queue,set>:: ~cpp_tokenizer_kernel_1 ( ) { } // ---------------------------------------------------------------------------------------- template < typename tok, typename queue, typename set > void cpp_tokenizer_kernel_1<tok,queue,set>:: clear( ) { tokenizer.clear(); buffer.clear(); have_peeked = false; // set the tokenizer's IDENTIFIER token for C++ identifiers tokenizer.set_identifier_token( "$_" + tokenizer.lowercase_letters() + tokenizer.uppercase_letters(), "$_" + tokenizer.lowercase_letters() + tokenizer.uppercase_letters() + tokenizer.numbers() ); } // ---------------------------------------------------------------------------------------- template < typename tok, typename queue, typename set > void cpp_tokenizer_kernel_1<tok,queue,set>:: set_stream ( std::istream& in ) { tokenizer.set_stream(in); buffer.clear(); have_peeked = false; } // ---------------------------------------------------------------------------------------- template < typename tok, typename queue, typename set > bool cpp_tokenizer_kernel_1<tok,queue,set>:: stream_is_set ( ) const { return tokenizer.stream_is_set(); } // ---------------------------------------------------------------------------------------- template < typename tok, typename queue, typename set > std::istream& cpp_tokenizer_kernel_1<tok,queue,set>:: get_stream ( ) const { return tokenizer.get_stream(); } // ---------------------------------------------------------------------------------------- template < typename tok, typename queue, typename set > void cpp_tokenizer_kernel_1<tok,queue,set>:: get_token ( int& type, std::string& token ) { using namespace std; if (!have_peeked) { if (buffer.size() > 0) { // just return what is in the buffer token_text_pair temp; buffer.dequeue(temp); type = temp.type; token = temp.token; return; } tokenizer.get_token(type,token); switch (type) { case tok::END_OF_FILE: { type = END_OF_FILE; } break; case tok::END_OF_LINE: case tok::WHITE_SPACE: { type = tokenizer.peek_type(); if (type == tok::END_OF_LINE || type == tok::WHITE_SPACE) { std::string temp; do { tokenizer.get_token(type,temp); token += temp; type = tokenizer.peek_type(); }while (type == tok::END_OF_LINE || type == tok::WHITE_SPACE); } type = WHITE_SPACE; } break; case tok::NUMBER: { // this could be a hex number such as 0xa33. we should check for this. if (tokenizer.peek_type() == tok::IDENTIFIER && token == "0" && (tokenizer.peek_token()[0] == 'x' || tokenizer.peek_token()[0] == 'X')) { // this is a hex number so accumulate all the numbers and identifiers that follow // because they have to be part of the number std::string temp; tokenizer.get_token(type,temp); token = "0" + temp; // get the rest of the hex number while (tokenizer.peek_type() == tok::IDENTIFIER || tokenizer.peek_type() == tok::NUMBER ) { tokenizer.get_token(type,temp); token += temp; } } // or this could be a floating point value else if (tokenizer.peek_type() == tok::CHAR && tokenizer.peek_token()[0] == '.') { std::string temp; tokenizer.get_token(type,temp); token += '.'; // now get the rest of the floating point value while (tokenizer.peek_type() == tok::IDENTIFIER || tokenizer.peek_type() == tok::NUMBER ) { tokenizer.get_token(type,temp); token += temp; } } type = NUMBER; } break; case tok::IDENTIFIER: { if (keywords.is_member(token)) { type = KEYWORD; } else { type = IDENTIFIER; } } break; case tok::CHAR: type = OTHER; switch (token[0]) { case '#': { // this might be a preprocessor keyword so we should check the // next token if (tokenizer.peek_type() == tok::IDENTIFIER && keywords.is_member('#'+tokenizer.peek_token())) { tokenizer.get_token(type,token); token = '#' + token; type = KEYWORD; } else { token = '#'; type = OTHER; } } break; case '"': { string temp; tokenizer.get_token(type,token); while (type != tok::END_OF_FILE) { // if this is the end of the quoted string if (type == tok::CHAR && token[0] == '"' && (temp.size() == 0 || temp[temp.size()-1] != '\\' || (temp.size() > 1 && temp[temp.size()-2] == '\\') )) { buffer_token(DOUBLE_QUOTED_TEXT,temp); buffer_token(OTHER,'"'); break; } else { temp += token; } tokenizer.get_token(type,token); } type = OTHER; token = '"'; } break; case '\'': { string temp; tokenizer.get_token(type,token); if (type == tok::CHAR && token[0] == '\\') { temp += '\\'; tokenizer.get_token(type,token); } temp += token; buffer_token(SINGLE_QUOTED_TEXT,temp); // The next character should be a ' so take it out and put it in // the buffer. tokenizer.get_token(type,token); buffer_token(OTHER,token); type = OTHER; token = '\''; } break; case '/': { // look ahead to see if this is the start of a comment if (tokenizer.peek_type() == tok::CHAR) { if (tokenizer.peek_token()[0] == '/') { tokenizer.get_token(type,token); // this is the start of a line comment token = "//"; string temp; tokenizer.get_token(type,temp); while (type != tok::END_OF_FILE) { // if this is the end of the comment if (type == tok::END_OF_LINE && token[token.size()-1] != '\\' ) { token += '\n'; break; } else { token += temp; } tokenizer.get_token(type,temp); } type = COMMENT; } else if (tokenizer.peek_token()[0] == '*') { tokenizer.get_token(type,token); // this is the start of a block comment token = "/*"; string temp; tokenizer.get_token(type,temp); while (type != tok::END_OF_FILE) { // if this is the end of the comment if (type == tok::CHAR && temp[0] == '/' && token[token.size()-1] == '*') { token += '/'; break; } else { token += temp; } tokenizer.get_token(type,temp); } type = COMMENT; } } } break; default: break; } // switch (token[0]) } // switch (type) } else { // if we get this far it means we have peeked so we should // return the peek data. type = next_type; token = next_token; have_peeked = false; } } // ---------------------------------------------------------------------------------------- template < typename tok, typename queue, typename set > int cpp_tokenizer_kernel_1<tok,queue,set>:: peek_type ( ) const { const_cast<cpp_tokenizer_kernel_1<tok,queue,set>*>(this)->get_token(next_type,next_token); have_peeked = true; return next_type; } // ---------------------------------------------------------------------------------------- template < typename tok, typename queue, typename set > const std::string& cpp_tokenizer_kernel_1<tok,queue,set>:: peek_token ( ) const { const_cast<cpp_tokenizer_kernel_1<tok,queue,set>*>(this)->get_token(next_type,next_token); have_peeked = true; return next_token; } // ---------------------------------------------------------------------------------------- template < typename tok, typename queue, typename set > void cpp_tokenizer_kernel_1<tok,queue,set>:: swap ( cpp_tokenizer_kernel_1& item ) { tokenizer.swap(item.tokenizer); buffer.swap(item.buffer); } // ---------------------------------------------------------------------------------------- } #endif // DLIB_CPP_TOKENIZER_KERNEl_1_
[ "game-source@254f5b4c-bdf4-4503-907e-934c7b59e499" ]
game-source@254f5b4c-bdf4-4503-907e-934c7b59e499
5e43ffc9353202182cdac0f7570d719c15ac3e0d
6226d6aed3629aa4069c46971ffe764bb6c743f6
/Myway/Core/MWPlugin.h
612a855d6a17e1c8f052324f754aa32392d6ce69
[]
no_license
Myway3D/Myway3D
83c30258f1e3eae90e619269406acd0ddeac7887
39cf569993f62fc648cbba49ebf74b3f8a64e46a
refs/heads/master
2020-04-22T20:24:15.817427
2014-03-09T14:25:23
2014-03-09T14:25:23
170,640,096
2
1
null
null
null
null
UTF-8
C++
false
false
676
h
#pragma once #include "MWDebug.h" #include "MWSingleton.h" namespace Myway { class MW_ENTRY Plugin : public AllocObj { public: Plugin(const char * name); virtual ~Plugin(); const char * GetName(); virtual void Install() = 0; virtual void Uninstall() = 0; protected: char mName[32]; }; class MW_ENTRY PluginManager : public AllocObj { DECLARE_SINGLETON(PluginManager); static const int MAX_PLUGINS = 2000; public: PluginManager(); ~PluginManager(); void AddPlugin(Plugin * p); void InstallAll(); void UninstallAll(); protected: Plugin * mPlugins[MAX_PLUGINS]; }; }
[ "Myway3D@gmail.com@ff49bfeb-f889-bd78-9ae6-4dc862721fa0" ]
Myway3D@gmail.com@ff49bfeb-f889-bd78-9ae6-4dc862721fa0
3048d31055686d16347a984282ef4f9fa6eafd04
41b4adb10cc86338d85db6636900168f55e7ff18
/aws-cpp-sdk-ecs/include/aws/ecs/model/RegisterTaskDefinitionResult.h
745e3da4ef0a9ebf8db6c910f31256882985e2dc
[ "JSON", "MIT", "Apache-2.0" ]
permissive
totalkyos/AWS
1c9ac30206ef6cf8ca38d2c3d1496fa9c15e5e80
7cb444814e938f3df59530ea4ebe8e19b9418793
refs/heads/master
2021-01-20T20:42:09.978428
2016-07-16T00:03:49
2016-07-16T00:03:49
63,465,708
1
1
null
null
null
null
UTF-8
C++
false
false
2,256
h
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #pragma once #include <aws/ecs/ECS_EXPORTS.h> #include <aws/ecs/model/TaskDefinition.h> namespace Aws { template<typename RESULT_TYPE> class AmazonWebServiceResult; namespace Utils { namespace Json { class JsonValue; } // namespace Json } // namespace Utils namespace ECS { namespace Model { class AWS_ECS_API RegisterTaskDefinitionResult { public: RegisterTaskDefinitionResult(); RegisterTaskDefinitionResult(const AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); RegisterTaskDefinitionResult& operator=(const AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); /** * <p>The full description of the registered task definition.</p> */ inline const TaskDefinition& GetTaskDefinition() const{ return m_taskDefinition; } /** * <p>The full description of the registered task definition.</p> */ inline void SetTaskDefinition(const TaskDefinition& value) { m_taskDefinition = value; } /** * <p>The full description of the registered task definition.</p> */ inline void SetTaskDefinition(TaskDefinition&& value) { m_taskDefinition = value; } /** * <p>The full description of the registered task definition.</p> */ inline RegisterTaskDefinitionResult& WithTaskDefinition(const TaskDefinition& value) { SetTaskDefinition(value); return *this;} /** * <p>The full description of the registered task definition.</p> */ inline RegisterTaskDefinitionResult& WithTaskDefinition(TaskDefinition&& value) { SetTaskDefinition(value); return *this;} private: TaskDefinition m_taskDefinition; }; } // namespace Model } // namespace ECS } // namespace Aws
[ "henso@amazon.com" ]
henso@amazon.com
612292e810420ff4be79c216baaff3f5493fa885
d81385d2484a1d465477d58983f496ba6875f4d8
/src/joystick_manager_glfw.cpp
b59e74ad72cf2d1c0d3d0334887c2da4d33222cf
[ "MIT" ]
permissive
ChristopherHX/game-window
da42cde67722e3442a492c886f23b98442616e35
ce09f0fa0e3869bd2ff4b0f7916de166a21b90c3
refs/heads/master
2020-08-29T17:11:59.226786
2020-02-05T17:21:41
2020-02-05T17:21:41
218,106,090
2
0
null
2019-10-28T17:26:51
2019-10-28T17:26:50
null
UTF-8
C++
false
false
5,019
cpp
#include "joystick_manager_glfw.h" #include <cstring> #include <fstream> #include "window_glfw.h" std::unordered_set<GLFWGameWindow*> GLFWJoystickManager::windows; GLFWGameWindow* GLFWJoystickManager::focusedWindow; std::unordered_map<int, GLFWJoystickManager::JoystickInfo> GLFWJoystickManager::connectedJoysticks; std::unordered_set<int> GLFWJoystickManager::userIds; void GLFWJoystickManager::init() { glfwSetJoystickCallback(_glfwJoystickCallback); loadMappingsFromFile("gamecontrollerdb.txt"); for (int i = GLFW_JOYSTICK_1; i <= GLFW_JOYSTICK_LAST; i++) { if (glfwJoystickPresent(i) && glfwJoystickIsGamepad(i)) _glfwJoystickCallback(i, GLFW_CONNECTED); } } void GLFWJoystickManager::loadMappingsFromFile(std::string const& path) { std::ifstream fs(path); if (!fs) return; std::string line; while (std::getline(fs, line)) { if (!line.empty()) glfwUpdateGamepadMappings(line.c_str()); } } int GLFWJoystickManager::nextUnassignedUserId() { for (int i = 0; ; i++) { if (userIds.count(i) <= 0) return i; } } void GLFWJoystickManager::update(GLFWGameWindow* window) { if (focusedWindow != window) return; for (auto& j : connectedJoysticks) { GLFWgamepadstate state; glfwGetGamepadState(j.first, &state); for (int i = 0; i <= GLFW_GAMEPAD_BUTTON_LAST; i++) { if (state.buttons[i] != j.second.oldButtonStates[i]) { window->onGamepadButton(j.second.userId, mapButtonId(i), state.buttons[i] != 0); } } for (int i = 0; i <= GLFW_GAMEPAD_AXIS_LAST; i++) { window->onGamepadAxis(j.second.userId, mapAxisId(i), state.axes[i]); } memcpy(j.second.oldButtonStates, state.buttons, GLFW_GAMEPAD_BUTTON_LAST + 1); } } void GLFWJoystickManager::update() { update(focusedWindow); } void GLFWJoystickManager::addWindow(GLFWGameWindow* window) { windows.insert(window); for (auto& joystick : connectedJoysticks) window->onGamepadState(joystick.second.userId, true); } void GLFWJoystickManager::removeWindow(GLFWGameWindow* window) { windows.erase(window); } void GLFWJoystickManager::onWindowFocused(GLFWGameWindow* window, bool focused) { if (focused) focusedWindow = window; else if (focusedWindow == window /* && !focused */) focusedWindow = nullptr; } void GLFWJoystickManager::_glfwJoystickCallback(int joystick, int action) { if (!glfwJoystickIsGamepad(joystick)) return; auto js = connectedJoysticks.find(joystick); int userId; if (action == GLFW_CONNECTED) { if (js != connectedJoysticks.end()) return; userId = nextUnassignedUserId(); userIds.insert(userId); connectedJoysticks.insert({joystick, JoystickInfo(userId)}); } else if (action == GLFW_DISCONNECTED) { if (js == connectedJoysticks.end()) return; userId = js->second.userId; userIds.erase(userId); connectedJoysticks.erase(joystick); } for (GLFWGameWindow* window : windows) window->onGamepadState(userId, action == GLFW_CONNECTED); } GamepadButtonId GLFWJoystickManager::mapButtonId(int id) { switch (id) { case GLFW_GAMEPAD_BUTTON_A: return GamepadButtonId::A; case GLFW_GAMEPAD_BUTTON_B: return GamepadButtonId::B; case GLFW_GAMEPAD_BUTTON_X: return GamepadButtonId::X; case GLFW_GAMEPAD_BUTTON_Y: return GamepadButtonId::Y; case GLFW_GAMEPAD_BUTTON_BACK: return GamepadButtonId::BACK; case GLFW_GAMEPAD_BUTTON_START: return GamepadButtonId::START; case GLFW_GAMEPAD_BUTTON_GUIDE: return GamepadButtonId::GUIDE; case GLFW_GAMEPAD_BUTTON_LEFT_BUMPER: return GamepadButtonId::LB; case GLFW_GAMEPAD_BUTTON_RIGHT_BUMPER: return GamepadButtonId::RB; case GLFW_GAMEPAD_BUTTON_LEFT_THUMB: return GamepadButtonId::LEFT_STICK; case GLFW_GAMEPAD_BUTTON_RIGHT_THUMB: return GamepadButtonId::RIGHT_STICK; case GLFW_GAMEPAD_BUTTON_DPAD_UP: return GamepadButtonId::DPAD_UP; case GLFW_GAMEPAD_BUTTON_DPAD_RIGHT: return GamepadButtonId::DPAD_RIGHT; case GLFW_GAMEPAD_BUTTON_DPAD_DOWN: return GamepadButtonId::DPAD_DOWN; case GLFW_GAMEPAD_BUTTON_DPAD_LEFT: return GamepadButtonId::DPAD_LEFT; default: return GamepadButtonId::UNKNOWN; } } GamepadAxisId GLFWJoystickManager::mapAxisId(int id) { switch (id) { case GLFW_GAMEPAD_AXIS_LEFT_X: return GamepadAxisId::LEFT_X; case GLFW_GAMEPAD_AXIS_LEFT_Y: return GamepadAxisId::LEFT_Y; case GLFW_GAMEPAD_AXIS_RIGHT_X: return GamepadAxisId::RIGHT_X; case GLFW_GAMEPAD_AXIS_RIGHT_Y: return GamepadAxisId::RIGHT_Y; case GLFW_GAMEPAD_AXIS_LEFT_TRIGGER: return GamepadAxisId::LEFT_TRIGGER; case GLFW_GAMEPAD_AXIS_RIGHT_TRIGGER: return GamepadAxisId::RIGHT_TRIGGER; default: return GamepadAxisId::UNKNOWN; } }
[ "mcmrarm@gmail.com" ]
mcmrarm@gmail.com
9f0de2186f5c634538a73c7614867f751a3ea1eb
97af5b4565fb1912b9fd556b18ec4f824d5ac014
/GTRACT/Cmdline/gtractResampleDWIInPlace.cxx
7beb9a050a88cc7ac06e86c10b1ddef0cc564823
[]
no_license
xjtugaolei/BRAINSTools
f8ee7a33d039602843463fbca68b01bcc08257ea
934eeb4c0e5853b4f43a3afd71c31995528bd56c
refs/heads/master
2021-01-17T20:58:52.031765
2013-11-09T17:04:13
2013-11-09T17:05:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
17,324
cxx
/*========================================================================= Program: GTRACT (Guided Tensor Restore Anatomical Connectivity Tractography) Module: $RCSfile: $ Language: C++ Date: $Date: 2006/03/29 14:53:40 $ Version: $Revision: 1.9 $ Copyright (c) University of Iowa Department of Radiology. All rights reserved. See GTRACT-Copyright.txt or http://mri.radiology.uiowa.edu/copyright/GTRACT-Copyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include <iostream> #include <fstream> #include <cmath> #include <itkImage.h> #include <itkVectorImage.h> #include <itkImageFileWriter.h> #include <itkImageFileReader.h> #include <itkExceptionObject.h> #include <itkVectorIndexSelectionCastImageFilter.h> #include <itkComposeImageFilter.h> #include <itkImageRegionIterator.h> #include <itkImageRegionConstIterator.h> #include <itkResampleImageFilter.h> #include <itkVectorResampleImageFilter.h> #include <itkTransformFileWriter.h> #include <itkMetaDataDictionary.h> #include <itkMetaDataObject.h> #include "GenericTransformImage.h" #include "BRAINSFitHelper.h" #include "BRAINSThreadControl.h" #include "gtractResampleDWIInPlaceCLP.h" #include "itkImageDuplicator.h" #include "itkNumberToString.h" /** * \author Hans J. Johnson * \brief This templated function will duplicate the input image, change the direction and origin to refelect the physical space * tranform that would be equivalent to calling the resample image filter. * InplaceImage=SetVectorImageRigidTransformInPlace(RigidTransform,InputImage); ResampleImage(InplaceImage,Identity); * should produce the same result as ResampleImage(InputImage,RigidTransform); * \param RigidTransform -- Currently must be a VersorRigid3D * \param InputImage The image to be duplicated and modified to incorporate the rigid transform. * \return an image with the same voxels values as the input, but with differnt physical space representation. */ template <class IOImageType> typename IOImageType::Pointer SetVectorImageRigidTransformInPlace( typename VersorRigid3DTransformType::ConstPointer RigidTransform, const IOImageType *InputImage) { typename VersorRigid3DTransformType::Pointer InvOfRigidTransform = VersorRigid3DTransformType::New(); const typename IOImageType::PointType centerPoint = RigidTransform->GetCenter(); InvOfRigidTransform->SetCenter( centerPoint ); InvOfRigidTransform->SetIdentity(); RigidTransform->GetInverse(InvOfRigidTransform); /** Wei: The output image will have exact the same index contents but with modified image info so that the index-to-physical mapping makes the image in the physical space AC-PC aligned */ typedef itk::ImageDuplicator<IOImageType> DuplicatorType; typename DuplicatorType::Pointer duplicator = DuplicatorType::New(); duplicator->SetInputImage(InputImage); duplicator->Update(); typename IOImageType::Pointer OutputAlignedImage = duplicator->GetModifiableOutput(); // Now change the Origin and Direction to make data aligned. OutputAlignedImage->SetOrigin( InvOfRigidTransform->GetMatrix() * InputImage->GetOrigin() + InvOfRigidTransform->GetTranslation() ); OutputAlignedImage->SetDirection( InvOfRigidTransform->GetMatrix() * InputImage->GetDirection() ); OutputAlignedImage->SetMetaDataDictionary(InputImage->GetMetaDataDictionary() ); return OutputAlignedImage; } int main(int argc, char *argv[]) { PARSE_ARGS; BRAINSRegisterAlternateIO(); const BRAINSUtils::StackPushITKDefaultNumberOfThreads TempDefaultNumberOfThreadsHolder(numberOfThreads); itk::NumberToString<double> doubleConvert; bool debug = true; if( debug ) { std::cout << "=====================================================" << std::endl; std::cout << "DWI Image: " << inputVolume << std::endl; std::cout << "Input Transform: " << inputTransform << std::endl; std::cout << "Output Image: " << outputVolume << std::endl; std::cout << "Debug Level: " << debugLevel << std::endl; std::cout << "Image Output Size: " << imageOutputSize[0] << "," << imageOutputSize[1] << "," << imageOutputSize[2] << std::endl; std::cout << "=====================================================" << std::endl; } bool violated = false; if( inputVolume.size() == 0 ) { violated = true; std::cout << " --inputVolume Required! " << std::endl; } if( inputTransform.size() == 0 ) { violated = true; std::cout << " --inputTransform Required! " << std::endl; } if( outputVolume.size() == 0 ) { violated = true; std::cout << " --outputVolume Required! " << std::endl; } if( violated ) { return EXIT_FAILURE; } typedef signed short PixelType; typedef itk::VectorImage<PixelType, 3> NrrdImageType; typedef itk::VersorRigid3DTransform<double> RigidTransformType; typedef itk::Image<PixelType, 3> SingleComponentImageType; typedef itk::ImageFileReader<NrrdImageType, itk::DefaultConvertPixelTraits<PixelType> > FileReaderType; FileReaderType::Pointer imageReader = FileReaderType::New(); imageReader->SetFileName( inputVolume ); try { imageReader->Update(); } catch( itk::ExceptionObject & ex ) { std::cout << ex << std::endl; throw; } std::cout << "Read Image" << std::endl; NrrdImageType::Pointer resampleImage = imageReader->GetOutput(); NrrdImageType::DirectionType myDirection = resampleImage->GetDirection(); itk::MetaDataDictionary inputMetaDataDictionary = resampleImage->GetMetaDataDictionary(); GenericTransformType::Pointer baseTransform = NULL; if( inputTransform == "ID" ) { RigidTransformType::Pointer LocalRigidTransform = RigidTransformType::New(); LocalRigidTransform->SetIdentity(); baseTransform = LocalRigidTransform; } else { baseTransform = itk::ReadTransformFromDisk(inputTransform); } RigidTransformType::Pointer rigidTransform = dynamic_cast<RigidTransformType *>( baseTransform.GetPointer() ); if( rigidTransform.IsNull() ) { std::cerr << "Transform " << inputTransform << " wasn't of the expected type itk::VersorRigid3DTransform<double" << std::endl; return EXIT_FAILURE; } // Get measurement frame and its inverse from DWI scan std::vector<std::vector<double> > msrFrame; itk::ExposeMetaData<std::vector<std::vector<double> > >( inputMetaDataDictionary, "NRRD_measurement frame", msrFrame ); vnl_matrix_fixed<double, 3, 3> DWIMeasurementFrame; if( msrFrame.size() != 0 ) { for( unsigned int i = 0; i < 3; i++ ) { for( unsigned int j = 0; j < 3; j++ ) { DWIMeasurementFrame[i][j] = msrFrame[i][j]; } } } else { std::cout << "File does not have NRRD measurement frame metadata!" << std::endl << "If this is not a DWI NRRD file (e.g. fMRI NIFTI, etc.), you can safely ignore this" << std::endl; DWIMeasurementFrame.set_identity(); } vnl_matrix_fixed<double, 3, 3> DWIInverseMeasurementFrame = vnl_inverse( DWIMeasurementFrame ); // Resample DWI in place resampleImage = SetVectorImageRigidTransformInPlace<NrrdImageType>(rigidTransform.GetPointer(), resampleImage); std::cout << "Rigid transform matrix: " << rigidTransform->GetMatrix().GetVnlMatrix() << std::endl; // Rotate gradient vectors by rigid transform and inverse measurement frame for( unsigned int i = 0; i < resampleImage->GetVectorLength(); i++ ) { // Get Current Gradient Direction vnl_vector<double> curGradientDirection(3); char tmpStr[64]; sprintf(tmpStr, "DWMRI_gradient_%04u", i); std::string KeyString(tmpStr); std::string NrrdValue; itk::ExposeMetaData<std::string>(inputMetaDataDictionary, KeyString, NrrdValue); sscanf( NrrdValue.c_str(), " %lf %lf %lf", &curGradientDirection[0], &curGradientDirection[1], &curGradientDirection[2]); // Rotate the diffusion gradient with rigid transform and inverse measurement frame RigidTransformType::Pointer inverseRigidTransform = RigidTransformType::New(); curGradientDirection = inverseRigidTransform->GetMatrix().GetVnlMatrix() * DWIInverseMeasurementFrame * curGradientDirection; // Updated the Image MetaData Dictionary with Updated Gradient Information // sprintf(tmpStr, " %18.15lf %18.15lf %18.15lf", curGradientDirection[0], curGradientDirection[1], // curGradientDirection[2]); // NrrdValue = tmpStr; NrrdValue = " "; for( unsigned dir = 0; dir < 3; ++dir ) { if( dir > 0 ) { NrrdValue += " "; } NrrdValue += doubleConvert(curGradientDirection[dir]); } itk::EncapsulateMetaData<std::string>(resampleImage->GetMetaDataDictionary(), KeyString, NrrdValue); } // Set DWI measurement frame to identity by multiplying by its inverse // Update Image MetaData Dictionary with new measurement frame vnl_matrix_fixed<double, 3, 3> newMeasurementFrame = DWIInverseMeasurementFrame * DWIMeasurementFrame; std::vector<std::vector<double> > newMf(3); for( unsigned int i = 0; i < 3; i++ ) { newMf[i].resize(3); for( unsigned int j = 0; j < 3; j++ ) { newMf[i][j] = newMeasurementFrame[i][j]; } } itk::EncapsulateMetaData<std::vector<std::vector<double> > >( resampleImage->GetMetaDataDictionary(), "NRRD_measurement frame", newMf ); // Pad image const NrrdImageType::RegionType inputRegion = resampleImage->GetLargestPossibleRegion(); const NrrdImageType::SizeType inputSize = inputRegion.GetSize(); const NrrdImageType::PointType inputOrigin = resampleImage->GetOrigin(); const NrrdImageType::DirectionType inputDirection = resampleImage->GetDirection(); const NrrdImageType::SpacingType inputSpacing = resampleImage->GetSpacing(); NrrdImageType::SizeType newSize; std::vector<size_t> imagePadding(6, 0); for( int qq = 0; qq < 3; ++qq ) { if( ( imageOutputSize[qq] > 0 ) && ( static_cast<itk::SizeValueType>( imageOutputSize[qq] ) > inputSize[qq] ) ) { const size_t sizeDiff = imageOutputSize[qq] - inputSize[qq]; const size_t halfPadding = sizeDiff / 2; const size_t isOddDiff = sizeDiff % 2; imagePadding[qq] = halfPadding + isOddDiff; imagePadding[qq + 3] = halfPadding; } newSize[qq] = inputSize[qq] + imagePadding[qq] + imagePadding[qq + 3]; } vnl_matrix_fixed<double, 3, 3> inputDirectionMatrix; vnl_matrix_fixed<double, 3, 3> inputSpacingMatrix; for( unsigned int i = 0; i < 3; i++ ) { for( unsigned int j = 0; j < 3; j++ ) { inputDirectionMatrix[i][j] = inputDirection[i][j]; if( i == j ) { inputSpacingMatrix[i][j] = inputSpacing[i]; } else { inputSpacingMatrix[i][j] = 0.0; } } } vnl_matrix_fixed<double, 3, 3> spaceDirections = inputDirectionMatrix * inputSpacingMatrix; vnl_matrix_fixed<double, 3, 4> newMatrix; for( unsigned int i = 0; i < 3; i++ ) { for( unsigned int j = 0; j < 4; j++ ) { if( j == 3 ) { newMatrix[i][j] = inputOrigin[i]; } else { newMatrix[i][j] = spaceDirections[i][j]; } } } vnl_matrix_fixed<double, 4, 1> voxelShift; voxelShift[0][0] = -1.0 * ( double )( imagePadding[0] ); voxelShift[1][0] = -1.0 * ( double )( imagePadding[1] ); voxelShift[2][0] = -1.0 * ( double )( imagePadding[2] ); voxelShift[3][0] = 1.0; vnl_matrix_fixed<double, 3, 1> newOriginMatrix = newMatrix * voxelShift; NrrdImageType::PointType newOrigin; for( unsigned int i = 0; i < 3; i++ ) { newOrigin[i] = newOriginMatrix[i][0]; } std::cout << "Input DWI Image Origin: ( " << inputOrigin[0] << ", " << inputOrigin[1] << ", " << inputOrigin[2] << " )" << std::endl; std::cout << "Input DWI Image Size: " << inputSize[0] << " " << inputSize[1] << " " << inputSize[2] << std::endl; std::cout << " " << std::endl; std::cout << "Output DWI Image Origin: ( " << newOrigin[0] << ", " << newOrigin[1] << ", " << newOrigin[2] << " )" << std::endl; std::cout << "Output DWI Image Size: " << newSize[0] << " " << newSize[1] << " " << newSize[2] << std::endl; NrrdImageType::Pointer paddedImage = NrrdImageType::New(); paddedImage->CopyInformation(resampleImage); paddedImage->SetVectorLength( resampleImage->GetVectorLength() ); paddedImage->SetMetaDataDictionary( resampleImage->GetMetaDataDictionary() ); paddedImage->SetRegions( newSize ); paddedImage->SetOrigin( newOrigin ); paddedImage->Allocate(); NrrdImageType::Pointer finalImage; typedef itk::ImageRegionIterator<NrrdImageType> IteratorType; IteratorType InIt( resampleImage, resampleImage->GetRequestedRegion() ); for( InIt.GoToBegin(); !InIt.IsAtEnd(); ++InIt ) { NrrdImageType::IndexType InIndex = InIt.GetIndex(); NrrdImageType::IndexType OutIndex; OutIndex[0] = InIndex[0] + imagePadding[0]; OutIndex[1] = InIndex[1] + imagePadding[1]; OutIndex[2] = InIndex[2] + imagePadding[2]; NrrdImageType::PixelType InImagePixel = resampleImage->GetPixel( InIndex ); paddedImage->SetPixel( OutIndex, InImagePixel ); } paddedImage->Update(); if(referenceVolume != "") { //For each component, extract, resample to list, and finally compose back into a vector image. typedef itk::ImageFileReader<SingleComponentImageType> ReferenceFileReaderType; ReferenceFileReaderType::Pointer referenceImageReader = ReferenceFileReaderType::New(); referenceImageReader->SetFileName(referenceVolume); referenceImageReader->Update(); const size_t lengthOfPixelVector = paddedImage->GetVectorLength(); typedef itk::ComposeImageFilter<SingleComponentImageType, NrrdImageType> ComposeCovariantVectorImageFilterType; ComposeCovariantVectorImageFilterType::Pointer composer= ComposeCovariantVectorImageFilterType::New(); typedef itk::VectorIndexSelectionCastImageFilter< NrrdImageType, SingleComponentImageType > VectorIndexSelectionCastImageFilterType; VectorIndexSelectionCastImageFilterType::Pointer vectorImageToImageSelector = VectorIndexSelectionCastImageFilterType::New(); vectorImageToImageSelector->SetInput(paddedImage); for(size_t componentToExtract = 0 ; componentToExtract < lengthOfPixelVector; ++componentToExtract ) { vectorImageToImageSelector->SetIndex( componentToExtract ); vectorImageToImageSelector->Update(); // Resample to a new space with basic linear/identity transform. typedef itk::ResampleImageFilter<SingleComponentImageType,SingleComponentImageType> ComponentResamplerType; ComponentResamplerType::Pointer componentResampler = ComponentResamplerType::New(); componentResampler->SetOutputParametersFromImage(referenceImageReader->GetOutput()); componentResampler->SetInput(vectorImageToImageSelector->GetOutput()); //default to linear //default to IdentityTransform //default background value of 0. componentResampler->Update(); //Add to list for Compose composer->SetInput(componentToExtract,componentResampler->GetOutput()); } composer->Update(); finalImage = composer->GetOutput(); finalImage->SetMetaDataDictionary(paddedImage->GetMetaDataDictionary() ); } else { finalImage=paddedImage; } // Write out resampled in place DWI typedef itk::ImageFileWriter<NrrdImageType> WriterType; WriterType::Pointer nrrdWriter = WriterType::New(); nrrdWriter->UseCompressionOn(); nrrdWriter->UseInputMetaDataDictionaryOn(); nrrdWriter->SetInput( finalImage ); nrrdWriter->SetFileName( outputVolume ); try { nrrdWriter->Update(); } catch( itk::ExceptionObject & e ) { std::cout << e << std::endl; } if(!outputResampledB0.empty()) { const size_t B0Index=0; typedef itk::VectorIndexSelectionCastImageFilter< NrrdImageType, SingleComponentImageType > VectorIndexSelectionCastImageFilterType; VectorIndexSelectionCastImageFilterType::Pointer vectorImageToImageSelector = VectorIndexSelectionCastImageFilterType::New(); vectorImageToImageSelector->SetInput(finalImage); vectorImageToImageSelector->SetIndex( B0Index ); vectorImageToImageSelector->Update(); // Write out resampled in place DWI typedef itk::ImageFileWriter<SingleComponentImageType> B0WriterType; B0WriterType::Pointer B0Writer = B0WriterType::New(); B0Writer->UseCompressionOn(); B0Writer->SetInput( vectorImageToImageSelector->GetOutput() ); B0Writer->SetFileName( outputResampledB0 ); try { B0Writer->Update(); } catch( itk::ExceptionObject & e ) { std::cout << e << std::endl; } } return EXIT_SUCCESS; }
[ "hans-johnson@uiowa.edu" ]
hans-johnson@uiowa.edu
768ebf312788af169b348a1573ea162c8cda66c5
e91fe439081e35094ccc68eb5f40bcb5854b4ab9
/MazeSolver/maze.h
8a5bc6088cdb70bc50717adcd1555473390fdd08
[]
no_license
joshfermin/DataStructures
afa12372ec443e21be89516eb00142a530c397d3
23067a78359d8171d89715607ad82c47368227ef
refs/heads/master
2021-01-10T20:35:52.954722
2014-05-13T05:22:23
2014-05-13T05:22:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
529
h
#ifndef MAZE_H_ #define MAZE_H_ #include <iostream> ;class maze { public: maze(); // opens maze.txt void init(); // finds starting position, and calls solve bool solve(int index); friend std::ostream& operator << (std::ostream& outs, const maze& source); // overload ostream operator and print out maze // double loop? private: char* mazeArray; // representing maze in 1D int startingIndex; // an int that represents starting pt int xDim; // x dimension of maze int yDim; // y dimension of maze }; #endif
[ "joshfermin@gmail.com" ]
joshfermin@gmail.com
ae8441dfe132a9ac38f2343a5a16dd312f996301
8f8efcf2500b9b5d68c32961a6b1c4218b7e243c
/fleur_core/include/ProcessingException.h
b4d6f8d4f5e6e1ef6ab6348e20bd45dee605fae4
[]
no_license
egeorgel/Fleur
71b9ca33161a0c0aacaeee23605ddc34b97cc0b9
7e16a5f6471a62fa3cf4ff49008e539f13271d1c
refs/heads/master
2020-06-11T06:22:11.172487
2017-09-27T13:07:13
2017-09-27T13:07:13
75,747,845
5
0
null
null
null
null
UTF-8
C++
false
false
613
h
// // Created by Edgar on 02/01/2017. // #ifndef FLEUR_PROCESSINGEXCEPTION_H #define FLEUR_PROCESSINGEXCEPTION_H #include <exception> #include <string> namespace fleur { class ProcessingException : public std::exception { public: ProcessingException(std::string const& message="") throw() : _message(message) {} virtual const char* what() const throw() { return _message.c_str(); } virtual ~ProcessingException() throw() {} private: std::string _message; }; } #endif //FLEUR_PROCESSINGEXCEPTION_H
[ "edgar.georgel@gmail.com" ]
edgar.georgel@gmail.com
0eebce935198acbf92b9aad8fda9ed4f37e36431
3f24a6811b01df8ec359de33957b00a696a915d4
/input_grammar/GrammaticSchemeListener.h
2f9d27faf30a37fe361ccddabacab33fdbe09eb2
[]
no_license
evgeniyfeder/parser_generator
fd741b54321b882b44fb585d22ea08c085909eb8
2aa6d0e673c0808cae62c2fe236c6ff3138a48f6
refs/heads/master
2020-04-19T18:08:56.348685
2019-07-13T18:54:05
2019-07-13T18:54:05
168,354,901
0
0
null
null
null
null
UTF-8
C++
false
false
1,345
h
#include <string> #include "../parser_generator/grammatic.h" // Generated from /home/efeder/work/itmo/mt/lab4/input_grammar/GrammaticScheme.g4 by ANTLR 4.7.2 #pragma once #include "antlr4-runtime.h" #include "GrammaticSchemeParser.h" /** * This interface defines an abstract listener for a parse tree produced by GrammaticSchemeParser. */ class GrammaticSchemeListener : public antlr4::tree::ParseTreeListener { public: virtual void enterGrammatic(GrammaticSchemeParser::GrammaticContext *ctx) = 0; virtual void exitGrammatic(GrammaticSchemeParser::GrammaticContext *ctx) = 0; virtual void enterStart(GrammaticSchemeParser::StartContext *ctx) = 0; virtual void exitStart(GrammaticSchemeParser::StartContext *ctx) = 0; virtual void enterHeader(GrammaticSchemeParser::HeaderContext *ctx) = 0; virtual void exitHeader(GrammaticSchemeParser::HeaderContext *ctx) = 0; virtual void enterLexem(GrammaticSchemeParser::LexemContext *ctx) = 0; virtual void exitLexem(GrammaticSchemeParser::LexemContext *ctx) = 0; virtual void enterRules(GrammaticSchemeParser::RulesContext *ctx) = 0; virtual void exitRules(GrammaticSchemeParser::RulesContext *ctx) = 0; virtual void enterOne_rule(GrammaticSchemeParser::One_ruleContext *ctx) = 0; virtual void exitOne_rule(GrammaticSchemeParser::One_ruleContext *ctx) = 0; };
[ "evgeniyfeder@github.com" ]
evgeniyfeder@github.com
48b32ef39f8ede0c225165dbdbe3b204122c72ea
4e79be93132ed09fc0d0dafd0e7bc97c14c38744
/core/ray.h
efd1c96ab7db9ea6fbabc4dadb4dc4e6e2b4e15d
[]
no_license
sike2017/rdx
b7d483213e6bb08816741e92c7215bca1ac55018
09ba67508be1b04d670e3099f30e76e9ff47d737
refs/heads/master
2023-05-04T05:54:54.502464
2021-05-19T10:34:10
2021-05-19T10:34:10
326,327,284
1
0
null
null
null
null
UTF-8
C++
false
false
414
h
#pragma once #include "math/monolith_math.h" class Ray { public: __host__ __device__ Ray() {} __host__ __device__ Ray(const Vector3f& a, const Vector3f& b) { A = a; B = b; } __host__ __device__ Vector3f origin() const { return A; } __host__ __device__ Vector3f direction() const { return B; } __host__ __device__ Vector3f point_at_parameter(float t) const { return A + t * B; } Vector3f A; Vector3f B; };
[ "sikegrbd@outlook.com" ]
sikegrbd@outlook.com
980067e5d614d5d425d0c7a5b8a8a979c9279f89
24c4e3a4d988f78634c124359968daabf70b7804
/Display_characters_of_a_string_one__on_a_7_segment_display.ino
791797d9c214a8343e15f1d13527f76745ba4e00
[]
no_license
joyantabd/Display_characters_of_a_string_one__on_a_7_segment_display
39d377ed1deb2f775418957c369f8614c982d77b
cbe3197654cc10ee145d32c8b87ffed99d67a612
refs/heads/master
2020-06-26T01:46:56.937194
2019-07-29T16:17:56
2019-07-29T16:17:56
199,487,563
0
0
null
null
null
null
UTF-8
C++
false
false
985
ino
/*This is the code to show the alphabetical characters on a 7 segment LED display*/ //bits representing the alphabetical characters const byte alphabet[16]= { B11101110, //A B00111110, //b B10011100, //C B00011010, //c B01111010, //d B10011110, //E B10001110, //F B01101110, //H B00101110, //h B00011100, //L B01100000, //l B11111100, //O B00111010, //o B11001110, //P B10110110, //S B00000000, //shows nothing }; //pins for each segment (a-g) on the 7 segment LED display with the corresponding arduino connection const int segmentPins[8]= { 5,8,9,7,6,4,3,2 }; void setup() { for (int i=0; i < 8; i++) { pinMode(segmentPins[i], OUTPUT); } } void loop() { for (int i=0; i <=15; i++) { showDigit(i); delay(1000); } delay(2000); //after LED segment shuts off, there is a 2-second delay } void showDigit (int number) { boolean isBitSet; for (int segment=0; segment < 15; segment++) { isBitSet= bitRead(alphabet[number], segment); digitalWrite(segmentPins[segment], isBitSet); } }
[ "you@example.com" ]
you@example.com
9c5003ce815d693c21b5099e5f69c24c14b78993
3a0b544370e8b8e8c52f7b5dd97cec5e18ca3ea0
/src/Rpc/CoreRpcServerCommandsDefinitions.h
422bed1727270a5aa158ce2b6733602954996871
[]
no_license
cryptonoteclub/adon-core
278a3c1126aad27d514ac6f7678e844c99f04a92
5105fc79a4467880e315f0eef727bf4ce6243b9b
refs/heads/master
2020-07-14T04:10:06.216628
2019-08-26T08:56:10
2019-08-26T08:56:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
29,452
h
// Copyright (c) 2018-2019 Adon Network developers // Copyright (c) 2011-2016 The Cryptonote developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #pragma once #include "BlockchainExplorerData.h" #include "BlockchainExplorerDataEx.h" #include "CryptoNoteProtocol/CryptoNoteProtocolDefinitions.h" #include "CryptoNoteCore/CryptoNoteBasic.h" #include "CryptoNoteCore/Difficulty.h" #include "crypto/hash.h" #include "Serialization/SerializationOverloads.h" #include "Serialization/BlockchainExplorerDataSerialization.h" namespace CryptoNote { //----------------------------------------------- #define CORE_RPC_STATUS_OK "OK" #define CORE_RPC_STATUS_BUSY "BUSY" struct EMPTY_STRUCT { void serialize(ISerializer &s) {} }; struct STATUS_STRUCT { std::string status; void serialize(ISerializer &s) { KV_MEMBER(status) } }; struct COMMAND_RPC_GET_HEIGHT { typedef EMPTY_STRUCT request; struct response { uint64_t height; std::string status; void serialize(ISerializer &s) { KV_MEMBER(height) KV_MEMBER(status) } }; }; struct COMMAND_RPC_GET_BLOCKS_FAST { struct request { std::vector<Crypto::Hash> block_ids; //*first 10 blocks id goes sequential, next goes in pow(2,n) offset, like 2, 4, 8, 16, 32, 64 and so on, and the last one is always genesis block */ void serialize(ISerializer &s) { serializeAsBinary(block_ids, "block_ids", s); } }; struct response { std::vector<block_complete_entry> blocks; uint64_t start_height; uint64_t current_height; std::string status; void serialize(ISerializer &s) { KV_MEMBER(blocks) KV_MEMBER(start_height) KV_MEMBER(current_height) KV_MEMBER(status) } }; }; //----------------------------------------------- struct COMMAND_RPC_GET_TRANSACTIONS { struct request { std::vector<std::string> txs_hashes; void serialize(ISerializer &s) { KV_MEMBER(txs_hashes) } }; struct response { std::vector<std::string> txs_as_hex; //transactions blobs as hex std::vector<std::string> missed_tx; //not found transactions std::string status; void serialize(ISerializer &s) { KV_MEMBER(txs_as_hex) KV_MEMBER(missed_tx) KV_MEMBER(status) } }; }; //----------------------------------------------- struct COMMAND_RPC_GET_POOL_CHANGES { struct request { Crypto::Hash tailBlockId; std::vector<Crypto::Hash> knownTxsIds; void serialize(ISerializer &s) { KV_MEMBER(tailBlockId) serializeAsBinary(knownTxsIds, "knownTxsIds", s); } }; struct response { bool isTailBlockActual; std::vector<BinaryArray> addedTxs; // Added transactions blobs std::vector<Crypto::Hash> deletedTxsIds; // IDs of not found transactions std::string status; void serialize(ISerializer &s) { KV_MEMBER(isTailBlockActual) KV_MEMBER(addedTxs) serializeAsBinary(deletedTxsIds, "deletedTxsIds", s); KV_MEMBER(status) } }; }; struct COMMAND_RPC_GET_POOL_CHANGES_LITE { struct request { Crypto::Hash tailBlockId; std::vector<Crypto::Hash> knownTxsIds; void serialize(ISerializer &s) { KV_MEMBER(tailBlockId) serializeAsBinary(knownTxsIds, "knownTxsIds", s); } }; struct response { bool isTailBlockActual; std::vector<TransactionPrefixInfo> addedTxs; // Added transactions blobs std::vector<Crypto::Hash> deletedTxsIds; // IDs of not found transactions std::string status; void serialize(ISerializer &s) { KV_MEMBER(isTailBlockActual) KV_MEMBER(addedTxs) serializeAsBinary(deletedTxsIds, "deletedTxsIds", s); KV_MEMBER(status) } }; }; //----------------------------------------------- struct COMMAND_RPC_GET_TX_GLOBAL_OUTPUTS_INDEXES { struct request { Crypto::Hash txid; void serialize(ISerializer &s) { KV_MEMBER(txid) } }; struct response { std::vector<uint64_t> o_indexes; std::string status; void serialize(ISerializer &s) { KV_MEMBER(o_indexes) KV_MEMBER(status) } }; }; //----------------------------------------------- struct COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS_request { std::vector<uint64_t> amounts; uint64_t outs_count; void serialize(ISerializer &s) { KV_MEMBER(amounts) KV_MEMBER(outs_count) } }; #pragma pack(push, 1) struct COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS_out_entry { uint64_t global_amount_index; Crypto::PublicKey out_key; }; #pragma pack(pop) struct COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS_outs_for_amount { uint64_t amount; std::vector<COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS_out_entry> outs; void serialize(ISerializer &s) { KV_MEMBER(amount) serializeAsBinary(outs, "outs", s); } }; struct COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS_response { std::vector<COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS_outs_for_amount> outs; std::string status; void serialize(ISerializer &s) { KV_MEMBER(outs); KV_MEMBER(status) } }; struct COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS { typedef COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS_request request; typedef COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS_response response; typedef COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS_out_entry out_entry; typedef COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS_outs_for_amount outs_for_amount; }; //----------------------------------------------- struct COMMAND_RPC_SEND_RAW_TX { struct request { std::string tx_as_hex; request() {} explicit request(const Transaction &); void serialize(ISerializer &s) { KV_MEMBER(tx_as_hex) } }; struct response { std::string status; void serialize(ISerializer &s) { KV_MEMBER(status) } }; }; //----------------------------------------------- struct COMMAND_RPC_START_MINING { struct request { std::string miner_address; uint64_t threads_count; void serialize(ISerializer &s) { KV_MEMBER(miner_address) KV_MEMBER(threads_count) } }; struct response { std::string status; void serialize(ISerializer &s) { KV_MEMBER(status) } }; }; //----------------------------------------------- struct COMMAND_RPC_GET_INFO { typedef EMPTY_STRUCT request; struct response { std::string status; uint64_t height; uint64_t difficulty; uint64_t min_tx_fee; std::string readable_tx_fee; uint64_t tx_count; uint64_t tx_pool_size; uint64_t alt_blocks_count; uint64_t outgoing_connections_count; uint64_t incoming_connections_count; uint64_t rpc_connections_count; uint64_t white_peerlist_size; uint64_t grey_peerlist_size; uint32_t last_known_block_index; std::string top_block_hash; uint64_t start_time; std::string contact; std::string fee_address; std::string version; uint8_t block_major_version; uint64_t already_generated_coins; uint8_t block_minor_version; uint64_t last_block_reward; uint64_t last_block_timestamp; uint64_t last_block_difficulty; uint64_t full_deposit_amount; uint64_t full_deposit_interest; void serialize(ISerializer &s) { KV_MEMBER(status) KV_MEMBER(version) KV_MEMBER(height) KV_MEMBER(difficulty) KV_MEMBER(min_tx_fee) KV_MEMBER(readable_tx_fee) KV_MEMBER(tx_count) KV_MEMBER(tx_pool_size) KV_MEMBER(alt_blocks_count) KV_MEMBER(outgoing_connections_count) KV_MEMBER(incoming_connections_count) KV_MEMBER(rpc_connections_count) KV_MEMBER(white_peerlist_size) KV_MEMBER(grey_peerlist_size) KV_MEMBER(last_known_block_index) KV_MEMBER(top_block_hash) KV_MEMBER(start_time) KV_MEMBER(block_major_version) KV_MEMBER(already_generated_coins) KV_MEMBER(full_deposit_amount) KV_MEMBER(full_deposit_interest) KV_MEMBER(block_minor_version) KV_MEMBER(last_block_reward) KV_MEMBER(last_block_timestamp) KV_MEMBER(last_block_difficulty) KV_MEMBER(fee_address) KV_MEMBER(contact) } }; }; //----------------------------------------------- struct COMMAND_RPC_STOP_MINING { typedef EMPTY_STRUCT request; typedef STATUS_STRUCT response; }; //----------------------------------------------- struct COMMAND_RPC_STOP_DAEMON { typedef EMPTY_STRUCT request; typedef STATUS_STRUCT response; }; //----------------------------------------------- struct COMMAND_RPC_GET_FEE_ADDRESS { typedef EMPTY_STRUCT request; struct response { std::string fee_address; void serialize(ISerializer &s) { KV_MEMBER(fee_address) } }; }; //----------------------------------------------- struct COMMAND_RPC_GET_PEER_LIST { typedef EMPTY_STRUCT request; struct response { std::vector<std::string> peers; std::string status; void serialize(ISerializer &s) { KV_MEMBER(peers) KV_MEMBER(status) } }; }; // struct COMMAND_RPC_GETBLOCKCOUNT { typedef std::vector<std::string> request; struct response { uint64_t count; std::string status; void serialize(ISerializer &s) { KV_MEMBER(count) KV_MEMBER(status) } }; }; struct COMMAND_RPC_GETBLOCKHASH { typedef std::vector<uint64_t> request; typedef std::string response; }; struct COMMAND_RPC_GETBLOCKTEMPLATE { struct request { uint64_t reserve_size; //max 255 bytes std::string wallet_address; void serialize(ISerializer &s) { KV_MEMBER(reserve_size) KV_MEMBER(wallet_address) } }; struct response { uint64_t difficulty; uint32_t height; uint64_t reserved_offset; std::string blocktemplate_blob; std::string status; void serialize(ISerializer &s) { KV_MEMBER(difficulty) KV_MEMBER(height) KV_MEMBER(reserved_offset) KV_MEMBER(blocktemplate_blob) KV_MEMBER(status) } }; }; struct COMMAND_RPC_GET_CURRENCY_ID { typedef EMPTY_STRUCT request; struct response { std::string currency_id_blob; void serialize(ISerializer &s) { KV_MEMBER(currency_id_blob) } }; }; struct COMMAND_RPC_SUBMITBLOCK { typedef std::vector<std::string> request; typedef STATUS_STRUCT response; }; struct block_header_response { uint8_t major_version; uint8_t minor_version; uint64_t timestamp; std::string prev_hash; uint32_t nonce; bool orphan_status; uint64_t height; uint64_t depth; std::string hash; difficulty_type difficulty; uint64_t reward; void serialize(ISerializer &s) { KV_MEMBER(major_version) KV_MEMBER(minor_version) KV_MEMBER(timestamp) KV_MEMBER(prev_hash) KV_MEMBER(nonce) KV_MEMBER(orphan_status) KV_MEMBER(height) KV_MEMBER(depth) KV_MEMBER(hash) KV_MEMBER(difficulty) KV_MEMBER(reward) } }; struct BLOCK_HEADER_RESPONSE { std::string status; block_header_response block_header; void serialize(ISerializer &s) { KV_MEMBER(block_header) KV_MEMBER(status) } }; struct COMMAND_RPC_GET_LAST_BLOCK_HEADER { typedef EMPTY_STRUCT request; typedef BLOCK_HEADER_RESPONSE response; }; struct COMMAND_RPC_GET_BLOCK_HEADER_BY_HASH { struct request { std::string hash; void serialize(ISerializer &s) { KV_MEMBER(hash) } }; typedef BLOCK_HEADER_RESPONSE response; }; struct COMMAND_RPC_GET_BLOCK_HEADER_BY_HEIGHT { struct request { uint64_t height; void serialize(ISerializer &s) { KV_MEMBER(height) } }; typedef BLOCK_HEADER_RESPONSE response; }; struct COMMAND_RPC_QUERY_BLOCKS { struct request { std::vector<Crypto::Hash> block_ids; //*first 10 blocks id goes sequential, next goes in pow(2,n) offset, like 2, 4, 8, 16, 32, 64 and so on, and the last one is always genesis block */ uint64_t timestamp; void serialize(ISerializer &s) { serializeAsBinary(block_ids, "block_ids", s); KV_MEMBER(timestamp) } }; struct response { std::string status; uint64_t start_height; uint64_t current_height; uint64_t full_offset; std::vector<BlockFullInfo> items; void serialize(ISerializer &s) { KV_MEMBER(status) KV_MEMBER(start_height) KV_MEMBER(current_height) KV_MEMBER(full_offset) KV_MEMBER(items) } }; }; struct COMMAND_RPC_QUERY_BLOCKS_LITE { struct request { std::vector<Crypto::Hash> blockIds; uint64_t timestamp; void serialize(ISerializer &s) { serializeAsBinary(blockIds, "block_ids", s); KV_MEMBER(timestamp) } }; struct response { std::string status; uint64_t startHeight; uint64_t currentHeight; uint64_t fullOffset; std::vector<BlockShortInfo> items; void serialize(ISerializer &s) { KV_MEMBER(status) KV_MEMBER(startHeight) KV_MEMBER(currentHeight) KV_MEMBER(fullOffset) KV_MEMBER(items) } }; }; struct f_transaction_short_response { std::string hash; uint64_t fee; uint64_t amount_out; uint64_t size; void serialize(ISerializer &s) { KV_MEMBER(hash) KV_MEMBER(fee) KV_MEMBER(amount_out) KV_MEMBER(size) } }; struct f_transaction_details_response { std::string hash; size_t size; std::string paymentId; uint64_t mixin; uint64_t fee; uint64_t amount_out; uint32_t confirmations = 0; void serialize(ISerializer &s) { KV_MEMBER(hash) KV_MEMBER(size) KV_MEMBER(paymentId) KV_MEMBER(mixin) KV_MEMBER(fee) KV_MEMBER(amount_out) KV_MEMBER(confirmations) } }; struct f_mempool_transaction_response { std::string hash; uint64_t fee; uint64_t amount_out; uint64_t size; uint64_t receiveTime; bool keptByBlock; uint32_t max_used_block_height; std::string max_used_block_id; uint32_t last_failed_height; std::string last_failed_id; void serialize(ISerializer &s) { KV_MEMBER(hash) KV_MEMBER(fee) KV_MEMBER(amount_out) KV_MEMBER(size) KV_MEMBER(receiveTime) KV_MEMBER(keptByBlock) KV_MEMBER(max_used_block_height) KV_MEMBER(max_used_block_id) KV_MEMBER(last_failed_height) KV_MEMBER(last_failed_id) } }; struct f_block_short_response { uint64_t timestamp; uint32_t height; std::string hash; uint64_t tx_count; uint64_t cumul_size; difficulty_type difficulty; uint64_t min_tx_fee; void serialize(ISerializer &s) { KV_MEMBER(timestamp) KV_MEMBER(height) KV_MEMBER(hash) KV_MEMBER(cumul_size) KV_MEMBER(tx_count) KV_MEMBER(difficulty) KV_MEMBER(min_tx_fee) } }; struct f_block_details_response { uint8_t major_version; uint8_t minor_version; uint64_t timestamp; std::string prev_hash; uint32_t nonce; bool orphan_status; uint64_t height; uint64_t depth; std::string hash; difficulty_type difficulty; uint64_t reward; uint64_t blockSize; size_t sizeMedian; uint64_t effectiveSizeMedian; uint64_t transactionsCumulativeSize; std::string alreadyGeneratedCoins; uint64_t alreadyGeneratedTransactions; uint64_t full_deposit_amount; uint64_t full_deposit_interest; uint64_t baseReward; double penalty; uint64_t totalFeeAmount; std::vector<f_transaction_short_response> transactions; void serialize(ISerializer &s) { KV_MEMBER(major_version) KV_MEMBER(minor_version) KV_MEMBER(timestamp) KV_MEMBER(prev_hash) KV_MEMBER(nonce) KV_MEMBER(orphan_status) KV_MEMBER(height) KV_MEMBER(depth) KV_MEMBER(hash) KV_MEMBER(difficulty) KV_MEMBER(reward) KV_MEMBER(blockSize) KV_MEMBER(sizeMedian) KV_MEMBER(effectiveSizeMedian) KV_MEMBER(transactionsCumulativeSize) KV_MEMBER(alreadyGeneratedCoins) KV_MEMBER(alreadyGeneratedTransactions) KV_MEMBER(full_deposit_amount); KV_MEMBER(full_deposit_interest); KV_MEMBER(baseReward) KV_MEMBER(penalty) KV_MEMBER(transactions) KV_MEMBER(totalFeeAmount) } }; struct F_COMMAND_RPC_GET_BLOCKS_LIST { struct request { uint64_t height; void serialize(ISerializer &s) { KV_MEMBER(height) } }; struct response { std::vector<f_block_short_response> blocks; //transactions blobs as hex std::string status; void serialize(ISerializer &s) { KV_MEMBER(blocks) KV_MEMBER(status) } }; }; struct F_COMMAND_RPC_GET_BLOCK_DETAILS { struct request { std::string hash; void serialize(ISerializer &s) { KV_MEMBER(hash) } }; struct response { f_block_details_response block; std::string status; void serialize(ISerializer &s) { KV_MEMBER(block) KV_MEMBER(status) } }; }; struct F_COMMAND_RPC_GET_TRANSACTION_DETAILS { struct request { std::string hash; void serialize(ISerializer &s) { KV_MEMBER(hash) } }; struct response { Transaction tx; f_transaction_details_response txDetails; f_block_short_response block; std::string status; void serialize(ISerializer &s) { KV_MEMBER(tx) KV_MEMBER(txDetails) KV_MEMBER(block) KV_MEMBER(status) } }; }; struct F_COMMAND_RPC_GET_POOL { typedef EMPTY_STRUCT request; struct response { std::vector<f_transaction_short_response> transactions; std::string status; void serialize(ISerializer &s) { KV_MEMBER(transactions) KV_MEMBER(status) } }; }; struct COMMAND_RPC_GET_MEMPOOL { typedef EMPTY_STRUCT request; struct response { std::vector<f_mempool_transaction_response> mempool; std::string status; void serialize(ISerializer &s) { KV_MEMBER(mempool) KV_MEMBER(status) } }; }; //----------------------------------------------- struct COMMAND_RPC_GET_TRANSACTIONS_BY_PAYMENT_ID { struct request { std::string payment_id; void serialize(ISerializer &s) { KV_MEMBER(payment_id) } }; struct response { std::vector<f_transaction_short_response> transactions; std::string status; void serialize(ISerializer &s) { KV_MEMBER(transactions) KV_MEMBER(status) } }; }; struct COMMAND_RPC_GET_TRANSACTION_HASHES_BY_PAYMENT_ID { struct request { Crypto::Hash paymentId; void serialize(ISerializer &s) { KV_MEMBER(paymentId) } }; struct response { std::vector<Crypto::Hash> transactionHashes; std::string status; void serialize(ISerializer &s) { KV_MEMBER(status) KV_MEMBER(transactionHashes); } }; }; struct COMMAND_RPC_GET_BLOCKS_DETAILS_BY_HEIGHTS { struct request { std::vector<uint32_t> blockHeights; void serialize(ISerializer& s) { KV_MEMBER(blockHeights); } }; struct response { std::vector<BlockDetailsEx> blocks; std::string status; void serialize(ISerializer& s) { KV_MEMBER(status) KV_MEMBER(blocks) } }; }; struct COMMAND_RPC_GET_BLOCKS_DETAILS_BY_HASHES { struct request { std::vector<Crypto::Hash> blockHashes; void serialize(ISerializer& s) { KV_MEMBER(blockHashes); } }; struct response { std::vector<BlockDetailsEx> blocks; std::string status; void serialize(ISerializer& s) { KV_MEMBER(status) KV_MEMBER(blocks) } }; }; struct COMMAND_RPC_GET_BLOCK_DETAILS_BY_HEIGHT { struct request { uint32_t blockHeight; void serialize(ISerializer& s) { KV_MEMBER(blockHeight) } }; struct response { BlockDetailsEx block; std::string status; void serialize(ISerializer& s) { KV_MEMBER(status) KV_MEMBER(block) } }; }; struct COMMAND_RPC_GET_BLOCKS_HASHES_BY_TIMESTAMPS { struct request { uint64_t timestampBegin; uint64_t timestampEnd; uint32_t limit; void serialize(ISerializer &s) { KV_MEMBER(timestampBegin) KV_MEMBER(timestampEnd) KV_MEMBER(limit) } }; struct response { std::vector<Crypto::Hash> blockHashes; uint32_t count; std::string status; void serialize(ISerializer &s) { KV_MEMBER(status) KV_MEMBER(count) KV_MEMBER(blockHashes) } }; }; struct COMMAND_RPC_GET_TRANSACTIONS_DETAILS_BY_HASHES { struct request { std::vector<Crypto::Hash> transactionHashes; void serialize(ISerializer &s) { KV_MEMBER(transactionHashes); } }; struct response { std::vector<TransactionDetailsEx> transactions; std::string status; void serialize(ISerializer &s) { KV_MEMBER(status) KV_MEMBER(transactions) } }; }; struct COMMAND_RPC_GET_TRANSACTION_DETAILS_BY_HASH { struct request { Crypto::Hash hash; void serialize(ISerializer &s) { KV_MEMBER(hash); } }; struct response { TransactionDetailsEx transaction; std::string status; void serialize(ISerializer &s) { KV_MEMBER(status) KV_MEMBER(transaction) } }; }; struct COMMAND_RPC_GET_TRANSACTION_DETAILS_BY_HASHES { struct request { std::vector<Crypto::Hash> transactionHashes; void serialize(ISerializer &s) { KV_MEMBER(transactionHashes); } }; struct response { std::vector<TransactionDetailsEx> transactions; std::string status; void serialize(ISerializer &s) { KV_MEMBER(status) KV_MEMBER(transactions) } }; }; //----------------------------------------------- struct COMMAND_RPC_CHECK_TX_KEY { struct request { std::string txid; std::string txkey; std::string address; void serialize(ISerializer &s) { KV_MEMBER(txid) KV_MEMBER(txkey) KV_MEMBER(address) } }; struct response { uint64_t amount; std::vector<TransactionOutput> outputs; std::string status; void serialize(ISerializer &s) { KV_MEMBER(amount) KV_MEMBER(outputs) KV_MEMBER(status) } }; }; //----------------------------------------------- struct COMMAND_RPC_CHECK_TX_WITH_PRIVATE_VIEW_KEY { struct request { std::string txid; std::string view_key; std::string address; void serialize(ISerializer &s) { KV_MEMBER(txid) KV_MEMBER(view_key) KV_MEMBER(address) } }; struct response { uint64_t amount; std::vector<TransactionOutput> outputs; uint32_t confirmations = 0; std::string status; void serialize(ISerializer &s) { KV_MEMBER(amount) KV_MEMBER(outputs) KV_MEMBER(confirmations) KV_MEMBER(status) } }; }; //----------------------------------------------- struct K_COMMAND_RPC_CHECK_TX_KEY { struct request { std::string txid; std::string txkey; std::string address; void serialize(ISerializer &s) { KV_MEMBER(txid) KV_MEMBER(txkey) KV_MEMBER(address) } }; struct response { uint64_t amount; std::vector<TransactionOutput> outputs; std::string status; void serialize(ISerializer &s) { KV_MEMBER(amount) KV_MEMBER(outputs) KV_MEMBER(status) } }; }; struct COMMAND_RPC_VALIDATE_ADDRESS { struct request { std::string address; void serialize(ISerializer &s) { KV_MEMBER(address) } }; struct response { bool isvalid; std::string address; std::string spendPublicKey; std::string viewPublicKey; std::string status; void serialize(ISerializer &s) { KV_MEMBER(isvalid) KV_MEMBER(address) KV_MEMBER(spendPublicKey) KV_MEMBER(viewPublicKey) KV_MEMBER(status) } }; }; struct COMMAND_RPC_VERIFY_MESSAGE { struct request { std::string message; std::string address; std::string signature; void serialize(ISerializer &s) { KV_MEMBER(message) KV_MEMBER(address) KV_MEMBER(signature) } }; struct response { bool sig_valid; std::string status; void serialize(ISerializer &s) { KV_MEMBER(sig_valid) KV_MEMBER(status) } }; }; struct COMMAND_RPC_CHECK_TX_PROOF { struct request { std::string tx_id; std::string dest_address; std::string signature; void serialize(ISerializer &s) { KV_MEMBER(tx_id) KV_MEMBER(dest_address) KV_MEMBER(signature) } }; struct response { bool signature_valid; uint64_t received_amount; std::vector<TransactionOutput> outputs; uint32_t confirmations = 0; std::string status; void serialize(ISerializer &s) { KV_MEMBER(signature_valid) KV_MEMBER(received_amount) KV_MEMBER(outputs) KV_MEMBER(confirmations) KV_MEMBER(status) } }; }; struct COMMAND_RPC_CHECK_RESERVE_PROOF { struct request { std::string address; std::string message; std::string signature; void serialize(ISerializer &s) { KV_MEMBER(address) KV_MEMBER(message) KV_MEMBER(signature) } }; struct response { bool good; uint64_t total; uint64_t spent; void serialize(ISerializer &s) { KV_MEMBER(good) KV_MEMBER(total) KV_MEMBER(spent) } }; }; //----------------------------------------------- struct reserve_proof_entry { Crypto::Hash txid; uint64_t index_in_tx; Crypto::PublicKey shared_secret; Crypto::KeyImage key_image; Crypto::Signature shared_secret_sig; Crypto::Signature key_image_sig; void serialize(ISerializer &s) { KV_MEMBER(txid) KV_MEMBER(index_in_tx) KV_MEMBER(shared_secret) KV_MEMBER(key_image) KV_MEMBER(shared_secret_sig) KV_MEMBER(key_image_sig) } }; struct reserve_proof { std::vector<reserve_proof_entry> proofs; Crypto::Signature signature; void serialize(ISerializer &s) { KV_MEMBER(proofs) KV_MEMBER(signature) } }; struct COMMAND_RPC_GEN_PAYMENT_ID { typedef EMPTY_STRUCT request; struct response { std::string payment_id; void serialize(ISerializer &s) { KV_MEMBER(payment_id) } }; }; }
[ "admin@adon.network" ]
admin@adon.network
7e1b4977fb706295395793cc1f5d655c947935cb
0bf8d7dc50c2417d53e952e630dc650b23bf8f96
/TG/bookcodes/ch2/la3641.cpp
77a2febb349434499409ebfd0585f30f6f15037d
[ "Apache-2.0" ]
permissive
shuvro/aoapc-code
ce2f8efd8ce7e5e5fc6792b6a92fecfafb6a011d
e787a01380698fb9236d933462052f97b20e6132
refs/heads/master
2021-06-03T10:20:53.765574
2016-10-01T01:18:24
2016-10-01T01:18:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
678
cpp
// LA3641 Leonardo's Notebook // Rujia Liu #include<cstdio> #include<cstring> int main() { char B[30]; int vis[30], cnt[30], T; scanf("%d", &T); while(T--) { scanf("%s", B); memset(vis, 0, sizeof(vis)); memset(cnt, 0, sizeof(cnt)); for(int i = 0; i < 26; i++) if(!vis[i]) { // 找一个从i开始的循环 int j = i, n = 0; do { vis[j] = 1; // 标记j为“已访问” j = B[j] - 'A'; n++; } while(j != i); cnt[n]++; } int ok = 1; for(int i = 2; i <= 26; i++) if(i%2 == 0 && cnt[i]%2 == 1) ok = 0; if(ok) printf("Yes\n"); else printf("No\n"); } return 0; }
[ "yileian@umich.edu" ]
yileian@umich.edu
7f31c37f0c1a73d7f8216de1b502867eda17ea1d
96e7347db30d3ae35f2df119a18472cf5b251fa2
/Classes/Native/mscorlib_System_Collections_Generic_List_1_gen3200083838.h
42681eb737a4cd52b8ca057240f1bb6d7ec3e8be
[]
no_license
Henry0285/abcwriting
04b111887489d9255fd2697a4ea8d9971dc17d89
ed2e4da72fbbad85d9e0e9d912e73ddd33bc91ec
refs/heads/master
2021-01-20T14:16:48.025648
2017-05-08T06:00:06
2017-05-08T06:00:06
90,583,162
0
0
null
null
null
null
UTF-8
C++
false
false
2,790
h
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> // System.Transactions.ISinglePhaseNotification[] struct ISinglePhaseNotificationU5BU5D_t1768506678; #include "mscorlib_System_Object707969140.h" #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Collections.Generic.List`1<System.Transactions.ISinglePhaseNotification> struct List_1_t3200083838 : public Il2CppObject { public: // T[] System.Collections.Generic.List`1::_items ISinglePhaseNotificationU5BU5D_t1768506678* ____items_1; // System.Int32 System.Collections.Generic.List`1::_size int32_t ____size_2; // System.Int32 System.Collections.Generic.List`1::_version int32_t ____version_3; public: inline static int32_t get_offset_of__items_1() { return static_cast<int32_t>(offsetof(List_1_t3200083838, ____items_1)); } inline ISinglePhaseNotificationU5BU5D_t1768506678* get__items_1() const { return ____items_1; } inline ISinglePhaseNotificationU5BU5D_t1768506678** get_address_of__items_1() { return &____items_1; } inline void set__items_1(ISinglePhaseNotificationU5BU5D_t1768506678* value) { ____items_1 = value; Il2CppCodeGenWriteBarrier(&____items_1, value); } inline static int32_t get_offset_of__size_2() { return static_cast<int32_t>(offsetof(List_1_t3200083838, ____size_2)); } inline int32_t get__size_2() const { return ____size_2; } inline int32_t* get_address_of__size_2() { return &____size_2; } inline void set__size_2(int32_t value) { ____size_2 = value; } inline static int32_t get_offset_of__version_3() { return static_cast<int32_t>(offsetof(List_1_t3200083838, ____version_3)); } inline int32_t get__version_3() const { return ____version_3; } inline int32_t* get_address_of__version_3() { return &____version_3; } inline void set__version_3(int32_t value) { ____version_3 = value; } }; struct List_1_t3200083838_StaticFields { public: // T[] System.Collections.Generic.List`1::EmptyArray ISinglePhaseNotificationU5BU5D_t1768506678* ___EmptyArray_4; public: inline static int32_t get_offset_of_EmptyArray_4() { return static_cast<int32_t>(offsetof(List_1_t3200083838_StaticFields, ___EmptyArray_4)); } inline ISinglePhaseNotificationU5BU5D_t1768506678* get_EmptyArray_4() const { return ___EmptyArray_4; } inline ISinglePhaseNotificationU5BU5D_t1768506678** get_address_of_EmptyArray_4() { return &___EmptyArray_4; } inline void set_EmptyArray_4(ISinglePhaseNotificationU5BU5D_t1768506678* value) { ___EmptyArray_4 = value; Il2CppCodeGenWriteBarrier(&___EmptyArray_4, value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif
[ "phamnguyentruc@yahoo.com" ]
phamnguyentruc@yahoo.com
04dce68c1219451b2fc72946563d11e0ea86d86d
aaff0a475ba8195d622b6989c089ba057f180d54
/backup/2/exercism/c++/bob.cpp
e66ae6b10e159c1dafccddeb80f5e01bb1427b84
[ "Apache-2.0" ]
permissive
DandelionLU/code-camp
328b2660391f1b529f1187a87c41e15a3eefb3ee
0fd18432d0d2c4123b30a660bae156283a74b930
refs/heads/master
2023-08-24T00:01:48.900746
2021-10-30T06:37:42
2021-10-30T06:37:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,164
cpp
// Hi, I'm Yanzhan. For more algothmic problems, visit my Youtube Channel (Yanzhan Yang's Youtube Channel) : https://www.youtube.com/channel/UCDkz-__gl3frqLexukpG0DA?view_as=subscriber or my Twitter Account (Yanzhan Yang's Twitter) : https://twitter.com/YangYanzhan or my GitHub HomePage (Yanzhan Yang's GitHub HomePage) : https://yanzhan.site . // For this specific algothmic problem, visit my Youtube Video : . // It's fascinating to solve algothmic problems, follow Yanzhan to learn more! // Blog URL for this problem: https://yanzhan.site/exercism/bob.html . // bob.h #include <string> using namespace std; class bob { public: static string hey(string in); }; // bob.cpp #include <regex> #include "bob.h" string bob::hey(string in) { string uppered; for (char ch : in) { uppered += toupper(ch); } bool hasAlpha = regex_match(uppered, regex(".*[A-Z].*")); if (hasAlpha && in == uppered) { return "Whoa, chill out!"; } if (regex_match(in, regex(".*[?][ ]*"))) { return "Sure."; } if (regex_match(in, regex("[ ]*"))) { return "Fine. Be that way!"; } return "Whatever."; }
[ "yangyanzhan@gmail.com" ]
yangyanzhan@gmail.com
c4fe09db2f9c2ada54e2c17915749077d653fc5d
e6b3cd949984c5eafb3df83bd7aa5aab32d1ed9b
/lab19/lab19.cpp
8130be612487c0657c0292533e196bc72a423e8e
[]
no_license
ike4892/CSCI20-Fall2016
edded9e5ab054cc1562bcb3126bd8d59ac71f2cc
305e44bc0971a75689dac1576f21ea83a19fb72f
refs/heads/master
2020-12-05T02:16:03.993325
2016-12-15T20:54:03
2016-12-15T20:54:03
66,294,219
0
0
null
null
null
null
UTF-8
C++
false
false
3,035
cpp
/* Kasey Koch * lab 19 * 11/09/2016 */ #include <iostream> #include <string> #include <fstream> using namespace std; int main(){ ifstream inFS; const int numRows = 4; const int numCols = 5; int fileNum = 0; int fileNumber[numRows][numCols]; inFS.open("text.txt"); // opens the file if (!inFS.is_open()) { cout<<"Failed to open text file."<<endl; return 1; // 1 shows error } //Process input file: while(!inFS.eof() ) { for(int i = 0; i < (numRows - 1); i++){ for(int j = 0; j < (numCols - 1); j++){ inFS >> fileNumber[i][j]; } } } cout << "input array: " << endl; for(int i = 0; i < 3; i++){ for(int j = 0; j < 4; j++){ cout << fileNumber[i][j]<<" "; } cout << endl; } inFS.close(); // closes the document cout << endl; cout << "current array: " << endl; //Process sum of rows: for(int i = 0; i < 3; i++){ for(int j = 0; j < 4; j++){ fileNum = fileNum + fileNumber[i][j]; } fileNumber[i][4] = fileNum; fileNum = 0; } for(int i = 0; i < 3; i++){ for(int j = 0; j < 5; j++){ cout << fileNumber[i][j]<<" "; } cout << endl; } cout << endl; cout << "output array: " << endl; //Process sum of columns: for(int i = 0; i < 4; i++){ for(int j =0; j < 3; j++){ fileNum = fileNum + fileNumber[j][i]; } fileNumber[3][i] = fileNum; fileNum = 0; } //clean the messy spot fileNumber[3][4] = 0; for(int i = 0; i < 4; i++){ for(int j = 0; j < 5; j++){ cout << fileNumber[i][j]<<" "; } cout << endl; } //Create and output finished array: ofstream outfs; outfs.open("output.txt"); for(int i = 0; i < 4; i++){ for(int j = 0; j < 5; j++){ outfs << fileNumber[i][j] << " "; } outfs << endl; } return 0; } /* PSEUDOCODE: *File input * Create array (4 long, 5 wide) * Process the input of text.txt: * Store into array, end of line starts new row (remember to skip whitespaces!) Process the output of text.txt: FOR LOOP: array[N][4] => SUM of indexes 0 to 3 for N row index where N is 0 to 2 FOR LOOP: array[3][N] => SUM of indexes 0 to 2 for N column index where N is 0 to 3 Output the value of the resultant file output.txt Following format: 1 2 3 4 SUM_OF_ROW_ONE 5 6 7 8 SUM_OF_ROW_TWO 9 10 11 12 SUM_OF_ROW_THREE SUM_OF_COLUMN_ONE SUM_OF_COLUMN_TWO SUM_OF_COLUMN_THREE SUM_OF_COLUMN_FOUR */
[ "kkoch002@student.butte.edu" ]
kkoch002@student.butte.edu
dc1f91abbe2fc2edb46b2d2b0c9b6ed41389ba48
58c75699c6f28b92620689b027f35565e751629e
/gate_set.h
8d0d1799f76164082ab40dd020e559f8a5b3276a
[]
no_license
Evanchaii/Drexel-ECEC672-JASSTA
66192ec5052a6d6da670d301ccf5880bb4c4c8ba
15d8a02c5b3b82ce3c15ffde5d28e6410ebbfcce
refs/heads/master
2020-09-06T08:31:00.277841
2013-07-07T05:57:40
2013-07-07T05:57:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
481
h
#ifndef _gate_set_ #define _gate_set_ #include <iostream> //#include "gate_cpdf.h" #include <vector> using namespace std; //Class to do set operations with gates class gate_cpdf; class gate_set { public: gate_set(); void insert(gate_cpdf * g); gate_set gs_union( gate_set * gs); //union keyword used gate_set intersect( gate_set * gs); gate_set difference( gate_set * gs); int get_index(gate_cpdf * g); vector<gate_cpdf * > gates; }; #endif
[ "jvk@drexel.edu" ]
jvk@drexel.edu
5cab8555cd088bdd094ee242a79afc663315503d
dbb50d74406518f58baae0f91e7fb44874ab31e6
/RingingMaster/MatrixManagerEventListener.h
ea8a149db4c1ae546481268e306b204c68b92368
[]
no_license
lakestephen/ringingmaster_cpp
60f917eb66970e6fc84f9703a229dd0028892632
3d34efa1c4dca560a67a8aee1375df92fdcbeb6f
refs/heads/master
2023-02-20T14:41:35.756431
2021-01-26T19:45:38
2021-01-26T19:45:38
333,197,351
1
0
null
null
null
null
UTF-8
C++
false
false
527
h
#pragma once enum MatrixEntityToken; class MatrixManagerEventListener { public: MatrixManagerEventListener() {}; ~MatrixManagerEventListener() {}; virtual void matrixManager_updateFilterList() {}; virtual void matrixManager_entityAdded(MatrixEntityToken /*token*/, long /*id*/) {}; virtual void matrixManager_entityRemoved(MatrixEntityToken /*token*/, long /*id*/) {}; virtual void matrixManager_refresh() {}; }; typedef CArray<MatrixManagerEventListener*, MatrixManagerEventListener*> MatrixManagerEventListeners;
[ "steve.lake@anaplan.com" ]
steve.lake@anaplan.com
4a651cc6090a80c5f7fd113e8b3de30c811307ee
8f2843049463d24888d9a4532b1fd5d283b131ad
/skia/third_party/externals/dawn/src/tests/end2end/NonzeroTextureCreationTests.cpp
00f26c3c32c04bc99b1c036f76e7e33ab085cf31
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "MIT", "Libpng", "FTL", "ICU", "BSD-3-Clause", "IJG", "Zlib", "NAIST-2003", "MIT-Modern-Variant", "LicenseRef-scancode-unicode", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-public-domain", "LicenseRef-scan...
permissive
openharmony/third_party_flutter
90a413f139848ce36a6af11233f1cee101bdb1c1
3282d03b17ac498e90d993761296a53a4f89c546
refs/heads/master
2023-08-30T17:42:32.034443
2021-10-21T11:36:39
2021-10-21T11:36:39
400,092,174
0
1
null
null
null
null
UTF-8
C++
false
false
4,317
cpp
// Copyright 2019 The Dawn Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "tests/DawnTest.h" #include "utils/ComboRenderPipelineDescriptor.h" #include "utils/DawnHelpers.h" class NonzeroTextureCreationTests : public DawnTest { protected: void SetUp() override { DawnTest::SetUp(); } constexpr static uint32_t kSize = 128; }; // Test that texture clears to 1's because toggle is enabled. TEST_P(NonzeroTextureCreationTests, TextureCreationClearsOneBits) { dawn::TextureDescriptor descriptor; descriptor.dimension = dawn::TextureDimension::e2D; descriptor.size.width = kSize; descriptor.size.height = kSize; descriptor.size.depth = 1; descriptor.arrayLayerCount = 1; descriptor.sampleCount = 1; descriptor.format = dawn::TextureFormat::RGBA8Unorm; descriptor.mipLevelCount = 1; descriptor.usage = dawn::TextureUsageBit::OutputAttachment | dawn::TextureUsageBit::CopySrc; dawn::Texture texture = device.CreateTexture(&descriptor); RGBA8 filledWithOnes(255, 255, 255, 255); EXPECT_PIXEL_RGBA8_EQ(filledWithOnes, texture, 0, 0); } // Test that non-zero mip level clears to 1's because toggle is enabled. TEST_P(NonzeroTextureCreationTests, MipMapClears) { constexpr uint32_t mipLevels = 4; dawn::TextureDescriptor descriptor; descriptor.dimension = dawn::TextureDimension::e2D; descriptor.size.width = kSize; descriptor.size.height = kSize; descriptor.size.depth = 1; descriptor.arrayLayerCount = 1; descriptor.sampleCount = 1; descriptor.format = dawn::TextureFormat::RGBA8Unorm; descriptor.mipLevelCount = mipLevels; descriptor.usage = dawn::TextureUsageBit::OutputAttachment | dawn::TextureUsageBit::CopySrc; dawn::Texture texture = device.CreateTexture(&descriptor); std::vector<RGBA8> expected; RGBA8 filledWithOnes(255, 255, 255, 255); for (uint32_t i = 0; i < kSize * kSize; ++i) { expected.push_back(filledWithOnes); } uint32_t mipSize = kSize >> 2; EXPECT_TEXTURE_RGBA8_EQ(expected.data(), texture, 0, 0, mipSize, mipSize, 2, 0); } // Test that non-zero array layers clears to 1's because toggle is enabled. TEST_P(NonzeroTextureCreationTests, ArrayLayerClears) { constexpr uint32_t arrayLayers = 4; dawn::TextureDescriptor descriptor; descriptor.dimension = dawn::TextureDimension::e2D; descriptor.size.width = kSize; descriptor.size.height = kSize; descriptor.size.depth = 1; descriptor.arrayLayerCount = arrayLayers; descriptor.sampleCount = 1; descriptor.format = dawn::TextureFormat::RGBA8Unorm; descriptor.mipLevelCount = 1; descriptor.usage = dawn::TextureUsageBit::OutputAttachment | dawn::TextureUsageBit::CopySrc; dawn::Texture texture = device.CreateTexture(&descriptor); std::vector<RGBA8> expected; RGBA8 filledWithOnes(255, 255, 255, 255); for (uint32_t i = 0; i < kSize * kSize; ++i) { expected.push_back(filledWithOnes); } EXPECT_TEXTURE_RGBA8_EQ(expected.data(), texture, 0, 0, kSize, kSize, 0, 2); } DAWN_INSTANTIATE_TEST(NonzeroTextureCreationTests, ForceWorkarounds(D3D12Backend, {"nonzero_clear_resources_on_creation_for_testing"}, {"lazy_clear_resource_on_first_use"}), ForceWorkarounds(OpenGLBackend, {"nonzero_clear_resources_on_creation_for_testing"}, {"lazy_clear_resource_on_first_use"}), ForceWorkarounds(VulkanBackend, {"nonzero_clear_resources_on_creation_for_testing"}, {"lazy_clear_resource_on_first_use"}));
[ "mamingshuai1@huawei.com" ]
mamingshuai1@huawei.com
c033d27891b16fe14e6be9330ba7959ad1d2dc37
ffd6e7f0f3dc76e41c7784bebdd28973191900f2
/USACO/slowdown.cpp
099bac694442917df0926fac66652279bdda8c76
[]
no_license
theopan8/competitive-programming
e12a1b2f8a00748d7170ec8c130c0bfdb605baa8
c507102b204e09ccd037dd37e6e3677dae1bb89c
refs/heads/main
2023-07-22T20:56:39.956584
2021-08-31T20:57:11
2021-08-31T20:57:11
387,005,395
0
0
null
null
null
null
UTF-8
C++
false
false
1,416
cpp
#include <iostream> #include <vector> #include <algorithm> #include <string> #include <map> #include <cstdio> #include <utility> #include <queue> #include <math.h> #include <set> #include <bitset> #include <cmath> #include <bitset> #include <cstring> using namespace std; #define MaxVal 100005 int tree[MaxVal]; vector<int> graph[MaxVal]; int visited[MaxVal]; map<int,int> barn_cowmap; int answer[MaxVal]; int read(int idx){ int sum = 0; while (idx > 0){ sum += tree[idx]; idx -= (idx & -idx); } return sum; } void update(int idx, int val){ while (idx <= MaxVal){ tree[idx] += val; idx += (idx & -idx); } } void dfs (int pasture) { if (visited[pasture] != 0) { return; } visited[pasture] = 1; answer[barn_cowmap[pasture]] = read(barn_cowmap[pasture]); update(barn_cowmap[pasture], 1); for(int i = 0; i < graph[pasture].size(); i++) { if (visited[graph[pasture][i]] == 0) { dfs(graph[pasture][i]); } } update(barn_cowmap[pasture], -1); } int main() { int n; cin >> n; for(int i = 0; i < n-1; i++) { int a, b; cin >> a >> b; graph[a].push_back(b); graph[b].push_back(a); } for(int i = 1; i <= n; i++) { int p; cin >> p; barn_cowmap[p] = i; } dfs(1); for(int i = 1; i <= n; i++) { cout << answer[i] << endl; } }
[ "noreply@github.com" ]
noreply@github.com
1c3bbac5af48c4c469ca6d4105dcba293259f62d
806a34aca3deabd4d7de22e272e0be65eae5ae03
/yy/game/DZPoker/Classes/GameTable/GameLogic.cpp
58ae51a05d5e57d50e3f7f3038c4fb1b58c43cab
[ "MIT" ]
permissive
seem-sky/yygame
ea293c0942611e6060cc9c7eab91b084985be45c
117806d536700b165f03992fe0643e2bba0409c5
refs/heads/master
2020-06-29T05:25:37.848022
2016-09-24T06:54:03
2016-09-24T06:54:03
null
0
0
null
null
null
null
GB18030
C++
false
false
15,014
cpp
#include "GameLogic.h" #include <stdlib.h> #define ARRAY_COUNT(_array) (sizeof(_array) / sizeof(_array[0])) //扑克定义 static BYTE s_CardData[FULL_COUNT] = { 0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D, //方块 2 - A 0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19,0x1A,0x1B,0x1C,0x1D, //梅花 2 - A 0x21,0x22,0x23,0x24,0x25,0x26,0x27,0x28,0x29,0x2A,0x2B,0x2C,0x2D, //红桃 2 - A 0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x3A,0x3B,0x3C,0x3D, //黑桃 2 - A }; GameLogic::GameLogic() { } GameLogic::~GameLogic() { } //混乱扑克 void GameLogic::randCard(BYTE cbCardBuffer[], BYTE cbBufferCount) { //混乱准备 BYTE cbCardData[ARRAY_COUNT(s_CardData)] = {0}; //混乱扑克 BYTE cbRandCount = 0, cbPosition = 0; do { cbPosition = rand()%(cbBufferCount-cbRandCount); cbCardBuffer[cbRandCount++] = cbCardData[cbPosition]; cbCardData[cbPosition] = cbCardData[cbBufferCount - cbRandCount]; } while (cbRandCount < cbBufferCount); } //获取类型 BYTE GameLogic::getCardType(BYTE cbCardData[], BYTE cbCardCount) { //数据校验 assert(cbCardCount == MAX_CENTERCOUNT); if(cbCardCount != MAX_CENTERCOUNT) return 0; //变量定义 bool cbSameColor = true, bLineCard = true; BYTE cbFirstColor = getCardColor(cbCardData[0]); BYTE cbFirstValue = getCardLogicValue(cbCardData[0]); //牌形分析 for (BYTE i = 1; i < cbCardCount; i++) { //数据分析 if (getCardColor(cbCardData[i]) != cbFirstColor) cbSameColor = false; if (cbFirstValue!=(getCardLogicValue(cbCardData[i])+i)) bLineCard = false; //结束判断 if ((cbSameColor == false) && (bLineCard == false)) break; } //最小同花顺 if((bLineCard == false)&&(cbFirstValue == 14)) { BYTE i=1; for( i = 1; i < cbCardCount; i++) { BYTE cbLogicValue = getCardLogicValue(cbCardData[i]); if ((cbFirstValue != (cbLogicValue+i+8))) break; } if (i == cbCardCount) { bLineCard = true; } } //皇家同花顺 if (cbSameColor && bLineCard && (getCardLogicValue(cbCardData[1]) == 13 )) return CT_KING_TONG_HUA_SHUN; //顺子类型 if (!cbSameColor && bLineCard) return CT_SHUN_ZI; //同花类型 if (cbSameColor && !bLineCard) return CT_TONG_HUA; //同花顺类型 if (cbSameColor && bLineCard) return CT_TONG_HUA_SHUN; //扑克分析 CardAnalyseResult AnalyseResult; analysebCardData(cbCardData, cbCardCount, AnalyseResult); //类型判断 if (AnalyseResult.cbFourCount == 1) return CT_TIE_ZHI; if (AnalyseResult.cbLONGCount == 2) return CT_TWO_LONG; if ((AnalyseResult.cbLONGCount == 1) && (AnalyseResult.cbThreeCount == 1)) return CT_HU_LU; if ((AnalyseResult.cbThreeCount == 1) && (AnalyseResult.cbLONGCount == 0)) return CT_THREE_TIAO; if ((AnalyseResult.cbLONGCount == 1) && (AnalyseResult.cbSignedCount == 3)) return CT_ONE_LONG; return CT_SINGLE; } //查找扑克 BYTE GameLogic::getSameCard(const BYTE bCardData[],const BYTE bMaxCard[],BYTE bCardCount,BYTE bMaxCardCount,BYTE bResultData[]) { if(bCardData[0] == 0 || bMaxCard[0]==0)return 0; BYTE bTempCount = 0; for (BYTE i = 0; i < bCardCount; i++) { for (BYTE j = 0; j < bMaxCardCount; j++) { if (bCardData[i] == bMaxCard[j]) bResultData[bTempCount++] = bMaxCard[j]; } } return bTempCount; } //最大牌型 BYTE GameLogic::fiveFromSeven(BYTE cbHandCardData[],BYTE cbHandCardCount,BYTE cbCenterCardData[],BYTE cbCenterCardCount,BYTE cbLastCardData[],BYTE cbLastCardCount) { //临时变量 BYTE cbTempCardData[MAX_COUNT + MAX_CENTERCOUNT],cbTempLastCardData[5]; memset(cbTempCardData, 0x0, sizeof(cbTempCardData)); memset(cbTempLastCardData, 0x0, sizeof(cbTempLastCardData)); //拷贝数据 memcpy(cbTempCardData, cbHandCardData, sizeof(BYTE)*MAX_COUNT); memcpy(&cbTempCardData[2], cbCenterCardData, sizeof(BYTE)*MAX_CENTERCOUNT); //排列扑克 sortCard(cbTempCardData, ARRAY_COUNT(cbTempCardData)); memcpy(cbLastCardData,cbTempCardData,sizeof(BYTE)*MAX_CENTERCOUNT); BYTE cbCardKind = getCardType(cbLastCardData, sizeof(BYTE)*MAX_CENTERCOUNT); BYTE cbTempCardKind = 0; //组合算法 for (int i=0;i<3;i++) { for (int j= i+1;j<4;j++) { for (int k = j+1;k<5;k++) { for (int l =k+1;l<6;l++) { for (int m=l+1;m<7;m++) { //获取数据 cbTempLastCardData[0]=cbTempCardData[i]; cbTempLastCardData[1]=cbTempCardData[j]; cbTempLastCardData[2]=cbTempCardData[k]; cbTempLastCardData[3]=cbTempCardData[l]; cbTempLastCardData[4]=cbTempCardData[m]; //获取牌型 cbTempCardKind = getCardType(cbTempLastCardData,ARRAY_COUNT(cbTempLastCardData)); //牌型大小 if(compareCard(cbTempLastCardData,cbLastCardData,ARRAY_COUNT(cbTempLastCardData))==2) { cbCardKind = cbTempCardKind; memcpy(cbLastCardData,cbTempLastCardData,sizeof(BYTE) * ARRAY_COUNT(cbTempLastCardData)); } } } } } } return cbCardKind; } //查找最大 bool GameLogic::selectMaxUser(BYTE bCardData[GAME_PLAYER][MAX_CENTERCOUNT], UserWinList &EndResult, const LLONG lAddScore[]) { //清理数据 memset(&EndResult, 0x0, sizeof(EndResult)); //First数据 WORD wWinnerID; BYTE i = 0; for (i = 0; i < GAME_PLAYER; i++) { if(bCardData[i][0] != 0) { wWinnerID = i; break; } } //过滤全零 if(i == GAME_PLAYER)return false; //查找最大用户 WORD wTemp = wWinnerID; for(WORD i=1;i<GAME_PLAYER;i++) { WORD j=(i+wTemp)%GAME_PLAYER; if(bCardData[j][0]==0)continue; if(compareCard(bCardData[j],bCardData[wWinnerID],MAX_CENTERCOUNT)>1) { wWinnerID=j; } } //查找相同数据 EndResult.wWinerList[EndResult.bSameCount++] = wWinnerID; for(WORD i=0;i<GAME_PLAYER;i++) { if(i==wWinnerID || bCardData[i][0]==0)continue; if(compareCard(bCardData[i],bCardData[wWinnerID],MAX_CENTERCOUNT)==false) { EndResult.wWinerList[EndResult.bSameCount++] = i; } } //从小到大 if(EndResult.bSameCount>1 && lAddScore!=nullptr) { int iSameCount=(int)EndResult.bSameCount; while((iSameCount--)>0) { LLONG lTempSocre = lAddScore[EndResult.wWinerList[iSameCount]]; for(int i=iSameCount-1;i>=0;i--) { assert(lAddScore[EndResult.wWinerList[i]]>0); if(lTempSocre < lAddScore[EndResult.wWinerList[i]]) { lTempSocre = lAddScore[EndResult.wWinerList[i]]; WORD wTemp = EndResult.wWinerList[iSameCount]; EndResult.wWinerList[iSameCount] = EndResult.wWinerList[i]; EndResult.wWinerList[i] = wTemp; } } } } return true; } //排列扑克 void GameLogic::sortCard(BYTE cbCardData[], BYTE cbCardCount) { //转换数值 BYTE cbLogicValue[FULL_COUNT]; for (BYTE i=0;i<cbCardCount;i++) { cbLogicValue[i] = getCardLogicValue(cbCardData[i]); } //排序操作 bool bSorted = true; BYTE cbTempData,bLast=cbCardCount-1; do { bSorted=true; for (BYTE i=0;i<bLast;i++) { if ((cbLogicValue[i]<cbLogicValue[i+1])|| ((cbLogicValue[i]==cbLogicValue[i+1])&&(cbCardData[i]<cbCardData[i+1]))) { //交换位置 cbTempData=cbCardData[i]; cbCardData[i]=cbCardData[i+1]; cbCardData[i+1]=cbTempData; cbTempData=cbLogicValue[i]; cbLogicValue[i]=cbLogicValue[i+1]; cbLogicValue[i+1]=cbTempData; bSorted = false; } } bLast--; } while(bSorted==false); return; } //逻辑数值 BYTE GameLogic::getCardLogicValue(BYTE cbCardData) { //扑克属性 BYTE bCardColor = getCardColor(cbCardData); BYTE bCardValue = getCardValue(cbCardData); //转换数值 return (bCardValue == 1) ? (bCardValue + 13) : bCardValue; } //对比扑克 BYTE GameLogic::compareCard(BYTE cbFirstData[], BYTE cbNextData[], BYTE cbCardCount) { //获取类型 BYTE cbNextType = getCardType(cbNextData,cbCardCount); BYTE cbFirstType = getCardType(cbFirstData,cbCardCount); //类型判断 //大 if(cbFirstType > cbNextType) return 2; //小 if(cbFirstType < cbNextType) return 1; //简单类型 switch(cbFirstType) { case CT_SINGLE: //单牌 { //对比数值 BYTE i=0; for (i=0;i<cbCardCount;i++) { BYTE cbNextValue = getCardLogicValue(cbNextData[i]); BYTE cbFirstValue = getCardLogicValue(cbFirstData[i]); //大 if(cbFirstValue > cbNextValue) return 2; //小 else if(cbFirstValue <cbNextValue) return 1; //等 else continue; } //平 if (i == cbCardCount) return 0; assert(false); } case CT_ONE_LONG: //对子 case CT_TWO_LONG: //两对 case CT_THREE_TIAO: //三条 case CT_TIE_ZHI: //铁支 case CT_HU_LU: //葫芦 { //分析扑克 CardAnalyseResult AnalyseResultNext; CardAnalyseResult AnalyseResultFirst; analysebCardData(cbNextData,cbCardCount,AnalyseResultNext); analysebCardData(cbFirstData,cbCardCount,AnalyseResultFirst); //四条数值 if (AnalyseResultFirst.cbFourCount>0) { BYTE cbNextValue=AnalyseResultNext.cbFourLogicVolue[0]; BYTE cbFirstValue=AnalyseResultFirst.cbFourLogicVolue[0]; //比较四条 if(cbFirstValue != cbNextValue)return (cbFirstValue > cbNextValue)?2:1; //比较单牌 assert(AnalyseResultFirst.cbSignedCount==1 && AnalyseResultNext.cbSignedCount==1); cbFirstValue = AnalyseResultFirst.cbSignedLogicVolue[0]; cbNextValue = AnalyseResultNext.cbSignedLogicVolue[0]; if(cbFirstValue != cbNextValue)return (cbFirstValue > cbNextValue)?2:1; else return 0; } //三条数值 if (AnalyseResultFirst.cbThreeCount>0) { BYTE cbNextValue=AnalyseResultNext.cbThreeLogicVolue[0]; BYTE cbFirstValue=AnalyseResultFirst.cbThreeLogicVolue[0]; //比较三条 if(cbFirstValue != cbNextValue)return (cbFirstValue > cbNextValue)?2:1; //葫芦牌型 if(CT_HU_LU == cbFirstType) { //比较对牌 assert(AnalyseResultFirst.cbLONGCount==1 && AnalyseResultNext.cbLONGCount==1); cbFirstValue = AnalyseResultFirst.cbLONGLogicVolue[0]; cbNextValue = AnalyseResultNext.cbLONGLogicVolue[0]; if(cbFirstValue != cbNextValue)return (cbFirstValue > cbNextValue)?2:1; else return 0; } else //三条带单 { //比较单牌 assert(AnalyseResultFirst.cbSignedCount==2 && AnalyseResultNext.cbSignedCount==2); //散牌数值 BYTE i=0; for (i=0;i<AnalyseResultFirst.cbSignedCount;i++) { BYTE cbNextValue=AnalyseResultNext.cbSignedLogicVolue[i]; BYTE cbFirstValue=AnalyseResultFirst.cbSignedLogicVolue[i]; //大 if(cbFirstValue > cbNextValue) return 2; //小 else if(cbFirstValue <cbNextValue) return 1; //等 else continue; } if( i == AnalyseResultFirst.cbSignedCount) return 0; assert(false); } } //对子数值 BYTE i=0; for ( i=0;i<AnalyseResultFirst.cbLONGCount;i++) { BYTE cbNextValue=AnalyseResultNext.cbLONGLogicVolue[i]; BYTE cbFirstValue=AnalyseResultFirst.cbLONGLogicVolue[i]; //大 if(cbFirstValue > cbNextValue) return 2; //小 else if(cbFirstValue <cbNextValue) return 1; //平 else continue; } //比较单牌 assert( i == AnalyseResultFirst.cbLONGCount); { assert(AnalyseResultFirst.cbSignedCount==AnalyseResultNext.cbSignedCount && AnalyseResultNext.cbSignedCount>0); //散牌数值 for (i=0;i<AnalyseResultFirst.cbSignedCount;i++) { BYTE cbNextValue=AnalyseResultNext.cbSignedLogicVolue[i]; BYTE cbFirstValue=AnalyseResultFirst.cbSignedLogicVolue[i]; //大 if(cbFirstValue > cbNextValue) return 2; //小 else if(cbFirstValue <cbNextValue) return 1; //等 else continue; } //平 if( i == AnalyseResultFirst.cbSignedCount) return 0; } break; } case CT_SHUN_ZI: //顺子 case CT_TONG_HUA_SHUN: //同花顺 { //数值判断 BYTE cbNextValue = getCardLogicValue(cbNextData[0]); BYTE cbFirstValue = getCardLogicValue(cbFirstData[0]); bool bFirstmin= (cbFirstValue ==(getCardLogicValue(cbFirstData[1])+9)); bool bNextmin= (cbNextValue ==(getCardLogicValue(cbNextData[1])+9)); //大小顺子 if ((bFirstmin==true)&&(bNextmin == false)) { return 1; } //大小顺子 else if ((bFirstmin==false)&&(bNextmin == true)) { return 2; } //等同顺子 else { //平 if(cbFirstValue == cbNextValue)return 0; return (cbFirstValue > cbNextValue)?2:1; } } case CT_TONG_HUA: //同花 { BYTE i = 0; //散牌数值 for (i = 0; i < cbCardCount; i++) { BYTE cbNextValue=getCardLogicValue(cbNextData[i]); BYTE cbFirstValue=getCardLogicValue(cbFirstData[i]); if(cbFirstValue == cbNextValue)continue; return (cbFirstValue > cbNextValue)?2:1; } //平 if( i == cbCardCount) return 0; } } return 0; } //分析扑克 void GameLogic::analysebCardData(const BYTE cbCardData[], BYTE cbCardCount, CardAnalyseResult & AnalyseResult) { //设置结果 memset(&AnalyseResult, 0x0, sizeof(AnalyseResult)); //扑克分析 for (BYTE i=0;i<cbCardCount;i++) { //变量定义 BYTE cbSameCount=1; BYTE cbSameCardData[4]={cbCardData[i],0,0,0}; BYTE cbLogicValue=getCardLogicValue(cbCardData[i]); //获取同牌 for (int j=i+1;j<cbCardCount;j++) { //逻辑对比 if (getCardLogicValue(cbCardData[j])!=cbLogicValue) break; //设置扑克 cbSameCardData[cbSameCount++]=cbCardData[j]; } //保存结果 switch (cbSameCount) { case 1: //单张 { AnalyseResult.cbSignedLogicVolue[AnalyseResult.cbSignedCount]=cbLogicValue; memcpy(&AnalyseResult.cbSignedCardData[(AnalyseResult.cbSignedCount++)*cbSameCount],cbSameCardData,cbSameCount); break; } case 2: //两张 { AnalyseResult.cbLONGLogicVolue[AnalyseResult.cbLONGCount]=cbLogicValue; memcpy(&AnalyseResult.cbLONGCardData[(AnalyseResult.cbLONGCount++)*cbSameCount],cbSameCardData,cbSameCount); break; } case 3: //三张 { AnalyseResult.cbThreeLogicVolue[AnalyseResult.cbThreeCount]=cbLogicValue; memcpy(&AnalyseResult.cbThreeCardData[(AnalyseResult.cbThreeCount++)*cbSameCount],cbSameCardData,cbSameCount); break; } case 4: //四张 { AnalyseResult.cbFourLogicVolue[AnalyseResult.cbFourCount]=cbLogicValue; memcpy(&AnalyseResult.cbFourCardData[(AnalyseResult.cbFourCount++)*cbSameCount],cbSameCardData,cbSameCount); break; } } //设置递增 i+=cbSameCount-1; } return; } //////////////////////////////////////////////////////////////////////////
[ "haizhou@haizhoumac.local" ]
haizhou@haizhoumac.local
860d6b083b998d789f8a7d5e15fd6a67eb0a9926
65e7c6b56ad89adf8f1d9a55f6cb411a93cff941
/7-b14mei2.cpp
95aa13f21fbb174fc6b3ec2d3039bfb49dafc89a
[]
no_license
shunf4-assignment/shenjian-cpp-assignments
bfe77d24e5648843610728cb44f7b978e689f5cb
4f9abf67b77aaadec27278d08776f8a67517957a
refs/heads/master
2021-03-30T16:48:48.453937
2017-08-17T09:31:36
2017-08-17T09:31:36
71,679,542
3
1
null
null
null
null
GB18030
C++
false
false
838
cpp
/*梅语冰 计科3班 1652311*/ #define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<fstream> #include<string.h> #include <iomanip> using namespace std; int main(int argc, char *argv[]) { int i = 0, j; char filepath[100]; char ch[16] = { 0 }; ifstream fin; if (argc == 2) { strcpy(filepath, argv[1]); } if (argc == 1) { cout << "请输入文件路径:"; cin >> filepath; } fin.open(filepath, ios::binary|ios::in); if (fin.is_open() == 0) { cout << "打开文件失败" << endl; return 0; } for (j = 0;!fin.eof(); j++) { cout <<setw(8)<<hex<< setfill('0')<<fin.tellg() << " "; for (i = 0; i < 16&&!fin.eof(); i++) { fin.read((char *)&ch[i], sizeof(ch[i])); cout << fin.gcount() << " "; if (i == 7) cout << "-"; } cout << " "; cout << ch << endl; } return 0; }
[ "shunf@顺子-LAPTOP" ]
shunf@顺子-LAPTOP
1fa68a8a68b2ebb41a8b4d29a6ecbf2fda221387
db8be521b8e2eab424f594a50886275d68dd5a1b
/Competitive Programming/codechef/OCT13/KMHAMHA.cpp
d822e2af27ce05102f7ed25f7f95dbce5a2ae505
[]
no_license
purnimamehta/Articles-n-Algorithms
7f2aa8046c8eef0e510689771a493f84707e9297
aaea50bf1627585b935f8e43465360866b3b4eac
refs/heads/master
2021-01-11T01:01:53.382696
2017-01-15T04:12:44
2017-01-15T04:12:44
70,463,305
10
4
null
null
null
null
UTF-8
C++
false
false
1,411
cpp
#include<iostream> #include<list> #include<map> #include<vector> #include<climits> #include<algorithm> using namespace std; pair<int,int> getmaxvalue(const map<int,pair<int,list<int> > > &MAP) { int MAX=INT_MIN; int maxpos=-1; for(auto i=MAP.begin();i!=MAP.end();i++) { MAX=max(MAX,(i->second).first); maxpos=i->first; } return make_pair(MAX,maxpos); } void erase_element(map<int,pair<int,list<int> > > &MAP,int element) { for(auto i=MAP.begin();i!=MAP.end();i++) { for(auto j=(i->second).second.begin();j!=(i->second).second.begin();j++) { if((*j)==element) { *j=-1; (i->second).first--; } } } } int main() { int t; cin>>t; while(t--) { int n; cin>>n; map<int,pair<int,list<int> > > row; map<int,pair<int,list<int> > > column; for(int i=0;i<n;i++) { int x,y; cin>>x>>y; row[x].first++; row[x].second.push_back(y); column[y].first++; column[y].second.push_back(x); } int count=0; while(n>0) { pair<int,int> maxrow=getmaxvalue(row); pair<int,int> maxcolumn=getmaxvalue(column); if(maxrow.first>maxcolumn.first) { n-=row[maxrow.second].first; row.erase(maxrow.second); erase_element(column,maxrow.second); } else { n-=column[maxcolumn.second].first; column.erase(maxcolumn.second); erase_element(row,maxcolumn.second); } count++; } cout<<count<<endl; } }
[ "me@lefeeza.com" ]
me@lefeeza.com
8df3141b1c15cb8341c63a33480d31b433d4973e
73020030a511bbbbaf537c9f0049ed9ec58f13dd
/WednesdayPattern8/src/WednesdayPattern8.cpp
0dac81fc663af7d11b23b677c6bcefaa9a8397ce
[]
no_license
Sagar-Pro3/c_c-master
1275f6088f881fd7b97d5b325c51ded8ec1c9e0a
874b172792547b91e2668c71948158e5fc05034b
refs/heads/main
2023-03-09T15:45:06.148084
2021-02-27T04:08:53
2021-02-27T04:08:53
335,394,298
0
0
null
null
null
null
UTF-8
C++
false
false
809
cpp
//============================================================================ // Name : WednesdayPattern8.cpp // Author : // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ //4444444 // 33333 // 222 // 1 #include <iostream> using namespace std; class name { public: int line = 4; int numcount = 7; int space = 0; int num = 4; void fun() { for (int i = 1; i <= line; i++) { for (int j = 1; j <= space; j++) { cout << " "; } for (int k = 1; k <= numcount; k++) { cout << num; } cout << endl; space++; num--; numcount-=2; } } private: }; int main() { name n1; n1.fun(); cout << "" << endl; // prints return 0; }
[ "noreply@github.com" ]
noreply@github.com
00973c74899847dc860eb78eb97d1c413325c06e
ba40f7d4dad32547e519ef5e3c3ee1e46a5fd9d7
/SGA API Project tengai/SGA API presentation 1/SGA API presentation 1/RectManeger.h
b886124862b1cea957a0a4b8eeedb4d1080b02d2
[]
no_license
WISDOMEYES/TENGAI
de8c883279763b9e30b8f14ed3ad99f99bd08225
37e4a9aaf8981567e4c166bbc7917b7598226573
refs/heads/master
2020-03-28T20:10:43.376414
2018-09-17T00:21:17
2018-09-17T00:21:17
149,046,844
1
0
null
null
null
null
UTF-8
C++
false
false
117
h
#pragma once #include"singletonBase.h" class RectManeger { private: public: RectManeger(); ~RectManeger(); };
[ "wngus3508@naver.com" ]
wngus3508@naver.com
5908c18147ec511755348f2c1b5a263f7ad16955
755efc0b1f844e8f237e9395ec1e2b9ae66da635
/software/BeagleBone/beaglebone/source/device/I2CDevice.cpp
61222f74dd1c894856fa36bf85026f1c590d1666
[ "MIT" ]
permissive
jusseb/artemis
1be7b1e74ddf6aef1d8d5883386854bd193c23a3
30513fd2602c580156f1469ea797c891d0e38f3c
refs/heads/master
2023-04-03T02:51:08.525310
2021-03-19T23:11:21
2021-03-19T23:11:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,381
cpp
#include "device/I2CDevice.h" #include <iostream> #include <sstream> #include <fcntl.h> #include <stdio.h> #include <iomanip> #include <unistd.h> #include <sys/ioctl.h> #include <linux/i2c.h> #include <linux/i2c-dev.h> #define BBB_I2C_0 "/dev/i2c-0" #define BBB_I2C_1 "/dev/i2c-1" #define BBB_I2C_2 "/dev/i2c-2" using namespace std; using namespace cubesat; #define HEX(x) setw(2) << setfill('0') << hex << (int)(x) I2CDevice::I2CDevice() { file = -1; bus = -1; device = -1; is_open = false; } /** * Constructor for the I2CDevice class. It requires the bus number and device number. The constructor * opens a file handle to the I2C device, which is destroyed when the destructor is called * @param bus The bus number. Usually 0 or 1 on the BBB * @param device The device ID on the bus. */ I2CDevice::I2CDevice(uint8_t bus, uint8_t device) : bus(bus), device(device), file(-1), is_open(false) { } std::string I2CDevice::GetDevicePath() const { switch ( bus ) { case 0: return BBB_I2C_0; break; case 1: return BBB_I2C_1; break; case 2: return BBB_I2C_2; break; default: return ""; } } /** * Open a connection to an I2C device * @return -1 on failure to open to the bus or device, 0 on success. */ int I2CDevice::Open() { if ( IsOpen() ) return -1; string name = GetDevicePath(); if ( name.empty() ) return -1; file = open(name.c_str(), O_RDWR); if ( file < 0 ) { perror("Failed to open I2C bus\n"); file = -1; return -1; } if ( ioctl(file, I2C_SLAVE, device) != 0 ) { perror("Failed to connect to I2C device\n"); close(file); return -1; } // Try writing to the device to see if it is actually available unsigned char buffer[3]; buffer[0] = 0x00; buffer[1] = 0; buffer[2] = 0; if ( write(file, buffer, 3) != 3 ) { close(file); return -1; } is_open = true; return 0; } /** * Write a single byte value to a single register. * @param registerAddress The register address * @param value The value to be written to the register * @return -1 on failure to write, 0 on success. */ int I2CDevice::WriteRegister(uint8_t registerAddress, uint16_t value){ if ( !IsOpen() ) return -1; unsigned char buffer[3]; buffer[0] = registerAddress; buffer[1] = value >> 8; buffer[2] = value & 0x00FF; if ( write(file, buffer, 3) != 3 ) { perror("Failed write to the I2C device\n"); return -1; } return 0; } /** * Write a single value to the I2C device. Used to set up the device to read from a * particular address. * @param value the value to write to the device * @return -1 on failure to write, 0 on success. */ int I2CDevice::Write(uint8_t value){ if ( !IsOpen() ) return -1; unsigned char buffer[1] = {value}; if ( write(file, buffer, 1) != 1 ) { perror("Failed write to the I2C device\n"); return -1; } return 0; } /** * Read a single register value from the address on the device. * @param registerAddress the address to read from * @return the byte value at the register address. */ uint16_t I2CDevice::ReadRegister(uint8_t registerAddress) { if ( !IsOpen() ) return -1; Write(registerAddress); uint8_t buffer[2]; if ( read(this->file, buffer, 2) != 2 ) { perror("Failed to read from I2C device\n"); return -1; } return buffer[0] | (buffer[1] << 8); } /** * Method to read a number of registers from a single device. This is much more efficient than * reading the registers individually. The from address is the starting address to read from, which * defaults to 0x00. * @param number the number of registers to read from the device * @param fromAddress the starting address to read from * @return a pointer of type unsigned char* that points to the first element in the block of registers */ int I2CDevice::ReadRegisters(uint8_t *out, uint8_t first_addr, uint8_t len) { if ( !IsOpen() ) return -1; this->Write(first_addr); int bytes_read; if ( (bytes_read = read(this->file, out, len)) != (int)len ) { perror("Failed to read in full buffer from I2C device\n"); return 0; } return bytes_read; } /** * Close the file handles and sets a temporary state to -1. */ void I2CDevice::Close(){ if ( IsOpen() ) { close(file); file = -1; } } /** * Closes the file on destruction, provided that it has not already been closed. */ I2CDevice::~I2CDevice() { Close(); }
[ "mtmk@hawaii.edu" ]
mtmk@hawaii.edu
bea01b7feb293d959920e9e3ee211c7e0bddea9d
f7fba49bd63a926531b81c40f1a7ae5caf6bdd1a
/rct_optimizations/test/src/observation_creator.cpp
00a20a60593aab8bb5f0981c1ca6aa0fb6481d7d
[]
no_license
jworch/robot_cal_tools
85cea6a7705c8d29e1fd38173e27e9862edf2cbd
2dfc8646e4bfa75af59dcdc2dd9e996342bf6cba
refs/heads/master
2020-12-12T07:28:02.094933
2020-01-29T15:01:45
2020-01-29T15:01:45
234,077,811
1
0
null
2020-01-29T15:01:46
2020-01-15T12:39:21
C++
UTF-8
C++
false
false
1,878
cpp
#include "rct_optimizations_tests/observation_creator.h" #include "rct_optimizations/ceres_math_utilities.h" static bool projectAndTest(const Eigen::Vector3d& pt_in_camera, const rct_optimizations::test::Camera& camera, Eigen::Vector2d& pt_in_image) { rct_optimizations::projectPoint(camera.intr, pt_in_camera.data(), pt_in_image.data()); if (pt_in_image(0) < 0 || pt_in_image(0) > camera.width || pt_in_image(1) < 0 || pt_in_image(1) > camera.height) { return false; } else return true; } bool rct_optimizations::test::project(const Eigen::Affine3d& camera_pose, const Eigen::Affine3d& target_pose, const test::Camera& camera, const test::Target& target, std::vector<Eigen::Vector2d>& out_observations) { Eigen::Affine3d to_camera = camera_pose.inverse() * target_pose; std::vector<Eigen::Vector2d> obs; // Loop over points for (const auto& point : target.points) { Eigen::Vector3d pt_in_camera = to_camera * point; if (pt_in_camera.z() < 0.0) // behind the camera { return false; } Eigen::Vector2d in_image; if (!projectAndTest(pt_in_camera, camera, in_image)) // If this fails, the point is outside image { return false; } // Point is good obs.push_back(in_image); } out_observations = obs; return true; } Eigen::Affine3d rct_optimizations::test::lookat(const Eigen::Vector3d& origin, const Eigen::Vector3d& eye, const Eigen::Vector3d& up) { Eigen::Vector3d z = (eye - origin).normalized(); Eigen::Vector3d x = z.cross(up).normalized(); Eigen::Vector3d y = z.cross(x).normalized(); auto p = Eigen::Affine3d::Identity(); p.translation() = origin; p.matrix().col(0).head<3>() = x; p.matrix().col(1).head<3>() = y; p.matrix().col(2).head<3>() = z; return p; }
[ "Jmeyer1292@gmail.com" ]
Jmeyer1292@gmail.com
5a52190fec0b526c0faf8f26a2fdf5d8bd3448b0
f9f7b95d4e4d7bae7a7357e5dcc692ef08304886
/src/gssexception.cpp
db19643038fed57f2e77078aa0e884a7aa48412f
[ "Apache-2.0" ]
permissive
hamstergene/gsspp
ff3f18034019a54341a5a91a07851e253c275116
933f41b0939cd6d32c5bcde20c764050c353af72
refs/heads/master
2021-01-25T10:49:46.502047
2018-01-24T15:15:36
2018-01-24T15:15:36
93,878,668
0
0
null
2017-06-09T16:44:17
2017-06-09T16:44:17
null
UTF-8
C++
false
false
1,343
cpp
#include "gsspp/gssexception.h" #include "gsspp/gssbuffer.h" #include <cstring> void display_helper( OM_uint32 code, int type, char * message, int len ); GSSException::GSSException( OM_uint32 maj_stat, OM_uint32 min_stat, const char * func ) throw() : major_status( maj_stat ), minor_status( min_stat ) { strncpy( function, func, sizeof( function ) - 1 ); function[sizeof( function ) - 1] = 0; try { display_helper( maj_stat, GSS_C_GSS_CODE, major_message, sizeof( major_message ) ); display_helper( min_stat, GSS_C_MECH_CODE, minor_message, sizeof( minor_message ) ); } catch ( GSSException& e ) { strcpy( major_message, e.major_message ); strcpy( minor_message, e.minor_message ); strcpy( function, e.function ); } } const char * GSSException::what() const throw() { if ( minor_status ) return minor_message; return major_message; } void display_helper( OM_uint32 code, int type, char * message, int len ) { OM_uint32 maj, min; OM_uint32 msg_ctx = 0; int pos = 0; do { GSSBuffer buff; maj = gss_display_status( &min, code, type, GSS_C_NO_OID, &msg_ctx, buff ); if ( maj != GSS_S_COMPLETE ) throw GSSException( maj, min, "gss_display_status" ); strncpy( message + pos, buff.bytes(), len - pos - 1 ); pos += buff.size(); } while ( msg_ctx && pos < len ); message[len - 1] = 0; }
[ "bschlenk@Brians-MacBook-Pro.local" ]
bschlenk@Brians-MacBook-Pro.local
b033c4fae828bbed088b925c7da5bd6a2e562bc5
df1b9041ba4cad34e2d13a05a508514f76e4f2ad
/Leetcode/15_3sum.cpp
a036a413de99bc43d4403151825bfd36b71dfb6b
[]
no_license
parthkris13/Interview-Bit
56a0e3b1ed2f74b0fe886c5c98e029bb4dc6bfa5
fc9dcc7708f8e91205383f25aa7f777cbab6006f
refs/heads/master
2023-06-20T12:52:09.207817
2021-07-25T18:32:28
2021-07-25T18:32:28
387,144,131
0
0
null
null
null
null
UTF-8
C++
false
false
1,076
cpp
class Solution { public: vector<vector<int>> threeSum(vector<int> &nums) { sort(begin(nums), end(nums)); vector<vector<int>> result; for (int i = size(nums) - 1; i >= 2; --i) { if (i + 1 < size(nums) && nums[i] == nums[i + 1]) { continue; } const auto& target = -nums[i]; int left = 0, right = i - 1; while (left < right) { if (nums[left] + nums[right] < target) { ++left; } else if (nums[left] + nums[right] > target) { --right; } else { result.push_back({nums[left], nums[right], nums[i]}); ++left; --right; while (left < right && nums[left] == nums[left - 1]) { ++left; } while (left < right && nums[right] == nums[right + 1]) { --right; } } } } return result; } };
[ "parthkrishna99@gmail.com" ]
parthkrishna99@gmail.com
4f2f76593e697fccd5f552e3075b8728f8bcfc97
f06a4993f86f3a5f1975ad0630e73284d241aed8
/source/48_RotateImage.cpp
d676711e839fc49410e2a17f93a88b3dcdae4115
[]
no_license
praveensonare/Leetcode
c3eb9b3f3ad903ae61537fa39393bc8748699e4f
84257364c641fbb8fbd8d04fa40dd05cb3ff8689
refs/heads/master
2023-07-17T05:25:55.586206
2021-08-30T06:04:26
2021-08-30T06:04:26
308,696,742
0
0
null
null
null
null
UTF-8
C++
false
false
1,764
cpp
#include "Utility.h" // 48. Rotate Image // Level - Medium // // You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). // You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation. // // Example 1: // Input: matrix = {{1,2,3},{4,5,6},{7,8,9}} // Output: {{7,4,1},{8,5,2},{9,6,3}} // // Example 2: // Input: matrix = {{5,1,9,11},{2,4,8,10},{13,3,6,7},{15,14,12,16}} // Output: {{15,13,2,5},{14,3,4,1},{12,6,8,9},{16,7,10,11}} // // Example 3: // Input: matrix = {{1}} // Output: {{1}} // // Example 4: // Input: matrix = {{1,2},{3,4}} // Output: {{3,1},{4,2}} // // Constraints: // matrix.length == n // matrix[i].length == n // 1 <= n <= 20 // -1000 <= matrix[i][j] <= 1000 void rotate(vector<vector<int>>& matrix) { int len = matrix.size() - 1; int temp; for (int y = 0; y <= len/2; ++y) { for (int x = y; x < len - y; ++x) { temp = matrix[y][x]; matrix[y][x] = matrix[len - x][y]; matrix[len - x][y] = matrix[len - y][len - x]; matrix[len - y][len - x] = matrix[x][len - y]; matrix[x][len - y] = temp; } } } void test_rotate() { vector<VVI> tc = {{{1,2,3},{4,5,6},{7,8,9}}, {{5,1,9,11},{2,4,8,10},{13,3,6,7},{15,14,12,16}}, {{1}}, {{1,2},{3,4}}}; vector<VVI> answers = {{{7,4,1},{8,5,2},{9,6,3}}, {{15,13,2,5},{14,3,4,1},{12,6,8,9},{16,7,10,11}}, {{1}}, {{3,1},{4,2}}}; for (unsigned i = 0; i < tc.size(); ++i) { rotate(tc[i]); if (tc[i] != answers[i]) ERROR_LOG; } }
[ "praveens@blackmagicdesign.com" ]
praveens@blackmagicdesign.com
c639154bb6ca494585765e495c29e903e49ed03e
1e101a641884a7ba3928b82cca62530c78617d38
/kissBear/Classes/HelloWorldScene.cpp
324dabe41ca03741af085f0f5059da04703bedc6
[]
no_license
Crasader/cocos2d-x-1
43c34367ae6ad3e76067ce085d717e9ba8347908
784636bfb6dce285e927bd8242f8008de4d3f2fb
refs/heads/master
2020-11-29T04:20:46.587639
2016-07-15T09:09:18
2016-07-15T09:09:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,704
cpp
#include "HelloWorldScene.h" #include <iostream> USING_NS_CC; Scene* HelloWorld::createScene() { // 'scene' is an autorelease object auto scene = Scene::create(); // 'layer' is an autorelease object auto layer = HelloWorld::create(); // add layer as a child to scene scene->addChild(layer); // return the scene return scene; } // on "init" you need to initialize your instance bool HelloWorld::init() { ////////////////////////////// // 1. super init first if ( !Layer::init() ) { return false; } Size visibleSize = Director::getInstance()->getVisibleSize(); Point origin = Director::getInstance()->getVisibleOrigin(); auto bg=Sprite::create("bg1.png"); bg->setPosition(visibleSize.width/2,visibleSize.height/2); addChild(bg); auto wc1=Sprite::create("wc.png"); wc1->setPosition(100,200); wc1->setTag(1); addChild(wc1); auto wc2=Sprite::create("wc.png"); wc2->setPosition(300,200); wc2->setTag(2); addChild(wc2); auto wc3=Sprite::create("wc.png"); wc3->setPosition(500,200); wc3->setTag(3); addChild(wc3); auto wc4=Sprite::create("wc.png"); wc4->setPosition(100,400); wc4->setTag(4); addChild(wc4); auto wc5=Sprite::create("wc.png"); wc5->setPosition(300,400); wc5->setTag(5); addChild(wc5); auto wc6=Sprite::create("wc.png"); wc6->setPosition(500,400); wc6->setTag(6); addChild(wc6); auto wc7=Sprite::create("wc.png"); wc7->setPosition(100,600); wc7->setTag(7); addChild(wc7); auto wc8=Sprite::create("wc.png"); wc8->setPosition(300,600); wc8->setTag(8); addChild(wc8); auto wc9=Sprite::create("wc.png"); wc9->setPosition(500,600); wc9->setTag(9); addChild(wc9); this->schedule(schedule_selector(HelloWorld::bearShow), interval); bear=Sprite::create("b.png"); bear->setPosition(-100,100); addChild(bear); wo=Sprite::create("wo.png"); wo->setPosition(-100,100); this->addChild(wo); kiss=Sprite::create("m.png"); kiss->setVisible(false); addChild(kiss); auto scoreString=__String::createWithFormat("%d", score); auto scoreLabel=Label::createWithTTF(scoreString->getCString(), "Marker Felt.ttf", 50); scoreLabel->setPosition(300,820); scoreLabel->setTag(101); this->addChild(scoreLabel); //TOUCH listener=EventListenerTouchOneByOne::create(); listener->onTouchBegan=[this](Touch *touch,Event *event) { auto touchPoint=touch->getLocation(); auto bearSize=bear->getContentSize(); auto touchPointInBear=bear->convertToNodeSpace(touchPoint); auto rect=Rect(0, 0, bearSize.width, bearSize.height); if (rect.containsPoint(touchPointInBear)) { j[n-1]=99; kiss->setVisible(true); kiss->setPosition(bear->getPosition()); kiss->setRotation(20); bear->setVisible(false); bear->removeFromParent(); wo->setVisible(false); wo->removeFromParent(); score=score+1; log("touched,score =%d,level=%d",score,level); switch (score){ case 10: interval=1.5; this->unscheduleAllSelectors(); this->schedule(schedule_selector(HelloWorld::bearShow), interval); break; case 15: interval=1; this->unscheduleAllSelectors(); this->schedule(schedule_selector(HelloWorld::bearShow), interval); break; case 20: interval=1; this->unscheduleAllSelectors(); this->schedule(schedule_selector(HelloWorld::bearShow), interval); break; case 25: interval=0.6; this->unscheduleAllSelectors(); this->schedule(schedule_selector(HelloWorld::bearShow), interval); break; case 30: interval=0.7; this->unscheduleAllSelectors(); this->schedule(schedule_selector(HelloWorld::bearShow), interval); break; case 35: interval=1; this->unscheduleAllSelectors(); this->schedule(schedule_selector(HelloWorld::bearShow), interval); break; case 40: interval=0.5; this->unscheduleAllSelectors(); this->schedule(schedule_selector(HelloWorld::bearShow), interval); break; case 50: interval=0.3; this->unscheduleAllSelectors(); this->schedule(schedule_selector(HelloWorld::bearShow), interval); break; } if (this->getChildByTag(101)==nullptr) { log("non"); } this->removeChildByTag(101); auto scoreString=__String::createWithFormat("%d", score); auto scoreLabel=Label::createWithTTF(scoreString->getCString(), "Marker Felt.ttf", 50); scoreLabel->setPosition(300,820); scoreLabel->setTag(101); this->addChild(scoreLabel); } return false; }; Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, this); return true; } void HelloWorld::setBearPosition() { Size visibleSize = Director::getInstance()->getVisibleSize(); i=CCRANDOM_0_1()*9; for (int a=0; a<n; a++) { while(j[a]==i) { i=CCRANDOM_0_1()*9; a=0; } } j[n]=i; log("%d",i); n=n+1; wo=Sprite::create("wo.png"); wo->setPosition(bearP[i]); this->addChild(wo); bear=Sprite::create("b.png"); bear->setVisible(true); bear->setPosition(bearP[i]); this->addChild(bear); //如果出现x个bear,则判定结束 if (this->getChildrenCount()>30) { this->pause(); auto nodes=this->getChildren(); for (const auto &node :nodes) { node->pause(); } auto scoreStringVoer=__String::createWithFormat(" Game Over! Score is %d", score); auto scoreLabelVoer=Label::createWithTTF(scoreStringVoer->getCString(), "Marker Felt.ttf", 50); scoreLabelVoer->setColor(Color3B::RED); scoreLabelVoer->setPosition(visibleSize.width/2,visibleSize.height/1.8); addChild(scoreLabelVoer); auto restartBtn=MenuItemFont::create("Restart", CC_CALLBACK_0(HelloWorld::restartGame, this )); restartBtn->setColor(Color3B::RED); auto mu=Menu::create(restartBtn, NULL); mu->setPosition(visibleSize.width/2,visibleSize.height/3); addChild(mu); } } void HelloWorld::bearShow(float dt) { kiss->setVisible(false); this->setBearPosition();} void HelloWorld::restartGame() { this->removeAllChildren(); Director::getInstance()->getEventDispatcher()->removeEventListener(listener); Director::getInstance()->popScene(); }
[ "zwjioro@163.com" ]
zwjioro@163.com
ae69b4857449c49fa1002d701d993de87664f230
55bb84592fbbb48f321a56a118d507dc2241fea2
/Starting_Out/ch4/09_changeForDollarGame.cpp
144a9d3a6af0bf07a11267b794acd7a865b16cc0
[]
no_license
tdiliberto19/cpp-practice
8f801fedf5bf6fba56dc8120c6c2b36d2bc0ce0b
f5068e4fb7abb70219564024cb36041fc45370e1
refs/heads/master
2020-11-24T04:36:07.731061
2020-05-27T22:11:57
2020-05-27T22:11:57
227,964,906
0
0
null
null
null
null
UTF-8
C++
false
false
692
cpp
#include <iostream> using namespace std; int main() { const double PENNY = 0.01, NICKEL = 0.05, DIME = 0.1, QUARTER = 0.25; int pennies, nickels, dimes, quarters, total; cout << "Please enter the following quantities: \n"; cout << "Pennies: "; cin >> pennies; cout << "Nickels: "; cin >> nickels; cout << "Dimes: "; cin >> dimes; cout << "Quarters: "; cin >> quarters; total = (pennies * PENNY) + (nickels * NICKEL) + (dimes * DIME) + (quarters * QUARTER); if (total == 1) cout << "Congratulations, you won by making a dollar!\n"; else cout << "Sorry, you didn't win (hint: its just a dollar!)\n"; return 0; }
[ "tdiliberto19@berkeley.edu" ]
tdiliberto19@berkeley.edu
5eadf4de2d362a9506a6b7c847eb95e16483f9ae
dbd759663b6f5d90da258aaeab5998c131d054a4
/project-euler/problem_49.cpp
2303e7e1bff38eba8005020bae99f1e0fa57ca06
[ "Apache-2.0" ]
permissive
sihrc/Personal-Code-Bin
9c0005993dfbd371f51e86ab525b3d4a9ac7a218
91a894a68606151d2381cf8f25709b997df00011
refs/heads/master
2020-02-26T15:13:33.960604
2014-04-28T16:02:28
2014-04-28T16:02:28
13,988,578
0
1
null
null
null
null
UTF-8
C++
false
false
499
cpp
/* Prime permutations Problem 49 The arithmetic sequence, 1487, 4817, 8147, in which each of the terms increases by 3330, is unusual in two ways: (i) each of the three terms are prime, and, (ii) each of the 4-digit numbers are permutations of one another. There are no arithmetic sequences made up of three 1-, 2-, or 3-digit primes, exhibiting this property, but there is one other 4-digit increasing sequence. What 12-digit number do you form by concatenating the three terms in this sequence? */
[ "sihrc.c.lee@gmail.com" ]
sihrc.c.lee@gmail.com
655fb10c70038e6f0a31bcf96ecba36842e14f36
a59cf55eede41357f37efc784d823002345fe9b4
/bundle3/inputgen.cpp
606cb0b6f8f3f0dcfbc4d1e04120c02e0e2fd7e8
[]
no_license
abhiskaushik/C-plus-plus-programs
271b3d45f1b915e34403d50d485784e108f9236e
96739d3e1bb651e7bdf779da7223d2146dce342e
refs/heads/master
2020-04-10T00:30:39.661808
2015-09-10T08:09:00
2015-09-10T08:09:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
445
cpp
#include<bits/stdc++.h> using namespace std; int main(int argc, char const *argv[]) { srand(time(NULL)); long long vll=1000; ofstream file; file.open("input.txt"); int notc=rand()%10 +1; //int notc=5; cout<<notc<<endl; file<<notc<<endl; while(notc--){ int n=rand()%vll +1; int m=rand()%(2*vll) +1; file<<n<<" "<<m<<endl; } file.close(); return 0; }
[ "stndlkr200@gmail.com" ]
stndlkr200@gmail.com
7ae99dc0d6a7f01ba4a72dd443364df07cdae5e5
3cf9e141cc8fee9d490224741297d3eca3f5feff
/C++ Benchmark Programs/Benchmark Files 1/classtester/autogen-sources/source-17635.cpp
6b2ab5dbd5bcd8fa5538ee1e2042be5084954ca7
[]
no_license
TeamVault/tauCFI
e0ac60b8106fc1bb9874adc515fc01672b775123
e677d8cc7acd0b1dd0ac0212ff8362fcd4178c10
refs/heads/master
2023-05-30T20:57:13.450360
2021-06-14T09:10:24
2021-06-14T09:10:24
154,563,655
0
1
null
null
null
null
UTF-8
C++
false
false
3,192
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 : virtual c0 { bool active1; c1() : active1(true) {} virtual ~c1() { tester1(this); c0 *p0_0 = (c0*)(c1*)(this); tester0(p0_0); active1 = false; } virtual void f1(){} }; void __attribute__ ((noinline)) tester1(c1* p) { p->f1(); if (p->active0) p->f0(); } struct c2; void __attribute__ ((noinline)) tester2(c2* p); struct c2 : c1 { bool active2; c2() : active2(true) {} virtual ~c2() { tester2(this); c0 *p0_0 = (c0*)(c1*)(c2*)(this); tester0(p0_0); c1 *p1_0 = (c1*)(c2*)(this); tester1(p1_0); active2 = false; } virtual void f2(){} }; void __attribute__ ((noinline)) tester2(c2* p) { p->f2(); if (p->active1) p->f1(); if (p->active0) p->f0(); } struct c3; void __attribute__ ((noinline)) tester3(c3* p); struct c3 : virtual c0, virtual c1 { bool active3; c3() : active3(true) {} virtual ~c3() { tester3(this); c0 *p0_0 = (c0*)(c3*)(this); tester0(p0_0); c0 *p0_1 = (c0*)(c1*)(c3*)(this); tester0(p0_1); c1 *p1_0 = (c1*)(c3*)(this); tester1(p1_0); active3 = false; } virtual void f3(){} }; void __attribute__ ((noinline)) tester3(c3* p) { p->f3(); if (p->active0) p->f0(); if (p->active1) p->f1(); } struct c4; void __attribute__ ((noinline)) tester4(c4* p); struct c4 : virtual c3, virtual c0, virtual c1 { bool active4; c4() : active4(true) {} virtual ~c4() { tester4(this); c0 *p0_0 = (c0*)(c3*)(c4*)(this); tester0(p0_0); c0 *p0_1 = (c0*)(c1*)(c3*)(c4*)(this); tester0(p0_1); c0 *p0_2 = (c0*)(c4*)(this); tester0(p0_2); c0 *p0_3 = (c0*)(c1*)(c4*)(this); tester0(p0_3); c1 *p1_0 = (c1*)(c3*)(c4*)(this); tester1(p1_0); c1 *p1_1 = (c1*)(c4*)(this); tester1(p1_1); c3 *p3_0 = (c3*)(c4*)(this); tester3(p3_0); active4 = false; } virtual void f4(){} }; void __attribute__ ((noinline)) tester4(c4* p) { p->f4(); if (p->active0) p->f0(); if (p->active1) p->f1(); if (p->active3) p->f3(); } int __attribute__ ((noinline)) inc(int v) {return ++v;} int main() { c0* ptrs0[25]; ptrs0[0] = (c0*)(new c0()); ptrs0[1] = (c0*)(c1*)(new c1()); ptrs0[2] = (c0*)(c1*)(c2*)(new c2()); ptrs0[3] = (c0*)(c3*)(new c3()); ptrs0[4] = (c0*)(c1*)(c3*)(new c3()); ptrs0[5] = (c0*)(c3*)(c4*)(new c4()); ptrs0[6] = (c0*)(c1*)(c3*)(c4*)(new c4()); ptrs0[7] = (c0*)(c4*)(new c4()); ptrs0[8] = (c0*)(c1*)(c4*)(new c4()); for (int i=0;i<9;i=inc(i)) { tester0(ptrs0[i]); delete ptrs0[i]; } c1* ptrs1[25]; ptrs1[0] = (c1*)(new c1()); ptrs1[1] = (c1*)(c2*)(new c2()); ptrs1[2] = (c1*)(c3*)(new c3()); ptrs1[3] = (c1*)(c3*)(c4*)(new c4()); ptrs1[4] = (c1*)(c4*)(new c4()); for (int i=0;i<5;i=inc(i)) { tester1(ptrs1[i]); delete ptrs1[i]; } c2* ptrs2[25]; ptrs2[0] = (c2*)(new c2()); for (int i=0;i<1;i=inc(i)) { tester2(ptrs2[i]); delete ptrs2[i]; } c3* ptrs3[25]; ptrs3[0] = (c3*)(new c3()); ptrs3[1] = (c3*)(c4*)(new c4()); for (int i=0;i<2;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
38d6275e4c92e7435f43aac60d7f04cd99f9f5bb
0494c9caa519b27f3ed6390046fde03a313d2868
/src/cc/trees/layer_tree_settings.h
d3a71cf8ed76dc082ce0914edaa55877d5ba9e55
[ "BSD-3-Clause" ]
permissive
mhcchang/chromium30
9e9649bec6fb19fe0dc2c8b94c27c9d1fa69da2c
516718f9b7b95c4280257b2d319638d4728a90e1
refs/heads/master
2023-03-17T00:33:40.437560
2017-08-01T01:13:12
2017-08-01T01:13:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,284
h
// Copyright 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CC_TREES_LAYER_TREE_SETTINGS_H_ #define CC_TREES_LAYER_TREE_SETTINGS_H_ #include <string> #include "base/basictypes.h" #include "cc/base/cc_export.h" #include "cc/debug/layer_tree_debug_state.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/gfx/size.h" namespace cc { class CC_EXPORT LayerTreeSettings { public: LayerTreeSettings(); ~LayerTreeSettings(); bool impl_side_painting; bool allow_antialiasing; bool throttle_frame_production; bool begin_frame_scheduling_enabled; bool using_synchronous_renderer_compositor; bool per_tile_painting_enabled; bool partial_swap_enabled; bool cache_render_pass_contents; bool accelerated_animation_enabled; bool background_color_instead_of_checkerboard; bool show_overdraw_in_tracing; bool can_use_lcd_text; bool should_clear_root_render_pass; bool use_linear_fade_scrollbar_animator; int scrollbar_linear_fade_delay_ms; int scrollbar_linear_fade_length_ms; bool solid_color_scrollbars; SkColor solid_color_scrollbar_color; int solid_color_scrollbar_thickness_dip; bool calculate_top_controls_position; bool use_memory_management; bool timeout_and_draw_when_animation_checkerboards; bool layer_transforms_should_scale_layer_contents; float minimum_contents_scale; float low_res_contents_scale_factor; float top_controls_height; float top_controls_show_threshold; float top_controls_hide_threshold; double refresh_rate; size_t max_partial_texture_updates; size_t num_raster_threads; gfx::Size default_tile_size; gfx::Size max_untiled_layer_size; gfx::Size minimum_occlusion_tracking_size; bool use_pinch_zoom_scrollbars; bool use_pinch_virtual_viewport; size_t max_tiles_for_interest_area; size_t max_unused_resource_memory_percentage; int highp_threshold_min; bool force_direct_layer_drawing; // With Skia GPU backend. bool strict_layer_property_change_checking; bool use_map_image; std::string compositor_name; bool ignore_root_layer_flings; LayerTreeDebugState initial_debug_state; }; } // namespace cc #endif // CC_TREES_LAYER_TREE_SETTINGS_H_
[ "1990zhaoshuang@163.com" ]
1990zhaoshuang@163.com
410e1fb9f37cdd41381045970b3d420f6dd6e7e6
191707dd19837f7abd6f4255cd42b78d3ca741c5
/X11R6/contrib/programs/ixx/list.h
3e8db77baf7e5605bbfa448757440ecb0085750d
[]
no_license
yoya/x.org
4709089f97b1b48f7de2cfbeff1881c59ea1d28e
fb9e6d4bd0c880cfc674d4697322331fe39864d9
refs/heads/master
2023-08-08T02:00:51.277615
2023-07-25T14:05:05
2023-07-25T14:05:05
163,954,490
2
0
null
null
null
null
UTF-8
C++
false
false
8,780
h
/* $XConsortium: list.h,v 1.3 94/06/03 21:41:04 matt Exp $ */ /* * Copyright (c) 1987, 1988, 1989, 1990, 1991 Stanford University * Copyright (c) 1991 Silicon Graphics, Inc. * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the names of * Stanford and Silicon Graphics may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Stanford and Silicon Graphics. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL STANFORD OR SILICON GRAPHICS BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ /* * Generic list implemented as dynamic array */ #ifndef list_h #define list_h #include "types.h" extern void ListImpl_range_error(long index); extern long ListImpl_best_new_count(long count, unsigned size); #if !defined(UNIXCPP) #define __ListItr(List) List##_Iterator #define ListItr(List) __ListItr(List) #define __ListUpdater(List) List##_Updater #define ListUpdater(List) __ListUpdater(List) #else #define __ListItr(List) List/**/_Iterator #define ListItr(List) __ListItr(List) #define __ListUpdater(List) List/**/_Updater #define ListUpdater(List) __ListUpdater(List) #endif #define declareList(List,T) \ class List { \ public: \ List(long size = 0); \ ~List(); \ \ long count() const; \ T item(long index) const; \ T& item_ref(long index) const; \ \ void prepend(const T&); \ void append(const T&); \ void insert(long index, const T&); \ void remove(long index); \ void remove_all(); \ private: \ T* items_; \ long size_; \ long count_; \ long free_; \ }; \ \ inline long List::count() const { return count_; } \ \ inline T List::item(long index) const { \ if (index < 0 || index >= count_) { \ ListImpl_range_error(index); \ } \ long i = index < free_ ? index : index + size_ - count_; \ return items_[i]; \ } \ inline T& List::item_ref(long index) const { \ if (index < 0 || index >= count_) { \ ListImpl_range_error(index); \ } \ long i = index < free_ ? index : index + size_ - count_; \ return items_[i]; \ } \ \ inline void List::append(const T& item) { insert(count_, item); } \ inline void List::prepend(const T& item) { insert(0, item); } \ \ class ListItr(List) { \ public: \ ListItr(List)(const List&); \ \ Boolean more() const; \ T cur() const; \ T& cur_ref() const; \ void next(); \ private: \ const List* list_; \ long cur_; \ }; \ \ inline Boolean ListItr(List)::more() const { return cur_ < list_->count(); } \ inline T ListItr(List)::cur() const { return list_->item(cur_); } \ inline T& ListItr(List)::cur_ref() const { \ return list_->item_ref(cur_); \ } \ inline void ListItr(List)::next() { ++cur_; } \ \ class ListUpdater(List) { \ public: \ ListUpdater(List)(List&); \ \ Boolean more() const; \ T cur() const; \ T& cur_ref() const; \ void remove_cur(); \ void next(); \ private: \ List* list_; \ long cur_; \ }; \ \ inline Boolean ListUpdater(List)::more() const { \ return cur_ < list_->count(); \ } \ inline T ListUpdater(List)::cur() const { return list_->item(cur_); } \ inline T& ListUpdater(List)::cur_ref() const { \ return list_->item_ref(cur_); \ } \ inline void ListUpdater(List)::remove_cur() { list_->remove(cur_); } \ inline void ListUpdater(List)::next() { ++cur_; } /* * Lists of pointers * * Don't ask me to explain the AnyPtr nonsense. C++ compilers * have a hard time deciding between (const void*)& and const (void*&). * Typedefs help, though still keep me guessing. */ typedef void* __AnyPtr; declareList(__AnyPtrList,__AnyPtr) #define declarePtrList(PtrList,T) \ class PtrList { \ public: \ PtrList(long size = 0); \ \ long count() const; \ T* item(long index) const; \ \ void prepend(T*); \ void append(T*); \ void insert(long index, T*); \ void remove(long index); \ void remove_all(); \ private: \ __AnyPtrList impl_; \ }; \ \ inline PtrList::PtrList(long size) : impl_(size) { } \ inline long PtrList::count() const { return impl_.count(); } \ inline T* PtrList::item(long index) const { return (T*)impl_.item(index); } \ inline void PtrList::append(T* item) { insert(impl_.count(), item); } \ inline void PtrList::prepend(T* item) { insert(0, item); } \ inline void PtrList::remove(long index) { impl_.remove(index); } \ inline void PtrList::remove_all() { impl_.remove_all(); } \ \ class ListItr(PtrList) { \ public: \ ListItr(PtrList)(const PtrList&); \ \ Boolean more() const; \ T* cur() const; \ void next(); \ private: \ const PtrList* list_; \ long cur_; \ }; \ \ inline Boolean ListItr(PtrList)::more() const { \ return cur_ < list_->count(); \ } \ inline T* ListItr(PtrList)::cur() const { return list_->item(cur_); } \ inline void ListItr(PtrList)::next() { ++cur_; } \ \ class ListUpdater(PtrList) { \ public: \ ListUpdater(PtrList)(PtrList&); \ \ Boolean more() const; \ T* cur() const; \ void remove_cur(); \ void next(); \ private: \ PtrList* list_; \ long cur_; \ }; \ \ inline Boolean ListUpdater(PtrList)::more() const { \ return cur_ < list_->count(); \ } \ inline T* ListUpdater(PtrList)::cur() const { return list_->item(cur_); } \ inline void ListUpdater(PtrList)::remove_cur() { list_->remove(cur_); } \ inline void ListUpdater(PtrList)::next() { ++cur_; } /* * List implementation */ #define implementList(List,T) \ List::List(long size) { \ if (size > 0) { \ size_ = ListImpl_best_new_count(size, sizeof(T)); \ items_ = new T[size_]; \ } else { \ size_ = 0; \ items_ = 0; \ } \ count_ = 0; \ free_ = 0; \ } \ \ List::~List() { \ delete [] items_; \ } \ \ void List::insert(long index, const T& item) { \ if (count_ == size_) { \ long size = ListImpl_best_new_count(size_ + 1, sizeof(T)); \ T* items = new T[size]; \ if (items_ != 0) { \ register long i; \ for (i = 0; i < free_; ++i) { \ items[i] = items_[i]; \ } \ for (i = 0; i < count_ - free_; ++i) { \ items[free_ + size - count_ + i] = \ items_[free_ + size_ - count_ + i]; \ } \ delete [] items_; \ } \ items_ = items; \ size_ = size; \ } \ if (index >= 0 && index <= count_) { \ if (index < free_) { \ for (register long i = free_ - index - 1; i >= 0; --i) { \ items_[index + size_ - count_ + i] = items_[index + i]; \ } \ } else if (index > free_) { \ for (register long i = 0; i < index - free_; ++i) { \ items_[free_ + i] = items_[free_ + size_ - count_ + i]; \ } \ } \ free_ = index + 1; \ count_ += 1; \ items_[index] = item; \ } \ } \ \ void List::remove(long index) { \ if (index >= 0 && index <= count_) { \ if (index < free_) { \ for (register long i = free_ - index - 2; i >= 0; --i) { \ items_[size_ - count_ + index + 1 + i] = \ items_[index + 1 + i]; \ } \ } else if (index > free_) { \ for (register long i = 0; i < index - free_; ++i) { \ items_[free_ + i] = items_[free_ + size_ - count_ + i]; \ } \ } \ free_ = index; \ count_ -= 1; \ } \ } \ \ void List::remove_all() { \ count_ = 0; \ free_ = 0; \ } \ \ ListItr(List)::ListItr(List)(const List& list) { \ list_ = &list; \ cur_ = 0; \ } \ \ ListUpdater(List)::ListUpdater(List)(List& list) { \ list_ = &list; \ cur_ = 0; \ } #define implementPtrList(PtrList,T) \ void PtrList::insert(long index, T* item) { \ const __AnyPtr p = item; \ impl_.insert(index, p); \ } \ ListItr(PtrList)::ListItr(PtrList)(const PtrList& list) { \ list_ = &list; \ cur_ = 0; \ } \ \ ListUpdater(PtrList)::ListUpdater(PtrList)(PtrList& list) { \ list_ = &list; \ cur_ = 0; \ } #endif
[ "yoya@awm.jp" ]
yoya@awm.jp
2fcc794fb9695d262d3188a7b35cfc14e322bf60
998ef3b393a3d3070dd402cded0d88f128795caa
/ggAnalysis/ggNtuplizer/test/Skim_test/code/ControlPlot.cc
614b4446ef419f80d87d2251e1476cdd6bf20a99
[]
no_license
saswatinandan/HHTo4Tau
c430dc0185e199ce43c1f23cdef736c1dcefa710
06bdba27d986d450275b00e154ed2c3845ad2173
refs/heads/master
2021-09-10T08:33:39.481118
2018-03-22T20:27:52
2018-03-22T20:27:52
126,345,720
0
0
null
null
null
null
UTF-8
C++
false
false
34,542
cc
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Compiling the code: ./Make.sh ZTT_XSection.cc // Running the code: ./ZTT_XSection.exe OutPut.root Input.root //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include "TreeReader.h" #include "WeightCalculator.h" #include "TLorentzVector.h" #include <string> //remove space for successful compilation #include <ostream> //remove space for successful compilation #include <iostream> #include <iomanip> #include <sstream> TFile * HZZ= TFile::Open("ScaleFactors_mu_Moriond2017_v2.root"); TH2F* SF = (TH2F*) HZZ->Get("FINAL"); bool taumatch(double eta,double phi, std::vector<TLorentzVector>& taugen); std::pair<double,double> tauPtE(double taupt, double tauenergy,int sys); double fakeweight(double pt); int main(int argc, char** argv) { using namespace std; std::vector<string> input; for (int f = 1; f < argc; f++) { input.push_back(*(argv + f)); cout << "\n INPUT NAME IS: " << input[f - 1] << "\n"; } if(input[0] != "Muon" && input[0] != "Electron" && input[0] != "MuElectron") { cout << "*************upppsssss************** pls type either Muon or Electron or MuElectron" << endl; return 1; } bool Muon = (input[0]=="Muon"); bool Electron = (input[0] == "Electron"); bool Muelectron = (input[0] == "MuElectron"); vector <float> W_events = W_EvenetMultiplicity(); vector <float> DY_events = DY_EvenetMultiplicity(); for(int k=1; k<input.size(); k++ ) { myMap1 = new std::map<std::string, TH1F*>(); myMap2 = new map<string, TH2F*>(); myMap3 = new map<string, TH3F*>(); TFile *f_Double = TFile::Open(input[k].c_str()); cout << "\n Now is running on -------> " << std::string(f_Double->GetName()) << "\n"; TFile * myFile = TFile::Open(f_Double->GetName()); TH1F * HistoTot = (TH1F*) myFile->Get("hcount"); //TTree *Run_Tree = (TTree*) f_Double->Get("ggNtuplizer/EventTree"); TTree *Run_Tree = (TTree*) f_Double->Get("EventTree"); std::string output = input[k]; size_t root = output.find(".root"); output.erase(root); output += "_controlPlot.root"; cout << "\n\n\n OUTPUT NAME IS: " << output << endl; //PRINTING THE OUTPUT FILE NAME TFile *fout = TFile::Open(output.c_str(), "RECREATE"); TH1F* pu = new TH1F("pu","pu",100,0.,2.); TH1F* h_preweight = new TH1F("preweight","weight before applying SF",100,0.,5.); TH1F* h_postweight = new TH1F("postweight","weight after applying SF",100,0.,5.); TH1F* h_SF1 = new TH1F("SF1","SF1",100,0.9,1.1); TH1F* h_SF2 = new TH1F("SF2","SF2",100,0.9,1.1); TH1F* h_SF = new TH1F("SF","SF",100,0.9,1.1); TH1F* h_musize = new TH1F("musize","musize",10,0,10); TH1F* h_tausize = new TH1F("tausize","tausize",10,0,10); TH1F* corrpu; string Charge[2] = {"opposite_sign","same_sign"}; string totcharge[2] = {"totCharge==0","totCharge!=0"}; string taumucharge[2] = {"totCharge==0_and_mucharge==0","totCharge==0_and_mucharge_not_equal_to_zero_i.e_signal_region"}; string tauCharge_[2] = {"opposite_sign_tau","same_sign_tau"}; string muCharge_[2] = {"opposite_sign_muon","same_sign_muon"}; ///////////////////////// General Info Run_Tree->SetBranchAddress("isData", &isData); Run_Tree->SetBranchAddress("run", &run); Run_Tree->SetBranchAddress("lumis", &lumis); Run_Tree->SetBranchAddress("event", &event); Run_Tree->SetBranchAddress("genWeight",&genWeight); Run_Tree->SetBranchAddress("HLTEleMuX", &HLTEleMuX); Run_Tree->SetBranchAddress("HLTEleMuXIsPrescaled", &HLTEleMuXIsPrescaled); Run_Tree->SetBranchAddress("puTrue", &puTrue); ///////////////////////// Tau Info Run_Tree->SetBranchAddress("nTau", &nTau); Run_Tree->SetBranchAddress("tauPt" ,&tauPt); Run_Tree->SetBranchAddress("tauEta" ,&tauEta); Run_Tree->SetBranchAddress("tauPhi" ,&tauPhi); Run_Tree->SetBranchAddress("tauMass" ,&tauMass); Run_Tree->SetBranchAddress("tauCharge" ,&tauCharge); Run_Tree->SetBranchAddress("taupfTausDiscriminationByDecayModeFinding", &taupfTausDiscriminationByDecayModeFinding); Run_Tree->SetBranchAddress("tauByTightMuonRejection3", &tauByTightMuonRejection3); Run_Tree->SetBranchAddress("tauByLooseMuonRejection3", &tauByLooseMuonRejection3); Run_Tree->SetBranchAddress("tauByMVA6TightElectronRejection" ,&tauByMVA6TightElectronRejection); Run_Tree->SetBranchAddress("tauByLooseCombinedIsolationDeltaBetaCorr3Hits",&tauByLooseCombinedIsolationDeltaBetaCorr3Hits); Run_Tree->SetBranchAddress("tauByMediumCombinedIsolationDeltaBetaCorr3Hits",&tauByMediumCombinedIsolationDeltaBetaCorr3Hits); Run_Tree->SetBranchAddress("tauByMVA6LooseElectronRejection", &tauByMVA6LooseElectronRejection); Run_Tree->SetBranchAddress("tauDxy",&tauDxy); Run_Tree->SetBranchAddress("tauByMediumIsolationMVArun2v1DBoldDMwLT", &tauByMediumIsolationMVArun2v1DBoldDMwLT); Run_Tree->SetBranchAddress("tauByLooseIsolationMVArun2v1DBoldDMwLT", &tauByLooseIsolationMVArun2v1DBoldDMwLT); Run_Tree->SetBranchAddress("tauByVLooseIsolationMVArun2v1DBoldDMwLT", &tauByVLooseIsolationMVArun2v1DBoldDMwLT); ///////////////////////// Mu Info Run_Tree->SetBranchAddress("nMu", &nMu); Run_Tree->SetBranchAddress("eleEn", &eleEn); Run_Tree->SetBranchAddress("muEn", &muEn); Run_Tree->SetBranchAddress("tauEnergy", &tauEnergy); Run_Tree->SetBranchAddress("muPt" ,&muPt); Run_Tree->SetBranchAddress("muEta" ,&muEta); Run_Tree->SetBranchAddress("muPhi" ,&muPhi); Run_Tree->SetBranchAddress("muIsoTrk", &muIsoTrk); Run_Tree->SetBranchAddress("muCharge",&muCharge); // Run_Tree->SetBranchAddress("muIsMediumID",&muIsMediumID); //Run_Tree->SetBranchAddress("muIsLooseID",&muIsLooseID); Run_Tree->SetBranchAddress("muPFChIso", &muPFChIso); Run_Tree->SetBranchAddress("muPFPhoIso", &muPFPhoIso); Run_Tree->SetBranchAddress("muPFNeuIso", &muPFNeuIso); Run_Tree->SetBranchAddress("muPFPUIso", &muPFPUIso); Run_Tree->SetBranchAddress("muD0",&muD0); Run_Tree->SetBranchAddress("muDz",&muDz); Run_Tree->SetBranchAddress("muIDbit", &muIDbit); ///////////////////////// Ele Info Run_Tree->SetBranchAddress("nEle", &nEle); Run_Tree->SetBranchAddress("elePt" ,&elePt); Run_Tree->SetBranchAddress("eleEta" ,&eleEta); Run_Tree->SetBranchAddress("elePhi" ,&elePhi); Run_Tree->SetBranchAddress("elePFChIso", &elePFChIso); Run_Tree->SetBranchAddress("eleIDMVA", &eleIDMVA); Run_Tree->SetBranchAddress("eleCharge",&eleCharge); Run_Tree->SetBranchAddress("eleSCEta",&eleSCEta); Run_Tree->SetBranchAddress("elePFChIso", &elePFChIso); Run_Tree->SetBranchAddress("elePFPhoIso", &elePFPhoIso); Run_Tree->SetBranchAddress("elePFNeuIso", &elePFNeuIso); Run_Tree->SetBranchAddress("elePFPUIso", &elePFPUIso); Run_Tree->SetBranchAddress("eleIDMVANonTrg", &eleIDMVANonTrg); Run_Tree->SetBranchAddress("eleD0",&eleD0); Run_Tree->SetBranchAddress("eleDz",&eleDz); Run_Tree->SetBranchAddress("eleMissHits", &eleMissHits); Run_Tree->SetBranchAddress("eleConvVeto", &eleConvVeto); ///////////////////////// Jet Info Run_Tree->SetBranchAddress("nJet",&nJet); Run_Tree->SetBranchAddress("jetPt",&jetPt); Run_Tree->SetBranchAddress("jetEta",&jetEta); Run_Tree->SetBranchAddress("jetPhi",&jetPhi); Run_Tree->SetBranchAddress("jetEn",&jetEn); // Run_Tree->SetBranchAddress("jetpfCombinedInclusiveSecondaryVertexV2BJetTags",&jetpfCombinedInclusiveSecondaryVertexV2BJetTags); Run_Tree->SetBranchAddress("jetCSV2BJetTags",&jetCSV2BJetTags); Run_Tree->SetBranchAddress("mcMomPID" ,&mcMomPID); Run_Tree->SetBranchAddress("mcGMomPID" ,&mcGMomPID); Run_Tree->SetBranchAddress("nMC" ,&nMC); Run_Tree->SetBranchAddress("mcPID", &mcPID); Run_Tree->SetBranchAddress("mcPt", &mcPt); Run_Tree->SetBranchAddress("mcEta", &mcEta); Run_Tree->SetBranchAddress("mcPhi", &mcPhi); Run_Tree->SetBranchAddress("mcE", &mcE); Run_Tree->SetBranchAddress("mcMomPt", &mcMomPt); Run_Tree->SetBranchAddress("mcMomEta", &mcMomEta); Run_Tree->SetBranchAddress("mcMomPhi", &mcMomPhi); Run_Tree->SetBranchAddress("mcMomMass", &mcMomMass); Run_Tree->SetBranchAddress("mcHadronPt", &mcHadronPt); Run_Tree->SetBranchAddress("mcHadronEta", &mcHadronEta); Run_Tree->SetBranchAddress("mcHadronPhi", &mcHadronPhi); Run_Tree->SetBranchAddress("mcHadronMass", &mcHadronMass); Run_Tree->SetBranchAddress("mcHadronE", &mcHadronE); Run_Tree->SetBranchAddress("mcHadronGMomPID", &mcHadronGMomPID); Run_Tree->SetBranchAddress("mcHadronMomPID", &mcHadronMomPID); Run_Tree->SetBranchAddress("mcHadronMomPt", &mcHadronMomPt); Run_Tree->SetBranchAddress("mcHadronMomMass", &mcHadronMomMass); Run_Tree->SetBranchAddress("mcHadronMomEta", &mcHadronMomEta); Run_Tree->SetBranchAddress("mcHadronMomPhi", &mcHadronMomPhi); Run_Tree->SetBranchAddress("mcStatusFlag", &mcStatusFlag); Run_Tree->SetBranchAddress("mcStatus", &mcStatus); Run_Tree->SetBranchAddress("mcMass", &mcMass); Run_Tree->SetBranchAddress("num_gen_jets", &num_gen_jets); Run_Tree->SetBranchAddress("isPVGood", &isPVGood); ///////////////////////// MET Info Run_Tree->SetBranchAddress("pfMET",&pfMET); Run_Tree->SetBranchAddress("pfMETPhi",&pfMETPhi); Int_t nentries_wtn = (Int_t) Run_Tree->GetEntries(); cout<<"nentries_wtn====" << nentries_wtn << "\n"; TFile * PUData= TFile::Open("dataMoriondPU.root"); TH1F * HistoPUData= (TH1F *) PUData->Get("pileup"); HistoPUData->Scale(1.0/HistoPUData->Integral()); TFile * PUMC= TFile::Open("mcMoriondPU.root"); TH1F * HistoPUMC= (TH1F *) PUMC->Get("pileup"); HistoPUMC->Scale(1.0/HistoPUMC->Integral()); corrpu = (TH1F*)HistoPUMC->Clone(); for ( Int_t i =0; i < nentries_wtn; i++) { //for ( Int_t i =0; i < 1000; i++) { Run_Tree->GetEntry(i); if (i % 1000 == 0) fprintf(stdout, "\r Processed events: %8d of %8d ", i, nentries_wtn); // if(!isPVGood) continue; bool PassTrigger = (Muon) ? ((HLTEleMuX >> 14 & 1) || (HLTEleMuX >> 15 & 1)) : ( Electron ? (HLTEleMuX >> 5 & 1) : (HLTEleMuX >> 5 & 1));// || (HLTEleMuX >> 19 & 1) || (HLTEleMuX >> 20 & 1)) : (HLTEleMuX >> 34 & 1); if(!PassTrigger) continue; // cout << "PassTrigger" << endl; int count_bjet(0); for (int ijet= 0 ; ijet < nJet ; ijet++){ if (jetPt->at(ijet) > 20 && fabs(jetEta->at(ijet)) < 2.5 && jetCSV2BJetTags->at(ijet) > 0.800){ count_bjet +=1; break; } } if(count_bjet) continue; float LumiWeight = 1; float GetGenWeight=1; float PUWeight = 1; if(input[k].find("DY1Jets") != string::npos) num_gen_jets =1; if(input[k].find("DY2Jets") != string::npos) num_gen_jets=2; if(input[k].find("DY3Jets") != string::npos) num_gen_jets=3; if(input[k].find("DY4Jets") != string::npos) num_gen_jets=4; if(input[k].find("W1Jets") != string::npos) num_gen_jets=1; if(input[k].find("W2Jets") != string::npos) num_gen_jets=2; if(input[k].find("W3Jets") != string::npos) num_gen_jets=3; if(input[k].find("W4Jets") != string::npos) num_gen_jets=4; if (!isData) { if (HistoTot) LumiWeight = weightCalc(HistoTot, input[k], num_gen_jets, W_events, DY_events); // cout << "lumi=========" << LumiWeight << input[k] << endl; GetGenWeight=genWeight; int puNUmmc=int(puTrue->at(0)*10); int puNUmdata=int(puTrue->at(0)*10); float PUMC_=HistoPUMC->GetBinContent(puNUmmc+1); float PUData_=HistoPUData->GetBinContent(puNUmdata+1); if (PUMC_ ==0) cout<<"PUMC_ is zero!!! & num pileup= "<< puTrue->at(0)<<"\n"; else PUWeight= PUData_/PUMC_; corrpu->SetBinContent(puNUmmc+1,HistoPUMC->GetBinContent(puNUmmc+1)*PUWeight*LumiWeight); } pu->Fill(PUWeight); double weight = GetGenWeight*PUWeight*LumiWeight; /////////////////////////////////////////////// //Important Analysis Loop Will Happen Here!!!// /////////////////////////////////////////////// bool firstPart(true); std::vector<int> vec_muele, vec_tauNor, vec_tau, vec_tauiso, vec_tauUp, vec_tauDn; if(Muon) { for (int imu=0 ; imu < nMu; imu++){ bool mupt = (firstPart) ? (muPt->at(imu) >18) : (muPt->at(imu) >9); UShort_t id = (muIDbit->at(imu) >> 1 & 1); float IsoMu=muPFChIso->at(imu)/muPt->at(imu); if ( (muPFNeuIso->at(imu) + muPFPhoIso->at(imu) - 0.5* muPFPUIso->at(imu) ) > 0.0) IsoMu= ( muPFChIso->at(imu) + muPFNeuIso->at(imu) + muPFPhoIso->at(imu) - 0.5* muPFPUIso->at(imu))/muPt->at(imu); if(mupt && id && fabs(muEta->at(imu)) <2.4 && IsoMu <0.3) { firstPart = false; vec_muele.push_back(imu); } } } else if (Electron) { for (int iele = 0; iele < nEle; ++iele) { bool elept = (firstPart) ? (elePt->at(iele) >18) : (elePt->at(iele) >15); float IsoEle=elePFChIso->at(iele)/elePt->at(iele); if ( (elePFNeuIso->at(iele) + elePFPhoIso->at(iele) - 0.5* elePFPUIso->at(iele)) > 0.0) IsoEle= (elePFChIso->at(iele) + elePFNeuIso->at(iele) + elePFPhoIso->at(iele) - 0.5* elePFPUIso->at(iele))/elePt->at(iele); bool eleMVAId= false; if (fabs (eleSCEta->at(iele)) < 0.8 && eleIDMVA->at(iele) > 0.967083) eleMVAId= true; else if (fabs (eleSCEta->at(iele)) > 0.8 &&fabs (eleSCEta->at(iele)) < 1.5 && eleIDMVA->at(iele) > 0.929117) eleMVAId= true; else if ( fabs (eleSCEta->at(iele)) > 1.5 && eleIDMVA->at(iele) > 0.726311 ) eleMVAId= true; else eleMVAId= false; if(elept && eleMVAId && fabs(eleEta->at(iele)) <2.5 && IsoEle <0.1) { firstPart = false; vec_muele.push_back(iele); } } } else { } double tauESUp = 1.03; double tauESDn = 0.97; for (int itau=0 ; itau < nTau; itau++) { bool antielemu = (Muon) ? tauByMVA6LooseElectronRejection->at(itau) !=0 && tauByTightMuonRejection3->at(itau) !=0 : ((Electron) ? tauByMVA6TightElectronRejection->at(itau) !=0 && tauByLooseMuonRejection3->at(itau) !=0 : tauByMVA6TightElectronRejection->at(itau) !=0 && tauByTightMuonRejection3->at(itau) !=0); if(fabs(tauEta->at(itau)) < 2.3 && antielemu && taupfTausDiscriminationByDecayModeFinding->at(itau) !=0) { if(tauPt->at(itau) >20) vec_tauNor.push_back(itau); if(tauPt->at(itau)*tauESUp >20) vec_tauUp.push_back(itau); if(tauPt->at(itau)*tauESDn >20) vec_tauDn.push_back(itau); } if(tauPt->at(itau) >20 && fabs(tauEta->at(itau)) < 2.3 && antielemu && taupfTausDiscriminationByDecayModeFinding->at(itau) !=0 && tauByLooseIsolationMVArun2v1DBoldDMwLT->at(itau) !=0) vec_tauiso.push_back(itau); } std::string part; std::vector<double> pt, eta,ene,chrg,phi; if(vec_muele.size()<2) continue; if (Muon) { part = "#mu_"; for (int imu=0; imu<vec_muele.size(); ++imu) { pt.push_back(muPt->at(vec_muele[imu])); eta.push_back(muEta->at(vec_muele[imu])); phi.push_back(muPhi->at(vec_muele[imu])); ene.push_back(muEn->at(vec_muele[imu])); chrg.push_back(muCharge->at(vec_muele[imu])); } } else if(Electron) { part = "#ele_"; for (int iele=0; iele<vec_muele.size(); ++iele) { pt.push_back(elePt->at(vec_muele[iele])); eta.push_back(eleEta->at(vec_muele[iele])); phi.push_back(elePhi->at(vec_muele[iele])); ene.push_back(eleEn->at(vec_muele[iele])); chrg.push_back(eleCharge->at(vec_muele[iele])); } } else { part = "#mu_#ele"; for (int imuele=0; imuele<vec_muele.size(); ++imuele) { double pt_ = (k==0) ? muPt->at(vec_muele[k]) : elePt->at(vec_muele[k]); pt.push_back(pt_); double eta_ = (k==0) ? muEta->at(vec_muele[k]) : eleEta->at(vec_muele[k]); eta.push_back(eta_); double phi_ = (k==0) ? muPhi->at(vec_muele[k]) : elePhi->at(vec_muele[k]); phi.push_back(phi_); double ene_ = (k==0) ? muEn->at(vec_muele[k]) : eleEn->at(vec_muele[k]); ene.push_back(ene_); double chrg_ = (k==0) ? muCharge->at(vec_muele[k]) : eleCharge->at(vec_muele[k]); chrg.push_back(chrg_); } } bool charge(false), samesign(false); charge = chrg[0]*chrg[1] >0; samesign = charge ? true : false; bool mucharge[2] = {!samesign, samesign}; bool zerojet = vec_tauiso.size() ==0; bool onejet = vec_tauiso.size() ==1; bool twojet = vec_tauiso.size() ==2; bool jet[3] = {zerojet, onejet, twojet}; std::string Jet[3] = {"zero_tau_jet_region", "one_tau_jet_region", "two_tau_jet_region"}; TLorentzVector m1,m2,M; m1.SetPtEtaPhiE(pt[0],eta[0],phi[0],ene[0]); m2.SetPtEtaPhiE(pt[1],eta[1],phi[1],ene[1]); M= m1+m2; double leading_weight = 1; double subleading_weight = 1; double muonweight = 1; h_preweight->Fill(weight); if(!isData && Muon) { leading_weight = scaleFactor(pt[0],eta[0]); subleading_weight = scaleFactor(pt[1],eta[1]); h_SF1->Fill(leading_weight); h_SF2->Fill(subleading_weight); muonweight = leading_weight*subleading_weight; h_SF->Fill(muonweight); } h_postweight->Fill(muonweight); for(int i=0; i<2; i++) { if(!mucharge[i]) continue; std::string title = Charge[i]+"_and_no_cut_on_#tau_leg"; if(M.M() >=20 && M.M() <=200) { plotFill("InvariantMass_of_"+part+"pair_with_" +title+"_with_mass_20-200GeV",M.M(),90,20,200,weight*muonweight); plotFill("pt_distribution_of_Leading_"+part+title+"_with_mass_20-200GeV",pt[0],50,0,100,weight*leading_weight); plotFill("pt_distribution_of_SubLeading_"+part+title+"_with_mass_20-200GeV",pt[1],50,0,100,weight*subleading_weight); plotFill("eta_distribution_of_Leading_"+part+title+"_with_mass_20-200GeV",eta[0],20,-2.4,2.4,weight*leading_weight); plotFill("eta_distribution_of_SubLeading_"+part+title+"_with_mass_20-200GeV",eta[1],20,-2.4,2.4,weight*subleading_weight); } if(M.M() >=60 && M.M() <=120) { plotFill("InvariantMass_of_"+part+"pair_with_" +title+"_with_mass_60-120GeV",M.M(),30,60,120,weight*muonweight); plotFill("pt_distribution_of_Leading_"+part+title+"_with_mass_60-120GeV",pt[0],50,0,100,weight*leading_weight); plotFill("pt_distribution_of_SubLeading_"+part+title+"_with_mass_60-120GeV",pt[1],50,0,100,weight*subleading_weight); plotFill("eta_distribution_of_Leading_"+part+title+"_with_mass_60-120GeV",eta[0],20,-2.4,2.4,weight*leading_weight); plotFill("eta_distribution_of_SubLeading_"+part+title+"_with_mass_60-120GeV",eta[1],20,-2.4,2.4,weight*subleading_weight); } for(int j=0; j<3; j++ ){ if(!jet[j]) continue; std::string title = Charge[i]+"_in_"+Jet[j]; plotFill("InvariantMass_of_"+part+"pair_with_" +title,M.M(),20,70,110,weight*muonweight); } } TLorentzVector taugen_, mugen_; std::vector<TLorentzVector> taugen, mugen; for(int imc=0; imc<nMC; imc++) { if(fabs(mcPID->at(imc)) ==13) { TLorentzVector genMu; genMu.SetPtEtaPhiE(mcPt->at(imc),mcEta->at(imc),mcPhi->at(imc),mcE->at(imc)); mugen.push_back(genMu); } if(mcHadronPt->at(imc) < 0) continue; taugen_.SetPtEtaPhiE(mcHadronPt->at(imc),mcHadronEta->at(imc),mcHadronPhi->at(imc),mcHadronE->at(imc)); taugen.push_back(taugen_); } for(int isys=0; isys<4; isys++) { vec_tau = (isys==0 || isys==1) ? vec_tauNor : ((isys==2) ? vec_tauUp : vec_tauDn); std::string systematic = (isys==0) ? "" : ((isys==1) ? "Nom" : ((isys==2) ? "Up" : "Dn")); if(vec_tau.size() >1) { TLorentzVector t1,t2,T,HH; for(int itau=0; itau<vec_tau.size(); itau++) { std::pair<double,double> pte1 = tauPtE(tauPt->at(vec_tau[itau]), tauEnergy->at(vec_tau[itau]),isys); t1.SetPtEtaPhiE(pte1.first,tauEta->at(vec_tau[itau]),tauPhi->at(vec_tau[itau]),pte1.second); bool tau1match(false); if(taugen.size() !=0 && isys !=0) { for(unsigned int igentau=0; igentau<taugen.size(); igentau++) { if(t1.DeltaR(taugen[igentau]) <0.5) { tau1match = true; break; } } } if(isys !=0 && !tau1match) continue; for(int jtau=itau+1; jtau<vec_tau.size(); jtau++) { std::pair<double,double> pte2 = tauPtE(tauPt->at(vec_tau[jtau]), tauEnergy->at(vec_tau[jtau]),isys); t2.SetPtEtaPhiE(pte2.first,tauEta->at(vec_tau[jtau]),tauPhi->at(vec_tau[jtau]),pte2.second); bool tau2match(false); if(taugen.size() !=0 && isys !=0) { for(unsigned int igentau=0; igentau<taugen.size(); igentau++) { if(t2.DeltaR(taugen[igentau]) <0.5) { tau2match = true; break; } } } if(isys !=0 && !tau2match) continue; if(t1.DeltaR(t2) <0.5) continue; bool tau1antiiso = (tauByLooseIsolationMVArun2v1DBoldDMwLT->at(vec_tau[itau]) ==0 && tauByLooseIsolationMVArun2v1DBoldDMwLT->at(vec_tau[jtau]) !=0 ); bool tau2antiiso = (tauByLooseIsolationMVArun2v1DBoldDMwLT->at(vec_tau[jtau]) ==0 && tauByLooseIsolationMVArun2v1DBoldDMwLT->at(vec_tau[itau]) !=0 ); bool tau1antiisotau2antiiso = (tauByLooseIsolationMVArun2v1DBoldDMwLT->at(vec_tau[itau]) ==0 && tauByLooseIsolationMVArun2v1DBoldDMwLT->at(vec_tau[jtau]) ==0 ); bool tau1iso_tau2iso = (tauByLooseIsolationMVArun2v1DBoldDMwLT->at(vec_tau[itau]) !=0 && tauByLooseIsolationMVArun2v1DBoldDMwLT->at(vec_tau[jtau]) !=0); double fake(1),fake1(1),fake2(1), fake12(1); if(tau1antiiso) { double f = fakeweight(pte1.first); fake1 *= f/(1-f); fake *= fake1; } if(tau2antiiso) { double f = fakeweight(pte2.first); fake2 *= f/(1-f); fake *= fake2; } if(tau1antiisotau2antiiso) { fake12 = fakeweight(pte1.first)/(1-fakeweight(pte1.first)) * fakeweight(pte2.first)/(1-fakeweight(pte2.first)); fake *= fake12; } if(!tau1antiiso && !tau2antiiso && !tau1iso_tau2iso && !tau1antiisotau2antiiso) continue; std::string tauiso = (tau1antiiso) ? "_in_tau1anti_iso" : (tau2antiiso ? "_in_tau2anti_iso" : (tau1iso_tau2iso ? "_in_tau1iso_tau2iso" : "_in_tau1antiso_tau2antiiso")); T= t1+t2; charge = tauCharge->at(vec_tau[itau])*tauCharge->at(vec_tau[jtau]) >0; samesign = charge ? true : false; bool taucharge[2] = {!samesign, samesign}; for(int imu=0; imu<vec_muele.size(); imu++) { m1.SetPtEtaPhiE(pt[imu],eta[imu],phi[imu],ene[imu]); if(!isData) leading_weight = scaleFactor(pt[imu],eta[imu]); if(m1.DeltaR(t1) <0.5) continue; if(m1.DeltaR(t2) <0.5) continue; bool mu1match(false); for(int jmu=imu+1; jmu<vec_muele.size(); jmu++) { m2.SetPtEtaPhiE(pt[jmu],eta[jmu],phi[jmu],ene[jmu]); if(m2.DeltaR(m1) <0.5) continue; if(m2.DeltaR(t1) <0.5) continue; if(m2.DeltaR(t2) <0.5) continue; bool mu2match(false); if(!isData) subleading_weight = scaleFactor(pt[jmu],eta[jmu]); M = m1+m2; HH = T+M; charge = chrg[imu]*chrg[jmu] >0; samesign = charge ? true : false; bool mucharge[2] = {!samesign, samesign}; if(isys ==0) { for(int muchrg=0; muchrg<2; muchrg++) { // if(muchrg!=1) continue; if(!mucharge[muchrg]) continue; std::string title = muCharge_[muchrg]; plotFill("InvariantMass_of_tau_pair_with_"+title+tauiso,T.M(),6,50,110,weight*fake); plotFill("pt_distribution_of_Leading_#tau_with_"+title+tauiso,tauPt->at(vec_tau[itau]),50,0,150,weight*fake); plotFill("pt_distribution_of_SubLeading_#tau_with_"+title+tauiso,tauPt->at(vec_tau[jtau]),50,0,150,weight*fake); plotFill("eta_distribution_of_Leading_#tau_with_"+title+tauiso,tauEta->at(vec_tau[itau]),20,-2.4,2.4,weight*fake); plotFill("eta_distribution_of_SubLeading_#tau_with_"+title+tauiso,tauEta->at(vec_tau[jtau]),20,-2.4,2.4,weight*fake); plotFill("InvariantMass_of_mu_pair_with_"+title+tauiso,M.M(),6,60,120,weight*fake); plotFill("pt_distribution_of_Leading_#mu_with_"+title+tauiso,muPt->at(vec_muele[imu]),50,0,150,weight*fake); plotFill("pt_distribution_of_SubLeading_#mu_with_"+title+tauiso,muPt->at(vec_muele[jmu]),50,0,150,weight*fake); plotFill("eta_distribution_of_Leading_#mu_with_"+title+tauiso,muEta->at(vec_muele[imu]),20,-2.4,2.4,weight*fake); plotFill("eta_distribution_of_SubLeading_#mu_with_"+title+tauiso,muEta->at(vec_muele[jmu]),20,-2.4,2.4,weight*fake); plotFill("InvariantMass_of_4_particle_with_"+title+tauiso,HH.M(),6,250,900,weight*leading_weight*subleading_weight*fake); } } bool taumuCharge; taumuCharge = chrg[imu]+chrg[jmu] + tauCharge->at(vec_tau[itau])+tauCharge->at(vec_tau[jtau]) ==0; bool taumucharge_[2], mucharge_[0]; taumucharge_[0] = taumuCharge ? true : false; taumucharge_[1] = !taumuCharge ; for(int totchrg=0; totchrg<2; totchrg++) { if(!mucharge[1]) continue; if(!taumucharge_[totchrg]) continue; if(isys ==0) { if(tau1iso_tau2iso) { if(mugen.size() !=0) { for(unsigned int igenmu=0; igenmu<mugen.size(); igenmu++) { if(m1.DeltaR(mugen[igenmu]) <0.5) mu1match = true; if(m2.DeltaR(mugen[igenmu]) <0.5) mu2match = true; } } float muSFup(1.), muSFdn(1.); if(mu1match && mu2match) { muSFup = 1.04; muSFdn = 0.96; } else if(mu1match || mu2match) { muSFup = 1.02; muSFdn = 0.98; } if(mu1match || mu2match) { plotFill("InvariantMass_of_4_particle_with_"+totcharge[totchrg]+tauiso+"_muSFup",HH.M(),6,250,900,weight*leading_weight*subleading_weight*fake*muSFup); plotFill("InvariantMass_of_4_particle_with_"+totcharge[totchrg]+tauiso+"_muSFdn",HH.M(),6,250,900,weight*leading_weight*subleading_weight*fake*muSFdn); } if(taugen.size() !=0) { for(unsigned int igentau=0; igentau<taugen.size(); igentau++) { if(t1.DeltaR(taugen[igentau]) <0.5) tau1match = true; if(t2.DeltaR(taugen[igentau]) <0.5) tau2match = true; } } float tauSFup(1.), tauSFdn(1.); if(tau1match && tau2match) { tauSFup = 1.16; tauSFdn = 0.84; } else if(tau1match || tau2match) { tauSFup = 1.08; tauSFdn = 0.92; } if(tau1match || tau2match) { plotFill("InvariantMass_of_4_particle_with_"+totcharge[totchrg]+tauiso+"_tauSFup",HH.M(),6,250,900,weight*leading_weight*subleading_weight*fake*tauSFup); plotFill("InvariantMass_of_4_particle_with_"+totcharge[totchrg]+tauiso+"_tauSFdn",HH.M(),6,250,900,weight*leading_weight*subleading_weight*fake*tauSFdn); } } plotFill("InvariantMass_of_4_particle_with_"+totcharge[totchrg]+tauiso,HH.M(),6,250,900,weight*leading_weight*subleading_weight*fake); plotFill("InvariantMass_of_4_particle_with_"+totcharge[totchrg]+tauiso+"_nofake_weight",HH.M(),6,250,900,weight*leading_weight*subleading_weight); plotFill("InvariantMass_of_#mu_pair_with_"+totcharge[totchrg]+tauiso,M.M(),30,60,120,weight*leading_weight*subleading_weight); plotFill("InvariantMass_of_#mu_pair_with_"+totcharge[totchrg]+tauiso+"_nofake_weight",M.M(),30,60,120,weight*leading_weight*subleading_weight); plotFill("InvariantMass_of_#tau_pair_with_"+totcharge[totchrg]+tauiso,T.M(),35,50,120,weight*fake); plotFill("InvariantMass_of_#tau_pair_with_"+totcharge[totchrg]+tauiso+"_nofake_weight",T.M(),35,50,120,weight); plotFill("pt_distribution_of_Leading_#tau_with_"+totcharge[totchrg]+tauiso,tauPt->at(vec_tau[itau]),50,0,150,weight*fake); plotFill("pt_distribution_of_SubLeading_#tau_with_"+totcharge[totchrg]+tauiso,tauPt->at(vec_tau[jtau]),50,0,150,weight*fake); plotFill("eta_distribution_of_Leading_#tau_with_"+totcharge[totchrg]+tauiso,tauEta->at(vec_tau[itau]),20,-2.4,2.4,weight*fake); plotFill("eta_distribution_of_SubLeading_#tau_with_"+totcharge[totchrg]+tauiso,tauEta->at(vec_tau[jtau]),20,-2.4,2.4,weight*fake); plotFill("pt_distribution_of_Leading_#tau_with_"+totcharge[totchrg]+tauiso+"_nofake_weight",tauPt->at(vec_tau[itau]),50,0,150,weight); plotFill("pt_distribution_of_SubLeading_#tau_with_"+totcharge[totchrg]+tauiso+"_nofake_weight",tauPt->at(vec_tau[jtau]),50,0,150,weight); plotFill("eta_distribution_of_Leading_#tau_with_"+totcharge[totchrg]+tauiso+"_nofake_weight",tauEta->at(vec_tau[itau]),20,-2.4,2.4,weight); plotFill("eta_distribution_of_SubLeading_#tau_with_"+totcharge[totchrg]+tauiso+"_nofake_weight",tauEta->at(vec_tau[jtau]),20,-2.4,2.4,weight); plotFill("pt_distribution_of_Leading_#mu_with_"+totcharge[totchrg]+tauiso,muPt->at(vec_muele[imu]),50,0,150,weight*fake); plotFill("pt_distribution_of_SubLeading_#mu_with_"+totcharge[totchrg]+tauiso,muPt->at(vec_muele[jmu]),50,0,150,weight*fake); plotFill("eta_distribution_of_Leading_#mu_with_"+totcharge[totchrg]+tauiso,muEta->at(vec_muele[imu]),20,-2.4,2.4,weight*fake); plotFill("eta_distribution_of_SubLeading_#mu_with_"+totcharge[totchrg]+tauiso,muEta->at(vec_muele[jmu]),20,-2.4,2.4,weight*fake); plotFill("pt_distribution_of_Leading_#mu_with_"+totcharge[totchrg]+tauiso+"_nofake_weight",muPt->at(vec_muele[imu]),50,0,150,weight); plotFill("pt_distribution_of_SubLeading_#mu_with_"+totcharge[totchrg]+tauiso+"_nofake_weight",muPt->at(vec_muele[jmu]),50,0,150,weight); plotFill("eta_distribution_of_Leading_#mu_with_"+totcharge[totchrg]+tauiso+"_nofake_weight",muEta->at(vec_muele[imu]),20,-2.4,2.4,weight); plotFill("eta_distribution_of_SubLeading_#mu_with_"+totcharge[totchrg]+tauiso+"_nofake_weight",muEta->at(vec_muele[jmu]),20,-2.4,2.4,weight); TLorentzVector H; for(int i=0; i<2; i++) { TLorentzVector tau = (i==0) ? t1 : t2; for(int j=0; j<2; j++) { TLorentzVector mu = (j==0) ? m1 : m2; H = tau+mu; muonweight = (j==0) ? leading_weight : subleading_weight; plotFill("InvariantMass_of_taumu_with_"+totcharge[totchrg]+tauiso,H.M(),8,40,200,weight*fake*muonweight); plotFill("InvariantMass_of_taumu_with_"+totcharge[totchrg]+tauiso+"_nofake_weight",H.M(),8,40,200,weight*muonweight); } } } if(isys!=0){ plotFill("InvariantMass_of_4_particle_with_"+totcharge[totchrg]+tauiso+"_"+systematic,HH.M(),6,250,900,weight*leading_weight*subleading_weight*fake); cout << isys << "\t" << t1.Pt() << "\t" << t2.Pt() << "\t" << HH.M() << endl; } } } } } } } } } //end of analysis code, close and write histograms/file fout->cd(); pu->Write(); corrpu->Scale(1/corrpu->Integral()); corrpu->Write(); h_musize->Write(); h_tausize->Write(); h_SF1->Write(); h_SF2->Write(); h_SF->Write(); h_preweight->Write(); h_postweight->Write(); map<string, TH1F*>::const_iterator iMap1 = myMap1->begin(); map<string, TH1F*>::const_iterator jMap1 = myMap1->end(); for (; iMap1 != jMap1; ++iMap1) nplot1(iMap1->first)->Write(); map<string, TH2F*>::const_iterator iMap2 = myMap2->begin(); map<string, TH2F*>::const_iterator jMap2 = myMap2->end(); for (; iMap2 != jMap2; ++iMap2) nplot2(iMap2->first)->Write(); map<string, TH3F*>::const_iterator iMap3 = myMap3->begin(); map<string, TH3F*>::const_iterator jMap3 = myMap3->end(); for (; iMap3 != jMap3; ++iMap3) nplot3(iMap3->first)->Write(); fout->Close(); } } double scaleFactor(double pt, double eta) { int ptbin(-1), etabin(-1); for(int i=0; i<SF->GetYaxis()->GetNbins(); i++) { double binlow = SF->GetYaxis()->GetBinLowEdge(i+1); double binwidth = SF->GetYaxis()->GetBinWidth(i+1); // cout << "binlow== " << binlow << "binhigh= " << binlow+binwidth << "pt== " << pt << endl; if(pt >= binlow && pt < binlow+binwidth) { ptbin = i+1; break; } } if(ptbin==-1) { // cout << "**************** pt = " << pt << "\t doesn't fall within the pt range of the histogram" << endl; ptbin = SF->GetYaxis()->GetNbins(); } for(int i=0; i<SF->GetXaxis()->GetNbins(); i++) { double binlow = SF->GetXaxis()->GetBinLowEdge(i+1); double binwidth = SF->GetXaxis()->GetBinWidth(i+1); if(eta >=binlow && eta < binlow+binwidth) { etabin = i+1; break; } } if(etabin==-1)cout <<"**************** eta = " << eta << "\t doesn't fall within the eta range of the histogram"<< endl; // cout << "ptbin== " << ptbin << "\t" << "etabin== " << etabin << "pt== " << pt << "eta== " << eta << endl; //cout << "SF== " << SF->GetBinContent(etabin,ptbin) << endl; return SF->GetBinContent(etabin,ptbin); } double fakeweight(double pt) { // TF1 *f = new TF1("fa2","TMath::Exp(-0.019*x)",0,150); // return TMath::Exp(-0.019*pt); // [2]+[0]*TMath::Exp([1]*x // return 0.196+.229*TMath::Exp(-.0648*pt); // return .0196+.229*TMath::Exp(-.0648*pt); return .0192+.230*TMath::Exp(-.0651*pt);///L // return .036+.477*TMath::Exp(-.070*pt);///VL } bool taumatch(double eta, double phi, std::vector<TLorentzVector>& taugen) { for(unsigned int i=0; i<taugen.size(); i++) { // if(t.DeltaR(taugen.at(i)) <0.5) return true; double dr= dR_(eta,phi,taugen.at(i).Eta(),taugen.at(i).Phi()); if(dr<0.5) return true; } return false; } std::pair<double,double> tauPtE(double taupt, double tauenergy,int sys) { const double tauESUp(1.05), tauESDn(0.95); double pt = (sys==0 || sys==1) ? taupt : ((sys==2) ? taupt*tauESUp : taupt*tauESDn); double E = (sys==0 || sys==1) ? tauenergy : ((sys==2) ? tauenergy*tauESUp : tauenergy*tauESDn); return std::pair<double,double>(pt,E); }
[ "[saswati.nandan@cern.ch]" ]
[saswati.nandan@cern.ch]
22de07eb0a1877393585844ecb60edeb6023fb7c
b6bfc597130a008739f16d991eee8b4327391955
/8PRO128-TP3/boss1.h
e838b62cc146e1784bbefda1b63f4be0d42b6b2d
[ "MIT" ]
permissive
Hexzhe/8PRO128-TP3
2a50fd461c17d709344bb5686bfbaafd7a0231e5
24dc226465c7e216752ded07592a013e88e7e3e2
refs/heads/master
2022-03-28T17:41:07.414338
2019-11-29T19:15:19
2019-11-29T19:15:19
224,756,465
0
0
null
null
null
null
UTF-8
C++
false
false
350
h
// Fig. 10.1: boss1.h // Boss class derived from Employee #ifndef BOSS1_H #define BOSS1_H #include "employ2.h" class Boss : public Employee { public: Boss(const char *, const char *, Date bd, double = 0.0); void setWeeklySalary(double); virtual double earnings(Date) const; virtual void print() const; private: double weeklySalary; }; #endif
[ "hexzhe@jsngbt.com" ]
hexzhe@jsngbt.com
714fe68350b887ced06872030bde3a8dab6e83a2
3cf9e141cc8fee9d490224741297d3eca3f5feff
/C++ Benchmark Programs/Benchmark Files 1/classtester/autogen-sources/source-2580.cpp
ec6e1e73d0bd50308b1d9bd5a1a62c964bfe67b7
[]
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,499
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 { bool active2; c2() : active2(true) {} virtual ~c2() { tester2(this); active2 = false; } virtual void f2(){} }; void __attribute__ ((noinline)) tester2(c2* p) { p->f2(); } struct c3; void __attribute__ ((noinline)) tester3(c3* p); struct c3 : virtual c1, c0 { bool active3; c3() : active3(true) {} virtual ~c3() { tester3(this); c0 *p0_0 = (c0*)(c3*)(this); tester0(p0_0); c1 *p1_0 = (c1*)(c3*)(this); tester1(p1_0); active3 = false; } virtual void f3(){} }; void __attribute__ ((noinline)) tester3(c3* p) { p->f3(); if (p->active0) p->f0(); if (p->active1) p->f1(); } struct c4; void __attribute__ ((noinline)) tester4(c4* p); struct c4 : c3, c2 { bool active4; c4() : active4(true) {} virtual ~c4() { tester4(this); c0 *p0_0 = (c0*)(c3*)(c4*)(this); tester0(p0_0); c1 *p1_0 = (c1*)(c3*)(c4*)(this); tester1(p1_0); c2 *p2_0 = (c2*)(c4*)(this); tester2(p2_0); c3 *p3_0 = (c3*)(c4*)(this); tester3(p3_0); active4 = false; } virtual void f4(){} }; void __attribute__ ((noinline)) tester4(c4* p) { p->f4(); if (p->active0) p->f0(); if (p->active2) p->f2(); if (p->active3) p->f3(); if (p->active1) p->f1(); } int __attribute__ ((noinline)) inc(int v) {return ++v;} int main() { c0* ptrs0[25]; ptrs0[0] = (c0*)(new c0()); ptrs0[1] = (c0*)(c3*)(new c3()); ptrs0[2] = (c0*)(c3*)(c4*)(new c4()); for (int i=0;i<3;i=inc(i)) { tester0(ptrs0[i]); delete ptrs0[i]; } c1* ptrs1[25]; ptrs1[0] = (c1*)(new c1()); ptrs1[1] = (c1*)(c3*)(new c3()); ptrs1[2] = (c1*)(c3*)(c4*)(new c4()); for (int i=0;i<3;i=inc(i)) { tester1(ptrs1[i]); delete ptrs1[i]; } c2* ptrs2[25]; ptrs2[0] = (c2*)(new c2()); ptrs2[1] = (c2*)(c4*)(new c4()); for (int i=0;i<2;i=inc(i)) { tester2(ptrs2[i]); delete ptrs2[i]; } c3* ptrs3[25]; ptrs3[0] = (c3*)(new c3()); ptrs3[1] = (c3*)(c4*)(new c4()); for (int i=0;i<2;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
6eee50fc1bc057cd0de3d9008809efabb99f00c3
1902a42008d706a00e5a5f721b4dc3859c3bd1eb
/MAG3110.h
db6608d6130e868be587118e364232669e871439
[]
no_license
malbrec2/MAG3110
8f39e0658da6dde59dc71f366f00cd95f5bb3f32
c49e75c9928354d82d902e7c9ca5aa745ebb70d9
refs/heads/master
2020-12-25T17:56:21.150902
2015-05-08T21:08:49
2015-05-08T21:08:49
35,301,998
0
0
null
null
null
null
UTF-8
C++
false
false
1,189
h
/****************************************************************************** MAG3110.h MAG3110 Library Header File Michael Albrecht @ AT&T Foundry Original Creation Date: June 3, 2014 This file prototypes the MMA8452Q class, implemented in SFE_MMA8452Q.cpp. In addition, it defines every register in the MMA8452Q. Development environment specifics: IDE: Arduino 1.0.5 Hardware Platform: Arduino Uno This code is beerware; if you see me (or any other SparkFun employee) at the local, and you've found our code helpful, please buy us a round! Distributed as-is; no warranty is given. ******************************************************************************/ #ifndef MAG3110_h #define MAG3110_h #include <Arduino.h> //////////////////////////////// // MMA8452Q Misc Declarations // //////////////////////////////// //////////////////////////////// // MMA8452Q Class Declaration // //////////////////////////////// class MAG3110 { public: MAG3110(byte addr = 0x0E); // Constructor void init(); void read(); int x, y, z; float cx, cy, cz; private: uint8_t address; int read_axis(char axis); }; #endif
[ "ma701m@att.com" ]
ma701m@att.com
5ce65540022ac1b045c22a65f251d0f26b3d3c3c
a771d0b33e1ea4ebe98e7ca02f15e6c48043c3f2
/Source/U00_Portfolio/Player/C_PlayerAnimInstance.cpp
1628a33a46049c0ead466d01a62058fcc108abda
[]
no_license
midohvan/UnrealPortfolioSource
0b532097b9ce69e97cd54ba54b70ce4995a8b7fd
a85ee073d1f97ef36ebfe1efe2f9be53808124c2
refs/heads/master
2020-07-23T09:03:45.327090
2019-09-10T08:40:33
2019-09-10T08:40:33
207,507,698
0
0
null
null
null
null
UTF-8
C++
false
false
919
cpp
#include "C_PlayerAnimInstance.h" #include "C_Player.h" #include "C_PlayerController.h" #include "GameFramework/CharacterMovementComponent.h" void UC_PlayerAnimInstance::NativeUpdateAnimation(float Delta) { Super::NativeUpdateAnimation(Delta); APawn* pawn = TryGetPawnOwner(); player = Cast<AC_Player>(pawn); if (player == NULL) return; CController = Cast<AC_PlayerController>(player->GetController()); if (CController == NULL) return; Speed = CController->GetControlledPlayer()->GetVelocity().Size(); Direction = CalculateDirection(CController->GetControlledPlayer()->GetVelocity(), CController->GetControlledPlayer()->GetActorRotation()); bInAir = CController->GetControlledPlayer()->GetCharacterMovement()->IsFalling(); bDrawing = CController->GetDrawingWeapon(); bSheathing = CController->GetSheathingWeapon(); bDead = CController->GetDead(); bWeaponDrawn = CController->GetWeaponDrawn(); }
[ "48056296+midohvan@users.noreply.github.com" ]
48056296+midohvan@users.noreply.github.com
bae79da1e772d7ec1943f8487c1173c1f837803c
de9bc70cf11ae42ba7019fb7ae54905901df1e50
/ogldev-source/tutorial16/tutorial16.cpp
0735a3c370de9c2fe7e185a8e7df61a5d2a59c54
[]
no_license
jayzhen520/image-warping-morphing
09781beca9b2feea75d097a1dbf4e27d7cedcc01
c4549ef562c4e90d2ad38b6e5d07f3533558b8be
refs/heads/master
2016-09-05T19:32:49.991002
2015-09-06T10:00:52
2015-09-06T10:00:52
41,663,333
0
2
null
null
null
null
UTF-8
C++
false
false
7,188
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/>. Tutorial 16 - Basic Texture Mapping */ #include <stdio.h> #include <string.h> #include <assert.h> #include <math.h> #include <GL/glew.h> #include <GL/freeglut.h> #include "ogldev_util.h" #include "ogldev_glut_backend.h" #include "ogldev_pipeline.h" #include "ogldev_camera.h" #include "ogldev_texture.h" #define WINDOW_WIDTH 1280 #define WINDOW_HEIGHT 1024 struct Vertex { Vector3f m_pos; Vector2f m_tex; Vertex() {} Vertex(Vector3f pos, Vector2f tex) { m_pos = pos; m_tex = tex; } }; GLuint VBO; GLuint IBO; GLuint gWVPLocation; GLuint gSampler; Texture* pTexture = NULL; Camera* pGameCamera = NULL; PersProjInfo gPersProjInfo; const char* pVSFileName = "shader.vs"; const char* pFSFileName = "shader.fs"; static void RenderSceneCB() { pGameCamera->OnRender(); glClear(GL_COLOR_BUFFER_BIT); static float Scale = 0.0f; Scale += 0.1f; Pipeline p; p.Rotate(0.0f, Scale, 0.0f); p.WorldPos(0.0f, 0.0f, 3.0f); p.SetCamera(*pGameCamera); p.SetPerspectiveProj(gPersProjInfo); glUniformMatrix4fv(gWVPLocation, 1, GL_TRUE, (const GLfloat*)p.GetWVPTrans()); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glBindBuffer(GL_ARRAY_BUFFER, VBO); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid*)12); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO); pTexture->Bind(GL_TEXTURE0); glDrawElements(GL_TRIANGLES, 12, GL_UNSIGNED_INT, 0); glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); glutSwapBuffers(); } static void SpecialKeyboardCB(int Key, int x, int y) { OGLDEV_KEY OgldevKey = GLUTKeyToOGLDEVKey(Key); pGameCamera->OnKeyboard(OgldevKey); } static void KeyboardCB(unsigned char Key, int x, int y) { switch (Key) { case 'q': glutLeaveMainLoop(); } } static void PassiveMouseCB(int x, int y) { pGameCamera->OnMouse(x, y); } static void InitializeGlutCallbacks() { glutDisplayFunc(RenderSceneCB); glutIdleFunc(RenderSceneCB); glutSpecialFunc(SpecialKeyboardCB); glutPassiveMotionFunc(PassiveMouseCB); glutKeyboardFunc(KeyboardCB); } static void CreateVertexBuffer() { Vertex Vertices[4] = { Vertex(Vector3f(-1.0f, -1.0f, 0.5773f), Vector2f(0.0f, 0.0f)), Vertex(Vector3f(0.0f, -1.0f, -1.15475f), Vector2f(0.5f, 0.0f)), Vertex(Vector3f(1.0f, -1.0f, 0.5773f), Vector2f(1.0f, 0.0f)), Vertex(Vector3f(0.0f, 1.0f, 0.0f), Vector2f(0.5f, 1.0f)) }; glGenBuffers(1, &VBO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(Vertices), Vertices, GL_STATIC_DRAW); } static void CreateIndexBuffer() { unsigned int Indices[] = { 0, 3, 1, 1, 3, 2, 2, 3, 0, 0, 1, 2 }; glGenBuffers(1, &IBO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(Indices), Indices, GL_STATIC_DRAW); } static void AddShader(GLuint ShaderProgram, const char* pShaderText, GLenum ShaderType) { GLuint ShaderObj = glCreateShader(ShaderType); if (ShaderObj == 0) { fprintf(stderr, "Error creating shader type %d\n", ShaderType); exit(1); } const GLchar* p[1]; p[0] = pShaderText; GLint Lengths[1]; Lengths[0]= strlen(pShaderText); glShaderSource(ShaderObj, 1, p, Lengths); glCompileShader(ShaderObj); GLint success; glGetShaderiv(ShaderObj, GL_COMPILE_STATUS, &success); if (!success) { GLchar InfoLog[1024]; glGetShaderInfoLog(ShaderObj, 1024, NULL, InfoLog); fprintf(stderr, "Error compiling shader type %d: '%s'\n", ShaderType, InfoLog); exit(1); } glAttachShader(ShaderProgram, ShaderObj); } static void CompileShaders() { GLuint ShaderProgram = glCreateProgram(); if (ShaderProgram == 0) { fprintf(stderr, "Error creating shader program\n"); exit(1); } string vs, fs; if (!ReadFile(pVSFileName, vs)) { exit(1); }; if (!ReadFile(pFSFileName, fs)) { exit(1); }; AddShader(ShaderProgram, vs.c_str(), GL_VERTEX_SHADER); AddShader(ShaderProgram, fs.c_str(), GL_FRAGMENT_SHADER); GLint Success = 0; GLchar ErrorLog[1024] = { 0 }; glLinkProgram(ShaderProgram); glGetProgramiv(ShaderProgram, GL_LINK_STATUS, &Success); if (Success == 0) { glGetProgramInfoLog(ShaderProgram, sizeof(ErrorLog), NULL, ErrorLog); fprintf(stderr, "Error linking shader program: '%s'\n", ErrorLog); exit(1); } glValidateProgram(ShaderProgram); glGetProgramiv(ShaderProgram, GL_VALIDATE_STATUS, &Success); if (!Success) { glGetProgramInfoLog(ShaderProgram, sizeof(ErrorLog), NULL, ErrorLog); fprintf(stderr, "Invalid shader program: '%s'\n", ErrorLog); exit(1); } glUseProgram(ShaderProgram); gWVPLocation = glGetUniformLocation(ShaderProgram, "gWVP"); assert(gWVPLocation != 0xFFFFFFFF); gSampler = glGetUniformLocation(ShaderProgram, "gSampler"); assert(gSampler != 0xFFFFFFFF); } int main(int argc, char** argv) { // Magick::InitializeMagick(*argv); glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGBA); glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT); glutInitWindowPosition(100, 100); glutCreateWindow("Tutorial 16"); glutGameModeString("1280x1024@32"); // glutEnterGameMode(); InitializeGlutCallbacks(); pGameCamera = new Camera(WINDOW_WIDTH, WINDOW_HEIGHT); // Must be done after glut is initialized! GLenum res = glewInit(); if (res != GLEW_OK) { fprintf(stderr, "Error: '%s'\n", glewGetErrorString(res)); return 1; } glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glFrontFace(GL_CW); glCullFace(GL_BACK); glEnable(GL_CULL_FACE); CreateVertexBuffer(); CreateIndexBuffer(); CompileShaders(); glUniform1i(gSampler, 0); pTexture = new Texture(GL_TEXTURE_2D, "../Content/test.png"); if (!pTexture->Load()) { return 1; } gPersProjInfo.FOV = 60.0f; gPersProjInfo.Height = WINDOW_HEIGHT; gPersProjInfo.Width = WINDOW_WIDTH; gPersProjInfo.zNear = 1.0f; gPersProjInfo.zFar = 100.0f; glutMainLoop(); return 0; }
[ "jizhen@baozou.com" ]
jizhen@baozou.com
4e2e647f8747d36a192da663a42a0c3ad95300ee
30dd9ff200f97b525b069577471d23387b23970b
/src/sensing/driver/velodyne/velodyne_pointcloud/src/lib/rawdata.cc
97e8c384412bf53d89b25293cbf21b3c99837ce1
[ "BSD-3-Clause" ]
permissive
ColleyLi/AutowareArchitectureProposal
cd544ef913e3c49852d385883c3e3ee5b518b1b8
80ac2a8823d342e5a1e34703dbde27e8e9b5cd98
refs/heads/master
2022-04-18T01:41:53.649137
2020-04-21T12:18:58
2020-04-21T12:18:58
257,659,506
2
0
Apache-2.0
2020-04-21T17:03:50
2020-04-21T17:03:49
null
UTF-8
C++
false
false
29,807
cc
/* * Copyright 2015-2019 Autoware Foundation. 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. */ /* * Copyright (C) 2007 Austin Robot Technology, Patrick Beeson * Copyright (C) 2009, 2010, 2012 Austin Robot Technology, Jack O'Quin * * License: Modified BSD Software License Agreement * * $Id$ */ /** * @file * * Velodyne 3D LIDAR data accessor class implementation. * * Class for unpacking raw Velodyne LIDAR packets into useful * formats. * * Derived classes accept raw Velodyne data for either single packets * or entire rotations, and provide it in various formats for either * on-line or off-line processing. * * @author Patrick Beeson * @author Jack O'Quin * * HDL-64E S2 calibration support provided by Nick Hillier */ #include <math.h> #include <fstream> #include <angles/angles.h> #include <ros/package.h> #include <ros/ros.h> #include <velodyne_pointcloud/rawdata.h> namespace velodyne_rawdata { inline float SQR(float val) { return val * val; } //////////////////////////////////////////////////////////////////////// // // RawData base class implementation // //////////////////////////////////////////////////////////////////////// RawData::RawData() {} /** Update parameters: conversions and update */ void RawData::setParameters( double min_range, double max_range, double view_direction, double view_width) { config_.min_range = min_range; config_.max_range = max_range; //converting angle parameters into the velodyne reference (rad) config_.tmp_min_angle = view_direction + view_width / 2; config_.tmp_max_angle = view_direction - view_width / 2; //computing positive modulo to keep theses angles into [0;2*M_PI] config_.tmp_min_angle = fmod(fmod(config_.tmp_min_angle, 2 * M_PI) + 2 * M_PI, 2 * M_PI); config_.tmp_max_angle = fmod(fmod(config_.tmp_max_angle, 2 * M_PI) + 2 * M_PI, 2 * M_PI); //converting into the hardware velodyne ref (negative yaml and degrees) //adding 0.5 perfomrs a centered double to int conversion config_.min_angle = 100 * (2 * M_PI - config_.tmp_min_angle) * 180 / M_PI + 0.5; config_.max_angle = 100 * (2 * M_PI - config_.tmp_max_angle) * 180 / M_PI + 0.5; if (config_.min_angle == config_.max_angle) { //avoid returning empty cloud if min_angle = max_angle config_.min_angle = 0; config_.max_angle = 36000; } } int RawData::scansPerPacket() const { if (calibration_.num_lasers == 16) { return BLOCKS_PER_PACKET * VLP16_FIRINGS_PER_BLOCK * VLP16_SCANS_PER_FIRING; } else { return BLOCKS_PER_PACKET * SCANS_PER_BLOCK; } } int RawData::getNumLasers() const { return calibration_.num_lasers; } double RawData::getMaxRange() const { return config_.max_range; } double RawData::getMinRange() const { return config_.min_range; } /** Set up for on-line operation. */ int RawData::setup(ros::NodeHandle private_nh) { // get path to angles.config file for this device if (!private_nh.getParam("calibration", config_.calibrationFile)) { ROS_ERROR_STREAM("No calibration angles specified! Using test values!"); // have to use something: grab unit test version as a default std::string pkgPath = ros::package::getPath("velodyne_pointcloud"); config_.calibrationFile = pkgPath + "/params/64e_utexas.yaml"; } ROS_INFO_STREAM("correction angles: " << config_.calibrationFile); calibration_.read(config_.calibrationFile); if (!calibration_.initialized) { ROS_ERROR_STREAM("Unable to open calibration file: " << config_.calibrationFile); return -1; } ROS_INFO_STREAM("Number of lasers: " << calibration_.num_lasers << "."); // Set up cached values for sin and cos of all the possible headings for (uint16_t rot_index = 0; rot_index < ROTATION_MAX_UNITS; ++rot_index) { float rotation = angles::from_degrees(ROTATION_RESOLUTION * rot_index); cos_rot_table_[rot_index] = cosf(rotation); sin_rot_table_[rot_index] = sinf(rotation); } for (uint8_t i = 0; i < 16; i++) { vls_128_laser_azimuth_cache[i] = (VLS128_CHANNEL_TDURATION / VLS128_SEQ_TDURATION) * (i + i / 8); } return 0; } /** Set up for offline operation */ int RawData::setupOffline(std::string calibration_file, double max_range_, double min_range_) { config_.max_range = max_range_; config_.min_range = min_range_; ROS_INFO_STREAM( "data ranges to publish: [" << config_.min_range << ", " << config_.max_range << "]"); config_.calibrationFile = calibration_file; ROS_INFO_STREAM("correction angles: " << config_.calibrationFile); calibration_.read(config_.calibrationFile); if (!calibration_.initialized) { ROS_ERROR_STREAM("Unable to open calibration file: " << config_.calibrationFile); return -1; } // Set up cached values for sin and cos of all the possible headings for (uint16_t rot_index = 0; rot_index < ROTATION_MAX_UNITS; ++rot_index) { float rotation = angles::from_degrees(ROTATION_RESOLUTION * rot_index); cos_rot_table_[rot_index] = cosf(rotation); sin_rot_table_[rot_index] = sinf(rotation); } for (uint8_t i = 0; i < 16; i++) { vls_128_laser_azimuth_cache[i] = (VLS128_CHANNEL_TDURATION / VLS128_SEQ_TDURATION) * (i + i / 8); } return 0; } /** @brief convert raw packet to point cloud * * @param pkt raw packet to unpack * @param pc shared pointer to point cloud (points are appended) */ void RawData::unpack(const velodyne_msgs::VelodynePacket & pkt, DataContainerBase & data) { using velodyne_pointcloud::LaserCorrection; ROS_DEBUG_STREAM("Received packet, time: " << pkt.stamp); /** special parsing for the VLP16 **/ if (calibration_.num_lasers == 16) { unpack_vlp16(pkt, data); return; } const raw_packet_t * raw = (const raw_packet_t *)&pkt.data[0]; for (int i = 0; i < BLOCKS_PER_PACKET; i++) { // upper bank lasers are numbered [0..31] // NOTE: this is a change from the old velodyne_common implementation int bank_origin = 0; if (raw->blocks[i].header == LOWER_BANK) { // lower bank lasers are [32..63] bank_origin = 32; } /** special parsing for the VLS128 **/ else if (calibration_.num_lasers == 128) { unpack_vls128(pkt, data); return; } for (int j = 0, k = 0; j < SCANS_PER_BLOCK; j++, k += RAW_SCAN_SIZE) { float x, y, z; float intensity; const uint8_t laser_number = j + bank_origin; const LaserCorrection & corrections = calibration_.laser_corrections[laser_number]; /** Position Calculation */ const raw_block_t & block = raw->blocks[i]; union two_bytes tmp; tmp.bytes[0] = block.data[k]; tmp.bytes[1] = block.data[k + 1]; // if (tmp.bytes[0]==0 &&tmp.bytes[1]==0 ) //no laser beam return // { // continue; // } // float distance = tmp.uint * calibration_.distance_resolution_m; // distance += corrections.dist_correction; // if (!pointInRange(distance)) continue; /*condition added to avoid calculating points which are not in the interesting defined area (min_angle < area < max_angle)*/ if ( (block.rotation >= config_.min_angle && block.rotation <= config_.max_angle && config_.min_angle < config_.max_angle) || (config_.min_angle > config_.max_angle && (raw->blocks[i].rotation <= config_.max_angle || raw->blocks[i].rotation >= config_.min_angle))) { float distance = tmp.uint * calibration_.distance_resolution_m; bool is_invalid_distance = false; if (distance == 0.0) { is_invalid_distance = true; distance = 0.3; } else { distance += corrections.dist_correction; } float cos_vert_angle = corrections.cos_vert_correction; float sin_vert_angle = corrections.sin_vert_correction; float cos_rot_correction = corrections.cos_rot_correction; float sin_rot_correction = corrections.sin_rot_correction; // cos(a-b) = cos(a)*cos(b) + sin(a)*sin(b) // sin(a-b) = sin(a)*cos(b) - cos(a)*sin(b) float cos_rot_angle = cos_rot_table_[block.rotation] * cos_rot_correction + sin_rot_table_[block.rotation] * sin_rot_correction; float sin_rot_angle = sin_rot_table_[block.rotation] * cos_rot_correction - cos_rot_table_[block.rotation] * sin_rot_correction; float horiz_offset = corrections.horiz_offset_correction; float vert_offset = corrections.vert_offset_correction; // Compute the distance in the xy plane (w/o accounting for rotation) /**the new term of 'vert_offset * sin_vert_angle' * was added to the expression due to the mathemathical * model we used. */ float xy_distance = distance * cos_vert_angle - vert_offset * sin_vert_angle; // Calculate temporal X, use absolute value. float xx = xy_distance * sin_rot_angle - horiz_offset * cos_rot_angle; // Calculate temporal Y, use absolute value float yy = xy_distance * cos_rot_angle + horiz_offset * sin_rot_angle; if (xx < 0) xx = -xx; if (yy < 0) yy = -yy; // Get 2points calibration values,Linear interpolation to get distance // correction for X and Y, that means distance correction use // different value at different distance float distance_corr_x = 0; float distance_corr_y = 0; if (corrections.two_pt_correction_available) { distance_corr_x = (corrections.dist_correction - corrections.dist_correction_x) * (xx - 2.4) / (25.04 - 2.4) + corrections.dist_correction_x; distance_corr_x -= corrections.dist_correction; distance_corr_y = (corrections.dist_correction - corrections.dist_correction_y) * (yy - 1.93) / (25.04 - 1.93) + corrections.dist_correction_y; distance_corr_y -= corrections.dist_correction; } float distance_x = distance + distance_corr_x; /**the new term of 'vert_offset * sin_vert_angle' * was added to the expression due to the mathemathical * model we used. */ xy_distance = distance_x * cos_vert_angle - vert_offset * sin_vert_angle; ///the expression wiht '-' is proved to be better than the one with '+' x = xy_distance * sin_rot_angle - horiz_offset * cos_rot_angle; float distance_y = distance + distance_corr_y; xy_distance = distance_y * cos_vert_angle - vert_offset * sin_vert_angle; /**the new term of 'vert_offset * sin_vert_angle' * was added to the expression due to the mathemathical * model we used. */ y = xy_distance * cos_rot_angle + horiz_offset * sin_rot_angle; // Using distance_y is not symmetric, but the velodyne manual // does this. /**the new term of 'vert_offset * cos_vert_angle' * was added to the expression due to the mathemathical * model we used. */ z = distance_y * sin_vert_angle + vert_offset * cos_vert_angle; /** Use standard ROS coordinate system (right-hand rule) */ float x_coord = y; float y_coord = -x; float z_coord = z; /** Intensity Calculation */ float min_intensity = corrections.min_intensity; float max_intensity = corrections.max_intensity; intensity = raw->blocks[i].data[k + 2]; float focal_offset = 256 * (1 - corrections.focal_distance / 13100) * (1 - corrections.focal_distance / 13100); float focal_slope = corrections.focal_slope; intensity += focal_slope * (std::abs(focal_offset - 256 * SQR(1 - static_cast<float>(tmp.uint) / 65535))); intensity = (intensity < min_intensity) ? min_intensity : intensity; intensity = (intensity > max_intensity) ? max_intensity : intensity; double time_stamp = i * 55.296 / 1000.0 / 1000.0 + j * 2.304 / 1000.0 / 1000.0 + pkt.stamp.toSec(); if (is_invalid_distance) { data.addPoint( x_coord, y_coord, z_coord, corrections.laser_ring, raw->blocks[i].rotation, 0, intensity, time_stamp); } else { data.addPoint( x_coord, y_coord, z_coord, corrections.laser_ring, raw->blocks[i].rotation, distance, intensity, time_stamp); } } } } } /** @brief convert raw VLP16 packet to point cloud * * @param pkt raw packet to unpack * @param pc shared pointer to point cloud (points are appended) */ void RawData::unpack_vlp16(const velodyne_msgs::VelodynePacket & pkt, DataContainerBase & data) { float azimuth; float azimuth_diff; int raw_azimuth_diff; static float last_azimuth_diff = 0; float azimuth_corrected_f; int azimuth_corrected; float x, y, z; float intensity; const raw_packet_t * raw = (const raw_packet_t *)&pkt.data[0]; for (int block = 0; block < BLOCKS_PER_PACKET; block++) { // ignore packets with mangled or otherwise different contents if (UPPER_BANK != raw->blocks[block].header) { // Do not flood the log with messages, only issue at most one // of these warnings per minute. ROS_WARN_STREAM_THROTTLE( 60, "skipping invalid VLP-16 packet: block " << block << " header value is " << raw->blocks[block].header); return; // bad packet: skip the rest } // Calculate difference between current and next block's azimuth angle. azimuth = (float)(raw->blocks[block].rotation); if (block < (BLOCKS_PER_PACKET - 1)) { raw_azimuth_diff = raw->blocks[block + 1].rotation - raw->blocks[block].rotation; azimuth_diff = (float)((36000 + raw_azimuth_diff) % 36000); // // some packets contain an angle overflow where azimuth_diff < 0 // if(raw_azimuth_diff < 0)//raw->blocks[block+1].rotation - raw->blocks[block].rotation < 0) // { // ROS_WARN_STREAM_THROTTLE(60, "Packet containing angle overflow, first angle: " << raw->blocks[block].rotation << " second angle: " << raw->blocks[block+1].rotation); // // if last_azimuth_diff was not zero, we can assume that the velodyne's speed did not change very much and use the same difference // if(last_azimuth_diff > 0){ // azimuth_diff = last_azimuth_diff; // } // // otherwise we are not able to use this data // // TODO: we might just not use the second 16 firings // else{ // continue; // } // } last_azimuth_diff = azimuth_diff; } else { azimuth_diff = last_azimuth_diff; } for (int firing = 0, k = 0; firing < VLP16_FIRINGS_PER_BLOCK; firing++) { for (int dsr = 0; dsr < VLP16_SCANS_PER_FIRING; dsr++, k += RAW_SCAN_SIZE) { velodyne_pointcloud::LaserCorrection & corrections = calibration_.laser_corrections[dsr]; /** Position Calculation */ union two_bytes tmp; tmp.bytes[0] = raw->blocks[block].data[k]; tmp.bytes[1] = raw->blocks[block].data[k + 1]; // float distance = tmp.uint * calibration_.distance_resolution_m; // distance += corrections.dist_correction; // skip the point if out of range //if ( !pointInRange(distance)) continue; /** correct for the laser rotation as a function of timing during the firings **/ azimuth_corrected_f = azimuth + (azimuth_diff * ((dsr * VLP16_DSR_TOFFSET) + (firing * VLP16_FIRING_TOFFSET)) / VLP16_BLOCK_TDURATION); azimuth_corrected = ((int)round(azimuth_corrected_f)) % 36000; /*condition added to avoid calculating points which are not in the interesting defined area (min_angle < area < max_angle)*/ if ( (azimuth_corrected >= config_.min_angle && azimuth_corrected <= config_.max_angle && config_.min_angle < config_.max_angle) || (config_.min_angle > config_.max_angle && (azimuth_corrected <= config_.max_angle || azimuth_corrected >= config_.min_angle))) { // convert polar coordinates to Euclidean XYZ float distance = tmp.uint * calibration_.distance_resolution_m; bool is_invalid_distance = false; if (distance == 0.0) { is_invalid_distance = true; distance = 0.3; } else { distance += corrections.dist_correction; } float cos_vert_angle = corrections.cos_vert_correction; float sin_vert_angle = corrections.sin_vert_correction; float cos_rot_correction = corrections.cos_rot_correction; float sin_rot_correction = corrections.sin_rot_correction; // cos(a-b) = cos(a)*cos(b) + sin(a)*sin(b) // sin(a-b) = sin(a)*cos(b) - cos(a)*sin(b) float cos_rot_angle = cos_rot_table_[azimuth_corrected] * cos_rot_correction + sin_rot_table_[azimuth_corrected] * sin_rot_correction; float sin_rot_angle = sin_rot_table_[azimuth_corrected] * cos_rot_correction - cos_rot_table_[azimuth_corrected] * sin_rot_correction; float horiz_offset = corrections.horiz_offset_correction; float vert_offset = corrections.vert_offset_correction; // Compute the distance in the xy plane (w/o accounting for rotation) /**the new term of 'vert_offset * sin_vert_angle' * was added to the expression due to the mathemathical * model we used. */ float xy_distance = distance * cos_vert_angle - vert_offset * sin_vert_angle; // Calculate temporal X, use absolute value. float xx = xy_distance * sin_rot_angle - horiz_offset * cos_rot_angle; // Calculate temporal Y, use absolute value float yy = xy_distance * cos_rot_angle + horiz_offset * sin_rot_angle; if (xx < 0) xx = -xx; if (yy < 0) yy = -yy; // Get 2points calibration values,Linear interpolation to get distance // correction for X and Y, that means distance correction use // different value at different distance float distance_corr_x = 0; float distance_corr_y = 0; if (corrections.two_pt_correction_available) { distance_corr_x = (corrections.dist_correction - corrections.dist_correction_x) * (xx - 2.4) / (25.04 - 2.4) + corrections.dist_correction_x; distance_corr_x -= corrections.dist_correction; distance_corr_y = (corrections.dist_correction - corrections.dist_correction_y) * (yy - 1.93) / (25.04 - 1.93) + corrections.dist_correction_y; distance_corr_y -= corrections.dist_correction; } float distance_x = distance + distance_corr_x; /**the new term of 'vert_offset * sin_vert_angle' * was added to the expression due to the mathemathical * model we used. */ xy_distance = distance_x * cos_vert_angle - vert_offset * sin_vert_angle; x = xy_distance * sin_rot_angle - horiz_offset * cos_rot_angle; float distance_y = distance + distance_corr_y; /**the new term of 'vert_offset * sin_vert_angle' * was added to the expression due to the mathemathical * model we used. */ xy_distance = distance_y * cos_vert_angle - vert_offset * sin_vert_angle; y = xy_distance * cos_rot_angle + horiz_offset * sin_rot_angle; // Using distance_y is not symmetric, but the velodyne manual // does this. /**the new term of 'vert_offset * cos_vert_angle' * was added to the expression due to the mathemathical * model we used. */ z = distance_y * sin_vert_angle + vert_offset * cos_vert_angle; /** Use standard ROS coordinate system (right-hand rule) */ float x_coord = y; float y_coord = -x; float z_coord = z; /** Intensity Calculation */ float min_intensity = corrections.min_intensity; float max_intensity = corrections.max_intensity; intensity = raw->blocks[block].data[k + 2]; float focal_offset = 256 * SQR(1 - corrections.focal_distance / 13100); float focal_slope = corrections.focal_slope; intensity += focal_slope * (std::abs(focal_offset - 256 * SQR(1 - tmp.uint / 65535))); intensity = (intensity < min_intensity) ? min_intensity : intensity; intensity = (intensity > max_intensity) ? max_intensity : intensity; double time_stamp = (block * 2 + firing) * 55.296 / 1000.0 / 1000.0 + dsr * 2.304 / 1000.0 / 1000.0 + pkt.stamp.toSec(); if (is_invalid_distance) { data.addPoint( x_coord, y_coord, z_coord, corrections.laser_ring, azimuth_corrected, 0, intensity, time_stamp); } else { data.addPoint( x_coord, y_coord, z_coord, corrections.laser_ring, azimuth_corrected, distance, intensity, time_stamp); } } } } } } /** @brief convert raw VLS128 packet to point cloud * * @param pkt raw packet to unpack * @param pc shared pointer to point cloud (points are appended) */ // void RawData::unpack_vls128(const velodyne_msgs::VelodynePacket &pkt, DataContainerBase &data, const ros::Time& scan_start_time) { void RawData::unpack_vls128(const velodyne_msgs::VelodynePacket &pkt, DataContainerBase &data) { float last_azimuth_diff = 0; float azimuth_diff, azimuth_corrected_f; uint16_t azimuth, azimuth_next, azimuth_corrected; float x_coord, y_coord, z_coord; float distance, intensity; const raw_packet_t *raw = (const raw_packet_t *) &pkt.data[0]; union two_bytes tmp; // float time_diff_start_to_this_packet = (pkt.stamp - scan_start_time).toSec(); float cos_vert_angle, sin_vert_angle, cos_rot_correction, sin_rot_correction; float cos_rot_angle, sin_rot_angle; float xy_distance; uint8_t laser_number, firing_order; bool dual_return = (pkt.data[1204] == 57); for (int block = 0; block < BLOCKS_PER_PACKET - (4* dual_return); block++) { // cache block for use const raw_block_t &current_block = raw->blocks[block]; int bank_origin = 0; // Used to detect which bank of 32 lasers is in this block switch (current_block.header) { case VLS128_BANK_1: bank_origin = 0; break; case VLS128_BANK_2: bank_origin = 32; break; case VLS128_BANK_3: bank_origin = 64; break; case VLS128_BANK_4: bank_origin = 96; break; default: // ignore packets with mangled or otherwise different contents // Do not flood the log with messages, only issue at most one // of these warnings per minute. ROS_WARN_STREAM_THROTTLE(60, "skipping invalid VLS-128 packet: block " << block << " header value is " << raw->blocks[block].header); return; // bad packet: skip the rest } // Calculate difference between current and next block's azimuth angle. if (block == 0) { azimuth = current_block.rotation; } else { azimuth = azimuth_next; } if (block < (BLOCKS_PER_PACKET - (1+dual_return))) { // Get the next block rotation to calculate how far we rotate between blocks azimuth_next = raw->blocks[block + (1+dual_return)].rotation; // Finds the difference between two sucessive blocks azimuth_diff = (float)((36000 + azimuth_next - azimuth) % 36000); // This is used when the last block is next to predict rotation amount last_azimuth_diff = azimuth_diff; } else { // This makes the assumption the difference between the last block and the next packet is the // same as the last to the second to last. // Assumes RPM doesn't change much between blocks azimuth_diff = (block == BLOCKS_PER_PACKET - (4*dual_return)-1) ? 0 : last_azimuth_diff; } // condition added to avoid calculating points which are not in the interesting defined area (min_angle < area < max_angle) if ((config_.min_angle < config_.max_angle && azimuth >= config_.min_angle && azimuth <= config_.max_angle) || (config_.min_angle > config_.max_angle)) { for (int j = 0, k = 0; j < SCANS_PER_BLOCK; j++, k += RAW_SCAN_SIZE) { // distance extraction tmp.bytes[0] = current_block.data[k]; tmp.bytes[1] = current_block.data[k + 1]; if (tmp.bytes[0]==0 &&tmp.bytes[1]==0 ) //no laser beam return { continue; } // if (data.pointInRange(distance)) { { laser_number = j + bank_origin; // Offset the laser in this block by which block it's in firing_order = laser_number / 8; // VLS-128 fires 8 lasers at a time velodyne_pointcloud::LaserCorrection &corrections = calibration_.laser_corrections[laser_number]; distance = tmp.uint * VLP128_DISTANCE_RESOLUTION; bool is_invalid_distance = false; if(distance == 0.0) { is_invalid_distance = true; distance = 0.3; } else { distance += corrections.dist_correction; } // correct for the laser rotation as a function of timing during the firings azimuth_corrected_f = azimuth + (azimuth_diff * vls_128_laser_azimuth_cache[firing_order]); azimuth_corrected = ((uint16_t) round(azimuth_corrected_f)) % 36000; /*condition added to avoid calculating points which are not in the interesting defined area (min_angle < area < max_angle)*/ if ((azimuth_corrected >= config_.min_angle && azimuth_corrected <= config_.max_angle && config_.min_angle < config_.max_angle) ||(config_.min_angle > config_.max_angle && (azimuth_corrected <= config_.max_angle || azimuth_corrected >= config_.min_angle))){ // convert polar coordinates to Euclidean XYZ cos_vert_angle = corrections.cos_vert_correction; sin_vert_angle = corrections.sin_vert_correction; cos_rot_correction = corrections.cos_rot_correction; sin_rot_correction = corrections.sin_rot_correction; // cos(a-b) = cos(a)*cos(b) + sin(a)*sin(b) // sin(a-b) = sin(a)*cos(b) - cos(a)*sin(b) cos_rot_angle = cos_rot_table_[azimuth_corrected] * cos_rot_correction + sin_rot_table_[azimuth_corrected] * sin_rot_correction; sin_rot_angle = sin_rot_table_[azimuth_corrected] * cos_rot_correction - cos_rot_table_[azimuth_corrected] * sin_rot_correction; // Compute the distance in the xy plane (w/o accounting for rotation) xy_distance = distance * cos_vert_angle; /** Use standard ROS coordinate system (right-hand rule) */ // append this point to the cloud //VPoint point; //point.ring = corrections.laser_ring; //point.x = xy_distance * cos_rot_angle; // velodyne y //point.y = -(xy_distance * sin_rot_angle); // velodyne x //point.z = distance * sin_vert_angle; // velodyne z //// Intensity extraction //point.intensity = current_block.data[k + 2]; //pc.points.push_back(point); //++pc.width; x_coord = xy_distance * cos_rot_angle; // velodyne y y_coord = -(xy_distance * sin_rot_angle); // velodyne x z_coord = distance * sin_vert_angle; // velodyne z intensity = current_block.data[k + 2]; // float time = 0; // if (timing_offsets.size()) // time = timing_offsets[block][j] + time_diff_start_to_this_packet; double time_stamp = block * 55.3 / 1000.0 / 1000.0 + j * 2.665 / 1000.0 / 1000.0 + pkt.stamp.toSec(); if (is_invalid_distance) { data.addPoint(x_coord, y_coord, z_coord, corrections.laser_ring, azimuth_corrected, 0, intensity, time_stamp); } else { data.addPoint(x_coord, y_coord, z_coord, corrections.laser_ring, azimuth_corrected, distance, intensity, time_stamp); } } } } // data.newLine(); } } } } // namespace velodyne_rawdata
[ "yukky.saito@gmail.com" ]
yukky.saito@gmail.com
097874518f4fc3136efb9667c94ea4644aa9d3b4
d8e7a11322f6d1b514c85b0c713bacca8f743ff5
/7.6.00.37/V76_00_37/MaxDB_ORG/sys/src/ni/vni33.cpp
150715184248ea33cf4ebcafde4ea396de746c5b
[]
no_license
zhaonaiy/MaxDB_GPL_Releases
a224f86c0edf76e935d8951d1dd32f5376c04153
15821507c20bd1cd251cf4e7c60610ac9cabc06d
refs/heads/master
2022-11-08T21:14:22.774394
2020-07-07T00:52:44
2020-07-07T00:52:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
53,577
cpp
/*!***************************************************************************** module: vni33.cpp ------------------------------------------------------------------------------ responsible: TiloH special area: ni layer description: implementation of classes for process handling last change: 1999-10-04 15:33 version: 7.2 see also: ------------------------------------------------------------------------------ Copyright (c) 1999-2005 SAP AG ========== licence begin GPL Copyright (c) 1999-2005 SAP AG 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, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. ========== licence end *******************************************************************************/ // ----------------------------------------------------------------------------- // includes // ----------------------------------------------------------------------------- #include"hni33.h" #include"hni35.h" #include<string.h> #include<ctype.h> #include<stdio.h> #if defined (WIN32) #elif defined (UNIX) #include<stdlib.h> #include<unistd.h> #include<sys/wait.h> #include<fcntl.h> #include<sys/types.h> #include<signal.h> #include<errno.h> #else #error hni33.cpp only coded for WIN32 and UNIX (Define one of them.) #endif // ----------------------------------------------------------------------------- // private function: ni33IsWhiteSpace // // description : decides that the argument is a white space character or not // arguments : c [in] character to check // return value: 1 if c is a white space, 0 if it is not // ----------------------------------------------------------------------------- static int ni33IsWhiteSpace(char c) { return isspace((int)c); } // ----------------------------------------------------------------------------- // implementation of class tni33_ArgumentList // ----------------------------------------------------------------------------- tni33_ArgumentList::tni33_ArgumentList() :NumberOfArguments(0), LastArgument(0), CommandLine(0), NumberOfArgumentsOfCurrentCommandLine(0) { } tni33_ArgumentList::~tni33_ArgumentList() { DeleteAll(); } int tni33_ArgumentList::AddArgument(const char * NewArgument) { return AddArgument(NewArgument, strlen(NewArgument)); } int tni33_ArgumentList::AddArgument(const char * NewArgument, size_t NewArgumentLength) { int rc=0; char * CopyOfNewArgument=new char [NewArgumentLength+1]; if(0!=CopyOfNewArgument) { ni31_ListElem<char *> * NewLastArgument; strncpy(CopyOfNewArgument, NewArgument, NewArgumentLength); CopyOfNewArgument[NewArgumentLength]='\0'; if(0==LastArgument) NewLastArgument=Arguments.Add(CopyOfNewArgument); else NewLastArgument=Arguments.Add(CopyOfNewArgument, *LastArgument); if(0==NewLastArgument) { ErrorHandler_ni35->Report(tni35_AStandardError::OutOfMemory); //not enough memory for the list element pointing to the string delete [] CopyOfNewArgument; //last chance to delete the memory reserved above } else { LastArgument=NewLastArgument; NumberOfArguments++; rc=1; } } else ErrorHandler_ni35->Report(tni35_AStandardError::OutOfMemory); return rc; } void tni33_ArgumentList::DeleteAll() { ni31_ListElem<char *> *h; for(h=Arguments.First(); 0!=h; h=h->Next()) delete [] h->GiveInfo(); //delete the strings the list elements are pointing to Arguments.DelAll(); //delete the list elements itself if(0!=CommandLine) { delete [] CommandLine; CommandLine=0; } NumberOfArguments=0; LastArgument=0; NumberOfArgumentsOfCurrentCommandLine=0; } int tni33_ArgumentList::ConstructCommandLine() { int rc=1; size_t Length=0; ni31_ListElem<char *> * ArgListElem; if(0!=CommandLine) { delete [] CommandLine; CommandLine=0; } NumberOfArgumentsOfCurrentCommandLine=0; for(ArgListElem=Arguments.First(); 0!=ArgListElem; ArgListElem=ArgListElem->Next()) { const char * CurrentArgument=ArgListElem->GiveInfo(); int FoundASpace=0; Length+=strlen(CurrentArgument); // we will only add something to the argument string int FoundBackslashes=0; for(; '\0'!=(*CurrentArgument); CurrentArgument++) //as long as we have not reached the end of the argument string { if('\\'==(*CurrentArgument)) //a backslash must only masked on NT by a backslash if it (or a row of backslashes) is followed by a '\"' FoundBackslashes++; else { if('\"'==(*CurrentArgument)) //if a qoute is Length+=FoundBackslashes+1; //have to place a backslashes in front of any backslash and one backslash in front of the '\"' else { if(ni33IsWhiteSpace(*CurrentArgument)) FoundASpace=1; #if defined (UNIX) Length+=FoundBackslashes; //double every backslashe found on UNIX (also if not terminated by a '\"') #elif defined (WIN32) #else #error tni33_ArgumentList::CreateArgumentString() not coded for this operating system! #endif } FoundBackslashes=0; //the row of backslashes was terminated, so other backslashes count for themself } } #if defined (UNIX) Length+=FoundBackslashes; ///double every backslashe found on UNIX (also if at the end of the string) #elif defined (WIN32) #else #error tni33_ArgumentList::CreateArgumentString() not coded for this operating system! #endif if(FoundASpace) Length+=2; //must put an argument with white spaces in quotes Length+=1; //put a ' ' between two arguments } if(0!=Length) { CommandLine=new char[Length]; //allocate memory for the string, not Length+1 because we have computed space for a ' ' after every argument if(0==CommandLine) { rc=0; ErrorHandler_ni35->Report(tni35_AStandardError::OutOfMemory); } else { char * CurrentPosition=CommandLine; for(ArgListElem=Arguments.First(); 0!=ArgListElem; ArgListElem=ArgListElem->Next()) { const char * CurrentArgument; int FoundASpace=0; int FoundBackslashes=0; for(CurrentArgument=ArgListElem->GiveInfo(); '\0'!=(*CurrentArgument) && 0==FoundASpace; CurrentArgument++) { if(ni33IsWhiteSpace(*CurrentArgument)) FoundASpace=1; } if(FoundASpace) *(CurrentPosition++)='\"'; for(CurrentArgument=ArgListElem->GiveInfo(); '\0'!=(*CurrentArgument); CurrentArgument++) //as long as we have not reached the end of the argument string { if('\\'==(*CurrentArgument)) //a backslash must only masked on NT by a backslash if it (or a row of backslashes) is followed by a '\"' FoundBackslashes++; else { if('\"'==(*CurrentArgument)) //if a qoute is { memset(CurrentPosition, '\\', FoundBackslashes); CurrentPosition+=FoundBackslashes; *(CurrentPosition++)='\\'; } else { #if defined (UNIX) if(0<FoundBackslashes) { memset(CurrentPosition, '\\', FoundBackslashes); CurrentPosition+=FoundBackslashes; } #elif defined (WIN32) #else #error tni33_ArgumentList::CreateArgumentString() not coded for this operating system! #endif } FoundBackslashes=0; //the row of backslashes was terminated, so other backslashes count for themself } *(CurrentPosition++)=(*CurrentArgument); //copy the character itself } #if defined (UNIX) if(0<FoundBackslashes) { memset(CurrentPosition, '\\', FoundBackslashes); CurrentPosition+=FoundBackslashes; } #elif defined (WIN32) #else #error tni33_ArgumentList::CreateArgumentString() not coded for this operating system! #endif if(FoundASpace) *(CurrentPosition++)='\"'; *(CurrentPosition++)=' '; } *(CurrentPosition-1)='\0'; //the last arguments ' ' is replaced with the terminating zero if(Length-1!=strlen(CommandLine)) { rc=0; ErrorHandler_ni35->Report(tni35_AStandardError(tni35_AStandardError::CaseInternalError)); } } } else { CommandLine=new char [1]; if(0==CommandLine) { rc=0; ErrorHandler_ni35->Report(tni35_AStandardError::OutOfMemory); } else CommandLine[0]='\0'; } if(rc) NumberOfArgumentsOfCurrentCommandLine=NumberOfArguments; return rc; } const char * tni33_ArgumentList::GiveCommandLine() { if(0==CommandLine || NumberOfArgumentsOfCurrentCommandLine!=NumberOfArguments) ConstructCommandLine(); return CommandLine; } const char * tni33_ArgumentList::GiveArgument(int Number) { const char *rc; if(0<=Number) rc=Arguments[(unsigned)Number]->GiveInfo(); else rc=0; return rc; } // ----------------------------------------------------------------------------- // implementation of class tni33_ABackgroundProcess // ----------------------------------------------------------------------------- tni33_ABackgroundProcess::tni33_ABackgroundProcess(const char * Cmdline, const tni34_AFile * StdIn, const tni34_AFile * StdOut, const int AppendStdOut, const tni34_AFile * StdErr, const int AppendStdErr, const bool DetachConsoleAtWindows) { InitAndStartBackgroundProcess(Cmdline, StdIn, 1, StdOut, AppendStdOut, 1, StdErr, AppendStdErr, 1, DetachConsoleAtWindows); } tni33_ABackgroundProcess::tni33_ABackgroundProcess(const char * Cmdline, const tni34_AFile * StdIn, const tni34_APipe * StdOut, const int AppendStdOut, const tni34_AFile * StdErr, const int AppendStdErr, const bool DetachConsoleAtWindows) { InitAndStartBackgroundProcess(Cmdline, StdIn, 1, StdOut, AppendStdOut, 0, StdErr, AppendStdErr, 1, DetachConsoleAtWindows); } tni33_ABackgroundProcess::tni33_ABackgroundProcess(const char * Cmdline, const tni34_APipe * StdIn, const tni34_AFile * StdOut, const int AppendStdOut, const tni34_AFile * StdErr, const int AppendStdErr, const bool DetachConsoleAtWindows) { InitAndStartBackgroundProcess(Cmdline, StdIn, 0, StdOut, AppendStdOut, 1, StdErr, AppendStdErr, 1, DetachConsoleAtWindows); } tni33_ABackgroundProcess::tni33_ABackgroundProcess(const char * Cmdline, const tni34_APipe * StdIn, const tni34_APipe * StdOut, const int AppendStdOut, const tni34_AFile * StdErr, const int AppendStdErr, const bool DetachConsoleAtWindows) { InitAndStartBackgroundProcess(Cmdline, StdIn, 0, StdOut, AppendStdOut, 0, StdErr, AppendStdErr, 1, DetachConsoleAtWindows); } tni33_ABackgroundProcess::tni33_ABackgroundProcess(tni33_ArgumentList & Arguments, const tni34_AFile * StdIn, const tni34_AFile * StdOut, const int AppendStdOut, const tni34_AFile * StdErr, const int AppendStdErr, const bool DetachConsoleAtWindows) { InitAndStartBackgroundProcess(Arguments, StdIn, 1, StdOut, AppendStdOut, 1, StdErr, AppendStdErr, 1, DetachConsoleAtWindows); } void tni33_ABackgroundProcess::InitAndStartBackgroundProcess(const char * Cmdline, const tni34_ADataEntry * StdIn, const int StdInIsFile, const tni34_ADataEntry * StdOut, const int AppendStdOut, const int StdOutIsFile, const tni34_AFile * StdErr, const int AppendStdErr, const int StdErrIsFile, const bool DetachConsoleAtWindows) { m_Pid = RTE_UNDEF_OSPID; Process=AInvalidProcessHandle_ni33; RetCode=InvalidReturnCode_ni33; #if defined (WIN32) Thread=AInvalidProcessHandle_ni33; StandardInHandle=INVALID_HANDLE_VALUE; StandardOutHandle=INVALID_HANDLE_VALUE; StandardErrorHandle=INVALID_HANDLE_VALUE; OpenedStandardInHandle=0; OpenedStandardOutHandle=0; OpenedStandardErrorHandle=0; StandardInIsFile=StdInIsFile; StandardOutIsFile=StdOutIsFile; StandardErrorIsFile=StdErrIsFile; #elif defined (UNIX) #else #error tni33_ABackgroundProcess::tni33_ABackgroundProcess() not coded for this operating system! #endif if(0==(CommandLine=new char[strlen(Cmdline)+1])) ErrorHandler_ni35->Report(tni35_AStandardError::OutOfMemory); else { strcpy(CommandLine, Cmdline); #if defined (WIN32) SECURITY_ATTRIBUTES SecurityAttrib={sizeof(SECURITY_ATTRIBUTES), 0, TRUE}; if(0!=StdIn) { StandardInHandle=CreateFile(StdIn->GiveName(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, & SecurityAttrib, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); OpenedStandardInHandle=1; } else StandardInHandle=GetStdHandle(STD_INPUT_HANDLE); if(INVALID_HANDLE_VALUE==StandardInHandle) ErrorHandler_ni35->Report(tni35_AStandardError(tni35_AStandardError::CaseCouldNotCreateChildProcess, CommandLine)); else { if(0!=StdOut) { StandardOutHandle=CreateFile(StdOut->GiveName(), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, & SecurityAttrib, AppendStdOut==0 ? CREATE_ALWAYS : OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); OpenedStandardOutHandle=1; if(AppendStdOut && INVALID_HANDLE_VALUE!=StandardOutHandle && 0xFFFFFFFF==SetFilePointer(StandardOutHandle, 0, 0, FILE_END)) { CloseHandle(StandardOutHandle); StandardOutHandle=INVALID_HANDLE_VALUE; } } else StandardOutHandle=GetStdHandle(STD_OUTPUT_HANDLE); if(INVALID_HANDLE_VALUE==StandardOutHandle) ErrorHandler_ni35->Report(tni35_AStandardError(tni35_AStandardError::CaseCouldNotCreateChildProcess, CommandLine)); else { if(0!=StdErr) { StandardErrorHandle=CreateFile(StdErr->GiveName(), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, & SecurityAttrib, AppendStdOut==0 ? CREATE_ALWAYS : OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); OpenedStandardErrorHandle=1; if(AppendStdErr && INVALID_HANDLE_VALUE!=StandardErrorHandle && 0xFFFFFFFF==SetFilePointer(StandardErrorHandle, 0, 0, FILE_END)) { CloseHandle(StandardErrorHandle); StandardErrorHandle=INVALID_HANDLE_VALUE; } } else StandardErrorHandle=GetStdHandle(STD_ERROR_HANDLE); if(INVALID_HANDLE_VALUE==StandardErrorHandle) ErrorHandler_ni35->Report(tni35_AStandardError(tni35_AStandardError::CaseCouldNotCreateChildProcess, CommandLine)); else { STARTUPINFO si={DWORD(sizeof(STARTUPINFO)), LPTSTR(0), LPTSTR(0), LPTSTR(0), DWORD(0), DWORD(0), DWORD(0), DWORD(0), DWORD(0), DWORD(0), DWORD(0), STARTF_USESTDHANDLES, WORD(0), WORD(0), LPBYTE(0), StandardInHandle, StandardOutHandle, StandardErrorHandle}; PROCESS_INFORMATION pi; if(!CreateProcess(0, CommandLine, 0, 0, TRUE, (DetachConsoleAtWindows?DETACHED_PROCESS:0)|CREATE_NO_WINDOW, 0, 0, &si, &pi)) { ErrorHandler_ni35->Report(tni35_AStandardError(tni35_AStandardError::CaseCouldNotCreateChildProcess,CommandLine)); Process=AInvalidProcessHandle_ni33; } else { Process=pi.hProcess; Thread=pi.hThread; m_Pid = pi.dwProcessId; } } } } AdjustFileHandles(); //regardless if the new process was started or not, the file handles we got, should be adjusted, before further child's are created #elif defined (UNIX) int argc=0,p=0; while(CommandLine[p]!=0 && ni33IsWhiteSpace(CommandLine[p])) p++; while(CommandLine[p]!=0) { while(CommandLine[p]!=0 && !ni33IsWhiteSpace(CommandLine[p])) p++; argc++; while(CommandLine[p]!=0 && ni33IsWhiteSpace(CommandLine[p])) p++; } if(argc<=0) { ErrorHandler_ni35->Report(tni35_AStandardError(tni35_AStandardError::CaseCouldNotCreateChildProcess,CommandLine)); Process=AInvalidProcessHandle_ni33; } else { char **Arguments=new char * [argc+1]; if(0==Arguments) { ErrorHandler_ni35->Report(tni35_AStandardError::OutOfMemory); Process=AInvalidProcessHandle_ni33; } else { int i=0; for(i=0;i<=argc;i++) Arguments[i]=0; p=0; i=0; while(CommandLine[p]!=0 && ni33IsWhiteSpace(CommandLine[p])) p++; int p1,ErrorOccured=0; while(CommandLine[p]!=0 && !ErrorOccured) { p1=p; while(CommandLine[p1]!=0 && !ni33IsWhiteSpace(CommandLine[p1])) p1++; if(0==(Arguments[i]=new char [p1-p+1])) { ErrorHandler_ni35->Report(tni35_AStandardError::OutOfMemory); Process=AInvalidProcessHandle_ni33; ErrorOccured=1; } else { strncpy(Arguments[i],CommandLine+p,p1-p); Arguments[i++][p1-p]=0; p=p1; while(CommandLine[p]!=0 && ni33IsWhiteSpace(CommandLine[p])) p++; } } if(!ErrorOccured) { fflush(stdout); //empty any buffer used for stdout before forking (otherwise previous output can be duplicated) fflush(stderr); //empty any buffer used for stderr (seems not to be necessary, but should not hurt) if((Process=fork())<0) { ErrorHandler_ni35->Report(tni35_AStandardError(tni35_AStandardError::CaseCouldNotCreateChildProcess,CommandLine)); Process=AInvalidProcessHandle_ni33; } else if(Process==0) // following code is executed only by the child process { int GotAllFileDescriptors=1; int Desc; if(0!=StdIn) { fclose(stdin); if(0!=(Desc=open(StdIn->GiveName(), O_RDONLY))) { ErrorHandler_ni35->Report(tni35_AStandardError(tni35_AStandardError::CaseCouldNotCreateChildProcess, CommandLine)); Process=AInvalidProcessHandle_ni33; GotAllFileDescriptors=0; } } if(GotAllFileDescriptors && 0!=StdOut) { fclose(stdout); if(AppendStdOut) Desc=open(StdOut->GiveName(), O_WRONLY|O_APPEND); else Desc=open(StdOut->GiveName(), O_WRONLY|O_TRUNC); if(1!=Desc) { ErrorHandler_ni35->Report(tni35_AStandardError(tni35_AStandardError::CaseCouldNotCreateChildProcess, CommandLine)); Process=AInvalidProcessHandle_ni33; GotAllFileDescriptors=0; } } if(GotAllFileDescriptors && 0!=StdErr) { fclose(stderr); if(AppendStdErr) Desc=open(StdErr->GiveName(), O_WRONLY|O_APPEND); else Desc=open(StdErr->GiveName(), O_WRONLY|O_TRUNC); if(2!=Desc) { ErrorHandler_ni35->Report(tni35_AStandardError(tni35_AStandardError::CaseCouldNotCreateChildProcess, CommandLine)); Process=AInvalidProcessHandle_ni33; GotAllFileDescriptors=0; } } if(GotAllFileDescriptors) { char *ProgramName=Arguments[0]; execvp(ProgramName,Arguments); //coming to this point means, that an error occurred. Report the reason and end the child-process. ErrorHandler_ni35->Report(tni35_AStandardError(tni35_AStandardError::CaseCouldNotCreateChildProcess,CommandLine)); exit(1); } else exit(1); // could not change StdIn, StdOut or StdErr for the child as requested, error was allready reported } else { // executed by parent only m_Pid = Process; } } for(i=0;i<argc;i++) if(Arguments[i]!=0) delete [] (Arguments[i]); delete [] Arguments; } } #else #error tni33_ABackgroundProcess::tni33_ABackgroundProcess not coded for this operating system! #endif } if(AInvalidProcessHandle_ni33==Process) State=NotStarted; else State=Started; if(State!=Started) // do not block the file handles if the process could not be started FreeFileHandles(); } void tni33_ABackgroundProcess::InitAndStartBackgroundProcess(tni33_ArgumentList & Arguments, const tni34_ADataEntry * StdIn, const int StdInIsFile, const tni34_ADataEntry * StdOut, const int AppendStdOut, const int StdOutIsFile, const tni34_AFile * StdErr, const int AppendStdErr, const int StdErrIsFile, const bool DetachConsoleAtWindows) { m_Pid = RTE_UNDEF_OSPID; Process=AInvalidProcessHandle_ni33; RetCode=InvalidReturnCode_ni33; #if defined (WIN32) Thread=AInvalidProcessHandle_ni33; StandardInHandle=INVALID_HANDLE_VALUE; StandardOutHandle=INVALID_HANDLE_VALUE; StandardErrorHandle=INVALID_HANDLE_VALUE; OpenedStandardInHandle=0; OpenedStandardOutHandle=0; OpenedStandardErrorHandle=0; StandardInIsFile=StdInIsFile; StandardOutIsFile=StdOutIsFile; StandardErrorIsFile=StdErrIsFile; #elif defined (UNIX) #else #error tni33_ABackgroundProcess::InitAndStartBackgroundProcess() not coded for this operating system! #endif if(Arguments.ConstructCommandLine()) { if(0==(CommandLine=new char[strlen(Arguments.GiveCommandLine())+1])) ErrorHandler_ni35->Report(tni35_AStandardError::OutOfMemory); else { strcpy(CommandLine, Arguments.GiveCommandLine()); //make a copy of the command line Windows can play with and which is available later in the object #if defined (WIN32) SECURITY_ATTRIBUTES SecurityAttrib={sizeof(SECURITY_ATTRIBUTES), 0, TRUE}; if(0!=StdIn) { StandardInHandle=CreateFile(StdIn->GiveName(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, & SecurityAttrib, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); OpenedStandardInHandle=1; } else StandardInHandle=GetStdHandle(STD_INPUT_HANDLE); if(INVALID_HANDLE_VALUE==StandardInHandle) ErrorHandler_ni35->Report(tni35_AStandardError(tni35_AStandardError::CaseCouldNotCreateChildProcess, CommandLine)); else { if(0!=StdOut) { StandardOutHandle=CreateFile(StdOut->GiveName(), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, & SecurityAttrib, AppendStdOut==0 ? CREATE_ALWAYS : OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); OpenedStandardOutHandle=1; if(AppendStdOut && INVALID_HANDLE_VALUE!=StandardOutHandle && 0xFFFFFFFF==SetFilePointer(StandardOutHandle, 0, 0, FILE_END)) { CloseHandle(StandardOutHandle); StandardOutHandle=INVALID_HANDLE_VALUE; } } else StandardOutHandle=GetStdHandle(STD_OUTPUT_HANDLE); if(INVALID_HANDLE_VALUE==StandardOutHandle) ErrorHandler_ni35->Report(tni35_AStandardError(tni35_AStandardError::CaseCouldNotCreateChildProcess, CommandLine)); else { if(0!=StdErr) { StandardErrorHandle=CreateFile(StdErr->GiveName(), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, & SecurityAttrib, AppendStdOut==0 ? CREATE_ALWAYS : OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); OpenedStandardErrorHandle=1; if(AppendStdErr && INVALID_HANDLE_VALUE!=StandardErrorHandle && 0xFFFFFFFF==SetFilePointer(StandardErrorHandle, 0, 0, FILE_END)) { CloseHandle(StandardErrorHandle); StandardErrorHandle=INVALID_HANDLE_VALUE; } } else StandardErrorHandle=GetStdHandle(STD_ERROR_HANDLE); if(INVALID_HANDLE_VALUE==StandardErrorHandle) ErrorHandler_ni35->Report(tni35_AStandardError(tni35_AStandardError::CaseCouldNotCreateChildProcess, CommandLine)); else { STARTUPINFO si={DWORD(sizeof(STARTUPINFO)), LPTSTR(0), LPTSTR(0), LPTSTR(0), DWORD(0), DWORD(0), DWORD(0), DWORD(0), DWORD(0), DWORD(0), DWORD(0), STARTF_USESTDHANDLES, WORD(0), WORD(0), LPBYTE(0), StandardInHandle, StandardOutHandle, StandardErrorHandle}; PROCESS_INFORMATION pi; if(!CreateProcess(0, CommandLine, 0, 0, TRUE, (DetachConsoleAtWindows?DETACHED_PROCESS:0)|CREATE_NO_WINDOW, 0, 0, &si, &pi)) { ErrorHandler_ni35->Report(tni35_AStandardError(tni35_AStandardError::CaseCouldNotCreateChildProcess,CommandLine)); Process=AInvalidProcessHandle_ni33; } else { Process=pi.hProcess; Thread=pi.hThread; m_Pid = pi.dwProcessId; } } } } AdjustFileHandles(); //regardless if the new process was started or not, the file handles we got, should be adjusted, before further child's are created #elif defined (UNIX) int argc=Arguments.GiveNumberOfArguments(); if(argc<=0) { ErrorHandler_ni35->Report(tni35_AStandardError(tni35_AStandardError::CaseCouldNotCreateChildProcess,CommandLine)); Process=AInvalidProcessHandle_ni33; } else { char **Args=new char * [argc+1]; if(0==Args) { ErrorHandler_ni35->Report(tni35_AStandardError::OutOfMemory); Process=AInvalidProcessHandle_ni33; } else { int i=0, ErrorOccured=0; for(i=0; i<=argc; i++) Args[i]=0; for(i=0; !ErrorOccured && i<argc; i++) { Args[i]=new char [strlen(Arguments.GiveArgument(i))+1]; if(0==Args[i]) { ErrorHandler_ni35->Report(tni35_AStandardError::OutOfMemory); Process=AInvalidProcessHandle_ni33; ErrorOccured=1; } else strcpy(Args[i], Arguments.GiveArgument(i)); } if(!ErrorOccured) { fflush(stdout); //empty any buffer used for stdout before forking (otherwise previous output can be duplicated) fflush(stderr); //empty any buffer used for stderr (seems not to be necessary, but should not hurt) if((Process=fork())<0) { ErrorHandler_ni35->Report(tni35_AStandardError(tni35_AStandardError::CaseCouldNotCreateChildProcess,CommandLine)); Process=AInvalidProcessHandle_ni33; } else if(Process==0) // following code is executed only by the child process { int GotAllFileDescriptors=1; int Desc; if(0!=StdIn) { fclose(stdin); if(0!=(Desc=open(StdIn->GiveName(), O_RDONLY))) { ErrorHandler_ni35->Report(tni35_AStandardError(tni35_AStandardError::CaseCouldNotCreateChildProcess, CommandLine)); Process=AInvalidProcessHandle_ni33; GotAllFileDescriptors=0; } } if(GotAllFileDescriptors && 0!=StdOut) { fclose(stdout); if(AppendStdOut) Desc=open(StdOut->GiveName(), O_WRONLY|O_APPEND); else Desc=open(StdOut->GiveName(), O_WRONLY|O_TRUNC); if(1!=Desc) { ErrorHandler_ni35->Report(tni35_AStandardError(tni35_AStandardError::CaseCouldNotCreateChildProcess, CommandLine)); Process=AInvalidProcessHandle_ni33; GotAllFileDescriptors=0; } } if(GotAllFileDescriptors && 0!=StdErr) { fclose(stderr); if(AppendStdErr) Desc=open(StdErr->GiveName(), O_WRONLY|O_APPEND); else Desc=open(StdErr->GiveName(), O_WRONLY|O_TRUNC); if(2!=Desc) { ErrorHandler_ni35->Report(tni35_AStandardError(tni35_AStandardError::CaseCouldNotCreateChildProcess, CommandLine)); Process=AInvalidProcessHandle_ni33; GotAllFileDescriptors=0; } } if(GotAllFileDescriptors) { const char *ProgramName=Args[0]; execvp(ProgramName, Args); //coming to this point means, that an error occurred. Report the reason and end the child-process. ErrorHandler_ni35->Report(tni35_AStandardError(tni35_AStandardError::CaseCouldNotCreateChildProcess,CommandLine)); exit(1); } else exit(1); // could not change StdIn, StdOut or StdErr for the child as requested, error was allready reported } else { // executed by parent only m_Pid = Process; } } for(i=0; i<argc; i++) if(0!=Args[i]) delete [] (Args[i]); delete [] Args; } } #else #error tni33_ABackgroundProcess::tni33_ABackgroundProcess not coded for this operating system! #endif } } if(AInvalidProcessHandle_ni33==Process) State=NotStarted; else State=Started; if(State!=Started) // do not block the file handles if the process could not be started FreeFileHandles(); } int tni33_ABackgroundProcess::AdjustFileHandles() { int rc=1; #if defined (WIN32) if(OpenedStandardInHandle && INVALID_HANDLE_VALUE!=StandardInHandle && 0==SetHandleInformation(StandardInHandle, HANDLE_FLAG_INHERIT, !HANDLE_FLAG_INHERIT)) { ErrorHandler_ni35->Report(tni35_AStandardError(tni35_AStandardError::CaseCouldNotSetHandleInformation, "standard in")); rc=0; } if(OpenedStandardOutHandle && INVALID_HANDLE_VALUE!=StandardOutHandle && 0==SetHandleInformation(StandardOutHandle, HANDLE_FLAG_INHERIT, !HANDLE_FLAG_INHERIT)) { ErrorHandler_ni35->Report(tni35_AStandardError(tni35_AStandardError::CaseCouldNotSetHandleInformation, "standard out")); rc=0; } if(OpenedStandardErrorHandle && INVALID_HANDLE_VALUE!=StandardErrorHandle && 0==SetHandleInformation(StandardErrorHandle, HANDLE_FLAG_INHERIT, !HANDLE_FLAG_INHERIT)) { ErrorHandler_ni35->Report(tni35_AStandardError(tni35_AStandardError::CaseCouldNotSetHandleInformation, "standard error")); rc=0; } #elif defined (UNIX) #else #error tni33_ABackgroundProcess::AdjustFileHandles() not coded for this operating system! #endif return rc; } void tni33_ABackgroundProcess::FreeFileHandles() { #if defined (WIN32) if(OpenedStandardInHandle && INVALID_HANDLE_VALUE!=StandardInHandle) //close StandardInHandle also if it is a pipe (we get here only if the processes is dead already) { CloseHandle(StandardInHandle); StandardInHandle=INVALID_HANDLE_VALUE; // don't close it again } if(StandardOutIsFile && OpenedStandardOutHandle && INVALID_HANDLE_VALUE!=StandardOutHandle) { CloseHandle(StandardOutHandle); StandardOutHandle=INVALID_HANDLE_VALUE; // don't close it again } if(StandardErrorIsFile && OpenedStandardErrorHandle && INVALID_HANDLE_VALUE!=StandardErrorHandle) { CloseHandle(StandardErrorHandle); StandardErrorHandle=INVALID_HANDLE_VALUE; // don't close it again } #elif defined (UNIX) #else #error tni33_ABackgroundProcess::FreeFileHandles() not coded for this operating system! #endif } tni33_ABackgroundProcess::~tni33_ABackgroundProcess() { if(CommandLine!=0) delete [] CommandLine; #if defined (WIN32) if(AInvalidProcessHandle_ni33!=Process) CloseHandle(Process); if(AInvalidProcessHandle_ni33!=Thread) CloseHandle(Thread); if(OpenedStandardInHandle && INVALID_HANDLE_VALUE!=StandardInHandle) CloseHandle(StandardInHandle); if(OpenedStandardOutHandle && INVALID_HANDLE_VALUE!=StandardOutHandle) CloseHandle(StandardOutHandle); if(OpenedStandardErrorHandle && INVALID_HANDLE_VALUE!=StandardErrorHandle) CloseHandle(StandardErrorHandle); #elif defined (UNIX) #else #error tni33_ABackgroundProcess::~tni33_ABackgroundProcess() not coded for this operating system! #endif } int tni33_ABackgroundProcess::Stop() { // All kill operations are brute force without cleanup ! int rc=0; if(State==Started) { #if defined (WIN32) if(TerminateProcess(Process, 256)) //we use an arbitrary number different from 0 as exit code for the child process, 256 made it, as exit codes on UNIX range only from 0 to 255. { Sleep(0); //give up time slice, so that terminated process or OS has a chance to use exit code 256 set above State=Stopped; if(GetExitCodeProcess(Process, &RetCode)) { rc=1; CloseHandle(Process); //TODO: check return code of CloseHandle() FreeFileHandles(); Process=AInvalidProcessHandle_ni33; } else { ErrorHandler_ni35->Report(tni35_AStandardError(tni35_AStandardError::CaseCouldNotGetReturnCode, CommandLine)); RetCode=InvalidReturnCode_ni33; } } else ErrorHandler_ni35->Report(tni35_AStandardError(tni35_AStandardError::CaseCouldNotStopProcess, CommandLine)); #elif defined(UNIX) errno=0; if(kill(Process, SIGKILL)) ErrorHandler_ni35->Report(tni35_AStandardError(tni35_AStandardError::CaseCouldNotStopProcess, CommandLine)); else { State=Stopped; int RCProcess; pid_t ReturnedPID; do { errno=0; //if(Process==waitpid(Process,&RCProcess,WNOHANG)) ReturnedPID=waitpid(Process, &RCProcess, 0); // we hope, that the kill signal will end the process so that the waitpid-function will return, when the OS has done it's work of killing the process } while(((pid_t)-1)==ReturnedPID && EINTR==errno); //we are not interested in signals ending waitpid (the kill signal will kill us any day) if(Process==ReturnedPID) { rc=1; Process=AInvalidProcessHandle_ni33; if(WIFEXITED(RCProcess)) RetCode=WEXITSTATUS(RCProcess); else if(WIFSIGNALED(RCProcess)) RetCode=InvalidReturnCode_ni33; else RetCode=InvalidReturnCode_ni33; } else { ErrorHandler_ni35->Report(tni35_AStandardError(tni35_AStandardError::CaseCouldNotGetReturnCode, CommandLine)); RetCode=InvalidReturnCode_ni33; } } #else #error tni33_ABackgroundProcess::Stop() was only coded for WIN32 and UNIX (define one of them). #endif } return rc; } int tni33_ABackgroundProcess::Wait() { int rc=0; if(State==Started) { #if defined (WIN32) if(WAIT_FAILED==WaitForSingleObject(Process,INFINITE)) ErrorHandler_ni35->Report(tni35_AStandardError(tni35_AStandardError::CaseWaitForProcessFailed, CommandLine)); if(GetExitCodeProcess(Process,&RetCode)) { rc=1; CloseHandle(Process); FreeFileHandles(); Process=AInvalidProcessHandle_ni33; State=Stopped; } else { ErrorHandler_ni35->Report(tni35_AStandardError(tni35_AStandardError::CaseCouldNotGetReturnCode, CommandLine)); RetCode=InvalidReturnCode_ni33; } #elif defined (UNIX) int RCProcess=0; pid_t ReturnedPID; do { errno=0; ReturnedPID=waitpid(Process, &RCProcess, 0); } while(((pid_t)-1)==ReturnedPID && EINTR==errno); //we are not interested in signals ending waitpid (the kill signal will kill us anyday) if(Process==ReturnedPID) { rc=1; Process=AInvalidProcessHandle_ni33; State=Stopped; if(WIFEXITED(RCProcess)) RetCode=WEXITSTATUS(RCProcess); else if(WIFSIGNALED(RCProcess)) RetCode=InvalidReturnCode_ni33; else RetCode=InvalidReturnCode_ni33; } else { ErrorHandler_ni35->Report(tni35_AStandardError(tni35_AStandardError::CaseWaitForProcessFailed,CommandLine)); RetCode=InvalidReturnCode_ni33; } #else #error tni33_ABackgroundProcess::Wait() not coded for this operating system! #endif } else ErrorHandler_ni35->Report(tni35_AStandardError(tni35_AStandardError::CaseProcessNotStarted, CommandLine)); return rc; } int tni33_ABackgroundProcess::IsRunning() { int rc=0; if(State==Started) { #if defined (WIN32) if(!GetExitCodeProcess(Process,&RetCode)) ErrorHandler_ni35->Report(tni35_AStandardError(tni35_AStandardError::CaseWaitForProcessFailed,CommandLine)); else { if(STILL_ACTIVE==RetCode) rc=1; else { CloseHandle(Process); FreeFileHandles(); Process=AInvalidProcessHandle_ni33; State=Stopped; } } #elif defined (UNIX) int RCProcess; pid_t ReturnedPID; do { errno=0; ReturnedPID=waitpid(Process, &RCProcess, WNOHANG); } while(((pid_t)-1)==ReturnedPID && EINTR==errno); //we are not interested in signals ending waitpid (the kill signal will kill us anyday) if(0==ReturnedPID) rc=1; else if(Process!=ReturnedPID) { RetCode=InvalidReturnCode_ni33; ErrorHandler_ni35->Report(tni35_AStandardError(tni35_AStandardError::CaseWaitForProcessFailed,CommandLine)); } else { Process=AInvalidProcessHandle_ni33; State=Stopped; if(WIFEXITED(RCProcess)) RetCode=WEXITSTATUS(RCProcess); else if(WIFSIGNALED(RCProcess)) RetCode=InvalidReturnCode_ni33; else RetCode=InvalidReturnCode_ni33; } #else #error tni33_ABackgroundProcess::Wait() not coded for this operating system! #endif } return rc; } void tni33_ABackgroundProcess::WaitForMultipleBackgroundProcesses(int NoProcs,tni33_ABackgroundProcess **Procs) { int i; for(i=0;i<NoProcs;i++) Procs[i]->Wait(); } // ----------------------------------------------------------------------------- // implementation of class tni33_AProcess // ----------------------------------------------------------------------------- tni33_AProcess::tni33_AProcess(const char * Cmdline, const tni34_AFile * StdIn, const tni34_AFile * StdOut, const int AppendStdOut, const tni34_AFile * StdErr, const int AppendStdErr) :P(Cmdline, StdIn, StdOut, AppendStdOut, StdErr, AppendStdErr) { if(P.WasStarted()) P.Wait(); } tni33_AProcess::tni33_AProcess(tni33_ArgumentList & Arguments, const tni34_AFile * StdIn, const tni34_AFile * StdOut, const int AppendStdOut, const tni34_AFile * StdErr, const int AppendStdErr) :P(Arguments, StdIn, StdOut, AppendStdOut, StdErr, AppendStdErr) { if(P.WasStarted()) P.Wait(); }
[ "gunter.mueller@gmail.com" ]
gunter.mueller@gmail.com
cfe5bdfa0853e6fe2c4e6a56c666208a2b75f14c
de7e771699065ec21a340ada1060a3cf0bec3091
/test-framework/src/java/org/apache/lucene/codecs/asserting/AssertingPostingsFormat.h
d72addc706daf7fea3d6495361228c960282fe17
[]
no_license
sraihan73/Lucene-
0d7290bacba05c33b8d5762e0a2a30c1ec8cf110
1fe2b48428dcbd1feb3e10202ec991a5ca0d54f3
refs/heads/master
2020-03-31T07:23:46.505891
2018-12-08T14:57:54
2018-12-08T14:57:54
152,020,180
7
0
null
null
null
null
UTF-8
C++
false
false
4,562
h
#pragma once #include "stringhelper.h" #include <memory> #include <string> // C++ NOTE: Forward class declarations: #include "core/src/java/org/apache/lucene/codecs/PostingsFormat.h" #include "core/src/java/org/apache/lucene/codecs/FieldsConsumer.h" #include "core/src/java/org/apache/lucene/index/SegmentWriteState.h" #include "core/src/java/org/apache/lucene/codecs/FieldsProducer.h" #include "core/src/java/org/apache/lucene/index/SegmentReadState.h" #include "core/src/java/org/apache/lucene/index/Terms.h" #include "core/src/java/org/apache/lucene/util/Accountable.h" #include "core/src/java/org/apache/lucene/index/Fields.h" /* * Licensed to the Syed Mamun Raihan (sraihan.com) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * sraihan.com licenses this file to You under GPLv3 License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * https://www.gnu.org/licenses/gpl-3.0.en.html * * 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. */ namespace org::apache::lucene::codecs::asserting { using FieldsConsumer = org::apache::lucene::codecs::FieldsConsumer; using FieldsProducer = org::apache::lucene::codecs::FieldsProducer; using PostingsFormat = org::apache::lucene::codecs::PostingsFormat; using Fields = org::apache::lucene::index::Fields; using SegmentReadState = org::apache::lucene::index::SegmentReadState; using SegmentWriteState = org::apache::lucene::index::SegmentWriteState; using Terms = org::apache::lucene::index::Terms; using Accountable = org::apache::lucene::util::Accountable; using TestUtil = org::apache::lucene::util::TestUtil; /** * Just like the default postings format but with additional asserts. */ class AssertingPostingsFormat final : public PostingsFormat { GET_CLASS_NAME(AssertingPostingsFormat) private: const std::shared_ptr<PostingsFormat> in_ = TestUtil::getDefaultPostingsFormat(); public: AssertingPostingsFormat(); std::shared_ptr<FieldsConsumer> fieldsConsumer( std::shared_ptr<SegmentWriteState> state) override; std::shared_ptr<FieldsProducer> fieldsProducer( std::shared_ptr<SegmentReadState> state) override; public: class AssertingFieldsProducer : public FieldsProducer { GET_CLASS_NAME(AssertingFieldsProducer) private: const std::shared_ptr<FieldsProducer> in_; public: AssertingFieldsProducer(std::shared_ptr<FieldsProducer> in_); virtual ~AssertingFieldsProducer(); std::shared_ptr<Iterator<std::wstring>> iterator() override; std::shared_ptr<Terms> terms(const std::wstring &field) override; int size() override; int64_t ramBytesUsed() override; std::shared_ptr<std::deque<std::shared_ptr<Accountable>>> getChildResources() override; void checkIntegrity() override; std::shared_ptr<FieldsProducer> getMergeInstance() override; virtual std::wstring toString(); protected: std::shared_ptr<AssertingFieldsProducer> shared_from_this() { return std::static_pointer_cast<AssertingFieldsProducer>( org.apache.lucene.codecs.FieldsProducer::shared_from_this()); } }; public: class AssertingFieldsConsumer : public FieldsConsumer { GET_CLASS_NAME(AssertingFieldsConsumer) private: const std::shared_ptr<FieldsConsumer> in_; const std::shared_ptr<SegmentWriteState> writeState; public: AssertingFieldsConsumer(std::shared_ptr<SegmentWriteState> writeState, std::shared_ptr<FieldsConsumer> in_); void write(std::shared_ptr<Fields> fields) override; virtual ~AssertingFieldsConsumer(); protected: std::shared_ptr<AssertingFieldsConsumer> shared_from_this() { return std::static_pointer_cast<AssertingFieldsConsumer>( org.apache.lucene.codecs.FieldsConsumer::shared_from_this()); } }; protected: std::shared_ptr<AssertingPostingsFormat> shared_from_this() { return std::static_pointer_cast<AssertingPostingsFormat>( org.apache.lucene.codecs.PostingsFormat::shared_from_this()); } }; } // #include "core/src/java/org/apache/lucene/codecs/asserting/
[ "smamunr@fedora.localdomain" ]
smamunr@fedora.localdomain
18eb210c4f3b9507299e1bf4345ed652f4dba9ac
45645fd8c0836f239e59bb09f2a022a57c031c17
/GMAT-R2019aBeta1/src/gmatutil/util/Code500EphemerisFile.cpp
c027a82600cc7da62e3c3efaf0d931dd7c3c4099
[ "Apache-2.0" ]
permissive
daniestevez/gmat-dslwp-source
03678e983f814ed1dcfb41079813e1da9bad2a6e
9f02f6f94e2188161b624cd3d818a9b230c65845
refs/heads/master
2022-10-07T07:05:03.266744
2020-06-06T13:32:41
2020-06-06T13:32:41
260,881,226
2
1
null
null
null
null
UTF-8
C++
false
false
125,200
cpp
//$Id$ //------------------------------------------------------------------------------ // Code500EphemerisFile //------------------------------------------------------------------------------ // GMAT: General Mission Analysis Tool // // Copyright (c) 2002-2013 United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. // All Other 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. // // Developed jointly by NASA/GSFC and Thinking Systems, Inc. under contract // number S-67573-G // // Author: Linda Jun // Created: 2013.05.01 // // This class reads and writes ephemeris file in Code-500 format in either // big-endian (UNIX) or little-endian (PC) byte order, and can automatically // detect the endianness of the file for reading. // // The file format is based on the section 4.1.1 of Flight Dynamics Division // Generic Data Products Formats Interface Control Document & Appendix A.3 // of Swingby User's Guide: Swingby User 552-FDD-93-046R3UD0 document. // // Notes on endianness: // Endianness refers to how bytes are ordered within a data item. A big-endian // machine stores the most significant byte first at the lowest byte address // while a little-endian machine stores the least significant byte first. // // //------------------------------------------------------------------------------ #include "Code500EphemerisFile.hpp" #include "TimeSystemConverter.hpp" // For ConvertGregorianToMjd() #include "StateConversionUtil.hpp" // For Convert() #include "Rvector6.hpp" #include "DateUtil.hpp" // For friend function UnpackDate(), ToHMSFromSecondsOfDay #include "RealUtilities.hpp" // For IsEqual() #include "GregorianDate.hpp" // For GregorianDate() #include "GmatConstants.hpp" // For GmatTimeConstants::A1_TAI_OFFSET #include "UtilityException.hpp" // for UtilityException #include "MessageInterface.hpp" #include "A1Mjd.hpp" #include "DateUtil.hpp" //#define DEBUG_OPEN //#define DEBUG_INIT //#define DEBUG_SET //#define DEBUG_READ_DATA //#define DEBUG_WRITE_HEADERS //#define DEBUG_READ_HEADERS //#define DEBUG_WRITE_DATA_SEGMENT //#define DEBUG_WRITE_DATA_SEGMENT_MORE //#define DEBUG_WRITE_DATA //#define DEBUG_DATA_SEGMENT_TIME //#define DEBUG_WRITE_SENTINELS //#define DEBUG_UNPACK_HEADERS //#define DEBUG_UNPACK_DATA //#define DEBUG_TIME_CONVERSION //#define DEBUG_INITIAL_FINAL //--------------------------------- // static data //--------------------------------- // For unit conversion const double Code500EphemerisFile::DUL_TO_KM = 10000.0; const double Code500EphemerisFile::DUL_DUT_TO_KM_SEC = 10000.0 / 864.0; const double Code500EphemerisFile::KM_TO_DUL = 1.0 / 10000.0; const double Code500EphemerisFile::KM_SEC_TO_DUL_DUT = 864.0 / 10000.0; const double Code500EphemerisFile::SEC_TO_DUT = 1.0 / 864.0; const double Code500EphemerisFile::DAY_TO_DUT = 86400.0 / 864.0; const double Code500EphemerisFile::DUT_TO_DAY = 864.0 / 86400.0; const double Code500EphemerisFile::DUT_TO_SEC = 864.0; //------------------------------------------------------------------------------ // Code500EphemerisFile(double satId, const std::string &productId, ...) //------------------------------------------------------------------------------ /** * Constructor * * @param fileName Filename to be opened * @param satId Spacecraft ID [123.0] * @param timeSystem Time system used "UTC" or "A1" ["UTC"] * @param sourceId Source ID ["GMAT"] * @param centralBody Central body name of output ephem used ["Earth"] * @param coordSystem 3 = True of date, 4 = J2000, 5 = Earth-fixed/Body-fixed [4] * @param fileMode 1 = input, 2 = output [2] * @param fileFormat 1 = Little-endian, 2 = Big-endian [1] * @param yearFormat 1 = YYY, 2 = YYYY */ //------------------------------------------------------------------------------ Code500EphemerisFile::Code500EphemerisFile(const std::string &fileName, double satId, const std::string &timeSystem, const std::string &sourceId, const std::string &centralBody, int coordSystemType, int fileMode, int fileFormat, int yearFormat) { #ifdef DEBUG_INIT MessageInterface::ShowMessage ("Code500EphemerisFile() entered\n fileName='%s', satId=%f, timeSystem='%s', sourceId='%s', " "centralBody='%s', coordSystemType='%d'\n", fileName.c_str(), satId, timeSystem.c_str(), sourceId.c_str(), centralBody.c_str(), coordSystemType); MessageInterface::ShowMessage (" fileMode=%d, fileFormat=%d, yearFormat=%d\n", fileMode, fileFormat, yearFormat); #endif mSatId = satId; mTimeSystem = timeSystem; mSourceId = sourceId; mOutputCentralBody = centralBody; mCoordSystemIndicator = coordSystemType; mFileMode = fileMode; mCentralBodyOfIntegration = -99.99; mCentralBodyOfOutputEphem = -99.99; if (mFileMode == 1) { mInputFileName = fileName; mInputFileFormat = fileFormat; mInputYearFormat = yearFormat; } else { mOutputFileName = fileName; mOutputFileFormat = fileFormat; mOutputYearFormat = yearFormat; // Just for testing // mInputYearFormat = 2; // mOutputYearFormat = 2; } mPrecNutIndicator = 1.0; // hardcoded a1StartEpoch = 0.0; a1EndEpoch = 0.0; theTimeConverter = TimeSystemConverter::Instance(); Initialize(); #ifdef DEBUG_INIT MessageInterface::ShowMessage ("%s ephemeris file in %s format\n", fileMode == 1 ? "Reading" : "Writing", fileFormat == 1 ? "little-endian" : "big-endian"); MessageInterface::ShowMessage ("mOutputFileName='%s', mOutputFileFormat=%d, mOutputYearFormat=%d\n", mOutputFileName.c_str(), mOutputFileFormat, mOutputYearFormat); MessageInterface::ShowMessage ("Code500EphemerisFile() leaving\n size of header1 = %d\n " "size of header2 = %d\n size of data = %d\n mSentinelData = % 1.15e\n", sizeof(mEphemHeader1), sizeof(mEphemHeader2), sizeof(mEphemData), mSentinelData); #endif } //------------------------------------------------------------------------------ // ~Code500EphemerisFile() //------------------------------------------------------------------------------ Code500EphemerisFile::~Code500EphemerisFile() { if (mEphemFileIn.is_open()) mEphemFileIn.close(); if (mEphemFileOut.is_open()) { mEphemFileOut.flush(); mEphemFileOut.close(); } } //------------------------------------------------------------------------------ // Code500EphemerisFile(const Code500EphemerisFile &ef) //------------------------------------------------------------------------------ Code500EphemerisFile::Code500EphemerisFile(const Code500EphemerisFile &ef) { mSatId = ef.mSatId; mTimeSystem = ef.mTimeSystem; mSourceId = ef.mSourceId; mOutputCentralBody = ef.mOutputCentralBody; mCoordSystemIndicator = ef.mCoordSystemIndicator; mCentralBodyOfIntegration = ef.mCentralBodyOfIntegration; mCentralBodyOfOutputEphem = ef.mCentralBodyOfOutputEphem; mFileMode = ef.mFileMode; mInputFileFormat = ef.mInputFileFormat; mOutputFileFormat = ef.mOutputFileFormat; mInputFileName = ef.mInputFileName; mOutputFileName = ef.mOutputFileName; mInputYearFormat = ef.mInputYearFormat; mOutputYearFormat = ef.mOutputYearFormat; a1StartEpoch = ef.a1StartEpoch; a1EndEpoch = ef.a1EndEpoch; Initialize(); } //------------------------------------------------------------------------------ // Code500EphemerisFile& operator=(const Code500EphemerisFile& ef) //------------------------------------------------------------------------------ Code500EphemerisFile& Code500EphemerisFile::operator=(const Code500EphemerisFile& ef) { if (this == &ef) { return *this; } else { mSatId = ef.mSatId; mTimeSystem = ef.mTimeSystem; mSourceId = ef.mSourceId; mOutputCentralBody = ef.mOutputCentralBody; mCoordSystemIndicator = ef.mCoordSystemIndicator; mCentralBodyOfIntegration = ef.mCentralBodyOfIntegration; mCentralBodyOfOutputEphem = ef.mCentralBodyOfOutputEphem; mFileMode = ef.mFileMode; mInputFileFormat = ef.mInputFileFormat; mOutputFileFormat = ef.mOutputFileFormat; mInputFileName = ef.mInputFileName; mOutputFileName = ef.mOutputFileName; mInputYearFormat = ef.mInputYearFormat; mOutputYearFormat = ef.mOutputYearFormat; a1StartEpoch = ef.a1StartEpoch; a1EndEpoch = ef.a1EndEpoch; Initialize(); return *this; } } //------------------------------------------------------------------------------ // void Initialize() //------------------------------------------------------------------------------ void Code500EphemerisFile::Initialize() { #ifdef DEBUG_INIT MessageInterface::ShowMessage ("Code500EphemerisFile::Initialize() entered, mOutputCentralBody='%s', mSwapInputEndian=%d, " "mSwapOutputEndian=%d\n", mOutputCentralBody.c_str(), mSwapInputEndian, mSwapOutputEndian); #endif mProductId = "EPHEM "; mTapeId = "STANDARD"; // Set central body of output ephem mCentralBodyOfOutputEphem = GetBodyIndicator(mOutputCentralBody, 2); // Set central body of integration indicator same body as output for now if (mCentralBodyOfOutputEphem == -99.99) mCentralBodyOfIntegration = -99.99; else mCentralBodyOfIntegration = mCentralBodyOfOutputEphem + 1; // Time System Indicator: 0.0 = A.1, Atomic Time, 1.0 = UTC, Universal Time Coordinated mInputTimeSystem = 0.0; mOutputTimeSystem = 0.0; if (mTimeSystem == "A1") mOutputTimeSystem = 1.0; else if (mTimeSystem == "UTC") mOutputTimeSystem = 2.0; mCoordSystem = "2000"; if (mCoordSystemIndicator == 3) mCoordSystem = "INER"; else if (mCoordSystemIndicator == 5) mCoordSystem = "EFI "; mDataRecWriteCounter = 2; // data record starts at 3 mLastDataRecRead = 2; mLastStateIndexRead = -1; mNumberOfRecordsInFile = -1; mSentinelData = 9.999999999999999e15; mSentinelsFound = false; mGregorianOfDUTRef = "18 Sep 1957 00:00:00.000"; mRefTimeForDUT_YYMMDD = 570918.0; mMjdOfDUTRef = theTimeConverter->ConvertGregorianToMjd(mGregorianOfDUTRef); mTimeIntervalBetweenPointsSecs = 0.0; mLeapSecsStartOutput = 0.0; mLeapSecsEndOutput = 0.0; mStartUtcMjd = 0.0; mEndUtcMjd = 0.0; mLeapSecsInput = 0.0; mOutputCentralBodyMu = 0.0; mSwapInputEndian = false; mSwapOutputEndian = false; // Open file if (mFileMode == 1) OpenForRead(mInputFileName, mInputFileFormat); else if (mFileMode == 2) OpenForWrite(mOutputFileName, mOutputFileFormat); // Fill in some header and data record with initial values if writing if (mFileMode == 2) { InitializeHeaderRecord1(); InitializeHeaderRecord2(); InitializeDataRecord(); } #ifdef DEBUG_INIT MessageInterface::ShowMessage ("Code500EphemerisFile::Initialize() leaving, mOutputCentralBody='%s', " "mCentralBodyOfIntegration=%f, mCentralBodyOfOutputEphem=%f, " "mCoordSystem='%s' ,mCoordSystemIndicator='%d'\n", mOutputCentralBody.c_str(), mCentralBodyOfIntegration, mCentralBodyOfOutputEphem, mCoordSystem.c_str(), mCoordSystemIndicator); #endif } //------------------------------------------------------------------------------ // void Validate() //------------------------------------------------------------------------------ /** * Validates header data. This method is usually called after Initialize. */ //------------------------------------------------------------------------------ void Code500EphemerisFile::Validate() { // If file mode is writing, check for some header value if (mFileMode == 1) { // Check for uninitialized central body indicator if (mCentralBodyOfOutputEphem == -99.99) throw UtilityException ("Code 500 ephemeris header field error: central body of output ephem " "indicator is uninitialized for the file \"" + mOutputFileName + "\""); } } //------------------------------------------------------------------------------ // bool OpenForRead(const std::string &fileName, int fileFormat = 0, logOption = 0) //------------------------------------------------------------------------------ /** * Opens ephemeris file for reading. * * @param fileName File name to be open for reading * @param fileFormat Input file format (0 = Auto-Detect, 1 = Little-Endian, 2 = Big-Endian) * @param logOption 0 = no debug, 1 = write file size in bytes */ //------------------------------------------------------------------------------ bool Code500EphemerisFile::OpenForRead(const std::string &fileName, int fileFormat, int logOption) { #ifdef DEBUG_OPEN MessageInterface::ShowMessage ("OpenForRead() entered, fileName='%s', fileFormat=%d, logOption=%d\n", fileName.c_str(), fileFormat, logOption); #endif if (fileName == "") { #ifdef DEBUG_OPEN MessageInterface::ShowMessage ("OpenForRead() returning false, file name is blank\n"); #endif return false; } if (mInputFileName != fileName) { // Close it first CloseForRead(); mEphemFileIn.open(fileName.c_str(), std::ios_base::binary); if (!mEphemFileIn.is_open()) throw UtilityException("Cannot open code 500 ephemeris file \"" + fileName + "\" for reading"); mInputFileName = fileName; } std::streampos fsize = mEphemFileIn.tellg(); mEphemFileIn.seekg(0, std::ios::end); fsize = mEphemFileIn.tellg() - fsize; mEphemFileIn.seekg(std::ios_base::beg); mNumberOfRecordsInFile = (unsigned long)fsize / RECORD_SIZE; mSwapInputEndian = false; if (fileFormat == 0) mSwapInputEndian = IsFileEndianSwapped(); else if (fileFormat == 1) mSwapInputEndian = !IsProcessorLittleEndian(); else if (fileFormat == 2) mSwapInputEndian = IsProcessorLittleEndian(); if (logOption == 1) { // Write out size of the file MessageInterface::ShowMessage ("Code500EphemerisFile::OpenForRead() \n ephem file: '%s'\n" " size in bytes = %lu, number of records = %d\n", fileName.c_str(), (unsigned long)fsize, mNumberOfRecordsInFile); } #ifdef DEBUG_OPEN MessageInterface::ShowMessage ("OpenForRead() returning true, ephemeris file successfully opened for reading\n"); #endif return true; } //------------------------------------------------------------------------------ // bool OpenForWrite(const std::string &fileName, int fileFormat = 1) //------------------------------------------------------------------------------ /** * Opens ephemeris file for writing. * * @param fileName File name to be open for writing * @param fileFormat Output file format (1 = Little-Endian, 2 = Big-Endian) */ //------------------------------------------------------------------------------ bool Code500EphemerisFile::OpenForWrite(const std::string &fileName, int fileFormat) { #ifdef DEBUG_OPEN MessageInterface::ShowMessage ("OpenForWrite() entered, fileName='%s', fileFormat=%d\n", fileName.c_str(), fileFormat); #endif if (fileName == "") { #ifdef DEBUG_OPEN MessageInterface::ShowMessage ("OpenForWrite() returning false, file name is blank\n"); #endif return false; } if (mInputFileName != fileName) { // Close it firat CloseForWrite(); mEphemFileOut.open(fileName.c_str(), std::ios_base::binary); if (!mEphemFileOut.is_open()) throw UtilityException("Cannot open code 500 ephemeris file \"" + fileName + "\" for writing"); mSwapOutputEndian = false; if (fileFormat == 1) mSwapOutputEndian = !IsProcessorLittleEndian(); else if (fileFormat == 2) mSwapOutputEndian = IsProcessorLittleEndian(); } #ifdef DEBUG_OPEN MessageInterface::ShowMessage ("OpenForWrite() returning true, ephemeris file successfully opened for writing\n"); #endif return true; } //------------------------------------------------------------------------------ // void CloseForRead() //------------------------------------------------------------------------------ void Code500EphemerisFile::CloseForRead() { if (mEphemFileIn.is_open()) mEphemFileIn.close(); mSentinelsFound = false; } //------------------------------------------------------------------------------ // void CloseForWrite() //------------------------------------------------------------------------------ void Code500EphemerisFile::CloseForWrite() { if (mEphemFileOut.is_open()) mEphemFileOut.close(); } //------------------------------------------------------------------------------ // bool GetInitialAndFinalStates(Real &initialEpoch, Real &finalEpoch, // Rvector6 &initialState, Rvector6 &finalState, std::string &centralBody, // std::string &coordSystem, Integer &coordSysIndicator) //------------------------------------------------------------------------------ /** * Retrieves inital and final epochs and states from the input Code500 ephemeris file. * It also retrieves central body and coordinate system on the file. It assumes * that input file is already opened successfully. * * @param initialEpoch Initial epoch on the file * @param finalEpoch Final epoch on the file * @param initialState Initial state on the file * @param finalState Final state on the file * @param centralBody Central body of output on the file * @param coordSystem Coordinate system on the file * ("2000" for J2000, "INER" for true of reference, "MEAN" for B1950) * @param coordSysIndicator Coordinate system indicator * (2 = Mean of 1950, 3 = True of reference, 4 = J2000) * */ //------------------------------------------------------------------------------ bool Code500EphemerisFile::GetInitialAndFinalStates(Real &initialEpoch, Real &finalEpoch, Rvector6 &initialState, Rvector6 &finalState, std::string &centralBody, std::string &coordSystem, Integer &coordSysIndicator) { #ifdef DEBUG_INITIAL_FINAL MessageInterface::ShowMessage ("Code500EphemerisFile::GetInitialAndFinalState() entered\n"); MessageInterface::ShowMessage(" mNumberOfRecordsInFile = %d\n", mNumberOfRecordsInFile); #endif // For initial and final epoch/state #ifdef DEBUG_INITIAL_FINAL ReadHeader1(1); #else ReadHeader1(); #endif // For initial state ReadDataAt(1); int i = 0; double posDult, velDult; for (int j = 0; j < 3; j++) { posDult = ReadDoubleField(&mEphemData.firstStateVector_DULT[j]); mInitialState[j] = posDult * DUL_TO_KM; } for (int j = 3; j < 6; j++) { velDult = ReadDoubleField(&mEphemData.firstStateVector_DULT[j]); mInitialState[j] = velDult * DUL_DUT_TO_KM_SEC; } // For final state ReadDataAt(mNumberOfRecordsInFile-2); i = mLastStateIndexRead; for (int j = 0; j < 3; j++) { posDult = ReadDoubleField(&mEphemData.stateVector2Thru50_DULT[i][j]); mFinalState[j] = posDult * DUL_TO_KM; } for (int j = 3; j < 6; j++) { velDult = ReadDoubleField(&mEphemData.stateVector2Thru50_DULT[i][j]); mFinalState[j] = velDult * DUL_DUT_TO_KM_SEC; } #ifdef DEBUG_INITIAL_FINAL MessageInterface::ShowMessage (" a1StartEpoch = %.12f\n a1EndEpoch = %.12f\n", a1StartEpoch, a1EndEpoch); MessageInterface::ShowMessage (" initialState = %s\n finalState = %s\n", mInitialState.ToString().c_str(), mFinalState.ToString().c_str()); #endif initialEpoch = a1StartEpoch; finalEpoch = a1EndEpoch; initialState = mInitialState; finalState = mFinalState; // Set central body name of output ephem centralBody = GetBodyName(mCentralBodyOfOutputEphem, 2); // Set coordiante system // "INER" for True of date, "2000" for J2000, "EFI " for Earth-fixed coordSystem = mCoordSystem; // 3 = True of date, 4 = J2000, 5 = Earth-fixed coordSysIndicator = mCoordSystemIndicator; #ifdef DEBUG_INITIAL_FINAL MessageInterface::ShowMessage (" centralBody = '%s', coordSystem = '%s', coordSysIndicator = %d\n", centralBody.c_str(), coordSystem.c_str(), coordSysIndicator); MessageInterface::ShowMessage ("Code500EphemerisFile::GetInitialAndFinalState() returning true\n"); #endif return true; } //------------------------------------------------------------------------------ // bool IsProcessorLittleEndian() //------------------------------------------------------------------------------ /** * Checks if the processor is little-endian * * @return true if the processor is little-endian, * false if the processor is big-endian */ //------------------------------------------------------------------------------ bool Code500EphemerisFile::IsProcessorLittleEndian() { UnsignedInt endianInt = 1U; bool isLittleEndian = ((char*)&endianInt)[0] == 0x01; return isLittleEndian; } //------------------------------------------------------------------------------ // bool IsFileEndianSwapped() //------------------------------------------------------------------------------ /** * Checks the value of mEphemHeader1.timeSystemIndicator to determine if the * endianness of the file needs to be swapped in order to be read. * * @return true if the endianness of the file is swapped, * false if the endianness of the file is the same */ //------------------------------------------------------------------------------ bool Code500EphemerisFile::IsFileEndianSwapped() { if (!mEphemFileIn.is_open()) throw UtilityException("Cannot open code 500 ephemeris file \"" + mInputFileName + "\" for reading"); // Read the first header mEphemFileIn.seekg(std::ios_base::beg); mEphemFileIn.read((char*)(&mEphemHeader1), RECORD_SIZE); // Save infile time system used //mInputTimeSystem = mEphemHeader1.timeSystemIndicator; Real timeSystemIndicator = mEphemHeader1.timeSystemIndicator; if (timeSystemIndicator == 1 || timeSystemIndicator == 2) return false; // Endianness matches return true; } //------------------------------------------------------------------------------ // bool ReadHeader1(int logOption = 0) //------------------------------------------------------------------------------ /** * Unpacks header 1 record and log values to log file on option. * * @param logOption 0 = no log, 1 = log all header data */ //------------------------------------------------------------------------------ bool Code500EphemerisFile::ReadHeader1(int logOption) { #ifdef DEBUG_READ_HEADERS MessageInterface::ShowMessage ("Code500EphemerisFile::ReadHeader1() entered, logOption=%d, mInputYearFormat=%d\n", logOption, mInputYearFormat); #endif if (!mEphemFileIn.is_open()) throw UtilityException("Cannot open code 500 ephemeris file \"" + mInputFileName + "\" for reading"); // Read the first header mEphemFileIn.seekg(std::ios_base::beg); mEphemFileIn.read((char*)(&mEphemHeader1), RECORD_SIZE); // Save infile time system used //mInputTimeSystem = mEphemHeader1.timeSystemIndicator; mInputTimeSystem = ReadDoubleField(&mEphemHeader1.timeSystemIndicator); if (logOption == 1) UnpackHeader1(); // Save the data used by the Code500 propagator in GMAT compatible formats double yyymmddStart = ReadDoubleField(&mEphemHeader1.startDateOfEphem_YYYMMDD); if (mInputYearFormat == 2) yyymmddStart = yyymmddStart - 19000000; double secsOfDayStart = ReadDoubleField(&mEphemHeader1.startSecondsOfDay); Real startDate = ReadDoubleField(&mEphemHeader1.startDateOfEphem_YYYMMDD); Real startSecs = ReadDoubleField(&mEphemHeader1.startSecondsOfDay); Real endDate = ReadDoubleField(&mEphemHeader1.endDateOfEphem_YYYMMDD); Real endSecs = ReadDoubleField(&mEphemHeader1.endSecondsOfDay); Integer year = (Integer)(startDate / 10000); Integer month = (Integer)((startDate - year * 10000) / 100); Integer day = (Integer)(startDate - year * 10000 - month * 100); year += 1900; Integer hour = (Integer)(startSecs / 3600); Integer minute = (Integer)((startSecs - hour * 3600) / 60); Real second = startSecs - hour * 3600 - minute * 60; GmatEpoch epoch = ModifiedJulianDate(year, month, day, hour, minute, second); year = (Integer)(endDate / 10000); month = (Integer)((endDate - year * 10000) / 100); day = (Integer)(endDate - year * 10000 - month * 100); year += 1900; hour = (Integer)(endSecs / 3600); minute = (Integer)((endSecs - hour * 3600) / 60); second = endSecs - hour * 3600 - minute * 60; GmatEpoch epochend = ModifiedJulianDate(year, month, day, hour, minute, second); if (mInputTimeSystem == 1.0) { a1StartEpoch = epoch; a1EndEpoch = epochend; } else if (mInputTimeSystem == 2.0) // UTC { a1StartEpoch = theTimeConverter->Convert(epoch, TimeSystemConverter::UTCMJD, TimeSystemConverter::A1MJD); a1EndEpoch = theTimeConverter->Convert(epochend, TimeSystemConverter::UTCMJD, TimeSystemConverter::A1MJD); } // Save central body of integration indicator mCentralBodyOfIntegration = ReadDoubleField(&mEphemHeader1.centralBodyIndicator); // Save central body and coordinate system needed by GetInitialAndFinalState() mCentralBodyOfOutputEphem = ReadDoubleField(&mEphemHeader1.coordinateCenterIndicator); std::string coordSystemStr = mEphemHeader1.coordSystemIndicator1; mCoordSystem = coordSystemStr.substr(0,4); mCoordSystemIndicator = ReadIntegerField(&mEphemHeader1.coordSystemIndicator2); // Save initial state needed by GetInitialAndFinalState() for (int i = 0; i < 3; i++) { double posDult = ReadDoubleField(&mEphemHeader1.cartesianElementsAtEpoch_DULT[i]); // Save initial position mInitialState[i] = posDult * DUL_TO_KM; } for (int i = 3; i < 6; i++) { double velDult = ReadDoubleField(&mEphemHeader1.cartesianElementsAtEpoch_DULT[i]); // Save initial velocity mInitialState[i] = velDult * DUL_DUT_TO_KM_SEC; } #ifdef DEBUG_READ_HEADERS MessageInterface::ShowMessage("A.1 Start Epoch: %.12lf\n", a1StartEpoch); MessageInterface::ShowMessage("A.1 End Epoch: %.12lf\n", a1EndEpoch); MessageInterface::ShowMessage("A.1 Step Size: %.12lf\n", ReadDoubleField(&mEphemHeader1.stepSize_SEC)); MessageInterface::ShowMessage ("Code500EphemerisFile::ReadHeader1() returning true, mInputTimeSystem=%d\n", mInputTimeSystem); #endif return true; } //------------------------------------------------------------------------------ // bool ReadHeader2(int logOption = 0) //------------------------------------------------------------------------------ /** * Unpacks header 2 record and log values to log file on option. * * @param logOption 0 = no log, 1 = log all header data */ //------------------------------------------------------------------------------ bool Code500EphemerisFile::ReadHeader2(int logOption) { if (!mEphemFileIn.is_open()) throw UtilityException("Cannot open code 500 ephemeris file \"" + mInputFileName + "\" for reading"); // Read the second header mEphemFileIn.seekg(RECORD_SIZE, std::ios_base::beg); mEphemFileIn.read((char*)&mEphemHeader2, RECORD_SIZE); if (logOption == 1) UnpackHeader2(); return true; } //------------------------------------------------------------------------------ // void GetStartAndEndEpochs(GmatEpoch &startEpoch, GmatEpoch &endEpoch) //------------------------------------------------------------------------------ /** * Accesses the start and end epochs as contained in the header data * * @param startEpoch The start epoch * @param endEpoch The end epoch */ //------------------------------------------------------------------------------ void Code500EphemerisFile::GetStartAndEndEpochs(GmatEpoch &startEpoch, GmatEpoch &endEpoch, std::vector<EphemData> **records) { startEpoch = a1StartEpoch; endEpoch = a1EndEpoch; *records = &ephemRecords; } //------------------------------------------------------------------------------ // bool ReadDataAt(int dataRecNumber, int logOption = 0) //------------------------------------------------------------------------------ /** * Reads data record at requested data record number. It will add the size of * 2 header records before positioning the file. * * @param dataRecNumber Data record number * @param logOption = 0, no log * = 1, log first state vector of only first and last record * = 2, log first and last state vector of all records * = 3, log all state vectors of all records */ //------------------------------------------------------------------------------ bool Code500EphemerisFile::ReadDataAt(int dataRecNumber, int logOption) { #ifdef DEBUG_READ_DATA MessageInterface::ShowMessage ("ReadDataAt() entered, dataRecNumber = %d, logOption = %d\n", dataRecNumber, logOption); #endif if (!mEphemFileIn.is_open()) throw UtilityException("Cannot open code 500 ephemeris file \"" + mInputFileName + "\" for reading"); int filePos = (dataRecNumber + 1) * RECORD_SIZE; #ifdef DEBUG_READ_DATA MessageInterface::ShowMessage(" filePos = %d\n", filePos); #endif // Position file at requested data record number mEphemFileIn.seekg(filePos, std::ios_base::beg); // Check for eof if (mEphemFileIn.eof()) { #ifdef DEBUG_READ_DATA MessageInterface::ShowMessage ("ReadDataAt() returning false, input ephem file reached eof\n"); #endif return false; } mEphemFileIn.read((char*)&mEphemData, RECORD_SIZE); // Always unpack data to find sentinel data for end of state vector UnpackDataRecord(dataRecNumber, logOption); #ifdef DEBUG_READ_DATA MessageInterface::ShowMessage ("ReadDataAt() returning true, dataRecNumber = %d, mLastStateIndexRead = %d\n", dataRecNumber, mLastStateIndexRead); #endif return true; } //------------------------------------------------------------------------------ // bool ReadDataRecords(int numRecordsToRead = -1, int logOption = 0) //------------------------------------------------------------------------------ /** * Reads data record at requested data record number. It will add the size of * 2 header records before positioning the file. * * @param numRecordsToRead = -999, Read entire file * > 0, Reads number of records * @param logOption = 0, no log * = 1, log first state vector of only first and last record * = 2, log first state vector of all specified number of records * = 3, log all state vectors of all specified number of records */ //------------------------------------------------------------------------------ bool Code500EphemerisFile::ReadDataRecords(int numRecordsToRead, int logOption) { #ifdef DEBUG_READ_DATA MessageInterface::ShowMessage ("ReadDataRecords() entered, numRecordsToRead = %d, logOption = %d, " "mSentinelsFound=%d\n", numRecordsToRead, logOption, mSentinelsFound); #endif if (!mEphemFileIn.is_open()) throw UtilityException("Cannot open code 500 ephemeris file \"" + mInputFileName + "\" for reading"); int recCount = 1; ephemRecords.clear(); // Position file to first data record int filePos = RECORD_SIZE * 2; #ifdef DEBUG_READ_DATA MessageInterface::ShowMessage(" filePos = %d\n", filePos); #endif mEphemFileIn.seekg(filePos, std::ios_base::beg); // Read the data until eof or 10 sentinels found, or numRecordsToRead reached bool continueRead = true; //while (continueRead && !mSentinelsFound) while (continueRead) { if (mEphemFileIn.eof()) { #ifdef DEBUG_READ_DATA MessageInterface::ShowMessage("End of file reached\n"); #endif break; } else { ReadDataAt(recCount, logOption); if ((numRecordsToRead != -999) && (recCount >= numRecordsToRead)) { #ifdef DEBUG_READ_DATA MessageInterface::ShowMessage("Read requested %d records\n", numRecordsToRead); #endif break; } else if (mSentinelsFound) { #ifdef DEBUG_READ_DATA MessageInterface::ShowMessage ("Sentinels found at record # %d, mLastStateIndexRead = %d\n", recCount, mLastStateIndexRead); #endif // Log last data record if (logOption > 0) UnpackDataRecord(recCount, logOption); break; } recCount++; } } #ifdef DEBUG_READ_DATA MessageInterface::ShowMessage("ReadDataRecords() returning true\n"); #endif return true; } //------------------------------------------------------------------------------ // bool FinalizeHeaders() //------------------------------------------------------------------------------ bool Code500EphemerisFile::FinalizeHeaders() { #ifdef DEBUG_WRITE_HEADERS MessageInterface::ShowMessage("Code500EphemerisFile::FinalizeHeaders() entered\n"); #endif // Anything to finalize header 1? // Write final header 1 record WriteHeader1(); mEphemFileOut.flush(); #ifdef DEBUG_WRITE_HEADERS DebugDouble("mEphemHeader1.endDateOfEphem_YYYMMDD = %f\n", mEphemHeader1.endDateOfEphem_YYYMMDD, mSwapOutputEndian); DebugDouble("mEphemHeader1.endTimeOfEphemeris_DUT = %f\n", mEphemHeader1.endTimeOfEphemeris_DUT, mSwapOutputEndian); #endif #ifdef DEBUG_WRITE_HEADERS MessageInterface::ShowMessage("Code500EphemerisFile::FinalizeHeaders() returning true\n"); #endif return true; } //------------------------------------------------------------------------------ // bool WriteHeader1() //------------------------------------------------------------------------------ bool Code500EphemerisFile::WriteHeader1() { #ifdef DEBUG_WRITE_HEADERS MessageInterface::ShowMessage("Code500EphemerisFile::WriteHeader1() entered\n"); #endif if (!mEphemFileOut.is_open()) { #ifdef DEBUG_WRITE_HEADERS MessageInterface::ShowMessage ("Code500EphemerisFile::WriteHeader1() returning false, output ephem file is not opened\n"); #endif return false; } mEphemFileOut.seekp(std::ios_base::beg); mEphemFileOut.write((char*)&mEphemHeader1, RECORD_SIZE); #ifdef DEBUG_WRITE_HEADERS MessageInterface::ShowMessage("Code500EphemerisFile::WriteHeader1() returning true\n"); #endif return true; } //------------------------------------------------------------------------------ // bool WriteHeader2() //------------------------------------------------------------------------------ bool Code500EphemerisFile::WriteHeader2() { #ifdef DEBUG_WRITE_HEADERS MessageInterface::ShowMessage("Code500EphemerisFile::WriteHeader2() entered\n"); #endif if (!mEphemFileOut.is_open()) { #ifdef DEBUG_WRITE_HEADERS MessageInterface::ShowMessage ("Code500EphemerisFile::WriteHeader2() returning false, output ephem file is not opened\n"); #endif return false; } mEphemFileOut.seekp(RECORD_SIZE, std::ios_base::beg); mEphemFileOut.write((char*)&mEphemHeader2, RECORD_SIZE); #ifdef DEBUG_WRITE_HEADERS MessageInterface::ShowMessage("Code500EphemerisFile::WriteHeader2() returning true\n"); #endif return true; } //------------------------------------------------------------------------------ // bool WriteDataAt(int recNumber) //------------------------------------------------------------------------------ bool Code500EphemerisFile::WriteDataAt(int recNumber) { #ifdef DEBUG_WRITE_DATA MessageInterface::ShowMessage ("============================= Code500EphemerisFile::WriteDataAt() entered, recNumber=%d\n", recNumber); #endif if (!mEphemFileOut.is_open()) { #ifdef DEBUG_WRITE_DATA MessageInterface::ShowMessage ("Code500EphemerisFile::WriteDataAt() returning false, output ephem file is not opened\n"); #endif //@note Should exception thron here? return false; } if (recNumber <=2) { #ifdef DEBUG_WRITE_DATA MessageInterface::ShowMessage ("Code500EphemerisFile::WriteDataAt() returning false, data records starts at 3, but requsted at %d\n", recNumber); #endif return false; } #ifdef DEBUG_WRITE_DATA MessageInterface::ShowMessage ("Writing data record at %d\n", RECORD_SIZE * (recNumber-1)); #endif // Set to no thrust WriteDoubleField(&mEphemData.thrustIndicator, 2.0); // 1 = thrust, 2 = free flight mEphemFileOut.seekp(RECORD_SIZE * (recNumber-1), std::ios_base::beg); mEphemFileOut.write((char*)&mEphemData, RECORD_SIZE); #ifdef DEBUG_WRITE_DATA MessageInterface::ShowMessage("Code500EphemerisFile::WriteDataAt() leaving\n"); #endif return true; } //------------------------------------------------------------------------------ // bool WriteDataSegment(const EpochArray &epochArray, const StateArray &stateArray, // bool canFinalize = false) //------------------------------------------------------------------------------ /** * Handles writing state vector to data record. * * @param epochArray Array of epoch pointer * @param stateArray Array of state vector pointer * * @note It assumes the maximum number of state vector receiving is NUM_STATES_PER_RECORD (50). */ //------------------------------------------------------------------------------ bool Code500EphemerisFile::WriteDataSegment(const EpochArray &epochArray, const StateArray &stateArray, bool canFinalize) { Integer numPoints = stateArray.size(); #ifdef DEBUG_WRITE_DATA_SEGMENT MessageInterface::ShowMessage ("============================================================\n" "Code500EphemerisFile::WriteDataSegment() entered, numPoints=%d, canFinalize=%d\n", numPoints, canFinalize); #endif if (numPoints == 0) { #ifdef DEBUG_WRITE_DATA_SEGMENT MessageInterface::ShowMessage ("Code500EphemerisFile::WriteDataSegment() just returning true, data size is zero\n"); #endif return true; } else if (numPoints > NUM_STATES_PER_RECORD) { UtilityException ue; ue.SetDetails("Code500EphemerisFile::WriteDataSegment() received too many state vector: %d, " "The maximum it can handle is 50\n", numPoints); throw ue; } // For multiple segments, end epoch of previous segment may be the same as // beginning epoch of new segmnet, so check for duplicate epoch and use the // state of new epoch since any maneuver or some spacecraft property update // may happened. if (!mA1MjdArray.empty()) { A1Mjd *end = mA1MjdArray.back(); A1Mjd *newStart = epochArray.front(); if (end->GetReal() == newStart->GetReal()) { #ifdef DEBUG_WRITE_DATA_SEGMENT MessageInterface::ShowMessage ("Duplicate epoch found, so removing end dadta, end=%f, newStart=%f\n", end->GetReal(), newStart->GetReal()); #endif // Remove the last dadta mA1MjdArray.pop_back(); mStateArray.pop_back(); } } // Fill the buffer for (int i = 0; i < numPoints; i++) { // Push cloned epoch and state since epoch and state POINTER array is cleared in // the EphemerisFile mA1MjdArray.push_back(epochArray[i]->Clone()); mStateArray.push_back(stateArray[i]->Clone()); #ifdef DEBUG_WRITE_DATA_SEGMENT_INDEX MessageInterface::ShowMessage("i=%2d, mA1MjdArray.size()=%2d\n", i, mA1MjdArray.size()); #endif // If buffer is full, write data if ((int)mA1MjdArray.size() == NUM_STATES_PER_RECORD) { // Write data record and clear buffer bool isEndOfData = false; if (canFinalize && i == numPoints - 1) isEndOfData = true; WriteDataRecord(isEndOfData); ClearBuffer(); } } // If final data segment received, write data if (canFinalize) { WriteDataRecord(canFinalize); ClearBuffer(); } #ifdef DEBUG_WRITE_DATA_SEGMENT MessageInterface::ShowMessage ("Code500EphemerisFile::WriteDataSegment() leavng, mA1MjdArray.size()=%d\n", mA1MjdArray.size()); #endif return true; } //------------------------------------------------------------------------------ // void SetSwapEndian(bool swapEndian, int fileMode) //------------------------------------------------------------------------------ void Code500EphemerisFile::SetSwapEndian(bool swapEndian, int fileMode) { #ifdef DEBUG_SWAP_ENDIAN MessageInterface::ShowMessage ("Code500EphemerisFile::SetSwapEndian() entered, swapEndian=%d, fileMode=%d\n", swapEndian, fileMode); #endif if (fileMode == 1) mSwapInputEndian = swapEndian; else mSwapOutputEndian = swapEndian; #ifdef DEBUG_SWAP_ENDIAN MessageInterface::ShowMessage ("Code500EphemerisFile::SetSwapEndian() leaving, mSwapInputEndian=%d, mSwapOutputEndian=%d\n", mSwapInputEndian, mSwapOutputEndian); #endif } //------------------------------------------------------------------------------ // bool GetSwapEndian(int fileMode) //------------------------------------------------------------------------------ bool Code500EphemerisFile::GetSwapEndian(int fileMode) { if (fileMode == 1) return mSwapInputEndian; else return mSwapOutputEndian; } //------------------------------------------------------------------------------ // double SwapDoubleEndian(double value) //------------------------------------------------------------------------------ /** * Swaps endiness for double value */ //------------------------------------------------------------------------------ double Code500EphemerisFile::SwapDoubleEndian(double value) { mDoubleOriginBytes.doubleValue = value; double swapped = SwapDouble(); return swapped; } //------------------------------------------------------------------------------ // int SwapIntegerEndian(ing value) //------------------------------------------------------------------------------ /** * Swaps endiness for int value */ //------------------------------------------------------------------------------ int Code500EphemerisFile::SwapIntegerEndian(int value) { mIntOriginBytes.intValue = value; int swapped = SwapInteger(); return swapped; } //--------------------------------- // protected methods //--------------------------------- //------------------------------------------------------------------------------ // void InitializeHeaderRecord1() //------------------------------------------------------------------------------ void Code500EphemerisFile::InitializeHeaderRecord1() { #ifdef DEBUG_HEADERS MessageInterface::ShowMessage ("InitializeHeaderRecord1() entered, mSwapOutputEndian=%d\n", mSwapOutputEndian); #endif // Initialize all character arrays BlankOut(mEphemHeader1.productId, 8); BlankOut(mEphemHeader1.tapeId, 8); BlankOut(mEphemHeader1.sourceId, 8); BlankOut(mEphemHeader1.headerTitle, 56); BlankOut(mEphemHeader1.coordSystemIndicator1, 4); BlankOut(mEphemHeader1.orbitTheory, 8); BlankOut(mEphemHeader1.spares1, 16); BlankOut(mEphemHeader1.atmosphericDensityModel, 8); BlankOut(mEphemHeader1.spares2, 8); BlankOut(mEphemHeader1.spares3, 48); BlankOut(mEphemHeader1.spares4, 40); BlankOut(mEphemHeader1.spares5, 480); BlankOut(mEphemHeader1.spares6, 660); BlankOut(mEphemHeader1.harmonicsWithTitles1, 456); CopyString(mEphemHeader1.productId, mProductId, 8); WriteDoubleField(&mEphemHeader1.satId, mSatId); CopyString(mEphemHeader1.tapeId, mTapeId, 8); CopyString(mEphemHeader1.sourceId, mSourceId, 8); WriteDoubleField(&mEphemHeader1.timeSystemIndicator, mOutputTimeSystem); WriteDoubleField(&mEphemHeader1.refTimeForDUT_YYMMDD, mRefTimeForDUT_YYMMDD); WriteDoubleField(&mEphemHeader1.centralBodyIndicator, mCentralBodyOfIntegration); WriteDoubleField(&mEphemHeader1.coordinateCenterIndicator, mCentralBodyOfOutputEphem); CopyString(mEphemHeader1.coordSystemIndicator1, mCoordSystem, 4); // "2000" for J2000 WriteIntegerField(&mEphemHeader1.coordSystemIndicator2, mCoordSystemIndicator); // 2 = Mean of 1950, 3 = True of reference, 4 = J2000 std::string str; #ifdef DEBUG_HEADERS str = mEphemHeader1.tapeId; MessageInterface::ShowMessage("tapeId = '%s'\n", str.substr(0,8).c_str()); str = mEphemHeader1.sourceId; MessageInterface::ShowMessage("sourceId = '%s'\n", str.substr(0,8).c_str()); #endif // Set Orbit Theory to COWELL str = "COWELL "; CopyString(mEphemHeader1.orbitTheory, str, 8); // Set leap second info WriteIntegerField(&mEphemHeader1.leapSecondIndicator, 1); // 1 = no leap second occurs, 2 = leap second occurs WriteDoubleField(&mEphemHeader1.dateOfLeapSeconds_YYYMMDD, 0.0); WriteDoubleField(&mEphemHeader1.timeOfLeapSeconds_HHMMSS, 0.0); WriteDoubleField(&mEphemHeader1.utcTimeAdjustment_SEC, 0.0); // Write precession-nutation info WriteDoubleField(&mEphemHeader1.precessionNutationIndicator, mPrecNutIndicator); // Write other indicators WriteDoubleField(&mEphemHeader1.zonalTesseralHarmonicsIndicator, 1.0); WriteDoubleField(&mEphemHeader1.lunarGravPerturbIndicator, 1.0); WriteDoubleField(&mEphemHeader1.solarRadiationPerturbIndicator, 1.0); WriteDoubleField(&mEphemHeader1.solarGravPerturbIndicator, 1.0); WriteDoubleField(&mEphemHeader1.atmosphericDragPerturbIndicator, 1.0); #ifdef DEBUG_HEADERS MessageInterface::ShowMessage("InitializeHeaderRecord1() leaving\n"); #endif } //------------------------------------------------------------------------------ // void InitializeHeaderRecord2() //------------------------------------------------------------------------------ void Code500EphemerisFile::InitializeHeaderRecord2() { #ifdef DEBUG_HEADERS MessageInterface::ShowMessage("InitializeHeaderRecord2() entered\n"); #endif BlankOut(mEphemHeader2.harmonicsWithTitles2, RECORD_SIZE); #ifdef DEBUG_HEADERS MessageInterface::ShowMessage("InitializeHeaderRecord2() leaving\n"); #endif } //------------------------------------------------------------------------------ // void InitializeDataRecord() //------------------------------------------------------------------------------ void Code500EphemerisFile::InitializeDataRecord() { // Set to no thrust WriteDoubleField(&mEphemData.thrustIndicator, 0.0); // Set all states to sentinels WriteDoubleField(&mEphemData.firstStateVector_DULT[0], mSentinelData); WriteDoubleField(&mEphemData.firstStateVector_DULT[1], mSentinelData); WriteDoubleField(&mEphemData.firstStateVector_DULT[2], mSentinelData); WriteDoubleField(&mEphemData.firstStateVector_DULT[3], mSentinelData); WriteDoubleField(&mEphemData.firstStateVector_DULT[4], mSentinelData); WriteDoubleField(&mEphemData.firstStateVector_DULT[5], mSentinelData); for (int i = 0; i < NUM_STATES_PER_RECORD - 1; i++) { for (int j = 0; j < 6; j++) WriteDoubleField(&mEphemData.stateVector2Thru50_DULT[i][j], mSentinelData); } // Blank out spares BlankOut(mEphemData.spares1, 344); } //------------------------------------------------------------------------------ // void SetEphemerisStartTime(const A1Mjd &a1Mjd) //------------------------------------------------------------------------------ /** * Sets start time of ephemeris in the header record 1. */ //------------------------------------------------------------------------------ void Code500EphemerisFile::SetEphemerisStartTime(const A1Mjd &a1Mjd) { #ifdef DEBUG_SET MessageInterface::ShowMessage ("Code500EphemerisFile::SetEphemerisStartTime() entered, a1Mjd=%f\n", a1Mjd.GetReal()); #endif double startMjd = 0.0; if (mOutputTimeSystem == 1) // A1 time system { startMjd = a1Mjd.GetReal(); mStartUtcMjd = ToUtcModJulian(a1Mjd); } else // UTC time system { startMjd = ToUtcModJulian(a1Mjd); mStartUtcMjd = startMjd; } mLeapSecsStartOutput = theTimeConverter->NumberOfLeapSecondsFrom(startMjd); #ifdef DEBUG_SET MessageInterface::ShowMessage("mLeapSecsStartOutput = %f\n", mLeapSecsStartOutput); #endif double yyymmdd, hhmmss; ToYYYMMDDHHMMSS(startMjd, yyymmdd, hhmmss); hhmmss = 200000; // hard-code this double doy = ToDayOfYear(startMjd); double secsOfDay = ToSecondsOfDay(startMjd); #ifdef DEBUG_SET MessageInterface::ShowMessage ("yyymmdd=%f, hhmmss=%f, doy=%f, secsOfDay=%f\n", yyymmdd, hhmmss, doy, secsOfDay); #endif if (mOutputYearFormat == 2) yyymmdd = yyymmdd + 19000000; WriteDoubleField(&mEphemHeader1.startDateOfEphem_YYYMMDD, yyymmdd); WriteDoubleField(&mEphemHeader1.startDayCountOfYear, doy); WriteDoubleField(&mEphemHeader1.startSecondsOfDay, secsOfDay); double startDut = ToDUT(startMjd); WriteDoubleField(&mEphemHeader1.startTimeOfEphemeris_DUT, startDut); // Should I set initiation time to start time of ephemeris? WriteDoubleField(&mEphemHeader1.dateOfInitiationOfEphemComp_YYYMMDD, yyymmdd); WriteDoubleField(&mEphemHeader1.timeOfInitiationOfEphemComp_HHMMSS, hhmmss); #ifdef DEBUG_SET if (mOutputYearFormat == 2) yyymmdd = yyymmdd - 19000000; std::string ymdhms = ToYearMonthDayHourMinSec(yyymmdd, secsOfDay); MessageInterface::ShowMessage("startYYYYMMDDHHMMSSsss = %s\n", ymdhms.c_str()); DebugDouble("mEphemHeader1.startTimeOfEphemeris_DUT = %f\n", startDut, mSwapOutputEndian); MessageInterface::ShowMessage("Code500EphemerisFile::SetEphemerisStartTime() leaving\n"); #endif } //------------------------------------------------------------------------------ // void SetEphemerisEndTime(const A1Mjd &a1Mjd) //------------------------------------------------------------------------------ /** * Sets end time of ephemeris in the header record 1. */ //------------------------------------------------------------------------------ void Code500EphemerisFile::SetEphemerisEndTime(const A1Mjd &a1Mjd) { #ifdef DEBUG_SET MessageInterface::ShowMessage ("Code500EphemerisFile::SetEphemerisEndTime() entered, a1Mjd=%f\n", a1Mjd.GetReal()); #endif double endMjd = 0.0; if (mOutputTimeSystem == 1) // A1 time system { endMjd = a1Mjd.GetReal(); mEndUtcMjd = ToUtcModJulian(a1Mjd); } else // UTC time system { endMjd = ToUtcModJulian(a1Mjd); mEndUtcMjd = endMjd; } // Leap seconds info mLeapSecsEndOutput = theTimeConverter->NumberOfLeapSecondsFrom(endMjd); #ifdef DEBUG_SET MessageInterface::ShowMessage("mLeapSecsEndOutput = %f\n", mLeapSecsEndOutput); #endif if ((mLeapSecsEndOutput - mLeapSecsStartOutput) > 0) { // Find out UTC date and time of the first leap second occurred between start and end time double firstUtcMjd = theTimeConverter->GetFirstLeapSecondMJD(mStartUtcMjd, mEndUtcMjd); #ifdef DEBUG_SET MessageInterface::ShowMessage("firstUtcMjd = %.12f\n", firstUtcMjd); #endif if (firstUtcMjd != -1.0) { double ymd, hms; ToYYYMMDDHHMMSS(firstUtcMjd, ymd, hms); // Add a couple of seconds to avoid noise at the leap second date boundary Real firstUtcMjd2 = firstUtcMjd + (2.0/86400); Real firstA1Mjd = theTimeConverter->Convert(firstUtcMjd2, TimeSystemConverter::UTCMJD, TimeSystemConverter::A1MJD); double a1UtcOffsetInSecs = (firstA1Mjd - firstUtcMjd2) * 86400.0; #ifdef DEBUG_SET MessageInterface::ShowMessage("firstUtcMjd+2sec = %.12f\n", firstUtcMjd2); MessageInterface::ShowMessage("firstA1Mjd = %.12f\n", firstA1Mjd); MessageInterface::ShowMessage("a1UtcOffsetInSecs = %.12f\n", a1UtcOffsetInSecs); #endif WriteIntegerField(&mEphemHeader1.leapSecondIndicator, 2); // 1 = no leap second occurs, 2 = leap second occurs WriteDoubleField(&mEphemHeader1.dateOfLeapSeconds_YYYMMDD, ymd); WriteDoubleField(&mEphemHeader1.timeOfLeapSeconds_HHMMSS, hms); WriteDoubleField(&mEphemHeader1.utcTimeAdjustment_SEC, a1UtcOffsetInSecs); } } double yyymmdd = ToYYYMMDD(endMjd); double doy = ToDayOfYear(endMjd); double secsOfDay = ToSecondsOfDay(endMjd); if (mOutputYearFormat == 2) yyymmdd = yyymmdd + 19000000; WriteDoubleField(&mEphemHeader1.endDateOfEphem_YYYMMDD, yyymmdd); WriteDoubleField(&mEphemHeader1.endDayCountOfYear, doy); WriteDoubleField(&mEphemHeader1.endSecondsOfDay, secsOfDay); double endDut = ToDUT(endMjd); WriteDoubleField(&mEphemHeader1.endTimeOfEphemeris_DUT, endDut); #ifdef DEBUG_SET if (mOutputYearFormat == 2) yyymmdd = yyymmdd - 19000000; std::string ymdhms = ToYearMonthDayHourMinSec(yyymmdd, secsOfDay); MessageInterface::ShowMessage("endYYYYMMDDHHMMSSsss. = %s\n", ymdhms.c_str()); DebugDouble("mEphemHeader1.endDateOfEphem_YYYMMDD = %f\n", mEphemHeader1.endDateOfEphem_YYYMMDD, mSwapOutputEndian); DebugDouble("mEphemHeader1.endTimeOfEphemeris_DUT = %f\n", mEphemHeader1.endTimeOfEphemeris_DUT, mSwapOutputEndian); MessageInterface::ShowMessage("Code500EphemerisFile::SetEphemerisEndTime() leaving\n"); #endif } //------------------------------------------------------------------------------ // void SetTimeIntervalBetweenPoints(double secs) //------------------------------------------------------------------------------ /** * Sets time interval between ephemeris points. * * @param secs Time interval in secconds (-999.999 indicates variable interval) */ //------------------------------------------------------------------------------ void Code500EphemerisFile::SetTimeIntervalBetweenPoints(double secs) { #ifdef DEBUG_SET MessageInterface::ShowMessage("SetTimeIntervalBetweenPoints() entered, secs=%f\n", secs); #endif if (secs == -999.999) { mTimeIntervalBetweenPointsSecs = 0.0;//@note What should be the default value? WriteIntegerField(&mEphemHeader1.outputIntervalIndicator, 2); // 1 = fixed step, 2 = variable step } else { mTimeIntervalBetweenPointsSecs = secs; WriteIntegerField(&mEphemHeader1.outputIntervalIndicator, 1); // 1 = fixed step, 2 = variable step } WriteDoubleField(&mEphemHeader1.stepSize_SEC, mTimeIntervalBetweenPointsSecs); WriteDoubleField(&mEphemHeader1.timeIntervalBetweenPoints_DUT, mTimeIntervalBetweenPointsSecs * SEC_TO_DUT); #ifdef DEBUG_SET MessageInterface::ShowMessage ("SetTimeIntervalBetweenPoints() leaving, mTimeIntervalBetweenPointsSecs=%f\n", mTimeIntervalBetweenPointsSecs); #endif } //------------------------------------------------------------------------------ // void SetCentralBodyMu(double mu) //------------------------------------------------------------------------------ /** * Sets central body mu for ephem output cartesian to keplerian conversion */ //------------------------------------------------------------------------------ void Code500EphemerisFile::SetCentralBodyMu(double mu) { #ifdef DEBUG_CENTRALBODY_MU MessageInterface::ShowMessage ("Code500EphemerisFile::SetCentralBodyMu() entered, mu=%.15f\n", mu); #endif mOutputCentralBodyMu = mu; } //------------------------------------------------------------------------------ // void SetInitialEpoch(const A1Mjd &a1Mjd) //------------------------------------------------------------------------------ void Code500EphemerisFile::SetInitialEpoch(const A1Mjd &a1Mjd) { #ifdef DEBUG_SET MessageInterface::ShowMessage ("SetInitialEpoch() entered, a1Mjd=%f\n", a1Mjd.GetReal()); #endif std::string initialGreg; double initialMjd; if (mOutputTimeSystem == 1) // A1 time system { initialGreg = ToA1Gregorian(a1Mjd); initialMjd = a1Mjd.GetReal(); } else // UTC time system { initialGreg = ToUtcGregorian(a1Mjd); initialMjd = ToUtcModJulian(a1Mjd); } A1Mjd tempA1Mjd = initialMjd; double epochDUT = ToDUT(initialMjd); Real year, month, day, hour, min, sec; A1Date a1Date = tempA1Mjd.ToA1Date(); a1Date.ToYearMonthDayHourMinSec(year, month, day, hour, min, sec); WriteDoubleField(&mEphemHeader1.epochTimeOfElements_DUT, epochDUT); WriteDoubleField(&mEphemHeader1.yearOfEpoch_YYY, year - 1900); WriteDoubleField(&mEphemHeader1.monthOfEpoch_MM, month); WriteDoubleField(&mEphemHeader1.dayOfEpoch_DD, day); WriteDoubleField(&mEphemHeader1.hourOfEpoch_HH, hour); WriteDoubleField(&mEphemHeader1.minuteOfEpoch_MM, min); WriteDoubleField(&mEphemHeader1.secondsOfEpoch_MILSEC, sec * 1000.0); #ifdef DEBUG_SET MessageInterface::ShowMessage ("SetInitialEpoch() leaving, epochDUT=%f\n", epochDUT); #endif } //------------------------------------------------------------------------------ // void SetInitialState(Rvector6 *kmsec) //------------------------------------------------------------------------------ void Code500EphemerisFile::SetInitialState(Rvector6 *kmsec) { Rvector6 cartState = *kmsec; SetInitialCartesianState(cartState); Rvector6 kepState = StateConversionUtil::Convert(cartState, "Cartesian", "Keplerian", mOutputCentralBodyMu); // flat, radius, "TA"); SetInitialKeplerianState(kepState); } //------------------------------------------------------------------------------ // void SetInitialCartesianState(const Rvector6 &cartState) //------------------------------------------------------------------------------ void Code500EphemerisFile::SetInitialCartesianState(const Rvector6 &cartState) { #ifdef DEBUG_SET MessageInterface::ShowMessage ("SetInitialCartesianState() entered, cartState[0]=%f\n", cartState[0]); #endif Rvector6 cartStateDULT = cartState; for (int i = 0; i < 3; i++) cartStateDULT[i] = cartState[i] * KM_TO_DUL; for (int i = 3; i < 6; i++) cartStateDULT[i] = cartState[i] * KM_SEC_TO_DUL_DUT; for (int i = 0; i < 6; i++) { WriteDoubleField(&mEphemHeader1.cartesianElementsAtEpoch_DULT[i], cartStateDULT[i]); } #ifdef DEBUG_SET MessageInterface::ShowMessage ("SetKeplerianElements() leaving, cartStateDULT[0]=%f\n", cartStateDULT[0]); #endif } //------------------------------------------------------------------------------ // void SetInitialKeplerianState(const Rvector6 &kepState) //------------------------------------------------------------------------------ void Code500EphemerisFile::SetInitialKeplerianState(const Rvector6 &kepState) { #ifdef DEBUG_SET MessageInterface::ShowMessage ("SetInitialKeplerianState() entered, kepState[2]=%f\n", kepState[2]); #endif Rvector6 kepStateRad = kepState; // Keplerian elements: // [SMA, ECC, INC, RAAN, AOP, TA] for (int i = 2; i < 6; i++) kepStateRad[i] = kepState[i] * GmatMathConstants::RAD_PER_DEG; // It should write MA instead of TA Real ma = StateConversionUtil::TrueToMeanAnomaly(kepStateRad[5], kepState[1], true); kepStateRad[5] = ma; WriteDoubleField(&mEphemHeader1.keplerianElementsAtEpoch_RAD[0], kepStateRad[0]); WriteDoubleField(&mEphemHeader1.keplerianElementsAtEpoch_RAD[1], kepStateRad[1]); WriteDoubleField(&mEphemHeader1.keplerianElementsAtEpoch_RAD[2], kepStateRad[2]); // file stores RAAN and AOP in reverse order WriteDoubleField(&mEphemHeader1.keplerianElementsAtEpoch_RAD[3], kepStateRad[4]); WriteDoubleField(&mEphemHeader1.keplerianElementsAtEpoch_RAD[4], kepStateRad[3]); WriteDoubleField(&mEphemHeader1.keplerianElementsAtEpoch_RAD[5], kepStateRad[5]); #ifdef DEBUG_SET MessageInterface::ShowMessage ("SetKeplerianElements() leaving, kepStateRad[2]=%f\n", kepStateRad[2]); #endif } //------------------------------------------------------------------------------ // void WriteDataRecord(bool canFinalize) //------------------------------------------------------------------------------ void Code500EphemerisFile::WriteDataRecord(bool canFinalize) { #ifdef DEBUG_WRITE_DATA_SEGMENT MessageInterface::ShowMessage ("==================================================\n" "Code500EphemerisFile::WriteDataRecord() entered, canFinalize=%d, " "mA1MjdArray.size()=%d, mStateArray.size()=%d\n", canFinalize, mA1MjdArray.size(), mStateArray.size()); #endif int numPoints = mA1MjdArray.size(); A1Mjd *start = mA1MjdArray.front(); A1Mjd *end = mA1MjdArray.back(); if (numPoints == 0) { #ifdef DEBUG_WRITE_DATA_SEGMENT MessageInterface::ShowMessage ("Code500EphemerisFile::WriteDataRecord() leaving, there are no data to write\n"); #endif return; } double startMjd = 0.0; if (mOutputTimeSystem == 1) // A1 time system { mLastDataRecStartGreg = ToA1Gregorian(*start); mLastDataRecEndGreg = ToA1Gregorian(*end); startMjd = start->GetReal(); } else // UTC time system { mLastDataRecStartGreg = ToUtcGregorian(*start); mLastDataRecEndGreg = ToUtcGregorian(*end); startMjd = ToUtcModJulian(*start); } // Write data record mDataRecWriteCounter++; #ifdef DEBUG_DATA_SEGMENT_TIME // Note: Subtracted 2 from mDataRecWriteCounter for actual data record counter // since it started at 2 MessageInterface::ShowMessage ("===> mDataRecWriteCounter=%2d, start=%f '%s', end=%f '%s'\n", mDataRecWriteCounter-2, start->GetReal(), mLastDataRecStartGreg.c_str(), end->GetReal(), mLastDataRecEndGreg.c_str()); #endif // Set start date of ephemeris if first data record // Header1 = record1, Header2 = record2, Data1 = record3 if (mDataRecWriteCounter == 3) { SetInitialEpoch(*start); SetInitialState(mStateArray[0]); SetEphemerisStartTime(*start); // Write initial headers WriteHeader1(); WriteHeader2(); } if (canFinalize) SetEphemerisEndTime(*end); WriteDoubleField(&mEphemData.dateOfFirstEphemPoint_YYYMMDD, ToYYYMMDD(startMjd)); WriteDoubleField(&mEphemData.dayOfYearForFirstEphemPoint, ToDayOfYear(startMjd)); WriteDoubleField(&mEphemData.secsOfDayForFirstEphemPoint, ToSecondsOfDay(startMjd)); WriteDoubleField(&mEphemData.timeIntervalBetweenPoints_SEC, mTimeIntervalBetweenPointsSecs); // Write first state vector double stateDULT[6]; ConvertStateKmSecToDULT(mStateArray[0], stateDULT); #ifdef DEBUG_WRITE_DATA_SEGMENT MessageInterface::ShowMessage("----- State vector 1\n"); DebugWriteState(mStateArray[0], stateDULT, 2); #endif WriteDoubleField(&mEphemData.firstStateVector_DULT[0], stateDULT[0]); WriteDoubleField(&mEphemData.firstStateVector_DULT[1], stateDULT[1]); WriteDoubleField(&mEphemData.firstStateVector_DULT[2], stateDULT[2]); WriteDoubleField(&mEphemData.firstStateVector_DULT[3], stateDULT[3]); WriteDoubleField(&mEphemData.firstStateVector_DULT[4], stateDULT[4]); WriteDoubleField(&mEphemData.firstStateVector_DULT[5], stateDULT[5]); #ifdef DEBUG_WRITE_DATA_SEGMENT DebugDouble("mEphemData.firstStateVector_DULT[0] =% 1.15e\n", mEphemData.firstStateVector_DULT[0], mSwapOutputEndian); #endif // Write state 2 through numPoints, // data record state vector index starts from 0 and ends at numPoints - 1 for (int i = 1; i < numPoints; i++) { ConvertStateKmSecToDULT(mStateArray[i], stateDULT); for (int j = 0; j < 6; j++) WriteDoubleField(&mEphemData.stateVector2Thru50_DULT[i-1][j], stateDULT[j]); #ifdef DEBUG_WRITE_DATA_SEGMENT_MORE MessageInterface::ShowMessage("----- State vector %d\n", i+1); DebugWriteState(mStateArray[i], stateDULT, 2); DebugWriteStateVector(mEphemData.stateVector2Thru50_DULT[i-1], i-1, 1); #endif } #ifdef DEBUG_WRITE_DATA_SEGMENT MessageInterface::ShowMessage("Check if sentinel data needs to be written out\n"); #endif // If data points received is less than NUM_STATES_PER_RECORD, write sentinel flag if ((numPoints < NUM_STATES_PER_RECORD) && canFinalize) { #ifdef DEBUG_WRITE_SENTINELS MessageInterface::ShowMessage ("===> Writing %d sentinel data\n", NUM_STATES_PER_RECORD-numPoints); #endif for (int i = numPoints - 1; i < NUM_STATES_PER_RECORD - 1; i++) { for (int j = 0; j < 6; j++) WriteDoubleField(&mEphemData.stateVector2Thru50_DULT[i][j], mSentinelData); #ifdef DEBUG_WRITE_DATA_SEGMENT_MORE DebugWriteStateVector(mEphemData.stateVector2Thru50_DULT[i], i, 1); #endif } } // Write time of first data point and time interval in DUT #ifdef DEBUG_WRITE_DATA_SEGMENT MessageInterface::ShowMessage("Writing time of first data point and time interval\n"); #endif double timeInDUT = ToDUT(startMjd); WriteDoubleField(&mEphemData.timeOfFirstDataPoint_DUT, timeInDUT); WriteDoubleField(&mEphemData.timeIntervalBetweenPoints_SEC, mTimeIntervalBetweenPointsSecs); WriteDoubleField(&mEphemData.timeIntervalBetweenPoints_DUT, mTimeIntervalBetweenPointsSecs * SEC_TO_DUT); // Write data record #ifdef DEBUG_WRITE_DATA_SEGMENT MessageInterface::ShowMessage("Calling WriteDataAt(%d)\n", mDataRecWriteCounter); #endif WriteDataAt(mDataRecWriteCounter); // Flush data to a file mEphemFileOut.flush(); // If last data record contains NUM_STATES_PER_RECORD valid states and writing // final data, write next record with 10 sentinels. if (numPoints == NUM_STATES_PER_RECORD && canFinalize) { #ifdef DEBUG_WRITE_SENTINELS MessageInterface::ShowMessage ("===> Writing last data record with first 10 sentinel data\n"); #endif // Initialize state vectors with sentinel value InitializeDataRecord(); // Write 4 fields with sentinels WriteDoubleField(&mEphemData.dateOfFirstEphemPoint_YYYMMDD, mSentinelData); WriteDoubleField(&mEphemData.dayOfYearForFirstEphemPoint, mSentinelData); WriteDoubleField(&mEphemData.secsOfDayForFirstEphemPoint, mSentinelData); WriteDoubleField(&mEphemData.timeIntervalBetweenPoints_SEC, mSentinelData); mDataRecWriteCounter++; WriteDataAt(mDataRecWriteCounter); } // Flush data to a file mEphemFileOut.flush(); #ifdef DEBUG_WRITE_DATA_SEGMENT MessageInterface::ShowMessage("Code500EphemerisFile::WriteDataRecord() leaving\n"); #endif } //------------------------------------------------------------------------------ // double ReadDoubleField(double *field) //------------------------------------------------------------------------------ double Code500EphemerisFile::ReadDoubleField(double *field) { double value = *field; if (mSwapInputEndian) { mDoubleOriginBytes.doubleValue = value; double swapped = SwapDouble(); value = swapped; } return value; } //------------------------------------------------------------------------------ // int ReadIntegerField(int *field) //------------------------------------------------------------------------------ int Code500EphemerisFile::ReadIntegerField(int *field) { int value = *field; if (mSwapInputEndian) { mIntOriginBytes.intValue = value; int swapped = SwapInteger(); value = swapped; } return value; } //------------------------------------------------------------------------------ // void WriteDoubleField(double *field, double value) //------------------------------------------------------------------------------ void Code500EphemerisFile::WriteDoubleField(double *field, double value) { if (mSwapOutputEndian) { mDoubleOriginBytes.doubleValue = value; double swapped = SwapDouble(); *field = swapped; } else { *field = value; } } //------------------------------------------------------------------------------ // void WriteIntegerField(int *field, int value) //------------------------------------------------------------------------------ void Code500EphemerisFile::WriteIntegerField(int *field, int value) { if (mSwapOutputEndian) { mIntOriginBytes.intValue = value; int swapped = SwapInteger(); *field = swapped; } else { *field = value; } } //------------------------------------------------------------------------------ // void ClearBuffer() //------------------------------------------------------------------------------ void Code500EphemerisFile::ClearBuffer() { #ifdef DEBUG_CLEAR_BUFFER MessageInterface::ShowMessage ("Code500EphemerisFile::ClearBuffer() entered, mA1MjdArray.size()=%d, " "mStateArray.size()=%d\n", mA1MjdArray.size(), mStateArray.size()); #endif EpochArray::iterator ei; for (ei = mA1MjdArray.begin(); ei != mA1MjdArray.end(); ++ei) delete (*ei); StateArray::iterator si; for (si = mStateArray.begin(); si != mStateArray.end(); ++si) delete (*si); mA1MjdArray.clear(); mStateArray.clear(); } //------------------------------------------------------------------------------ // void UnpackHeader1() //------------------------------------------------------------------------------ void Code500EphemerisFile::UnpackHeader1() { MessageInterface::ShowMessage("======================================== Begin of Header1\n"); bool swap = mSwapInputEndian; MessageInterface::ShowMessage("mSwapInputEndian = %d\n", mSwapInputEndian); std::string str(mEphemHeader1.productId); MessageInterface::ShowMessage("productId = '%s'\n", str.substr(0,8).c_str()); DebugDouble("satId = % f\n", mEphemHeader1.satId, swap); DebugDouble("timeSystemIndicator = % f\n", mEphemHeader1.timeSystemIndicator, swap); DebugDouble("StartDateOfEphem_YYYMMDD = % f\n", mEphemHeader1.startDateOfEphem_YYYMMDD, swap); DebugDouble("startDayCountOfYear = % f\n", mEphemHeader1.startDayCountOfYear, swap); DebugDouble("startSecondsOfDay = % f\n", mEphemHeader1.startSecondsOfDay, swap); DebugDouble("endDateOfEphem_YYYMMDD = % f\n", mEphemHeader1.endDateOfEphem_YYYMMDD, swap); DebugDouble("endDayCountOfYear = % f\n", mEphemHeader1.endDayCountOfYear, swap); DebugDouble("endSecondsOfDay = % f\n", mEphemHeader1.endSecondsOfDay, swap); DebugDouble("stepSize_SEC = % f\n", mEphemHeader1.stepSize_SEC, swap); double yyymmddStart = ReadDoubleField(&mEphemHeader1.startDateOfEphem_YYYMMDD); //MessageInterface::ShowMessage("==> yyymmddStart = %f\n", yyymmddStart); if (mInputYearFormat == 2) yyymmddStart = yyymmddStart - 19000000; //MessageInterface::ShowMessage("==> yyymmddStart = %f\n", yyymmddStart); double secsOfDayStart = ReadDoubleField(&mEphemHeader1.startSecondsOfDay); std::string ymdhmsStart = ToYearMonthDayHourMinSec(yyymmddStart, secsOfDayStart); MessageInterface::ShowMessage("startYYYYMMDDHHMMSSsss. = %s\n", ymdhmsStart.c_str()); double yyymmddEnd = ReadDoubleField(&mEphemHeader1.endDateOfEphem_YYYMMDD); if (mInputYearFormat == 2) yyymmddEnd = yyymmddEnd - 19000000; double secsOfDayEnd = ReadDoubleField(&mEphemHeader1.endSecondsOfDay); std::string ymdhmsEnd = ToYearMonthDayHourMinSec(yyymmddEnd, secsOfDayEnd); MessageInterface::ShowMessage("endYYYYMMDDHHMMSSsss. = %s\n", ymdhmsEnd.c_str()); std::string tapeIdStr = mEphemHeader1.tapeId; std::string sourceIdStr = mEphemHeader1.sourceId; std::string headerTitleStr = mEphemHeader1.headerTitle; std::string coordSystemStr = mEphemHeader1.coordSystemIndicator1; std::string orbitTheoryStr = mEphemHeader1.orbitTheory; MessageInterface::ShowMessage("tapeId = '%s'\n", tapeIdStr.substr(0,8).c_str()); MessageInterface::ShowMessage("sourceId = '%s'\n", sourceIdStr.substr(0,8).c_str()); MessageInterface::ShowMessage("headerTitle = '%s'\n", headerTitleStr.substr(0,56).c_str()); DebugDouble("centralBodyIndicator = % f\n", mEphemHeader1.centralBodyIndicator, swap); DebugDouble("coordinateCenterIndicator = % f\n", mEphemHeader1.coordinateCenterIndicator, swap); DebugDouble("refTimeForDUT_YYMMDD = % f\n", mEphemHeader1.refTimeForDUT_YYMMDD, swap); MessageInterface::ShowMessage("coordSystemIndicator1 = '%s'\n", coordSystemStr.substr(0,4).c_str()); DebugInteger("coordSystemIndicator2 = %d\n", mEphemHeader1.coordSystemIndicator2, swap); DebugInteger("coordSystemIndicator2 = %d\n", mCoordSystemIndicator, swap); MessageInterface::ShowMessage("orbitTheory = '%s'\n", orbitTheoryStr.substr(0,8).c_str()); double timeIntervalDUT = ReadDoubleField(&mEphemHeader1.timeIntervalBetweenPoints_DUT); DebugDouble("timeIntervalBetweenPoints_DUT = % f\n", timeIntervalDUT); DebugDouble("timeIntervalBetweenPoints_SEC. = % f\n", timeIntervalDUT * DUT_TO_SEC, false); DebugInteger("outputIntervalIndicator = %d\n", mEphemHeader1.outputIntervalIndicator, swap); double epochTimeDUT = ReadDoubleField(&mEphemHeader1.epochTimeOfElements_DUT); DebugDouble("epochTimeOfElements_DUT = % f\n", epochTimeDUT); DebugDouble("epochTimeOfElements_DAY. = % f\n", epochTimeDUT * DUT_TO_DAY, false); double dutTime = ReadDoubleField(&mEphemHeader1.epochTimeOfElements_DUT); std::string epochA1Greg = ToA1Gregorian(dutTime, false); MessageInterface::ShowMessage("epochA1Greg. = '%s'\n", epochA1Greg.c_str()); std::string epochUtcGreg = ToUtcGregorian(dutTime, false); MessageInterface::ShowMessage("epochUtcGreg. = '%s'\n", epochUtcGreg.c_str()); DebugDouble("yearOfEpoch_YYY = % f\n", mEphemHeader1.yearOfEpoch_YYY, swap); DebugDouble("monthOfEpoch_MM = % f\n", mEphemHeader1.monthOfEpoch_MM, swap); DebugDouble("dayOfEpoch_DD = % f\n", mEphemHeader1.dayOfEpoch_DD, swap); DebugDouble("hourOfEpoch_HH = % f\n", mEphemHeader1.hourOfEpoch_HH, swap); DebugDouble("minuteOfEpoch_MM = % f\n", mEphemHeader1.minuteOfEpoch_MM, swap); DebugDouble("secondsOfEpoch_MILSEC = % f\n", mEphemHeader1.secondsOfEpoch_MILSEC, swap); // SMA is not angular DebugDouble("keplerianElementsAtEpoch_RAD[0] = % 1.15e\n", mEphemHeader1.keplerianElementsAtEpoch_RAD[0], swap); for (int i = 1; i < 6; i++) { double elemRad = ReadDoubleField(&mEphemHeader1.keplerianElementsAtEpoch_RAD[i]); DebugDouble("keplerianElementsAtEpoch_RAD[%d] = % 1.15e\n", i, elemRad, false); DebugDouble("keplerianElementsAtEpoch_DEG[%d]. = % 1.15e\n", i, elemRad * GmatMathConstants::DEG_PER_RAD, false); } for (int i = 0; i < 3; i++) { double posDult = ReadDoubleField(&mEphemHeader1.cartesianElementsAtEpoch_DULT[i]); DebugDouble("cartesianElementsAtEpoch_DULT[%d] = % 1.15e\n", i, posDult, false); DebugDouble("cartesianElementsAtEpoch_KMSE[%d]. = % 1.15e\n", i, posDult * DUL_TO_KM, false); } for (int i = 3; i < 6; i++) { double velDult = ReadDoubleField(&mEphemHeader1.cartesianElementsAtEpoch_DULT[i]); DebugDouble("cartesianElementsAtEpoch_DULT[%d] = % 1.15e\n", i, velDult, false); DebugDouble("cartesianElementsAtEpoch_KMSE[%d]. = % 1.15e\n", i, velDult * DUL_DUT_TO_KM_SEC, false); } double rval = ReadDoubleField(&mEphemHeader1.startTimeOfEphemeris_DUT); DebugDouble("startTimeOfEphemeris_DUT = % f\n", rval, false); DebugDouble("startTimeOfEphemeris_DAY. = % f\n", rval * DUT_TO_DAY, false); rval = ReadDoubleField(&mEphemHeader1.endTimeOfEphemeris_DUT); DebugDouble("endTimeOfEphemeris_DUT = % f\n", rval, false); DebugDouble("endTimeOfEphemeris_DAY. = % f\n", rval * DUT_TO_DAY, false); rval = ReadDoubleField(&mEphemHeader1.timeIntervalBetweenPoints_DUT); DebugDouble("timeIntervalBetweenPoints_DUT = % f\n", rval, false); DebugDouble("timeIntervalBetweenPoints_SEC. = % f\n", rval * DUT_TO_SEC, false); DebugDouble("precessionNutationIndicator = % f\n", mEphemHeader1.precessionNutationIndicator, swap); DebugDouble("zonalTesseralHarmonicsIndicator = % f\n", mEphemHeader1.zonalTesseralHarmonicsIndicator, swap); DebugDouble("lunarGravPerturbIndicator = % f\n", mEphemHeader1.lunarGravPerturbIndicator, swap); DebugDouble("solarRadiationPerturbIndicator = % f\n", mEphemHeader1.solarRadiationPerturbIndicator, swap); DebugDouble("solarGravPerturbIndicator = % f\n", mEphemHeader1.solarGravPerturbIndicator, swap); DebugDouble("atmosphericDragPerturbIndicator = % f\n", mEphemHeader1.atmosphericDragPerturbIndicator, swap); DebugDouble("dateOfInitiationOfEphemComp_YYYMMDD = % f\n", mEphemHeader1.dateOfInitiationOfEphemComp_YYYMMDD, swap); DebugDouble("timeOfInitiationOfEphemComp_HHMMSS = % f\n", mEphemHeader1.timeOfInitiationOfEphemComp_HHMMSS, swap); DebugInteger("leapSecondIndicator = % d\n", mEphemHeader1.leapSecondIndicator, swap); DebugDouble("dateOfLeapSeconds_YYYMMDD = % f\n", mEphemHeader1.dateOfLeapSeconds_YYYMMDD, swap); DebugDouble("dateOfLeapSeconds_HHMMSS = % f\n", mEphemHeader1.timeOfLeapSeconds_HHMMSS, swap); DebugDouble("utcTimeAdjustment_SEC = % .9f\n", mEphemHeader1.utcTimeAdjustment_SEC, swap); MessageInterface::ShowMessage("======================================== End of Header1\n"); } //------------------------------------------------------------------------------ // void UnpackHeader2() //------------------------------------------------------------------------------ void Code500EphemerisFile::UnpackHeader2() { #ifdef DEBUG_UNPACK_HEADERS MessageInterface::ShowMessage ("======================================== Begin of Header2\n ... todo ..."); #endif } //------------------------------------------------------------------------------ // void UnpackDataRecord(int recNum, int logOption) //------------------------------------------------------------------------------ /** * Unpacks data fields in the data record. * * @param recNum Data record number (must start from 3) * @param logOption = 0, no log * = 1, log first state vector of only first and last record * = 2, log first and last state vector of all records * = 3, log all state vectors of all records */ //------------------------------------------------------------------------------ void Code500EphemerisFile::UnpackDataRecord(int recNum, int logOption) { if ((logOption > 1) || (logOption == 1 && recNum == 1) || (logOption == 1 && mSentinelsFound)) MessageInterface::ShowMessage ("======================================== Begin of data record %d\nmSentinelsFound = %s\n", recNum, mSentinelsFound ? "true" : "false"); bool swap = mSwapInputEndian; double sentinels[50]; sentinels[0] = ReadDoubleField(&mEphemData.dateOfFirstEphemPoint_YYYMMDD); sentinels[1] = ReadDoubleField(&mEphemData.dayOfYearForFirstEphemPoint); sentinels[2] = ReadDoubleField(&mEphemData.secsOfDayForFirstEphemPoint); sentinels[3] = ReadDoubleField(&mEphemData.timeIntervalBetweenPoints_SEC); mLastDataRecRead = recNum; if ((logOption > 1) || (logOption == 1 && recNum == 1) || (logOption == 1 && mSentinelsFound)) { double firstDate = ReadDoubleField(&mEphemData.dateOfFirstEphemPoint_YYYMMDD); double firstSecs = ReadDoubleField(&mEphemData.secsOfDayForFirstEphemPoint); std::string ymdhmsStr = "sentinel"; // If data and secs are not sentinels, convert to string if ((!GmatMathUtil::IsEqual(firstDate, mSentinelData, 10.0) && !GmatMathUtil::IsEqual(firstSecs, mSentinelData, 10.0))) ymdhmsStr = ToYearMonthDayHourMinSec(firstDate, firstSecs); MessageInterface::ShowMessage("timeOfFirstEphemPoint. = %s\n", ymdhmsStr.c_str()); DebugDouble("dateOfFirstEphemPoint_YYYMMDD = % f\n", mEphemData.dateOfFirstEphemPoint_YYYMMDD, swap); DebugDouble("dayOfYearForFirstEphemPoint = % f\n", mEphemData.dayOfYearForFirstEphemPoint, swap); DebugDouble("secsOfDayForFirstEphemPoint = % f\n", mEphemData.secsOfDayForFirstEphemPoint, swap); DebugDouble("timeIntervalBetweenPoints_SEC = % f\n", mEphemData.timeIntervalBetweenPoints_SEC, swap); } double posDult, velDult; // First position vector for (int j = 0; j < 3; j++) { sentinels[4+j] = ReadDoubleField(&mEphemData.firstStateVector_DULT[j]); posDult = ReadDoubleField(&mEphemData.firstStateVector_DULT[j]); if ((logOption > 1) || (logOption == 1 && recNum == 1) || (logOption == 1 && mSentinelsFound)) { DebugDouble("firstStateVector_DULT[%d] = % 1.15e\n", j, posDult, false); DebugDouble("firstStateVector_KMSE[%d]. = % 1.15e\n", j, posDult * DUL_TO_KM, false); } } // First velocity vector for (int j = 3; j < 6; j++) { sentinels[4+j] = ReadDoubleField(&mEphemData.firstStateVector_DULT[j]); velDult = ReadDoubleField(&mEphemData.firstStateVector_DULT[j]); if ((logOption > 1) || (logOption == 1 && recNum == 1) || (logOption == 1 && mSentinelsFound)) { DebugDouble("firstStateVector_DULT[%d] = % 1.15e\n", j, velDult, false); DebugDouble("firstStateVector_KMSE[%d]. = % 1.15e\n", j, velDult * DUL_DUT_TO_KM_SEC, false); } } // If sentinels already found, log data and return if (mSentinelsFound) { int i = mLastStateIndexRead; if (logOption >= 2) MessageInterface::ShowMessage("timeOfLastEphemPoint. = %s\n", mLastDataRecEndGreg.c_str()); for (int j = 0; j < 3; j++) { posDult = ReadDoubleField(&mEphemData.stateVector2Thru50_DULT[i][j]); if (logOption >= 2) { DebugDouble("stateVector2Thru50_DULT[%2d][%2d] = % 1.15e\n", i, j, posDult, false); DebugDouble("stateVector2Thru50_KMSE[%2d][%2d].= % 1.15e\n", i, j, posDult * DUL_TO_KM, false); } } for (int j = 3; j < 6; j++) { velDult = ReadDoubleField(&mEphemData.stateVector2Thru50_DULT[i][j]); if (logOption >= 2) { DebugDouble("stateVector2Thru50_DULT[%2d][%2d] = % 1.15e\n", i, j, velDult, false); DebugDouble("stateVector2Thru50_KMSE[%2d][%2d].= % 1.15e\n", i, j, velDult * DUL_DUT_TO_KM_SEC, false); } } return; } // Check for sentinels int sentinelCount = 0; for (int k = 0; k < 10; k++) { #ifdef DEBUG_UNPACK_DATA MessageInterface::ShowMessage(" sentinels[%d] = % 1.15e\n", k, sentinels[k]); #endif if (GmatMathUtil::IsEqual(sentinels[k], mSentinelData, 10.0)) sentinelCount++; } #ifdef DEBUG_UNPACK_DATA MessageInterface::ShowMessage(" sentinelCount = %d\n", sentinelCount); #endif if (sentinelCount == 10) { if (logOption > 0) MessageInterface::ShowMessage("=====> First 10 sentinels found\n"); mSentinelsFound = true; mLastStateIndexRead = -1; return; } // Initially set last state index to 48, index starts from 0 to 48 mLastStateIndexRead = 48; // State vector 2 through NUM_STATES_PER_RECORD for (int i = 0; i < NUM_STATES_PER_RECORD - 1; i++) { sentinelCount = 0; for (int j = 0; j < 3; j++) sentinels[j] = ReadDoubleField(&mEphemData.stateVector2Thru50_DULT[i][j]); for (int j = 3; j < 6; j++) sentinels[j] = ReadDoubleField(&mEphemData.stateVector2Thru50_DULT[i][j]); if (logOption > 2 || (logOption == 2 && i == mLastStateIndexRead)) DebugWriteStateVector(mEphemData.stateVector2Thru50_DULT[i], i, 6, swap); #ifdef DEBUG_UNPACK_DATA MessageInterface::ShowMessage("Checking for sentinels\n"); #endif // Check for sentinels for (int k = 0; k < 6; k++) { if (GmatMathUtil::IsEqual(sentinels[k], mSentinelData, 10.0)) sentinelCount++; } #ifdef DEBUG_UNPACK_DATA MessageInterface::ShowMessage("sentinelCount = %d\n", sentinelCount); #endif if (sentinelCount > 5) { if (logOption > 0) MessageInterface::ShowMessage("=====> State sentinels found\n"); mSentinelsFound = true; mLastStateIndexRead = i - 1; break; } #ifdef DEBUG_UNPACK_DATA MessageInterface::ShowMessage("Checking for zero state vector\n"); #endif // Check for zero vector sentinelCount = 0; for (int k = 0; k < 6; k++) { #ifdef DEBUG_UNPACK_DATA MessageInterface::ShowMessage("sentinels[%d] = % 1.15e\n", k, sentinels[k]); #endif // Check for zero state vector if (GmatMathUtil::IsZero(sentinels[k], 1e-12)) sentinelCount++; } #ifdef DEBUG_UNPACK_DATA MessageInterface::ShowMessage("sentinelCount = %d\n", sentinelCount); #endif if (sentinelCount > 5) { if (logOption > 0) MessageInterface::ShowMessage("=====> State zero vector found\n"); mSentinelsFound = true; mLastStateIndexRead = i - 1; break; } } #ifdef DEBUG_UNPACK_DATA MessageInterface::ShowMessage("mLastStateIndexRead = %d\n", mLastStateIndexRead); #endif if ((logOption > 1) || (logOption == 1 && recNum == 1) || (logOption == 1 && mSentinelsFound)) { DebugDouble("timeOfFirstDataPoint_DUT = % f\n", mEphemData.timeOfFirstDataPoint_DUT, swap); DebugDouble("timeIntervalBetweenPoints_DUT = % f\n", mEphemData.timeIntervalBetweenPoints_DUT, swap); DebugDouble("thrustIndicator = % f\n", mEphemData.thrustIndicator, swap); MessageInterface::ShowMessage ("======================================== End of data record %d\n", recNum); } ephemRecords.push_back(mEphemData); } //------------------------------------------------------------------------------ // void ConvertStateKmSecToDULT(Rvector6 *kmsec, double *dult) //------------------------------------------------------------------------------ void Code500EphemerisFile::ConvertStateKmSecToDULT(Rvector6 *kmsec, double *dult) { // DUT = 864 seconds // DUL = 10000 km dult[0] = kmsec->Get(0) * KM_TO_DUL; dult[1] = kmsec->Get(1) * KM_TO_DUL; dult[2] = kmsec->Get(2) * KM_TO_DUL; dult[3] = kmsec->Get(3) * KM_SEC_TO_DUL_DUT; dult[4] = kmsec->Get(4) * KM_SEC_TO_DUL_DUT; dult[5] = kmsec->Get(5) * KM_SEC_TO_DUL_DUT; } //------------------------------------------------------------------------------ // void ConvertAsciiToEbcdic(char *ascii, char *ebcdic, int numChars) //------------------------------------------------------------------------------ void Code500EphemerisFile::ConvertAsciiToEbcdic(char *ascii, char *ebcdic, int numChars) { unsigned char asc; unsigned char ebc; for (int i = 0; i < numChars; i++) { asc = (unsigned char)ascii[i]; ebc = AsciiToEbcdic(asc); ebcdic[i] = (char)ebc; } } //------------------------------------------------------------------------------ // void ConvertEbcdicToAscii(char *ebcdic, char *ascii, int numChars) //------------------------------------------------------------------------------ void Code500EphemerisFile::ConvertEbcdicToAscii(char *ebcdic, char *ascii, int numChars) { unsigned char asc; unsigned char ebc; for (int i = 0; i < numChars; i++) { ebc = (unsigned char)ebcdic[i]; asc = EbcdicToAscii(ebc); ascii[i] = (char)asc; } } //------------------------------------------------------------------------------ // Real Code500EphemerisFile::GetTimeSystem() //------------------------------------------------------------------------------ /** * Returns the time system as set mOutputTimeSystem * * @return The real number value for the time system setting */ //------------------------------------------------------------------------------ Real Code500EphemerisFile::GetTimeSystem() { return mOutputTimeSystem; } //------------------------------------------------------------------------------ // std::string GetCentralBody() //------------------------------------------------------------------------------ /** * Retrieves the name of the central body of output ephem * * @return The central body name */ //------------------------------------------------------------------------------ std::string Code500EphemerisFile::GetCentralBody() { mOutputCentralBody = GetBodyName(mCentralBodyOfOutputEphem, 2); return mOutputCentralBody; } //------------------------------------------------------------------------------ // Integer GetCoordSystemIndicator() //------------------------------------------------------------------------------ /** * Retrieves the coordinate system indicator * * @return The coordinate system indicator */ //------------------------------------------------------------------------------ Integer Code500EphemerisFile::GetCoordSystemIndicator() { return mCoordSystemIndicator; } //------------------------------------------------------------------------------ // void ToYearMonthDayHourMinSec(double yyymmdd, double secsOfDay, ... //------------------------------------------------------------------------------ void Code500EphemerisFile::ToYearMonthDayHourMinSec(double yyymmdd, double secsOfDay, int &year, int &month, int &day, int &hour, int &min, double &sec) { ToYearMonthDay(yyymmdd, year, month, day); ToHMSFromSecondsOfDay(secsOfDay, hour, min, sec); } //------------------------------------------------------------------------------ // std::string ToYearMonthDayHourMinSec(double yyymmdd, double secsOfDay) //------------------------------------------------------------------------------ std::string Code500EphemerisFile::ToYearMonthDayHourMinSec(double yyymmdd, double secsOfDay) { int year, month, day, hour, min; double sec; ToYearMonthDayHourMinSec(yyymmdd, secsOfDay, year, month, day, hour, min, sec); char buffer[30]; sprintf(buffer, "%d-%02d-%02d %02d:%02d:%09.6f", year, month, day, hour, min, sec); return std::string(buffer); } //------------------------------------------------------------------------------ // void ToYearMonthDay(double yyymmdd, int &year, int &month, int &day) //------------------------------------------------------------------------------ /** * Converts time in yyymmdd to yyyy, mm, day. */ //------------------------------------------------------------------------------ void Code500EphemerisFile::ToYearMonthDay(double yyymmdd, int &year, int &month, int &day) { double yyyymmdd = yyymmdd + 19000000; UnpackDate(yyyymmdd, year, month, day); } //------------------------------------------------------------------------------ // void ToYYYMMDDHHMMSS(double mjd, double &ymd, double &hms) //------------------------------------------------------------------------------ void Code500EphemerisFile::ToYYYMMDDHHMMSS(double mjd, double &ymd, double &hms) { A1Mjd tempA1Mjd(mjd); A1Date a1Date = tempA1Mjd.ToA1Date(); a1Date.ToYearMonthDayHourMinSec(ymd, hms); // Since ymd is in yyyymmdd, subtract 19000000 ymd = ymd - 19000000.0; } //------------------------------------------------------------------------------ // double ToDUT(double mjd) //------------------------------------------------------------------------------ double Code500EphemerisFile::ToDUT(double mjd) { double dut = (mjd - mMjdOfDUTRef) * DAY_TO_DUT; return dut; } //------------------------------------------------------------------------------ // double ToUtcModJulian(const A1Mjd &a1Mjd) //------------------------------------------------------------------------------ double Code500EphemerisFile::ToUtcModJulian(const A1Mjd &a1Mjd) { #ifdef DEBUG_TIME_CONVERSION MessageInterface::ShowMessage("ToUtcModJulian() entered, a1Mjd=%f\n", a1Mjd.GetReal()); #endif Real a1MjdReal = a1Mjd.GetReal(); //std::string epochStr; //Integer format = 1; // Need to apply leap seconds, so use TimeSystemConverter // Convert current epoch to specified format //theTimeConverter->Convert("A1ModJulian", mjd, "", "UTCModJulian", // utcMjd, epochStr, format); Real utcMjd = theTimeConverter->Convert(a1MjdReal, TimeSystemConverter::A1MJD, TimeSystemConverter::UTCMJD); #ifdef DEBUG_TIME_CONVERSION MessageInterface::ShowMessage("ToUtcModJulian() returning utcMjd=%f\n", utcMjd); #endif return utcMjd; } //------------------------------------------------------------------------------ // double ToYYYMMDD(double mjd) //------------------------------------------------------------------------------ /** * Converts mod julian days to YYYMMDD format. Assuming input mjd has * leap seconds already applied for UTC time system. * * @param mjd Modified julian days in A1 or UTC, or other time system */ //------------------------------------------------------------------------------ double Code500EphemerisFile::ToYYYMMDD(double mjd) { #ifdef DEBUG_TIME_CONVERSION MessageInterface::ShowMessage("ToYYYMMDD() entered, mjd=% f\n", mjd); #endif A1Mjd tempA1Mjd(mjd); A1Date a1Date = tempA1Mjd.ToA1Date(); double yyymmdd = a1Date.ToPackedYYYMMDD(); #ifdef DEBUG_TIME_CONVERSION MessageInterface::ShowMessage("ToYYYMMDD() returning % f\n", yyymmdd); #endif return yyymmdd; } //------------------------------------------------------------------------------ // double ToHHMMSS(double mjd) //------------------------------------------------------------------------------ /** * Converts mod julian days to HHMMSS.mmm format. Assuming input mjd has * leap seconds already applied for UTC time system. * * @param mjd Modified julian days in A1 or UTC, or other time system */ //------------------------------------------------------------------------------ double Code500EphemerisFile::ToHHMMSS(double mjd) { #ifdef DEBUG_TIME_CONVERSION MessageInterface::ShowMessage("ToHHMMSS() entered, mjd=f\n", mjd); #endif A1Mjd tempA1Mjd(mjd); A1Date a1Date = tempA1Mjd.ToA1Date(); double hhmmss = a1Date.ToPackedHHMMSS(); #ifdef DEBUG_TIME_CONVERSION MessageInterface::ShowMessage("ToHHMMSS() returning % f\n", hhmmss); #endif return hhmmss; } //------------------------------------------------------------------------------ // double ToDayOfYear(double mjd) //------------------------------------------------------------------------------ /** * Converts mod julian days to day of year. Assuming input mjd has * leap seconds already applied for UTC time system. * * @param mjd Modified julian days in A1 or UTC, or other time system */ //------------------------------------------------------------------------------ double Code500EphemerisFile::ToDayOfYear(double mjd) { #ifdef DEBUG_TIME_CONVERSION MessageInterface::ShowMessage("ToDayOfYear() entered, mjd=%f\n", mjd); #endif A1Mjd tempA1Mjd(mjd); A1Date a1Date = tempA1Mjd.ToA1Date(); double doy = a1Date.ToDayOfYear(); #ifdef DEBUG_TIME_CONVERSION MessageInterface::ShowMessage("ToDayOfYear() returning % f\n", doy); #endif return doy; } //------------------------------------------------------------------------------ // double ToSecondsOfDay(double mjd) //------------------------------------------------------------------------------ /** * Converts mod julian days to seconds of day part. Assuming input mjd has * leap seconds already applied for UTC time system. * * @param mjd Modified julian days in A1 or UTC, or other time system */ //------------------------------------------------------------------------------ double Code500EphemerisFile::ToSecondsOfDay(double mjd) { #ifdef DEBUG_TIME_CONVERSION MessageInterface::ShowMessage("ToSecondsOfDay() entered, mjd=%f\n", mjd); #endif A1Mjd tempA1Mjd(mjd); A1Date a1Date = tempA1Mjd.ToA1Date(); double secs = a1Date.GetSecondsOfDay(); #ifdef DEBUG_TIME_CONVERSION MessageInterface::ShowMessage("ToSecondsOfDay() returning % f\n", secs); #endif return secs; } //------------------------------------------------------------------------------ // A1Mjd ToA1Mjd(double dutTime, bool forOutput = true) //------------------------------------------------------------------------------ /** * Converts DUT time in given time system to A1Mjd. * * @param dutTime Input time in DUT unit(centiday) * @param forOutput true if converting for writing */ //------------------------------------------------------------------------------ A1Mjd Code500EphemerisFile::ToA1Mjd(double dutTime, bool forOutput) { #ifdef DEBUG_TIME_CONVERSION MessageInterface::ShowMessage ("ToA1Mjd() entered, dutTime=%f, forOutput=%d, mInputTimeSystem=%f\n", dutTime, forOutput, mInputTimeSystem); #endif Real timeOffset = 0.0; double a1MjdReal = (dutTime * DUT_TO_DAY) + mMjdOfDUTRef + timeOffset; A1Mjd a1Mjd = A1Mjd(a1MjdReal); #ifdef DEBUG_TIME_CONVERSION MessageInterface::ShowMessage ("ToA1Mjd() returning a1Mjd=%f for dutTime=%f\n", a1MjdReal, dutTime); #endif return a1Mjd; } //------------------------------------------------------------------------------ // std::string ToA1Gregorian(double dutTime, bool forOutput = true) //------------------------------------------------------------------------------ /** * Converts DUT time to A1 Gregorian time system (no leap seconds) * * @param dutTime time in DUT unit (centiday) * @param forOutput true if converting for writing */ //------------------------------------------------------------------------------ std::string Code500EphemerisFile::ToA1Gregorian(double dutTime, bool forOutput) { #ifdef DEBUG_TIME_CONVERSION MessageInterface::ShowMessage ("ToA1Gregorian() entered, dutTime=%f, forOutput=%d\n", dutTime, forOutput); #endif A1Mjd tempA1Mjd = ToA1Mjd(dutTime, forOutput); std::string epochStr = ToA1Gregorian(tempA1Mjd); #ifdef DEBUG_TIME_CONVERSION MessageInterface::ShowMessage ("ToA1Gregorian() returning '%s' for dutTime=%f\n", epochStr.c_str(), dutTime); #endif return epochStr; } //------------------------------------------------------------------------------ // std::string ToA1Gregorian(const A1Mjd &a1Mjd) //------------------------------------------------------------------------------ /** * Converts A1 mod julian time to A1 Gregorian time system (no leap seconds) */ //------------------------------------------------------------------------------ std::string Code500EphemerisFile::ToA1Gregorian(const A1Mjd &a1Mjd) { // format 1 = "01 Jan 2000 11:59:28.000" // 2 = "2000-01-01T11:59:28.000" #ifdef DEBUG_TIME_CONVERSION MessageInterface::ShowMessage("ToA1Gregorian() entered, a1Mjd=%f\n", a1Mjd.GetReal()); #endif Integer format = 1; A1Mjd tempA1Mjd = a1Mjd; A1Date a1Date = tempA1Mjd.ToA1Date(); GregorianDate gregorianDate(&a1Date, format); std::string epochStr = gregorianDate.GetDate(); #ifdef DEBUG_TIME_CONVERSION MessageInterface::ShowMessage ("ToA1Gregorian() returning '%s' for a1Mjd=%f\n", epochStr.c_str(), a1Mjd.GetReal()); #endif return epochStr; } //------------------------------------------------------------------------------ // std::string ToUtcGregorian(double dutTime, bool forOutput = true) //------------------------------------------------------------------------------ /** * Converts DUT time to UTC Gregorian time system. * * @param dutTime time in DUT unit (centiday) * @param forOutput true if converting for writing */ //------------------------------------------------------------------------------ std::string Code500EphemerisFile::ToUtcGregorian(double dutTime, bool forOutput) { #ifdef DEBUG_TIME_CONVERSION MessageInterface::ShowMessage ("ToUtcGregorian() entered, dutTime=%f, forOutput=%d\n", dutTime, forOutput); #endif A1Mjd tempA1Mjd = ToA1Mjd(dutTime, forOutput); std::string epochStr = ToUtcGregorian(tempA1Mjd, forOutput); #ifdef DEBUG_TIME_CONVERSION MessageInterface::ShowMessage ("ToUtcGregorian() returning '%s' for dutTime=%f\n", epochStr.c_str(), dutTime); #endif return epochStr; } //------------------------------------------------------------------------------ // std::string ToUtcGregorian(const A1Mjd &a1Mjd, bool forOutput = true) //------------------------------------------------------------------------------ /** * Converts A1 mod julian time to UTC Gregorian time system (with leap seconds) * * @param a1Mjd time in A1 mod julian * @param forOutput true if converting for writing */ //------------------------------------------------------------------------------ std::string Code500EphemerisFile::ToUtcGregorian(const A1Mjd &a1Mjd, bool forOutput) { #ifdef DEBUG_TIME_CONVERSION MessageInterface::ShowMessage ("ToUtcGregorian() entered, a1Mjd=%f, forOutput=%d\n", a1Mjd.GetReal(), forOutput); #endif // format 1 = "01 Jan 2000 11:59:28.000" // 2 = "2000-01-01T11:59:28.000" Integer format = 1; std::string epochStr; if (forOutput) { Real utcMjd; Real epochInDays = a1Mjd.GetReal(); // Need to apply leap seconds, so use TimeSystemConverter // Convert current epoch to specified format theTimeConverter->Convert("A1ModJulian", epochInDays, "", "UTCGregorian", utcMjd, epochStr, format); if (epochStr == "") { MessageInterface::ShowMessage ("**** ERROR **** Code500EphemerisFile::ToUtcGregorian() Cannot convert epoch %.10f " "to UTCGregorian\n", a1Mjd.GetReal()); epochStr = "EpochError"; } } else { // No extra leap seconds applied epochStr = ToA1Gregorian(a1Mjd); } #ifdef DEBUG_TIME_CONVERSION MessageInterface::ShowMessage ("ToUtcGregorian() returning '%s' for a1Mjd=%f\n", epochStr.c_str(), a1Mjd.GetReal()); #endif return epochStr; } //------------------------------------------------------------------------------ // double GetBodyIndicator(const std::string &bodyName, int forWhich) //------------------------------------------------------------------------------ /** * Returns body indicator for integration or ephemeris output * * @param forWhich body indicator for integration = 1 * body indicator for ephemeris output = 2 */ //------------------------------------------------------------------------------ double Code500EphemerisFile::GetBodyIndicator(const std::string &bodyName, int forWhich) { // Central body name from central body of integration // 1.0 = Earth, 2.0 = Luna(Earth Moon), 3.0 = Sun, 4.0 = Mars, 5.0 = Jupiter, // 6.0 = Saturn, 7.0 = Uranus, 8.0 = Neptune, 9.0 = Pluto, 10.0 = Mercury, // 11.0 = Venus // Central body name from central body of ephem output // 0.0 = Earth, 1.0 = Luna(Earth Moon), 2.0 = Sun, 3.0 = Mars, 4.0 = Jupiter, // 5.0 = Saturn, 6.0 = Uranus, 7.0 = Neptune, 8.0 = Pluto, 9.0 = Mercury, // 10.0 = Venus double bodyIndicator = -99.99; if (bodyName == "Earth") bodyIndicator = 1.0; else if (bodyName == "Luna") bodyIndicator = 2.0; else if (bodyName == "Sun") bodyIndicator = 3.0; else if (bodyName == "Mars") bodyIndicator = 4.0; else if (bodyName == "Jupiter") bodyIndicator = 5.0; else if (bodyName == "Saturn") bodyIndicator = 6.0; else if (bodyName == "Uranus") bodyIndicator = 7.0; else if (bodyName == "Neptune") bodyIndicator = 8.0; else if (bodyName == "Pluto") bodyIndicator = 9.0; else if (bodyName == "Mercury") bodyIndicator = 10.0; else if (bodyName == "Venus") bodyIndicator = 11.0; else bodyIndicator = -99.99; if (forWhich == 2) if (bodyIndicator != -99.99) bodyIndicator = bodyIndicator - 1; return bodyIndicator; } //------------------------------------------------------------------------------ // std::string GetBodyName(double bodyInd, int forWhich) //------------------------------------------------------------------------------ /** * Returns body name for integration or ephemeris output * * @param bodyInd body index * @param forWhich body string for integration = 1 * body string for ephemeris output = 2 */ //------------------------------------------------------------------------------ std::string Code500EphemerisFile::GetBodyName(double bodyInd, int forWhich) { #ifdef DEBUG_BODY_NAME MessageInterface::ShowMessage ("Code500EphemerisFile::GetBodyName() entered, bodyInd=%f, forWhich=%d\n", bodyInd, forWhich); #endif std::string bodyName = "Unknown"; double bodyIndicator = bodyInd; // Central body name from central body of integration // 1.0 = Earth, 2.0 = Luna(Earth Moon), 3.0 = Sun, 4.0 = Mars, 5.0 = Jupiter, // 6.0 = Saturn, 7.0 = Uranus, 8.0 = Neptune, 9.0 = Pluto, 10.0 = Mercury, // 11.0 = Venus // Central body name from central body of ephem output // 0.0 = Earth, 1.0 = Luna(Earth Moon), 2.0 = Sun, 3.0 = Mars, 4.0 = Jupiter, // 5.0 = Saturn, 6.0 = Uranus, 7.0 = Neptune, 8.0 = Pluto, 9.0 = Mercury, // 10.0 = Venus if (forWhich == 2) bodyIndicator = bodyInd + 1; #ifdef DEBUG_BODY_NAME MessageInterface::ShowMessage(" bodyIndicator=%d\n", bodyIndicator); #endif if (bodyIndicator == 1.0) bodyName = "Earth"; else if (bodyIndicator == 2.0) bodyName = "Luna"; else if (bodyIndicator == 3.0) bodyName = "Sun"; else if (bodyIndicator == 4.0) bodyName = "Mars"; else if (bodyIndicator == 5.0) bodyName = "Jupiter"; else if (bodyIndicator == 6.0) bodyName = "Saturn"; else if (bodyIndicator == 7.0) bodyName = "Uranus"; else if (bodyIndicator == 8.0) bodyName = "Neptune"; else if (bodyIndicator == 9.0) bodyName = "Pluto"; else if (bodyIndicator == 10.0) bodyName = "Mercury"; else if (bodyIndicator == 11.0) bodyName = "Venus"; #ifdef DEBUG_BODY_NAME MessageInterface::ShowMessage ("Code500EphemerisFile::GetBodyName() returning '%s'\n", bodyName.c_str()); #endif return bodyName; } //------------------------------------------------------------------------------ // void CopyString(char *to, const std::string &from, int numChars) //------------------------------------------------------------------------------ void Code500EphemerisFile::CopyString(char *to, const std::string &from, int numChars) { #ifdef DEBUG_COPY_STRING MessageInterface::ShowMessage ("CopyString() entered, from='%s', numChars=%d\n", from.c_str(), numChars); #endif int fromSize = from.size(); for (int i = 0; i < fromSize; i++) to[i] = from[i]; if (fromSize < numChars) for (int i = fromSize; i < numChars; i++) to[i] = ' '; std::string toStr(to); #ifdef DEBUG_COPY_STRING MessageInterface::ShowMessagememcopoy (" from = '%s'\n to = '%s'\n", from.c_str(), toStr.substr(0,numChars).c_str()); MessageInterface::ShowMessage("CopyString() leaving\n"); #endif } //------------------------------------------------------------------------------ // void CopyString(char *to, char *from, int numChars) //------------------------------------------------------------------------------ void Code500EphemerisFile::CopyString(char *to, char *from, int numChars) { memcpy(to, from, numChars); } //------------------------------------------------------------------------------ // void BlankOut(char *str, int numChars) //------------------------------------------------------------------------------ void Code500EphemerisFile::BlankOut(char *str, int numChars) { for (int i = 0; i < numChars; i++) str[i] = ' '; } //------------------------------------------------------------------------------ // unsigned char AsciiToEbcdic(unsigned char ascii) //------------------------------------------------------------------------------ unsigned char Code500EphemerisFile::AsciiToEbcdic(unsigned char ascii) { unsigned char ebcd; static unsigned char ascToEbcTable[256]= { 0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40, /* */ 0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40, /* */ 0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40, /* */ 0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40, /* */ 0x40,0x4F,0x7F,0x7B,0x5B,0x6C,0x50,0x7D, /* !"#$%&' */ 0x4D,0x5D,0x5C,0x4E,0x6B,0x60,0x4B,0x61, /* ()*+,-./ */ 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7, /* 01234567 */ 0xF8,0xF9,0x7A,0x5E,0x4C,0x7E,0x6E,0x6F, /* 89:;<=>? */ 0x7C,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7, /* @ABCDEFG */ 0xC8,0xC9,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6, /* HIJKLMNO */ 0xD7,0xD8,0xD9,0xE2,0xE3,0xE4,0xE5,0xE6, /* PQRSTUVW */ 0xE7,0xE8,0xE9,0x4A,0xE0,0x5A,0x5F,0x6D, /* XYZ[\]^_ */ 0x79,0x81,0x82,0x83,0x84,0x85,0x86,0x87, /* `abcdefg */ 0x88,0x89,0x91,0x92,0x93,0x94,0x95,0x96, /* hijklmno */ 0x97,0x98,0x99,0xA2,0xA3,0xA4,0xA5,0xA6, /* pqrstuvw */ 0xA7,0xA8,0xA9,0xC0,0x6A,0xD0,0xA1,0x40, /* xyz{|}~ */ 0xB9,0xBA,0xED,0xBF,0xBC,0xBD,0xEC,0xFA, /* */ 0xCB,0xCC,0xCD,0xCE,0xCF,0xDA,0xDB,0xDC, /* */ 0xDE,0xDF,0xEA,0xEB,0xBE,0xCA,0xBB,0xFE, /* */ 0xFB,0xFD,0x7d,0xEF,0xEE,0xFC,0xB8,0xDD, /* */ 0x77,0x78,0xAF,0x8D,0x8A,0x8B,0xAE,0xB2, /* */ 0x8F,0x90,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, /* */ 0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40, /* */ 0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40, /* */ 0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40, /* */ 0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40, /* */ 0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40, /* */ 0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40, /* */ 0xAA,0xAB,0xAC,0xAD,0x8C,0x8E,0x80,0xB6, /* */ 0xB3,0xB5,0xB7,0xB1,0xB0,0xB4,0x76,0xA0, /* */ 0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40, /* */ 0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40 /* */ }; ebcd = ascToEbcTable[ascii]; return (ebcd); } //------------------------------------------------------------------------------ // unsigned char EbcdicToAscii(unsigned char ebcd) //------------------------------------------------------------------------------ unsigned char Code500EphemerisFile::EbcdicToAscii(unsigned char ebcd) { unsigned char asc; static int ebcToAscTable[256]= { 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 91, 46, 60, 40, 43, 33, 38, 32, 32, 32, 32, 32, 32, 32, 32, 32, 93, 36, 42, 41, 59, 94, 45, 47, 32, 32, 32, 32, 32, 32, 32, 32,124, 44, 37, 95, 62, 63, 32, 32, 32, 32, 32, 32,238,160, 161, 96, 58, 35, 64, 39, 61, 34, 230, 97, 98, 99,100,101,102,103, 104,105,164,165,228,163,229,168, 169,106,107,108,109,110,111,112, 113,114,170,171,172,173,174,175, 239,126,115,116,117,118,119,120, 121,122,224,225,226,227,166,162, 236,235,167,232,237,233,231,234, 158,128,129,150,132,133,148,131, 123, 65, 66, 67, 68, 69, 70, 71, 72, 73,149,136,137,138,139,140, 125, 74, 75, 76, 77, 78, 79, 80, 81, 82,141,142,143,159,144,145, 92, 32, 83, 84, 85, 86, 87, 88, 89, 90,146,147,134,130,156,155, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57,135,152,157,153,151, 32 }; asc = ebcToAscTable[ebcd]; return (asc); } #if 0 //------------------------------------------------------------------------------ // void SwapEndian(char *input, int numBytes) //------------------------------------------------------------------------------ void Code500EphemerisFile::SwapEndian(char *input, int numBytes) { char *temp = NULL; temp = new char[numBytes]; memcpy( temp, input, numBytes); for (int i = 0; i < numBytes; i++) input[(numBytes - 1) - i] = temp[i]; delete [] temp; } #endif //------------------------------------------------------------------------------ // double SwapDouble() //------------------------------------------------------------------------------ double Code500EphemerisFile::SwapDouble() { return SwapDoubleBytes(mDoubleOriginBytes.doubleBytes.byte1, mDoubleOriginBytes.doubleBytes.byte2, mDoubleOriginBytes.doubleBytes.byte3, mDoubleOriginBytes.doubleBytes.byte4, mDoubleOriginBytes.doubleBytes.byte5, mDoubleOriginBytes.doubleBytes.byte6, mDoubleOriginBytes.doubleBytes.byte7, mDoubleOriginBytes.doubleBytes.byte8); } //------------------------------------------------------------------------------ // double SwapDoubleBytes(const Byte byte1, const Byte byte2, const Byte byte3, ...) //------------------------------------------------------------------------------ double Code500EphemerisFile::SwapDoubleBytes(const Byte byte1, const Byte byte2, const Byte byte3, const Byte byte4, const Byte byte5, const Byte byte6, const Byte byte7, const Byte byte8) { mDoubleSwappedBytes.doubleBytes.byte1 = byte8; mDoubleSwappedBytes.doubleBytes.byte2 = byte7; mDoubleSwappedBytes.doubleBytes.byte3 = byte6; mDoubleSwappedBytes.doubleBytes.byte4 = byte5; mDoubleSwappedBytes.doubleBytes.byte5 = byte4; mDoubleSwappedBytes.doubleBytes.byte6 = byte3; mDoubleSwappedBytes.doubleBytes.byte7 = byte2; mDoubleSwappedBytes.doubleBytes.byte8 = byte1; return mDoubleSwappedBytes.doubleValue; } //------------------------------------------------------------------------------ // int SwapInteger() //------------------------------------------------------------------------------ int Code500EphemerisFile::SwapInteger() { return SwapIntegerBytes(mIntOriginBytes.intBytes.byte1, mIntOriginBytes.intBytes.byte2, mIntOriginBytes.intBytes.byte3, mIntOriginBytes.intBytes.byte4); } //------------------------------------------------------------------------------ // int SwapIntegerBytes(const Byte byte1, const Byte byte2, const Byte byte3, const Byte byte4) //------------------------------------------------------------------------------ int Code500EphemerisFile::SwapIntegerBytes(const Byte byte1, const Byte byte2, const Byte byte3, const Byte byte4) { mIntSwappedBytes.intBytes.byte1 = byte4; mIntSwappedBytes.intBytes.byte2 = byte3; mIntSwappedBytes.intBytes.byte3 = byte2; mIntSwappedBytes.intBytes.byte4 = byte1; return mIntSwappedBytes.intValue; } //------------------------------------------------------------------------------ // void DebugDouble(const std::string &fieldAndFormat, double value, bool swapEndian = false) //------------------------------------------------------------------------------ /** * Writes debug out of double field value. * * @param fieldAndFormat Filed name and format * @param value Real value * @param swapEndian true if swapping endian; false otherwise [false] */ //------------------------------------------------------------------------------ void Code500EphemerisFile::DebugDouble(const std::string &fieldAndFormat, double value, bool swapEndian) { if (swapEndian) MessageInterface::ShowMessage(fieldAndFormat.c_str(), SwapDoubleEndian(value)); else MessageInterface::ShowMessage(fieldAndFormat.c_str(), value); } //------------------------------------------------------------------------------ // void DebugDouble(const std::string &fieldAndFormat, double value, int index, // bool swapEndian = false) //------------------------------------------------------------------------------ /** * Writes debug out of double field value. * * @param fieldAndFormat Filed name and format * @param index Index of input field * @param value Real value * @param swapEndian true if swapping endian; false otherwise */ //------------------------------------------------------------------------------ void Code500EphemerisFile::DebugDouble(const std::string &fieldAndFormat, int index, double value, bool swapEndian) { if (swapEndian) MessageInterface::ShowMessage(fieldAndFormat.c_str(), index, SwapDoubleEndian(value)); else MessageInterface::ShowMessage(fieldAndFormat.c_str(), index, value); } //------------------------------------------------------------------------------ // void DebugDouble(const std::string &fieldAndFormat, double value, int index1, // int index2, bool swapEndian = false) //------------------------------------------------------------------------------ /** * Writes debug out of double field value. * * @param fieldAndFormat Filed name and format * @param index1 Row index of input field * @param index2 Column index of input field * @param value Real value * @param swapEndian true if swapping endian; false otherwise */ //------------------------------------------------------------------------------ void Code500EphemerisFile::DebugDouble(const std::string &fieldAndFormat, int index1, int index2, double value, bool swapEndian) { if (swapEndian) MessageInterface::ShowMessage(fieldAndFormat.c_str(), index1, index2, SwapDoubleEndian(value)); else MessageInterface::ShowMessage(fieldAndFormat.c_str(), index1, index2, value); } //------------------------------------------------------------------------------ // void DebugInteger(const std::string &fieldAndFormat, int value, bool swapEndian = false) //------------------------------------------------------------------------------ /** * Writes debug out of integer field value. * * @param fieldAndFormat Filed name and format * @param value Integer value * @param swapEndian Set to true if swapping endian; false otherwise */ //------------------------------------------------------------------------------ void Code500EphemerisFile::DebugInteger(const std::string &fieldAndFormat, int value, bool swapEndian) { if (swapEndian) MessageInterface::ShowMessage(fieldAndFormat.c_str(), SwapIntegerEndian(value)); else MessageInterface::ShowMessage(fieldAndFormat.c_str(), value); } //------------------------------------------------------------------------------ // void DebugWriteStateVector(double *stateDULT, int i, int numElem = 1, // bool swapEndian = false) //------------------------------------------------------------------------------ void Code500EphemerisFile::DebugWriteStateVector(double *stateDULT, int i, int numElem, bool swapEndian) { double posDult, velDult; for (int j = 0; j < 3; j++) { if (numElem < j) break; if (swapEndian) posDult = ReadDoubleField(&mEphemData.stateVector2Thru50_DULT[i][j]); else posDult = mEphemData.stateVector2Thru50_DULT[i][j]; MessageInterface::ShowMessage ("stateVector2Thru50_DULT[%2d][%2d] = % 1.15e\n", i, j, posDult); MessageInterface::ShowMessage ("stateVector2Thru50_KMSE[%2d][%2d].= % 1.15e\n", i, j, posDult * DUL_TO_KM); } for (int j = 3; j < 6; j++) { if (numElem < j) break; if (swapEndian) velDult = ReadDoubleField(&mEphemData.stateVector2Thru50_DULT[i][j]); else velDult = mEphemData.stateVector2Thru50_DULT[i][j]; MessageInterface::ShowMessage ("stateVector2Thru50_DULT[%2d][%2d] = % 1.15e\n", i, j, velDult); MessageInterface::ShowMessage ("stateVector2Thru50_KMSE[%2d][%2d].= % 1.15e\n", i, j, velDult * DUL_DUT_TO_KM_SEC); } } //------------------------------------------------------------------------------ // void DebugWriteState(Rvector6 *stateKmSec, double *stateDULT, int option = 1) //------------------------------------------------------------------------------ /** * Write state in km/sec or in DULT. * * @param option 1 = Write only in km/sec * 2 = Write in km/sec and in DUL/DUT * other = Write only in DUL/DUT */ //------------------------------------------------------------------------------ void Code500EphemerisFile::DebugWriteState(Rvector6 *stateKmSec, double *stateDULT, int option) { if (option == 1 || option == 2) { MessageInterface::ShowMessage ("stateKmSec = % 1.15e % 1.15e % 1.15e % 1.15e % 1.15e % 1.15e\n", stateKmSec->Get(0), stateKmSec->Get(1), stateKmSec->Get(2), stateKmSec->Get(3), stateKmSec->Get(4), stateKmSec->Get(5)); if (option == 2) MessageInterface::ShowMessage ("stateDULT = % 1.15e % 1.15e % 1.15e % 1.15e % 1.15e % 1.15e\n", stateDULT[0], stateDULT[1], stateDULT[2], stateDULT[3], stateDULT[4], stateDULT[5]); } else MessageInterface::ShowMessage ("stateDULT = % 1.15e % 1.15e % 1.15e % 1.15e % 1.15e % 1.15e\n", stateDULT[0], stateDULT[1], stateDULT[2], stateDULT[3], stateDULT[4], stateDULT[5]); }
[ "daniel@destevez.net" ]
daniel@destevez.net
aa615d50649de81827e8df5cad1bc237d77abc8c
7da3fca158ea3fb03a578aaff783739a91194bab
/Code/LG/LG2634/code.cpp
5448217a08a6cb2b70bd308914f2cd9633f7d3e3
[]
no_license
powerLEO101/Work
f1b16d410a55a9136470e0d04ccc4abcfd95e18b
6ae5de17360a7a06e1b65d439158ff5c2d506c2a
refs/heads/master
2021-06-18T01:33:07.380867
2021-02-16T10:16:47
2021-02-16T10:16:47
105,882,852
0
0
null
null
null
null
UTF-8
C++
false
false
2,759
cpp
/************************** * Writer : Leo101 * Problem : Luogu P2634 [国家集训队]聪聪可可 * Tags : 点分治,数学 **************************/ #include <iostream> #include <cstdio> #include <algorithm> #include <cstring> #define _FILE(s) freopen(#s".in", "r", stdin); freopen(#s".out", "w", stdout) #define gi get_int() const int MAXN = 4e4, INF = 0x3f3f3f3f; int get_int() { int x = 0, y = 1; char ch = getchar(); while ((ch < '0' || ch > '9') && ch != '-') ch = getchar(); if (ch == '-') y = -1,ch = getchar(); while (ch <= '9' && ch >= '0') { x = x * 10 + ch - '0'; ch = getchar(); } return x * y; } class Edge { public: int next, to, value; } edges[MAXN << 1]; int head[MAXN], edgesNum; void addEdge(int from, int to, int value) { edges[edgesNum] = (Edge) {head[from], to, value}; head[from] = edgesNum++; } int size[MAXN], count[MAXN], dis[MAXN]; int globalMin, nextRoot, fullSize, cnt; bool vis[MAXN]; long long ans; void getFocus(int now, int pre = -1) { int maxVal = 0; size[now] = 1; for (int i = head[now]; i != -1; i = edges[i].next) { int to = edges[i].to; if (vis[to] == true || to == pre) continue; getFocus(to, now); size[now] += size[to]; maxVal = std :: max(maxVal, size[to]); } maxVal = std :: max(maxVal, fullSize - size[now]); if (maxVal < globalMin) { globalMin = maxVal; nextRoot = now; } } void dfs(int now, int extra, int pre = -1, int dist = 0) { dis[cnt++] = dist + extra; for (int i = head[now]; i != -1; i = edges[i].next) { int to = edges[i].to, value = edges[i].value; if (to == pre || vis[to] == true) continue; dfs(to, extra, now, dist + value); } } long long getAns(int now, int extra) { memset(count, 0, sizeof(count)); cnt = 0; dfs(now, extra); for (int i = 0; i < cnt; i++) count[dis[i] % 3]++; return 2ll * count[1] * count[2] + (count[0] == 0 ? 0 : 1ll * count[0] * (count[0] - 1)); } void divide(int now) { vis[now] = true; ans += getAns(now, 0); int sizeBackup = fullSize; for (int i = head[now]; i != -1; i = edges[i].next) { int to = edges[i].to, value = edges[i].value; if (vis[to] == true) continue; ans -= getAns(to, value); fullSize = size[to] > size[now] ? sizeBackup - size[now] : size[to]; globalMin = INF; getFocus(to); divide(nextRoot); } } long long getGcd(long long x, long long y) { return y == 0 ? x : getGcd(y, x % y); } int main() { _FILE(code); memset(head, -1, sizeof(head)); int n = gi; for (int i = 1; i < n; i++) { int from = gi, to = gi, value = gi; addEdge(from, to, value); addEdge(to, from, value); } fullSize = n; globalMin = INF; getFocus(1); divide(nextRoot); ans += n; long long gcd = getGcd(ans, 1ll * n * n); printf("%lld/%lld", ans / gcd, 1ll * n * n / gcd); return 0; }
[ "powerLEO101@outlook.com" ]
powerLEO101@outlook.com
0f3b27943a655e12ccf60da888f9a80859af9b99
bbcda48854d6890ad029d5973e011d4784d248d2
/trunk/win/Source/Includes/QtIncludes/src/gui/embedded/qmouse_qws.h
5f2314d6874ffa7053cc72b2f1adf1cc8ea481e8
[ "MIT", "curl", "LGPL-2.1-or-later", "BSD-3-Clause", "BSL-1.0", "Apache-2.0", "LicenseRef-scancode-public-domain", "LGPL-2.1-only", "Zlib", "LicenseRef-scancode-unknown", "LicenseRef-scancode-unknown-license-reference", "MS-LPL" ]
permissive
dyzmapl/BumpTop
9c396f876e6a9ace1099b3b32e45612a388943ff
1329ea41411c7368516b942d19add694af3d602f
refs/heads/master
2020-12-20T22:42:55.100473
2020-01-25T21:00:08
2020-01-25T21:00:08
236,229,087
0
0
Apache-2.0
2020-01-25T20:58:59
2020-01-25T20:58:58
null
UTF-8
C++
false
false
3,770
h
/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** 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.1, 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. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QMOUSE_QWS_H #define QMOUSE_QWS_H #include <QtCore/qobject.h> #include <QtGui/qpolygon.h> QT_BEGIN_HEADER QT_BEGIN_NAMESPACE QT_MODULE(Gui) class QWSMouseHandlerPrivate; class QScreen; class Q_GUI_EXPORT QWSPointerCalibrationData { public: enum Location { TopLeft = 0, BottomLeft = 1, BottomRight = 2, TopRight = 3, Center = 4, LastLocation = Center }; QPoint devPoints[5]; QPoint screenPoints[5]; }; class Q_GUI_EXPORT QWSMouseHandler { public: explicit QWSMouseHandler(const QString &driver = QString(), const QString &device = QString()); virtual ~QWSMouseHandler(); virtual void clearCalibration() {} virtual void calibrate(const QWSPointerCalibrationData *) {} virtual void getCalibration(QWSPointerCalibrationData *) const {} virtual void resume() = 0; virtual void suspend() = 0; void limitToScreen(QPoint &pt); void mouseChanged(const QPoint& pos, int bstate, int wheel = 0); const QPoint &pos() const { return mousePos; } void setScreen(const QScreen *screen); protected: QPoint &mousePos; QWSMouseHandlerPrivate *d_ptr; }; class Q_GUI_EXPORT QWSCalibratedMouseHandler : public QWSMouseHandler { public: explicit QWSCalibratedMouseHandler(const QString &driver = QString(), const QString &device = QString()); virtual void clearCalibration(); virtual void calibrate(const QWSPointerCalibrationData *); virtual void getCalibration(QWSPointerCalibrationData *) const; protected: bool sendFiltered(const QPoint &, int button); QPoint transform(const QPoint &); void readCalibration(); void writeCalibration(); void setFilterSize(int); private: int a, b, c; int d, e, f; int s; QPolygon samples; int currSample; int numSamples; }; QT_END_NAMESPACE QT_END_HEADER #endif // QMOUSE_QWS_H
[ "anandx@google.com" ]
anandx@google.com
507b9d88a98f99758c2b6407c423f24adc6220f0
11ef4bbb8086ba3b9678a2037d0c28baaf8c010e
/Source Code/server/binaries/chromium/gen/components/mirroring/mojom/session_parameters.mojom-shared.h
30981480604509b52d78c73f04042c8ea860db85
[]
no_license
lineCode/wasmview.github.io
8f845ec6ba8a1ec85272d734efc80d2416a6e15b
eac4c69ea1cf0e9af9da5a500219236470541f9b
refs/heads/master
2020-09-22T21:05:53.766548
2019-08-24T05:34:04
2019-08-24T05:34:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,921
h
// 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. #ifndef COMPONENTS_MIRRORING_MOJOM_SESSION_PARAMETERS_MOJOM_SHARED_H_ #define COMPONENTS_MIRRORING_MOJOM_SESSION_PARAMETERS_MOJOM_SHARED_H_ #include <stdint.h> #include <functional> #include <ostream> #include <type_traits> #include <utility> #include "base/compiler_specific.h" #include "base/containers/flat_map.h" #include "mojo/public/cpp/bindings/array_data_view.h" #include "mojo/public/cpp/bindings/enum_traits.h" #include "mojo/public/cpp/bindings/interface_data_view.h" #include "mojo/public/cpp/bindings/lib/bindings_internal.h" #include "mojo/public/cpp/bindings/lib/serialization.h" #include "mojo/public/cpp/bindings/map_data_view.h" #include "mojo/public/cpp/bindings/string_data_view.h" #include "components/mirroring/mojom/session_parameters.mojom-shared-internal.h" #include "services/network/public/mojom/ip_address.mojom-shared.h" #include "mojo/public/cpp/bindings/lib/interface_serialization.h" #include "mojo/public/cpp/bindings/native_enum.h" #include "mojo/public/cpp/bindings/lib/native_struct_serialization.h" namespace mirroring { namespace mojom { class SessionParametersDataView; } // namespace mojom } // namespace mirroring namespace mojo { namespace internal { template <> struct MojomTypeTraits<::mirroring::mojom::SessionParametersDataView> { using Data = ::mirroring::mojom::internal::SessionParameters_Data; using DataAsArrayElement = Pointer<Data>; static constexpr MojomTypeCategory category = MojomTypeCategory::STRUCT; }; } // namespace internal } // namespace mojo namespace mirroring { namespace mojom { enum class SessionType : int32_t { AUDIO_ONLY, VIDEO_ONLY, AUDIO_AND_VIDEO, kMinValue = 0, kMaxValue = 2, }; std::ostream& operator<<(std::ostream& os, SessionType value); inline bool IsKnownEnumValue(SessionType value) { return internal::SessionType_Data::IsKnownValue( static_cast<int32_t>(value)); } class SessionParametersDataView { public: SessionParametersDataView() {} SessionParametersDataView( internal::SessionParameters_Data* data, mojo::internal::SerializationContext* context) : data_(data), context_(context) {} bool is_null() const { return !data_; } template <typename UserType> WARN_UNUSED_RESULT bool ReadType(UserType* output) const { auto data_value = data_->type; return mojo::internal::Deserialize<::mirroring::mojom::SessionType>( data_value, output); } SessionType type() const { return static_cast<SessionType>(data_->type); } inline void GetReceiverAddressDataView( ::network::mojom::IPAddressDataView* output); template <typename UserType> WARN_UNUSED_RESULT bool ReadReceiverAddress(UserType* output) { auto* pointer = data_->receiver_address.Get(); return mojo::internal::Deserialize<::network::mojom::IPAddressDataView>( pointer, output, context_); } inline void GetReceiverModelNameDataView( mojo::StringDataView* output); template <typename UserType> WARN_UNUSED_RESULT bool ReadReceiverModelName(UserType* output) { auto* pointer = data_->receiver_model_name.Get(); return mojo::internal::Deserialize<mojo::StringDataView>( pointer, output, context_); } private: internal::SessionParameters_Data* data_ = nullptr; mojo::internal::SerializationContext* context_ = nullptr; }; } // namespace mojom } // namespace mirroring namespace std { template <> struct hash<::mirroring::mojom::SessionType> : public mojo::internal::EnumHashImpl<::mirroring::mojom::SessionType> {}; } // namespace std namespace mojo { template <> struct EnumTraits<::mirroring::mojom::SessionType, ::mirroring::mojom::SessionType> { static ::mirroring::mojom::SessionType ToMojom(::mirroring::mojom::SessionType input) { return input; } static bool FromMojom(::mirroring::mojom::SessionType input, ::mirroring::mojom::SessionType* output) { *output = input; return true; } }; namespace internal { template <typename MaybeConstUserType> struct Serializer<::mirroring::mojom::SessionType, MaybeConstUserType> { using UserType = typename std::remove_const<MaybeConstUserType>::type; using Traits = EnumTraits<::mirroring::mojom::SessionType, UserType>; static void Serialize(UserType input, int32_t* output) { *output = static_cast<int32_t>(Traits::ToMojom(input)); } static bool Deserialize(int32_t input, UserType* output) { return Traits::FromMojom(static_cast<::mirroring::mojom::SessionType>(input), output); } }; } // namespace internal namespace internal { template <typename MaybeConstUserType> struct Serializer<::mirroring::mojom::SessionParametersDataView, MaybeConstUserType> { using UserType = typename std::remove_const<MaybeConstUserType>::type; using Traits = StructTraits<::mirroring::mojom::SessionParametersDataView, UserType>; static void Serialize(MaybeConstUserType& input, Buffer* buffer, ::mirroring::mojom::internal::SessionParameters_Data::BufferWriter* output, SerializationContext* context) { if (CallIsNullIfExists<Traits>(input)) return; (*output).Allocate(buffer); mojo::internal::Serialize<::mirroring::mojom::SessionType>( Traits::type(input), &(*output)->type); decltype(Traits::receiver_address(input)) in_receiver_address = Traits::receiver_address(input); typename decltype((*output)->receiver_address)::BaseType::BufferWriter receiver_address_writer; mojo::internal::Serialize<::network::mojom::IPAddressDataView>( in_receiver_address, buffer, &receiver_address_writer, context); (*output)->receiver_address.Set( receiver_address_writer.is_null() ? nullptr : receiver_address_writer.data()); MOJO_INTERNAL_DLOG_SERIALIZATION_WARNING( (*output)->receiver_address.is_null(), mojo::internal::VALIDATION_ERROR_UNEXPECTED_NULL_POINTER, "null receiver_address in SessionParameters struct"); decltype(Traits::receiver_model_name(input)) in_receiver_model_name = Traits::receiver_model_name(input); typename decltype((*output)->receiver_model_name)::BaseType::BufferWriter receiver_model_name_writer; mojo::internal::Serialize<mojo::StringDataView>( in_receiver_model_name, buffer, &receiver_model_name_writer, context); (*output)->receiver_model_name.Set( receiver_model_name_writer.is_null() ? nullptr : receiver_model_name_writer.data()); MOJO_INTERNAL_DLOG_SERIALIZATION_WARNING( (*output)->receiver_model_name.is_null(), mojo::internal::VALIDATION_ERROR_UNEXPECTED_NULL_POINTER, "null receiver_model_name in SessionParameters struct"); } static bool Deserialize(::mirroring::mojom::internal::SessionParameters_Data* input, UserType* output, SerializationContext* context) { if (!input) return CallSetToNullIfExists<Traits>(output); ::mirroring::mojom::SessionParametersDataView data_view(input, context); return Traits::Read(data_view, output); } }; } // namespace internal } // namespace mojo namespace mirroring { namespace mojom { inline void SessionParametersDataView::GetReceiverAddressDataView( ::network::mojom::IPAddressDataView* output) { auto pointer = data_->receiver_address.Get(); *output = ::network::mojom::IPAddressDataView(pointer, context_); } inline void SessionParametersDataView::GetReceiverModelNameDataView( mojo::StringDataView* output) { auto pointer = data_->receiver_model_name.Get(); *output = mojo::StringDataView(pointer, context_); } } // namespace mojom } // namespace mirroring #endif // COMPONENTS_MIRRORING_MOJOM_SESSION_PARAMETERS_MOJOM_SHARED_H_
[ "wasmview@gmail.com" ]
wasmview@gmail.com
33e908abd4897ce61a64eb75f2c96119542de9dd
b1be8471950a7d7a834d67b11b24d70aa7ece501
/DemoFramework/FslDemoHost/Vulkan/source/FslDemoHost/Vulkan/VulkanDemoHostOptionParser.cpp
8254703f4cd25b1156c5b20da6f4154130461ac1
[ "GPL-1.0-or-later", "JSON" ]
permissive
alexvonduar/gtec-demo-framework
1b212d9b43094abdfeae61e0d2e8a258e5a97771
6f8a7e429d0e15242ba64eb4cb41bfc2dd7dc749
refs/heads/master
2021-06-15T13:25:02.498022
2021-03-26T06:11:43
2021-03-26T06:11:43
168,854,730
0
0
BSD-3-Clause
2019-03-25T23:59:42
2019-02-02T16:59:46
C++
UTF-8
C++
false
false
9,184
cpp
/**************************************************************************************************************************************************** * Copyright (c) 2016 Freescale Semiconductor, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the Freescale Semiconductor, Inc. nor the names of * its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT 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 <FslBase/Exceptions.hpp> #include <FslBase/Getopt/OptionBaseValues.hpp> #include <FslBase/Log/Log3Fmt.hpp> #include <FslBase/Log/String/FmtStringViewLite.hpp> #include <FslBase/String/StringParseUtil.hpp> #include <FslDemoHost/Vulkan/VulkanDemoHostOptionParser.hpp> #include <algorithm> #include <array> #include <cstring> #include <string> #include <utility> namespace Fsl { namespace { struct CommandId { enum Enum { VkPhysicalDevice = DEMO_HOST_OPTION_BASE, VkValidate, VkApiDump, VkPresentMode, LogExtensions, LogLayers, LogSurfaceFormats, VkScreenshot, }; }; struct PresentMode { VkPresentModeKHR Mode; StringViewLite StrMode; constexpr PresentMode(const VkPresentModeKHR mode, StringViewLite str) : Mode(mode) , StrMode(str) { } }; // NOLINTNEXTLINE(modernize-avoid-c-arrays) constexpr const PresentMode g_presentModes[] = { PresentMode(VK_PRESENT_MODE_IMMEDIATE_KHR, "VK_PRESENT_MODE_IMMEDIATE_KHR"), PresentMode(VK_PRESENT_MODE_MAILBOX_KHR, "VK_PRESENT_MODE_MAILBOX_KHR"), PresentMode(VK_PRESENT_MODE_FIFO_KHR, "VK_PRESENT_MODE_FIFO_KHR"), PresentMode(VK_PRESENT_MODE_FIFO_RELAXED_KHR, "VK_PRESENT_MODE_FIFO_RELAXED_KHR"), #if VK_HEADER_VERSION >= 51 PresentMode(VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR, "VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR"), PresentMode(VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR, "VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR"), #endif }; constexpr auto g_presentModeCount = sizeof(g_presentModes) / sizeof(PresentMode); std::string GetPresentModesString() { fmt::memory_buffer buf; fmt::format_to(buf, "{} ({})", g_presentModes[0].StrMode, g_presentModes[0].Mode); for (std::size_t i = 1; i < g_presentModeCount; ++i) { fmt::format_to(buf, ", {} ({})", g_presentModes[i].StrMode, g_presentModes[i].Mode); } return fmt::to_string(buf); } bool TryParseAsString(VkPresentModeKHR& rPresentMode, const StringViewLite& strOptArg) { // Try to see if we can find a string match for (std::size_t i = 0; i < g_presentModeCount; ++i) { if (strOptArg == g_presentModes[i].StrMode) { rPresentMode = g_presentModes[i].Mode; return true; } } rPresentMode = VK_PRESENT_MODE_FIFO_KHR; return false; } bool TryParseAsValue(VkPresentModeKHR& rPresentMode, const StringViewLite& strOptArg) { rPresentMode = VK_PRESENT_MODE_FIFO_KHR; // Try to see if we can parse it as a number int32_t value = 0; try { StringParseUtil::Parse(value, strOptArg); } catch (const std::exception&) { return false; } for (std::size_t i = 0; i < g_presentModeCount; ++i) { if (value == g_presentModes[i].Mode) { rPresentMode = g_presentModes[i].Mode; return true; } } FSLLOG3_WARNING("Unknown presentMode '{}' supplied, trying it out", value); rPresentMode = static_cast<VkPresentModeKHR>(value); return true; } bool TryParse(VkPresentModeKHR& rPresentMode, const StringViewLite& strOptArg) { if (TryParseAsString(rPresentMode, strOptArg)) { return true; } return TryParseAsValue(rPresentMode, strOptArg); } } VulkanDemoHostOptionParser::VulkanDemoHostOptionParser() : ADemoHostOptionParser(DemoHostOptionConfig::WindowApp) { } void VulkanDemoHostOptionParser::ArgumentSetup(std::deque<Option>& rOptions) { ADemoHostOptionParser::ArgumentSetup(rOptions); auto presentModes = GetPresentModesString(); std::string presentModeDesc = std::string("Override the present mode with the supplied value. Known values: ") + presentModes; rOptions.emplace_back("VkPhysicalDevice", OptionArgument::OptionRequired, CommandId::VkPhysicalDevice, "Set the physical device index.", OptionGroup::Host); rOptions.emplace_back("VkValidate", OptionArgument::OptionRequired, CommandId::VkValidate, "Enable/disable the VK_LAYER_LUNARG_standard_validation layer.", OptionGroup::Host); rOptions.emplace_back("VkApiDump", OptionArgument::OptionNone, CommandId::VkApiDump, "Enable the VK_LAYER_LUNARG_api_dump layer.", OptionGroup::Host); rOptions.emplace_back("VkPresentMode", OptionArgument::OptionRequired, CommandId::VkPresentMode, presentModeDesc, OptionGroup::Host); rOptions.emplace_back("LogExtensions", OptionArgument::OptionNone, CommandId::LogExtensions, "Output the extensions to the log", OptionGroup::Host); rOptions.emplace_back("LogLayers", OptionArgument::OptionNone, CommandId::LogLayers, "Output the layers to the log", OptionGroup::Host); rOptions.emplace_back("LogSurfaceFormats", OptionArgument::OptionNone, CommandId::LogSurfaceFormats, "Output the supported surface formats to the log", OptionGroup::Host); rOptions.emplace_back("VkScreenshot", OptionArgument::OptionRequired, CommandId::VkScreenshot, "Enable/disable screenshot support (defaults to enabled)", OptionGroup::Host); } OptionParseResult VulkanDemoHostOptionParser::Parse(const int cmdId, const StringViewLite& strOptArg) { bool boolValue = false; switch (cmdId) { case CommandId::VkPhysicalDevice: StringParseUtil::Parse(m_physicalDeviceIndex, strOptArg); return OptionParseResult::Parsed; case CommandId::VkValidate: StringParseUtil::Parse(boolValue, strOptArg); m_validationLayer = boolValue ? OptionUserChoice::On : OptionUserChoice::Off; return OptionParseResult::Parsed; case CommandId::VkApiDump: m_apiDump = OptionUserChoice::On; return OptionParseResult::Parsed; case CommandId::VkPresentMode: { VkPresentModeKHR presentMode = VkPresentModeKHR::VK_PRESENT_MODE_FIFO_KHR; if (TryParse(presentMode, strOptArg)) { m_launchOptions.OverridePresentMode = true; m_launchOptions.PresentMode = presentMode; return OptionParseResult::Parsed; } FSLLOG3_INFO("Known presentMode value or strings: {}", GetPresentModesString()); return OptionParseResult::Failed; } case CommandId::LogExtensions: m_logExtensions = true; m_launchOptions.LogDeviceExtensions = true; return OptionParseResult::Parsed; case CommandId::LogLayers: m_logLayers = true; return OptionParseResult::Parsed; case CommandId::LogSurfaceFormats: m_logSurfaceFormats = true; return OptionParseResult::Parsed; case CommandId::VkScreenshot: StringParseUtil::Parse(boolValue, strOptArg); m_launchOptions.ScreenshotsEnabled = boolValue ? OptionUserChoice::On : OptionUserChoice::Off; return OptionParseResult::Parsed; default: return ADemoHostOptionParser::Parse(cmdId, strOptArg); } } bool VulkanDemoHostOptionParser::ParsingComplete() { return ADemoHostOptionParser::ParsingComplete(); } }
[ "Rene.Thrane@nxp.com" ]
Rene.Thrane@nxp.com
80c9a271a5033f677f74e2790ebd8f458a78edae
1dac9cd841cc2afd6f7cbe106da6669cdeca8f3d
/ArbreBinaireDictionnaire/stdafx.cpp
9e004468d9daf8cc69e27e2bf21d314b8ee99308
[]
no_license
Ichinin/Dictionnaire_Arbre_Binaire
95e9651fc067a73ddfc71e513545187eafeb9d01
87ffaa36b521716df81d27ab0b5f661cb9b377ef
refs/heads/master
2021-01-21T20:18:53.743587
2017-05-31T18:15:59
2017-05-31T18:15:59
92,218,411
0
0
null
null
null
null
ISO-8859-1
C++
false
false
346
cpp
// stdafx.cpp : fichier source incluant simplement les fichiers Include standard // ArbreBinaireDictionnaire.pch représente l'en-tête précompilé // stdafx.obj contient les informations de type précompilées #include "stdafx.h" // TODO: faites référence aux en-têtes supplémentaires nécessaires dans STDAFX.H // absents de ce fichier
[ "r.suntharasarma@gmail.com" ]
r.suntharasarma@gmail.com
d3bf05f2bdc2fdfb0f3583588e3427f394126026
6e223938bbb420cada962d7a34da6b7f834f4f33
/DAG.cpp
4a3f4ff0b6497a12e41ac4d25f84386db0058761
[]
no_license
AyushVa27/DAG
8cd34bca175b21039d509e76ba6db982ec77946c
97cb05a37662152e3d09a724720149240d01ee52
refs/heads/main
2023-05-22T16:00:36.387432
2021-06-10T10:29:16
2021-06-10T10:29:16
375,658,911
0
0
null
null
null
null
UTF-8
C++
false
false
1,799
cpp
#include<iostream> #include<string> #include<unordered_map> using namespace std; class DAG { public: char label; char data; DAG* left; DAG* right; DAG(char x){ label='_'; data=x; left=NULL; right=NULL; } DAG(char lb, char x, DAG* lt, DAG* rt){ label=lb; data=x; left=lt; right=rt; } }; int main(){ int n; n=3; string st[n]; st[0]="A=x+y"; st[1]="B=A*z"; st[2]="C=B/x"; unordered_map<char, DAG*> labelDAGNode; for(int i=0;i<3;i++){ string stTemp=st[i]; for(int j=0;j<5;j++){ char tempLabel = stTemp[0]; char tempLeft = stTemp[2]; char tempData = stTemp[3]; char tempRight = stTemp[4]; DAG* leftPtr; DAG* rightPtr; if(labelDAGNode.count(tempLeft) == 0){ leftPtr = new DAG(tempLeft); } else{ leftPtr = labelDAGNode[tempLeft]; } if(labelDAGNode.count(tempRight) == 0){ rightPtr = new DAG(tempRight); } else{ rightPtr = labelDAGNode[tempRight]; } DAG* nn = new DAG(tempLabel,tempData,leftPtr,rightPtr); labelDAGNode.insert(make_pair(tempLabel,nn)); } } cout<<"Label ptr leftPtr rightPtr"<<endl; for(int i=0;i<n;i++){ DAG* x=labelDAGNode[st[i][0]]; cout<<st[i][0]<<" "<<x->data<<" "; if(x->left->label=='_')cout<<x->left->data; else cout<<x->left->label; cout<<" "; if(x->right->label=='_')cout<<x->right->data; else cout<<x->right->label; cout<<endl; } return 0; }
[ "noreply@github.com" ]
noreply@github.com
ac9a9d697a56b2b070020df6c877a801a49c2ee3
bddf3eee728421f4ea7acb2582a0b28aa8fbd541
/pro_of_Qt/faims_04-08/faims_/utils.cpp
e0cbd3d29dc12d2f247d7e12b79c72e4331abec5
[]
no_license
yzkaa/CPP_All_Test
6e64ab12fd9f41a35b660330d922da73d6c13524
3bd8076247551b9180a0ddf1fb01e71632c5693a
refs/heads/master
2023-05-06T02:42:19.639079
2021-05-29T15:34:23
2021-05-29T15:34:23
318,482,502
0
0
null
null
null
null
UTF-8
C++
false
false
13,683
cpp
#include "utils.h" Utils::Utils() { } bool sortByY(const QPointF &p1, const QPointF &p2) { return p1.y() < p2.y();//升序排列 } void Utils::Filter(QList<QPointF> &pointList) { QList<QPointF> fittedResult; QList<QPointF> fittedAndSmoothResult; fittedResult.clear(); //线性五点拟合去差值 double tmpY; double flag=0; if(pointList.size()>=5){ int N_1 = pointList.size(); std::vector<QPointF> tmpData(5); for(int i=0;i<N_1-5;i++){ tmpData.clear(); for(int j=i;j<i+5;j++){ tmpData.push_back(pointList[j]); } std::sort(tmpData.begin(),tmpData.end(),sortByY); //升序排列 tmpY = (tmpData[1].y()+tmpData[2].y()+tmpData[3].y())/3; fittedResult.push_back(QPointF(pointList[i].x(),tmpY)); } fittedResult[fittedResult.size()-1].setX(pointList[pointList.size()-1].x()); } //线性五点平滑 int N_2 = fittedResult.size(); tmpY = (3.0*fittedResult[0].y()+2.0*fittedResult[1].y()+fittedResult[2].y()-fittedResult[4].y()) / 5.0; if(tmpY<=0){ tmpY = 0; } fittedAndSmoothResult.push_back(QPointF(fittedResult[0].x(), tmpY)); tmpY = (4.0 * fittedResult[0].y() + 3.0 * fittedResult[1].y() + 2 * fittedResult[2].y() + fittedResult[3].y()) / 10.0; fittedAndSmoothResult.push_back(QPointF(fittedResult[1].x(), tmpY)); for(int i=2;i<N_2 - 3;i++){ tmpY = (fittedResult[i - 2].y() + fittedResult[i - 1].y() + fittedResult[i].y() + fittedResult[i + 1].y() + fittedResult[i + 2].y()) / 5.0; fittedAndSmoothResult.push_back(QPointF(fittedResult[i].x(), tmpY)); } tmpY = (4.0 * fittedResult[N_2 - 1].y() + 3.0 * fittedResult[N_2 - 2].y() + 2 * fittedResult[N_2 - 3].y() + fittedResult[N_2 - 4].y()) / 10.0; fittedAndSmoothResult.push_back(QPointF(fittedResult[N_2 - 2].x(), tmpY)); tmpY = (3.0 * fittedResult[N_2 - 1].y() + 2.0 * fittedResult[N_2 - 2].y() + fittedResult[N_2 - 3].y() - fittedResult[N_2 - 5].y()) / 5.0; fittedAndSmoothResult.push_back(QPointF(fittedResult[N_2 - 1].x(), tmpY)); pointList.clear(); pointList = fittedAndSmoothResult; } void Utils::tipMessageBox(QString Info) { if(Info.isEmpty()) { return; } QMessageBox Tip; Tip.setText(Info); Tip.exec(); } void Utils::peakParameterCalculation(QList<QPointF> &currentData, double &FWHM, double &Area) { //取得最大最小值 //STL风格遍历 int index = 0; int currentMaxValue = 0; int currentMinValue = 0; int currentmaxIndex = 0; QList<QPointF>::const_iterator temp; for(temp = currentData.begin(); temp != currentData.end(); temp++,index++) { QPointF point = *temp; if(point.y() > currentMaxValue) { currentMaxValue = point.y(); currentmaxIndex = index; } if(point.y() < currentMinValue) { currentMinValue = point.y(); } } double mingap; mingap = (currentMaxValue - currentMinValue) / 28; ////峰参数 //未来5点趋势(斜率值) 数组 Km QList<QVector<double>> AmplitudeTrand; QVector<double> Km; QVector<double> point5; double sum = 0; double y1,y2,x1,x2; for(int i = 0, n = 1; i + n <currentData.size(); n++) { y2 = currentData.at(i + n).y(); y1 = currentData.at(i).y(); x2 = currentData.at(i + n).x(); x1 = currentData.at(i).x(); point5 += (y2 - y1) / (x2 - x1); sum += (y2 - y1) / (x2 - x1); if(n > 5) { //每个点与之后5个点的斜率,打包 AmplitudeTrand.push_back(point5); //再进一级,用at直接对QVector赋值会出错,原理未知,所以采用新的QVector,用append sum = sum / 5; Km.push_back(sum); sum = 0; point5.clear(); n = 1; i++; } } //条件:K0 和 Ks 需要总结 //趋势数组trand int up = 0, down = 0; double k0 = 0.5, Ks = 8; QVector<int> trand; for(int i = 0; i < AmplitudeTrand.size(); i++) { up = 0; down = 0; //其值与K0对比,判断上升下降趋势 for(int j = 0; j<AmplitudeTrand.at(i).size(); j++) { if(AmplitudeTrand.at(i).at(j) > k0) up++; else if(AmplitudeTrand.at(i).at(j) < -k0) down++; } // 1 上升 -1下降 0抖动或平缓 if(up >= 3) trand += 1; else if(down >= 3) trand += -1; else trand += 0; } //峰起点终点初始别 //mingap是显示的刻度最小一格的刻度 //起始点 //ks总结得出限度 //起点条件:5点平均趋势Km大于设定好的Ks,处于上升区段的第一点,(由于第一个条件或方式没处理好,要加上第三个条件两点幅值相差最小显示) int startflag, endflag, i2; QVector<int> startIndex; QVector<int> endIndex; for(int i = 0; i < trand.size();i++) { if(trand.at(i) == 1) { startflag = 0; for(i2 = i; i2 < trand.size() && i2 < Km.size(); i2++) { if(trand.at(i2) == 1) { if(Km.at(i2) > Ks && startflag == 0 && currentData.at(i2).y() - currentData.at(i).y() > mingap) { startIndex += i; startflag = 1; } } else break; } i=i2; } } //终点 for(int i = 0; i < trand.size(); i++) { if(trand.at(i) == -1) { endflag = 0; for(i2 = i; i2 < trand.size() && i2 < Km.size(); i2++) { if(trand.at(i2) == -1) { if(Km.at(i2) > -Ks/2 && endflag == 0 && currentData.at(i).y() - currentData.at(i2).y() > mingap) { endIndex += i2; endflag = 1; } } else break; } i = i2; } } //总共的起点终点,单峰多峰情况 QVector<int> startpointIndex; QVector<int> endpointIndex; startpointIndex.append(startIndex); endpointIndex.append(endIndex); //最终起点终点分析 //前肩峰,寄生峰分析 QVector<int> addstartIndex; QVector<int> addendIndex; if(startIndex.size()>1){ for(int i = 1; i<startIndex.size(); i++) { down = 0; for(i2 = startIndex.at(i - 1); ; i2++) { if(trand.at(i2) == -1) { down = 1; if(endIndex.contains(i2)) break;//无前肩峰,与未识别的寄生峰 } else if(i2 == startIndex.at(i) && down ==1 ) { //有未被识别的前寄生峰,录入寄生峰数组 addstartIndex += startIndex.at(i-1); addendIndex += startIndex.at(i); break; } else if(i2 == startIndex.at(i) && down == 0) { startpointIndex.removeAt(i);//肩峰情况,上升点移除后一个 break; } } } } //后肩峰,寄生峰分析 if(endIndex.size()>1) { for(int i=1;i<endIndex.size();i++) { up = 0; for(i2 = endIndex.at(i-1);; i2++) { if(trand.at(i2) == 1) { up = 1; if(startIndex.contains(i2)) break;//无后肩峰,与未识别的寄生峰 } else if(i2==endIndex.at(i)&&up==1) { //有未被识别的后寄生峰,把第一个终点当作寄生峰终点 addstartIndex += endIndex.at(i-1); addendIndex += endIndex.at(i); break; } else if(i2 == endIndex.at(i) && up == 0) { endpointIndex.removeAt(i-1);//肩峰情况,上升点移除上一个 break; } } } } //截取传递范围 (第一个峰起点到最后一个峰终点) int StartIndex_one; int EndIndex_one; StartIndex_one = startpointIndex.at(0); EndIndex_one = endpointIndex.at(endpointIndex.size() - 1); ////单峰半峰宽 // FWHMcompute(point); int i,flag=0; double k,b,x; QList<QPointF> FittingLine; QList<QPointF> intermediary; QVector<double> pointX; double mid_value=(currentMaxValue - (currentData.at(startpointIndex.at(0)).y() + currentData.at(endpointIndex.at(0)).y()) / 2) / 2; // foreach (QPoint point, currentData) { // if (point) // { // } // } //8点 for(i = startpointIndex.at(0); i < endpointIndex.at(0); i++) { if(currentData.at(i).y() > mid_value && i < currentmaxIndex && flag == 0) { intermediary << currentData.at(i - 2); intermediary << currentData.at(i - 1); intermediary << currentData.at(i); intermediary << currentData.at(i + 1); flag = 1; } if(currentData.at(i).y() < mid_value && i > currentmaxIndex) { intermediary << currentData.at(i-2); intermediary << currentData.at(i-1); intermediary << currentData.at(i); intermediary << currentData.at(i+1); //按x轴顺序录入 break; } } //4点 for(i=0;i<intermediary.size();) { if(qAbs(intermediary.at(i).y() - mid_value) < qAbs(intermediary.at(i+2).y() - mid_value)) FittingLine << intermediary.at(i) << intermediary.at(i+1); else if(qAbs(intermediary.at(i+3).y() - mid_value) < qAbs(intermediary.at(i+1).y() - mid_value)) FittingLine << intermediary.at(i+2) << intermediary.at(i+3); else FittingLine << intermediary.at(i+1) << intermediary.at(i+2); i += 4; } //两条拟合直线,两个点 for(i = 0; i < FittingLine.size();) { k = (FittingLine.at(i).y() - FittingLine.at(i+1).y()) / (FittingLine.at(i).x() - FittingLine.at(i+1).x()); b = FittingLine.at(i).y() - k * FittingLine.at(i).x(); x = (mid_value-b) / k; pointX.push_back(x); i += 2; } //半峰宽值 FWHM = pointX.at(1) - pointX.at(0); ////面积 // PeakAreaCalculation(point); //!!! double leve, a1, a2, h, TriangleArea; double startY = currentData.at(StartIndex_one).y(); double startX = currentData.at(StartIndex_one).x(); double endY = currentData.at(EndIndex_one).y(); double endX = currentData.at(EndIndex_one).x(); //单峰情况 if(startY > endY) { leve = startY; } else { leve = endY; } TriangleArea=qAbs(startY - endY) * (endX - startX) / 2; for(int i2 = StartIndex_one;i2 <= EndIndex_one; i2++) { a1 = currentData.at(i2).y() - leve; a2 = currentData.at(i2 - 1).y() - leve; h = currentData.at(i2).x() - currentData.at(i2 - 1).x(); Area += (a1+a2) * h / 2; } Area = Area - TriangleArea; } void Utils::systemSettingsInit() { QString filePath = Utils::getSettingFilePath(); if (filePath.isEmpty()) { Utils::tipMessageBox("配置文件路径错误"); return; } QFileInfo info(filePath); //已存在配置文件 if (info.exists()) { return; } //数据库 DBParams db; writeSettings(&db); //UDP UdpParams udp; writeSettings(&udp); //数据入库参数配置 DBInsertParams dbInsert; writeSettings(&dbInsert); } QString Utils::getSettingFilePath() { QString filePath = QDir::currentPath(); if (!filePath.isEmpty()) { filePath.append("/Settings.ini"); } return filePath; } void Utils::readSettings(Params *data) { QString filePath = getSettingFilePath(); QSettings settings(filePath, QSettings::IniFormat); if (settings.childGroups().contains(data->groupName)) { settings.beginGroup(data->groupName); for (int i = 0; i < data->nameList.size(); i++) { data->valueList[i] = settings.value(data->nameList.at(i)); } settings.endGroup(); data->isSucess = true; return; } data->isSucess = false; } void Utils::writeSettings(Params *data) { QString filePath = getSettingFilePath(); QSettings settings(filePath, QSettings::IniFormat); settings.beginGroup(data->groupName); int lenth = data->nameList.size(); for (int i = 0; i < lenth; i ++) { settings.setValue(data->nameList.at(i), data->valueList.at(i)); } settings.endGroup(); }
[ "1076992525@qq.com" ]
1076992525@qq.com
5562965f300489fed340c5b1e61128af9b9af9ad
2aec12368cc5a493af73301d500afb59f0d19d28
/GeometryTool/LibGraphics/SceneGraph/Wm4BoundingVolume.h
4ccefa938fdb7cee5256d30dfe92946e8a59452e
[]
no_license
GGBone/WM4
ec964fc61f98ae39e160564a38fe7624273137fb
8e9998e25924df3e0d765921b6d2a715887fbb01
refs/heads/master
2021-01-11T21:48:17.477941
2017-01-13T14:09:53
2017-01-13T14:09:53
78,854,366
0
2
null
null
null
null
UTF-8
C++
false
false
3,135
h
// Geometric Tools, Inc. // http://www.geometrictools.com // Copyright (c) 1998-2006. All Rights Reserved // // The Wild Magic Version 4 Restricted Libraries source code is supplied // under the terms of the license agreement // http://www.geometrictools.com/License/Wm4RestrictedLicense.pdf // and may not be copied or disclosed except in accordance with the terms // of that agreement. #ifndef WM4BOUNDINGVOLUME_H #define WM4BOUNDINGVOLUME_H #include "Wm4GraphicsLIB.h" #include "Wm4Object.h" #include "Wm4Plane3.h" #include "Wm4Ray3.h" #include "Wm4Transformation.h" #include "Wm4Vector3Array.h" #include "Wm4VertexBuffer.h" namespace Wm4 { class WM4_GRAPHICS_ITEM BoundingVolume : public Object { WM4_DECLARE_RTTI; WM4_DECLARE_NAME_ID; WM4_DECLARE_STREAM; public: // abstract base class virtual ~BoundingVolume (); // run-time type information enum BVType { BV_SPHERE, BV_BOX, BV_QUANTITY }; virtual int GetBVType () const = 0; // all bounding volumes must define a center and radius virtual void SetCenter (const Vector3f& rkCenter) = 0; virtual void SetRadius (float fRadius) = 0; virtual Vector3f GetCenter () const = 0; virtual float GetRadius () const = 0; // One of the derived classes has the responsibility for implementing // this factory function. Our default is the WmlSphereBV class, but // you may change it to another. static BoundingVolume* Create (); // Compute a bounding volume that contains all the points. virtual void ComputeFromData (const Vector3fArray* pkVertices) = 0; virtual void ComputeFromData (const VertexBuffer* pkVBuffer) = 0; // Transform the bounding volume (model-to-world conversion). virtual void TransformBy (const Transformation& rkTransform, BoundingVolume* pkResult) = 0; // Determine if the bounding volume is one side of the plane, the other // side, or straddles the plane. If it is on the positive side (the // side to which the normal points), the return value is +1. If it is // on the negative side, the return value is -1. If it straddles the // plane, the return value is 0. virtual int WhichSide (const Plane3f& rkPlane) const = 0; // Test for intersection of ray and bound (points of intersection not // computed). The input direction must be unit length. virtual bool TestIntersection (const Ray3f& rkRay) const = 0; // Test for intersection of the two bounds. virtual bool TestIntersection (const BoundingVolume* pkInput) const = 0; // Make a copy of the bounding volume. virtual void CopyFrom (const BoundingVolume* pkInput) = 0; // Change the current bounding volume so that it contains the input // bounding volume as well as its old bounding volume. virtual void GrowToContain (const BoundingVolume* pkInput) = 0; // test for containment of a point virtual bool Contains (const Vector3f& rkPoint) const = 0; protected: BoundingVolume (); }; WM4_REGISTER_STREAM(BoundingVolume); typedef Pointer<BoundingVolume> BoundingVolumePtr; } #endif
[ "z652137200@gmail.com" ]
z652137200@gmail.com
9a69907603be6910843d73e716224623b77acbac
9fa5d9ef9f9a4896126f42d2d16e87948a73579d
/xagent/xagent.hxx
878c27e9e462809031d20a702bb3c71c6c83650d
[]
no_license
ReadingCode/xware
6c3272171922014f49216c36f70de31756ccd2b1
6a7edf746822d38c084867a7ce9930cc5a764da9
refs/heads/master
2020-03-26T05:03:53.876231
2013-05-29T06:09:32
2013-05-29T06:09:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,499
hxx
/* * **************************************************************************** * * * * * Copyright 2008, xWorkshop Inc. * * * All rights reserved. * * * Redistribution and use in source and binary forms, with or without * * * modification, are permitted provided that the following conditions are * * * met: * * * * Redistributions of source code must retain the above copyright * * * notice, this list of conditions and the following disclaimer. * * * * Redistributions in binary form must reproduce the above * * * copyright notice, this list of conditions and the following disclaimer * * * in the documentation and/or other materials provided with the * * * distribution. * * * * Neither the name of xWorkshop Inc. nor the names of its * * * contributors may be used to endorse or promote products derived from * * * this software without specific prior written permission. * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * * * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * * * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * * * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * * * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * * * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * * * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * * * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * * * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * * * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * * * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * * * * * Author: stoneyrh@163.com * * * * * **************************************************************************** */ #ifndef _X_AGENT_H_ #define _X_AGENT_H_ #include "xnetwork.hxx" #include "xtcp_server.hxx" #include "xtcp_io_object.hxx" #include "xnet_service_manager.hxx" #include "xnet_message_handler_manager.hxx" #include "xconsole_event_listener.hxx" namespace xws { class xagent : public xconsole_event_listener { public: xagent(); virtual ~xagent(); xio_service& io_service() { return io_service_; } virtual int run(); virtual void stop(); /* * xconsole_event_listener */ virtual bool on_ctrl_c(); virtual bool on_ctrl_close(); virtual bool on_ctrl_break(); virtual bool on_ctrl_log_off(); virtual bool on_ctrl_shutdown(); private: void on_connection_established(xtcp_io_object_ptr& io_object); private: xio_service io_service_; xtcp_server tcp_server_; xnet_message_handler_manager_ptr tcp_service_handler_manager_; xnet_service_manager net_service_manager_; }; } // namespace xws #endif
[ "stoneyrh@163.com" ]
stoneyrh@163.com
9d3bdaffd541bf7c14e33bd3b1c082be6f666288
91b65dccbf5e9076f95194a30447c482681b691e
/munin/src/toggle_button.cpp
931a965179716fb421f248d8804ccde84b05e8db
[ "MIT" ]
permissive
Cloudxtreme/paradice9
0dfbbd1bbafb59924c7f72e3c4bacafdb90d0d13
448532b0c717ee321cffd2727eab60d1cf57883c
refs/heads/master
2021-05-31T17:06:31.847371
2016-06-09T18:31:07
2016-06-09T18:31:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,225
cpp
// ========================================================================== // Munin Toggle Button. // // Copyright (C) 2012 Matthew Chaplain, All Rights Reserved. // // Permission to reproduce, distribute, perform, display, and to prepare // derivitive works from this file under the following conditions: // // 1. Any copy, reproduction or derivitive work of any part of this file // contains this copyright notice and licence in its entirety. // // 2. The rights granted to you under this license automatically terminate // should you attempt to assert any patent claims against the licensor // or contributors, which in any way restrict the ability of any party // from using this software or portions thereof in any form under the // terms of this license. // // Disclaimer: 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 "munin/toggle_button.hpp" #include "munin/container.hpp" #include "munin/framed_component.hpp" #include "munin/grid_layout.hpp" #include "munin/image.hpp" #include "munin/solid_frame.hpp" #include <terminalpp/ansi/mouse.hpp> #include <terminalpp/string.hpp> #include <terminalpp/virtual_key.hpp> namespace munin { // ========================================================================== // TOGGLE_BUTTON::IMPLEMENTATION STRUCTURE // ========================================================================== struct toggle_button::impl { std::shared_ptr<image> image_; bool state_; }; // ========================================================================== // CONSTRUCTOR // ========================================================================== toggle_button::toggle_button(bool default_state) : pimpl_(std::make_shared<impl>()) { pimpl_->image_ = make_image(default_state ? "X" : " "); pimpl_->image_->set_can_focus(true); pimpl_->state_ = default_state; get_container()->set_layout(make_grid_layout(1, 1)); get_container()->add_component( make_framed_component(make_solid_frame(), pimpl_->image_)); } // ========================================================================== // DESTRUCTOR // ========================================================================== toggle_button::~toggle_button() { } // ========================================================================== // SET_TOGGLE // ========================================================================== void toggle_button::set_toggle(bool toggle) { using namespace terminalpp::literals; if (toggle != pimpl_->state_) { pimpl_->state_ = toggle; pimpl_->image_->set_image(toggle ? "X" : " "); } } // ========================================================================== // GET_TOGGLE // ========================================================================== bool toggle_button::get_toggle() const { return pimpl_->state_; } // ========================================================================== // DO_EVENT // ========================================================================== void toggle_button::do_event(boost::any const &event) { auto vk = boost::any_cast<terminalpp::virtual_key>(&event); if (vk) { if (vk->key == terminalpp::vk::space || vk->key == terminalpp::vk::enter) { set_toggle(!get_toggle()); set_focus(); } } auto report = boost::any_cast<terminalpp::ansi::mouse::report>(&event); if (report && report->button_ == terminalpp::ansi::mouse::report::LEFT_BUTTON_DOWN) { set_toggle(!get_toggle()); set_focus(); } } }
[ "matthew.chaplain@gmail.com" ]
matthew.chaplain@gmail.com
69ef5da03c189cab77babea8e56f573dd2a8fc5d
9d51fd27f6aa8941cab53b9b1b19f853d1716c49
/SMA_Toolbox/tools/RDCapture/src/rdcapture_cache.cpp
39a8d082b932398179e22cb6f4f6fd728acd88e1
[]
no_license
samanthalschwartz/NeuronAnalysisToolbox
ca0794976f686a8e8f50a55c0fd9442ce9203d5f
bc05a36ae940510860f0c97e74d0b9b72e58e69b
refs/heads/master
2021-06-07T14:16:26.263498
2019-11-19T03:40:11
2019-11-19T03:40:11
135,669,686
2
1
null
null
null
null
UTF-8
C++
false
false
293
cpp
/** @file rdcapture_cache.cpp * @author Mark J. Olah (mjo\@cs.unm.edu) * @date 07-2016 * @brief Cache RDCaptrue computations for certain times. * */ #include "rdcapture_cache.h" RDCaptureCache::RDCaptureCache(const RDCapture &_rd) : rd(std::make_shared<RDCapture>(_rd)) { }
[ "samantha.schwartz(at)ucdenver(dot)edu" ]
samantha.schwartz(at)ucdenver(dot)edu
1599c5df1ce998384e6034fde850298f70b29bdf
9098e625bf59edc15361008075e3a00fc95da414
/Practica1/Practica 1 FInal/sketch_feb09a/sketch_feb09a.ino
12fcfc3c415c57ffd992f5be1e8e3c36f8847cbb
[]
no_license
ricardcutzh/Arqui1_Arduino
749e8e5416a68e1f16f6c6a5ba29514aee352f7e
429545598ba11b9020739a2c06520134bd47689f
refs/heads/master
2021-05-03T21:27:23.900170
2018-02-25T22:31:27
2018-02-25T22:31:27
120,384,673
0
0
null
null
null
null
UTF-8
C++
false
false
15,135
ino
#include<stdio.h> #include<stdlib.h> #include<string.h> // // Declaramos pines a usar para 74ls48 int a = 5; int b = 4; int c = 3; int d = 2; //Variables para la lectura de la resistencia int analogPin= 0; int raw= 0; int Vin= 5; float Vout= 0; float R1= 100000; float R2= 0; float buffer= 0; //PUERTOS DEFINIDOS ANTERIOR MENTE EN EL ARDUINO MEGA Y DIAGRAMA DE COMBINACIONES // 5, 2, 7, 1, e, 8, c, h int portColums[] = {30, 24, 34, 22, 31, 36, 27, 37}; // a, b, f, 6, g, 4, 3, d int portRows[] = {23, 25, 33, 32, 35, 28, 26, 29}; //NUMERO DE LETRAS int cantidad; //VARIABLES ENCARGADAS DE LLEVAR LA POSICION DE LOS LIMITES int posinicio, posfin; //VARIABLE QUE IDENTIFICA LA POSICION int posicion; //VARIABLE QUE MANEJA LA VELOCIDA int velocidad; //VARIABLE QUE LLEVA EL CONTROL DE LA LETRA QUE SE DEBE DE MOSTRAR int indice; //TIPO DE MOVIMIENTO int tipo; int dir; //MATRIZ GLOBAL int matrizTrans[8][8] = { {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0} }; //MATRIZ DE PRUEBA // COL | FILA int BLANK[4][8] = { {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0} }; int GUION[4][8] = { {0, 0, 0, 1, 1, 0, 0, 0}, {0, 0, 0, 1, 1, 0, 0, 0}, {0, 0, 0, 1, 1, 0, 0, 0}, {0, 0, 0, 1, 1, 0, 0, 0} }; int AST[4][8] = { {0, 0, 1, 0, 1, 0, 1, 0}, {0, 0, 0, 1, 1, 1, 0, 0}, {0, 0, 0, 1, 1, 1, 0, 0}, {0, 0, 1, 0, 1, 0, 1, 0} }; /*----------------------------*/ int A[4][8] = { {0, 1, 1, 1, 1, 1, 1, 0}, {0, 0, 0, 0, 1, 0, 1, 0}, {0, 0, 0, 0, 1, 0, 1, 0}, {0, 1, 1, 1, 1, 1, 1, 0} }; /*----------------------------*/ int B[4][8] = { {0, 1, 1, 1, 1, 1, 1, 0}, {0, 1, 0, 0, 1, 0, 1, 0}, {0, 1, 0, 0, 1, 0, 1, 0}, {0, 0, 1, 1, 0, 1, 1, 0} }; /*----------------------------*/ int C[4][8] = { {0, 0, 1, 1, 1, 1, 0, 0}, {0, 1, 0, 0, 0, 0, 1, 0}, {0, 1, 0, 0, 0, 0, 1, 0}, {0, 0, 1, 0, 0, 1, 0, 0} }; /*----------------------------*/ int D[4][8] = { {0, 1, 1, 1, 1, 1, 1, 0}, {0, 1, 0, 0, 0, 0, 1, 0}, {0, 1, 0, 0, 0, 0, 1, 0}, {0, 0, 1, 1, 1, 1, 0, 0} }; /*----------------------------*/ int E[4][8] = { {0, 1, 1, 1, 1, 1, 1, 0}, {0, 1, 0, 0, 1, 0, 1, 0}, {0, 1, 0, 0, 1, 0, 1, 0}, {0, 1, 0, 0, 0, 0, 1, 0} }; /*----------------------------*/ int F[4][8] = { {0, 1, 1, 1, 1, 1, 1, 0}, {0, 0, 0, 0, 1, 0, 1, 0}, {0, 0, 0, 0, 1, 0, 1, 0}, {0, 0, 0, 0, 0, 0, 1, 0} }; /*----------------------------*/ int G[4][8] = { {0, 1, 1, 1, 1, 1, 1, 0}, {0, 1, 0, 0, 0, 0, 1, 0}, {0, 1, 0, 0, 1, 0, 1, 0}, {0, 1, 1, 1, 1, 0, 1, 0} }; /*----------------------------*/ int H[4][8] = { {0, 1, 1, 1, 1, 1, 1, 0}, {0, 0, 0, 0, 1, 0, 0, 0}, {0, 0, 0, 0, 1, 0, 0, 0}, {0, 1, 1, 1, 1, 1, 1, 0} }; /*----------------------------*/ int I[4][8] = { {0, 1, 0, 0, 0, 0, 1, 0}, {0, 1, 1, 1, 1, 1, 1, 0}, {0, 1, 1, 1, 1, 1, 1, 0}, {0, 1, 0, 0, 0, 0, 1, 0} }; /*----------------------------*/ int J[4][8] = { {0, 1, 1, 1, 0, 0, 1, 0}, {0, 1, 0, 0, 0, 0, 1, 0}, {0, 1, 1, 1, 1, 1, 1, 0}, {0, 0, 0, 0, 0, 0, 1, 0} }; /*----------------------------*/ int K[4][8] = { {0, 1, 1, 1, 1, 1, 1, 0}, {0, 0, 0, 1, 1, 0, 0, 0}, {0, 0, 1, 0, 0, 1, 0, 0}, {0, 1, 0, 0, 0, 0, 1, 0} }; /*----------------------------*/ int L[4][8] = { {0, 1, 1, 1, 1, 1, 1, 0}, {0, 1, 0, 0, 0, 0, 0, 0}, {0, 1, 0, 0, 0, 0, 0, 0}, {0, 1, 0, 0, 0, 0, 0, 0} }; /*----------------------------*/ int M[4][8] = { {0, 1, 1, 1, 1, 1, 1, 0}, {0, 0, 0, 0, 0, 1, 0, 0}, {0, 0, 0, 0, 0, 1, 0, 0}, {0, 1, 1, 1, 1, 1, 1, 0} }; /*----------------------------*/ int N[4][8] = { {0, 1, 1, 1, 1, 1, 1, 0}, {0, 0, 0, 0, 1, 0, 0, 0}, {0, 0, 0, 1, 0, 0, 0, 0}, {0, 1, 1, 1, 1, 1, 1, 0} }; /*----------------------------*/ int O[4][8] = { {0, 0, 1, 1, 1, 1, 0, 0}, {0, 1, 0, 0, 0, 0, 1, 0}, {0, 1, 0, 0, 0, 0, 1, 0}, {0, 0, 1, 1, 1, 1, 0, 0} }; /*----------------------------*/ int P[4][8] = { {0, 1, 1, 1, 1, 1, 1, 0}, {0, 0, 0, 1, 0, 0, 1, 0}, {0, 0, 0, 1, 0, 0, 1, 0}, {0, 0, 0, 0, 1, 1, 0, 0} }; /*----------------------------*/ int Q[4][8] = { {0, 0, 1, 1, 1, 1, 0, 0}, {0, 1, 0, 0, 0, 0, 1, 0}, {0, 1, 1, 0, 0, 0, 1, 0}, {0, 1, 1, 1, 1, 1, 0, 0} }; /*----------------------------*/ int R[4][8] = { {0, 1, 1, 1, 1, 1, 1, 0}, {0, 0, 0, 1, 0, 0, 1, 0}, {0, 0, 1, 1, 0, 0, 1, 0}, {0, 1, 0, 0, 1, 1, 0, 0} }; /*----------------------------*/ int S[4][8] = { {0, 0, 1, 0, 0, 1, 0, 0}, {0, 1, 0, 0, 1, 0, 1, 0}, {0, 1, 0, 0, 1, 0, 1, 0}, {0, 0, 1, 1, 0, 0, 1, 0} }; /*----------------------------*/ int T[4][8] = { {0, 0, 0, 0, 0, 1, 1, 0}, {0, 1, 1, 1, 1, 1, 1, 0}, {0, 1, 1, 1, 1, 1, 1, 0}, {0, 0, 0, 0, 0, 1, 1, 0} }; /*----------------------------*/ int U[4][8] = { {0, 0, 1, 1, 1, 1, 1, 0}, {0, 1, 0, 0, 0, 0, 0, 0}, {0, 1, 0, 0, 0, 0, 0, 0}, {0, 0, 1, 1, 1, 1, 1, 0} }; /*----------------------------*/ int V[4][8] = { {0, 1, 1, 1, 1, 1, 1, 0}, {0, 1, 0, 0, 0, 0, 0, 0}, {0, 1, 0, 0, 0, 0, 0, 0}, {0, 1, 1, 1, 1, 1, 1, 0} }; /*----------------------------*/ int W[4][8] = { {0, 1, 1, 1, 1, 1, 1, 0}, {0, 0, 1, 0, 0, 0, 0, 0}, {0, 0, 1, 0, 0, 0, 0, 0}, {0, 1, 1, 1, 1, 1, 1, 0} }; /*----------------------------*/ int Y[4][8] = { {0, 0, 0, 0, 0, 1, 1, 0}, {0, 0, 0, 0, 1, 0, 0, 0}, {0, 1, 1, 1, 1, 0, 0, 0}, {0, 0, 0, 0, 0, 1, 1, 0} }; int N1[4][8] = { {0, 1, 0, 0, 1, 0, 0, 0}, {0, 1, 0, 0, 0, 1, 0, 0}, {0, 1, 1, 1, 1, 1, 1, 0}, {0, 1, 0, 0, 0, 0, 0, 0} }; int N7[4][8] = { {0, 0, 0, 0, 0, 0, 1, 0}, {0, 0, 0, 0, 1, 0, 1, 0}, {0, 1, 1, 1, 1, 1, 1, 0}, {0, 0, 0, 0, 0, 0, 0, 0} }; int N2[4][8] = { {0, 1, 1, 1, 0, 1, 0, 0}, {0, 1, 0, 1, 0, 0, 1, 0}, {0, 1, 0, 0, 1, 0, 1, 0}, {0, 1, 1, 0, 0, 1, 0, 0} }; char letras[] = "*TP1-GRUPO-7-SECCION-A*"; int len = sizeof(letras) / sizeof(char); void setup() { // put your setup code here, to run once: Serial.begin(9600); indice = 0; init_setup(); setColumns(); setRows(); set_display(); pinMode(50, INPUT); pinMode(39, INPUT); cantidad = len; definirLimites(cantidad, digitalRead(50)); posicion = posinicio; } void loop() { // put your main code here, to run repeatedly: dir = digitalRead(50); tipo = digitalRead(39); if (dir == LOW && tipo == LOW) //IZQUIERDA A DERECHA,CORRIDO { definirLimites(cantidad, dir); posicion--; if (posicion <= posfin) { posicion = posinicio; } int val; for (int x = 0; x < len; x++) { char l = letras[x]; val = posicion + (x * 5); if (val >= 0 && val < 7) { indice = x; selecciona_Letra(l, val); } } int vel = consultarVelocidad(); interpreta_matriz(matrizTrans, vel); clearMatrix(); } else if (dir == LOW && tipo == HIGH) //IZQUIERDA A DERECHA,ESTATICO { indice++; if (indice >= len) { indice = 0; } int vel = consultarVelocidad(); selecciona_Letra(letras[indice], 2); interpreta_matriz(matrizTrans, vel+vel); clearMatrix(); } else if (dir == HIGH && tipo == LOW) //DERECHA A IZQUIERDA,CORRIDO { definirLimites(cantidad, dir); posicion++; if (posicion >= posfin) { posicion = posinicio; } int val; for (int x = 0; x < len; x++) { char l = letras[x]; val = posicion + (x * 5); if (val >= 0 && val < 7) { indice = x; selecciona_Letra(l, val); } } int vel = consultarVelocidad(); interpreta_matriz(matrizTrans, vel); clearMatrix(); } else if (dir == HIGH && tipo == HIGH) //DERECHA A IZQUIERDA,ESTATICO { clearMatrix(); indice--; if (indice < 0) { indice = len; } int vel = consultarVelocidad(); selecciona_Letra(letras[indice], 2); interpreta_matriz(matrizTrans, vel+vel); } } /**************************************************************/ void mov_estatico() { define_incremento_est(); selecciona_Letra(letras[indice], 2); interpreta_matriz(matrizTrans, 0); clearMatrix(); } void define_incremento_est() { if (dir == HIGH) { indice++; if (indice >= len) { indice = 0; } } else { indice--; if (indice < 0) { indice = len; } } } /**************************************************************/ void mov_corrido() { if (dir == HIGH) { definirLimites(cantidad, dir); posicion++; if (posicion >= posfin) { posicion = posinicio; } } else { definirLimites(cantidad, dir); posicion--; if (posicion <= posfin) { posicion = posinicio; } } movimiento(); } void movimiento() { int val; for (int x = 0; x < len; x++) { char l = letras[x]; val = posicion + (x * 5); if (val >= 0 || val < 7) { indice = x; selecciona_Letra(l, val); } } interpreta_matriz(matrizTrans, 0); clearMatrix(); } //METODO PARA MOSTRAR void definirLimites(int numeroLetras, int direccion) { int op = -((numeroLetras - 1) * 5 + 4); if (direccion == HIGH) //VA LA DERECHA { //DEFINICION DE LOS LIMITES posfin = 8; if (numeroLetras == 1) { posinicio = -4; } else { posinicio = op; } //DEFINICION DE LOS LIMITES } else { //DEFINICION DE LOS LIMITES posinicio = 8; if (numeroLetras == 1) { posfin = -4; } else { posfin = op; } //DEFINICION DE LOS LIMITES } } //METODO QUE SE ENCARGA DE INTERPRETAR UNA MATRIZ QUE DEFINE LA SALIDA DE LOS LEDS void interpreta_matriz(int matriz[8][8], int retardo) { for (int x = 0; x < retardo; x++) { for (int col = 0; col < 8; col++) { digitalWrite(portColums[col], HIGH); for (int fil = 0; fil < 8; fil++) { if (matriz[col][fil] == 1) { digitalWrite(portRows[fil], LOW); } } digitalWrite(portColums[col], LOW); setRows(); } } } //CORRE LA LETRA HACIA LA DERECHA void correLetra(int letra[4][8], int colinicio) { //clearMatrix(); if (!(colinicio < -4)) { int colfinal = colinicio + 4; if (colfinal > 8) { colfinal = 8; } for (int col = colinicio; col < colfinal; col++) { for (int fil = 0; fil < 8; fil++) { matrizTrans[col][fil] = letra[col - colinicio][fil]; } } } } //PARA VER LA //MATRIZ EN EL PUERTO SERIAL void printMatrix() { Serial.begin(9600); for (int col = 0; col < 8; col++) { for (int fil = 0; fil < 8; fil++) { Serial.print(matrizTrans[col][fil]); Serial.print(" "); } Serial.println(""); } Serial.println("---------------------------------------------"); } //VACIA LA MATRIZ void clearMatrix() { for (int col = 0; col < 8; col++) { for (int fil = 0; fil < 8; fil++) { matrizTrans[col][fil] = 0; } } } //METODO QUE SE ENCARGA DE SETEAR DE INICIO LA MODALIDAD DE LOS PINES A UTILIZAR void init_setup() { for (int x = 22; x < 38; x++) { pinMode(x, OUTPUT); } } //METODO QUE SE ENCARGA DE PONER LAS FILAS COLUMNAS EN APAGADOS void setColumns() { for (int x = 0; x < 8; x++) { digitalWrite(portColums[x], LOW); } } //METODO QUE SE ENCARGA DE PONER LAS FILAS EN APAGADOS void setRows() { for (int x = 0; x < 8; x++) { digitalWrite(portRows[x], HIGH); } } void selecciona_Letra(char letra, int pos) { if ('-' == letra) { correLetra(GUION, pos); return; } if ('*' == letra) { correLetra(AST, pos); return; } if ('A' == letra) { correLetra(A, pos); return; } if ('B' == letra) { correLetra(B, pos); return; } if ('C' == letra) { correLetra(C, pos); return; } if ('D' == letra) { correLetra(D, pos); return; } if ('E' == letra) { correLetra(E, pos); return; } if ('F' == letra) { correLetra(F, pos); return; } if ('G' == letra) { correLetra(G, pos); return; } if ('H' == letra) { correLetra(H, pos); return; } if ('I' == letra) { correLetra(I, pos); return; } if ('J' == letra) { correLetra(J, pos); return; } if ('K' == letra) { correLetra(K, pos); return; } if ('L' == letra) { correLetra(L, pos); return; } if ('M' == letra) { correLetra(M, pos); return; } if ('N' == letra) { correLetra(N, pos); return; } if ('O' == letra) { correLetra(O, pos); return; } if ('P' == letra) { correLetra(P, pos); return; } if ('Q' == letra) { correLetra(Q, pos); return; } if ('R' == letra) { correLetra(R, pos); return; } if ('S' == letra) { correLetra(S, pos); return; } if ('T' == letra) { correLetra(T, pos); return; } if ('U' == letra) { correLetra(U, pos); return; } if ('V' == letra) { correLetra(V, pos); return; } if ('W' == letra) { correLetra(W, pos); return; } if ('Y' == letra) { correLetra(Y, pos); return; } if ('1' == letra) { correLetra(N1, pos); return; } if ('7' == letra) { correLetra(N7, pos); return; } if ('2' == letra) { correLetra(N2, pos); return; } } void set_display() { //Definir Pines de Display pinMode(a, OUTPUT); pinMode(b, OUTPUT); pinMode(c, OUTPUT); pinMode(d, OUTPUT); } /*************************DISPLAY*********************************/ void numeroUno(){ //Numero 1 digitalWrite(a, HIGH); digitalWrite(b, LOW); digitalWrite(c, LOW); digitalWrite(d, LOW); } void numeroDos(){ //numero 2 digitalWrite(a, LOW); digitalWrite(b, HIGH); digitalWrite(c, LOW); digitalWrite(d, LOW); } void numeroTres(){ //Numero 3 digitalWrite(a, HIGH); digitalWrite(b, HIGH); digitalWrite(c, LOW); digitalWrite(d, LOW); } void numeroCuatro(){ //Numero 4 digitalWrite(a, LOW); digitalWrite(b, LOW); digitalWrite(c, HIGH); digitalWrite(d, LOW); } void numeroCinco(){ //Numero 5 digitalWrite(a, HIGH); digitalWrite(b, LOW); digitalWrite(c, HIGH); digitalWrite(d, LOW); } /**************************************************************/ int consultarVelocidad() { //***Procedimiento para capturar el potenciometro**** int retorno=0; raw= analogRead(analogPin); if(raw){ buffer= raw * Vin; Vout= (buffer)/1024.0; buffer= (Vin/Vout) -1; R2= R1 * buffer; Serial.print("Vout: "); Serial.println(Vout); Serial.print("R2: "); Serial.println(R2); if (R2<100000){ retorno=1000; numeroUno(); }else if(R2<200000){ retorno = 800; numeroDos(); }else if(R2<300000){ retorno = 400; numeroTres(); }else if(R2<400000){ retorno = 200; numeroCuatro(); }else{ retorno = 100; numeroCinco(); } //delay(500); } return retorno; } /**************************************************************/
[ "ricardcutzh@gmail.com" ]
ricardcutzh@gmail.com
85663577fa0dd91544a561c4b51a96f31cfa1178
a202c9a7cf6f2476785a9ffbba43685b25a71072
/cbiexp-0.6/src/fopen.h
bbf2fcb141d789989e63c3ff0b2f678e52dd31ff
[ "BSD-3-Clause" ]
permissive
petablox/cbi
cd6a0baca3274fb616179ddc1a7f002c1eb4f98b
3ee890b51c656a936428842e1451f47218db6cfa
refs/heads/master
2021-09-08T01:22:17.432345
2018-03-05T03:16:36
2018-03-05T03:16:36
114,415,976
1
0
null
null
null
null
UTF-8
C++
false
false
297
h
#ifndef INCLUDE_fopen_h #define INCLUDE_fopen_h #include <cstdio> #include <string> #include <stdlib.h> #include <string.h> FILE *fopenRead(const char *); FILE *fopenRead(const std::string &); FILE *fopenWrite(const char *); FILE *fopenWrite(const std::string &); #endif // !INCLUDE_fopen_h
[ "wslee@fir08.gtisc.gatech.edu" ]
wslee@fir08.gtisc.gatech.edu
675f936e79725cb945f70ff13b961e35329d0a11
2d587926a2ba8a44e96085a2d09c4f2375a24f02
/display_list/testing/dl_rendering_unittests.cc
0c7f11640f87804d122775463255ac7625a57828
[ "BSD-3-Clause" ]
permissive
chrsan/engine
2b0701c1077730470c75ff30322b095f8778f9e6
d7a5de672d1e3e147e3374cef4d30119d87c8954
refs/heads/main
2023-05-26T00:23:47.875921
2023-05-16T13:32:28
2023-05-16T13:32:28
526,506,088
0
0
BSD-3-Clause
2022-08-19T07:29:10
2022-08-19T07:29:09
null
UTF-8
C++
false
false
159,210
cc
// Copyright 2013 The Flutter 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 <utility> #include "flutter/display_list/display_list.h" #include "flutter/display_list/dl_builder.h" #include "flutter/display_list/dl_op_flags.h" #include "flutter/display_list/dl_sampling_options.h" #include "flutter/display_list/skia/dl_sk_canvas.h" #include "flutter/display_list/skia/dl_sk_dispatcher.h" #include "flutter/display_list/testing/dl_test_surface_provider.h" #include "flutter/display_list/utils/dl_comparable.h" #include "flutter/fml/math.h" #include "flutter/testing/display_list_testing.h" #include "flutter/testing/testing.h" #include "third_party/skia/include/core/SkColorFilter.h" #include "third_party/skia/include/core/SkPictureRecorder.h" #include "third_party/skia/include/core/SkSurface.h" #include "third_party/skia/include/effects/SkGradientShader.h" #include "third_party/skia/include/effects/SkImageFilters.h" namespace flutter { namespace testing { using ClipOp = DlCanvas::ClipOp; using PointMode = DlCanvas::PointMode; constexpr int kTestWidth = 200; constexpr int kTestHeight = 200; constexpr int kRenderWidth = 100; constexpr int kRenderHeight = 100; constexpr int kRenderHalfWidth = 50; constexpr int kRenderHalfHeight = 50; constexpr int kRenderLeft = (kTestWidth - kRenderWidth) / 2; constexpr int kRenderTop = (kTestHeight - kRenderHeight) / 2; constexpr int kRenderRight = kRenderLeft + kRenderWidth; constexpr int kRenderBottom = kRenderTop + kRenderHeight; constexpr int kRenderCenterX = (kRenderLeft + kRenderRight) / 2; constexpr int kRenderCenterY = (kRenderTop + kRenderBottom) / 2; constexpr SkScalar kRenderRadius = std::min(kRenderWidth, kRenderHeight) / 2.0; constexpr SkScalar kRenderCornerRadius = kRenderRadius / 5.0; constexpr SkPoint kTestCenter = SkPoint::Make(kTestWidth / 2, kTestHeight / 2); constexpr SkRect kTestBounds = SkRect::MakeWH(kTestWidth, kTestHeight); constexpr SkRect kRenderBounds = SkRect::MakeLTRB(kRenderLeft, kRenderTop, kRenderRight, kRenderBottom); // The tests try 3 miter limit values, 0.0, 4.0 (the default), and 10.0 // These values will allow us to construct a diamond that spans the // width or height of the render box and still show the miter for 4.0 // and 10.0. // These values were discovered by drawing a diamond path in Skia fiddle // and then playing with the cross-axis size until the miter was about // as large as it could get before it got cut off. // The X offsets which will be used for tall vertical diamonds are // expressed in terms of the rendering height to obtain the proper angle constexpr SkScalar kMiterExtremeDiamondOffsetX = kRenderHeight * 0.04; constexpr SkScalar kMiter10DiamondOffsetX = kRenderHeight * 0.051; constexpr SkScalar kMiter4DiamondOffsetX = kRenderHeight * 0.14; // The Y offsets which will be used for long horizontal diamonds are // expressed in terms of the rendering width to obtain the proper angle constexpr SkScalar kMiterExtremeDiamondOffsetY = kRenderWidth * 0.04; constexpr SkScalar kMiter10DiamondOffsetY = kRenderWidth * 0.051; constexpr SkScalar kMiter4DiamondOffsetY = kRenderWidth * 0.14; // Render 3 vertical and horizontal diamonds each // designed to break at the tested miter limits // 0.0, 4.0 and 10.0 // Center is biased by 0.5 to include more pixel centers in the // thin miters constexpr SkScalar kXOffset0 = kRenderCenterX + 0.5; constexpr SkScalar kXOffsetL1 = kXOffset0 - kMiter4DiamondOffsetX; constexpr SkScalar kXOffsetL2 = kXOffsetL1 - kMiter10DiamondOffsetX; constexpr SkScalar kXOffsetL3 = kXOffsetL2 - kMiter10DiamondOffsetX; constexpr SkScalar kXOffsetR1 = kXOffset0 + kMiter4DiamondOffsetX; constexpr SkScalar kXOffsetR2 = kXOffsetR1 + kMiterExtremeDiamondOffsetX; constexpr SkScalar kXOffsetR3 = kXOffsetR2 + kMiterExtremeDiamondOffsetX; constexpr SkPoint kVerticalMiterDiamondPoints[] = { // Vertical diamonds: // M10 M4 Mextreme // /\ /|\ /\ top of RenderBounds // / \ / | \ / \ to // <----X--+--X----> RenderCenter // \ / \ | / \ / to // \/ \|/ \/ bottom of RenderBounds // clang-format off SkPoint::Make(kXOffsetL3, kRenderCenterY), SkPoint::Make(kXOffsetL2, kRenderTop), SkPoint::Make(kXOffsetL1, kRenderCenterY), SkPoint::Make(kXOffset0, kRenderTop), SkPoint::Make(kXOffsetR1, kRenderCenterY), SkPoint::Make(kXOffsetR2, kRenderTop), SkPoint::Make(kXOffsetR3, kRenderCenterY), SkPoint::Make(kXOffsetR2, kRenderBottom), SkPoint::Make(kXOffsetR1, kRenderCenterY), SkPoint::Make(kXOffset0, kRenderBottom), SkPoint::Make(kXOffsetL1, kRenderCenterY), SkPoint::Make(kXOffsetL2, kRenderBottom), SkPoint::Make(kXOffsetL3, kRenderCenterY), // clang-format on }; const int kVerticalMiterDiamondPointCount = sizeof(kVerticalMiterDiamondPoints) / sizeof(kVerticalMiterDiamondPoints[0]); constexpr SkScalar kYOffset0 = kRenderCenterY + 0.5; constexpr SkScalar kYOffsetU1 = kXOffset0 - kMiter4DiamondOffsetY; constexpr SkScalar kYOffsetU2 = kYOffsetU1 - kMiter10DiamondOffsetY; constexpr SkScalar kYOffsetU3 = kYOffsetU2 - kMiter10DiamondOffsetY; constexpr SkScalar kYOffsetD1 = kXOffset0 + kMiter4DiamondOffsetY; constexpr SkScalar kYOffsetD2 = kYOffsetD1 + kMiterExtremeDiamondOffsetY; constexpr SkScalar kYOffsetD3 = kYOffsetD2 + kMiterExtremeDiamondOffsetY; const SkPoint kHorizontalMiterDiamondPoints[] = { // Horizontal diamonds // Same configuration as Vertical diamonds above but // rotated 90 degrees // clang-format off SkPoint::Make(kRenderCenterX, kYOffsetU3), SkPoint::Make(kRenderLeft, kYOffsetU2), SkPoint::Make(kRenderCenterX, kYOffsetU1), SkPoint::Make(kRenderLeft, kYOffset0), SkPoint::Make(kRenderCenterX, kYOffsetD1), SkPoint::Make(kRenderLeft, kYOffsetD2), SkPoint::Make(kRenderCenterX, kYOffsetD3), SkPoint::Make(kRenderRight, kYOffsetD2), SkPoint::Make(kRenderCenterX, kYOffsetD1), SkPoint::Make(kRenderRight, kYOffset0), SkPoint::Make(kRenderCenterX, kYOffsetU1), SkPoint::Make(kRenderRight, kYOffsetU2), SkPoint::Make(kRenderCenterX, kYOffsetU3), // clang-format on }; const int kHorizontalMiterDiamondPointCount = (sizeof(kHorizontalMiterDiamondPoints) / sizeof(kHorizontalMiterDiamondPoints[0])); class SkImageSampling { public: static constexpr SkSamplingOptions kNearestNeighbor = SkSamplingOptions(SkFilterMode::kNearest); static constexpr SkSamplingOptions kLinear = SkSamplingOptions(SkFilterMode::kLinear); static constexpr SkSamplingOptions kMipmapLinear = SkSamplingOptions(SkFilterMode::kLinear, SkMipmapMode::kLinear); static constexpr SkSamplingOptions kCubic = SkSamplingOptions(SkCubicResampler{1 / 3.0f, 1 / 3.0f}); }; // A class to specify how much tolerance to allow in bounds estimates. // For some attributes, the machinery must make some conservative // assumptions as to the extent of the bounds, but some of our test // parameters do not produce bounds that expand by the full conservative // estimates. This class provides a number of tweaks to apply to the // pixel bounds to account for the conservative factors. // // An instance is passed along through the methods and if any test adds // a paint attribute or other modifier that will cause a more conservative // estimate for bounds, it can modify the factors here to account for it. // Ideally, all tests will be executed with geometry that will trigger // the conservative cases anyway and all attributes will be combined with // other attributes that make their output more predictable, but in those // cases where a given test sequence cannot really provide attributes to // demonstrate the worst case scenario, they can modify these factors to // avoid false bounds overflow notifications. class BoundsTolerance { public: BoundsTolerance() = default; BoundsTolerance(const BoundsTolerance&) = default; BoundsTolerance addBoundsPadding(SkScalar bounds_pad_x, SkScalar bounds_pad_y) const { BoundsTolerance copy = BoundsTolerance(*this); copy.bounds_pad_.offset(bounds_pad_x, bounds_pad_y); return copy; } BoundsTolerance mulScale(SkScalar scale_x, SkScalar scale_y) const { BoundsTolerance copy = BoundsTolerance(*this); copy.scale_.fX *= scale_x; copy.scale_.fY *= scale_y; return copy; } BoundsTolerance addAbsolutePadding(SkScalar absolute_pad_x, SkScalar absolute_pad_y) const { BoundsTolerance copy = BoundsTolerance(*this); copy.absolute_pad_.offset(absolute_pad_x, absolute_pad_y); return copy; } BoundsTolerance addPostClipPadding(SkScalar absolute_pad_x, SkScalar absolute_pad_y) const { BoundsTolerance copy = BoundsTolerance(*this); copy.clip_pad_.offset(absolute_pad_x, absolute_pad_y); return copy; } BoundsTolerance addDiscreteOffset(SkScalar discrete_offset) const { BoundsTolerance copy = BoundsTolerance(*this); copy.discrete_offset_ += discrete_offset; return copy; } BoundsTolerance clip(SkRect clip) const { BoundsTolerance copy = BoundsTolerance(*this); if (!copy.clip_.intersect(clip)) { copy.clip_.setEmpty(); } return copy; } static SkRect Scale(const SkRect& rect, const SkPoint& scales) { SkScalar outset_x = rect.width() * (scales.fX - 1); SkScalar outset_y = rect.height() * (scales.fY - 1); return rect.makeOutset(outset_x, outset_y); } bool overflows(SkIRect pix_bounds, int worst_bounds_pad_x, int worst_bounds_pad_y) const { SkRect allowed = SkRect::Make(pix_bounds); allowed.outset(bounds_pad_.fX, bounds_pad_.fY); allowed = Scale(allowed, scale_); allowed.outset(absolute_pad_.fX, absolute_pad_.fY); if (!allowed.intersect(clip_)) { allowed.setEmpty(); } allowed.outset(clip_pad_.fX, clip_pad_.fY); SkIRect rounded = allowed.roundOut(); int pad_left = std::max(0, pix_bounds.fLeft - rounded.fLeft); int pad_top = std::max(0, pix_bounds.fTop - rounded.fTop); int pad_right = std::max(0, pix_bounds.fRight - rounded.fRight); int pad_bottom = std::max(0, pix_bounds.fBottom - rounded.fBottom); int allowed_pad_x = std::max(pad_left, pad_right); int allowed_pad_y = std::max(pad_top, pad_bottom); if (worst_bounds_pad_x > allowed_pad_x || worst_bounds_pad_y > allowed_pad_y) { FML_LOG(ERROR) << "acceptable bounds padding: " // << allowed_pad_x << ", " << allowed_pad_y; } return (worst_bounds_pad_x > allowed_pad_x || worst_bounds_pad_y > allowed_pad_y); } SkScalar discrete_offset() const { return discrete_offset_; } bool operator==(BoundsTolerance const& other) const { return bounds_pad_ == other.bounds_pad_ && scale_ == other.scale_ && absolute_pad_ == other.absolute_pad_ && clip_ == other.clip_ && clip_pad_ == other.clip_pad_ && discrete_offset_ == other.discrete_offset_; } private: SkPoint bounds_pad_ = {0, 0}; SkPoint scale_ = {1, 1}; SkPoint absolute_pad_ = {0, 0}; SkRect clip_ = {-1E9, -1E9, 1E9, 1E9}; SkPoint clip_pad_ = {0, 0}; SkScalar discrete_offset_ = 0; }; using SkSetup = const std::function<void(SkCanvas*, SkPaint&)>; using SkRenderer = const std::function<void(SkCanvas*, const SkPaint&)>; using DlSetup = const std::function<void(DlCanvas*, DlPaint&)>; using DlRenderer = const std::function<void(DlCanvas*, const DlPaint&)>; static const SkSetup kEmptySkSetup = [](SkCanvas*, SkPaint&) {}; static const SkRenderer kEmptySkRenderer = [](SkCanvas*, const SkPaint&) {}; static const DlSetup kEmptyDlSetup = [](DlCanvas*, DlPaint&) {}; static const DlRenderer kEmptyDlRenderer = [](DlCanvas*, const DlPaint&) {}; using PixelFormat = DlSurfaceProvider::PixelFormat; using BackendType = DlSurfaceProvider::BackendType; class RenderResult { public: explicit RenderResult(const sk_sp<SkSurface>& surface) { SkImageInfo info = surface->imageInfo(); info = SkImageInfo::MakeN32Premul(info.dimensions()); addr_ = malloc(info.computeMinByteSize() * info.height()); pixmap_.reset(info, addr_, info.minRowBytes()); EXPECT_TRUE(surface->readPixels(pixmap_, 0, 0)); } ~RenderResult() { free(addr_); } int width() const { return pixmap_.width(); } int height() const { return pixmap_.height(); } const uint32_t* addr32(int x, int y) const { return pixmap_.addr32(x, y); } private: SkPixmap pixmap_; void* addr_ = nullptr; }; struct RenderJobInfo { int width = kTestWidth; int height = kTestHeight; DlColor bg = DlColor::kTransparent(); SkScalar scale = SK_Scalar1; SkScalar opacity = SK_Scalar1; }; struct JobRenderer { virtual void Render(SkCanvas* canvas, const RenderJobInfo& info) = 0; }; struct MatrixClipJobRenderer : public JobRenderer { public: const SkMatrix& setup_matrix() const { FML_CHECK(is_setup_); return setup_matrix_; } const SkIRect& setup_clip_bounds() const { FML_CHECK(is_setup_); return setup_clip_bounds_; } protected: bool is_setup_ = false; SkMatrix setup_matrix_; SkIRect setup_clip_bounds_; }; struct SkJobRenderer : public MatrixClipJobRenderer { explicit SkJobRenderer(const SkSetup& sk_setup = kEmptySkSetup, const SkRenderer& sk_render = kEmptySkRenderer, const SkRenderer& sk_restore = kEmptySkRenderer) : sk_setup_(sk_setup), sk_render_(sk_render), sk_restore_(sk_restore) {} void Render(SkCanvas* canvas, const RenderJobInfo& info) override { FML_DCHECK(info.opacity == SK_Scalar1); SkPaint paint; sk_setup_(canvas, paint); setup_paint_ = paint; setup_matrix_ = canvas->getTotalMatrix(); setup_clip_bounds_ = canvas->getDeviceClipBounds(); is_setup_ = true; sk_render_(canvas, paint); sk_restore_(canvas, paint); } sk_sp<SkPicture> MakePicture(const RenderJobInfo& info) { SkPictureRecorder recorder; SkRTreeFactory rtree_factory; SkCanvas* cv = recorder.beginRecording(kTestBounds, &rtree_factory); Render(cv, info); return recorder.finishRecordingAsPicture(); } const SkPaint& setup_paint() const { FML_CHECK(is_setup_); return setup_paint_; } private: const SkSetup sk_setup_; const SkRenderer sk_render_; const SkRenderer sk_restore_; SkPaint setup_paint_; }; struct DlJobRenderer : public MatrixClipJobRenderer { explicit DlJobRenderer(const DlSetup& dl_setup = kEmptyDlSetup, const DlRenderer& dl_render = kEmptyDlRenderer, const DlRenderer& dl_restore = kEmptyDlRenderer) : dl_setup_(dl_setup), dl_render_(dl_render), dl_restore_(dl_restore) {} void Render(SkCanvas* sk_canvas, const RenderJobInfo& info) override { DlSkCanvasAdapter canvas(sk_canvas); Render(&canvas, info); } void Render(DlCanvas* canvas, const RenderJobInfo& info) { FML_DCHECK(info.opacity == SK_Scalar1); DlPaint paint; dl_setup_(canvas, paint); setup_paint_ = paint; setup_matrix_ = canvas->GetTransform(); setup_clip_bounds_ = canvas->GetDestinationClipBounds().roundOut(); is_setup_ = true; dl_render_(canvas, paint); dl_restore_(canvas, paint); } sk_sp<DisplayList> MakeDisplayList(const RenderJobInfo& info) { DisplayListBuilder builder(kTestBounds); Render(&builder, info); return builder.Build(); } const DlPaint& setup_paint() const { FML_CHECK(is_setup_); return setup_paint_; } private: const DlSetup dl_setup_; const DlRenderer dl_render_; const DlRenderer dl_restore_; DlPaint setup_paint_; }; struct SkPictureJobRenderer : public JobRenderer { explicit SkPictureJobRenderer(sk_sp<SkPicture> picture) : picture_(std::move(picture)) {} void Render(SkCanvas* canvas, const RenderJobInfo& info) { FML_DCHECK(info.opacity == SK_Scalar1); picture_->playback(canvas); } private: sk_sp<SkPicture> picture_; }; struct DisplayListJobRenderer : public JobRenderer { explicit DisplayListJobRenderer(sk_sp<DisplayList> display_list) : display_list_(std::move(display_list)) {} void Render(SkCanvas* canvas, const RenderJobInfo& info) { DlSkCanvasAdapter(canvas).DrawDisplayList(display_list_, info.opacity); } private: sk_sp<DisplayList> display_list_; }; class RenderEnvironment { public: RenderEnvironment(const DlSurfaceProvider* provider, PixelFormat format) : provider_(provider), format_(format) { if (provider->supports(format)) { surface_1x_ = provider->MakeOffscreenSurface(kTestWidth, kTestHeight, format); surface_2x_ = provider->MakeOffscreenSurface(kTestWidth * 2, kTestHeight * 2, format); } } static RenderEnvironment Make565(const DlSurfaceProvider* provider) { return RenderEnvironment(provider, PixelFormat::k565_PixelFormat); } static RenderEnvironment MakeN32(const DlSurfaceProvider* provider) { return RenderEnvironment(provider, PixelFormat::kN32Premul_PixelFormat); } void init_ref(SkRenderer& sk_renderer, DlRenderer& dl_renderer, DlColor bg = DlColor::kTransparent()) { init_ref(kEmptySkSetup, sk_renderer, kEmptyDlSetup, dl_renderer, bg); } void init_ref(SkSetup& sk_setup, SkRenderer& sk_renderer, DlSetup& dl_setup, DlRenderer& dl_renderer, DlColor bg = DlColor::kTransparent()) { SkJobRenderer sk_job(sk_setup, sk_renderer); RenderJobInfo info = { .bg = bg, }; ref_sk_result_ = getResult(info, sk_job); DlJobRenderer dl_job(dl_setup, dl_renderer); ref_dl_result_ = getResult(info, dl_job); ref_dl_paint_ = dl_job.setup_paint(); ref_matrix_ = dl_job.setup_matrix(); ref_clip_bounds_ = dl_job.setup_clip_bounds(); ASSERT_EQ(sk_job.setup_matrix(), ref_matrix_); ASSERT_EQ(sk_job.setup_clip_bounds(), ref_clip_bounds_); } std::unique_ptr<RenderResult> getResult(const RenderJobInfo& info, JobRenderer& renderer) const { auto surface = getSurface(info.width, info.height); FML_DCHECK(surface != nullptr); auto canvas = surface->getCanvas(); canvas->clear(info.bg); int restore_count = canvas->save(); canvas->scale(info.scale, info.scale); renderer.Render(canvas, info); canvas->restoreToCount(restore_count); canvas->flush(); surface->flushAndSubmit(true); return std::make_unique<RenderResult>(surface); } std::unique_ptr<RenderResult> getResult(sk_sp<DisplayList> dl) const { DisplayListJobRenderer job(std::move(dl)); RenderJobInfo info = {}; return getResult(info, job); } const DlSurfaceProvider* provider() const { return provider_; } bool valid() const { return provider_->supports(format_); } const std::string backend_name() const { return provider_->backend_name(); } PixelFormat format() const { return format_; } const DlPaint& ref_dl_paint() const { return ref_dl_paint_; } const SkMatrix& ref_matrix() const { return ref_matrix_; } const SkIRect& ref_clip_bounds() const { return ref_clip_bounds_; } const RenderResult* ref_sk_result() const { return ref_sk_result_.get(); } const RenderResult* ref_dl_result() const { return ref_dl_result_.get(); } private: sk_sp<SkSurface> getSurface(int width, int height) const { FML_DCHECK(valid()); FML_DCHECK(surface_1x_ != nullptr); FML_DCHECK(surface_2x_ != nullptr); if (width == kTestWidth && height == kTestHeight) { return surface_1x_->sk_surface(); } if (width == kTestWidth * 2 && height == kTestHeight * 2) { return surface_2x_->sk_surface(); } FML_LOG(ERROR) << "Test surface size (" << width << " x " << height << ") not supported."; FML_DCHECK(false); return nullptr; } const DlSurfaceProvider* provider_; const PixelFormat format_; std::shared_ptr<DlSurfaceInstance> surface_1x_; std::shared_ptr<DlSurfaceInstance> surface_2x_; DlPaint ref_dl_paint_; SkMatrix ref_matrix_; SkIRect ref_clip_bounds_; std::unique_ptr<RenderResult> ref_sk_result_; std::unique_ptr<RenderResult> ref_dl_result_; }; class CaseParameters { public: explicit CaseParameters(std::string info) : CaseParameters(std::move(info), kEmptySkSetup, kEmptyDlSetup) {} CaseParameters(std::string info, SkSetup& sk_setup, DlSetup& dl_setup) : CaseParameters(std::move(info), sk_setup, dl_setup, kEmptySkRenderer, kEmptyDlRenderer, SK_ColorTRANSPARENT, false, false, false) {} CaseParameters(std::string info, SkSetup& sk_setup, DlSetup& dl_setup, SkRenderer& sk_restore, DlRenderer& dl_restore, DlColor bg, bool has_diff_clip, bool has_mutating_save_layer, bool fuzzy_compare_components) : info_(std::move(info)), bg_(bg), sk_setup_(sk_setup), dl_setup_(dl_setup), sk_restore_(sk_restore), dl_restore_(dl_restore), has_diff_clip_(has_diff_clip), has_mutating_save_layer_(has_mutating_save_layer), fuzzy_compare_components_(fuzzy_compare_components) {} CaseParameters with_restore(SkRenderer& sk_restore, DlRenderer& dl_restore, bool mutating_layer, bool fuzzy_compare_components = false) { return CaseParameters(info_, sk_setup_, dl_setup_, sk_restore, dl_restore, bg_, has_diff_clip_, mutating_layer, fuzzy_compare_components); } CaseParameters with_bg(DlColor bg) { return CaseParameters(info_, sk_setup_, dl_setup_, sk_restore_, dl_restore_, bg, has_diff_clip_, has_mutating_save_layer_, fuzzy_compare_components_); } CaseParameters with_diff_clip() { return CaseParameters(info_, sk_setup_, dl_setup_, sk_restore_, dl_restore_, bg_, true, has_mutating_save_layer_, fuzzy_compare_components_); } std::string info() const { return info_; } DlColor bg() const { return bg_; } bool has_diff_clip() const { return has_diff_clip_; } bool has_mutating_save_layer() const { return has_mutating_save_layer_; } bool fuzzy_compare_components() const { return fuzzy_compare_components_; } SkSetup sk_setup() const { return sk_setup_; } DlSetup dl_setup() const { return dl_setup_; } SkRenderer sk_restore() const { return sk_restore_; } DlRenderer dl_restore() const { return dl_restore_; } private: const std::string info_; const DlColor bg_; const SkSetup sk_setup_; const DlSetup dl_setup_; const SkRenderer sk_restore_; const DlRenderer dl_restore_; const bool has_diff_clip_; const bool has_mutating_save_layer_; const bool fuzzy_compare_components_; }; class TestParameters { public: TestParameters(const SkRenderer& sk_renderer, const DlRenderer& dl_renderer, const DisplayListAttributeFlags& flags) : sk_renderer_(sk_renderer), dl_renderer_(dl_renderer), flags_(flags) {} bool uses_paint() const { return !flags_.ignores_paint(); } bool should_match(const RenderEnvironment& env, const CaseParameters& caseP, const DlPaint& attr, const MatrixClipJobRenderer& renderer) const { if (caseP.has_mutating_save_layer()) { return false; } if (env.ref_clip_bounds() != renderer.setup_clip_bounds() || caseP.has_diff_clip()) { return false; } if (env.ref_matrix() != renderer.setup_matrix() && !flags_.is_flood()) { return false; } if (flags_.ignores_paint()) { return true; } const DlPaint& ref_attr = env.ref_dl_paint(); if (flags_.applies_anti_alias() && // ref_attr.isAntiAlias() != attr.isAntiAlias()) { return false; } if (flags_.applies_dither() && // ref_attr.isDither() != attr.isDither()) { return false; } if (flags_.applies_color() && // ref_attr.getColor() != attr.getColor()) { return false; } if (flags_.applies_blend() && // ref_attr.getBlendMode() != attr.getBlendMode()) { return false; } if (flags_.applies_color_filter() && // (ref_attr.isInvertColors() != attr.isInvertColors() || NotEquals(ref_attr.getColorFilter(), attr.getColorFilter()))) { return false; } if (flags_.applies_mask_filter() && // NotEquals(ref_attr.getMaskFilter(), attr.getMaskFilter())) { return false; } if (flags_.applies_image_filter() && // ref_attr.getImageFilter() != attr.getImageFilter()) { return false; } if (flags_.applies_shader() && // NotEquals(ref_attr.getColorSource(), attr.getColorSource())) { return false; } bool is_stroked = flags_.is_stroked(attr.getDrawStyle()); if (flags_.is_stroked(ref_attr.getDrawStyle()) != is_stroked) { return false; } DisplayListSpecialGeometryFlags geo_flags = flags_.WithPathEffect(attr.getPathEffect().get(), is_stroked); if (flags_.applies_path_effect() && // ref_attr.getPathEffect() != attr.getPathEffect()) { switch (attr.getPathEffect()->type()) { case DlPathEffectType::kDash: { if (is_stroked && !ignores_dashes()) { return false; } } } } if (!is_stroked) { return true; } if (ref_attr.getStrokeWidth() != attr.getStrokeWidth()) { return false; } if (geo_flags.may_have_end_caps() && // getCap(ref_attr, geo_flags) != getCap(attr, geo_flags)) { return false; } if (geo_flags.may_have_joins()) { if (ref_attr.getStrokeJoin() != attr.getStrokeJoin()) { return false; } if (ref_attr.getStrokeJoin() == DlStrokeJoin::kMiter) { SkScalar ref_miter = ref_attr.getStrokeMiter(); SkScalar test_miter = attr.getStrokeMiter(); // miter limit < 1.4 affects right angles if (geo_flags.may_have_acute_joins() || // ref_miter < 1.4 || test_miter < 1.4) { if (ref_miter != test_miter) { return false; } } } } return true; } DlStrokeCap getCap(const DlPaint& attr, DisplayListSpecialGeometryFlags geo_flags) const { DlStrokeCap cap = attr.getStrokeCap(); if (geo_flags.butt_cap_becomes_square() && cap == DlStrokeCap::kButt) { return DlStrokeCap::kSquare; } return cap; } const BoundsTolerance adjust(const BoundsTolerance& tolerance, const DlPaint& paint, const SkMatrix& matrix) const { if (is_draw_text_blob() && tolerance.discrete_offset() > 0) { // drawTextBlob needs just a little more leeway when using a // discrete path effect. return tolerance.addBoundsPadding(2, 2); } if (is_draw_line()) { return lineAdjust(tolerance, paint, matrix); } if (is_draw_arc_center()) { if (paint.getDrawStyle() != DlDrawStyle::kFill && paint.getStrokeJoin() == DlStrokeJoin::kMiter) { // the miter join at the center of an arc does not really affect // its bounds in any of our test cases, but the bounds code needs // to take it into account for the cases where it might, so we // relax our tolerance to reflect the miter bounds padding. SkScalar miter_pad = paint.getStrokeMiter() * paint.getStrokeWidth() * 0.5f; return tolerance.addBoundsPadding(miter_pad, miter_pad); } } return tolerance; } const BoundsTolerance lineAdjust(const BoundsTolerance& tolerance, const DlPaint& paint, const SkMatrix& matrix) const { SkScalar adjust = 0.0; SkScalar half_width = paint.getStrokeWidth() * 0.5f; if (tolerance.discrete_offset() > 0) { // When a discrete path effect is added, the bounds calculations must // allow for miters in any direction, but a horizontal line will not // have miters in the horizontal direction, similarly for vertical // lines, and diagonal lines will have miters off at a "45 degree" // angle that don't expand the bounds much at all. // Also, the discrete offset will not move any points parallel with // the line, so provide tolerance for both miters and offset. adjust = half_width * paint.getStrokeMiter() + tolerance.discrete_offset(); } auto path_effect = paint.getPathEffect(); DisplayListSpecialGeometryFlags geo_flags = flags_.WithPathEffect(path_effect.get(), true); if (paint.getStrokeCap() == DlStrokeCap::kButt && !geo_flags.butt_cap_becomes_square()) { adjust = std::max(adjust, half_width); } if (adjust == 0) { return tolerance; } SkScalar h_tolerance; SkScalar v_tolerance; if (is_horizontal_line()) { FML_DCHECK(!is_vertical_line()); h_tolerance = adjust; v_tolerance = 0; } else if (is_vertical_line()) { h_tolerance = 0; v_tolerance = adjust; } else { // The perpendicular miters just do not impact the bounds of // diagonal lines at all as they are aimed in the wrong direction // to matter. So allow tolerance in both axes. h_tolerance = v_tolerance = adjust; } BoundsTolerance new_tolerance = tolerance.addBoundsPadding(h_tolerance, v_tolerance); return new_tolerance; } const SkRenderer& sk_renderer() const { return sk_renderer_; } const DlRenderer& dl_renderer() const { return dl_renderer_; } // Tests that call drawTextBlob with an sk_ref paint attribute will cause // those attributes to be stored in an internal Skia cache so we need // to expect that the |sk_ref.unique()| call will fail in those cases. // See: (TBD(flar) - file Skia bug) bool is_draw_text_blob() const { return is_draw_text_blob_; } bool is_draw_display_list() const { return is_draw_display_list_; } bool is_draw_line() const { return is_draw_line_; } bool is_draw_arc_center() const { return is_draw_arc_center_; } bool is_draw_path() const { return is_draw_path_; } bool is_horizontal_line() const { return is_horizontal_line_; } bool is_vertical_line() const { return is_vertical_line_; } bool ignores_dashes() const { return ignores_dashes_; } TestParameters& set_draw_text_blob() { is_draw_text_blob_ = true; return *this; } TestParameters& set_draw_display_list() { is_draw_display_list_ = true; return *this; } TestParameters& set_draw_line() { is_draw_line_ = true; return *this; } TestParameters& set_draw_arc_center() { is_draw_arc_center_ = true; return *this; } TestParameters& set_draw_path() { is_draw_path_ = true; return *this; } TestParameters& set_ignores_dashes() { ignores_dashes_ = true; return *this; } TestParameters& set_horizontal_line() { is_horizontal_line_ = true; return *this; } TestParameters& set_vertical_line() { is_vertical_line_ = true; return *this; } private: const SkRenderer& sk_renderer_; const DlRenderer& dl_renderer_; const DisplayListAttributeFlags& flags_; bool is_draw_text_blob_ = false; bool is_draw_display_list_ = false; bool is_draw_line_ = false; bool is_draw_arc_center_ = false; bool is_draw_path_ = false; bool ignores_dashes_ = false; bool is_horizontal_line_ = false; bool is_vertical_line_ = false; }; class CanvasCompareTester { public: static std::vector<std::unique_ptr<DlSurfaceProvider>> kTestProviders; static BoundsTolerance DefaultTolerance; static void RenderAll(const TestParameters& params, const BoundsTolerance& tolerance = DefaultTolerance) { for (auto& provider : kTestProviders) { RenderEnvironment env = RenderEnvironment::MakeN32(provider.get()); env.init_ref(params.sk_renderer(), params.dl_renderer()); quickCompareToReference(env, "default"); RenderWithTransforms(params, env, tolerance); RenderWithClips(params, env, tolerance); RenderWithSaveRestore(params, env, tolerance); // Only test attributes if the canvas version uses the paint object if (params.uses_paint()) { RenderWithAttributes(params, env, tolerance); } } } static void RenderWithSaveRestore(const TestParameters& testP, const RenderEnvironment& env, const BoundsTolerance& tolerance) { SkRect clip = SkRect::MakeXYWH(kRenderCenterX - 1, kRenderCenterY - 1, 2, 2); SkRect rect = SkRect::MakeXYWH(kRenderCenterX, kRenderCenterY, 10, 10); DlColor alpha_layer_color = DlColor::kCyan().withAlpha(0x7f); SkRenderer sk_safe_restore = [=](SkCanvas* cv, const SkPaint& p) { // Draw another primitive to disable peephole optimizations cv->drawRect(kRenderBounds.makeOffset(500, 500), SkPaint()); cv->restore(); }; DlRenderer dl_safe_restore = [=](DlCanvas* cv, const DlPaint& p) { // Draw another primitive to disable peephole optimizations // As the rendering op rejection in the DisplayList Builder // gets smarter and smarter, this operation has had to get // sneakier and sneakier about specifying an operation that // won't practically show up in the output, but technically // can't be culled. cv->DrawRect( SkRect::MakeXYWH(kRenderCenterX, kRenderCenterY, 0.0001, 0.0001), DlPaint()); cv->Restore(); }; SkRenderer sk_opt_restore = [=](SkCanvas* cv, const SkPaint& p) { // Just a simple restore to allow peephole optimizations to occur cv->restore(); }; DlRenderer dl_opt_restore = [=](DlCanvas* cv, const DlPaint& p) { // Just a simple restore to allow peephole optimizations to occur cv->Restore(); }; SkRect layer_bounds = kRenderBounds.makeInset(15, 15); RenderWith(testP, env, tolerance, CaseParameters( "With prior save/clip/restore", [=](SkCanvas* cv, SkPaint& p) { cv->save(); cv->clipRect(clip, SkClipOp::kIntersect, false); SkPaint p2; cv->drawRect(rect, p2); p2.setBlendMode(SkBlendMode::kClear); cv->drawRect(rect, p2); cv->restore(); }, [=](DlCanvas* cv, DlPaint& p) { cv->Save(); cv->ClipRect(clip, ClipOp::kIntersect, false); DlPaint p2; cv->DrawRect(rect, p2); p2.setBlendMode(DlBlendMode::kClear); cv->DrawRect(rect, p2); cv->Restore(); })); RenderWith(testP, env, tolerance, CaseParameters( "saveLayer no paint, no bounds", [=](SkCanvas* cv, SkPaint& p) { // cv->saveLayer(nullptr, nullptr); }, [=](DlCanvas* cv, DlPaint& p) { // cv->SaveLayer(nullptr, nullptr); }) .with_restore(sk_safe_restore, dl_safe_restore, false)); RenderWith(testP, env, tolerance, CaseParameters( "saveLayer no paint, with bounds", [=](SkCanvas* cv, SkPaint& p) { // cv->saveLayer(layer_bounds, nullptr); }, [=](DlCanvas* cv, DlPaint& p) { // cv->SaveLayer(&layer_bounds, nullptr); }) .with_restore(sk_safe_restore, dl_safe_restore, true)); RenderWith(testP, env, tolerance, CaseParameters( "saveLayer with alpha, no bounds", [=](SkCanvas* cv, SkPaint& p) { SkPaint save_p; save_p.setColor(alpha_layer_color); cv->saveLayer(nullptr, &save_p); }, [=](DlCanvas* cv, DlPaint& p) { DlPaint save_p; save_p.setColor(alpha_layer_color); cv->SaveLayer(nullptr, &save_p); }) .with_restore(sk_safe_restore, dl_safe_restore, true)); RenderWith(testP, env, tolerance, CaseParameters( "saveLayer with peephole alpha, no bounds", [=](SkCanvas* cv, SkPaint& p) { SkPaint save_p; save_p.setColor(alpha_layer_color); cv->saveLayer(nullptr, &save_p); }, [=](DlCanvas* cv, DlPaint& p) { DlPaint save_p; save_p.setColor(alpha_layer_color); cv->SaveLayer(nullptr, &save_p); }) .with_restore(sk_opt_restore, dl_opt_restore, true, true)); RenderWith(testP, env, tolerance, CaseParameters( "saveLayer with alpha and bounds", [=](SkCanvas* cv, SkPaint& p) { SkPaint save_p; save_p.setColor(alpha_layer_color); cv->saveLayer(layer_bounds, &save_p); }, [=](DlCanvas* cv, DlPaint& p) { DlPaint save_p; save_p.setColor(alpha_layer_color); cv->SaveLayer(&layer_bounds, &save_p); }) .with_restore(sk_safe_restore, dl_safe_restore, true)); { // Being able to see a backdrop blur requires a non-default background // so we create a new environment for these tests that has a checkerboard // background that can be blurred by the backdrop filter. We also want // to avoid the rendered primitive from obscuring the blurred background // so we set an alpha value which works for all primitives except for // drawColor which can override the alpha with its color, but it now uses // a non-opaque color to avoid that problem. RenderEnvironment backdrop_env = RenderEnvironment::MakeN32(env.provider()); SkSetup sk_backdrop_setup = [=](SkCanvas* cv, SkPaint& p) { SkPaint setup_p; setup_p.setShader(kTestSkImageColorSource); cv->drawPaint(setup_p); }; DlSetup dl_backdrop_setup = [=](DlCanvas* cv, DlPaint& p) { DlPaint setup_p; setup_p.setColorSource(&kTestDlImageColorSource); cv->DrawPaint(setup_p); }; SkSetup sk_content_setup = [=](SkCanvas* cv, SkPaint& p) { p.setAlpha(p.getAlpha() / 2); }; DlSetup dl_content_setup = [=](DlCanvas* cv, DlPaint& p) { p.setAlpha(p.getAlpha() / 2); }; backdrop_env.init_ref(sk_backdrop_setup, testP.sk_renderer(), dl_backdrop_setup, testP.dl_renderer()); quickCompareToReference(backdrop_env, "backdrop"); DlBlurImageFilter dl_backdrop(5, 5, DlTileMode::kDecal); auto sk_backdrop = SkImageFilters::Blur(5, 5, SkTileMode::kDecal, nullptr); RenderWith(testP, backdrop_env, tolerance, CaseParameters( "saveLayer with backdrop", [=](SkCanvas* cv, SkPaint& p) { sk_backdrop_setup(cv, p); cv->saveLayer(SkCanvas::SaveLayerRec( nullptr, nullptr, sk_backdrop.get(), 0)); sk_content_setup(cv, p); }, [=](DlCanvas* cv, DlPaint& p) { dl_backdrop_setup(cv, p); cv->SaveLayer(nullptr, nullptr, &dl_backdrop); dl_content_setup(cv, p); }) .with_restore(sk_safe_restore, dl_safe_restore, true)); RenderWith(testP, backdrop_env, tolerance, CaseParameters( "saveLayer with bounds and backdrop", [=](SkCanvas* cv, SkPaint& p) { sk_backdrop_setup(cv, p); cv->saveLayer(SkCanvas::SaveLayerRec( &layer_bounds, nullptr, sk_backdrop.get(), 0)); sk_content_setup(cv, p); }, [=](DlCanvas* cv, DlPaint& p) { dl_backdrop_setup(cv, p); cv->SaveLayer(&layer_bounds, nullptr, &dl_backdrop); dl_content_setup(cv, p); }) .with_restore(sk_safe_restore, dl_safe_restore, true)); RenderWith(testP, backdrop_env, tolerance, CaseParameters( "clipped saveLayer with backdrop", [=](SkCanvas* cv, SkPaint& p) { sk_backdrop_setup(cv, p); cv->clipRect(layer_bounds); cv->saveLayer(SkCanvas::SaveLayerRec( nullptr, nullptr, sk_backdrop.get(), 0)); sk_content_setup(cv, p); }, [=](DlCanvas* cv, DlPaint& p) { dl_backdrop_setup(cv, p); cv->ClipRect(layer_bounds); cv->SaveLayer(nullptr, nullptr, &dl_backdrop); dl_content_setup(cv, p); }) .with_restore(sk_safe_restore, dl_safe_restore, true)); } { // clang-format off constexpr float rotate_alpha_color_matrix[20] = { 0, 1, 0, 0 , 0, 0, 0, 1, 0 , 0, 1, 0, 0, 0 , 0, 0, 0, 0, 0.5, 0, }; // clang-format on DlMatrixColorFilter dl_alpha_rotate_filter(rotate_alpha_color_matrix); auto sk_alpha_rotate_filter = SkColorFilters::Matrix(rotate_alpha_color_matrix); { RenderWith(testP, env, tolerance, CaseParameters( "saveLayer ColorFilter, no bounds", [=](SkCanvas* cv, SkPaint& p) { SkPaint save_p; save_p.setColorFilter(sk_alpha_rotate_filter); cv->saveLayer(nullptr, &save_p); p.setStrokeWidth(5.0); }, [=](DlCanvas* cv, DlPaint& p) { DlPaint save_p; save_p.setColorFilter(&dl_alpha_rotate_filter); cv->SaveLayer(nullptr, &save_p); p.setStrokeWidth(5.0); }) .with_restore(sk_safe_restore, dl_safe_restore, true)); } { RenderWith(testP, env, tolerance, CaseParameters( "saveLayer ColorFilter and bounds", [=](SkCanvas* cv, SkPaint& p) { SkPaint save_p; save_p.setColorFilter(sk_alpha_rotate_filter); cv->saveLayer(kRenderBounds, &save_p); p.setStrokeWidth(5.0); }, [=](DlCanvas* cv, DlPaint& p) { DlPaint save_p; save_p.setColorFilter(&dl_alpha_rotate_filter); cv->SaveLayer(&kRenderBounds, &save_p); p.setStrokeWidth(5.0); }) .with_restore(sk_safe_restore, dl_safe_restore, true)); } } { // clang-format off constexpr float color_matrix[20] = { 0.5, 0, 0, 0, 0.5, 0, 0.5, 0, 0, 0.5, 0, 0, 0.5, 0, 0.5, 0, 0, 0, 1, 0, }; // clang-format on DlMatrixColorFilter dl_color_filter(color_matrix); DlColorFilterImageFilter dl_cf_image_filter(dl_color_filter); auto sk_cf_image_filter = SkImageFilters::ColorFilter( SkColorFilters::Matrix(color_matrix), nullptr); { RenderWith(testP, env, tolerance, CaseParameters( "saveLayer ImageFilter, no bounds", [=](SkCanvas* cv, SkPaint& p) { SkPaint save_p; save_p.setImageFilter(sk_cf_image_filter); cv->saveLayer(nullptr, &save_p); p.setStrokeWidth(5.0); }, [=](DlCanvas* cv, DlPaint& p) { DlPaint save_p; save_p.setImageFilter(&dl_cf_image_filter); cv->SaveLayer(nullptr, &save_p); p.setStrokeWidth(5.0); }) .with_restore(sk_safe_restore, dl_safe_restore, true)); } { RenderWith(testP, env, tolerance, CaseParameters( "saveLayer ImageFilter and bounds", [=](SkCanvas* cv, SkPaint& p) { SkPaint save_p; save_p.setImageFilter(sk_cf_image_filter); cv->saveLayer(kRenderBounds, &save_p); p.setStrokeWidth(5.0); }, [=](DlCanvas* cv, DlPaint& p) { DlPaint save_p; save_p.setImageFilter(&dl_cf_image_filter); cv->SaveLayer(&kRenderBounds, &save_p); p.setStrokeWidth(5.0); }) .with_restore(sk_safe_restore, dl_safe_restore, true)); } } } static void RenderWithAttributes(const TestParameters& testP, const RenderEnvironment& env, const BoundsTolerance& tolerance) { RenderWith(testP, env, tolerance, CaseParameters("Defaults Test")); { // CPU renderer with default line width of 0 does not show antialiasing // for stroked primitives, so we make a new reference with a non-trivial // stroke width to demonstrate the differences RenderEnvironment aa_env = RenderEnvironment::MakeN32(env.provider()); // Tweak the bounds tolerance for the displacement of 1/10 of a pixel const BoundsTolerance aa_tolerance = tolerance.addBoundsPadding(1, 1); auto sk_aa_setup = [=](SkCanvas* cv, SkPaint& p, bool is_aa) { cv->translate(0.1, 0.1); p.setAntiAlias(is_aa); p.setStrokeWidth(5.0); }; auto dl_aa_setup = [=](DlCanvas* cv, DlPaint& p, bool is_aa) { cv->Translate(0.1, 0.1); p.setAntiAlias(is_aa); p.setStrokeWidth(5.0); }; aa_env.init_ref( [=](SkCanvas* cv, SkPaint& p) { sk_aa_setup(cv, p, false); }, testP.sk_renderer(), [=](DlCanvas* cv, DlPaint& p) { dl_aa_setup(cv, p, false); }, testP.dl_renderer()); quickCompareToReference(aa_env, "AntiAlias"); RenderWith( testP, aa_env, aa_tolerance, CaseParameters( "AntiAlias == True", [=](SkCanvas* cv, SkPaint& p) { sk_aa_setup(cv, p, true); }, [=](DlCanvas* cv, DlPaint& p) { dl_aa_setup(cv, p, true); })); RenderWith( testP, aa_env, aa_tolerance, CaseParameters( "AntiAlias == False", [=](SkCanvas* cv, SkPaint& p) { sk_aa_setup(cv, p, false); }, [=](DlCanvas* cv, DlPaint& p) { dl_aa_setup(cv, p, false); })); } { // The CPU renderer does not always dither for solid colors and we // need to use a non-default color (default is black) on an opaque // surface, so we use a shader instead of a color. Also, thin stroked // primitives (mainly drawLine and drawPoints) do not show much // dithering so we use a non-trivial stroke width as well. RenderEnvironment dither_env = RenderEnvironment::Make565(env.provider()); if (!dither_env.valid()) { // Currently only happens on Metal backend static std::set<std::string> warnings_sent; std::string name = dither_env.backend_name(); if (warnings_sent.find(name) == warnings_sent.end()) { warnings_sent.insert(name); FML_LOG(INFO) << "Skipping Dithering tests on " << name; } } else { DlColor dither_bg = DlColor::kBlack(); SkSetup sk_dither_setup = [=](SkCanvas*, SkPaint& p) { p.setShader(kTestSkImageColorSource); p.setAlpha(0xf0); p.setStrokeWidth(5.0); }; DlSetup dl_dither_setup = [=](DlCanvas*, DlPaint& p) { p.setColorSource(&kTestDlImageColorSource); p.setAlpha(0xf0); p.setStrokeWidth(5.0); }; dither_env.init_ref(sk_dither_setup, testP.sk_renderer(), dl_dither_setup, testP.dl_renderer(), dither_bg); quickCompareToReference(dither_env, "dither"); RenderWith(testP, dither_env, tolerance, CaseParameters( "Dither == True", [=](SkCanvas* cv, SkPaint& p) { sk_dither_setup(cv, p); p.setDither(true); }, [=](DlCanvas* cv, DlPaint& p) { dl_dither_setup(cv, p); p.setDither(true); }) .with_bg(dither_bg)); RenderWith(testP, dither_env, tolerance, CaseParameters( "Dither = False", [=](SkCanvas* cv, SkPaint& p) { sk_dither_setup(cv, p); p.setDither(false); }, [=](DlCanvas* cv, DlPaint& p) { dl_dither_setup(cv, p); p.setDither(false); }) .with_bg(dither_bg)); } } RenderWith( testP, env, tolerance, CaseParameters( "Color == Blue", [=](SkCanvas*, SkPaint& p) { p.setColor(SK_ColorBLUE); }, [=](DlCanvas*, DlPaint& p) { p.setColor(DlColor::kBlue()); })); RenderWith( testP, env, tolerance, CaseParameters( "Color == Green", [=](SkCanvas*, SkPaint& p) { p.setColor(SK_ColorGREEN); }, [=](DlCanvas*, DlPaint& p) { p.setColor(DlColor::kGreen()); })); RenderWithStrokes(testP, env, tolerance); { // half opaque cyan DlColor blendable_color = DlColor::kCyan().withAlpha(0x7f); DlColor bg = DlColor::kWhite(); RenderWith(testP, env, tolerance, CaseParameters( "Blend == SrcIn", [=](SkCanvas*, SkPaint& p) { p.setBlendMode(SkBlendMode::kSrcIn); p.setColor(blendable_color); }, [=](DlCanvas*, DlPaint& p) { p.setBlendMode(DlBlendMode::kSrcIn); p.setColor(blendable_color); }) .with_bg(bg)); RenderWith(testP, env, tolerance, CaseParameters( "Blend == DstIn", [=](SkCanvas*, SkPaint& p) { p.setBlendMode(SkBlendMode::kDstIn); p.setColor(blendable_color); }, [=](DlCanvas*, DlPaint& p) { p.setBlendMode(DlBlendMode::kDstIn); p.setColor(blendable_color); }) .with_bg(bg)); } { // Being able to see a blur requires some non-default attributes, // like a non-trivial stroke width and a shader rather than a color // (for drawPaint) so we create a new environment for these tests. RenderEnvironment blur_env = RenderEnvironment::MakeN32(env.provider()); SkSetup sk_blur_setup = [=](SkCanvas*, SkPaint& p) { p.setShader(kTestSkImageColorSource); p.setStrokeWidth(5.0); }; DlSetup dl_blur_setup = [=](DlCanvas*, DlPaint& p) { p.setColorSource(&kTestDlImageColorSource); p.setStrokeWidth(5.0); }; blur_env.init_ref(sk_blur_setup, testP.sk_renderer(), // dl_blur_setup, testP.dl_renderer()); quickCompareToReference(blur_env, "blur"); DlBlurImageFilter dl_filter_decal_5(5.0, 5.0, DlTileMode::kDecal); auto sk_filter_decal_5 = SkImageFilters::Blur(5.0, 5.0, SkTileMode::kDecal, nullptr); BoundsTolerance blur_5_tolerance = tolerance.addBoundsPadding(4, 4); { RenderWith(testP, blur_env, blur_5_tolerance, CaseParameters( "ImageFilter == Decal Blur 5", [=](SkCanvas* cv, SkPaint& p) { sk_blur_setup(cv, p); p.setImageFilter(sk_filter_decal_5); }, [=](DlCanvas* cv, DlPaint& p) { dl_blur_setup(cv, p); p.setImageFilter(&dl_filter_decal_5); })); } DlBlurImageFilter dl_filter_clamp_5(5.0, 5.0, DlTileMode::kClamp); auto sk_filter_clamp_5 = SkImageFilters::Blur(5.0, 5.0, SkTileMode::kClamp, nullptr); { RenderWith(testP, blur_env, blur_5_tolerance, CaseParameters( "ImageFilter == Clamp Blur 5", [=](SkCanvas* cv, SkPaint& p) { sk_blur_setup(cv, p); p.setImageFilter(sk_filter_clamp_5); }, [=](DlCanvas* cv, DlPaint& p) { dl_blur_setup(cv, p); p.setImageFilter(&dl_filter_clamp_5); })); } } { // Being able to see a dilate requires some non-default attributes, // like a non-trivial stroke width and a shader rather than a color // (for drawPaint) so we create a new environment for these tests. RenderEnvironment dilate_env = RenderEnvironment::MakeN32(env.provider()); SkSetup sk_dilate_setup = [=](SkCanvas*, SkPaint& p) { p.setShader(kTestSkImageColorSource); p.setStrokeWidth(5.0); }; DlSetup dl_dilate_setup = [=](DlCanvas*, DlPaint& p) { p.setColorSource(&kTestDlImageColorSource); p.setStrokeWidth(5.0); }; dilate_env.init_ref(sk_dilate_setup, testP.sk_renderer(), // dl_dilate_setup, testP.dl_renderer()); quickCompareToReference(dilate_env, "dilate"); DlDilateImageFilter dl_dilate_filter_5(5.0, 5.0); auto sk_dilate_filter_5 = SkImageFilters::Dilate(5.0, 5.0, nullptr); RenderWith(testP, dilate_env, tolerance, CaseParameters( "ImageFilter == Dilate 5", [=](SkCanvas* cv, SkPaint& p) { sk_dilate_setup(cv, p); p.setImageFilter(sk_dilate_filter_5); }, [=](DlCanvas* cv, DlPaint& p) { dl_dilate_setup(cv, p); p.setImageFilter(&dl_dilate_filter_5); })); } { // Being able to see an erode requires some non-default attributes, // like a non-trivial stroke width and a shader rather than a color // (for drawPaint) so we create a new environment for these tests. RenderEnvironment erode_env = RenderEnvironment::MakeN32(env.provider()); SkSetup sk_erode_setup = [=](SkCanvas*, SkPaint& p) { p.setShader(kTestSkImageColorSource); p.setStrokeWidth(6.0); }; DlSetup dl_erode_setup = [=](DlCanvas*, DlPaint& p) { p.setColorSource(&kTestDlImageColorSource); p.setStrokeWidth(6.0); }; erode_env.init_ref(sk_erode_setup, testP.sk_renderer(), // dl_erode_setup, testP.dl_renderer()); quickCompareToReference(erode_env, "erode"); // do not erode too much, because some tests assert there are enough // pixels that are changed. DlErodeImageFilter dl_erode_filter_1(1.0, 1.0); auto sk_erode_filter_1 = SkImageFilters::Erode(1.0, 1.0, nullptr); RenderWith(testP, erode_env, tolerance, CaseParameters( "ImageFilter == Erode 1", [=](SkCanvas* cv, SkPaint& p) { sk_erode_setup(cv, p); p.setImageFilter(sk_erode_filter_1); }, [=](DlCanvas* cv, DlPaint& p) { dl_erode_setup(cv, p); p.setImageFilter(&dl_erode_filter_1); })); } { // clang-format off constexpr float rotate_color_matrix[20] = { 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, }; constexpr float invert_color_matrix[20] = { -1.0, 0, 0, 1.0, 0, 0, -1.0, 0, 1.0, 0, 0, 0, -1.0, 1.0, 0, 1.0, 1.0, 1.0, 1.0, 0, }; // clang-format on DlMatrixColorFilter dl_color_filter(rotate_color_matrix); auto sk_color_filter = SkColorFilters::Matrix(rotate_color_matrix); { DlColor bg = DlColor::kWhite(); RenderWith(testP, env, tolerance, CaseParameters( "ColorFilter == RotateRGB", [=](SkCanvas*, SkPaint& p) { p.setColor(DlColor::kYellow()); p.setColorFilter(sk_color_filter); }, [=](DlCanvas*, DlPaint& p) { p.setColor(DlColor::kYellow()); p.setColorFilter(&dl_color_filter); }) .with_bg(bg)); } { DlColor bg = DlColor::kWhite(); RenderWith( testP, env, tolerance, CaseParameters( "ColorFilter == Invert", [=](SkCanvas*, SkPaint& p) { p.setColor(DlColor::kYellow()); p.setColorFilter(SkColorFilters::Matrix(invert_color_matrix)); }, [=](DlCanvas*, DlPaint& p) { p.setColor(DlColor::kYellow()); p.setInvertColors(true); }) .with_bg(bg)); } } { const DlBlurMaskFilter dl_mask_filter(DlBlurStyle::kNormal, 5.0); auto sk_mask_filter = SkMaskFilter::MakeBlur(kNormal_SkBlurStyle, 5.0); BoundsTolerance blur_5_tolerance = tolerance.addBoundsPadding(4, 4); { // Stroked primitives need some non-trivial stroke size to be blurred RenderWith(testP, env, blur_5_tolerance, CaseParameters( "MaskFilter == Blur 5", [=](SkCanvas*, SkPaint& p) { p.setStrokeWidth(5.0); p.setMaskFilter(sk_mask_filter); }, [=](DlCanvas*, DlPaint& p) { p.setStrokeWidth(5.0); p.setMaskFilter(&dl_mask_filter); })); } } { SkPoint end_points[] = { SkPoint::Make(kRenderBounds.fLeft, kRenderBounds.fTop), SkPoint::Make(kRenderBounds.fRight, kRenderBounds.fBottom), }; DlColor dl_colors[] = { DlColor::kGreen(), DlColor::kYellow().withAlpha(0x7f), DlColor::kBlue(), }; SkColor sk_colors[] = { SK_ColorGREEN, SkColorSetA(SK_ColorYELLOW, 0x7f), SK_ColorBLUE, }; float stops[] = { 0.0, 0.5, 1.0, }; auto dl_gradient = DlColorSource::MakeLinear(end_points[0], end_points[1], 3, dl_colors, stops, DlTileMode::kMirror); auto sk_gradient = SkGradientShader::MakeLinear( end_points, sk_colors, stops, 3, SkTileMode::kMirror, 0, nullptr); { RenderWith( testP, env, tolerance, CaseParameters( "LinearGradient GYB", [=](SkCanvas*, SkPaint& p) { p.setShader(sk_gradient); }, [=](DlCanvas*, DlPaint& p) { p.setColorSource(dl_gradient); })); } } } static void RenderWithStrokes(const TestParameters& testP, const RenderEnvironment& env, const BoundsTolerance& tolerance_in) { // The test cases were generated with geometry that will try to fill // out the various miter limits used for testing, but they can be off // by a couple of pixels so we will relax bounds testing for strokes by // a couple of pixels. BoundsTolerance tolerance = tolerance_in.addBoundsPadding(2, 2); RenderWith(testP, env, tolerance, CaseParameters( "Fill", [=](SkCanvas*, SkPaint& p) { // p.setStyle(SkPaint::kFill_Style); }, [=](DlCanvas*, DlPaint& p) { // p.setDrawStyle(DlDrawStyle::kFill); })); // Skia on HW produces a strong miter consistent with width=1.0 // for any width less than a pixel, but the bounds computations of // both DL and SkPicture do not account for this. We will get // OOB pixel errors for the highly mitered drawPath geometry if // we don't set stroke width to 1.0 for that test on HW. // See https://bugs.chromium.org/p/skia/issues/detail?id=14046 bool no_hairlines = testP.is_draw_path() && env.provider()->backend_type() != BackendType::kSoftware_Backend; RenderWith(testP, env, tolerance, CaseParameters( "Stroke + defaults", [=](SkCanvas*, SkPaint& p) { // if (no_hairlines) { p.setStrokeWidth(1.0); } p.setStyle(SkPaint::kStroke_Style); }, [=](DlCanvas*, DlPaint& p) { // if (no_hairlines) { p.setStrokeWidth(1.0); } p.setDrawStyle(DlDrawStyle::kStroke); })); RenderWith(testP, env, tolerance, CaseParameters( "Fill + unnecessary StrokeWidth 10", [=](SkCanvas*, SkPaint& p) { p.setStyle(SkPaint::kFill_Style); p.setStrokeWidth(10.0); }, [=](DlCanvas*, DlPaint& p) { p.setDrawStyle(DlDrawStyle::kFill); p.setStrokeWidth(10.0); })); RenderEnvironment stroke_base_env = RenderEnvironment::MakeN32(env.provider()); SkSetup sk_stroke_setup = [=](SkCanvas*, SkPaint& p) { p.setStyle(SkPaint::kStroke_Style); p.setStrokeWidth(5.0); }; DlSetup dl_stroke_setup = [=](DlCanvas*, DlPaint& p) { p.setDrawStyle(DlDrawStyle::kStroke); p.setStrokeWidth(5.0); }; stroke_base_env.init_ref(sk_stroke_setup, testP.sk_renderer(), dl_stroke_setup, testP.dl_renderer()); quickCompareToReference(stroke_base_env, "stroke"); RenderWith(testP, stroke_base_env, tolerance, CaseParameters( "Stroke Width 10", [=](SkCanvas*, SkPaint& p) { p.setStyle(SkPaint::kStroke_Style); p.setStrokeWidth(10.0); }, [=](DlCanvas*, DlPaint& p) { p.setDrawStyle(DlDrawStyle::kStroke); p.setStrokeWidth(10.0); })); RenderWith(testP, stroke_base_env, tolerance, CaseParameters( "Stroke Width 5", [=](SkCanvas*, SkPaint& p) { p.setStyle(SkPaint::kStroke_Style); p.setStrokeWidth(5.0); }, [=](DlCanvas*, DlPaint& p) { p.setDrawStyle(DlDrawStyle::kStroke); p.setStrokeWidth(5.0); })); RenderWith(testP, stroke_base_env, tolerance, CaseParameters( "Stroke Width 5, Square Cap", [=](SkCanvas*, SkPaint& p) { p.setStyle(SkPaint::kStroke_Style); p.setStrokeWidth(5.0); p.setStrokeCap(SkPaint::kSquare_Cap); }, [=](DlCanvas*, DlPaint& p) { p.setDrawStyle(DlDrawStyle::kStroke); p.setStrokeWidth(5.0); p.setStrokeCap(DlStrokeCap::kSquare); })); RenderWith(testP, stroke_base_env, tolerance, CaseParameters( "Stroke Width 5, Round Cap", [=](SkCanvas*, SkPaint& p) { p.setStyle(SkPaint::kStroke_Style); p.setStrokeWidth(5.0); p.setStrokeCap(SkPaint::kRound_Cap); }, [=](DlCanvas*, DlPaint& p) { p.setDrawStyle(DlDrawStyle::kStroke); p.setStrokeWidth(5.0); p.setStrokeCap(DlStrokeCap::kRound); })); RenderWith(testP, stroke_base_env, tolerance, CaseParameters( "Stroke Width 5, Bevel Join", [=](SkCanvas*, SkPaint& p) { p.setStyle(SkPaint::kStroke_Style); p.setStrokeWidth(5.0); p.setStrokeJoin(SkPaint::kBevel_Join); }, [=](DlCanvas*, DlPaint& p) { p.setDrawStyle(DlDrawStyle::kStroke); p.setStrokeWidth(5.0); p.setStrokeJoin(DlStrokeJoin::kBevel); })); RenderWith(testP, stroke_base_env, tolerance, CaseParameters( "Stroke Width 5, Round Join", [=](SkCanvas*, SkPaint& p) { p.setStyle(SkPaint::kStroke_Style); p.setStrokeWidth(5.0); p.setStrokeJoin(SkPaint::kRound_Join); }, [=](DlCanvas*, DlPaint& p) { p.setDrawStyle(DlDrawStyle::kStroke); p.setStrokeWidth(5.0); p.setStrokeJoin(DlStrokeJoin::kRound); })); RenderWith(testP, stroke_base_env, tolerance, CaseParameters( "Stroke Width 5, Miter 10", [=](SkCanvas*, SkPaint& p) { p.setStyle(SkPaint::kStroke_Style); p.setStrokeWidth(5.0); p.setStrokeMiter(10.0); p.setStrokeJoin(SkPaint::kMiter_Join); }, [=](DlCanvas*, DlPaint& p) { p.setDrawStyle(DlDrawStyle::kStroke); p.setStrokeWidth(5.0); p.setStrokeMiter(10.0); p.setStrokeJoin(DlStrokeJoin::kMiter); })); RenderWith(testP, stroke_base_env, tolerance, CaseParameters( "Stroke Width 5, Miter 0", [=](SkCanvas*, SkPaint& p) { p.setStyle(SkPaint::kStroke_Style); p.setStrokeWidth(5.0); p.setStrokeMiter(0.0); p.setStrokeJoin(SkPaint::kMiter_Join); }, [=](DlCanvas*, DlPaint& p) { p.setDrawStyle(DlDrawStyle::kStroke); p.setStrokeWidth(5.0); p.setStrokeMiter(0.0); p.setStrokeJoin(DlStrokeJoin::kMiter); })); { const SkScalar test_dashes_1[] = {29.0, 2.0}; const SkScalar test_dashes_2[] = {17.0, 1.5}; auto dl_dash_effect = DlDashPathEffect::Make(test_dashes_1, 2, 0.0f); auto sk_dash_effect = SkDashPathEffect::Make(test_dashes_1, 2, 0.0f); { RenderWith(testP, stroke_base_env, tolerance, CaseParameters( "PathEffect without forced stroking == Dash-29-2", [=](SkCanvas*, SkPaint& p) { // Provide some non-trivial stroke size to get dashed p.setStrokeWidth(5.0); p.setPathEffect(sk_dash_effect); }, [=](DlCanvas*, DlPaint& p) { // Provide some non-trivial stroke size to get dashed p.setStrokeWidth(5.0); p.setPathEffect(dl_dash_effect); })); } { RenderWith(testP, stroke_base_env, tolerance, CaseParameters( "PathEffect == Dash-29-2", [=](SkCanvas*, SkPaint& p) { // Need stroke style to see dashing properly p.setStyle(SkPaint::kStroke_Style); // Provide some non-trivial stroke size to get dashed p.setStrokeWidth(5.0); p.setPathEffect(sk_dash_effect); }, [=](DlCanvas*, DlPaint& p) { // Need stroke style to see dashing properly p.setDrawStyle(DlDrawStyle::kStroke); // Provide some non-trivial stroke size to get dashed p.setStrokeWidth(5.0); p.setPathEffect(dl_dash_effect); })); } dl_dash_effect = DlDashPathEffect::Make(test_dashes_2, 2, 0.0f); sk_dash_effect = SkDashPathEffect::Make(test_dashes_2, 2, 0.0f); { RenderWith(testP, stroke_base_env, tolerance, CaseParameters( "PathEffect == Dash-17-1.5", [=](SkCanvas*, SkPaint& p) { // Need stroke style to see dashing properly p.setStyle(SkPaint::kStroke_Style); // Provide some non-trivial stroke size to get dashed p.setStrokeWidth(5.0); p.setPathEffect(sk_dash_effect); }, [=](DlCanvas*, DlPaint& p) { // Need stroke style to see dashing properly p.setDrawStyle(DlDrawStyle::kStroke); // Provide some non-trivial stroke size to get dashed p.setStrokeWidth(5.0); p.setPathEffect(dl_dash_effect); })); } } } static void RenderWithTransforms(const TestParameters& testP, const RenderEnvironment& env, const BoundsTolerance& tolerance) { // If the rendering method does not fill the corners of the original // bounds, then the estimate under rotation or skewing will be off // so we scale the padding by about 5% to compensate. BoundsTolerance skewed_tolerance = tolerance.mulScale(1.05, 1.05); RenderWith(testP, env, tolerance, CaseParameters( "Translate 5, 10", // [=](SkCanvas* c, SkPaint&) { c->translate(5, 10); }, [=](DlCanvas* c, DlPaint&) { c->Translate(5, 10); })); RenderWith(testP, env, tolerance, CaseParameters( "Scale +5%", // [=](SkCanvas* c, SkPaint&) { c->scale(1.05, 1.05); }, [=](DlCanvas* c, DlPaint&) { c->Scale(1.05, 1.05); })); RenderWith(testP, env, skewed_tolerance, CaseParameters( "Rotate 5 degrees", // [=](SkCanvas* c, SkPaint&) { c->rotate(5); }, [=](DlCanvas* c, DlPaint&) { c->Rotate(5); })); RenderWith(testP, env, skewed_tolerance, CaseParameters( "Skew 5%", // [=](SkCanvas* c, SkPaint&) { c->skew(0.05, 0.05); }, [=](DlCanvas* c, DlPaint&) { c->Skew(0.05, 0.05); })); { // This rather odd transform can cause slight differences in // computing in-bounds samples depending on which base rendering // routine Skia uses. Making sure our matrix values are powers // of 2 reduces, but does not eliminate, these slight differences // in calculation when we are comparing rendering with an alpha // to rendering opaque colors in the group opacity tests, for // example. SkScalar tweak = 1.0 / 16.0; SkMatrix tx = SkMatrix::MakeAll(1.0 + tweak, tweak, 5, // tweak, 1.0 + tweak, 10, // 0, 0, 1); RenderWith(testP, env, skewed_tolerance, CaseParameters( "Transform 2D Affine", [=](SkCanvas* c, SkPaint&) { c->concat(tx); }, [=](DlCanvas* c, DlPaint&) { c->Transform(tx); })); } { SkM44 m44 = SkM44(1, 0, 0, kRenderCenterX, // 0, 1, 0, kRenderCenterY, // 0, 0, 1, 0, // 0, 0, .001, 1); m44.preConcat( SkM44::Rotate({1, 0, 0}, math::kPi / 60)); // 3 degrees around X m44.preConcat( SkM44::Rotate({0, 1, 0}, math::kPi / 45)); // 4 degrees around Y m44.preTranslate(-kRenderCenterX, -kRenderCenterY); RenderWith(testP, env, skewed_tolerance, CaseParameters( "Transform Full Perspective", [=](SkCanvas* c, SkPaint&) { c->concat(m44); }, [=](DlCanvas* c, DlPaint&) { c->Transform(m44); })); } } static void RenderWithClips(const TestParameters& testP, const RenderEnvironment& env, const BoundsTolerance& diff_tolerance) { // We used to use an inset of 15.5 pixels here, but since Skia's rounding // behavior at the center of pixels does not match between HW and SW, we // ended up with some clips including different pixels between the two // destinations and this interacted poorly with the carefully chosen // geometry in some of the tests which was designed to have just the // right features fully filling the clips based on the SW rounding. By // moving to a 15.4 inset, the edge of the clip is never on the "rounding // edge" of a pixel. SkRect r_clip = kRenderBounds.makeInset(15.4, 15.4); BoundsTolerance intersect_tolerance = diff_tolerance.clip(r_clip); intersect_tolerance = intersect_tolerance.addPostClipPadding(1, 1); RenderWith(testP, env, intersect_tolerance, CaseParameters( "Hard ClipRect inset by 15.4", [=](SkCanvas* c, SkPaint&) { c->clipRect(r_clip, SkClipOp::kIntersect, false); }, [=](DlCanvas* c, DlPaint&) { c->ClipRect(r_clip, ClipOp::kIntersect, false); })); RenderWith(testP, env, intersect_tolerance, CaseParameters( "AntiAlias ClipRect inset by 15.4", [=](SkCanvas* c, SkPaint&) { c->clipRect(r_clip, SkClipOp::kIntersect, true); }, [=](DlCanvas* c, DlPaint&) { c->ClipRect(r_clip, ClipOp::kIntersect, true); })); RenderWith(testP, env, diff_tolerance, CaseParameters( "Hard ClipRect Diff, inset by 15.4", [=](SkCanvas* c, SkPaint&) { c->clipRect(r_clip, SkClipOp::kDifference, false); }, [=](DlCanvas* c, DlPaint&) { c->ClipRect(r_clip, ClipOp::kDifference, false); }) .with_diff_clip()); // This test RR clip used to use very small radii, but due to // optimizations in the HW rrect rasterization, this caused small // bulges in the corners of the RRect which were interpreted as // "clip overruns" by the clip OOB pixel testing code. Using less // abusively small radii fixes the problem. SkRRect rr_clip = SkRRect::MakeRectXY(r_clip, 9, 9); RenderWith(testP, env, intersect_tolerance, CaseParameters( "Hard ClipRRect with radius of 15.4", [=](SkCanvas* c, SkPaint&) { c->clipRRect(rr_clip, SkClipOp::kIntersect, false); }, [=](DlCanvas* c, DlPaint&) { c->ClipRRect(rr_clip, ClipOp::kIntersect, false); })); RenderWith(testP, env, intersect_tolerance, CaseParameters( "AntiAlias ClipRRect with radius of 15.4", [=](SkCanvas* c, SkPaint&) { c->clipRRect(rr_clip, SkClipOp::kIntersect, true); }, [=](DlCanvas* c, DlPaint&) { c->ClipRRect(rr_clip, ClipOp::kIntersect, true); })); RenderWith(testP, env, diff_tolerance, CaseParameters( "Hard ClipRRect Diff, with radius of 15.4", [=](SkCanvas* c, SkPaint&) { c->clipRRect(rr_clip, SkClipOp::kDifference, false); }, [=](DlCanvas* c, DlPaint&) { c->ClipRRect(rr_clip, ClipOp::kDifference, false); }) .with_diff_clip()); SkPath path_clip = SkPath(); path_clip.setFillType(SkPathFillType::kEvenOdd); path_clip.addRect(r_clip); path_clip.addCircle(kRenderCenterX, kRenderCenterY, 1.0); RenderWith(testP, env, intersect_tolerance, CaseParameters( "Hard ClipPath inset by 15.4", [=](SkCanvas* c, SkPaint&) { c->clipPath(path_clip, SkClipOp::kIntersect, false); }, [=](DlCanvas* c, DlPaint&) { c->ClipPath(path_clip, ClipOp::kIntersect, false); })); RenderWith(testP, env, intersect_tolerance, CaseParameters( "AntiAlias ClipPath inset by 15.4", [=](SkCanvas* c, SkPaint&) { c->clipPath(path_clip, SkClipOp::kIntersect, true); }, [=](DlCanvas* c, DlPaint&) { c->ClipPath(path_clip, ClipOp::kIntersect, true); })); RenderWith(testP, env, diff_tolerance, CaseParameters( "Hard ClipPath Diff, inset by 15.4", [=](SkCanvas* c, SkPaint&) { c->clipPath(path_clip, SkClipOp::kDifference, false); }, [=](DlCanvas* c, DlPaint&) { c->ClipPath(path_clip, ClipOp::kDifference, false); }) .with_diff_clip()); } static void RenderWith(const TestParameters& testP, const RenderEnvironment& env, const BoundsTolerance& tolerance_in, const CaseParameters& caseP) { const std::string info = env.backend_name() + ": " + caseP.info(); const DlColor bg = caseP.bg(); RenderJobInfo base_info = { .bg = bg, }; // sk_result is a direct rendering via SkCanvas to SkSurface // DisplayList mechanisms are not involved in this operation // SkPaint sk_paint; SkJobRenderer sk_job(caseP.sk_setup(), // testP.sk_renderer(), // caseP.sk_restore()); auto sk_result = env.getResult(base_info, sk_job); DlJobRenderer dl_job(caseP.dl_setup(), // testP.dl_renderer(), // caseP.dl_restore()); auto dl_result = env.getResult(base_info, dl_job); EXPECT_EQ(sk_job.setup_matrix(), dl_job.setup_matrix()); EXPECT_EQ(sk_job.setup_clip_bounds(), dl_job.setup_clip_bounds()); ASSERT_EQ(sk_result->width(), kTestWidth) << info; ASSERT_EQ(sk_result->height(), kTestHeight) << info; ASSERT_EQ(dl_result->width(), kTestWidth) << info; ASSERT_EQ(dl_result->height(), kTestHeight) << info; const BoundsTolerance tolerance = testP.adjust(tolerance_in, dl_job.setup_paint(), dl_job.setup_matrix()); const sk_sp<SkPicture> sk_picture = sk_job.MakePicture(base_info); const sk_sp<DisplayList> display_list = dl_job.MakeDisplayList(base_info); SkRect sk_bounds = sk_picture->cullRect(); checkPixels(sk_result.get(), sk_bounds, info + " (Skia reference)", bg); if (testP.should_match(env, caseP, dl_job.setup_paint(), dl_job)) { quickCompareToReference(env.ref_sk_result(), sk_result.get(), true, info + " (attribute has no effect)"); } else { quickCompareToReference(env.ref_sk_result(), sk_result.get(), false, info + " (attribute affects rendering)"); } quickCompareToReference(sk_result.get(), dl_result.get(), true, info + " (DlCanvas output matches SkCanvas)"); { SkRect dl_bounds = display_list->bounds(); if (!sk_bounds.roundOut().contains(dl_bounds)) { FML_LOG(ERROR) << "For " << info; FML_LOG(ERROR) << "sk ref: " // << sk_bounds.fLeft << ", " << sk_bounds.fTop << " => " << sk_bounds.fRight << ", " << sk_bounds.fBottom; FML_LOG(ERROR) << "dl: " // << dl_bounds.fLeft << ", " << dl_bounds.fTop << " => " << dl_bounds.fRight << ", " << dl_bounds.fBottom; if (!dl_bounds.contains(sk_bounds)) { FML_LOG(ERROR) << "DisplayList bounds are too small!"; } if (!sk_bounds.roundOut().contains(dl_bounds.roundOut())) { FML_LOG(ERROR) << "###### DisplayList bounds larger than reference!"; } } // This EXPECT sometimes triggers, but when it triggers and I examine // the ref_bounds, they are always unnecessarily large and since the // pixel OOB tests in the compare method do not trigger, we will trust // the DL bounds. // EXPECT_TRUE(dl_bounds.contains(ref_bounds)) << info; // When we are drawing a DisplayList, the display_list built above // will contain just a single drawDisplayList call plus the case // attribute. The sk_picture will, however, contain a list of all // of the embedded calls in the display list and so the op counts // will not be equal between the two. if (!testP.is_draw_display_list()) { EXPECT_EQ(static_cast<int>(display_list->op_count()), sk_picture->approximateOpCount()) << info; EXPECT_EQ(static_cast<int>(display_list->op_count()), sk_picture->approximateOpCount()) << info; } DisplayListJobRenderer dl_builder_job(display_list); auto dl_builder_result = env.getResult(base_info, dl_builder_job); if (caseP.fuzzy_compare_components()) { compareToReference( dl_builder_result.get(), dl_result.get(), info + " (DlCanvas DL output close to Builder Dl output)", &dl_bounds, &tolerance, bg, true); } else { quickCompareToReference( dl_builder_result.get(), dl_result.get(), true, info + " (DlCanvas DL output matches Builder Dl output)"); } compareToReference(dl_result.get(), sk_result.get(), info + " (DisplayList built directly -> surface)", &dl_bounds, &tolerance, bg, caseP.fuzzy_compare_components()); if (display_list->can_apply_group_opacity()) { checkGroupOpacity(env, display_list, dl_result.get(), info + " with Group Opacity", bg); } } { // This sequence renders the SkCanvas calls to an SkPictureRecorder and // renders the DisplayList calls to a DisplayListBuilder and then // renders both back under a transform (scale(2x)) to see if their // rendering is affected differently by a change of matrix between // recording time and rendering time. const int test_width_2 = kTestWidth * 2; const int test_height_2 = kTestHeight * 2; const SkScalar test_scale = 2.0; SkPictureJobRenderer sk_job_x2(sk_picture); RenderJobInfo info_2x = { .width = test_width_2, .height = test_height_2, .bg = bg, .scale = test_scale, }; auto ref_x2_result = env.getResult(info_2x, sk_job_x2); ASSERT_EQ(ref_x2_result->width(), test_width_2) << info; ASSERT_EQ(ref_x2_result->height(), test_height_2) << info; DisplayListJobRenderer dl_job_x2(display_list); auto test_x2_result = env.getResult(info_2x, dl_job_x2); compareToReference(test_x2_result.get(), ref_x2_result.get(), info + " (Both rendered scaled 2x)", nullptr, nullptr, bg, caseP.fuzzy_compare_components(), // test_width_2, test_height_2, false); } } static bool fuzzyCompare(uint32_t pixel_a, uint32_t pixel_b, int fudge) { for (int i = 0; i < 32; i += 8) { int comp_a = (pixel_a >> i) & 0xff; int comp_b = (pixel_b >> i) & 0xff; if (std::abs(comp_a - comp_b) > fudge) { return false; } } return true; } static int groupOpacityFudgeFactor(const RenderEnvironment& env) { if (env.format() == PixelFormat::k565_PixelFormat) { return 9; } if (env.provider()->backend_type() == BackendType::kOpenGL_Backend) { // OpenGL gets a little fuzzy at times. Still, "within 5" (aka +/-4) // for byte samples is not bad, though the other backends give +/-1 return 5; } return 2; } static void checkGroupOpacity(const RenderEnvironment& env, const sk_sp<DisplayList>& display_list, const RenderResult* ref_result, const std::string& info, DlColor bg) { SkScalar opacity = 128.0 / 255.0; DisplayListJobRenderer opacity_job(display_list); RenderJobInfo opacity_info = { .bg = bg, .opacity = opacity, }; auto group_opacity_result = env.getResult(opacity_info, opacity_job); ASSERT_EQ(group_opacity_result->width(), kTestWidth) << info; ASSERT_EQ(group_opacity_result->height(), kTestHeight) << info; ASSERT_EQ(ref_result->width(), kTestWidth) << info; ASSERT_EQ(ref_result->height(), kTestHeight) << info; int pixels_touched = 0; int pixels_different = 0; int max_diff = 0; // We need to allow some slight differences per component due to the // fact that rearranging discrete calculations can compound round off // errors. Off-by-2 is enough for 8 bit components, but for the 565 // tests we allow at least 9 which is the maximum distance between // samples when converted to 8 bits. (You might think it would be a // max step of 8 converting 5 bits to 8 bits, but it is really // converting 31 steps to 255 steps with an average step size of // 8.23 - 24 of the steps are by 8, but 7 of them are by 9.) int fudge = groupOpacityFudgeFactor(env); for (int y = 0; y < kTestHeight; y++) { const uint32_t* ref_row = ref_result->addr32(0, y); const uint32_t* test_row = group_opacity_result->addr32(0, y); for (int x = 0; x < kTestWidth; x++) { uint32_t ref_pixel = ref_row[x]; uint32_t test_pixel = test_row[x]; if (ref_pixel != bg.argb || test_pixel != bg.argb) { pixels_touched++; for (int i = 0; i < 32; i += 8) { int ref_comp = (ref_pixel >> i) & 0xff; int bg_comp = (bg.argb >> i) & 0xff; SkScalar faded_comp = bg_comp + (ref_comp - bg_comp) * opacity; int test_comp = (test_pixel >> i) & 0xff; if (std::abs(faded_comp - test_comp) > fudge) { int diff = std::abs(faded_comp - test_comp); if (max_diff < diff) { max_diff = diff; } pixels_different++; break; } } } } } ASSERT_GT(pixels_touched, 20) << info; if (pixels_different > 1) { FML_LOG(ERROR) << "max diff == " << max_diff << " for " << info; } ASSERT_LE(pixels_different, 1) << info; } static void checkPixels(const RenderResult* ref_result, const SkRect ref_bounds, const std::string& info, const DlColor bg) { uint32_t untouched = bg.premultipliedArgb(); int pixels_touched = 0; int pixels_oob = 0; SkIRect i_bounds = ref_bounds.roundOut(); for (int y = 0; y < kTestHeight; y++) { const uint32_t* ref_row = ref_result->addr32(0, y); for (int x = 0; x < kTestWidth; x++) { if (ref_row[x] != untouched) { pixels_touched++; if (!i_bounds.contains(x, y)) { pixels_oob++; } } } } ASSERT_EQ(pixels_oob, 0) << info; ASSERT_GT(pixels_touched, 0) << info; } static int countModifiedTransparentPixels(const RenderResult* ref_result, const RenderResult* test_result) { int count = 0; for (int y = 0; y < kTestHeight; y++) { const uint32_t* ref_row = ref_result->addr32(0, y); const uint32_t* test_row = test_result->addr32(0, y); for (int x = 0; x < kTestWidth; x++) { if (ref_row[x] != test_row[x]) { if (ref_row[x] == 0) { count++; } } } } return count; } static void quickCompareToReference(const RenderEnvironment& env, const std::string& info) { quickCompareToReference(env.ref_sk_result(), env.ref_dl_result(), true, info + " reference rendering"); } static void quickCompareToReference(const RenderResult* ref_result, const RenderResult* test_result, bool should_match, const std::string& info) { int w = test_result->width(); int h = test_result->height(); ASSERT_EQ(w, ref_result->width()) << info; ASSERT_EQ(h, ref_result->height()) << info; int pixels_different = 0; for (int y = 0; y < h; y++) { const uint32_t* ref_row = ref_result->addr32(0, y); const uint32_t* test_row = test_result->addr32(0, y); for (int x = 0; x < w; x++) { if (ref_row[x] != test_row[x]) { if (should_match && pixels_different < 5) { FML_LOG(ERROR) << std::hex << ref_row[x] << " != " << test_row[x]; } pixels_different++; } } } if (should_match) { ASSERT_EQ(pixels_different, 0) << info; } else { ASSERT_NE(pixels_different, 0) << info; } } static void compareToReference(const RenderResult* test_result, const RenderResult* ref_result, const std::string& info, SkRect* bounds, const BoundsTolerance* tolerance, const DlColor bg, bool fuzzyCompares = false, int width = kTestWidth, int height = kTestHeight, bool printMismatches = false) { uint32_t untouched = bg.premultipliedArgb(); ASSERT_EQ(test_result->width(), width) << info; ASSERT_EQ(test_result->height(), height) << info; SkIRect i_bounds = bounds ? bounds->roundOut() : SkIRect::MakeWH(width, height); int pixels_different = 0; int pixels_oob = 0; int min_x = width; int min_y = height; int max_x = 0; int max_y = 0; for (int y = 0; y < height; y++) { const uint32_t* ref_row = ref_result->addr32(0, y); const uint32_t* test_row = test_result->addr32(0, y); for (int x = 0; x < width; x++) { if (bounds && test_row[x] != untouched) { if (min_x > x) { min_x = x; } if (min_y > y) { min_y = y; } if (max_x <= x) { max_x = x + 1; } if (max_y <= y) { max_y = y + 1; } if (!i_bounds.contains(x, y)) { pixels_oob++; } } bool match = fuzzyCompares ? fuzzyCompare(test_row[x], ref_row[x], 1) : test_row[x] == ref_row[x]; if (!match) { if (printMismatches && pixels_different < 5) { FML_LOG(ERROR) << "pix[" << x << ", " << y << "] mismatch: " << std::hex << test_row[x] << "(test) != (ref)" << ref_row[x] << std::dec; } pixels_different++; } } } if (pixels_oob > 0) { FML_LOG(ERROR) << "pix bounds[" // << min_x << ", " << min_y << " => " << max_x << ", " << max_y << "]"; FML_LOG(ERROR) << "dl_bounds[" // << bounds->fLeft << ", " << bounds->fTop // << " => " // << bounds->fRight << ", " << bounds->fBottom // << "]"; } else if (bounds) { showBoundsOverflow(info, i_bounds, tolerance, min_x, min_y, max_x, max_y); } ASSERT_EQ(pixels_oob, 0) << info; ASSERT_EQ(pixels_different, 0) << info; } static void showBoundsOverflow(const std::string& info, SkIRect& bounds, const BoundsTolerance* tolerance, int pixLeft, int pixTop, int pixRight, int pixBottom) { int pad_left = std::max(0, pixLeft - bounds.fLeft); int pad_top = std::max(0, pixTop - bounds.fTop); int pad_right = std::max(0, bounds.fRight - pixRight); int pad_bottom = std::max(0, bounds.fBottom - pixBottom); SkIRect pix_bounds = SkIRect::MakeLTRB(pixLeft, pixTop, pixRight, pixBottom); SkISize pix_size = pix_bounds.size(); int pix_width = pix_size.width(); int pix_height = pix_size.height(); int worst_pad_x = std::max(pad_left, pad_right); int worst_pad_y = std::max(pad_top, pad_bottom); if (tolerance->overflows(pix_bounds, worst_pad_x, worst_pad_y)) { FML_LOG(ERROR) << "Computed bounds for " << info; FML_LOG(ERROR) << "pix bounds[" // << pixLeft << ", " << pixTop << " => " // << pixRight << ", " << pixBottom // << "]"; FML_LOG(ERROR) << "dl_bounds[" // << bounds.fLeft << ", " << bounds.fTop // << " => " // << bounds.fRight << ", " << bounds.fBottom // << "]"; FML_LOG(ERROR) << "Bounds overly conservative by up to " // << worst_pad_x << ", " << worst_pad_y // << " (" << (worst_pad_x * 100.0 / pix_width) // << "%, " << (worst_pad_y * 100.0 / pix_height) << "%)"; int pix_area = pix_size.area(); int dl_area = bounds.width() * bounds.height(); FML_LOG(ERROR) << "Total overflow area: " << (dl_area - pix_area) // << " (+" << (dl_area * 100.0 / pix_area - 100.0) // << "% larger)"; FML_LOG(ERROR); } } static const sk_sp<SkImage> kTestImage; static const sk_sp<SkImage> makeTestImage() { sk_sp<SkSurface> surface = SkSurfaces::Raster( SkImageInfo::MakeN32Premul(kRenderWidth, kRenderHeight)); SkCanvas* canvas = surface->getCanvas(); SkPaint p0, p1; p0.setStyle(SkPaint::kFill_Style); p0.setColor(SkColorSetARGB(0xff, 0x00, 0xfe, 0x00)); // off-green p1.setStyle(SkPaint::kFill_Style); p1.setColor(SK_ColorBLUE); // Some pixels need some transparency for DstIn testing p1.setAlpha(128); int cbdim = 5; for (int y = 0; y < kRenderHeight; y += cbdim) { for (int x = 0; x < kRenderWidth; x += cbdim) { SkPaint& cellp = ((x + y) & 1) == 0 ? p0 : p1; canvas->drawRect(SkRect::MakeXYWH(x, y, cbdim, cbdim), cellp); } } return surface->makeImageSnapshot(); } static const DlImageColorSource kTestDlImageColorSource; static const sk_sp<SkShader> kTestSkImageColorSource; static sk_sp<SkTextBlob> MakeTextBlob(const std::string& string, SkScalar font_height) { SkFont font(SkTypeface::MakeFromName("ahem", SkFontStyle::Normal()), font_height); return SkTextBlob::MakeFromText(string.c_str(), string.size(), font, SkTextEncoding::kUTF8); } }; std::vector<std::unique_ptr<DlSurfaceProvider>> CanvasCompareTester::kTestProviders; BoundsTolerance CanvasCompareTester::DefaultTolerance = BoundsTolerance().addAbsolutePadding(1, 1); const sk_sp<SkImage> CanvasCompareTester::kTestImage = makeTestImage(); const DlImageColorSource CanvasCompareTester::kTestDlImageColorSource( DlImage::Make(kTestImage), DlTileMode::kRepeat, DlTileMode::kRepeat, DlImageSampling::kLinear); const sk_sp<SkShader> CanvasCompareTester::kTestSkImageColorSource = kTestImage->makeShader(SkTileMode::kRepeat, SkTileMode::kRepeat, SkImageSampling::kLinear); // Eventually this bare bones testing::Test fixture will subsume the // CanvasCompareTester and the TestParameters could then become just // configuration calls made upon the fixture. template <typename BaseT> class DisplayListCanvasTestBase : public BaseT, protected DisplayListOpFlags { public: DisplayListCanvasTestBase() = default; static bool StartsWith(std::string str, std::string prefix) { if (prefix.length() > str.length()) { return false; } for (size_t i = 0; i < prefix.length(); i++) { if (str[i] != prefix[i]) { return false; } } return true; } static void AddProvider(BackendType type, const std::string& name) { auto provider = DlSurfaceProvider::Create(type); if (provider == nullptr) { FML_LOG(ERROR) << "provider " << name << " not supported (ignoring)"; return; } provider->InitializeSurface(kTestWidth, kTestHeight, PixelFormat::kN32Premul_PixelFormat); CanvasCompareTester::kTestProviders.push_back(std::move(provider)); } static void SetUpTestSuite() { bool do_software = true; bool do_opengl = false; bool do_metal = false; std::vector<std::string> args = ::testing::internal::GetArgvs(); for (auto p_arg = std::next(args.begin()); p_arg != args.end(); p_arg++) { std::string arg = *p_arg; bool enable = true; if (StartsWith(arg, "--no")) { enable = false; arg = "-" + arg.substr(4); } if (arg == "--enable-software") { do_software = enable; } else if (arg == "--enable-opengl" || arg == "--enable-gl") { do_opengl = enable; } else if (arg == "--enable-metal") { do_metal = enable; } } if (do_software) { AddProvider(BackendType::kSoftware_Backend, "Software"); } if (do_opengl) { AddProvider(BackendType::kOpenGL_Backend, "OpenGL"); } if (do_metal) { AddProvider(BackendType::kMetal_Backend, "Metal"); } std::string providers = ""; auto begin = CanvasCompareTester::kTestProviders.cbegin(); auto end = CanvasCompareTester::kTestProviders.cend(); while (begin != end) { providers += " " + (*begin++)->backend_name(); } FML_LOG(INFO) << "Running tests on [" << providers << " ]"; } static void TearDownTestSuite() { // Deleting these provider objects allows Metal to clean up its // resources before the exit handler reports them as leaks. CanvasCompareTester::kTestProviders.clear(); } private: FML_DISALLOW_COPY_AND_ASSIGN(DisplayListCanvasTestBase); }; using DisplayListCanvas = DisplayListCanvasTestBase<::testing::Test>; TEST_F(DisplayListCanvas, DrawPaint) { CanvasCompareTester::RenderAll( // TestParameters( [=](SkCanvas* canvas, const SkPaint& paint) { // canvas->drawPaint(paint); }, [=](DlCanvas* canvas, const DlPaint& paint) { // canvas->DrawPaint(paint); }, kDrawPaintFlags)); } TEST_F(DisplayListCanvas, DrawOpaqueColor) { // We use a non-opaque color to avoid obliterating any backdrop filter output CanvasCompareTester::RenderAll( // TestParameters( [=](SkCanvas* canvas, const SkPaint& paint) { // DrawColor is not tested against attributes because it is supposed // to ignore them. So, if the paint has an alpha, it is because we // are doing a saveLayer+backdrop test and we need to not flood over // the backdrop output with a solid color. So, we perform an alpha // drawColor for that case only. SkColor color = SkColorSetA(SK_ColorMAGENTA, paint.getAlpha()); canvas->drawColor(color); }, [=](DlCanvas* canvas, const DlPaint& paint) { // DrawColor is not tested against attributes because it is supposed // to ignore them. So, if the paint has an alpha, it is because we // are doing a saveLayer+backdrop test and we need to not flood over // the backdrop output with a solid color. So, we transfer the alpha // from the paint for that case only. canvas->DrawColor(DlColor::kMagenta().withAlpha(paint.getAlpha())); }, kDrawColorFlags)); } TEST_F(DisplayListCanvas, DrawAlphaColor) { // We use a non-opaque color to avoid obliterating any backdrop filter output CanvasCompareTester::RenderAll( // TestParameters( [=](SkCanvas* canvas, const SkPaint& paint) { canvas->drawColor(0x7FFF00FF); }, [=](DlCanvas* canvas, const DlPaint& paint) { canvas->DrawColor(DlColor::kMagenta().withAlpha(0x7f)); }, kDrawColorFlags)); } TEST_F(DisplayListCanvas, DrawDiagonalLines) { SkPoint p1 = SkPoint::Make(kRenderLeft, kRenderTop); SkPoint p2 = SkPoint::Make(kRenderRight, kRenderBottom); SkPoint p3 = SkPoint::Make(kRenderLeft, kRenderBottom); SkPoint p4 = SkPoint::Make(kRenderRight, kRenderTop); // Adding some edge center to edge center diagonals to better fill // out the RRect Clip so bounds checking sees less empty bounds space. SkPoint p5 = SkPoint::Make(kRenderCenterX, kRenderTop); SkPoint p6 = SkPoint::Make(kRenderRight, kRenderCenterY); SkPoint p7 = SkPoint::Make(kRenderLeft, kRenderCenterY); SkPoint p8 = SkPoint::Make(kRenderCenterX, kRenderBottom); CanvasCompareTester::RenderAll( // TestParameters( [=](SkCanvas* canvas, const SkPaint& paint) { // // Skia requires kStroke style on horizontal and vertical // lines to get the bounds correct. // See https://bugs.chromium.org/p/skia/issues/detail?id=12446 SkPaint p = paint; p.setStyle(SkPaint::kStroke_Style); canvas->drawLine(p1, p2, p); canvas->drawLine(p3, p4, p); canvas->drawLine(p5, p6, p); canvas->drawLine(p7, p8, p); }, [=](DlCanvas* canvas, const DlPaint& paint) { // canvas->DrawLine(p1, p2, paint); canvas->DrawLine(p3, p4, paint); canvas->DrawLine(p5, p6, paint); canvas->DrawLine(p7, p8, paint); }, kDrawLineFlags) .set_draw_line()); } TEST_F(DisplayListCanvas, DrawHorizontalLine) { SkPoint p1 = SkPoint::Make(kRenderLeft, kRenderCenterY); SkPoint p2 = SkPoint::Make(kRenderRight, kRenderCenterY); CanvasCompareTester::RenderAll( // TestParameters( [=](SkCanvas* canvas, const SkPaint& paint) { // // Skia requires kStroke style on horizontal and vertical // lines to get the bounds correct. // See https://bugs.chromium.org/p/skia/issues/detail?id=12446 SkPaint p = paint; p.setStyle(SkPaint::kStroke_Style); canvas->drawLine(p1, p2, p); }, [=](DlCanvas* canvas, const DlPaint& paint) { // canvas->DrawLine(p1, p2, paint); }, kDrawHVLineFlags) .set_draw_line() .set_horizontal_line()); } TEST_F(DisplayListCanvas, DrawVerticalLine) { SkPoint p1 = SkPoint::Make(kRenderCenterX, kRenderTop); SkPoint p2 = SkPoint::Make(kRenderCenterY, kRenderBottom); CanvasCompareTester::RenderAll( // TestParameters( [=](SkCanvas* canvas, const SkPaint& paint) { // // Skia requires kStroke style on horizontal and vertical // lines to get the bounds correct. // See https://bugs.chromium.org/p/skia/issues/detail?id=12446 SkPaint p = paint; p.setStyle(SkPaint::kStroke_Style); canvas->drawLine(p1, p2, p); }, [=](DlCanvas* canvas, const DlPaint& paint) { // canvas->DrawLine(p1, p2, paint); }, kDrawHVLineFlags) .set_draw_line() .set_vertical_line()); } TEST_F(DisplayListCanvas, DrawRect) { // Bounds are offset by 0.5 pixels to induce AA CanvasCompareTester::RenderAll( // TestParameters( [=](SkCanvas* canvas, const SkPaint& paint) { // canvas->drawRect(kRenderBounds.makeOffset(0.5, 0.5), paint); }, [=](DlCanvas* canvas, const DlPaint& paint) { // canvas->DrawRect(kRenderBounds.makeOffset(0.5, 0.5), paint); }, kDrawRectFlags)); } TEST_F(DisplayListCanvas, DrawOval) { SkRect rect = kRenderBounds.makeInset(0, 10); CanvasCompareTester::RenderAll( // TestParameters( [=](SkCanvas* canvas, const SkPaint& paint) { // canvas->drawOval(rect, paint); }, [=](DlCanvas* canvas, const DlPaint& paint) { // canvas->DrawOval(rect, paint); }, kDrawOvalFlags)); } TEST_F(DisplayListCanvas, DrawCircle) { CanvasCompareTester::RenderAll( // TestParameters( [=](SkCanvas* canvas, const SkPaint& paint) { // canvas->drawCircle(kTestCenter, kRenderRadius, paint); }, [=](DlCanvas* canvas, const DlPaint& paint) { // canvas->DrawCircle(kTestCenter, kRenderRadius, paint); }, kDrawCircleFlags)); } TEST_F(DisplayListCanvas, DrawRRect) { SkRRect rrect = SkRRect::MakeRectXY(kRenderBounds, kRenderCornerRadius, kRenderCornerRadius); CanvasCompareTester::RenderAll( // TestParameters( [=](SkCanvas* canvas, const SkPaint& paint) { // canvas->drawRRect(rrect, paint); }, [=](DlCanvas* canvas, const DlPaint& paint) { // canvas->DrawRRect(rrect, paint); }, kDrawRRectFlags)); } TEST_F(DisplayListCanvas, DrawDRRect) { SkRRect outer = SkRRect::MakeRectXY(kRenderBounds, kRenderCornerRadius, kRenderCornerRadius); SkRect inner_bounds = kRenderBounds.makeInset(30.0, 30.0); SkRRect inner = SkRRect::MakeRectXY(inner_bounds, kRenderCornerRadius, kRenderCornerRadius); CanvasCompareTester::RenderAll( // TestParameters( [=](SkCanvas* canvas, const SkPaint& paint) { // canvas->drawDRRect(outer, inner, paint); }, [=](DlCanvas* canvas, const DlPaint& paint) { // canvas->DrawDRRect(outer, inner, paint); }, kDrawDRRectFlags)); } TEST_F(DisplayListCanvas, DrawPath) { SkPath path; // unclosed lines to show some caps path.moveTo(kRenderLeft + 15, kRenderTop + 15); path.lineTo(kRenderRight - 15, kRenderBottom - 15); path.moveTo(kRenderLeft + 15, kRenderBottom - 15); path.lineTo(kRenderRight - 15, kRenderTop + 15); path.addRect(kRenderBounds); // miter diamonds horizontally and vertically to show miters path.moveTo(kVerticalMiterDiamondPoints[0]); for (int i = 1; i < kVerticalMiterDiamondPointCount; i++) { path.lineTo(kVerticalMiterDiamondPoints[i]); } path.close(); path.moveTo(kHorizontalMiterDiamondPoints[0]); for (int i = 1; i < kHorizontalMiterDiamondPointCount; i++) { path.lineTo(kHorizontalMiterDiamondPoints[i]); } path.close(); CanvasCompareTester::RenderAll( // TestParameters( [=](SkCanvas* canvas, const SkPaint& paint) { // canvas->drawPath(path, paint); }, [=](DlCanvas* canvas, const DlPaint& paint) { // canvas->DrawPath(path, paint); }, kDrawPathFlags) .set_draw_path()); } TEST_F(DisplayListCanvas, DrawArc) { CanvasCompareTester::RenderAll( // TestParameters( [=](SkCanvas* canvas, const SkPaint& paint) { // canvas->drawArc(kRenderBounds, 60, 330, false, paint); }, [=](DlCanvas* canvas, const DlPaint& paint) { // canvas->DrawArc(kRenderBounds, 60, 330, false, paint); }, kDrawArcNoCenterFlags)); } TEST_F(DisplayListCanvas, DrawArcCenter) { // Center arcs that inscribe nearly a whole circle except for a small // arc extent gap have 2 angles that may appear or disappear at the // various miter limits tested (0, 4, and 10). // The center angle here is 12 degrees which shows a miter // at limit=10, but not 0 or 4. // The arcs at the corners where it turns in towards the // center show miters at 4 and 10, but not 0. // Limit == 0, neither corner does a miter // Limit == 4, only the edge "turn-in" corners miter // Limit == 10, edge and center corners all miter CanvasCompareTester::RenderAll( // TestParameters( [=](SkCanvas* canvas, const SkPaint& paint) { // canvas->drawArc(kRenderBounds, 60, 360 - 12, true, paint); }, [=](DlCanvas* canvas, const DlPaint& paint) { // canvas->DrawArc(kRenderBounds, 60, 360 - 12, true, paint); }, kDrawArcWithCenterFlags) .set_draw_arc_center()); } TEST_F(DisplayListCanvas, DrawPointsAsPoints) { // The +/- 16 points are designed to fall just inside the clips // that are tested against so we avoid lots of undrawn pixels // in the accumulated bounds. const SkScalar x0 = kRenderLeft; const SkScalar x1 = kRenderLeft + 16; const SkScalar x2 = (kRenderLeft + kRenderCenterX) * 0.5; const SkScalar x3 = kRenderCenterX + 0.1; const SkScalar x4 = (kRenderRight + kRenderCenterX) * 0.5; const SkScalar x5 = kRenderRight - 16; const SkScalar x6 = kRenderRight; const SkScalar y0 = kRenderTop; const SkScalar y1 = kRenderTop + 16; const SkScalar y2 = (kRenderTop + kRenderCenterY) * 0.5; const SkScalar y3 = kRenderCenterY + 0.1; const SkScalar y4 = (kRenderBottom + kRenderCenterY) * 0.5; const SkScalar y5 = kRenderBottom - 16; const SkScalar y6 = kRenderBottom; // clang-format off const SkPoint points[] = { {x0, y0}, {x1, y0}, {x2, y0}, {x3, y0}, {x4, y0}, {x5, y0}, {x6, y0}, {x0, y1}, {x1, y1}, {x2, y1}, {x3, y1}, {x4, y1}, {x5, y1}, {x6, y1}, {x0, y2}, {x1, y2}, {x2, y2}, {x3, y2}, {x4, y2}, {x5, y2}, {x6, y2}, {x0, y3}, {x1, y3}, {x2, y3}, {x3, y3}, {x4, y3}, {x5, y3}, {x6, y3}, {x0, y4}, {x1, y4}, {x2, y4}, {x3, y4}, {x4, y4}, {x5, y4}, {x6, y4}, {x0, y5}, {x1, y5}, {x2, y5}, {x3, y5}, {x4, y5}, {x5, y5}, {x6, y5}, {x0, y6}, {x1, y6}, {x2, y6}, {x3, y6}, {x4, y6}, {x5, y6}, {x6, y6}, }; // clang-format on const int count = sizeof(points) / sizeof(points[0]); CanvasCompareTester::RenderAll( // TestParameters( [=](SkCanvas* canvas, const SkPaint& paint) { // // Skia requires kStroke style on horizontal and vertical // lines to get the bounds correct. // See https://bugs.chromium.org/p/skia/issues/detail?id=12446 SkPaint p = paint; p.setStyle(SkPaint::kStroke_Style); canvas->drawPoints(SkCanvas::kPoints_PointMode, count, points, p); }, [=](DlCanvas* canvas, const DlPaint& paint) { // canvas->DrawPoints(PointMode::kPoints, count, points, paint); }, kDrawPointsAsPointsFlags) .set_draw_line() .set_ignores_dashes()); } TEST_F(DisplayListCanvas, DrawPointsAsLines) { const SkScalar x0 = kRenderLeft + 1; const SkScalar x1 = kRenderLeft + 16; const SkScalar x2 = kRenderRight - 16; const SkScalar x3 = kRenderRight - 1; const SkScalar y0 = kRenderTop; const SkScalar y1 = kRenderTop + 16; const SkScalar y2 = kRenderBottom - 16; const SkScalar y3 = kRenderBottom; // clang-format off const SkPoint points[] = { // Outer box {x0, y0}, {x3, y0}, {x3, y0}, {x3, y3}, {x3, y3}, {x0, y3}, {x0, y3}, {x0, y0}, // Diagonals {x0, y0}, {x3, y3}, {x3, y0}, {x0, y3}, // Inner box {x1, y1}, {x2, y1}, {x2, y1}, {x2, y2}, {x2, y2}, {x1, y2}, {x1, y2}, {x1, y1}, }; // clang-format on const int count = sizeof(points) / sizeof(points[0]); ASSERT_TRUE((count & 1) == 0); CanvasCompareTester::RenderAll( // TestParameters( [=](SkCanvas* canvas, const SkPaint& paint) { // // Skia requires kStroke style on horizontal and vertical // lines to get the bounds correct. // See https://bugs.chromium.org/p/skia/issues/detail?id=12446 SkPaint p = paint; p.setStyle(SkPaint::kStroke_Style); canvas->drawPoints(SkCanvas::kLines_PointMode, count, points, p); }, [=](DlCanvas* canvas, const DlPaint& paint) { // canvas->DrawPoints(PointMode::kLines, count, points, paint); }, kDrawPointsAsLinesFlags)); } TEST_F(DisplayListCanvas, DrawPointsAsPolygon) { const SkPoint points1[] = { // RenderBounds box with a diamond SkPoint::Make(kRenderLeft, kRenderTop), SkPoint::Make(kRenderRight, kRenderTop), SkPoint::Make(kRenderRight, kRenderBottom), SkPoint::Make(kRenderLeft, kRenderBottom), SkPoint::Make(kRenderLeft, kRenderTop), SkPoint::Make(kRenderCenterX, kRenderTop), SkPoint::Make(kRenderRight, kRenderCenterY), SkPoint::Make(kRenderCenterX, kRenderBottom), SkPoint::Make(kRenderLeft, kRenderCenterY), }; const int count1 = sizeof(points1) / sizeof(points1[0]); CanvasCompareTester::RenderAll( // TestParameters( [=](SkCanvas* canvas, const SkPaint& paint) { // // Skia requires kStroke style on horizontal and vertical // lines to get the bounds correct. // See https://bugs.chromium.org/p/skia/issues/detail?id=12446 SkPaint p = paint; p.setStyle(SkPaint::kStroke_Style); canvas->drawPoints(SkCanvas::kPolygon_PointMode, count1, points1, p); }, [=](DlCanvas* canvas, const DlPaint& paint) { // canvas->DrawPoints(PointMode::kPolygon, count1, points1, paint); }, kDrawPointsAsPolygonFlags)); } TEST_F(DisplayListCanvas, DrawVerticesWithColors) { // Cover as many sides of the box with only 6 vertices: // +----------+ // |xxxxxxxxxx| // | xxxxxx| // | xxx| // |xxx | // |xxxxxx | // |xxxxxxxxxx| // +----------| const SkPoint pts[6] = { // Upper-Right corner, full top, half right coverage SkPoint::Make(kRenderLeft, kRenderTop), SkPoint::Make(kRenderRight, kRenderTop), SkPoint::Make(kRenderRight, kRenderCenterY), // Lower-Left corner, full bottom, half left coverage SkPoint::Make(kRenderLeft, kRenderBottom), SkPoint::Make(kRenderLeft, kRenderCenterY), SkPoint::Make(kRenderRight, kRenderBottom), }; const DlColor dl_colors[6] = { DlColor::kRed(), DlColor::kBlue(), DlColor::kGreen(), DlColor::kCyan(), DlColor::kYellow(), DlColor::kMagenta(), }; const SkColor sk_colors[6] = { SK_ColorRED, SK_ColorBLUE, SK_ColorGREEN, SK_ColorCYAN, SK_ColorYELLOW, SK_ColorMAGENTA, }; const std::shared_ptr<DlVertices> dl_vertices = DlVertices::Make(DlVertexMode::kTriangles, 6, pts, nullptr, dl_colors); const auto sk_vertices = SkVertices::MakeCopy(SkVertices::VertexMode::kTriangles_VertexMode, 6, pts, nullptr, sk_colors); CanvasCompareTester::RenderAll( // TestParameters( [=](SkCanvas* canvas, const SkPaint& paint) { // canvas->drawVertices(sk_vertices, SkBlendMode::kSrcOver, paint); }, [=](DlCanvas* canvas, const DlPaint& paint) { // canvas->DrawVertices(dl_vertices, DlBlendMode::kSrcOver, paint); }, kDrawVerticesFlags)); } TEST_F(DisplayListCanvas, DrawVerticesWithImage) { // Cover as many sides of the box with only 6 vertices: // +----------+ // |xxxxxxxxxx| // | xxxxxx| // | xxx| // |xxx | // |xxxxxx | // |xxxxxxxxxx| // +----------| const SkPoint pts[6] = { // Upper-Right corner, full top, half right coverage SkPoint::Make(kRenderLeft, kRenderTop), SkPoint::Make(kRenderRight, kRenderTop), SkPoint::Make(kRenderRight, kRenderCenterY), // Lower-Left corner, full bottom, half left coverage SkPoint::Make(kRenderLeft, kRenderBottom), SkPoint::Make(kRenderLeft, kRenderCenterY), SkPoint::Make(kRenderRight, kRenderBottom), }; const SkPoint tex[6] = { SkPoint::Make(kRenderWidth / 2.0, 0), SkPoint::Make(0, kRenderHeight), SkPoint::Make(kRenderWidth, kRenderHeight), SkPoint::Make(kRenderWidth / 2, kRenderHeight), SkPoint::Make(0, 0), SkPoint::Make(kRenderWidth, 0), }; const std::shared_ptr<DlVertices> dl_vertices = DlVertices::Make(DlVertexMode::kTriangles, 6, pts, tex, nullptr); const auto sk_vertices = SkVertices::MakeCopy( SkVertices::VertexMode::kTriangles_VertexMode, 6, pts, tex, nullptr); CanvasCompareTester::RenderAll( // TestParameters( [=](SkCanvas* canvas, const SkPaint& paint) { // SkPaint v_paint = paint; if (v_paint.getShader() == nullptr) { v_paint.setShader(CanvasCompareTester::kTestSkImageColorSource); } canvas->drawVertices(sk_vertices, SkBlendMode::kSrcOver, v_paint); }, [=](DlCanvas* canvas, const DlPaint& paint) { // DlPaint v_paint = paint; if (v_paint.getColorSource() == nullptr) { v_paint.setColorSource( &CanvasCompareTester::kTestDlImageColorSource); } canvas->DrawVertices(dl_vertices, DlBlendMode::kSrcOver, v_paint); }, kDrawVerticesFlags)); } TEST_F(DisplayListCanvas, DrawImageNearest) { CanvasCompareTester::RenderAll( // TestParameters( [=](SkCanvas* canvas, const SkPaint& paint) { // canvas->drawImage(CanvasCompareTester::kTestImage, // kRenderLeft, kRenderTop, SkImageSampling::kNearestNeighbor, &paint); }, [=](DlCanvas* canvas, const DlPaint& paint) { canvas->DrawImage(DlImage::Make(CanvasCompareTester::kTestImage), SkPoint::Make(kRenderLeft, kRenderTop), DlImageSampling::kNearestNeighbor, &paint); }, kDrawImageWithPaintFlags)); } TEST_F(DisplayListCanvas, DrawImageNearestNoPaint) { CanvasCompareTester::RenderAll( // TestParameters( [=](SkCanvas* canvas, const SkPaint& paint) { // canvas->drawImage(CanvasCompareTester::kTestImage, // kRenderLeft, kRenderTop, SkImageSampling::kNearestNeighbor, nullptr); }, [=](DlCanvas* canvas, const DlPaint& paint) { canvas->DrawImage(DlImage::Make(CanvasCompareTester::kTestImage), SkPoint::Make(kRenderLeft, kRenderTop), DlImageSampling::kNearestNeighbor, nullptr); }, kDrawImageFlags)); } TEST_F(DisplayListCanvas, DrawImageLinear) { CanvasCompareTester::RenderAll( // TestParameters( [=](SkCanvas* canvas, const SkPaint& paint) { // canvas->drawImage(CanvasCompareTester::kTestImage, // kRenderLeft, kRenderTop, SkImageSampling::kLinear, &paint); }, [=](DlCanvas* canvas, const DlPaint& paint) { canvas->DrawImage(DlImage::Make(CanvasCompareTester::kTestImage), SkPoint::Make(kRenderLeft, kRenderTop), DlImageSampling::kLinear, &paint); }, kDrawImageWithPaintFlags)); } TEST_F(DisplayListCanvas, DrawImageRectNearest) { SkRect src = SkRect::MakeIWH(kRenderWidth, kRenderHeight).makeInset(5, 5); SkRect dst = kRenderBounds.makeInset(10.5, 10.5); CanvasCompareTester::RenderAll( // TestParameters( [=](SkCanvas* canvas, const SkPaint& paint) { // canvas->drawImageRect(CanvasCompareTester::kTestImage, src, dst, SkImageSampling::kNearestNeighbor, &paint, SkCanvas::kFast_SrcRectConstraint); }, [=](DlCanvas* canvas, const DlPaint& paint) { // canvas->DrawImageRect( DlImage::Make(CanvasCompareTester::kTestImage), src, dst, DlImageSampling::kNearestNeighbor, &paint, DlCanvas::SrcRectConstraint::kFast); }, kDrawImageRectWithPaintFlags)); } TEST_F(DisplayListCanvas, DrawImageRectNearestNoPaint) { SkRect src = SkRect::MakeIWH(kRenderWidth, kRenderHeight).makeInset(5, 5); SkRect dst = kRenderBounds.makeInset(10.5, 10.5); CanvasCompareTester::RenderAll( // TestParameters( [=](SkCanvas* canvas, const SkPaint& paint) { // canvas->drawImageRect(CanvasCompareTester::kTestImage, src, dst, SkImageSampling::kNearestNeighbor, nullptr, SkCanvas::kFast_SrcRectConstraint); }, [=](DlCanvas* canvas, const DlPaint& paint) { // canvas->DrawImageRect( DlImage::Make(CanvasCompareTester::kTestImage), src, dst, DlImageSampling::kNearestNeighbor, nullptr, DlCanvas::SrcRectConstraint::kFast); }, kDrawImageRectFlags)); } TEST_F(DisplayListCanvas, DrawImageRectLinear) { SkRect src = SkRect::MakeIWH(kRenderWidth, kRenderHeight).makeInset(5, 5); SkRect dst = kRenderBounds.makeInset(10.5, 10.5); CanvasCompareTester::RenderAll( // TestParameters( [=](SkCanvas* canvas, const SkPaint& paint) { // canvas->drawImageRect(CanvasCompareTester::kTestImage, src, dst, SkImageSampling::kLinear, &paint, SkCanvas::kFast_SrcRectConstraint); }, [=](DlCanvas* canvas, const DlPaint& paint) { // canvas->DrawImageRect( DlImage::Make(CanvasCompareTester::kTestImage), src, dst, DlImageSampling::kLinear, &paint, DlCanvas::SrcRectConstraint::kFast); }, kDrawImageRectWithPaintFlags)); } TEST_F(DisplayListCanvas, DrawImageNineNearest) { SkIRect src = SkIRect::MakeWH(kRenderWidth, kRenderHeight).makeInset(25, 25); SkRect dst = kRenderBounds.makeInset(10.5, 10.5); sk_sp<SkImage> image = CanvasCompareTester::kTestImage; CanvasCompareTester::RenderAll( // TestParameters( [=](SkCanvas* canvas, const SkPaint& paint) { canvas->drawImageNine(image.get(), src, dst, SkFilterMode::kNearest, &paint); }, [=](DlCanvas* canvas, const DlPaint& paint) { canvas->DrawImageNine(DlImage::Make(image), src, dst, DlFilterMode::kNearest, &paint); }, kDrawImageNineWithPaintFlags)); } TEST_F(DisplayListCanvas, DrawImageNineNearestNoPaint) { SkIRect src = SkIRect::MakeWH(kRenderWidth, kRenderHeight).makeInset(25, 25); SkRect dst = kRenderBounds.makeInset(10.5, 10.5); sk_sp<SkImage> image = CanvasCompareTester::kTestImage; CanvasCompareTester::RenderAll( // TestParameters( [=](SkCanvas* canvas, const SkPaint& paint) { canvas->drawImageNine(image.get(), src, dst, SkFilterMode::kNearest, nullptr); }, [=](DlCanvas* canvas, const DlPaint& paint) { canvas->DrawImageNine(DlImage::Make(image), src, dst, DlFilterMode::kNearest, nullptr); }, kDrawImageNineFlags)); } TEST_F(DisplayListCanvas, DrawImageNineLinear) { SkIRect src = SkIRect::MakeWH(kRenderWidth, kRenderHeight).makeInset(25, 25); SkRect dst = kRenderBounds.makeInset(10.5, 10.5); sk_sp<SkImage> image = CanvasCompareTester::kTestImage; CanvasCompareTester::RenderAll( // TestParameters( [=](SkCanvas* canvas, const SkPaint& paint) { canvas->drawImageNine(image.get(), src, dst, SkFilterMode::kLinear, &paint); }, [=](DlCanvas* canvas, const DlPaint& paint) { canvas->DrawImageNine(DlImage::Make(image), src, dst, DlFilterMode::kLinear, &paint); }, kDrawImageNineWithPaintFlags)); } TEST_F(DisplayListCanvas, DrawAtlasNearest) { const SkRSXform xform[] = { // clang-format off { 1.2f, 0.0f, kRenderLeft, kRenderTop}, { 0.0f, 1.2f, kRenderRight, kRenderTop}, {-1.2f, 0.0f, kRenderRight, kRenderBottom}, { 0.0f, -1.2f, kRenderLeft, kRenderBottom}, // clang-format on }; const SkRect tex[] = { // clang-format off {0, 0, kRenderHalfWidth, kRenderHalfHeight}, {kRenderHalfWidth, 0, kRenderWidth, kRenderHalfHeight}, {kRenderHalfWidth, kRenderHalfHeight, kRenderWidth, kRenderHeight}, {0, kRenderHalfHeight, kRenderHalfWidth, kRenderHeight}, // clang-format on }; const SkColor sk_colors[] = { SK_ColorBLUE, SK_ColorGREEN, SK_ColorYELLOW, SK_ColorMAGENTA, }; const DlColor dl_colors[] = { DlColor::kBlue(), DlColor::kGreen(), DlColor::kYellow(), DlColor::kMagenta(), }; const sk_sp<SkImage> image = CanvasCompareTester::kTestImage; const DlImageSampling dl_sampling = DlImageSampling::kNearestNeighbor; const SkSamplingOptions sk_sampling = SkImageSampling::kNearestNeighbor; CanvasCompareTester::RenderAll( // TestParameters( [=](SkCanvas* canvas, const SkPaint& paint) { canvas->drawAtlas(image.get(), xform, tex, sk_colors, 4, SkBlendMode::kSrcOver, sk_sampling, nullptr, &paint); }, [=](DlCanvas* canvas, const DlPaint& paint) { canvas->DrawAtlas(DlImage::Make(image), xform, tex, dl_colors, 4, DlBlendMode::kSrcOver, dl_sampling, nullptr, &paint); }, kDrawAtlasWithPaintFlags)); } TEST_F(DisplayListCanvas, DrawAtlasNearestNoPaint) { const SkRSXform xform[] = { // clang-format off { 1.2f, 0.0f, kRenderLeft, kRenderTop}, { 0.0f, 1.2f, kRenderRight, kRenderTop}, {-1.2f, 0.0f, kRenderRight, kRenderBottom}, { 0.0f, -1.2f, kRenderLeft, kRenderBottom}, // clang-format on }; const SkRect tex[] = { // clang-format off {0, 0, kRenderHalfWidth, kRenderHalfHeight}, {kRenderHalfWidth, 0, kRenderWidth, kRenderHalfHeight}, {kRenderHalfWidth, kRenderHalfHeight, kRenderWidth, kRenderHeight}, {0, kRenderHalfHeight, kRenderHalfWidth, kRenderHeight}, // clang-format on }; const SkColor sk_colors[] = { SK_ColorBLUE, SK_ColorGREEN, SK_ColorYELLOW, SK_ColorMAGENTA, }; const DlColor dl_colors[] = { DlColor::kBlue(), DlColor::kGreen(), DlColor::kYellow(), DlColor::kMagenta(), }; const sk_sp<SkImage> image = CanvasCompareTester::kTestImage; const DlImageSampling dl_sampling = DlImageSampling::kNearestNeighbor; const SkSamplingOptions sk_sampling = SkImageSampling::kNearestNeighbor; CanvasCompareTester::RenderAll( // TestParameters( [=](SkCanvas* canvas, const SkPaint& paint) { canvas->drawAtlas(image.get(), xform, tex, sk_colors, 4, SkBlendMode::kSrcOver, sk_sampling, // nullptr, nullptr); }, [=](DlCanvas* canvas, const DlPaint& paint) { canvas->DrawAtlas(DlImage::Make(image), xform, tex, dl_colors, 4, DlBlendMode::kSrcOver, dl_sampling, nullptr, nullptr); }, kDrawAtlasFlags)); } TEST_F(DisplayListCanvas, DrawAtlasLinear) { const SkRSXform xform[] = { // clang-format off { 1.2f, 0.0f, kRenderLeft, kRenderTop}, { 0.0f, 1.2f, kRenderRight, kRenderTop}, {-1.2f, 0.0f, kRenderRight, kRenderBottom}, { 0.0f, -1.2f, kRenderLeft, kRenderBottom}, // clang-format on }; const SkRect tex[] = { // clang-format off {0, 0, kRenderHalfWidth, kRenderHalfHeight}, {kRenderHalfWidth, 0, kRenderWidth, kRenderHalfHeight}, {kRenderHalfWidth, kRenderHalfHeight, kRenderWidth, kRenderHeight}, {0, kRenderHalfHeight, kRenderHalfWidth, kRenderHeight}, // clang-format on }; const SkColor sk_colors[] = { SK_ColorBLUE, SK_ColorGREEN, SK_ColorYELLOW, SK_ColorMAGENTA, }; const DlColor dl_colors[] = { DlColor::kBlue(), DlColor::kGreen(), DlColor::kYellow(), DlColor::kMagenta(), }; const sk_sp<SkImage> image = CanvasCompareTester::kTestImage; const DlImageSampling dl_sampling = DlImageSampling::kLinear; const SkSamplingOptions sk_sampling = SkImageSampling::kLinear; CanvasCompareTester::RenderAll( // TestParameters( [=](SkCanvas* canvas, const SkPaint& paint) { canvas->drawAtlas(image.get(), xform, tex, sk_colors, 2, // SkBlendMode::kSrcOver, sk_sampling, nullptr, &paint); }, [=](DlCanvas* canvas, const DlPaint& paint) { canvas->DrawAtlas(DlImage::Make(image), xform, tex, dl_colors, 2, DlBlendMode::kSrcOver, dl_sampling, nullptr, &paint); }, kDrawAtlasWithPaintFlags)); } sk_sp<DisplayList> makeTestDisplayList() { DisplayListBuilder builder; DlPaint paint; paint.setDrawStyle(DlDrawStyle::kFill); paint.setColor(SK_ColorRED); builder.DrawRect({kRenderLeft, kRenderTop, kRenderCenterX, kRenderCenterY}, paint); paint.setColor(SK_ColorBLUE); builder.DrawRect({kRenderCenterX, kRenderTop, kRenderRight, kRenderCenterY}, paint); paint.setColor(SK_ColorGREEN); builder.DrawRect({kRenderLeft, kRenderCenterY, kRenderCenterX, kRenderBottom}, paint); paint.setColor(SK_ColorYELLOW); builder.DrawRect( {kRenderCenterX, kRenderCenterY, kRenderRight, kRenderBottom}, paint); return builder.Build(); } TEST_F(DisplayListCanvas, DrawDisplayList) { sk_sp<DisplayList> display_list = makeTestDisplayList(); CanvasCompareTester::RenderAll( // TestParameters( [=](SkCanvas* canvas, const SkPaint& paint) { // DlSkCanvasAdapter(canvas).DrawDisplayList(display_list); }, [=](DlCanvas* canvas, const DlPaint& paint) { // canvas->DrawDisplayList(display_list); }, kDrawDisplayListFlags) .set_draw_display_list()); } TEST_F(DisplayListCanvas, DrawTextBlob) { // TODO(https://github.com/flutter/flutter/issues/82202): Remove once the // performance overlay can use Fuchsia's font manager instead of the empty // default. #if defined(OS_FUCHSIA) GTEST_SKIP() << "Rendering comparisons require a valid default font manager"; #endif // OS_FUCHSIA sk_sp<SkTextBlob> blob = CanvasCompareTester::MakeTextBlob("Testing", kRenderHeight * 0.33f); SkScalar render_y_1_3 = kRenderTop + kRenderHeight * 0.3; SkScalar render_y_2_3 = kRenderTop + kRenderHeight * 0.6; CanvasCompareTester::RenderAll( // TestParameters( [=](SkCanvas* canvas, const SkPaint& paint) { // canvas->drawTextBlob(blob, kRenderLeft, render_y_1_3, paint); canvas->drawTextBlob(blob, kRenderLeft, render_y_2_3, paint); canvas->drawTextBlob(blob, kRenderLeft, kRenderBottom, paint); }, [=](DlCanvas* canvas, const DlPaint& paint) { // canvas->DrawTextBlob(blob, kRenderLeft, render_y_1_3, paint); canvas->DrawTextBlob(blob, kRenderLeft, render_y_2_3, paint); canvas->DrawTextBlob(blob, kRenderLeft, kRenderBottom, paint); }, kDrawTextBlobFlags) .set_draw_text_blob(), // From examining the bounds differential for the "Default" case, the // SkTextBlob adds a padding of ~32 on the left, ~30 on the right, // ~12 on top and ~8 on the bottom, so we add 33h & 13v allowed // padding to the tolerance CanvasCompareTester::DefaultTolerance.addBoundsPadding(33, 13)); EXPECT_TRUE(blob->unique()); } TEST_F(DisplayListCanvas, DrawShadow) { SkPath path; path.addRoundRect( { kRenderLeft + 10, kRenderTop, kRenderRight - 10, kRenderBottom - 20, }, kRenderCornerRadius, kRenderCornerRadius); const DlColor color = DlColor::kDarkGrey(); const SkScalar elevation = 5; CanvasCompareTester::RenderAll( // TestParameters( [=](SkCanvas* canvas, const SkPaint& paint) { // DlSkCanvasDispatcher::DrawShadow(canvas, path, color, elevation, false, 1.0); }, [=](DlCanvas* canvas, const DlPaint& paint) { // canvas->DrawShadow(path, color, elevation, false, 1.0); }, kDrawShadowFlags), CanvasCompareTester::DefaultTolerance.addBoundsPadding(3, 3)); } TEST_F(DisplayListCanvas, DrawShadowTransparentOccluder) { SkPath path; path.addRoundRect( { kRenderLeft + 10, kRenderTop, kRenderRight - 10, kRenderBottom - 20, }, kRenderCornerRadius, kRenderCornerRadius); const DlColor color = DlColor::kDarkGrey(); const SkScalar elevation = 5; CanvasCompareTester::RenderAll( // TestParameters( [=](SkCanvas* canvas, const SkPaint& paint) { // DlSkCanvasDispatcher::DrawShadow(canvas, path, color, elevation, true, 1.0); }, [=](DlCanvas* canvas, const DlPaint& paint) { // canvas->DrawShadow(path, color, elevation, true, 1.0); }, kDrawShadowFlags), CanvasCompareTester::DefaultTolerance.addBoundsPadding(3, 3)); } TEST_F(DisplayListCanvas, DrawShadowDpr) { SkPath path; path.addRoundRect( { kRenderLeft + 10, kRenderTop, kRenderRight - 10, kRenderBottom - 20, }, kRenderCornerRadius, kRenderCornerRadius); const DlColor color = DlColor::kDarkGrey(); const SkScalar elevation = 5; CanvasCompareTester::RenderAll( // TestParameters( [=](SkCanvas* canvas, const SkPaint& paint) { // DlSkCanvasDispatcher::DrawShadow(canvas, path, color, elevation, false, 1.5); }, [=](DlCanvas* canvas, const DlPaint& paint) { // canvas->DrawShadow(path, color, elevation, false, 1.5); }, kDrawShadowFlags), CanvasCompareTester::DefaultTolerance.addBoundsPadding(3, 3)); } TEST_F(DisplayListCanvas, SaveLayerConsolidation) { float commutable_color_matrix[]{ // clang-format off 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, // clang-format on }; float non_commutable_color_matrix[]{ // clang-format off 0, 1, 0, .1, 0, 0, 0, 1, .1, 0, 1, 0, 0, .1, 0, 0, 0, 0, .7, 0, // clang-format on }; SkMatrix contract_matrix; contract_matrix.setScale(0.9f, 0.9f, kRenderCenterX, kRenderCenterY); std::vector<SkScalar> opacities = { 0, 0.5f, SK_Scalar1, }; std::vector<std::shared_ptr<DlColorFilter>> color_filters = { std::make_shared<DlBlendColorFilter>(DlColor::kCyan(), DlBlendMode::kSrcATop), std::make_shared<DlMatrixColorFilter>(commutable_color_matrix), std::make_shared<DlMatrixColorFilter>(non_commutable_color_matrix), DlSrgbToLinearGammaColorFilter::instance, DlLinearToSrgbGammaColorFilter::instance, }; std::vector<std::shared_ptr<DlImageFilter>> image_filters = { std::make_shared<DlBlurImageFilter>(5.0f, 5.0f, DlTileMode::kDecal), std::make_shared<DlDilateImageFilter>(5.0f, 5.0f), std::make_shared<DlErodeImageFilter>(5.0f, 5.0f), std::make_shared<DlMatrixImageFilter>(contract_matrix, DlImageSampling::kLinear), }; std::vector<std::unique_ptr<RenderEnvironment>> environments; for (auto& provider : CanvasCompareTester::kTestProviders) { auto env = std::make_unique<RenderEnvironment>( provider.get(), PixelFormat::kN32Premul_PixelFormat); environments.push_back(std::move(env)); } auto render_content = [](DisplayListBuilder& builder) { builder.DrawRect( SkRect{kRenderLeft, kRenderTop, kRenderCenterX, kRenderCenterY}, DlPaint(DlColor::kYellow())); builder.DrawRect( SkRect{kRenderCenterX, kRenderTop, kRenderRight, kRenderCenterY}, DlPaint(DlColor::kRed())); builder.DrawRect( SkRect{kRenderLeft, kRenderCenterY, kRenderCenterX, kRenderBottom}, DlPaint(DlColor::kBlue())); builder.DrawRect( SkRect{kRenderCenterX, kRenderCenterY, kRenderRight, kRenderBottom}, DlPaint(DlColor::kRed().modulateOpacity(0.5f))); }; auto test_attributes_env = [render_content](DlPaint& paint1, DlPaint& paint2, const DlPaint& paint_both, bool same, bool rev_same, const std::string& desc1, const std::string& desc2, const RenderEnvironment* env) { DisplayListBuilder nested_builder; nested_builder.SaveLayer(&kTestBounds, &paint1); nested_builder.SaveLayer(&kTestBounds, &paint2); render_content(nested_builder); auto nested_results = env->getResult(nested_builder.Build()); DisplayListBuilder reverse_builder; reverse_builder.SaveLayer(&kTestBounds, &paint2); reverse_builder.SaveLayer(&kTestBounds, &paint1); render_content(reverse_builder); auto reverse_results = env->getResult(reverse_builder.Build()); DisplayListBuilder combined_builder; combined_builder.SaveLayer(&kTestBounds, &paint_both); render_content(combined_builder); auto combined_results = env->getResult(combined_builder.Build()); // Set this boolean to true to test if combinations that are marked // as incompatible actually are compatible despite our predictions. // Some of the combinations that we treat as incompatible actually // are compatible with swapping the order of the operations, but // it would take a bit of new infrastructure to really identify // those combinations. The only hard constraint to test here is // when we claim that they are compatible and they aren't. const bool always = false; if (always || same) { CanvasCompareTester::quickCompareToReference( nested_results.get(), combined_results.get(), same, "nested " + desc1 + " then " + desc2); } if (always || rev_same) { CanvasCompareTester::quickCompareToReference( reverse_results.get(), combined_results.get(), rev_same, "nested " + desc2 + " then " + desc1); } }; auto test_attributes = [test_attributes_env, &environments]( DlPaint& paint1, DlPaint& paint2, const DlPaint& paint_both, bool same, bool rev_same, const std::string& desc1, const std::string& desc2) { for (auto& env : environments) { test_attributes_env(paint1, paint2, paint_both, // same, rev_same, desc1, desc2, env.get()); } }; // CF then Opacity should always work. // The reverse sometimes works. for (size_t cfi = 0; cfi < color_filters.size(); cfi++) { auto color_filter = color_filters[cfi]; std::string cf_desc = "color filter #" + std::to_string(cfi + 1); DlPaint nested_paint1 = DlPaint().setColorFilter(color_filter); for (size_t oi = 0; oi < opacities.size(); oi++) { SkScalar opacity = opacities[oi]; std::string op_desc = "opacity " + std::to_string(opacity); DlPaint nested_paint2 = DlPaint().setOpacity(opacity); DlPaint combined_paint = nested_paint1; combined_paint.setOpacity(opacity); bool op_then_cf_works = opacity <= 0.0 || opacity >= 1.0 || color_filter->can_commute_with_opacity(); test_attributes(nested_paint1, nested_paint2, combined_paint, true, op_then_cf_works, cf_desc, op_desc); } } // Opacity then IF should always work. // The reverse can also work for some values of opacity. // The reverse should also theoretically work for some IFs, but we // get some rounding errors that are more than just trivial. for (size_t oi = 0; oi < opacities.size(); oi++) { SkScalar opacity = opacities[oi]; std::string op_desc = "opacity " + std::to_string(opacity); DlPaint nested_paint1 = DlPaint().setOpacity(opacity); for (size_t ifi = 0; ifi < image_filters.size(); ifi++) { auto image_filter = image_filters[ifi]; std::string if_desc = "image filter #" + std::to_string(ifi + 1); DlPaint nested_paint2 = DlPaint().setImageFilter(image_filter); DlPaint combined_paint = nested_paint1; combined_paint.setImageFilter(image_filter); bool if_then_op_works = opacity <= 0.0 || opacity >= 1.0; test_attributes(nested_paint1, nested_paint2, combined_paint, true, if_then_op_works, op_desc, if_desc); } } // CF then IF should always work. // The reverse might work, but we lack the infrastructure to check it. for (size_t cfi = 0; cfi < color_filters.size(); cfi++) { auto color_filter = color_filters[cfi]; std::string cf_desc = "color filter #" + std::to_string(cfi + 1); DlPaint nested_paint1 = DlPaint().setColorFilter(color_filter); for (size_t ifi = 0; ifi < image_filters.size(); ifi++) { auto image_filter = image_filters[ifi]; std::string if_desc = "image filter #" + std::to_string(ifi + 1); DlPaint nested_paint2 = DlPaint().setImageFilter(image_filter); DlPaint combined_paint = nested_paint1; combined_paint.setImageFilter(image_filter); test_attributes(nested_paint1, nested_paint2, combined_paint, true, false, cf_desc, if_desc); } } } TEST_F(DisplayListCanvas, MatrixColorFilterModifyTransparencyCheck) { std::vector<std::unique_ptr<RenderEnvironment>> environments; for (auto& provider : CanvasCompareTester::kTestProviders) { auto env = std::make_unique<RenderEnvironment>( provider.get(), PixelFormat::kN32Premul_PixelFormat); environments.push_back(std::move(env)); } auto test_matrix = [&environments](int element, SkScalar value) { // clang-format off float matrix[] = { 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, }; // clang-format on std::string desc = "matrix[" + std::to_string(element) + "] = " + std::to_string(value); float original_value = matrix[element]; matrix[element] = value; DlMatrixColorFilter filter(matrix); auto dl_filter = DlMatrixColorFilter::Make(matrix); bool is_identity = (dl_filter == nullptr || original_value == value); DlPaint paint(0x7f7f7f7f); DlPaint filter_save_paint = DlPaint().setColorFilter(&filter); DisplayListBuilder builder1; builder1.Translate(kTestCenter.fX, kTestCenter.fY); builder1.Rotate(45); builder1.Translate(-kTestCenter.fX, -kTestCenter.fY); builder1.DrawRect(kRenderBounds, paint); auto display_list1 = builder1.Build(); DisplayListBuilder builder2; builder2.Translate(kTestCenter.fX, kTestCenter.fY); builder2.Rotate(45); builder2.Translate(-kTestCenter.fX, -kTestCenter.fY); builder2.SaveLayer(&kTestBounds, &filter_save_paint); builder2.DrawRect(kRenderBounds, paint); builder2.Restore(); auto display_list2 = builder2.Build(); for (auto& env : environments) { auto results1 = env->getResult(display_list1); auto results2 = env->getResult(display_list2); CanvasCompareTester::quickCompareToReference( results1.get(), results2.get(), is_identity, desc + " filter affects rendering"); int modified_transparent_pixels = CanvasCompareTester::countModifiedTransparentPixels(results1.get(), results2.get()); EXPECT_EQ(filter.modifies_transparent_black(), modified_transparent_pixels != 0) << desc; } }; // Tests identity (matrix[0] already == 1 in an identity filter) test_matrix(0, 1); // test_matrix(19, 1); for (int i = 0; i < 20; i++) { test_matrix(i, -0.25); test_matrix(i, 0); test_matrix(i, 0.25); test_matrix(i, 1); test_matrix(i, 1.25); test_matrix(i, SK_ScalarNaN); test_matrix(i, SK_ScalarInfinity); test_matrix(i, -SK_ScalarInfinity); } } TEST_F(DisplayListCanvas, MatrixColorFilterOpacityCommuteCheck) { std::vector<std::unique_ptr<RenderEnvironment>> environments; for (auto& provider : CanvasCompareTester::kTestProviders) { auto env = std::make_unique<RenderEnvironment>( provider.get(), PixelFormat::kN32Premul_PixelFormat); environments.push_back(std::move(env)); } auto test_matrix = [&environments](int element, SkScalar value) { // clang-format off float matrix[] = { 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, }; // clang-format on std::string desc = "matrix[" + std::to_string(element) + "] = " + std::to_string(value); matrix[element] = value; auto filter = DlMatrixColorFilter::Make(matrix); EXPECT_EQ(SkScalarIsFinite(value), filter != nullptr); DlPaint paint(0x80808080); DlPaint opacity_save_paint = DlPaint().setOpacity(0.5); DlPaint filter_save_paint = DlPaint().setColorFilter(filter); DisplayListBuilder builder1; builder1.SaveLayer(&kTestBounds, &opacity_save_paint); builder1.SaveLayer(&kTestBounds, &filter_save_paint); // builder1.DrawRect(kRenderBounds.makeOffset(20, 20), DlPaint()); builder1.DrawRect(kRenderBounds, paint); builder1.Restore(); builder1.Restore(); auto display_list1 = builder1.Build(); DisplayListBuilder builder2; builder2.SaveLayer(&kTestBounds, &filter_save_paint); builder2.SaveLayer(&kTestBounds, &opacity_save_paint); // builder1.DrawRect(kRenderBounds.makeOffset(20, 20), DlPaint()); builder2.DrawRect(kRenderBounds, paint); builder2.Restore(); builder2.Restore(); auto display_list2 = builder2.Build(); for (auto& env : environments) { auto results1 = env->getResult(display_list1); auto results2 = env->getResult(display_list2); if (!filter || filter->can_commute_with_opacity()) { CanvasCompareTester::compareToReference( results2.get(), results1.get(), desc, nullptr, nullptr, DlColor::kTransparent(), true, kTestWidth, kTestHeight, true); } else { CanvasCompareTester::quickCompareToReference( results1.get(), results2.get(), false, desc); } } }; // Tests identity (matrix[0] already == 1 in an identity filter) test_matrix(0, 1); // test_matrix(19, 1); for (int i = 0; i < 20; i++) { test_matrix(i, -0.25); test_matrix(i, 0); test_matrix(i, 0.25); test_matrix(i, 1); test_matrix(i, 1.1); test_matrix(i, SK_ScalarNaN); test_matrix(i, SK_ScalarInfinity); test_matrix(i, -SK_ScalarInfinity); } } #define FOR_EACH_BLEND_MODE_ENUM(FUNC) \ FUNC(kSrc) \ FUNC(kClear) \ FUNC(kSrc) \ FUNC(kDst) \ FUNC(kSrcOver) \ FUNC(kDstOver) \ FUNC(kSrcIn) \ FUNC(kDstIn) \ FUNC(kSrcOut) \ FUNC(kDstOut) \ FUNC(kSrcATop) \ FUNC(kDstATop) \ FUNC(kXor) \ FUNC(kPlus) \ FUNC(kModulate) \ FUNC(kScreen) \ FUNC(kOverlay) \ FUNC(kDarken) \ FUNC(kLighten) \ FUNC(kColorDodge) \ FUNC(kColorBurn) \ FUNC(kHardLight) \ FUNC(kSoftLight) \ FUNC(kDifference) \ FUNC(kExclusion) \ FUNC(kMultiply) \ FUNC(kHue) \ FUNC(kSaturation) \ FUNC(kColor) \ FUNC(kLuminosity) TEST_F(DisplayListCanvas, BlendColorFilterModifyTransparencyCheck) { std::vector<std::unique_ptr<RenderEnvironment>> environments; for (auto& provider : CanvasCompareTester::kTestProviders) { auto env = std::make_unique<RenderEnvironment>( provider.get(), PixelFormat::kN32Premul_PixelFormat); environments.push_back(std::move(env)); } auto test_mode_color = [&environments](DlBlendMode mode, DlColor color) { std::stringstream desc_str; desc_str << "blend[" << mode << ", " << color << "]"; std::string desc = desc_str.str(); DlBlendColorFilter filter(color, mode); if (filter.modifies_transparent_black()) { ASSERT_NE(DlBlendColorFilter::Make(color, mode), nullptr) << desc; } DlPaint paint(0x7f7f7f7f); DlPaint filter_save_paint = DlPaint().setColorFilter(&filter); DisplayListBuilder builder1; builder1.Translate(kTestCenter.fX, kTestCenter.fY); builder1.Rotate(45); builder1.Translate(-kTestCenter.fX, -kTestCenter.fY); builder1.DrawRect(kRenderBounds, paint); auto display_list1 = builder1.Build(); DisplayListBuilder builder2; builder2.Translate(kTestCenter.fX, kTestCenter.fY); builder2.Rotate(45); builder2.Translate(-kTestCenter.fX, -kTestCenter.fY); builder2.SaveLayer(&kTestBounds, &filter_save_paint); builder2.DrawRect(kRenderBounds, paint); builder2.Restore(); auto display_list2 = builder2.Build(); for (auto& env : environments) { auto results1 = env->getResult(display_list1); auto results2 = env->getResult(display_list2); int modified_transparent_pixels = CanvasCompareTester::countModifiedTransparentPixels(results1.get(), results2.get()); EXPECT_EQ(filter.modifies_transparent_black(), modified_transparent_pixels != 0) << desc; } }; auto test_mode = [&test_mode_color](DlBlendMode mode) { test_mode_color(mode, DlColor::kTransparent()); test_mode_color(mode, DlColor::kWhite()); test_mode_color(mode, DlColor::kWhite().modulateOpacity(0.5)); test_mode_color(mode, DlColor::kBlack()); test_mode_color(mode, DlColor::kBlack().modulateOpacity(0.5)); }; #define TEST_MODE(V) test_mode(DlBlendMode::V); FOR_EACH_BLEND_MODE_ENUM(TEST_MODE) #undef TEST_MODE } TEST_F(DisplayListCanvas, BlendColorFilterOpacityCommuteCheck) { std::vector<std::unique_ptr<RenderEnvironment>> environments; for (auto& provider : CanvasCompareTester::kTestProviders) { auto env = std::make_unique<RenderEnvironment>( provider.get(), PixelFormat::kN32Premul_PixelFormat); environments.push_back(std::move(env)); } auto test_mode_color = [&environments](DlBlendMode mode, DlColor color) { std::stringstream desc_str; desc_str << "blend[" << mode << ", " << color << "]"; std::string desc = desc_str.str(); DlBlendColorFilter filter(color, mode); if (filter.can_commute_with_opacity()) { // If it can commute with opacity, then it might also be a NOP, // so we won't necessarily get a non-null return from |::Make()| } else { ASSERT_NE(DlBlendColorFilter::Make(color, mode), nullptr) << desc; } DlPaint paint(0x80808080); DlPaint opacity_save_paint = DlPaint().setOpacity(0.5); DlPaint filter_save_paint = DlPaint().setColorFilter(&filter); DisplayListBuilder builder1; builder1.SaveLayer(&kTestBounds, &opacity_save_paint); builder1.SaveLayer(&kTestBounds, &filter_save_paint); // builder1.DrawRect(kRenderBounds.makeOffset(20, 20), DlPaint()); builder1.DrawRect(kRenderBounds, paint); builder1.Restore(); builder1.Restore(); auto display_list1 = builder1.Build(); DisplayListBuilder builder2; builder2.SaveLayer(&kTestBounds, &filter_save_paint); builder2.SaveLayer(&kTestBounds, &opacity_save_paint); // builder1.DrawRect(kRenderBounds.makeOffset(20, 20), DlPaint()); builder2.DrawRect(kRenderBounds, paint); builder2.Restore(); builder2.Restore(); auto display_list2 = builder2.Build(); for (auto& env : environments) { auto results1 = env->getResult(display_list1); auto results2 = env->getResult(display_list2); if (filter.can_commute_with_opacity()) { CanvasCompareTester::compareToReference( results2.get(), results1.get(), desc, nullptr, nullptr, DlColor::kTransparent(), true, kTestWidth, kTestHeight, true); } else { CanvasCompareTester::quickCompareToReference( results1.get(), results2.get(), false, desc); } } }; auto test_mode = [&test_mode_color](DlBlendMode mode) { test_mode_color(mode, DlColor::kTransparent()); test_mode_color(mode, DlColor::kWhite()); test_mode_color(mode, DlColor::kWhite().modulateOpacity(0.5)); test_mode_color(mode, DlColor::kBlack()); test_mode_color(mode, DlColor::kBlack().modulateOpacity(0.5)); }; #define TEST_MODE(V) test_mode(DlBlendMode::V); FOR_EACH_BLEND_MODE_ENUM(TEST_MODE) #undef TEST_MODE } #undef FOR_EACH_ENUM } // namespace testing } // namespace flutter
[ "noreply@github.com" ]
noreply@github.com
1e757ce4a90c2155be9f28aa6634742733a594f1
a176c15edf1e087307eee79331c6c9aa3d1b23ed
/05source/cfg/IPStaticCom.cpp
d606f73d234d7f84e5be2d052bfc47a017289a29
[]
no_license
bitores/QT_Demo
8aef7bc056cf85ba8bfab642a0f729bb1629fd56
6cdbb183e1044a03e5bb813cf6c7dd4d014753bb
refs/heads/master
2016-09-14T07:10:36.046678
2016-05-14T12:50:28
2016-05-14T12:50:28
58,807,477
0
0
null
null
null
null
UTF-8
C++
false
false
15,733
cpp
#include "IPStaticCom.h" CIPStaticCom::CIPStaticCom(QObject *parent) : QObject(parent) ,m_name("") ,m_rate(AbstractSerial::BaudRate9600) ,m_parity(AbstractSerial::ParityNone) ,m_databit(AbstractSerial::DataBits5) ,m_stopbit(AbstractSerial::StopBits1) { } CIPStaticCom::CIPStaticCom(const QString& name , AbstractSerial::BaudRate rate , AbstractSerial::Parity parity , AbstractSerial::DataBits databit , AbstractSerial::StopBits stopbit) :m_name(name) ,m_rate(rate) ,m_parity(parity) ,m_databit(databit) ,m_stopbit(stopbit) { } CIPStaticCom::CIPStaticCom(const QString& name, const QString& rate, const QString& parity , const QString& databit, const QString& stopbit) :m_name(name) { SetRate(rate); SetParity(parity); SetDataBit(databit); SetStopBit(stopbit); } CIPStaticCom::~CIPStaticCom() { } //拷贝构造函数 CIPStaticCom::CIPStaticCom(const CIPStaticCom& src) { if (this == &src) { return; } m_name = src.m_name; m_rate = src.m_rate; m_parity = src.m_parity; m_databit = src.m_databit; m_stopbit = src.m_stopbit; } //拷贝赋值函数 CIPStaticCom& CIPStaticCom::operator=(const CIPStaticCom& src) { if (this == &src) { return *this; } m_name = src.m_name; m_rate = src.m_rate; m_parity = src.m_parity; m_databit = src.m_databit; m_stopbit = src.m_stopbit; return *this; } //串口名称 void CIPStaticCom::SetName(const QString& name) { m_name = name; } QString CIPStaticCom::GetName() const { return m_name; } //串口波特率 void CIPStaticCom::SetRate(const QString& src) { m_rate = AbstractSerial::BaudRateUndefined; quint32 ui32rate = src.toUInt(); switch (ui32rate) { case 9600: m_rate = AbstractSerial::BaudRate9600; /*!< \~english Speed 9600 bauds. */ break; case 2400: m_rate = AbstractSerial::BaudRate2400; /*!< \~english Speed 2400 bauds. */ break; case 115200: m_rate = AbstractSerial::BaudRate115200; /*!< \~english Speed 115200 bauds. */ break; //以上波特率常用,提供switch匹配效率 case 50: m_rate = AbstractSerial::BaudRate50; /*!< \~english Speed 50 bauds. */ break; case 75: m_rate = AbstractSerial::BaudRate75; /*!< \~english Speed 75 bauds. */ break; case 110: m_rate = AbstractSerial::BaudRate110; /*!< \~english Speed 110 bauds. */ break; case 134: m_rate = AbstractSerial::BaudRate134; /*!< \~english Speed 134 bauds. */ break; case 150: m_rate = AbstractSerial::BaudRate150; /*!< \~english Speed 150 bauds. */ break; case 200: m_rate = AbstractSerial::BaudRate200; /*!< \~english Speed 200 bauds. */ break; case 300: m_rate = AbstractSerial::BaudRate300; /*!< \~english Speed 300 bauds. */ break; case 600: m_rate = AbstractSerial::BaudRate600; /*!< \~english Speed 600 bauds. */ break; case 1200: m_rate = AbstractSerial::BaudRate1200; /*!< \~english Speed 1200 bauds. */ break; case 1800: m_rate = AbstractSerial::BaudRate1800; /*!< \~english Speed 1800 bauds. */ break; //2400 case 4800: m_rate = AbstractSerial::BaudRate4800; /*!< \~english Speed 4800 bauds. */ break; //9600 case 14400: m_rate = AbstractSerial::BaudRate14400; /*!< \~english Speed 14400 bauds. */ break; case 19200: m_rate = AbstractSerial::BaudRate19200; /*!< \~english Speed 19200 bauds. */ break; case 38400: m_rate = AbstractSerial::BaudRate38400; /*!< \~english Speed 38400 bauds. */ break; case 56000: m_rate = AbstractSerial::BaudRate56000; /*!< \~english Speed 56000 bauds. */ break; case 57600: m_rate = AbstractSerial::BaudRate57600; /*!< \~english Speed 57600 bauds. */ break; case 76800: m_rate = AbstractSerial::BaudRate76800; /*!< \~english Speed 76800 bauds. */ break; //115200 case 128000: m_rate = AbstractSerial::BaudRate128000; /*!< \~english Speed 128000 bauds. */ break; case 230400: m_rate = AbstractSerial::BaudRate230400; /*!< \~english Speed 230400 bauds. */ //enhanced speed (experimental) break; case 256000: m_rate = AbstractSerial::BaudRate256000; /*!< \~english Speed 256000 bauds. */ break; case 460800: m_rate = AbstractSerial::BaudRate460800; /*!< \~english Speed 460800 bauds. */ //enhanced speed (experimental) break; case 500000: m_rate = AbstractSerial::BaudRate500000; /*!< \~english Speed 500000 bauds. */ //enhanced speed (experimental) break; case 576000: m_rate = AbstractSerial::BaudRate576000; /*!< \~english Speed 576000 bauds. */ //enhanced speed (experimental) break; case 921600: m_rate = AbstractSerial::BaudRate921600; /*!< \~english Speed 921600 bauds. */ //enhanced speed (experimental) break; case 1000000: m_rate = AbstractSerial::BaudRate1000000; /*!< \~english Speed 1000000 bauds. */ //enhanced speed (experimental) break; case 1152000: m_rate = AbstractSerial::BaudRate1152000; /*!< \~english Speed 1152000 bauds. */ //enhanced speed (experimental) break; case 1500000: m_rate = AbstractSerial::BaudRate1500000; /*!< \~english Speed 1500000 bauds. */ //enhanced speed (experimental) break; case 2000000: m_rate = AbstractSerial::BaudRate2000000; /*!< \~english Speed 2000000 bauds. */ //enhanced speed (experimental) break; case 2500000: m_rate = AbstractSerial::BaudRate2500000; /*!< \~english Speed 2500000 bauds. */ //enhanced speed (experimental) break; case 3000000: m_rate = AbstractSerial::BaudRate3000000; /*!< \~english Speed 3000000 bauds. */ //enhanced speed (experimental) break; case 3500000: m_rate = AbstractSerial::BaudRate3500000; /*!< \~english Speed 3500000 bauds. */ //enhanced speed (experimental) break; case 4000000: m_rate = AbstractSerial::BaudRate4000000; /*!< \~english Speed 4000000 bauds. */ //enhanced speed (experimental) break; default: break; } } void CIPStaticCom::SetRate(AbstractSerial::BaudRate rate /*= AbstractSerial::BaudRate9600*/) { m_rate = rate; } AbstractSerial::BaudRate CIPStaticCom::GetRate() const { return m_rate; } QString CIPStaticCom::GetRateValue() const { switch (m_rate) { case AbstractSerial::BaudRate9600: return "9600"; /*!< \~english Speed 9600 bauds. */ break; case AbstractSerial::BaudRate2400: return "2400"; /*!< \~english Speed 2400 bauds. */ break; case AbstractSerial::BaudRate115200: return "115200"; /*!< \~english Speed 115200 bauds. */ break; //以上波特率常用,提供switch匹配效率 case AbstractSerial::BaudRate50: return "50"; /*!< \~english Speed 50 bauds. */ break; case AbstractSerial::BaudRate75: return "75"; /*!< \~english Speed 75 bauds. */ break; case AbstractSerial::BaudRate110: return "110"; /*!< \~english Speed 110 bauds. */ break; case AbstractSerial::BaudRate134: return "134"; /*!< \~english Speed 134 bauds. */ break; case AbstractSerial::BaudRate150: return "150"; /*!< \~english Speed 150 bauds. */ break; case AbstractSerial::BaudRate200: return "200"; /*!< \~english Speed 200 bauds. */ break; case AbstractSerial::BaudRate300: return "300"; /*!< \~english Speed 300 bauds. */ break; case AbstractSerial::BaudRate600: return "600"; /*!< \~english Speed 600 bauds. */ break; case AbstractSerial::BaudRate1200: return "1200"; /*!< \~english Speed 1200 bauds. */ break; case AbstractSerial::BaudRate1800: return "1800"; /*!< \~english Speed 1800 bauds. */ break; //2400 case AbstractSerial::BaudRate4800: return "4800"; /*!< \~english Speed 4800 bauds. */ break; //9600 case AbstractSerial::BaudRate14400: return "14400"; /*!< \~english Speed 14400 bauds. */ break; case AbstractSerial::BaudRate19200: return "19200"; /*!< \~english Speed 19200 bauds. */ break; case AbstractSerial::BaudRate38400: return "38400"; /*!< \~english Speed 38400 bauds. */ break; case AbstractSerial::BaudRate56000: return "56000"; /*!< \~english Speed 56000 bauds. */ break; case AbstractSerial::BaudRate57600: return "57600"; /*!< \~english Speed 57600 bauds. */ break; case AbstractSerial::BaudRate76800: return "76800"; /*!< \~english Speed 76800 bauds. */ break; //115200 case AbstractSerial::BaudRate128000: return "128000"; /*!< \~english Speed 128000 bauds. */ break; case AbstractSerial::BaudRate230400: return "230400"; /*!< \~english Speed 230400 bauds. */ //enhanced speed (experimental) break; case AbstractSerial::BaudRate256000: return "256000"; /*!< \~english Speed 256000 bauds. */ break; case AbstractSerial::BaudRate460800: return "460800"; /*!< \~english Speed 460800 bauds. */ //enhanced speed (experimental) break; case AbstractSerial::BaudRate500000: return "500000"; /*!< \~english Speed 500000 bauds. */ //enhanced speed (experimental) break; case AbstractSerial::BaudRate576000: return "576000"; /*!< \~english Speed 576000 bauds. */ //enhanced speed (experimental) break; case AbstractSerial::BaudRate921600: return "921600"; /*!< \~english Speed 921600 bauds. */ //enhanced speed (experimental) break; case AbstractSerial::BaudRate1000000: return "1000000"; /*!< \~english Speed 1000000 bauds. */ //enhanced speed (experimental) break; case AbstractSerial::BaudRate1152000: return "1152000"; /*!< \~english Speed 1152000 bauds. */ //enhanced speed (experimental) break; case AbstractSerial::BaudRate1500000: return "1500000"; /*!< \~english Speed 1500000 bauds. */ //enhanced speed (experimental) break; case AbstractSerial::BaudRate2000000: return "2000000"; /*!< \~english Speed 2000000 bauds. */ //enhanced speed (experimental) break; case AbstractSerial::BaudRate2500000: return "2500000"; /*!< \~english Speed 2500000 bauds. */ //enhanced speed (experimental) break; case AbstractSerial::BaudRate3000000: return "3000000"; /*!< \~english Speed 3000000 bauds. */ //enhanced speed (experimental) break; case AbstractSerial::BaudRate3500000: return "3500000"; /*!< \~english Speed 3500000 bauds. */ //enhanced speed (experimental) break; case AbstractSerial::BaudRate4000000: return "4000000"; /*!< \~english Speed 4000000 bauds. */ //enhanced speed (experimental) break; default: return ""; break; } } //串口校验位 void CIPStaticCom::SetParity(const QString& src) { m_parity = AbstractSerial::ParityUndefined; if (0 == src.compare("None", Qt::CaseInsensitive)) { m_parity = AbstractSerial::ParityNone; } else if (0 == src.compare("Odd", Qt::CaseInsensitive)) { m_parity = AbstractSerial::ParityOdd; } else if (0 == src.compare("Even", Qt::CaseInsensitive)) { m_parity = AbstractSerial::ParityEven; } else if (0 == src.compare("Mark", Qt::CaseInsensitive)) { m_parity = AbstractSerial::ParityMark; } else if (0 == src.compare("Space", Qt::CaseInsensitive)) { m_parity = AbstractSerial::ParitySpace; } } void CIPStaticCom::SetParity(AbstractSerial::Parity parity /*= AbstractSerial::ParityNone*/) { m_parity = parity; } AbstractSerial::Parity CIPStaticCom::GetParity() const { return m_parity; } QString CIPStaticCom::GetParityValue() const { QString strret = ""; switch (m_parity) { case AbstractSerial::ParityNone: strret = "None"; break; case AbstractSerial::ParityOdd: strret = "Odd"; break; case AbstractSerial::ParityEven: strret = "Even"; break; case AbstractSerial::ParityMark: strret = "Mark"; break; case AbstractSerial::ParitySpace: strret = "Space"; break; default: strret = "None"; break; } return strret; } //串口数据位 void CIPStaticCom::SetDataBit(const QString& src) { m_databit = AbstractSerial::DataBitsUndefined; quint16 ui16databit = src.toUShort(); switch (ui16databit) { case 5: m_databit = AbstractSerial::DataBits5; break; case 6: m_databit = AbstractSerial::DataBits6; break; case 7: m_databit = AbstractSerial::DataBits7; break; case 8: m_databit = AbstractSerial::DataBits8; break; default: break; } } void CIPStaticCom::SetDataBit(AbstractSerial::DataBits databit /*= AbstractSerial::DataBits5*/) { m_databit = databit; } AbstractSerial::DataBits CIPStaticCom::GetDataBit() const { return m_databit; } QString CIPStaticCom::GetDataBitValue() const { QString strret = ""; switch (m_databit) { case AbstractSerial::DataBits5: strret = "5"; break; case AbstractSerial::DataBits6: strret = "6"; break; case AbstractSerial::DataBits7: strret = "7"; break; case AbstractSerial::DataBits8: strret = "8"; break; default: strret = "5"; break; } return strret; } //串口停止位 void CIPStaticCom::SetStopBit(const QString& src) { m_stopbit = AbstractSerial::StopBitsUndefined; if ("1" == src) { m_stopbit = AbstractSerial::StopBits1; } else if ("1.5" == src) { m_stopbit = AbstractSerial::StopBits1_5; } else if ("2" == src) { m_stopbit = AbstractSerial::StopBits2; } } void CIPStaticCom::SetStopBit(AbstractSerial::StopBits stopbit /*= AbstractSerial::StopBits1*/) { m_stopbit = stopbit; } AbstractSerial::StopBits CIPStaticCom::GetStopBit() const { return m_stopbit; } QString CIPStaticCom::GetStopBitValue() const { QString strret = ""; switch (m_stopbit) { case AbstractSerial::StopBits1: strret = "1"; break; case AbstractSerial::StopBits1_5: strret = "1.5"; break; case AbstractSerial::StopBits2: strret = "2"; break; default: strret = "1"; break; } return strret; } void CIPStaticCom::Clear() { m_name = ""; m_rate = AbstractSerial::BaudRateUndefined; m_parity = AbstractSerial::ParityUndefined; m_databit = AbstractSerial::DataBitsUndefined; m_stopbit = AbstractSerial::StopBitsUndefined; }
[ "773155801@qq.com" ]
773155801@qq.com
4edddbf912633783b2b4504fd8c13f0b30234fc8
5fe6bfee78f1d26df5ae9d7348696b2734da7d53
/NQUEEN.cpp
9b065f5ed8821d842ba075f8178ef09bcc58026d
[]
no_license
nkteaching/assignment-2-GhulamAsgharDahri
86f038dd90e2c9c6aa182b7f4d2bf9d6a74aaf62
4c01cdce066494921959c830e645d50712bdd10c
refs/heads/master
2021-04-22T21:49:55.262001
2020-03-25T03:24:13
2020-03-25T03:24:13
249,876,324
0
0
null
null
null
null
UTF-8
C++
false
false
2,106
cpp
#include<iostream> using namespace std; #include<string.h> class dsa2d{ public: int **board; int n; dsa2d() { board=NULL; } dsa2d(int n) { /*this is initialization of array */ this->n=n; board=new int*[n]; for(int i=0;i<n;i++) { board[i]=new int[n]; memset(board[i],0,sizeof(int)*n); } } //function to print the board after solution void displayBoard() { for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { cout<<board[i][j]<<" "; } cout<<"\n"; } } bool validity(int row,int col) { //condition to check queen for(int i=0;i<col;i++) { if(board[row][i]) { return false; } } //queen can run diagonally therefore checking upper diagonals for(int i=row,j=col;i>=0 && j>=0;i--,j--) { if(board[i][j]) { return false; } } //queen can run diagonally therefore checking upper diagonals for(int i=row,j=col;i<n && j>=0;i++,j--) { if(board[i][j]) { return false; } } return true; } bool solution(int col) { if(col>=n)//this is when col is equal to size meaning that solution has been done { return true; } for(int i=0;i<n;i++) { if(validity(i,col))//checking the conditions that can queen be placed { board[i][col]=1;//if yes then place if(solution(col+1))//recursive call to do this again { return true; } } board[i][col]=0;//other wise place 0 } return false; } bool solutionSetUp() { //this is to initiallize board with 0 for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { board[i][j]=0; } } // this is incase solution does not found if(solution(0)==false) { cout<<"No solution"; return false; } displayBoard(); } }; main() { dsa2d d1(4); // d1.display(); d1.solutionSetUp(); }
[ "noreply@github.com" ]
noreply@github.com
ddb375b1cbdca2117ba534466697aa67b934ab03
cb87390006faa6431a9399dd41b1316e8c377340
/Geometry/Quad.cpp
617edc2f22c7e20456f4a009f0a513fc00d2de25
[]
no_license
codinpsycho/Dark_Engine
98b2384f3eb2c33905e54a70eeca36acd63adff5
a9cf63dc4ae33e19957a5c12fa9cc255f02182f6
refs/heads/master
2021-01-06T20:43:07.989673
2015-05-13T19:44:18
2015-05-13T19:44:18
35,569,933
0
0
null
null
null
null
UTF-8
C++
false
false
9,175
cpp
#include "Quad.h" #include "WorldTransform.h" #include "Dark.h" #include "Texture.h" #include "ResourceManager.h" using namespace DarkEngine; Quad::Quad(void) { m_updateVertices = false; m_showNormals = false; for (int i = 0; i < 3; i++) { v[i].z = 0.5f; v[i].color1 = D3DXCOLOR(1.0f,0.0f,0.0f,1.0f); } depth = 1.0f; v[0].Normal.x = 0, v[0].Normal.y = 1, v[0].Normal.z = 0; v[1].Normal.x = 0, v[1].Normal.y = 1, v[1].Normal.z = 0; v[2].Normal.x = 0, v[2].Normal.y = 1, v[2].Normal.z = 0; v[3].Normal.x = 0, v[3].Normal.y = 1, v[3].Normal.z = 0; //Set default Textures UV's v[0].tu = 0, v[0].tv = 0; v[1].tu = 1, v[1].tv = 0; v[2].tu = 1, v[2].tv = 1; v[3].tu = 0; v[3].tv = 1; //Create Vertex Buffer if (FAILED(DarkEngine::Dark::Instance().GetRenderDevice()->CreateVertexBuffer(4*sizeof(VERTEX), 0, FVF, D3DPOOL_MANAGED, &vbuffer, NULL ))) { MESSAGE("Error creating Vertex Buffer"); } if(LoadVertexBuffer()) { //Now create the Index Buffer if (FAILED(DarkEngine::Dark::Instance().GetRenderDevice()->CreateIndexBuffer( 4*sizeof(short), 0, D3DFMT_INDEX16, D3DPOOL_DEFAULT, &ibuffer, NULL ))) { MESSAGE( "Error creating Index Buffer"); } LoadIndexBuffer(); } } Quad::Quad(VERTEX *v_) { m_updateVertices = false; m_showNormals = false; for (int i = 0; i < 3; i++) { v[i].z = 0.5f; v[i].color1 = D3DXCOLOR(1.0f,0.0f,0.0f,1.0f); } depth = 1.0f; v[0] = v_[0]; v[1] = v_[1]; v[2] = v_[2]; v[3] = v_[3]; v[0].Normal.x = 0, v[0].Normal.y = 1, v[0].Normal.z = 0; v[1].Normal.x = 0, v[1].Normal.y = 1, v[1].Normal.z = 0; v[2].Normal.x = 0, v[2].Normal.y = 1, v[2].Normal.z = 0; v[3].Normal.x = 0, v[3].Normal.y = 1, v[3].Normal.z = 0; //Maps Textures v[0].tu = 0, v[0].tv = 0; v[1].tu = 1, v[1].tv = 0; v[2].tu = 1, v[2].tv = 1; v[3].tu = 0; v[3].tv = 1; //Create Vertex Buffer if (FAILED(DarkEngine::Dark::Instance().GetRenderDevice()->CreateVertexBuffer(4*sizeof(VERTEX), 0, FVF, D3DPOOL_MANAGED, &vbuffer, NULL ))) { MESSAGE("Error creating Vertex Buffer"); } if(LoadVertexBuffer()) { //Now create the Index Buffer if (FAILED(DarkEngine::Dark::Instance().GetRenderDevice()->CreateIndexBuffer( 4*sizeof(short), 0, D3DFMT_INDEX16, D3DPOOL_DEFAULT, &ibuffer, NULL ))) { MESSAGE( "Error creating Index Buffer"); } LoadIndexBuffer(); } } Quad::Quad(const Quad& quad_ ) { } Quad::Quad( float _x, float _y, float _width, float _height ) { m_showNormals = false; for (int i = 0; i < 4; i++) { v[i].z = 0.5f; v[i].color1 = D3DXCOLOR(1.0f,1.0f,1.0f,1.0f); } width = _width, height = _height; depth = 1.0f; v[0].x = _x; v[0].y = _y; v[1].x = _x + width; v[1].y = _y; v[2].x = _x + width; v[2].y = _y - height; v[3].x = _x; v[3].y = _y - height; v[0].Normal.x = 0, v[0].Normal.y = 0, v[0].Normal.z = -1; v[1].Normal.x = 0, v[1].Normal.y = 0, v[1].Normal.z = -1; v[2].Normal.x = 0, v[2].Normal.y = 0, v[2].Normal.z = -1; v[3].Normal.x = 0, v[3].Normal.y = 0, v[3].Normal.z = -1; //Maps Textures v[0].tu = 0, v[0].tv = 0; v[1].tu = 1, v[1].tv = 0; v[2].tu = 1, v[2].tv = 1; v[3].tu = 0; v[3].tv = 1; //Create Vertex Buffer if (FAILED(DarkEngine::Dark::Instance().GetRenderDevice()->CreateVertexBuffer(4*sizeof(VERTEX), 0, FVF, D3DPOOL_MANAGED, &vbuffer, NULL ))) { MESSAGE("Error creating Vertex Buffer"); } if(LoadVertexBuffer()) { //Now create the Index Buffer if (FAILED(DarkEngine::Dark::Instance().GetRenderDevice()->CreateIndexBuffer( 6*sizeof(short), 0, D3DFMT_INDEX16, D3DPOOL_DEFAULT, &ibuffer, NULL ))) { MESSAGE( "Error creating Index Buffer"); } LoadIndexBuffer(); } } Quad::~Quad(void) { SAFE_RELEASE(vbuffer); SAFE_RELEASE(ibuffer); } bool Quad::LoadVertexBuffer() { void *data = 0; vbuffer->Lock(0,0,(void**)&data, 0); //Locked memcpy( data,v,sizeof(v) ); //loaded vbuffer->Unlock(); //Release m_updateVertices = false; return true; } bool Quad::LoadIndexBuffer() { //Now create an array of indices short indices[] = { 0,1,2,3,0,2 }; void *idata = 0; ibuffer->Lock(0,0, (void**)&idata, 0); //Locked memcpy(idata, indices, sizeof(indices) ); //loaded ibuffer->Unlock(); //Release return true; } bool Quad::Update(float dt, LPDIRECT3DDEVICE9 device) { //Physics based Update here return true; } bool Quad::DrawGeometry(LPDIRECT3DDEVICE9 device) { // if (FAILED(device->SetFVF(FVF))) // { // MESSAGE("Set FVF Failed"); // LOG("Set FVF Failed in Quad\n"); // return false; // } if(m_updateVertices) LoadVertexBuffer(); if (FAILED(device->SetStreamSource(0, vbuffer,0, sizeof(VERTEX) ))) { MESSAGE("Set Stream Source Failed"); LOG.Write("Stream source failed in Quad\n"); return false; } if (FAILED(device->SetIndices( ibuffer ))) { MESSAGE("Set Indices Failed"); LOG.Write("Set Indices Failed in Quad"); return false; } if(FAILED(device->DrawIndexedPrimitive(D3DPT_TRIANGLELIST,0,0,4,0,2))) { MESSAGE("Triangle Draw Failed"); LOG.Write("Triangle Draw Failed\n"); return false; } return true; } // // void Quad::SetDiffuseColor(DWORD color_, int index ) // { // switch (index) // { // case -1 : // v[0].color1 = color_; // v[1].color1 = color_; // v[2].color1 = color_; // v[3].color1 = color_; // break; // } // v[index].color1 = color_; // // LoadVertexBuffer(); // // } // void Quad::SetSpecularColor(DWORD color_, int index ) // { // switch (index) // { // case -1 : // // v[0].color2 = color_; // // v[1].color2 = color_; // // v[2].color2 = color_; // // v[3].color2 = color_; // break; // } // //v[index].color2 = color_; // // } // // void Quad::DrawNormals() // { // // lineZ->WorldTransform()->SetWorldTransform(this->WorldTransform()); // lineY->WorldTransform()->SetWorldTransform(this->WorldTransform()); // lineX->WorldTransform()->SetWorldTransform(this->WorldTransform()); // // } // void Quad::ShowNormals() // { // for ( int i = 0; i < 4; i++ ) // { // D3DXVec3Normalize(&v[i].Normal,&v[i].Normal); // } // // // lineX = new CLine(width/2,height/2,depth/2,v[0].Normal.x*10.0f,height/2,depth/2); // lineX->Initialize(); // lineY = new CLine(width/2,height/2,depth/2,width/2,v[0].Normal.y*10.0f,depth/2); // lineY->Initialize(); // lineZ = new CLine(width/2,height/2,depth/2,width/2,height/2,v[0].Normal.z*20.0f); // lineZ->Initialize(); // // lineX->Material()->SetDiffuse(COLORVALUE_RGBA(0.0f,0.0f,0.0f,0.0f)); // lineY->Material()->SetDiffuse(COLORVALUE_RGBA(0.0f,0.0f,0.0f,0.0f)); // lineZ->Material()->SetDiffuse(COLORVALUE_RGBA(0.0f,0.0f,0.0f,0.0f)); // // m_showNormals = true; // } // // void Quad::SetBlend(BLEND blend) // { // switch (blend) // { // case NO_BLENDING : // if (FAILED(EngineManager::Instance()->GetD3DDevice()->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ONE))) // message(L"No Blending Failed","ERROR"); // if (FAILED(EngineManager::Instance()->GetD3DDevice()->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ZERO))) // message(L"No Blending Failed","ERROR"); // break; // // // case COLOR_ADD : // if (FAILED(EngineManager::Instance()->GetD3DDevice()->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCCOLOR))) // message(L"No Blending Failed","ERROR"); // if (FAILED(EngineManager::Instance()->GetD3DDevice()->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_DESTCOLOR))) // message(L"No Blending Failed","ERROR"); // break; // // case COLOR_MUL : // if (FAILED(EngineManager::Instance()->GetD3DDevice()->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCCOLOR))) // message(L"No Blending Failed","ERROR"); // if (FAILED(EngineManager::Instance()->GetD3DDevice()->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCCOLOR))) // message(L"No Blending Failed","ERROR"); // break; // // case ALPHA_ADD : // if (FAILED(EngineManager::Instance()->GetD3DDevice()->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA))) // message(L"No Blending Failed","ERROR"); // if (FAILED(EngineManager::Instance()->GetD3DDevice()->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_DESTALPHA))) // message(L"No Blending Failed","ERROR"); // break; // // case ALPHA_MUL : // if (FAILED(EngineManager::Instance()->GetD3DDevice()->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCCOLOR))) // message(L"No Blending Failed","ERROR"); // if (FAILED(EngineManager::Instance()->GetD3DDevice()->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA))) // message(L"No Blending Failed","ERROR"); // break; // // case BURNOUT : // if (FAILED(EngineManager::Instance()->GetD3DDevice()->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ONE))) // message(L"No Blending Failed","ERROR"); // if (FAILED(EngineManager::Instance()->GetD3DDevice()->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE))) // message(L"No Blending Failed","ERROR"); // break; // case DARKEN : // if (FAILED(EngineManager::Instance()->GetD3DDevice()->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCCOLOR))) // message(L"No Blending Failed","ERROR"); // if (FAILED(EngineManager::Instance()->GetD3DDevice()->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_SRCCOLOR))) // message(L"No Blending Failed","ERROR"); // break; // } // }
[ "ishkaran.singh@hotmail.com" ]
ishkaran.singh@hotmail.com
ca917eb4f39e74fb3e8115b440edf8d8dd09a542
207d316b5c3f30ba44e353453bb56a85cfcb0090
/flockAIv1/Plugins/FlockAI/Source/FlockAI/Private/FlockAIMoveToComponent.cpp
b383121fe7e53237a72395f24168e83771868705
[]
no_license
liupanfengfreedom/flock
20173e3ca1b5bcedd4d871cb43253ea9aee42c4f
b173f0331b03b1183d9d4aefcfd4b2c9df2f87aa
refs/heads/master
2022-12-07T02:27:31.658292
2020-08-17T05:34:09
2020-08-17T05:34:09
286,279,644
0
0
null
null
null
null
UTF-8
C++
false
false
23,124
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "FlockAIMoveToComponent.h" #include "GameFramework/Actor.h" #include "Kismet/KismetMathLibrary.h" #include "Kismet/KismetSystemLibrary.h" #include "Engine.h" #include "FlockAIEnemyComponent.h" #include "Async/AsyncWork.h" // Sets default values for this component's properties UFlockAIMoveToComponent::UFlockAIMoveToComponent() { // Set this component to be initialized when the game starts, and to be ticked every frame. You can turn these features // off to improve performance if you don't need them. PrimaryComponentTick.bCanEverTick = true; // ... } // Called when the game starts void UFlockAIMoveToComponent::BeginPlay() { Super::BeginPlay(); Owner = GetOwner(); // ... FVector origin; Owner->GetActorBounds(false, origin, ownerbound); FVector origin1; if (AILeader) { AILeader->GetActorBounds(false, origin1, aileaderbound); keepdistance = ownerbound.Size() + aileaderbound.Size(); } //Async(EAsyncExecution::ThreadPool, [=]() {threadwork(); }, nullptr); //GetWorld()->GetTimerManager().SetTimer(th,this,&UFlockAIMoveToComponent::timerwork,0.02,true,0.1); GetWorld()->GetTimerManager().SetTimer(thf,this,&UFlockAIMoveToComponent::timerworkf,0.2,true,0.5); GetWorld()->GetTimerManager().SetTimer(thr,this,&UFlockAIMoveToComponent::timerworkr,0.2,true,0.5); GetWorld()->GetTimerManager().SetTimer(thu,this,&UFlockAIMoveToComponent::timerworku,0.2,true,0.5); } void UFlockAIMoveToComponent::timerworkf() { { #define FORWARDDIS 1.5 FVector starpoint = Owner->GetActorLocation(); FVector director = Owner->GetActorForwardVector(); FVector endpoint = starpoint + (ownerbound.X * FORWARDDIS * director* movespeed*20); FVector HalfSize = FVector(5, ownerbound.Y, ownerbound.Z); TArray<AActor*> actorarray; FHitResult hitresult; bool b = UKismetSystemLibrary::BoxTraceSingle(this, starpoint, endpoint, HalfSize, director.Rotation(), ETraceTypeQuery::TraceTypeQuery2, true, actorarray, EDrawDebugTrace::Type::None, hitresult, true, FLinearColor::Red, FLinearColor::Green, 5.0f); if (b) { forwardactor = hitresult.Actor; auto ft = forwardactor->GetComponentByClass(UFlockAIMoveToComponent::StaticClass()); auto ft1 = forwardactor->GetComponentByClass(UFlockAIEnemyComponent::StaticClass()); if (ft) { movespeed = SLOWSPEED; roatationspeed = SLOWROTATION; forwardblockgoalrotation = Owner->GetTransform().TransformRotation(FRotator(0, FMath::RandRange(-5, -2), FMath::RandRange(-5, -2)).Quaternion()).Rotator(); b_fb = true; } else if (ft1) { movespeed = FASTSPEED; roatationspeed = FASTROTATION; forwardblockgoalrotation = Owner->GetTransform().TransformRotation(FRotator(0, FMath::RandRange(-90, -70), FMath::RandRange(-90, -70)).Quaternion()).Rotator(); b_fb = true; } } } } void UFlockAIMoveToComponent::timerworkr() { { #define RIGHTDIS 3 FVector starpoint = Owner->GetActorLocation(); FVector director = Owner->GetActorRightVector(); FVector endpoint = starpoint + (ownerbound.Y * RIGHTDIS * director); FVector HalfSize = FVector(ownerbound.X, 5, ownerbound.Z); TArray<AActor*> actorarray; FHitResult hitresult; bool b = UKismetSystemLibrary::BoxTraceSingle(this, starpoint, endpoint, HalfSize, Owner->GetActorForwardVector().Rotation(), ETraceTypeQuery::TraceTypeQuery2, true, actorarray, EDrawDebugTrace::Type::None, hitresult, true, FLinearColor::Red, FLinearColor::Green, 5.0f); if (b) { rightactor = hitresult.Actor; auto ft = rightactor->GetComponentByClass(UFlockAIMoveToComponent::StaticClass()); if (ft) { movespeed = SLOWSPEED; roatationspeed = SLOWROTATION; b_rb = true; } } } } void UFlockAIMoveToComponent::timerworku() { { ///////////////////////////////////////////////////////////////////////////////////// ////////////up #define UPDIS 3 FVector starpoint = Owner->GetActorLocation(); FVector director = Owner->GetActorUpVector(); FVector endpoint = starpoint + (ownerbound.Y * UPDIS * director); FVector HalfSize = FVector(ownerbound.X, ownerbound.Y, 5); TArray<AActor*> actorarray; FHitResult hitresult; bool b = UKismetSystemLibrary::BoxTraceSingle(this, starpoint, endpoint, HalfSize, Owner->GetActorForwardVector().Rotation(), ETraceTypeQuery::TraceTypeQuery2, true, actorarray, EDrawDebugTrace::Type::None, hitresult, true, FLinearColor::Red, FLinearColor::Green, 5.0f); if (b) { upactor = hitresult.Actor; auto ft = upactor->GetComponentByClass(UFlockAIMoveToComponent::StaticClass()); if (ft) { movespeed = SLOWSPEED; roatationspeed = SLOWROTATION; b_ub = true; } } } } void UFlockAIMoveToComponent::timerwork() { if (AILeader) { //UKismetMathLibrary::FindLookAtRotation(Owner->GetActorLocation(), AILeader->GetActorLocation()); //UKismetMathLibrary::RLerp(Owner->GetActorRotation(), UKismetMathLibrary::FindLookAtRotation(Owner->GetActorLocation(), AILeader->GetActorLocation()),0.005f,true); auto forwarddetected = [=]() { #define FORWARDDIS 1.5 FVector starpoint = Owner->GetActorLocation(); FVector director = Owner->GetActorForwardVector(); FVector endpoint = starpoint + (ownerbound.X * FORWARDDIS * director); FVector HalfSize = FVector(5, ownerbound.Y, ownerbound.Z); TArray<AActor*> actorarray; FHitResult hitresult; bool b = UKismetSystemLibrary::BoxTraceSingle(this, starpoint, endpoint, HalfSize, director.Rotation(), ETraceTypeQuery::TraceTypeQuery2, true, actorarray, EDrawDebugTrace::Type::None, hitresult, true, FLinearColor::Red, FLinearColor::Green, 5.0f); if (b) { forwardactor = hitresult.Actor; auto ft = forwardactor->GetComponentByClass(UFlockAIMoveToComponent::StaticClass()); auto ft1 = forwardactor->GetComponentByClass(UFlockAIEnemyComponent::StaticClass()); if (ft) { movespeed = SLOWSPEED; roatationspeed = SLOWROTATION; forwardblockgoalrotation = Owner->GetTransform().TransformRotation(FRotator(0, FMath::RandRange(-20, 2), FMath::RandRange(-20, 2)).Quaternion()).Rotator(); b_fb = true; } else if (ft1) { movespeed = FASTSPEED; roatationspeed = FASTROTATION; forwardblockgoalrotation = Owner->GetTransform().TransformRotation(FRotator(0, FMath::RandRange(-90, -30), FMath::RandRange(-90, -30)).Quaternion()).Rotator(); b_fb = true; } } }; auto rightdetected = [=]() { #define RIGHTDIS 3 FVector starpoint = Owner->GetActorLocation(); FVector director = Owner->GetActorRightVector(); FVector endpoint = starpoint + (ownerbound.Y * RIGHTDIS * director); FVector HalfSize = FVector(ownerbound.X, 5, ownerbound.Z); TArray<AActor*> actorarray; FHitResult hitresult; bool b = UKismetSystemLibrary::BoxTraceSingle(this, starpoint, endpoint, HalfSize, Owner->GetActorForwardVector().Rotation(), ETraceTypeQuery::TraceTypeQuery2, true, actorarray, EDrawDebugTrace::Type::None, hitresult, true, FLinearColor::Red, FLinearColor::Green, 5.0f); if (b) { rightactor = hitresult.Actor; auto ft = rightactor->GetComponentByClass(UFlockAIMoveToComponent::StaticClass()); if (ft) { movespeed = SLOWSPEED; roatationspeed = SLOWROTATION; b_rb = true; } } }; auto updetected = [=]() { { ///////////////////////////////////////////////////////////////////////////////////// ////////////up #define UPDIS 3 FVector starpoint = Owner->GetActorLocation(); FVector director = Owner->GetActorUpVector(); FVector endpoint = starpoint + (ownerbound.Y * UPDIS * director); FVector HalfSize = FVector(ownerbound.X, ownerbound.Y, 5); TArray<AActor*> actorarray; FHitResult hitresult; bool b = UKismetSystemLibrary::BoxTraceSingle(this, starpoint, endpoint, HalfSize, Owner->GetActorForwardVector().Rotation(), ETraceTypeQuery::TraceTypeQuery2, true, actorarray, EDrawDebugTrace::Type::None, hitresult, true, FLinearColor::Red, FLinearColor::Green, 5.0f); if (b) { upactor = hitresult.Actor; auto ft = upactor->GetComponentByClass(UFlockAIMoveToComponent::StaticClass()); if (ft) { movespeed = SLOWSPEED; roatationspeed = SLOWROTATION; b_ub = true; } } } }; forwarddetected(); rightdetected(); updetected(); if (b_fb) { FRotator currentrotation = Owner->GetActorRotation(); if ((currentrotation - forwardblockgoalrotation).IsNearlyZero(1.5)) { b_fb = false; } else { Owner->SetActorRotation( UKismetMathLibrary::RLerp( currentrotation, forwardblockgoalrotation, roatationspeed * 0.005f, true ) ); } movespeed = SLOWSPEED; roatationspeed = SLOWROTATION; } switch (state) { case AIMoveStatus::normal: Owner->SetActorRotation( UKismetMathLibrary::RLerp( Owner->GetActorRotation(), UKismetMathLibrary::FindLookAtRotation(Owner->GetActorLocation(), AILeader->GetActorLocation()), roatationspeed * 0.005f, true ) ); if (b_fb || b_rb || b_ub) { state = AIMoveStatus::avoid; } break; case AIMoveStatus::avoid: if (b_rb) { Owner->AddActorWorldOffset(-Owner->GetActorRightVector() * turnspeed * FMath::FRand()); movespeed = FMath::RandRange(SLOWSPEED, SLOWSPEED + 1); if (rightmovecounter++ > 5) { b_rb = false; rightmovecounter = 0; } } if (b_ub) { Owner->AddActorWorldOffset(-Owner->GetActorUpVector() * turnspeed * FMath::FRand()); movespeed = FMath::RandRange(SLOWSPEED, SLOWSPEED + 1); if (rightmovecounter++ > 5) { b_ub = false; upmovecounter = 0; } } if (b_fb || b_rb || b_ub) { } else { movespeed = NORMALSPEED; roatationspeed = NORMALROTATION; state = AIMoveStatus::normal; } break; default: break; } if (FVector::Dist(Owner->GetActorLocation(), AILeader->GetActorLocation()) > keepdistance) { Owner->AddActorWorldOffset(Owner->GetActorForwardVector() * movespeed); } else { } } } //void UFlockAIMoveToComponent::threadwork() //{ // while (true) // { // FPlatformProcess::Sleep(0.05); // if (AILeader) // { // //UKismetMathLibrary::FindLookAtRotation(Owner->GetActorLocation(), AILeader->GetActorLocation()); // // //UKismetMathLibrary::RLerp(Owner->GetActorRotation(), UKismetMathLibrary::FindLookAtRotation(Owner->GetActorLocation(), AILeader->GetActorLocation()),0.005f,true); // auto forwarddetected = [=]() // { // //#define FORWARDDIS 1.5 // FVector starpoint = Owner->GetActorLocation(); // FVector director = Owner->GetActorForwardVector(); // FVector endpoint = starpoint + (ownerbound.X * FORWARDDIS * director); // FVector HalfSize = FVector(5, ownerbound.Y, ownerbound.Z); // TArray<AActor*> actorarray; // FHitResult hitresult; // bool b = UKismetSystemLibrary::BoxTraceSingle(this, starpoint, endpoint, HalfSize, director.Rotation(), // ETraceTypeQuery::TraceTypeQuery2, true, actorarray, // EDrawDebugTrace::Type::None, hitresult, true, // FLinearColor::Red, FLinearColor::Green, 5.0f); // if (b) // { // forwardactor = hitresult.Actor; // auto ft = forwardactor->GetComponentByClass(UFlockAIMoveToComponent::StaticClass()); // auto ft1 = forwardactor->GetComponentByClass(UFlockAIEnemyComponent::StaticClass()); // if (ft) // { // movespeed = SLOWSPEED; // roatationspeed = SLOWROTATION; // // forwardblockgoalrotation = Owner->GetTransform().TransformRotation(FRotator(0, FMath::RandRange(-20, 2), FMath::RandRange(-20, 2)).Quaternion()).Rotator(); // b_fb = true; // } // else if (ft1) // { // movespeed = FASTSPEED; // roatationspeed = FASTROTATION; // // forwardblockgoalrotation = Owner->GetTransform().TransformRotation(FRotator(0, FMath::RandRange(-90, -30), FMath::RandRange(-90, -30)).Quaternion()).Rotator(); // b_fb = true; // } // // } // }; // auto rightdetected = [=]() { // //#define RIGHTDIS 3 // // FVector starpoint = Owner->GetActorLocation(); // FVector director = Owner->GetActorRightVector(); // FVector endpoint = starpoint + (ownerbound.Y * RIGHTDIS * director); // FVector HalfSize = FVector(ownerbound.X, 5, ownerbound.Z); // TArray<AActor*> actorarray; // FHitResult hitresult; // bool b = UKismetSystemLibrary::BoxTraceSingle(this, starpoint, endpoint, HalfSize, Owner->GetActorForwardVector().Rotation(), // ETraceTypeQuery::TraceTypeQuery2, true, actorarray, // EDrawDebugTrace::Type::None, hitresult, true, // FLinearColor::Red, FLinearColor::Green, 5.0f); // if (b) // { // rightactor = hitresult.Actor; // auto ft = rightactor->GetComponentByClass(UFlockAIMoveToComponent::StaticClass()); // if (ft) // { // movespeed = SLOWSPEED; // roatationspeed = SLOWROTATION; // b_rb = true; // } // // } // }; // auto updetected = [=]() { // { // ///////////////////////////////////////////////////////////////////////////////////// // ////////////up //#define UPDIS 3 // FVector starpoint = Owner->GetActorLocation(); // FVector director = Owner->GetActorUpVector(); // FVector endpoint = starpoint + (ownerbound.Y * UPDIS * director); // FVector HalfSize = FVector(ownerbound.X, ownerbound.Y, 5); // TArray<AActor*> actorarray; // FHitResult hitresult; // bool b = UKismetSystemLibrary::BoxTraceSingle(this, starpoint, endpoint, HalfSize, Owner->GetActorForwardVector().Rotation(), // ETraceTypeQuery::TraceTypeQuery2, true, actorarray, // EDrawDebugTrace::Type::None, hitresult, true, // FLinearColor::Red, FLinearColor::Green, 5.0f); // if (b) // { // upactor = hitresult.Actor; // auto ft = upactor->GetComponentByClass(UFlockAIMoveToComponent::StaticClass()); // if (ft) // { // movespeed = SLOWSPEED; // roatationspeed = SLOWROTATION; // b_ub = true; // } // } // } // }; // //AsyncTask( // // ENamedThreads::GameThread, // // [=]() // // { // forwarddetected(); // rightdetected(); // updetected(); // AsyncTask( // ENamedThreads::GameThread, // [=]() // { // if (b_fb) // { // FRotator currentrotation = Owner->GetActorRotation(); // if ((currentrotation - forwardblockgoalrotation).IsNearlyZero(1.5)) // { // b_fb = false; // } // else // { // Owner->SetActorRotation( // UKismetMathLibrary::RLerp( // currentrotation, // forwardblockgoalrotation, // roatationspeed * 0.005f, // true // ) // ); // } // movespeed = SLOWSPEED; // roatationspeed = SLOWROTATION; // } // // // switch (state) // { // case AIMoveStatus::normal: // // Owner->SetActorRotation( // UKismetMathLibrary::RLerp( // Owner->GetActorRotation(), // UKismetMathLibrary::FindLookAtRotation(Owner->GetActorLocation(), AILeader->GetActorLocation()), // roatationspeed * 0.005f, // true // ) // ); // if (b_fb || b_rb || b_ub) // { // state = AIMoveStatus::avoid; // } // break; // case AIMoveStatus::avoid: // if (b_rb) // { // Owner->AddActorWorldOffset(-Owner->GetActorRightVector() * turnspeed * FMath::FRand()); // movespeed = FMath::RandRange(SLOWSPEED, SLOWSPEED + 1); // if (rightmovecounter++ > 5) // { // b_rb = false; // rightmovecounter = 0; // } // // } // if (b_ub) // { // Owner->AddActorWorldOffset(-Owner->GetActorUpVector() * turnspeed * FMath::FRand()); // movespeed = FMath::RandRange(SLOWSPEED, SLOWSPEED + 1); // if (rightmovecounter++ > 5) // { // b_ub = false; // // upmovecounter = 0; // } // } // if (b_fb || b_rb || b_ub) // { // } // else // { // movespeed = NORMALSPEED; // roatationspeed = NORMALROTATION; // state = AIMoveStatus::normal; // } // // break; // default: // break; // } // if (FVector::Dist(Owner->GetActorLocation(), AILeader->GetActorLocation()) > keepdistance) // { // Owner->AddActorWorldOffset(Owner->GetActorForwardVector() * movespeed); // } // else // { // // } // // } // // ); // // } // // } // //} // Called every frame void UFlockAIMoveToComponent::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) { Super::TickComponent(DeltaTime, TickType, ThisTickFunction); if (AILeader) { //UKismetMathLibrary::FindLookAtRotation(Owner->GetActorLocation(), AILeader->GetActorLocation()); //UKismetMathLibrary::RLerp(Owner->GetActorRotation(), UKismetMathLibrary::FindLookAtRotation(Owner->GetActorLocation(), AILeader->GetActorLocation()),0.005f,true); // auto forwarddetected = [=]() // { // //#define FORWARDDIS 1.5 // FVector starpoint = Owner->GetActorLocation(); // FVector director = Owner->GetActorForwardVector(); // FVector endpoint = starpoint + (ownerbound.X * FORWARDDIS * director); // FVector HalfSize = FVector(5, ownerbound.Y, ownerbound.Z); // TArray<AActor*> actorarray; // FHitResult hitresult; // bool b = UKismetSystemLibrary::BoxTraceSingle(this, starpoint, endpoint, HalfSize, director.Rotation(), // ETraceTypeQuery::TraceTypeQuery2, true, actorarray, // EDrawDebugTrace::Type::None, hitresult, true, // FLinearColor::Red, FLinearColor::Green, 5.0f); // if (b) // { // forwardactor = hitresult.Actor; // auto ft = forwardactor->GetComponentByClass(UFlockAIMoveToComponent::StaticClass()); // auto ft1 = forwardactor->GetComponentByClass(UFlockAIEnemyComponent::StaticClass()); // if (ft) // { // movespeed = SLOWSPEED; // roatationspeed = SLOWROTATION; // // forwardblockgoalrotation = Owner->GetTransform().TransformRotation(FRotator(0, FMath::RandRange(-20, 2), FMath::RandRange(-20, 2)).Quaternion()).Rotator(); // b_fb = true; // } // else if (ft1) // { // movespeed = FASTSPEED; // roatationspeed = FASTROTATION; // // forwardblockgoalrotation = Owner->GetTransform().TransformRotation(FRotator(0, FMath::RandRange(-90, -30), FMath::RandRange(-90, -30)).Quaternion()).Rotator(); // b_fb = true; // } // // } // }; // auto rightdetected = [=]() { // //#define RIGHTDIS 3 // // FVector starpoint = Owner->GetActorLocation(); // FVector director = Owner->GetActorRightVector(); // FVector endpoint = starpoint + (ownerbound.Y * RIGHTDIS * director); // FVector HalfSize = FVector(ownerbound.X, 5, ownerbound.Z); // TArray<AActor*> actorarray; // FHitResult hitresult; // bool b = UKismetSystemLibrary::BoxTraceSingle(this, starpoint, endpoint, HalfSize, Owner->GetActorForwardVector().Rotation(), // ETraceTypeQuery::TraceTypeQuery2, true, actorarray, // EDrawDebugTrace::Type::None, hitresult, true, // FLinearColor::Red, FLinearColor::Green, 5.0f); // if (b) // { // rightactor = hitresult.Actor; // auto ft = rightactor->GetComponentByClass(UFlockAIMoveToComponent::StaticClass()); // if (ft) // { // movespeed = SLOWSPEED; // roatationspeed = SLOWROTATION; // b_rb = true; // } // // } // }; // auto updetected = [=]() { // { // ///////////////////////////////////////////////////////////////////////////////////// // ////////////up //#define UPDIS 3 // FVector starpoint = Owner->GetActorLocation(); // FVector director = Owner->GetActorUpVector(); // FVector endpoint = starpoint + (ownerbound.Y * UPDIS * director); // FVector HalfSize = FVector(ownerbound.X, ownerbound.Y, 5); // TArray<AActor*> actorarray; // FHitResult hitresult; // bool b = UKismetSystemLibrary::BoxTraceSingle(this, starpoint, endpoint, HalfSize, Owner->GetActorForwardVector().Rotation(), // ETraceTypeQuery::TraceTypeQuery2, true, actorarray, // EDrawDebugTrace::Type::None, hitresult, true, // FLinearColor::Red, FLinearColor::Green, 5.0f); // if (b) // { // upactor = hitresult.Actor; // auto ft = upactor->GetComponentByClass(UFlockAIMoveToComponent::StaticClass()); // if (ft) // { // movespeed = SLOWSPEED; // roatationspeed = SLOWROTATION; // b_ub = true; // } // } // } // }; //forwarddetected(); //rightdetected(); //updetected(); if (b_fb) { FRotator currentrotation = Owner->GetActorRotation(); if ((currentrotation - forwardblockgoalrotation).IsNearlyZero(1.5)) { b_fb = false; } else { Owner->SetActorRotation( UKismetMathLibrary::RLerp( currentrotation, forwardblockgoalrotation, roatationspeed * 0.005f, true ) ); } movespeed = SLOWSPEED; roatationspeed = SLOWROTATION; } switch (state) { case AIMoveStatus::normal: Owner->SetActorRotation( UKismetMathLibrary::RLerp( Owner->GetActorRotation(), UKismetMathLibrary::FindLookAtRotation(Owner->GetActorLocation(), AILeader->GetActorLocation()), roatationspeed * 0.005f, true ) ); if (b_fb || b_rb || b_ub) { state = AIMoveStatus::avoid; } break; case AIMoveStatus::avoid: if (b_rb) { Owner->AddActorWorldOffset(-Owner->GetActorRightVector() * turnspeed * FMath::FRand()); movespeed = FMath::RandRange(SLOWSPEED, SLOWSPEED + 1); if (rightmovecounter++ > 5) { b_rb = false; rightmovecounter = 0; } } if (b_ub) { Owner->AddActorWorldOffset(-Owner->GetActorUpVector() * turnspeed * FMath::FRand()); movespeed = FMath::RandRange(SLOWSPEED, SLOWSPEED + 1); if (rightmovecounter++ > 5) { b_ub = false; upmovecounter = 0; } } if (b_fb || b_rb || b_ub) { } else { movespeed = NORMALSPEED; roatationspeed = NORMALROTATION; state = AIMoveStatus::normal; } break; case AIMoveStatus::idle: Owner->SetActorRotation( UKismetMathLibrary::RLerp( Owner->GetActorRotation(), idlerotation, roatationspeed * 0.005f, true ) ); Owner->AddActorWorldOffset(Owner->GetActorForwardVector() * movespeed); if (idlerotationcounter++ > 5) { idlerotationcounter = 0; movespeed = NORMALSPEED; roatationspeed = NORMALROTATION; state = AIMoveStatus::normal; } break; default: break; } //if (state == AIMoveStatus::idle||FVector::Dist(Owner->GetActorLocation(), AILeader->GetActorLocation()) > keepdistance) { Owner->AddActorWorldOffset(Owner->GetActorForwardVector() * movespeed); } //else //{ // movespeed = SLOWSPEED; // roatationspeed = SLOWROTATION; // state = AIMoveStatus::idle; // idlerotation = Owner->GetTransform().TransformRotation(FRotator(0, FMath::RandRange(-10, -2), FMath::RandRange(5, 10)).Quaternion()).Rotator(); //} } // ... }
[ "liupanfengfreedom@gmail.com" ]
liupanfengfreedom@gmail.com
43044e2517b8bc5cf1943fb3b2821c9aa4bd4445
66862c422fda8b0de8c4a6f9d24eced028805283
/slambook2/3rdparty/opencv-3.3.0/modules/ml/test/test_precomp.hpp
3147a9d96caad1ef75354d71044963f89516c2df
[ "MIT", "BSD-3-Clause" ]
permissive
zhh2005757/slambook2_in_Docker
57ed4af958b730e6f767cd202717e28144107cdb
f0e71327d196cdad3b3c10d96eacdf95240d528b
refs/heads/main
2023-09-01T03:26:37.542232
2021-10-27T11:45:47
2021-10-27T11:45:47
416,666,234
17
6
MIT
2021-10-13T09:51:00
2021-10-13T09:12:15
null
UTF-8
C++
false
false
2,528
hpp
#ifdef __GNUC__ # pragma GCC diagnostic ignored "-Wmissing-declarations" # if defined __clang__ || defined __APPLE__ # pragma GCC diagnostic ignored "-Wmissing-prototypes" # pragma GCC diagnostic ignored "-Wextra" # endif #endif #ifndef __OPENCV_TEST_PRECOMP_HPP__ #define __OPENCV_TEST_PRECOMP_HPP__ #include <iostream> #include <map> #include "opencv2/ts.hpp" #include "opencv2/ml.hpp" #include "opencv2/core/core_c.h" #define CV_NBAYES "nbayes" #define CV_KNEAREST "knearest" #define CV_SVM "svm" #define CV_EM "em" #define CV_ANN "ann" #define CV_DTREE "dtree" #define CV_BOOST "boost" #define CV_RTREES "rtrees" #define CV_ERTREES "ertrees" #define CV_SVMSGD "svmsgd" enum { CV_TRAIN_ERROR=0, CV_TEST_ERROR=1 }; using cv::Ptr; using cv::ml::StatModel; using cv::ml::TrainData; using cv::ml::NormalBayesClassifier; using cv::ml::SVM; using cv::ml::KNearest; using cv::ml::ParamGrid; using cv::ml::ANN_MLP; using cv::ml::DTrees; using cv::ml::Boost; using cv::ml::RTrees; using cv::ml::SVMSGD; class CV_MLBaseTest : public cvtest::BaseTest { public: CV_MLBaseTest( const char* _modelName ); virtual ~CV_MLBaseTest(); protected: virtual int read_params( CvFileStorage* fs ); virtual void run( int startFrom ); virtual int prepare_test_case( int testCaseIdx ); virtual std::string& get_validation_filename(); virtual int run_test_case( int testCaseIdx ) = 0; virtual int validate_test_results( int testCaseIdx ) = 0; int train( int testCaseIdx ); float get_test_error( int testCaseIdx, std::vector<float> *resp = 0 ); void save( const char* filename ); void load( const char* filename ); Ptr<TrainData> data; std::string modelName, validationFN; std::vector<std::string> dataSetNames; cv::FileStorage validationFS; Ptr<StatModel> model; std::map<int, int> cls_map; int64 initSeed; }; class CV_AMLTest : public CV_MLBaseTest { public: CV_AMLTest( const char* _modelName ); virtual ~CV_AMLTest() {} protected: virtual int run_test_case( int testCaseIdx ); virtual int validate_test_results( int testCaseIdx ); }; class CV_SLMLTest : public CV_MLBaseTest { public: CV_SLMLTest( const char* _modelName ); virtual ~CV_SLMLTest() {} protected: virtual int run_test_case( int testCaseIdx ); virtual int validate_test_results( int testCaseIdx ); std::vector<float> test_resps1, test_resps2; // predicted responses for test data std::string fname1, fname2; }; #endif
[ "594353397@qq.com" ]
594353397@qq.com
3ae949e14e96da762a790046b73dbdf6976b187b
8d3d080869d357b6afb06783c435fb5f4010d3ab
/Evolutionary_Computation/hw1/main.cpp
133344376307d9da5c118f60590d83d8f02791f0
[]
no_license
jxcodetw/NCTU_HW
1ca53986a44672744010bbfb2a6ff85b9823da78
fd9f3ee6cdd01e531ec2e0eb632b4d08ba8c5be3
refs/heads/master
2022-10-07T21:17:39.362080
2020-06-10T15:50:29
2020-06-10T15:50:29
271,316,136
1
0
null
null
null
null
UTF-8
C++
false
false
2,680
cpp
#include <iostream> #include <fstream> #include <vector> #include <array> const int BIT_LEN = 50; const int POP_SIZE = 200; const int ITERATION = 100; typedef std::array<bool, BIT_LEN> Gene; std::array<Gene, POP_SIZE> creatures, mating_pool; std::array<double, POP_SIZE> fit; double best_fit, sum_fit; std::vector<int> max_fitness_log; double base_fitness = 0; double fitness(Gene &g) { double f = base_fitness; for(int i=0;i<BIT_LEN;++i) { if (g[i] == true) { f += 1.0; } } return f; } void crossover() { if (POP_SIZE % 2 == 1) { std::cout << "crossover warning" << std::endl; return; } for(int i=0;i<POP_SIZE;i+=2) { int cut = rand() % (BIT_LEN - 2); for(int j=0;j<cut;++j) { bool tmp = mating_pool[i][j]; mating_pool[i][j] = mating_pool[i+1][j]; mating_pool[i+1][j] = tmp; } } } void roulette_wheel_selection() { static std::array<double, POP_SIZE> wheel; double acc = 0; for(int i=0;i<POP_SIZE;++i) { acc += fit[i]; wheel[i] = acc / sum_fit; } for(int i=0;i<POP_SIZE;++i) { double p = ((double)rand() / (double)RAND_MAX); for(int j=0;j<POP_SIZE;++j) { if (p < wheel[j]) { mating_pool[i] = creatures[j]; break; } } } } void tournament_selection() { for(int i=0;i<POP_SIZE;++i) { int p = rand() % POP_SIZE; int q = rand() % POP_SIZE; if (fit[p] > fit[q]) { mating_pool[i] = creatures[p]; } else { mating_pool[i] = creatures[q]; } } } void replacement() { creatures = mating_pool; } void udpate_fitness() { best_fit = -1; sum_fit = 0; for(int i=0;i<POP_SIZE;++i) { fit[i] = fitness(creatures[i]); best_fit = std::max(best_fit, fit[i]); sum_fit += fit[i]; } max_fitness_log.push_back(best_fit); } void print_status(int gen) { std::cout << "Generation " << gen << ": " << best_fit << std::endl; } void init() { for(int i=0;i<POP_SIZE;++i) { for(int j=0;j<BIT_LEN;++j) { creatures[i][j] = rand() % 1000 > 500; } } udpate_fitness(); } void save_log(std::string filename) { std::fstream fp; fp.open(filename, std::ios::out); for(int i=0;i<max_fitness_log.size();++i) { fp << max_fitness_log[i] << std::endl; } fp.close(); } int main(int argc, char *argv[]) { if (argc > 3) { base_fitness = std::stod(argv[3]); } bool is_tournament = false; if (argc > 4) { is_tournament = true; } srand(time(0)+std::stoul(argv[1])); init(); print_status(0); for(int i=1;i<=ITERATION;++i) { // selection if (is_tournament) { tournament_selection(); } else { roulette_wheel_selection(); } crossover(); // pc = 1.0 replacement(); // generational udpate_fitness(); print_status(i); } if (argc > 2) { save_log(argv[2]); } return 0; }
[ "jxcode.tw@gmail.com" ]
jxcode.tw@gmail.com
6d7a7ea69749a7073afa44ce5b5d629a2546c44a
268fe34dc7633b499e4c331e1d75c2280a91efb6
/main.cpp
86ab6a235bd891d246ddd7307edb25d59c0e7b2d
[]
no_license
klasing/QtDbProgramming_Lesson52
5b8ca8c71d7b9720d4afe361d29f0ed40e1ecd9d
4cd976ede6ec811b1781d72073d538a3385bd245
refs/heads/master
2020-12-25T14:48:09.930057
2016-07-08T13:24:17
2016-07-08T13:24:17
62,890,223
0
0
null
null
null
null
UTF-8
C++
false
false
1,132
cpp
#include <QCoreApplication> #include <QtSql> #include <QDebug> #include <QString> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QString serverName = "(localdb)\\Projects"; QString dbName = "test"; QSqlDatabase db = QSqlDatabase::addDatabase("QODBC"); db.setConnectOptions(); QString dsn = QString("Driver={SQL Server Native Client 11.0};Server=%1;Database=%2;Uid=odbc;Pwd=odbc;").arg(serverName).arg(dbName); db.setDatabaseName(dsn); if (db.open()) { qDebug() << "Opened!"; // create a query to investigate a table in the SQL Server (user odbc has the sysadmin role!) QSqlQuery qry; if (qry.exec("SELECT * FROM [test].[dbo].[people]")) { while (qry.next()) { qDebug() << qry.value(0).toInt() << " " << qry.value(1).toString() << " " << qry.value(2).toString(); } } else { qDebug() << "Error: " << db.lastError().text(); } qDebug() << "Closing..."; db.close(); } else { qDebug() << "Error: " << db.lastError().text(); } return a.exec(); }
[ "klasing1959@gmail.com" ]
klasing1959@gmail.com
09c542194c7c8080a7b3481966a957f97027a29a
41201958df63dac0d60e0df10d6b67677c34bb3b
/PROBLEMS on LL/occurance_in_ll.cpp
f57b83b12bf243add18bd8ad8c283bf651a33d4b
[]
no_license
uttkarsh2406/LINK_LIST
fb362178649b1a56fbcd48b917d880dc2ee5cc66
541dfa14571f7ba9e9047ebfdf89174137c28cca
refs/heads/main
2023-05-06T06:07:17.632206
2021-06-01T19:42:07
2021-06-01T19:42:07
366,806,125
2
0
null
null
null
null
UTF-8
C++
false
false
1,748
cpp
// { Driver Code Starts #include<stdio.h> #include<stdlib.h> #include<iostream> using namespace std; /* Link list node */ struct node { int data; struct node* next; node(int x){ data = x; next = NULL; } }*head; void insert() { int n,i,value; struct node *temp; scanf("%d",&n); for(i=0;i<n;i++) { scanf("%d",&value); if(i==0) { head=new node(value); head->next=NULL; temp=head; continue; } else { temp->next= new node(value); temp=temp->next; temp->next=NULL; } } } /* Function to print linked list */ void printList(struct node *node) { while (node != NULL) { printf("%d ", node->data); node = node->next; } printf("\n"); } // } Driver Code Ends /* Node is defined as struct node { int data; struct node* next; node(int x){ data = x; next = NULL; } }*head; */ class Solution { public: int count(struct node* head, int search_for) { //add your code here struct node *temp=head; int count=0; while(temp!=NULL){ if(temp->data==search_for){ count++; } temp=temp->next; } return count; } }; // { Driver Code Starts. /* Drier program to test above function*/ int main(void) { /* Start with the empty list */ int t,k,n,value; /* Created Linked list is 1->2->3->4->5->6->7->8->9 */ scanf("%d",&t); while(t--) { insert(); scanf("%d",&k); Solution ob; value=ob.count(head, k); printf("%d\n",value); } return(0); } // } Driver Code Ends
[ "74823692+uttkarsh2406@users.noreply.github.com" ]
74823692+uttkarsh2406@users.noreply.github.com
1e85f570de4c3a2a7665c276416b36d6e61a028c
e3a6f66d5ae8aef7b73d3f6064332f90a2a84df1
/src/bootloader/FwSelector/FwSelector.h
a31c9a0bd85cfcb03a49f9e165b944d6c56db291
[ "Apache-2.0", "LicenseRef-scancode-proprietary-license", "GPL-3.0-or-later", "BSD-3-Clause", "GCC-exception-3.1" ]
permissive
rv0/OpenDeck
03d1d70164688d5468b6bc353543eb5be1c19c1e
24256dd2cbf5dfc4cf8b48d1aaeff3da12b7ec7e
refs/heads/master
2022-01-25T13:15:18.531242
2022-01-23T14:02:55
2022-01-23T18:46:11
214,882,905
0
0
Apache-2.0
2019-10-13T19:44:21
2019-10-13T19:44:20
null
UTF-8
C++
false
false
2,082
h
/* Copyright 2015-2022 Igor Petrovic Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #pragma once #include <inttypes.h> class FwSelector { public: /// List of all possible firmwares which can be loaded and their magic values. /// Bootloader will load a firmware based on read value. /// Location of this value is board-specific. enum class fwType_t : uint32_t { application = 0xFF, bootloader = 0x47 }; class HWA { public: virtual uint8_t magicBootValue() = 0; virtual void setMagicBootValue(uint8_t value) = 0; virtual void load(fwType_t fwType) = 0; virtual void appAddrBoundary(uint32_t& first, uint32_t& last) = 0; virtual bool isHWtriggerActive() = 0; virtual uint8_t readFlash(uint32_t address) = 0; }; FwSelector(HWA& hwa) : _hwa(hwa) {} void select(); private: /// List of all possible bootloader triggers. enum class btldrTrigger_t : uint8_t { software, hardware, all, none }; /// Verifies if the programmed flash is valid. /// \return True if valid, false otherwise. bool isAppValid(); /// Reads the state of the button responsible for hardware bootloader entry. /// returns: True if pressed, false otherwise. If bootloader button doesn't exist, /// function will return false. bool isHWtriggerActive(); HWA& _hwa; };
[ "2544094+paradajz@users.noreply.github.com" ]
2544094+paradajz@users.noreply.github.com
36867e0574928b3885cba94606319f86d1f84a40
e6bac3cd8be920131d5690c6ec36a72d19575a2a
/LetUsSaveThePrincess/开发代码9.14/一起来救公主吧/kingCanyon.h
08f7604b138c97d6c5ac787811fc9850ab72dd36
[]
no_license
Histra/LetUsSaveThePrincess
f34f365d0108a482473d7c22c36adb887c0ccf01
cd148f1840d0a761d3d73ad3993f49f032df4de7
refs/heads/master
2020-07-25T20:58:57.922392
2019-09-14T10:47:22
2019-09-14T10:47:22
208,422,531
0
0
null
null
null
null
GB18030
C++
false
false
5,040
h
#pragma once #include "Monster.h" #include "Monster_2.h" HANDLE hConsole_kingCanyon; class kingCanyon : public Place{ public: kingCanyon(){ getMessage(); } void conversation_with_npc(){ hConsole_kingCanyon = GetStdHandle(STD_OUTPUT_HANDLE);//字体颜色 SetConsoleTextAttribute(hConsole_kingCanyon,2); cout<< "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~【农\t药\t峡\t谷】~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" <<endl; int tempX, tempY; getxy(tempX, tempY); SetConsoleTextAttribute(hConsole_kingCanyon,11); //Sleep(1000); cout << "\t" << npc1Name << "(Lv." << npc1Lv << "):" << endl; cout << "\t\t羁绊是什么意思呢?(自言自语中)" << endl; char tempChar; getchar(); tempChar = getchar(); cout << "\t狗蛋儿(Lv." << protagonist.showLevel() << "):" << endl; cout << "\t\t小......小姐 ,这样不好吧(听成了生殖器官的狗蛋)" << endl; tempChar = getchar(); clear_the_conversation(tempX, tempY); cout << "\t" << npc1Name << "(Lv." << npc1Lv << "):" << endl; cout <<"\t\t呵呵(银铃般的笑声),远道而来的客人,要来和妲己玩耍么"<<endl; tempChar = getchar(); cout << "\t狗蛋儿(Lv." << protagonist.showLevel() << "):" << endl; cout << "\t\t (一脸猪哥样)好啊好啊" << endl; tempChar = getchar(); clear_the_conversation(tempX, tempY); cout << "\t" << npc1Name << "(Lv." << npc1Lv << "):" << endl; cout << "\t\t可是和我玩耍的人必须是脚踏七彩祥云的盖世英雄,你愿意接受妲己的考验么?" <<endl; tempChar = getchar(); cout << "\t狗蛋儿(Lv." << protagonist.showLevel() << "): " << endl; cout << "\t\t这......这(有点犹豫)" ; tempChar = getchar(); clear_the_conversation(tempX, tempY); cout << "\t" << npc1Name << "(Lv." << npc1Lv << "):" << endl; cout << "\t\t如果通过了英雄的考验,妲己会给予你一样宝物呦" <<endl; cout << "[系统消息]叮,完成任务可获得;"<<endl; cout << "\t宠物:光精灵"; cout << "\t称号:带妹勇者"<<endl; tempChar = getchar(); cout << "\t狗蛋儿(Lv." << protagonist.showLevel() << "): " << endl; cout << "\t\t(一听到有如此丰厚的奖励,毫无犹豫的答应下来)no problem" ; tempChar = getchar(); clear_the_conversation(tempX, tempY); cout << "\t" << npc1Name << "(Lv." << npc1Lv << "):" << endl; cout <<"\t\t客人,去通过那无数英雄的陨落地---农药峡谷吧" <<endl; tempChar = getchar(); cout << "\t狗蛋儿(Lv." << protagonist.showLevel() << "): " << endl; cout << "\t\t(小心翼翼地迈入峡谷之中,不知道前方有多危险,能让妲己作为考验)" ; tempChar = getchar(); SetConsoleTextAttribute(hConsole_kingCanyon,10); cout << "[1.攻击]\n"; cout << "请选择______"; int tempChoose; cin >> tempChoose; if (tempChoose == 1){ int judge_live = 1; Monster_2 monster_2; monster_2.getMessage(); Fight <Monster_2> fight; fight.fighting(monster_2, judge_live); if (judge_live == 0){ fresh_village.conversation_with_npc1_npc2(); } } if (tempChoose == 2){ cout << "[系统消息]恭喜你狗蛋,成功逃跑!您真是跑得比兔子还快啊!" << endl; getchar(); char tempChar; tempChar= getchar(); system("CLS"); //print_menu(); } if (tempChoose == 3){ cout << "[系统消息]恭喜您!获得成就:怂的一B" << endl; protagonist.add_achievement("怂的一B"); getchar(); char tempChar; tempChar= getchar(); } //战斗结束 cout << "\t" << npc1Name << "(Lv." << npc1Lv << "):" << endl; cout <<"\t\t客人,我果然没有看错你,来陪妲己玩耍吧"<<endl; cout <<"[系统消息]恭喜您获得:最弱buff : 普通攻击 + 1"<<endl; protagonist.strength_plus(1); // protagonist.add_achievement("带妹勇者"); cout << "[系统消息](开发者觉得你有点儿可怜)获得经验+60, 金币+250" << endl; protagonist.experienceAmount_plus(60); packsack.possession_plus(250); getchar(); } void getMessage(){ //freshVillage_state = 1; ifstream file; file.open("kingCanyon_npc3.txt", ios_base :: in); if (file){ file >> npc1Name; file >> npc1Lv; } file.close(); } private: string npc1Name; int npc1Lv; };
[ "1497058369@qq.com" ]
1497058369@qq.com
5571cf2f69ac554b1148330bbdb65b3dc9d3c5f7
8465159705a71cede7f2e9970904aeba83e4fc6c
/src_change_the_layout/core/basicfb.h
590d57a7b20fbc4fae6b1152d330adc56c376cdd
[]
no_license
TuojianLYU/forte_IO_OPCUA_Integration
051591b61f902258e3d0d6608bf68e2302f67ac1
4a3aed7b89f8a7d5f9554ac5937cf0a93607a4c6
refs/heads/main
2023-08-20T16:17:58.147635
2021-10-27T05:34:43
2021-10-27T05:34:43
419,704,624
1
0
null
null
null
null
UTF-8
C++
false
false
4,284
h
/******************************************************************************* * Copyright (c) 2005 - 2015 Profactor GmbH, ACIN, fortiss GmbH * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0. * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * Thomas Strasser, Gunnar Grabmair, Alois Zoitl, Gerhard Ebenhofer, Ingo Hegny * - initial implementation and rework communication infrastructure *******************************************************************************/ #ifndef _BASICFB_H_ #define _BASICFB_H_ #include "funcbloc.h" #ifndef FORTE_BASIC_FB_DATA_ARRAY //with this check we can overwrite this define in a platform specific file (e.g., config.h) /*! Define that adds the data array to a Basic FB * May be overwritten by a platform specific version that adapts for example some alignment requirements */ #define FORTE_BASIC_FB_DATA_ARRAY(a_nNumEOs, a_nNumDIs, a_nNumDOs, a_nNumIntVars, a_nNumAdapters) \ union{ \ TForteByte m_anFBConnData[genFBConnDataSizeTemplate<a_nNumEOs, a_nNumDIs, a_nNumDOs>::value]; \ };\ union{ \ TForteByte m_anFBVarsData[genBasicFBVarsDataSizeTemplate<a_nNumDIs, a_nNumDOs, a_nNumIntVars, a_nNumAdapters>::value]; \ }; #endif /*!\ingroup CORE * \brief structure to hold the data needed for creating the internal vars * */ struct SInternalVarsInformation{ TPortId m_nNumIntVars; //!< Number of internal vars const CStringDictionary::TStringId * m_aunIntVarsNames; //!< List of the internalvarsnames const CStringDictionary::TStringId * m_aunIntVarsDataTypeNames; //!< List of the data type names for the internal vars }; /*!\ingroup CORE * * \brief Class for handling firmware basic function blocks. */ class CBasicFB : public CFunctionBlock{ public: /*!\brief The main constructur for a basic function block. */ CBasicFB(CResource *pa_poSrcRes, const SFBInterfaceSpec *pa_pstInterfaceSpec, const CStringDictionary::TStringId pa_nInstanceNameId, const SInternalVarsInformation *pa_pstVarInternals, TForteByte *pa_acFBConnData, TForteByte *pa_acBasicFBVarsData); virtual ~CBasicFB(); virtual CIEC_ANY* getVar(CStringDictionary::TStringId *paNameList, unsigned int paNameListSize); virtual EMGMResponse changeFBExecutionState(EMGMCommandType pa_unCommand); template<unsigned int ta_nNumDIs, unsigned int ta_nNumDOs, unsigned int ta_nNumIntVars, unsigned int ta_nNumAdapters = 0> struct genBasicFBVarsDataSizeTemplate{ enum { value = ((sizeof(TDataConnectionPtr) + sizeof(CIEC_ANY)) * ta_nNumIntVars + genFBVarsDataSizeTemplate<ta_nNumDIs, ta_nNumDOs, ta_nNumAdapters>::value) }; }; static size_t genBasicFBVarsDataSize(unsigned int pa_nNumDIs, unsigned int pa_nNumDOs, unsigned int pa_nNumIntVars, unsigned int pa_nNumAdapters = 0){ return ((sizeof(TDataConnectionPtr) + sizeof(CIEC_ANY)) * pa_nNumIntVars + genFBVarsDataSize(pa_nNumDIs, pa_nNumDOs, pa_nNumAdapters)); } ; protected: /*! \brief Get the internal variable with given number * * Attention this function will not perform any range checks on the pa_nVarIntNum parameter! * @param pa_nVarIntNum number of the internal variable starting with 0 * @return pointer to the internal variable */ CIEC_ANY *getVarInternal(unsigned int pa_nVarIntNum){ return m_aoInternals + pa_nVarIntNum; } CIEC_UINT m_nECCState; //! the current state of the ecc. start value is 0 = initial state id const SInternalVarsInformation * const cm_pstVarInternals; //!< struct holding the information on the internal vars. private: /*!\brief Get the pointer to a internal variable of the basic FB. * * \param pa_nInternalName StringId of the internal variable name. * \return Pointer to the internal variable or 0. */ CIEC_ANY *getInternalVar(CStringDictionary::TStringId pa_nInternalName); CIEC_ANY *m_aoInternals; //!< A list of pointers to the internal variables. #ifdef FORTE_FMU friend class fmuInstance; #endif //FORTE_FMU }; #endif /*_BASICFB_H_*/
[ "tuojianlyu@gmail.com" ]
tuojianlyu@gmail.com
d35c91709bbe28fed3382a6b9dfd83a476ac5bc8
cafc8bf6cabf11969399e876792908fe9c319bea
/pongping_read_level.cpp
4e16364403030b82e0e8a627756ade88b2b4db36
[]
no_license
wildrabbitt100/pongping
cbd8e1d4de8d08a8705755bbe9428265166e095b
64e5e5d84d40c0fc8992fb9d595753cb09bc5c5e
refs/heads/master
2020-04-13T22:35:14.963482
2019-04-12T19:57:34
2019-04-12T19:57:34
12,612,850
0
0
null
null
null
null
UTF-8
C++
false
false
31,141
cpp
/* * * * __________ __________ ____ ___ ____________ __________ __ ___ ___ ____________ * / __ /\ / ______ /\ / \ / /\ / ________/\ / __ /\ / /\ / \ / /\ / ________/\ * / /_/ / / / /\____/ / / / \ / / / / /\_______\/ / /_/ / / / / / / \ / / / / /\_______\/ * / ______/ / / / / / / / / /\ \ / / / / /_/______ / ______/ / / / / / /\ \ / / / / /_/______ * / /\_____\/ / /_/___/ / / / / /\ \/ / / /________ /\ / /\_____\/ / / / / / /\ \/ / / /________ /\ * /___/ / /_________/ / /___/ / \______/ / \_______/___/ / /___/ / /_/ / /___/ / \____/ / \_______/___/ / * \___\/ \_________\/ \___\/ \_____\/ \___\/ \___\/ \_\/ \___\/ \___\/ \___\/ * * * See readme.txt for copyright information. */ #include "pongping_headers/pongping_read_level_headers.h" /* read_level() : read a level return 0 for success, 1 for error. */ int OneGame::read_level() { const char *file_name = "game_data/levels_file.xml"; TiXmlDocument level_file( file_name ); TiXmlHandle hDoc(&level_file); TiXmlHandle hLevel(0), hLevelDefinition(0), hPongPingPolygon(0); TiXmlElement *pLevelDefinitionElement, *pElement, *pLevelElement, *pColorElement; int level_number; const char *s; int i1, i2, i3, i4, i5, i6, i7, i8, i9, i10; double f1, f2, f3; COULEUR colour; vector<COULEUR> colour_vector(0); int r, g, b; /*********************************************************************************/ #ifdef USE_LOG_FILE PPLOG(READ_LEVEL_READING_LEVEL); // say that level is being read #endif if(level_file.LoadFile() == false) { logfile << "Couldn't load " << file_name << endl << level_file.ErrorDesc() << endl; return 1; } #ifdef USE_LOG_FILE PPLOG(READ_LEVEL_LOADED_XML_FILE); #endif pLevelDefinitionElement = hDoc.FirstChild("level_definition_for_willam_labbetts_awesome_new_game" ).Element(); if(pLevelDefinitionElement == NULL) { logfile << "reading xml file - couldn't find a level_definition_for_willam_labbetts_awesome_new_game element.\n"; return 1; } hLevelDefinition = TiXmlHandle(pLevelDefinitionElement); pElement = hLevelDefinition.FirstChild("level").Element(); do { if( pElement->QueryIntAttribute( "level_number", &level_number) != TIXML_SUCCESS ) { logfile << "couldn't fins level_number attribute in level_number tag.\n\n"; return 1; } if(level_number == current_level) { break; } else { if((pElement = pElement->NextSiblingElement()) == NULL) { logfile << "couldn't find level " << current_level << "." << endl; return 1; } } } while(1); /* Found the right level */ #ifdef USE_LOG_FILE PPLOG(READ_LEVEL_FOUND_LEVEL); //PPLOGINT( #endif //logfile << "found the right level.\n" << level_number << "\n"; //eek(); hLevel = TiXmlHandle(pElement); if((pLevelElement = hLevel.FirstChild("task").Element()) == NULL || (s = pLevelElement->GetText()) == NULL) { return 1; } if(strlen(s) > 99) { logfile << "task string too long." << endl; eek(); } else { /* if(s != NULL) { printf(" s is not NULL.\n\n"); } */ //printf("copying string.\n\n"); //printf("string is <%s>", s); strcpy(task, s); } samples.clear(); if((pLevelElement = hLevel.FirstChild("song").Element()) != NULL) { if((s = pLevelElement->GetText()) == NULL) { logfile << "song element but no filename\n\n"; eek(); } else { ALLEGRO_SAMPLE *sample = al_load_sample(s); if(sample == NULL) { logfile << "couldn't load sample " << s << "\n\n"; eek(); } else { logfile << "loaded sample.\n\n"; } samples.push_back(sample); } } //logfile << "read the task.\n"; if((pLevelElement = hLevel.FirstChild("ball_position").Element()) == NULL) return 1; if( pLevelElement->QueryIntAttribute("x", &i1) != TIXML_SUCCESS || pLevelElement->QueryIntAttribute("y", &i2) != TIXML_SUCCESS) { return 1; } else { initial_ball_x = i1; if(i2 < BALL_ARENA_TOP_EDGE_Y) { initial_ball_y = BALL_ARENA_TOP_EDGE_Y; } else { initial_ball_y = i2; } } if((pLevelElement = hLevel.FirstChild("border_colour").Element()) == NULL) { logfile << "no border colour specified in level file.\n"; return 1; } else { if( pLevelElement->QueryIntAttribute("r", &i1) != TIXML_SUCCESS || pLevelElement->QueryIntAttribute("g", &i2) != TIXML_SUCCESS || pLevelElement->QueryIntAttribute("b", &i3) != TIXML_SUCCESS ) { logfile << "no r, g, and / or b in border colour element.\n"; return 1; } else { border_colour = al_map_rgb(i1, i2, i3); } } if((pLevelElement = hLevel.FirstChild("background_colour").Element()) == NULL) { logfile << "no backgound colour specified in level file.\n"; return 1; } else { if( pLevelElement->QueryIntAttribute("r", &i1) != TIXML_SUCCESS || pLevelElement->QueryIntAttribute("g", &i2) != TIXML_SUCCESS || pLevelElement->QueryIntAttribute("b", &i3) != TIXML_SUCCESS ) { logfile << "no r, g, and / or b in background colour element.\n"; return 1; } else { //logfile << "setting background_colour.\n"; //logfile << "i1 = " << i1 << " i2 = " << i2 << " i3 = " << i3 << "\n"; //eek(); background_colour = al_map_rgb(i1, i2, i3); } } if((pLevelElement = hLevel.FirstChild("ball_colour").Element()) == NULL) { logfile << "no ball colour specified in level file.\n"; return 1; } else { if( pLevelElement->QueryIntAttribute("r", &i1) != TIXML_SUCCESS || pLevelElement->QueryIntAttribute("g", &i2) != TIXML_SUCCESS || pLevelElement->QueryIntAttribute("b", &i3) != TIXML_SUCCESS ) { logfile << "no r, g, and / or b in ball colour element.\n"; return 1; } else { //logfile << "setting background_colour.\n"; //logfile << "i1 = " << i1 << " i2 = " << i2 << " i3 = " << i3 << "\n"; //eek(); ball_colour = al_map_rgb(i1, i2, i3); } } if((pLevelElement = hLevel.FirstChild("initial_angle").Element()) == NULL) { /* no angle specified so make the ball go in the direction of the bat. */ /* get the distance from initial bat x to middle of screen */ i1 = ( PONGPING_CANVAS_WIDTH / 2 ) - initial_ball_x; i2 = - BAT_Y_POSITION; f1 = atan( (float) i2 / (float) i1 ); principal_value(&f1); initial_ball_angle = f1; } else { if(pLevelElement->QueryDoubleAttribute("angle", &f1) != TIXML_SUCCESS) { return 1; } else { principal_value(&f1); initial_ball_angle = f1; } } /* increment for ball (initial speed) */ if((pLevelElement = hLevel.FirstChild("ball_increment").Element()) == NULL) { initial_ball_increment = 5.0f; } else { if( pLevelElement->QueryDoubleAttribute("increment", &f1) != TIXML_SUCCESS) { return 1; } else { initial_ball_increment = f1; } } /* ball speeds */ //logfile << "getting ball speeds.\n"; /* if((pLevelElement = hLevel.FirstChild("ball_speed_change").Element()) != NULL) { BallSpeedData b; int i = 0; for( ; ; pLevelElement = pLevelElement->NextSiblingElement("ball_speed_change")) { if(pLevelElement == NULL) { break; } if(pLevelElement->QueryIntAttribute("time", &i1) != TIXML_SUCCESS || pLevelElement->QueryDoubleAttribute("difference", &f1) != TIXML_SUCCESS) { logfile << "query issue with 'ball_speed_change' element.\n"; return 1; } else { b = BallSpeedData(i1, f1); bsd.push_back(b); } } } */ if((pLevelElement = hLevel.FirstChild("survive_until").Element()) != NULL ) { if(pLevelElement->QueryIntAttribute("time", &i1) == TIXML_SUCCESS) { end_when_time_reached = true; time_to_reach = i1; } } else { end_when_time_reached = false; } int cn; //collectable number int destructable_shaded; int rings; TiXmlElement *shaded; int polygon_number = 0; if((pLevelElement = hLevel.FirstChild("polygon").Element()) != NULL) { PongPingPolygon *rp = NULL; int i = 0; int number_of_colors; int number_of_layers = 0; rings = destructable_shaded = 0; //logfile << "found another polygon.\n\n"; for( ; ; pLevelElement = pLevelElement->NextSiblingElement("polygon")) { ++polygon_number; //logfile << "checking if pLevelElement NULL.\n\n"; i8 = 0; // must reset i8 for this polygon because it might have a value left over from last run of this loop if(pLevelElement == NULL) { logfile << "breaking.\n\n"; break; } //logfile << "got level feature.\n\n"; if( pLevelElement->QueryIntAttribute("x", &i1) != TIXML_SUCCESS || pLevelElement->QueryIntAttribute("y", &i2) != TIXML_SUCCESS || pLevelElement->QueryIntAttribute("sides", &i3) != TIXML_SUCCESS || pLevelElement->QueryIntAttribute("direction", &i4) != TIXML_SUCCESS || pLevelElement->QueryDoubleAttribute("increment_angle", &f2) != TIXML_SUCCESS || pLevelElement->QueryDoubleAttribute("initial_angle", &f3) != TIXML_SUCCESS || pLevelElement->QueryIntAttribute("layers", &number_of_layers) != TIXML_SUCCESS ) { logfile << "query issue with 'regular_polygon' element. one of x, y, sides, direction, increment_anglem initial_angle or layers missing.\n"; return 1; } else { s = pLevelElement->Attribute("regular"); if(s == NULL) { logfile << "no regular attribute in polygon tag\n\n"; return 1; } //logfile << "got string for regular. \n\n"; if(strcmp( s, "yes") == 0) { //logfile << "regular.\n\n"; i8 |= REGULAR; if(pLevelElement->QueryIntAttribute("sides", &i3) != TIXML_SUCCESS) { logfile << "query issue with 'regular_polygon' type polygon. No sides attribute. Polygon number :- " << polygon_number << ">.\n"; return 1; } if(pLevelElement->QueryDoubleAttribute("width", &f1) != TIXML_SUCCESS) { logfile << "query issue with 'regular_polygon' type polygon. No width attribute. Polygon number :- " << polygon_number << ">.\n"; return 1; } } else if(strcmp( s, "no") == 0) { i8 |= IRREGULAR; } else { logfile << "value of 'regular' attribute not recognised. It was " << s << "\n\n"; return 1; } //logfile << "worked out regularness.\n\n"; hPongPingPolygon = TiXmlHandle( pLevelElement ); /* if(hPongPingPolygon == NULL) { logfile << "handle NULL in read_level() .\n\n"; return 1; } */ //logfile << "i8 = " << i8 << " before type read\n"; s = pLevelElement->Attribute("type"); if(s == NULL) { logfile << "no type for polygon.\n"; return 1; } else { if(strcmp( s, "one_coloured") == 0) { i8 |= ONE_COLOURED_POLYGON; } else if(strcmp( s, "shaded") == 0) { i8 |= SHADED_POLYGON; } else if(strcmp( s, "destructable") == 0) { i8 |= PONGPING_VANISHING_POLYGON; //logfile << "got a DESTRUCTABLE polygon.\n"; } else if(strcmp( s, "reducable_polygon") == 0) { logfile << "or ing with PONGPING_HIT_X_TIMES_POLYGON.\n"; i8 |= PONGPING_HIT_X_TIMES_POLYGON; } else { logfile << "unrecognised type of polygon in level file.\n"; return 1; } } //logfile << "i8 = " << i8 << " after type read\n"; //logfile << "got type of polygon.\n\n"; rp = new PongPingPolygon( i1, i2, i3, i8 & REGULAR ? f1 : 0, f2, i4, f3, i8); if(rp == NULL) { logfile << "rp polygon is NULL.\n\n"; return 1; } //logfile << "got pointer to new polygon.\n\n"; if(i8 & IRREGULAR) //get the vertices { TiXmlElement *pVertexElement; //logfile << "irregular - getting vertex element.\n\n"; if( (pVertexElement = hPongPingPolygon.FirstChild("vertex").Element()) != NULL) { logfile << "got vertex.\n\n"; int x, y, vn; vn = 0; rp->furthest_vertex = 0; int vc = 0; for( ; ; pVertexElement = pVertexElement->NextSiblingElement( "vertex" )) { ++vc; logfile << " vc = " << vc << "\n"; double furthest_vertex = 0.0; if(pVertexElement == NULL) break; if( (pVertexElement->QueryIntAttribute("x", &x) != TIXML_SUCCESS ) || (pVertexElement->QueryIntAttribute("y", &y) != TIXML_SUCCESS ) ) { logfile << "no x and y elements for vertex of polygon.\n\n"; return 1; } else { logfile << "doing vertex " << vc << " x = " << x << " y = " << y << "\n\n"; polar_coordinates new_point;// = new Point [1]; new_point.radius = sqrt( (x - i1) * (x - i1) + (y - i2) * (y - i2) ); logfile << "radius = " << (x - i1) * (x - i1) << " * " << (y - i2) * (y - i2) << " = " << new_point.radius << "\n"; if(new_point.radius > rp->furthest_vertex) { //logfile << new_point.radius << "was greater than " << rp->furthest_vertex << "\n"; //logfile << "changing furthest vertex to " << new_point.radius << "\n"; rp->furthest_vertex = new_point.radius; } if( x == i1 ) // line from centre to vertex is vertical { if( y - i2 > 0.0 ) { new_point.angle = PONGPING_PI/ 2.0; } else if( y - i2 < 0.0 ) { new_point.angle = 3.0 * PONGPING_PI/ 2.0; } logfile << "new_point.angle = " << (new_point.angle * 180.0f / PONGPING_PI)<< "\n"; } else { new_point.angle = principal_value_2(atan2( (y - i2) , (x - i1) )); logfile << "atan(" << (y - i2) << " , " << (x - i1) << "\n"; /* if(new_point.angle < 0.0) { new_point.angle += ALLEGRO_PI; } */ logfile << "new_point.angle = " << (new_point.angle * 180.0f / PONGPING_PI)<< "\n"; } //logfile << "pushing point (radius) " << new_point.radius << " angle " << new_point.angle << "\n\n"; // logfile << "pushing point.\n"; rp->unrotated_points.push_back(new_point); } logfile << "finished.\n\n"; } rp->update_irregular_polygon(); //logfile << "out of for loop.\n\n"; } else { logfile << "no vertex elements for irregular polygon.\n\n"; return 1; } } else { rp->furthest_vertex = f1; logfile << "polygon regular.\n\n"; } /* Get the colors for the polygon. */ number_of_colors = 0; hPongPingPolygon = TiXmlHandle(pLevelElement); colour_vector.clear(); if( (pColorElement = hPongPingPolygon.FirstChild("color").Element()) != NULL) { for( ; ; pColorElement = pColorElement->NextSiblingElement("color") ) { if( pColorElement == NULL) { break; } /* else if(i8 & REDUCABLE_POLYGON && number_of_colors == 1) { logfile << "too many colours for one_coloured POLYGON.\n\n"; return 1; } else if(i8 & PONGPING_VANSHING_POLYGON && number_of_colors == 1) { logfile << "too many colours for one_coloured POLYGON.\n\n"; return 1; } */ else { //logfile << "got a color.\n\n" << "rings = " << rings; ++number_of_colors; if( pColorElement->QueryIntAttribute("r", &r) != TIXML_SUCCESS || pColorElement->QueryIntAttribute("g", &g) != TIXML_SUCCESS || pColorElement->QueryIntAttribute("b", &b) != TIXML_SUCCESS ) { logfile << "trouble reading r, g or b from color element for polygon.\n"; return 1; } else { colour_vector.push_back(al_map_rgb(r, g, b)); /* if(i8 & REDUCABLE_POLYGON) { int i; int r2, g2, b2; for(i = 0; i < NUMBER_OF_LAYERS_FOR_POLYGONS_WITH_COLLECTABLES; ++i) { r2 = (float) r * ( (float) i / (float) (NUMBER_OF_LAYERS_FOR_POLYGONS_WITH_COLLECTABLES - 1) ); g2 = (float) g * ( (float) i / (float) (NUMBER_OF_LAYERS_FOR_POLYGONS_WITH_COLLECTABLES - 1)); b2 = (float) b * ( (float) i / (float) (NUMBER_OF_LAYERS_FOR_POLYGONS_WITH_COLLECTABLES - 1)); colour = al_map_rgb( r2, g2, b2); rp->polygon_colours.push_back(colour); //logfile << "r = " << r2 << " g = " << g2 << " b = " << b2 << "\n\n"; } //logfile << "pushed all colours.\n\n"; } else { colour = al_map_rgb(r, g, b); //logfile << "pushing colour.\n"; rp->polygon_colours.push_back(colour); //logfile << "pushed colour.\n"; } */ } } } /* if(rp->polygon_colours.size() == 0) { logfile << "read_level : no colours for polygon. Will cause serious issues.\n"; } //logfile << "setting active_layers to " << number_of_colors << "\n"; if(i8 & REDUCABLE_POLYGON) { rp->active_layers = NUMBER_OF_LAYERS_FOR_POLYGONS_WITH_COLLECTABLES - 1; //logfile << "set active_layers to " << rp->active_layers << "\n\n"; } else if(i8 & PONGPING_VANSHING_POLYGON && shaded != NULL) { rp->active_layers = rings; } else { rp->active_layers = number_of_colors; } */ } else { logfile << "no color element for polygon.\n"; return 1; } //logfile << "colours counted = " << number_of_colors << "\n colour_vector.size() = " << colour_vector.size() << "\n"; if(i8 & PONGPING_VANISHING_POLYGON || i8 & PONGPING_HIT_X_TIMES_POLYGON ) { if(number_of_layers <= 0) { logfile << "number of layers specified for destructable type polygon less than or equal to zero.\n"; return 1; } if(colour_vector.size() == 1 && number_of_layers > 1) // make the colours from the one colour specified. { int i; int r2, g2, b2; unsigned char cr, cg, cb; double fraction; if( i8 & PONGPING_VANISHING_POLYGON ) { fraction *= 0.75; fraction += 0.25; } al_unmap_rgb(colour_vector[0], &cr, &cg, &cb); for(i = 0; i < number_of_layers; ++i) { double fraction = ( (float) i / (float) (number_of_layers - 1)); if( i8 & PONGPING_VANISHING_POLYGON ) { fraction *= 0.75; fraction += 0.25; } r2 = (float) cr * fraction; g2 = (float) cg * fraction; b2 = (float) cb * fraction; colour = al_map_rgb( r2, g2, b2); rp->polygon_colours.push_back(colour); //logfile << "r = " << r2 << " g = " << g2 << " b = " << b2 << "\n\n"; //logfile << "rings = " << rings; } } else if(colour_vector.size() == number_of_layers) { int i; for(i = 0; i < number_of_layers; ++i) { rp->polygon_colours.push_back(colour_vector[i]); } } else if(colour_vector.size() != number_of_layers) { logfile << "colour_vector.size() greater than one but not equal to number of layers specified. colour_vector.size() = \n" << colour_vector.size(); return 1; } rp->active_layers = ( i8 & PONGPING_VANISHING_POLYGON ) ? number_of_layers : number_of_layers - 1; //logfile << "rp->active_layers = " << rp->active_layers << "\n"; } else if(i8 & ONE_COLOURED_POLYGON) { if(number_of_colors != 1) { logfile << "more than on colour specified for one coloured polygon.\n"; return 1; } else { rp->polygon_colours.push_back(colour_vector[0]); } } //logfile << "pushing LevelFeature onto vector.\n"; features_for_level.push_back((LevelFeature *) rp); //logfile << "pushed LevelFeature.\n"; } } } if((pLevelElement = hLevel.FirstChild("catchment_area").Element()) != NULL) { for( ; ; pLevelElement = pLevelElement->NextSiblingElement("catchment_area")) { if(pLevelElement == NULL) // no more catchment areas { logfile << "breaking.\n\n"; break; } CatchmentArea *ca = NULL; if( (pLevelElement->QueryIntAttribute( "x", &i1) != TIXML_SUCCESS) || (pLevelElement->QueryIntAttribute( "y", &i2) != TIXML_SUCCESS) || (pLevelElement->QueryIntAttribute( "w", &i3) != TIXML_SUCCESS) || (pLevelElement->QueryIntAttribute( "h", &i4) != TIXML_SUCCESS) || (pLevelElement->QueryIntAttribute( "bitmap_number", &i5) != TIXML_SUCCESS) ) { logfile << "couldn't read one of the integer attributes of the catchment_area element.\n"; return 1; } else { ca = new CatchmentArea( i1, i2, i3, i4, i5 ); if(ca->init_okay == 0) { logfile << "problem initialising catchment area.\n"; return 1; } features_for_level.push_back( (LevelFeature *) ca ); } } } //logfile << "getting quota variables.\n"; if((pLevelElement = hLevel.FirstChild("quotas").Element()) != NULL) { int number = 0; int total_number = 0; logfile << "got quotas element.\n"; if( pLevelElement->QueryIntAttribute("letter_quota", &number) == TIXML_SUCCESS ) { collectable_type_quotas[PONGPING_EXTRA_LIFE_LETTER_CIRCLE_TYPE - 1] = number; total_number += number; } else { logfile << "no value for letter_quota in quotas element.\n"; return 1; } if( pLevelElement->QueryIntAttribute("bat_size_up_quota", &number) == TIXML_SUCCESS ) { collectable_type_quotas[PONGPING_BAT_SIZE_UP_CIRCLE_TYPE - 1] = number; total_number += number; } else { logfile << "no value for bat_size_up_quota in quotas element.\n"; return 1; } if( pLevelElement->QueryIntAttribute("ball_speed_up_quota", &number) == TIXML_SUCCESS ) { collectable_type_quotas[PONGPING_BALL_SIZE_UP_CIRCLE_TYPE - 1] = number; total_number += number; } else { logfile << "no value for ball_speed_up_quota in quotas element.\n"; return 1; } if( pLevelElement->QueryIntAttribute("ball_speed_down_quota", &number) == TIXML_SUCCESS ) { collectable_type_quotas[PONGPING_BALL_SPEED_DOWN_CIRCLE_TYPE - 1] = number; total_number += number; } else { logfile << "no value for ball_speed_down_quota in quotas element.\n"; return 1; } collectable_quota = total_number; } else { logfile << "reading level : no quota element needed for how many of different types of collectables there are.\n"; return 1; } //#ifdef USE_LOG_FILE //PPLOG(READ_LEVEL_FINISHED_READING_LEVEL); //#endif //logfile << "finished reading level.\n\n"; return 0; }
[ "willlabbett@talktalk.net" ]
willlabbett@talktalk.net
30dfcbd114a9bdf24843f9156e58aa8e1b90226c
c2d270aff0a4d939f43b6359ac2c564b2565be76
/src/chrome/browser/page_load_metrics/observers/data_reduction_proxy_metrics_observer.h
5c135be900f67b8b85788480bb0c71ee633b85cf
[ "BSD-3-Clause" ]
permissive
bopopescu/QuicDep
dfa5c2b6aa29eb6f52b12486ff7f3757c808808d
bc86b705a6cf02d2eade4f3ea8cf5fe73ef52aa0
refs/heads/master
2022-04-26T04:36:55.675836
2020-04-29T21:29:26
2020-04-29T21:29:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,907
h
// 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. #ifndef CHROME_BROWSER_PAGE_LOAD_METRICS_OBSERVERS_DATA_REDUCTION_PROXY_METRICS_OBSERVER_H_ #define CHROME_BROWSER_PAGE_LOAD_METRICS_OBSERVERS_DATA_REDUCTION_PROXY_METRICS_OBSERVER_H_ #include <stdint.h> #include <memory> #include "base/macros.h" #include "base/sequence_checker.h" #include "chrome/browser/page_load_metrics/page_load_metrics_observer.h" #include "components/ukm/ukm_source.h" namespace content { class BrowserContext; class NavigationHandle; } namespace data_reduction_proxy { class DataReductionProxyData; class DataReductionProxyPingbackClient; namespace internal { // Various UMA histogram names for DataReductionProxy core page load metrics. extern const char kHistogramDataReductionProxyPrefix[]; extern const char kHistogramDataReductionProxyLoFiOnPrefix[]; // Byte and request specific histogram suffixes. extern const char kResourcesPercentProxied[]; extern const char kBytesPercentProxied[]; extern const char kBytesCompressionRatio[]; extern const char kBytesInflationPercent[]; extern const char kNetworkResources[]; extern const char kResourcesProxied[]; extern const char kResourcesNotProxied[]; extern const char kNetworkBytes[]; extern const char kBytesProxied[]; extern const char kBytesNotProxied[]; extern const char kBytesOriginal[]; extern const char kBytesSavings[]; extern const char kBytesInflation[]; } // namespace internal // Observer responsible for recording core page load metrics releveant to // DataReductionProxy. class DataReductionProxyMetricsObserver : public page_load_metrics::PageLoadMetricsObserver { public: DataReductionProxyMetricsObserver(); ~DataReductionProxyMetricsObserver() override; // page_load_metrics::PageLoadMetricsObserver: ObservePolicy OnStart(content::NavigationHandle* navigation_handle, const GURL& currently_committed_url, bool started_in_foreground) override; ObservePolicy OnCommit(content::NavigationHandle* navigation_handle, ukm::SourceId source_id) override; ObservePolicy FlushMetricsOnAppEnterBackground( const page_load_metrics::mojom::PageLoadTiming& timing, const page_load_metrics::PageLoadExtraInfo& info) override; void OnComplete(const page_load_metrics::mojom::PageLoadTiming& timing, const page_load_metrics::PageLoadExtraInfo& info) override; void OnDomContentLoadedEventStart( const page_load_metrics::mojom::PageLoadTiming& timing, const page_load_metrics::PageLoadExtraInfo& info) override; void OnLoadEventStart( const page_load_metrics::mojom::PageLoadTiming& timing, const page_load_metrics::PageLoadExtraInfo& info) override; void OnFirstLayout(const page_load_metrics::mojom::PageLoadTiming& timing, const page_load_metrics::PageLoadExtraInfo& info) override; void OnFirstPaintInPage( const page_load_metrics::mojom::PageLoadTiming& timing, const page_load_metrics::PageLoadExtraInfo& info) override; void OnFirstTextPaintInPage( const page_load_metrics::mojom::PageLoadTiming& timing, const page_load_metrics::PageLoadExtraInfo& info) override; void OnFirstImagePaintInPage( const page_load_metrics::mojom::PageLoadTiming& timing, const page_load_metrics::PageLoadExtraInfo& info) override; void OnFirstContentfulPaintInPage( const page_load_metrics::mojom::PageLoadTiming& timing, const page_load_metrics::PageLoadExtraInfo& info) override; void OnFirstMeaningfulPaintInMainFrameDocument( const page_load_metrics::mojom::PageLoadTiming& timing, const page_load_metrics::PageLoadExtraInfo& info) override; void OnParseStart(const page_load_metrics::mojom::PageLoadTiming& timing, const page_load_metrics::PageLoadExtraInfo& info) override; void OnParseStop(const page_load_metrics::mojom::PageLoadTiming& timing, const page_load_metrics::PageLoadExtraInfo& info) override; void OnLoadedResource(const page_load_metrics::ExtraRequestCompleteInfo& extra_request_compelte_info) override; void OnEventOccurred(const void* const event_key) override; private: // Sends the page load information to the pingback client. void SendPingback(const page_load_metrics::mojom::PageLoadTiming& timing, const page_load_metrics::PageLoadExtraInfo& info, bool app_background_occurred); // Records UMA of page size when the observer is about to be deleted. void RecordPageSizeUMA() const; // Gets the default DataReductionProxyPingbackClient. Overridden in testing. virtual DataReductionProxyPingbackClient* GetPingbackClient() const; // Data related to this navigation. std::unique_ptr<DataReductionProxyData> data_; // The browser context this navigation is operating in. content::BrowserContext* browser_context_; // True if a Preview opt out occurred during this page load. bool opted_out_; // The number of resources that used data reduction proxy. int num_data_reduction_proxy_resources_; // The number of resources that did not come from cache. int num_network_resources_; // The total content network bytes that the user would have downloaded if they // were not using data reduction proxy. int64_t original_network_bytes_; // The total network bytes loaded through data reduction proxy. int64_t network_bytes_proxied_; // The total network bytes used. int64_t network_bytes_; SEQUENCE_CHECKER(sequence_checker_); DISALLOW_COPY_AND_ASSIGN(DataReductionProxyMetricsObserver); }; } // namespace data_reduction_proxy #endif // CHROME_BROWSER_PAGE_LOAD_METRICS_OBSERVERS_DATA_REDUCTION_PROXY_METRICS_OBSERVER_H_
[ "rdeshm0@aptvm070-6.apt.emulab.net" ]
rdeshm0@aptvm070-6.apt.emulab.net
c08dc2b0ac4d038a815782350b60710a166f72e8
4fe4d00c0c9a98d888d1626dedfbf8bd06451e2a
/computorv1/includes/solver.hpp
dcc1d250a91624e32bc22928e203878a76866269
[]
no_license
gguichard/42-workspace
00234e3e1108d1e0f2b7de067b875713df6b6362
9fafb1f3f536f2277cb454cb96a306504dd178b4
refs/heads/master
2021-07-10T13:02:37.527351
2020-06-25T07:40:59
2020-06-25T07:40:59
156,335,619
0
0
null
null
null
null
UTF-8
C++
false
false
698
hpp
#ifndef SOLVER_HPP #define SOLVER_HPP #include <vector> #include "lexer.hpp" #include "parser.hpp" #include "exprformula.hpp" #include "complex.hpp" class Solver { public: explicit Solver(std::string formula); void solve(bool debug); const Parser &parser() const; private: void solveQuadratic(const ExprFormula &expr, std::vector<Complex> &solutions, std::string &solutionHint) const; void solveCubic(const ExprFormula &expr, std::vector<Complex> &solutions, std::string &solutionHint, bool debug) const; void printSolutions(const ExprFormula &expr, std::vector<Complex> &solutions, std::string &solutionHint) const; private: Lexer m_lexer; Parser m_parser; }; #endif // SOLVER_HPP
[ "gguichar@student.42.fr" ]
gguichar@student.42.fr
1c579feb2407520d196218b07a019307f99fb9a8
f968a40cb4a71013244686766c23e08ab154b14e
/Server/DataBase/MysqlClient/MysqlDefine.h
7bc9c9c6e8cd06015ea58c26caedb2c0e19cfb90
[]
no_license
Mopipi/SoEasyFrameWork
2ea834bd76602d0e4d4ef7d1cb632d21fe7d761b
6aab0ada9a7e1a12c991bcb4c20dbf92ef072583
refs/heads/master
2023-05-05T15:38:41.790475
2021-05-31T15:55:28
2021-05-31T15:55:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
388
h
#pragma once #ifdef _WIN32 #include <WinSock2.h> #include <windows.h> #endif #include<vector> #include<sstream> #include"mysql.h" #include<memory> #include<unordered_map> #include<XCode/XCode.h> #include<Thread/ThreadTaskAction.h> using namespace std; using namespace SoEasy; namespace SoEasy { class MysqlManager; typedef MYSQL_RES MysqlQueryResult; typedef MYSQL SayNoMysqlSocket; }
[ "646585122@qq.com" ]
646585122@qq.com
ca345f55703fc1bb4ec0eaeb593187b65584d4b6
6ced41da926682548df646099662e79d7a6022c5
/aws-cpp-sdk-opensearch/source/model/ListVersionsResult.cpp
3810f59819b13da065228e2d046a7995de820093
[ "Apache-2.0", "MIT", "JSON" ]
permissive
irods/aws-sdk-cpp
139104843de529f615defa4f6b8e20bc95a6be05
2c7fb1a048c96713a28b730e1f48096bd231e932
refs/heads/main
2023-07-25T12:12:04.363757
2022-08-26T15:33:31
2022-08-26T15:33:31
141,315,346
0
1
Apache-2.0
2022-08-26T17:45:09
2018-07-17T16:24:06
C++
UTF-8
C++
false
false
1,252
cpp
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/opensearch/model/ListVersionsResult.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/UnreferencedParam.h> #include <utility> using namespace Aws::OpenSearchService::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws; ListVersionsResult::ListVersionsResult() { } ListVersionsResult::ListVersionsResult(const Aws::AmazonWebServiceResult<JsonValue>& result) { *this = result; } ListVersionsResult& ListVersionsResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result) { JsonView jsonValue = result.GetPayload().View(); if(jsonValue.ValueExists("Versions")) { Array<JsonView> versionsJsonList = jsonValue.GetArray("Versions"); for(unsigned versionsIndex = 0; versionsIndex < versionsJsonList.GetLength(); ++versionsIndex) { m_versions.push_back(versionsJsonList[versionsIndex].AsString()); } } if(jsonValue.ValueExists("NextToken")) { m_nextToken = jsonValue.GetString("NextToken"); } return *this; }
[ "aws-sdk-cpp-automation@github.com" ]
aws-sdk-cpp-automation@github.com
233f5a350e10fba6c996c6d44310a303f623d199
89f565900ad1c9e3e2f80d51d2082f09f4a873fa
/include/Cell.hpp
73934d9f2399032d6f6b78eda2835122fcb41286
[]
no_license
m-karcz/befungeInterpreter
12c4f67e682212b19314279c9bb66ee39946a616
b112655728d735f925093dfe776992857c274145
refs/heads/master
2020-04-09T14:14:16.039104
2018-12-05T18:52:16
2018-12-05T18:52:16
160,391,345
0
0
null
null
null
null
UTF-8
C++
false
false
336
hpp
#pragma once #include "ICell.hpp" namespace befunge { struct Cell : ICell { explicit Cell(char p_value) : m_value{p_value} {} char get() const override { return m_value; } void set(char p_value) override { p_value = m_value; } private: char m_value; }; }//namespace befunge
[ "mariusz0karcz@gmail.com" ]
mariusz0karcz@gmail.com
216724b14bdba46532979d11f918be06ae45ec05
786c484ca627050429c02539a88908978e482646
/EigenTwo/openglwindow.h
5baf2ab1c240c8b8efa2b7eb38bea0f41cda8e03
[]
no_license
Lvzwq/EigenTest
1cae047d4d8881d739510dee82b130ab3460f150
4f612b20d84f7a8bf78feec157fc7552f6e49f2e
refs/heads/master
2021-01-10T16:57:11.401990
2015-11-30T03:58:54
2015-11-30T03:58:54
46,976,084
0
0
null
null
null
null
UTF-8
C++
false
false
778
h
#ifndef OPENGLWINDOW_H #define OPENGLWINDOW_H #include<QWindow> #include<QOpenGLFunctions> #include<QEvent> #include<QOpenGLPaintDevice> class OpenGLWindow : public QWindow, protected QOpenGLFunctions { public: explicit OpenGLWindow(QWindow *parent = 0); ~OpenGLWindow(); virtual void render(QPainter *painter); virtual void render(); virtual void initialize(); void setAnimating(bool animating); signals: public slots: void renderLater(); void renderNow(); protected: bool event(QEvent *event) Q_DECL_OVERRIDE; void exposeEvent(QExposeEvent *event) Q_DECL_OVERRIDE; private: bool m_update_pending; bool m_animating; QOpenGLContext *m_context; QOpenGLPaintDevice *m_device; }; #endif // OPENGLWINDOW_H
[ "zhangwenqiang6@gmail.com" ]
zhangwenqiang6@gmail.com
6b6d3e682265152695af82cbee36d3a08760c3c5
4d32e11fd6a5891adb9f48d6de4ae97e5c78f2f0
/proj-rt-files/mesh.h
acf8f41f3859cecf68cea36de32d612c15d1e8c0
[]
no_license
mjime051/CS_130_Graphics
ef763e5b2ead2e5f4219366d0f05406b7b9aef2f
acc07cef037101c3eb12983a39cfc11891f35523
refs/heads/main
2023-04-15T13:40:42.397590
2021-04-21T08:21:31
2021-04-21T08:21:31
359,947,279
2
0
null
null
null
null
UTF-8
C++
false
false
647
h
#ifndef __MESH_H__ #define __MESH_H__ #include "object.h" // Consider a hit to be inside a triange if all barycentric weights // satisfy weight>=-weight_tol static const double weight_tol = 1e-4; class Mesh : public Object { std::vector<vec3> vertices; std::vector<ivec3> triangles; Box box; public: Mesh() {} virtual Hit Intersection(const Ray& ray, int part) const override; virtual vec3 Normal(const vec3& point, int part) const override; bool Intersect_Triangle(const Ray& ray, int tri, double& dist) const; void Read_Obj(const char* file); Box Bounding_Box(int part) const override; }; #endif
[ "mjime051@ucr.edu" ]
mjime051@ucr.edu
3c3f9ee8ad4dafad1169390289e525c6b73e31ee
dcdffe4230c3f675e780c8bcfde0a2246b423ff6
/modules/imgimport/src/DeckLinkCapture.cpp
195dc933604b4551efbd994cf4f775af4f1b55a8
[ "BSD-2-Clause" ]
permissive
benjaminwinger/computer-vision
75e704283881ef991ac305b79bf7e7e6d8ef1ff2
cee34a5c02b482c3e194ef51e289342b3a05c4da
refs/heads/master
2020-04-04T20:07:16.409434
2018-01-12T00:43:24
2018-01-12T00:43:24
42,910,713
1
0
null
null
null
null
UTF-8
C++
false
false
6,215
cpp
/* * DeckLinkCapture.cpp - Clase para capturar vídeo desde dispositivos DeckLink * * Copyright 2013 Jesús Torres <jmtorres@ull.es> * * 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 <DeckLinkAPI.h> #include <boost/thread.hpp> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <boost/log/core.hpp> #include <boost/log/trivial.hpp> #include "ComPtr.h" #include "DeckLinkCapture.h" #include "DeckLinkInputCallback.h" #include "DeckLinkOpenCv.h" DeckLinkCapture::DeckLinkCapture(ComPtr<IDeckLink> deckLink) : deckLink_(deckLink), error_(S_OK) { IDeckLinkInput* deckLinkInput; error_ = deckLink_->QueryInterface(IID_IDeckLinkInput, reinterpret_cast<void**>(&deckLinkInput)); if (SUCCEEDED(error_)) deckLinkInput_ = ComPtr<IDeckLinkInput>(deckLinkInput); else { errorString_ = "Unable to read the file"; return; } } DeckLinkCapture::DeckLinkCapture(DeckLinkCapture&& other) noexcept { deckLink_.swap(other.deckLink_); deckLinkInput_.swap(other.deckLinkInput_); deckLinkInputCallback_.swap(other.deckLinkInputCallback_); grabbedVideoFrame_.swap(other.grabbedVideoFrame_); errorString_.swap(other.errorString_); error_ = other.error_; other.error_ = S_OK; } DeckLinkCapture::~DeckLinkCapture() { if (deckLink_) stop(); } DeckLinkCapture& DeckLinkCapture::operator=(DeckLinkCapture&& other) noexcept { deckLink_ = other.deckLink_; other.deckLink_.reset(); deckLinkInput_ = other.deckLinkInput_; other.deckLinkInput_.reset(); deckLinkInputCallback_ = other.deckLinkInputCallback_; other.deckLinkInputCallback_.reset(); grabbedVideoFrame_ = other.grabbedVideoFrame_; other.grabbedVideoFrame_.reset(); errorString_.swap(other.errorString_); other.errorString_.erase(); error_ = other.error_; other.error_ = S_OK; return *this; } bool DeckLinkCapture::doesSupportVideoMode(BMDDisplayMode displayMode, BMDPixelFormat pixelFormat) { BMDDisplayModeSupport support; error_ = deckLinkInput_->DoesSupportVideoMode(displayMode, pixelFormat, 0, &support, nullptr); if (SUCCEEDED(error_)) return support == bmdDisplayModeSupported || support == bmdDisplayModeSupportedWithConversion; else { errorString_ = "Error selecting the appropriate displaymode via IDeckLinkInput::DoesSupportVideoMode()"; return false; } } bool DeckLinkCapture::start(BMDDisplayMode displayMode, BMDPixelFormat pixelFormat) { error_ = deckLinkInput_->EnableVideoInput(displayMode, pixelFormat, 0); if (FAILED(error_)) { switch (error_) { case E_INVALIDARG: errorString_ = "Invalid video mode."; break; case E_ACCESSDENIED: errorString_ = "Unable to access hardware or flow capture is active."; break; case E_OUTOFMEMORY: errorString_ = "Cannot create a new frame (out of memory)."; break; default: errorString_ = "Error invoking IDeckLinkInput::EnableVideoInput()"; } return false; } ComPtr<DeckLinkInputCallback> callback(new DeckLinkInputCallback()); error_ = deckLinkInput_->SetCallback(callback.get()); if (FAILED(error_)) { errorString_ = "Error invoking IDeckLinkInput::SetCallback()"; return false; } error_ = deckLinkInput_->StartStreams(); if (FAILED(error_)) { errorString_ = "Error invoking IDeckLinkInput::StartStream()"; return false; } deckLinkInputCallback_ = callback; return true; } void DeckLinkCapture::stop() { error_ = deckLinkInput_->StopStreams(); if (FAILED(error_)) errorString_ = "Error invoking IDeckLinkInput::StopStreams()"; error_ = deckLinkInput_->DisableVideoInput(); if (FAILED(error_)) errorString_ = "Error invoking IDeckLinkInput::DisableVideoInput()"; deckLinkInputCallback_.reset(); grabbedVideoFrame_.reset(); } bool DeckLinkCapture::grab() { if (! deckLinkInputCallback_) return false; grabbedVideoFrame_ = deckLinkInputCallback_->getVideoFrame(); return true; } bool DeckLinkCapture::retrieve(cv::Mat& videoFrame) { if (! deckLinkInputCallback_ || !grabbedVideoFrame_) { videoFrame.release(); return false; } bool status = deckLinkVideoFrameToCvMat(grabbedVideoFrame_, videoFrame); BOOST_LOG_TRIVIAL(info) << "Video Status: " << status << std::endl; if (!status) { error_ = E_FAIL; errorString_ = "Error converting the image format."; videoFrame.release(); return false; } return true; } bool DeckLinkCapture::read(cv::Mat& videoFrame) { if (grab()) return retrieve(videoFrame); else { videoFrame.release(); return false; } } DeckLinkCapture& DeckLinkCapture::operator>>(cv::Mat& videoFrame) { read(videoFrame); return *this; } std::string DeckLinkCapture::getDeviceModelName() { const char* name; error_ = deckLink_->GetModelName(&name); if (FAILED(error_)) { errorString_ = "Error invoking IDeckLinkInput::GetModelName()"; return std::string(); } std::string modelName(name); delete name; return modelName; } std::string DeckLinkCapture::getDeviceDisplayName() { const char* name; error_ = deckLink_->GetDisplayName(&name); if (FAILED(error_)) { errorString_ = "Error invoking IDeckLinkInput::GetDisplayName()"; return std::string(); } std::string displayName(name); delete name; return displayName; }
[ "chrishajduk84@gmail.com" ]
chrishajduk84@gmail.com
dcbbe9dcebfa405ac41f6dad4d4c3e9769bef648
ad85c921d614df2354c6aaea199084be7e935f04
/src/rcpp_delaunay_module.cpp
2c636c8955e4cac78657414960deaa214abe904d
[]
no_license
rcqls/EBSpatCGAL
3cf7fc1213aaae69424e7c18eb40a9210e10e0df
f20ba631e6b395e3fa8855e9f1981dbd0de143d0
refs/heads/master
2023-07-21T01:11:10.937736
2023-07-18T13:29:22
2023-07-18T13:29:22
12,945,905
5
1
null
null
null
null
UTF-8
C++
false
false
12,225
cpp
#include "rcpp_delaunay_module.h" RCPP_MODULE(delaunay_module) { class_<Del1TermType2D>( "Del1TermType2D" ) .constructor() .field( "locBefore", &Del1TermType2D::locBefore, "local list before" ) .field( "locAfter", &Del1TermType2D::locAfter, "local list after" ) .field( "exprs.size", &Del1TermType2D::exprs_size, "exprs size" ) .field( "cexprs.size", &Del1TermType2D::cexprs_size, "cexprs size" ) //.property( "graph", &Del1TermType2D::get_struct, &Del1TermType2D::set_struct,"graph structure" ) .property( "mode", &Del1TermType2D::get_mode, &Del1TermType2D::set_mode, "mode " ) .property( "exprs", &Del1TermType2D::get_exprs, &Del1TermType2D::set_exprs, "exprs list" ) .property( "cexprs", &Del1TermType2D::get_cexprs, &Del1TermType2D::set_cexprs, "common exprs list" ) .property( "infos", &Del1TermType2D::get_infos, &Del1TermType2D::set_infos, "infos list" ) .property("args",&Del1TermType2D::get_args, &Del1TermType2D::set_args, "args setting") .property( "params", &Del1TermType2D::get_params, &Del1TermType2D::set_params, "params list" ) .method("get_envir",&Del1TermType2D::get_envir,"get envir") .method("set_struct",&Del1TermType2D::set_struct,"set struct") .method("get_struct",&Del1TermType2D::get_struct,"get struct") .method("set_current",&Del1TermType2D::set_current,"set point by coordinates (insertion) or index (suppression)") .method("get_current",&Del1TermType2D::get_current,"get point") .method("make_before",&Del1TermType2D::make_before_list,"make before list") .method("make_after",&Del1TermType2D::make_after_list,"make after list") .method("eval_first_expr",&Del1TermType2D::eval_first_expr,"eval first expr") .method("eval_exprs",&Del1TermType2D::eval_exprs,"eval exprs") ; class_<Del2TermType2D>( "Del2TermType2D" ) .constructor() .field( "locBefore", &Del2TermType2D::locBefore, "local list before" ) .field( "locAfter", &Del2TermType2D::locAfter, "local list after" ) .field( "exprs.size", &Del2TermType2D::exprs_size, "exprs size" ) .field( "cexprs.size", &Del2TermType2D::cexprs_size, "cexprs size" ) //.property( "graph", &Del2TermType2D::get_struct, &Del2TermType2D::set_struct,"graph structure" ) .property( "mode", &Del2TermType2D::get_mode, &Del2TermType2D::set_mode, "mode " ) .property( "exprs", &Del2TermType2D::get_exprs, &Del2TermType2D::set_exprs, "exprs list" ) .property( "cexprs", &Del2TermType2D::get_cexprs, &Del2TermType2D::set_cexprs, "common exprs list" ) .property( "infos", &Del2TermType2D::get_infos, &Del2TermType2D::set_infos, "infos list" ) .property("args",&Del2TermType2D::get_args, &Del2TermType2D::set_args, "args setting") .property( "params", &Del2TermType2D::get_params, &Del2TermType2D::set_params, "params list" ) .method("get_envir",&Del2TermType2D::get_envir,"get envir") .method("set_struct",&Del2TermType2D::set_struct,"set struct") .method("get_struct",&Del2TermType2D::get_struct,"get struct") .method("set_current",&Del2TermType2D::set_current,"set point by coordinates (insertion) or index (suppression)") .method("get_current",&Del2TermType2D::get_current,"get point") .method("make_before",&Del2TermType2D::make_before_list,"make before list") .method("make_after",&Del2TermType2D::make_after_list,"make after list") .method("eval_first_expr",&Del2TermType2D::eval_first_expr,"eval first expr") .method("eval_exprs",&Del2TermType2D::eval_exprs,"eval exprs") .method("get_cexprs_caches",&Del2TermType2D::get_cexprs_caches,"get cexprs caches") //for debugging ; class_<Del3TermType2D>( "Del3TermType2D" ) .constructor() .field( "locBefore", &Del3TermType2D::locBefore, "local list before" ) .field( "locAfter", &Del3TermType2D::locAfter, "local list after" ) .field( "exprs.size", &Del3TermType2D::exprs_size, "exprs size" ) .field( "cexprs.size", &Del3TermType2D::cexprs_size, "cexprs size" ) //.property( "graph", &Del3TermType2D::get_struct, &Del3TermType2D::set_struct,"graph structure" ) .property( "mode", &Del3TermType2D::get_mode, &Del3TermType2D::set_mode, "mode " ) .property( "exprs", &Del3TermType2D::get_exprs, &Del3TermType2D::set_exprs, "exprs list" ) .property( "cexprs", &Del3TermType2D::get_cexprs, &Del3TermType2D::set_cexprs, "common exprs list" ) .property( "infos", &Del3TermType2D::get_infos, &Del3TermType2D::set_infos, "infos list" ) .property("args",&Del3TermType2D::get_args, &Del3TermType2D::set_args, "args setting") .property( "params", &Del3TermType2D::get_params, &Del3TermType2D::set_params, "params list" ) .method("get_envir",&Del3TermType2D::get_envir,"get envir") .method("set_struct",&Del3TermType2D::set_struct,"set struct") .method("get_struct",&Del3TermType2D::get_struct,"get struct") .method("set_current",&Del3TermType2D::set_current,"set point by coordinates (insertion) or index (suppression)") .method("get_current",&Del3TermType2D::get_current,"get point") .method("eval_first_expr",&Del3TermType2D::eval_first_expr,"eval first expr") .method("eval_exprs",&Del3TermType2D::eval_exprs,"eval exprs") .method("get_cexprs_caches",&Del3TermType2D::get_cexprs_caches,"get cexprs caches") //for debugging ; class_<All2TermType2D>( "All2TermType2D" ) .constructor() .field( "locBefore", &All2TermType2D::locBefore, "local list before" ) .field( "locAfter", &All2TermType2D::locAfter, "local list after" ) .field( "exprs.size", &All2TermType2D::exprs_size, "exprs size" ) .field( "cexprs.size", &All2TermType2D::cexprs_size, "cexprs size" ) //.property( "graph", &All2TermType2D::get_struct, &All2TermType2D::set_struct,"graph structure" ) .property( "mode", &All2TermType2D::get_mode, &All2TermType2D::set_mode, "mode " ) .property( "exprs", &All2TermType2D::get_exprs, &All2TermType2D::set_exprs, "exprs list" ) .property( "cexprs", &All2TermType2D::get_cexprs, &All2TermType2D::set_cexprs, "common exprs list" ) .property( "infos", &All2TermType2D::get_infos, &All2TermType2D::set_infos, "infos list" ) .property("args",&All2TermType2D::get_args, &All2TermType2D::set_args, "args setting") .property( "params", &All2TermType2D::get_params, &All2TermType2D::set_params, "params list" ) .method("get_envir",&All2TermType2D::get_envir,"get envir") .method("set_struct",&All2TermType2D::set_struct,"set struct") .method("get_struct",&All2TermType2D::get_struct,"get struct") .method("set_current",&All2TermType2D::set_current,"set point by coordinates (insertion) or index (suppression)") .method("get_current",&All2TermType2D::get_current,"get point") .method("make_before",&All2TermType2D::make_before_list,"make before list") .method("make_after",&All2TermType2D::make_after_list,"make after list") .method("eval_first_expr",&All2TermType2D::eval_first_expr,"eval first expr") .method("eval_exprs",&All2TermType2D::eval_exprs,"eval exprs") .method("get_cexprs_caches",&All2TermType2D::get_cexprs_caches,"get cexprs caches") //for debugging ; class_<Del2TermType3D>( "Del2TermType3D" ) .constructor() .field( "locBefore", &Del2TermType3D::locBefore, "documentation for locBefore" ) .field( "locAfter", &Del2TermType3D::locAfter, "documentation for locAfter" ) .field( "exprs.size", &Del2TermType3D::exprs_size, "exprs size" ) .field( "cexprs.size", &Del2TermType3D::cexprs_size, "cexprs size" ) //.property( "graph", &Del2TermType3D::get_struct, &Del2TermType3D::set_struct,"graph structure" ) .property( "mode", &Del2TermType3D::get_mode, &Del2TermType3D::set_mode, "mode " ) .property( "exprs", &Del2TermType3D::get_exprs, &Del2TermType3D::set_exprs, "exprs list" ) .property( "cexprs", &Del2TermType3D::get_cexprs, &Del2TermType3D::set_cexprs, "common exprs list" ) .property( "infos", &Del2TermType3D::get_infos, &Del2TermType3D::set_infos, "infos list" ) .property("args",&Del2TermType3D::get_args, &Del2TermType3D::set_args, "args setting") .property( "params", &Del2TermType3D::get_params, &Del2TermType3D::set_params, "params list" ) .method("set_struct",&Del2TermType3D::set_struct,"set struct") .method("get_struct",&Del2TermType3D::get_struct,"get struct") .method("set_current",&Del2TermType3D::set_current,"set point by coordinates (insertion) or index (suppression)") .method("get_current",&Del2TermType3D::get_current,"get point") .method("set_index",&Del2TermType3D::set_current_<DELETION>,"set (index) point to delete") .method("eval_first_expr",&Del2TermType3D::eval_first_expr,"eval first expr") .method("eval_exprs",&Del2TermType3D::eval_exprs,"eval exprs") ; class_<Interaction>("Interaction") .constructor<List>() .field( "single", &Interaction::single, "single parameter" ) //.method("set_before_mode",&Interaction::set_before_mode,"lset before mode") .method("set_current",&Interaction::set_current,"set current") .method("local_energy",&Interaction::local_energy,"local energy") ; class_<Domain>("DomainCpp") .constructor<std::vector<double>,std::vector<double> >() .field( "left", &Domain::left, "left" ) .field( "right", &Domain::right, "right" ) .field( "length_grid", &Domain::grid_length, "grid length" ) .field( "delta_grid", &Domain::grid_delta, "grid delta" ) .field( "size_grid", &Domain::grid_size, "grid size" ) .method("pick",&Domain::pick,"pick a point") .method("contains",&Domain::contains_,"contains") .method("get_dim",&Domain::get_dim,"get dim") .method("get_size",&Domain::get_size,"get size") .method("set_grid",&Domain::set_grid,"set grid") ; class_<GNZCache>("GNZCacheCpp") .constructor() //.constructor<Interaction*,Domain*>() .constructor< List,Domain* >() //.constructor< List,std::vector<double>,std::vector<double> >() .property("single",&GNZCache::get_single,&GNZCache::set_single,"single") .field( "nb_runs", &GNZCache::nb_runs, "nb_runs" ) .method("get_envir",&GNZCache::get_envir,"get envir") .method("get_inside_indexes",&GNZCache::get_inside_indexes,"get indexes inside domain") .method("get_inside_number",&GNZCache::get_inside_number,"get number of indexes inside domain") .method("get_mode",&GNZCache::get_mode,"get mode") .method("set_mode",&GNZCache::set_mode,"set mode") .method("mark_expr",&GNZCache::set_mark_expr,"set mark expr") .method("marked",&GNZCache::set_marked,"set marked") .method("new_mark",&GNZCache::new_mark,"new mark") .method("make_lists",&GNZCache::make_lists,"make lists cache") //.method("set_single",&GNZCache::set_single,"set single") .method("set_exprs_for_interaction",&GNZCache::set_exprs_for_interaction,"set caches exprs for interaction") .method("set_sizes_for_interaction",&GNZCache::set_sizes_for_interaction,"set caches sizes for interaction") .method("set_domain",&GNZCache::set_domain,"set domain") .method("get_domain",&GNZCache::get_domain,"get domain") .method("get_cexprs_lists",&GNZCache::get_cexprs_lists,"get cexprs lists cache") .method("get_exprs_lists",&GNZCache::get_exprs_lists,"get exprs lists") .method("eval_first_exprs",&GNZCache::eval_first_exprs,"eval first exprs") .method("eval_second_exprs",&GNZCache::eval_second_exprs,"eval second exprs") .method("eval_exprs",&GNZCache::eval_exprs,"eval exprs") ; class_<SimGibbs>( "SimGibbsCpp" ) .constructor() //.constructor< List,std::vector<double>,std::vector<double> >() .constructor< List,Domain* >() .field( "nb_runs", &SimGibbs::nb_runs, "nb_runs" ) .property("single",&SimGibbs::get_single,&SimGibbs::set_single,"single") .method("mark_expr",&SimGibbs::set_mark_expr,"set mark expr") .method("marked",&SimGibbs::set_marked,"set marked") .method("new_mark",&SimGibbs::new_mark,"new mark") .method("run",&SimGibbs::run,"run") .method("set_domain",&SimGibbs::set_domain,"set domain") .method("get_domain",&SimGibbs::get_domain,"get domain") ; }
[ "rdrouilh@gmail.com" ]
rdrouilh@gmail.com
ca9375375785c91e57d337726e5b877aa365e5ac
3062c8b8c05793b33b699c6800334c7ec07779d1
/neuralnetworks/aidl/utils/test/MockExecution.h
782e54f8742b8d136bed438a015c240b47208998
[ "Apache-2.0" ]
permissive
crdroidandroid/android_hardware_interfaces
d195f4fbd01ff8db36428667f73faff79a17b6e9
3ecf0495de1b1d20d42a0486ac3f742fc2758c5b
refs/heads/13.0
2023-08-18T19:30:51.587761
2023-08-12T18:01:14
2023-08-12T18:01:14
103,736,402
3
31
null
2023-07-29T14:54:17
2017-09-16T08:08:52
C++
UTF-8
C++
false
false
1,788
h
/* * Copyright (C) 2021 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. */ #ifndef ANDROID_HARDWARE_INTERFACES_NEURALNETWORKS_AIDL_UTILS_TEST_MOCK_EXECUTION_H #define ANDROID_HARDWARE_INTERFACES_NEURALNETWORKS_AIDL_UTILS_TEST_MOCK_EXECUTION_H #include <aidl/android/hardware/neuralnetworks/BnExecution.h> #include <android/binder_interface_utils.h> #include <gmock/gmock.h> #include <gtest/gtest.h> namespace aidl::android::hardware::neuralnetworks::utils { class MockExecution final : public BnExecution { public: static std::shared_ptr<MockExecution> create(); MOCK_METHOD(ndk::ScopedAStatus, executeSynchronously, (int64_t deadline, ExecutionResult* executionResult), (override)); MOCK_METHOD(ndk::ScopedAStatus, executeFenced, (const std::vector<ndk::ScopedFileDescriptor>& waitFor, int64_t deadline, int64_t duration, FencedExecutionResult* fencedExecutionResult), (override)); }; inline std::shared_ptr<MockExecution> MockExecution::create() { return ndk::SharedRefBase::make<MockExecution>(); } } // namespace aidl::android::hardware::neuralnetworks::utils #endif // ANDROID_HARDWARE_INTERFACES_NEURALNETWORKS_AIDL_UTILS_TEST_MOCK_EXECUTION_H
[ "xusongw@google.com" ]
xusongw@google.com
510ea97f4fe448a03d3b23ef066d9f71f9e7bec4
4b7ce5c214f4705eb994102f974be8e09609fe47
/Leetcode/836. Rectangle Overlap.cpp
f8367c4bcd419b0c45a272fbb91aed8bc966faab
[]
no_license
SEUNGHYUN-PARK/Algorithms
ab81cbdd8d43982a79131c75cb9ba402c24faa83
318624cc11a844c0082b25b9fd6bd099cb1befff
refs/heads/master
2020-03-07T21:07:55.572464
2019-01-15T14:26:18
2019-01-15T14:26:18
127,706,647
0
0
null
null
null
null
UTF-8
C++
false
false
281
cpp
class Solution { public: bool isRectangleOverlap(vector<int>& rec1, vector<int>& rec2) { if(rec2[2]<=rec1[0] || rec2[0]>=rec1[2]) return false; if(rec2[3]<=rec1[1] || rec2[1]>=rec1[3]) return false; return true; } };
[ "shstyle812@gmail.com" ]
shstyle812@gmail.com
e04082c6c4b9c55fe6a72d2941bb676dc1311cee
b0f1686f99446d54c21105a960feb4370c91306f
/Stack/Parenthesis Checker.cpp
39f5f22e37daf48c3fc15864be7cd4a7c2eb17dc
[]
no_license
AmanAswal/Geeksforgeeks
7d0a5fa60a8856871b5ec6a2879687e6019b68d8
70b5c1e4f82e4f08957ebd7b654e24f4ba28dd12
refs/heads/master
2022-11-27T00:52:38.196930
2020-08-04T04:54:03
2020-08-04T04:54:03
273,667,951
0
0
null
null
null
null
UTF-8
C++
false
false
895
cpp
bool ispar(string x) { stack<char> s; for(int i=0; i<x.length();i++) { char ch = x[i]; switch(ch) { case '(': case '{': case '[': s.push(ch); break; case ')': if(s.empty() || (s.top()!='(')){ return false; } else{ s.pop(); break; } case '}': if(s.empty() || (s.top()!='{')){ return false; } else{ s.pop(); break; } case ']': if(s.empty() || (s.top()!='[')){ return false; } else{ s.pop(); break; } } } return s.empty()? true:false; }
[ "noreply@github.com" ]
noreply@github.com
f5502acc22156618c3d0c64603c39ed210e418c4
37f12e47a3b4c08b927d225a24393b90b8a58beb
/Opdracht 6/SendHelp.h
bec67ce12f62eaf72e9d786107a64ae1cf997900
[]
no_license
simcha33/OBOPB
0e406641d7a78021f8f20bf98419fc6c3f2ac75f
740fed02908f99d40af0dd5b4851b50696ba88ac
refs/heads/master
2020-03-28T20:56:41.843979
2019-01-30T01:37:32
2019-01-30T01:37:32
149,115,992
0
0
null
null
null
null
UTF-8
C++
false
false
941
h
// // Created by simch on 12-11-2018. // #ifndef OPDRACHT_6_SENDHELP_H #define OPDRACHT_6_SENDHELP_H class Vehicle { protected: int bonusFee; int numberOfSeats; int kilometerPrice; public: virtual int berekenOpbrengst() = 0; }; class Bus : Vehicle { private: int numberOfSeats = 24; int bonusFee = 0; int kilometerPrice = 5; public: int calculateMoney(); }; class Train : Vehicle { private: int numberOfSeats = 600; int bonusFee = 0; int kilometerPrice = 4; public: int calculateMoney(); }; class ICE : Vehicle { private: int numberOfSeats = 600; int bonusFee = 20; int kilometerPrice = 10; public: int calculateMoney(); }; class Thalys : Vehicle { private: int numberOfSeats = 800; int bonusFee = 50; int kilometerPrice = 15; public: int calculateMoney(); }; #endif //OPDRACHT_6_SENDHELP_H
[ "noreply@github.com" ]
noreply@github.com
34139dac5a561cbac05fe19ab6a4934d539f77ac
d94bec121eed7c4982f9fd0ccfdd953c96a8f182
/common/imgui_file_dialog.cpp
a912a188beefe8c113067496c7bd0a471e813643
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
Hurleyworks/OptiX7_Utility
f2090369ab78b7d8c9c286bd86eef6bc48b50f30
67938b858aa7b6fae606b27a108066c1cefb4b12
refs/heads/master
2022-11-25T18:01:39.283631
2020-08-03T17:28:17
2020-08-03T17:28:17
284,817,364
0
0
null
2020-08-03T22:09:44
2020-08-03T22:09:43
null
SHIFT_JIS
C++
false
false
8,454
cpp
#include "imgui_file_dialog.h" FileDialog::Result FileDialog::drawAndGetResult() { namespace fs = std::filesystem; if (m_font) ImGui::PushFont(m_font); ImGuiIO &io = ImGui::GetIO(); ImGuiStyle &style = ImGui::GetStyle(); const auto getSeparatorHeightWithSpacing = [&style]() { return std::fmax(1, style.ItemSpacing.y); }; Result res = Result_Undecided; const float fileListMinHeight = 100; const float reducedItemSpacing = 1; const float windowMinHeight = ImGui::GetFrameHeight() + // Title bar ImGui::GetFrameHeightWithSpacing() + // dir path ImGui::GetFrameHeightWithSpacing() + // dir path buttons getSeparatorHeightWithSpacing() + // separator fileListMinHeight + style.ItemSpacing.y + getSeparatorHeightWithSpacing() + // separator ImGui::GetTextLineHeight() + reducedItemSpacing + // select count ImGui::GetFrameHeightWithSpacing() + // cur files ImGui::GetFrameHeight() + // OK/Cancel buttons 2 * style.WindowPadding.y; //ImGui::SetNextWindowSize(ImVec2(400, -1)); ImGui::SetNextWindowSizeConstraints(ImVec2(400, windowMinHeight), ImVec2(1e+6, 1e+6)); ImGui::SetNextWindowSize(ImVec2(600, 500), ImGuiCond_FirstUseEver); if (ImGui::BeginPopupModal(m_title, nullptr)) { fs::path newDir; bool fileDoubleClicked = false; // JP: カレントディレクトリの文字列を表示。 // EN: ImGui::PushID("Directory"); ImGui::SetNextItemWidth(-1); if (ImGui::InputText("", m_curDirText, sizeof(m_curDirText), ImGuiInputTextFlags_EnterReturnsTrue)) { fs::path dir = m_curDirText; if (fs::exists(dir)) { if (!fs::is_directory(dir)) dir.remove_filename(); newDir = dir; } else { newDir = m_curDir; } } ImGui::PopID(); // JP: カレントディレクトリのパスを分解してボタンとして表示する。 // EN: //ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0)); ImGui::BeginChild("Path Buttons", ImVec2(0, ImGui::GetFrameHeight())); for (auto it = m_curDirBlocks.begin(); it != m_curDirBlocks.end(); ++it) { if (it != m_curDirBlocks.begin()) ImGui::SameLine(); if (ImGui::Button(it->c_str())) { for (auto nit = m_curDirBlocks.begin(); nit != m_curDirBlocks.end(); ++nit) { newDir /= *nit; if (nit->find(':') == nit->length() - 1) newDir /= "\\"; if (nit == it) break; } } } ImGui::EndChild(); //ImGui::PopStyleVar(); ImGui::Separator(); // ---------------------------------------------------------------- // JP: ファイルリストの表示と選択処理。 float fileListHeight = std::fmax(ImGui::GetWindowSize().y - windowMinHeight, 0) + fileListMinHeight; ImGui::BeginChild("File List", ImVec2(ImGui::GetWindowContentRegionWidth(), fileListHeight)); bool multiplySelected = (m_numSelectedDirs + m_numSelectedFiles) > 1; bool selectionChanged = false; for (int i = 0; i < m_entryInfos.size(); ++i) { EntryInfo &entryInfo = m_entryInfos[i]; std::string name = entryInfo.is_directory() ? "[D] " : "[F] "; name += entryInfo.path().filename().u8string().c_str(); if (ImGui::Selectable(name.c_str(), entryInfo.selected, ImGuiSelectableFlags_DontClosePopups)) { if (((m_flags & Flag_DirectorySelection) && entryInfo.is_directory()) || ((m_flags & Flag_FileSelection) && !entryInfo.is_directory())) { // JP: 単一選択した場合は他の選択済み項目を非選択状態に変更する。 if (!ImGui::GetIO().KeyCtrl || ((m_flags & Flag_MultipleSelection) == 0)) { for (EntryInfo &e : m_entryInfos) { // JP: 複数選択状態なら選択状態になるようにする。 if (&e != &entryInfo || multiplySelected) e.selected = false; } } entryInfo.selected ^= true; selectionChanged = true; } } // JP: ダブルクリック時の処理。 if (ImGui::IsMouseDoubleClicked(0) && !ImGui::GetIO().KeyCtrl && ImGui::IsItemHovered()) { if (entryInfo.is_directory()) { if (entryInfo.path().is_relative()) newDir = m_curDir / entryInfo.path(); else newDir = entryInfo.path(); } else { // JP: 他の選択済み項目を非選択状態に変更する。 for (EntryInfo &e : m_entryInfos) { // JP: 複数選択状態なら自身だけ選択状態になるようにする。 if (&e != &entryInfo || multiplySelected) e.selected = false; } if ((m_flags & Flag_FileSelection) && !entryInfo.is_directory()) fileDoubleClicked = true; entryInfo.selected = true; selectionChanged = true; } } } if (selectionChanged) { m_numSelectedFiles = 0; m_numSelectedDirs = 0; for (int i = 0; i < m_entryInfos.size(); ++i) { const EntryInfo &entryInfo = m_entryInfos[i]; if (entryInfo.selected) { if (entryInfo.is_directory()) ++m_numSelectedDirs; else ++m_numSelectedFiles; } } genFilesText(); } ImGui::EndChild(); // END: // ---------------------------------------------------------------- ImGui::Separator(); ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(reducedItemSpacing, reducedItemSpacing)); ImGui::Text("%u files, %u dirs selected", m_numSelectedFiles, m_numSelectedDirs); ImGui::PopStyleVar(); ImGui::PushID("Current Files"); ImGui::SetNextItemWidth(-1); if (ImGui::InputText("", m_curFilesText, sizeof(m_curFilesText))) { } ImGui::PopID(); if (!newDir.empty()) changeDirectory(newDir); if (ImGui::Button("Cancel")) { ImGui::CloseCurrentPopup(); res = Result_Cancel; } ImGui::SameLine(); if (ImGui::Button("OK") || fileDoubleClicked) { ImGui::CloseCurrentPopup(); res = Result_OK; } ImGui::EndPopup(); } if (m_font) ImGui::PopFont(); return res; } void FileDialog::calcEntries(std::vector<std::filesystem::directory_entry>* entries) { namespace fs = std::filesystem; entries->clear(); std::string filesText = m_curFilesText; std::vector<std::string> fileFilters; while (!filesText.empty()) { size_t p = filesText.find(','); std::string file; if (p == std::string::npos) { file = filesText; filesText = ""; } else { file = filesText.substr(0, p); filesText = filesText.substr(p + 1); } if (!file.empty()) fileFilters.push_back(file); } for (const std::string &filter : fileFilters) { for (const EntryInfo &entryInfo : m_entryInfos) { if (((m_flags & Flag_DirectorySelection == 0) && entryInfo.is_directory()) || ((m_flags & Flag_FileSelection == 0) && !entryInfo.is_directory())) continue; if (entryInfo.path().filename().u8string() == filter) { if (entryInfo.path().is_relative()) entries->emplace_back(fs::canonical(m_curDir / entryInfo.path())); else entries->push_back(entryInfo.entry); break; } } } }
[ "shocker.0x15@gmail.com" ]
shocker.0x15@gmail.com
779dd04d25c23ea165f84567dd113e43e69a656f
77cdad40b288d062658af99a810628e3c0254a97
/Stage 2/ATmega/sketch_dec29a/sketch_dec29a.ino
6d41784c7e78eaac064f64bd706ae1a23de9a4f6
[]
no_license
petrushin-n-s/internship-assignment
4f3b746059c11171e93747ba4543825848a86af3
cc067c47d7ceafcc81bd79e49ed39d314fa84f3a
refs/heads/master
2023-03-10T20:08:49.722601
2021-02-22T14:50:03
2021-02-22T14:50:03
313,976,527
0
0
null
null
null
null
UTF-8
C++
false
false
693
ino
// ЛР9. Пример 1. Последовательный интерфейс I2C. Обработка информации от датчиков // Отправка данных c OrangePi на Ардуино через I2C #include <Wire.h> void setup() { pinMode(10, OUTPUT); pinMode(11, OUTPUT); Wire.begin(0x23); Wire.onReceive(recInt); Serial.begin(9600); } bool k = false; void loop() { int pin = 9; int d; if (k) d = 1; else d = 0; digitalWrite(pin + d, HIGH); delay(100); digitalWrite(pin + d, LOW); delay(100); } void recInt(int bytescount) { while (0 < Wire.available()) { int c = Wire.read(); if (c == 5) k = !k; Serial.println(c); } }
[ "petrushin.n.s@gmail.com" ]
petrushin.n.s@gmail.com
14cc5fa61d190e4b2de4f893229bc279ae1d72fb
b713405c04c190eca5efe146fd721eaf61426b50
/pais.h
2f5aff3637ea8e1b14b97ce49230e6df4491bbcc
[]
no_license
DanielMilstein/tarea4
a31e03dbfe31feb68c93e9111e62e545490240f9
49ed13d98df9cae84174694ef56b3948114bf2ee
refs/heads/main
2023-06-04T02:50:23.140657
2021-06-27T01:20:38
2021-06-27T01:20:38
376,196,244
0
0
null
null
null
null
UTF-8
C++
false
false
434
h
#ifndef _PAIS #define _PAIS #include<vector> #include <map> #include "city.h" using namespace std; class pais { public: pais(); vector<city> ciudades; int n = 0; map<pair<int, int>, double> edges; void agregar_ciudad(double, double); //Obvio double calcular(); //Longitud total de la via. double distancia_edge(double, double, double, double); //Entre 2 ciudades. double distancia(int, int); }; #endif
[ "dnmilstein@miuandes.cl" ]
dnmilstein@miuandes.cl
3e4f27d5e9dee359fa319289602acba6c1eb4b64
bf18adcb40cb7ae517890642cadf9ed6886ac818
/include/0Frame.h
49d16c234f0189911285d48a9afa036b7937d593
[]
no_license
Alegriabaile/My3dPhoto
c2709e219e334fe6f09c4cf00eaea76a76ba9696
5093fe88f8fcead541a1aee388b7f1f637adae3c
refs/heads/master
2022-05-14T18:56:39.401695
2020-01-16T14:05:37
2020-01-16T14:05:37
220,237,869
1
0
null
null
null
null
UTF-8
C++
false
false
1,107
h
// // Created by ale on 19-11-6. // #ifndef MY3DPHOTO_0FRAME_H #define MY3DPHOTO_0FRAME_H #include <opencv2/opencv.hpp> #include "0CameraParameters.h" namespace m3d { class State { public: unsigned int id; State(unsigned int id_ = 0): id(id_){} ~State(){} }; class Frame { public: std::string imageFileName; std::string depthFileName; std::string paramFileName; State state; ExtrinsicD extrinsicD; cv::Mat image, depth, disparity; std::vector<cv::KeyPoint> keypoints; cv::Mat descriptor; union { size_t minHwMaxHw[4]; struct { size_t minH, minW, maxH, maxW; }; }; cv::Mat pano_image, pano_depth, pano_error; cv::Mat pano_image_b, pano_depth_b; cv::Mat pano_label, pano_label_bgr; static IntrinsicD intrinsicD; static const size_t PANO_W; static const size_t PANO_H; Frame() = default; virtual ~Frame() {}; }; } #endif //MY3DPHOTO_0FRAME_H
[ "alegriabaile@gmail.com" ]
alegriabaile@gmail.com
351dd9fc21ab7799ac4c74ade0c489bd4d98e007
8f1c8940416dcef4492342ff02930dc63f4482e6
/interface/src/ui/overlays/Rectangle3DOverlay.cpp
383deb223928c961e4ca6a703a525c40f4619578
[ "Apache-2.0" ]
permissive
manlea/hifi
f24cd7dc244c6d13743eae23721b4ba6638c072a
2dff75dac126a11da2d2bcf6cb4a2ab55e633a10
refs/heads/master
2021-01-22T01:54:39.824202
2014-10-25T02:45:26
2014-10-25T02:45:26
25,757,352
1
0
null
null
null
null
UTF-8
C++
false
false
3,609
cpp
// // Rectangle3DOverlay.cpp // interface/src/ui/overlays // // Copyright 2014 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // // include this before QGLWidget, which includes an earlier version of OpenGL #include "InterfaceConfig.h" #include <QGLWidget> #include <SharedUtil.h> #include "Rectangle3DOverlay.h" #include "renderer/GlowEffect.h" Rectangle3DOverlay::Rectangle3DOverlay() { } Rectangle3DOverlay::~Rectangle3DOverlay() { } void Rectangle3DOverlay::render() { if (!_visible) { return; // do nothing if we're not visible } float alpha = getAlpha(); xColor color = getColor(); const float MAX_COLOR = 255.0f; glColor4f(color.red / MAX_COLOR, color.green / MAX_COLOR, color.blue / MAX_COLOR, alpha); glDisable(GL_LIGHTING); glm::vec3 position = getPosition(); glm::vec3 center = getCenter(); glm::vec2 dimensions = getDimensions(); glm::vec2 halfDimensions = dimensions * 0.5f; glm::quat rotation = getRotation(); float glowLevel = getGlowLevel(); Glower* glower = NULL; if (glowLevel > 0.0f) { glower = new Glower(glowLevel); } glPushMatrix(); glTranslatef(position.x, position.y, position.z); glm::vec3 axis = glm::axis(rotation); glRotatef(glm::degrees(glm::angle(rotation)), axis.x, axis.y, axis.z); glPushMatrix(); glm::vec3 positionToCenter = center - position; glTranslatef(positionToCenter.x, positionToCenter.y, positionToCenter.z); //glScalef(dimensions.x, dimensions.y, 1.0f); glLineWidth(_lineWidth); // for our overlay, is solid means we draw a solid "filled" rectangle otherwise we just draw a border line... if (getIsSolid()) { glBegin(GL_QUADS); glVertex3f(-halfDimensions.x, 0.0f, -halfDimensions.y); glVertex3f(halfDimensions.x, 0.0f, -halfDimensions.y); glVertex3f(halfDimensions.x, 0.0f, halfDimensions.y); glVertex3f(-halfDimensions.x, 0.0f, halfDimensions.y); glEnd(); } else { if (getIsDashedLine()) { glm::vec3 point1(-halfDimensions.x, 0.0f, -halfDimensions.y); glm::vec3 point2(halfDimensions.x, 0.0f, -halfDimensions.y); glm::vec3 point3(halfDimensions.x, 0.0f, halfDimensions.y); glm::vec3 point4(-halfDimensions.x, 0.0f, halfDimensions.y); drawDashedLine(point1, point2); drawDashedLine(point2, point3); drawDashedLine(point3, point4); drawDashedLine(point4, point1); } else { glBegin(GL_LINE_STRIP); glVertex3f(-halfDimensions.x, 0.0f, -halfDimensions.y); glVertex3f(halfDimensions.x, 0.0f, -halfDimensions.y); glVertex3f(halfDimensions.x, 0.0f, halfDimensions.y); glVertex3f(-halfDimensions.x, 0.0f, halfDimensions.y); glVertex3f(-halfDimensions.x, 0.0f, -halfDimensions.y); glEnd(); } } glPopMatrix(); glPopMatrix(); if (glower) { delete glower; } } void Rectangle3DOverlay::setProperties(const QScriptValue &properties) { Planar3DOverlay::setProperties(properties); }
[ "bradh@konamoxt.com" ]
bradh@konamoxt.com
3539a7fa1c635f1a9d0cac0e9c290f97e89c3297
59a44e2e0da612f3c93d4aea5f8f6fde9386510d
/core/Launcher.cpp
abf13803e0926867b4efe1f355caaf6d30400be8
[]
no_license
YerimB/OOP_arcade_2019
5d509f3c98adf483528a866a62da165a305fa034
d25f3ce51d7b56162f2be6b93b9954a94dec55b7
refs/heads/master
2022-11-21T18:56:22.689837
2020-07-22T08:56:31
2020-07-22T08:56:31
253,337,224
0
0
null
null
null
null
UTF-8
C++
false
false
3,711
cpp
/* ** EPITECH PROJECT, 2020 ** OOP_arcade_2019 ** File description: ** Launcher */ #include "Launcher.hpp" /** * @brief Launcher constructor * * Init Launcher and scan ./games directory to discover __.so games * Games are sorted alphabetically * * @return New instance of Launcher */ Launcher::Launcher() { std::string tmp; std::string line; std::string game; std::string score; std::string name; this->_gameSelection = true; for (const auto &entry : std::filesystem::directory_iterator("./games")) { tmp = entry.path().string(); if (tmp.compare(tmp.length() - 3, 3, ".so") == 0) this->_games.push_back(tmp); } std::sort( this->_games.begin(), this->_games.end(), [](const std::string &a, const std::string &b) { return (a < b); } // Lambda to sort ); std::ifstream scorefile; scorefile.open("score.txt"); if (scorefile.is_open()) { while (std::getline(scorefile, line)) { game = line.substr(0, line.find("|")); line = line.substr(line.find("|") + 1); name = line.substr(0, line.find("|")); line = line.substr(line.find("|") + 1); _scores[std::stoi(line)] = game + "->" + name; } } this->_currentIndex = 0; this->_selectedIndex = -1; } const std::string Launcher::formatText(const std::string &text) const { std::string tmp = text.substr(19); return (tmp.substr(0, tmp.find(".so"))); } const std::string Launcher::getColor(const int &index) const { if (index == this->_currentIndex) return ("yellow"); else if (index == this->_selectedIndex) return ("red"); return ("white"); } const std::vector<std::string> &Launcher::getInstructions(const std::string &event) { this->_instructions.clear(); int nb = 0; if (event == "e") { if (!this->_gameSelection) { this->_instructions.push_back("load " + _games[_currentIndex]); return (this->_instructions); } this->_gameSelection = false; } if (this->_gameSelection) { updateIndex(event); this->_instructions.push_back("text 'CHOSE GAME' 70 10 white"); this->_instructions.push_back("text 'press e to continue' 70 14 blue"); for (int i = 0; i < _games.size(); ++i) this->_instructions.push_back("text '" + formatText(_games[i]) \ + "' 70 " + std::to_string(25 + (i * 5)) + " " + getColor(i)); } else { this->_instructions.push_back("text 'press space to continue' 70 10 blue"); this->_instructions.push_back("text 'name:' 30 30 white"); this->_instructions.push_back("getstr text"); this->_instructions.push_back("text 'best scores:' 30 35 white"); for (auto it = _scores.rbegin(); it != _scores.rend(); it++) { if (nb == 3) break; if (it->second.substr(0, it->second.find("->") - 1) == formatText(_games[_currentIndex])) { _instructions.push_back( "text '" + it->second.substr(it->second.find("'") + 1, it->second.substr(it->second.find("'") + 1).find("'")) + "\t\t" + std::to_string(it->first) + "' 40 " + std::to_string(40 + (5 * nb)) + " green" ); nb++; } } } return (this->_instructions); } void Launcher::updateIndex(const std::string &direction) { if (direction == "down" && _currentIndex + 1 != _games.size()) _currentIndex += 1; else if (direction == "up" && _currentIndex - 1 >= 0) _currentIndex -= 1; }
[ "romain.bry@epitech.eu" ]
romain.bry@epitech.eu
95ec830f4e9780a72b10a6d5efc3c31ef10a1396
6d33b1bb5a0933297ed54ecc543be2d82921c048
/DLL/test/main.cpp
f7bfecbd2847a14920b1ee3fa35e6c9677f58112
[]
no_license
mapic91/MpcAsfTool
404ebc20dcf5309a5d28775494e7f10bcc4e2659
4b7aa5df0feeac97540ea5f870304d4a61068d42
refs/heads/master
2022-11-29T20:01:04.905305
2022-11-17T13:38:38
2022-11-17T13:38:38
32,773,531
12
12
null
null
null
null
UTF-8
C++
false
false
509
cpp
#include "wx/image.h" #include "JxqyPicture.h" int main(int argc, char** argv) { wxInitAllImageHandlers(); wxImage image; PBYTE data; if(ReadFile("2.spr")) { int width = GetCanvasWidth(); int height = GetCanvasHeight(); int count = GetFrameCount(); for(int i = 0 ; i < count; i++) { data = GetFrameDataRGB(i); image.Create(width, height, data, true); image.SaveFile(wxString::Format("0ut-%d.png", i), wxBITMAP_TYPE_PNG); } } FreeResource(); return 0; }
[ "mapic91@163.com" ]
mapic91@163.com
77c4583106c6e24b5217cbd183a30b9a4467d70c
76cae1f2493077e01a74014518037f7cb43120c2
/jni/mediaplayer/encoder_audio_mp3.cpp
7c66738d9db6bed74271d2f1f65e314db11685a8
[]
no_license
fanglinliu/AndPlayer
06ac690960d9ab117c8d9ba98854e0a9e12ea602
928c44b46af68d6be8c2c8e5a967f947abbcefcd
refs/heads/master
2021-01-21T17:22:50.591956
2014-09-05T17:01:38
2014-09-05T17:01:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,174
cpp
#include "encoder_audio_mp3.h" #include "mediaplayer.h" #define TAG "FFMpegEncoderAudioMP3" namespace ffmpeg { EncoderAudioMP3::EncoderAudioMP3(MediaPlayer* mediaPlayer, char* output, bool bEnableReverb) : EncoderAudio(mediaPlayer, output, bEnableReverb), mHandle(0) { mHandle = lame_init(); LOGI("Init parameters:"); lame_set_num_channels(mHandle, 2); lame_set_in_samplerate(mHandle, mMediaPlayer->getAudioSampleRate()); lame_set_brate(mHandle, 128000); lame_set_mode(mHandle, JOINT_STEREO); lame_set_quality(mHandle, 5); int res = lame_init_params(mHandle); LOGI("Init returned: %d", res); LOGI("initialized handle: %x", mHandle); } EncoderAudioMP3::~EncoderAudioMP3() { if (mHandle) { lame_close(mHandle); mHandle = NULL; } } void EncoderAudioMP3::doEncode() { AVPacket tmp_pkt1; AVPacket tmp_pkt2; AVPacket pkt1; AVPacket pkt2; int sampleRate = mMediaPlayer->getAudioSampleRate(); tmp_pkt1.size = tmp_pkt2.size = 0; tmp_pkt1.data = tmp_pkt2.data = 0; while(mRunning) { if(mPausing) { delay(10); continue; } if (tmp_pkt1.size <= 0) { if (mAudioBuffer1->get(&pkt1, true) < 0) { LOGI("failed to get buffer1"); break; } tmp_pkt1 = pkt1; } if (tmp_pkt2.size <= 0) { if (mAudioBuffer2->get(&pkt2, true) < 0) { LOGI("failed to get buffer2"); break; } tmp_pkt2 = pkt2; } int inputSize = FFMIN(tmp_pkt1.size, tmp_pkt2.size); int16_t* buffer1 = (int16_t*)tmp_pkt1.data; int16_t* buffer2 = (int16_t*)tmp_pkt2.data; for(int i = 0; i < inputSize / 2; i+=2) { int32_t l = buffer1[i] + buffer2[i]; int32_t r = buffer1[i + 1] + buffer2[i+1]; mMixedSamples[i] = clamp16(l); mMixedSamples[i+1] = clamp16(r); //mMixedSamples[i] = buffer1[i]; //mMixedSamples[i+1] = buffer2[i+1]; } if(mReverb) { //Do audio data reverb processing //OSStatus iRetVal = simpleDelay(mReverb, NULL, /*No use*/ inputSize / 2, mMixedSamples, sampleRate, 2); OSStatus iRetVal = simpleDelay1(mReverb, NULL, /*No use*/ inputSize / 2, mMixedSamples, sampleRate, 2); if (iRetVal != noErr) { LOGI("Unable to reverb audio: %x", noErr); } } tmp_pkt1.size -= inputSize; tmp_pkt1.data += inputSize; tmp_pkt2.size -= inputSize; tmp_pkt2.data += inputSize; if (tmp_pkt1.size <= 0) { av_free_packet(&pkt1); } if (tmp_pkt2.size <= 0) { av_free_packet(&pkt2); } int status = lame_encode_buffer_interleaved(mHandle, mMixedSamples, inputSize / 4, (unsigned char*)mOutputBuffer, AVCODEC_MAX_AUDIO_FRAME_SIZE * 2); if (status < 0) { if (status == -1) { LOGE("lame: output buffer too small"); } LOGI("Unable to encode frame: %x", status); break; } else if (status > 0) { fwrite(mOutputBuffer, 1, status, mOutFile); } } int status = lame_encode_flush(mHandle, (unsigned char*)mOutputBuffer, AVCODEC_MAX_AUDIO_FRAME_SIZE * 2); if (status > 0) { LOGI("Flushed %d bytes", status); fwrite(mOutputBuffer, 1, status, mOutFile); } } }
[ "okolitiy.viacheslav@yandex.ua" ]
okolitiy.viacheslav@yandex.ua
444e57f29716e7761e0af8b61527224f3ffa7a73
7eb2c186df7501fd3a3bbe670c4752a65e42997b
/Math/06.cpp
577a9612348400f5fd1cbc2f8eabf9ff3008b898
[]
no_license
varunjha089/The-Modern-C-Challenges
c9948527dd9b0ea5abb462ec0f5ea67ff8c7da0d
6bb8d262e0c225d05f7bb44790e7c83d42a1ebe7
refs/heads/main
2023-03-10T23:55:11.438766
2021-03-02T10:01:48
2021-03-02T10:01:48
343,146,162
0
0
null
null
null
null
UTF-8
C++
false
false
616
cpp
#include <iostream> bool is_prime(int const num){ if(num <= 3){ return num > 1; }else if(num % 2 == 0 || num % 3 == 0){ return false; }else{ for (int i = 5; i * i <= num; i += 6){ if(num % i == 0 || num % (i + 2) == 0){ return false; } } return true; } } int main(){ int limit = 0; std::cout << "Upper limit: "; std::cin >> limit; for (int n = 2; n <= limit; n++){ if(is_prime(n) && is_prime(n + 6)){ std::cout << n << ", " << n + 6 << std::endl; } } return 0; }
[ "varunjha089@gmail.com" ]
varunjha089@gmail.com
c63bb6131b49e26e53ae6212a3509695001ab26a
cc7661edca4d5fb2fc226bd6605a533f50a2fb63
/Assembly-CSharp/IPrefabNeedsWarming.h
1ee62d326bf97e71de654675c0eba1cdf79797a4
[ "MIT" ]
permissive
g91/Rust-C-SDK
698e5b573285d5793250099b59f5453c3c4599eb
d1cce1133191263cba5583c43a8d42d8d65c21b0
refs/heads/master
2020-03-27T05:49:01.747456
2017-08-23T09:07:35
2017-08-23T09:07:35
146,053,940
1
0
null
2018-08-25T01:13:44
2018-08-25T01:13:44
null
UTF-8
C++
false
false
91
h
#pragma once namespace rust { class IPrefabNeedsWarming { public: }; // size = 0x0 }
[ "info@cvm-solutions.co.uk" ]
info@cvm-solutions.co.uk