hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
651162572aa7b7cbd753b2f7fd25c25e50ba7b26
3,601
hpp
C++
ivarp/include/ivarp/refactor_constraint_system/bound_and_simplify/bounded.hpp
phillip-keldenich/squares-in-disk
501ebeb00b909b9264a9611fd63e082026cdd262
[ "MIT" ]
null
null
null
ivarp/include/ivarp/refactor_constraint_system/bound_and_simplify/bounded.hpp
phillip-keldenich/squares-in-disk
501ebeb00b909b9264a9611fd63e082026cdd262
[ "MIT" ]
null
null
null
ivarp/include/ivarp/refactor_constraint_system/bound_and_simplify/bounded.hpp
phillip-keldenich/squares-in-disk
501ebeb00b909b9264a9611fd63e082026cdd262
[ "MIT" ]
null
null
null
// The code is open source under the MIT license. // Copyright 2019-2020, Phillip Keldenich, TU Braunschweig, Algorithms Group // https://ibr.cs.tu-bs.de/alg // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies // of the Software, and to permit persons to whom the Software is furnished to do // so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // // Created by Phillip Keldenich on 18.01.20. // #pragma once namespace ivarp { namespace impl { template<typename Child, typename BoundsType, typename ArgBounds> struct BoundAndSimplify<BoundedMathExpr<Child, BoundsType>, ArgBounds, void> { using OldType = BoundedMathExpr<Child, BoundsType>; static inline IVARP_H auto apply(OldType&& old) { auto child_result = BoundAndSimplify<Child, ArgBounds>::apply(ivarp::move(old.child)); using CRT = decltype(child_result); using NewBounds = ExpressionBounds<ivarp::max(CRT::lb, BoundsType::lb), ivarp::min(CRT::ub, BoundsType::ub)>; return BoundedMathExpr<typename CRT::Child, NewBounds>{ivarp::move(child_result.child)}; } }; template<typename Child, typename BoundsType, typename ArgBounds> struct BoundAndSimplify<BoundedPredicate<Child, BoundsType>, ArgBounds, void> { private: using OldType = BoundedPredicate<Child, BoundsType>; template<typename NewBounds, typename Ch, std::enable_if_t<NewBounds::lb && NewBounds::ub, int> = 0> static inline IVARP_H auto simplify_by_bound(Ch&&) noexcept { return MathBoolConstant<bool,true,true>{true}; } template<typename NewBounds, typename Ch, std::enable_if_t<!NewBounds::lb && !NewBounds::ub, int> = 0> static inline IVARP_H auto simplify_by_bound(Ch&&) noexcept { return MathBoolConstant<bool,false,false>{false}; } template<typename NewBounds, typename Ch, std::enable_if_t<!NewBounds::lb && NewBounds::ub, int> = 0> static inline IVARP_H auto simplify_by_bound(Ch&& c) noexcept { return BoundedPredicate<std::remove_reference_t<Ch>, fixed_point_bounds::UnboundedPredicate>{ ivarp::forward<Ch>(c) }; } public: static inline IVARP_H auto apply(OldType&& old) { auto child_result = BoundAndSimplify<Child, ArgBounds>::apply(ivarp::move(old.child)); using CRT = decltype(child_result); using NewBounds = ExpressionBounds<CRT::lb || BoundsType::lb, CRT::ub && BoundsType::ub>; return simplify_by_bound<NewBounds>(ivarp::move(child_result.child)); } }; } }
43.914634
121
0.679811
phillip-keldenich
fb97ad979466ab2667fd371cd3d645500eda19eb
1,002
cpp
C++
progress/herding.cpp
birdhumming/usaco
f011e7bd4b71de22736a61004e501af2b273b246
[ "OLDAP-2.2.1" ]
null
null
null
progress/herding.cpp
birdhumming/usaco
f011e7bd4b71de22736a61004e501af2b273b246
[ "OLDAP-2.2.1" ]
null
null
null
progress/herding.cpp
birdhumming/usaco
f011e7bd4b71de22736a61004e501af2b273b246
[ "OLDAP-2.2.1" ]
null
null
null
#include <iostream> #include <fstream> using namespace std; bool herded(int A, int B, int C) { if (B-A==1 && C-B==1) return true; return false; } int find_min(int A, int B, int C, int moves) { if (herded(A, B, C)) { cout<<moves; return 0; } int ld, rd; //left distance, right distance ld=B-A, rd=C-B; if (ld==2 || rd==2) { cout<<moves+1; return 0; } cout<<moves+2; return 0; } int find_max(int A, int B, int C, int moves) { if (herded(A, B, C)) { cout<<moves<<'\n'; return 0; } int ld, rd; ld=B-A, rd=C-B; if (ld>=rd) { moves++; find_max(A, B-1, B, moves); } if (rd>ld) { moves++; find_max(B, B+1, C, moves); } return -1; } int main() { ifstream fin ("herding.in"); //freopen("herding.out", "w", stdout); cout<<"46\n"; int A, B, C; fin>>A>>B>>C; find_min(A, B, C, 0); cout<<'\n'; find_max(A, B, C, 0); }
18.555556
47
0.472056
birdhumming
fb97e50d4da5b7a44c96164089206351794cec06
1,547
cpp
C++
ch5/5-11_set_recv_buffer.cpp
JimmyTang178/MyLinuxServer
12d8b103163566090807469276fe4dcf4cef0b67
[ "Apache-2.0" ]
null
null
null
ch5/5-11_set_recv_buffer.cpp
JimmyTang178/MyLinuxServer
12d8b103163566090807469276fe4dcf4cef0b67
[ "Apache-2.0" ]
null
null
null
ch5/5-11_set_recv_buffer.cpp
JimmyTang178/MyLinuxServer
12d8b103163566090807469276fe4dcf4cef0b67
[ "Apache-2.0" ]
null
null
null
#include <sys/socket.h> #include <arpa/inet.h> #include <netinet/in.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <stdio.h> #include <assert.h> #define BUF_SIZE 1024 int main(int argc, char* argv[]){ if (argc <= 3){ printf("usage: %s ip port recv_buffer_size\n", argv[0]); return 1; } const char* ip = argv[1]; int port = atoi(argv[2]); struct sockaddr_in address; bzero(&address, sizeof(address)); address.sin_family = AF_INET; inet_pton(AF_INET, ip, &address.sin_addr); address.sin_port = htons(port); int sock = socket(AF_INET, SOCK_STREAM, 0); assert(sock >= 0); int recvbuf = atoi(argv[3]); int len = sizeof(recvbuf); /*先设置TCP接收缓冲区大小,然后立即读取*/ setsockopt(sock, SOL_SOCKET, SO_RCVBUF, &recvbuf, sizeof(recvbuf)); getsockopt(sock, SOL_SOCKET, SO_RCVBUF, &recvbuf, (socklen_t*)&len); printf("the TCP receive buffer size after setting is %d \n", recvbuf); int ret = bind(sock, (struct sockaddr*)&address, sizeof(address)); assert(ret != -1); ret = listen(sock, 5); assert(ret != -1); struct sockaddr_in client; socklen_t client_len = sizeof(client); int confd = accept(sock, (struct sockaddr*)&client, &client_len); if (confd < 0){ printf("errno is %d \n", errno); } else{ char buffer[BUF_SIZE]; memset(buffer, '\0', BUF_SIZE); while(recv(confd, buffer, BUF_SIZE-1, 0) > 0){ } close(confd); } close(sock); return 0; }
26.672414
74
0.618617
JimmyTang178
fb990ef5a987bd942b89128aa41020c92c8b31bd
251
cpp
C++
src/UOJ_1060 - (1698051) Accepted.cpp
dreamtocode/URI
1f402853e8ae43f3761fc3099e7694bff721d5bc
[ "MIT" ]
1
2015-04-26T03:55:07.000Z
2015-04-26T03:55:07.000Z
src/UOJ_1060 - (1698051) Accepted.cpp
dreamtocode/URI
1f402853e8ae43f3761fc3099e7694bff721d5bc
[ "MIT" ]
null
null
null
src/UOJ_1060 - (1698051) Accepted.cpp
dreamtocode/URI
1f402853e8ae43f3761fc3099e7694bff721d5bc
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { double a; int b = 0; for(int i = 0; i < 6; i++) { cin>>a; if (a==0) continue; if(a > 0) b++; } cout<<b<<" valores positivos\n"; return 0; }
16.733333
36
0.446215
dreamtocode
fb99bfed6e5eb5e89e24e969ae56f304c12a8651
870
cpp
C++
AZ3166/src/cores/arduino/system/SerialLog.cpp
duglah/devkit-sdk
7f016a1b00a25d6133009028c67b75e54495cf93
[ "MIT" ]
34
2019-05-08T07:36:51.000Z
2021-11-11T19:40:39.000Z
AZ3166/src/cores/arduino/system/SerialLog.cpp
duglah/devkit-sdk
7f016a1b00a25d6133009028c67b75e54495cf93
[ "MIT" ]
127
2018-01-04T10:24:22.000Z
2019-04-19T15:18:58.000Z
AZ3166/src/cores/arduino/system/SerialLog.cpp
duglah/devkit-sdk
7f016a1b00a25d6133009028c67b75e54495cf93
[ "MIT" ]
30
2018-01-15T03:40:57.000Z
2019-04-18T19:58:19.000Z
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. #include "Arduino.h" #ifdef __cplusplus extern "C" { #endif void serial_log(const char* msg) { if (msg != NULL) { Serial.print(msg); } } void serial_xlog(const char *format, ...) { va_list arg; va_start(arg, format); char temp[64]; char* buffer = temp; size_t len = vsnprintf(temp, sizeof(temp), format, arg); va_end(arg); if (len > sizeof(temp) - 1) { buffer = new char[len + 1]; if (!buffer) { return; } va_start(arg, format); vsnprintf(buffer, len + 1, format, arg); va_end(arg); } Serial.print(buffer); if (buffer != temp) { delete[] buffer; } } #ifdef __cplusplus } #endif
17.755102
61
0.514943
duglah
fb9a663e106034b1524963366ddb62a387e02449
2,749
cpp
C++
src/core/actions/set_categories_draw_disabled.cpp
svendcsvendsen/judoassistant
453211bff86d940c2b2de6f9eea2aabcdab830fa
[ "MIT" ]
3
2019-04-26T17:48:24.000Z
2021-11-08T20:21:51.000Z
src/core/actions/set_categories_draw_disabled.cpp
svendcsvendsen/judoassistant
453211bff86d940c2b2de6f9eea2aabcdab830fa
[ "MIT" ]
90
2019-04-25T17:23:10.000Z
2022-02-12T19:49:55.000Z
src/core/actions/set_categories_draw_disabled.cpp
judoassistant/judoassistant
3b200d3e35d9aff16ba224e6071ee9d888a5a03c
[ "MIT" ]
null
null
null
#include "core/actions/set_categories_draw_disabled.hpp" #include "core/actions/draw_categories_action.hpp" #include "core/draw_systems/draw_system.hpp" #include "core/rulesets/ruleset.hpp" #include "core/stores/category_store.hpp" #include "core/stores/tournament_store.hpp" SetCategoriesDrawDisabled::SetCategoriesDrawDisabled(std::vector<CategoryId> categoryIds, bool disabled) : SetCategoriesDrawDisabled(categoryIds, disabled, getSeed()) {} SetCategoriesDrawDisabled::SetCategoriesDrawDisabled(std::vector<CategoryId> categoryIds, bool disabled, unsigned int seed) : mCategoryIds(categoryIds) , mDisabled(disabled) , mSeed(seed) {} std::unique_ptr<Action> SetCategoriesDrawDisabled::freshClone() const { return std::make_unique<SetCategoriesDrawDisabled>(mCategoryIds, mDisabled, mSeed); } void SetCategoriesDrawDisabled::redoImpl(TournamentStore & tournament) { for (auto categoryId : mCategoryIds) { if (!tournament.containsCategory(categoryId)) continue; const auto &category = tournament.getCategory(categoryId); if (category.isDrawDisabled() == mDisabled) continue; mChangedCategories.push_back(categoryId); } for (auto categoryId : mChangedCategories) { CategoryStore & category = tournament.getCategory(categoryId); category.setDrawDisabled(mDisabled); } mDrawAction = std::make_unique<DrawCategoriesAction>(mChangedCategories, mSeed); mDrawAction->redo(tournament); tournament.changeCategories(mChangedCategories); } void SetCategoriesDrawDisabled::undoImpl(TournamentStore & tournament) { for (auto i = mChangedCategories.rbegin(); i != mChangedCategories.rend(); ++i) { auto categoryId = *i; CategoryStore & category = tournament.getCategory(categoryId); category.setDrawDisabled(!mDisabled); } mDrawAction->undo(tournament); tournament.changeCategories(mChangedCategories); // clean-up mDrawAction.reset(); mChangedCategories.clear(); } std::string SetCategoriesDrawDisabled::getDescription() const { if (mDisabled) return "Disabled categories match drawing"; return "Enable categories match drawing"; } bool SetCategoriesDrawDisabled::doesRequireConfirmation(const TournamentStore &tournament) const { if (!mDisabled) return false; // In this case, we only add matches for (auto categoryId : mCategoryIds) { if (!tournament.containsCategory(categoryId)) continue; const auto &category = tournament.getCategory(categoryId); if (category.isDrawDisabled() == mDisabled) continue; if (category.isStarted()) return true; } return false; }
32.72619
123
0.720626
svendcsvendsen
fba01e0641b67f43f20947fabad68968f2d80333
4,484
cpp
C++
SocketCode/PyC/serverP.cpp
TeCSAR-UNCC/NVDA_DETEC
6ec484ec0ef4ad1382056ceb0cd5e4c197c576b9
[ "Apache-2.0" ]
12
2019-05-10T09:56:39.000Z
2021-08-09T03:42:28.000Z
SocketCode/PyC/serverP.cpp
TeCSAR-UNCC/Edge-Video-Analytic
6ec484ec0ef4ad1382056ceb0cd5e4c197c576b9
[ "Apache-2.0" ]
null
null
null
SocketCode/PyC/serverP.cpp
TeCSAR-UNCC/Edge-Video-Analytic
6ec484ec0ef4ad1382056ceb0cd5e4c197c576b9
[ "Apache-2.0" ]
7
2019-06-14T03:38:09.000Z
2021-08-09T03:43:27.000Z
#include <unistd.h> #include <stdio.h> #include <sys/socket.h> #include <stdlib.h> #include <netinet/in.h> #include <string.h> #define PORT 65432 #define IPADDR INADDR_ANY #include "opencv2/opencv.hpp" using namespace cv; //g++ serverTest.cpp -o server `pkg-config --cflags --libs opencv` //gcc -shared -Wl,-soname,adder -o adder.so -fPIC add.c `pkg-config --cflags --libs opencv` //g++ -shared -o libServer.so -fPIC serverP.cpp `pkg-config --cflags --libs opencv` struct Info{ int name; int cameraID; int cx; int cy; int h; int w; }; struct uniqueID{ Info uInfo; //Mat hist; //uint8_t hits; //time }; #define TABLESIZE 300 #define NUMSTRUCTELEMENTS 6 #define SLOTFULL 1 #define SLOTEMPTY 0 #define NUMCOMMSOCK 100 //struct declaration and allocation int recvTable[TABLESIZE][NUMSTRUCTELEMENTS+1]; int comm_fd[NUMCOMMSOCK][2]; int listen_fd, comm; extern "C" int serverInit() { for(int i = 0; i < TABLESIZE; ++i) { recvTable[i][NUMSTRUCTELEMENTS] = SLOTEMPTY; } struct sockaddr_in servaddr; listen_fd = socket(AF_INET, SOCK_STREAM, 0); bzero( &servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htons(IPADDR); servaddr.sin_port = htons(PORT); bind(listen_fd, (struct sockaddr *) &servaddr, sizeof(servaddr)); return 0; } /* thread listen accept return the comm_fd to shift register thread the recv on that comm_fd (pop from shift register) send() close comm_fd */ extern "C" int cListen() { listen(listen_fd, 10); return 0; } extern "C" int cAccept() { comm = accept(listen_fd, (struct sockaddr*) NULL, NULL); return 0; } extern "C" int cListenAccept() { listen(listen_fd, 10); comm = accept(listen_fd, (struct sockaddr*) NULL, NULL); int commIndex = -1; for(int i = 0; i<NUMCOMMSOCK; ++i) { if(comm_fd[i][1] == SLOTEMPTY) { comm_fd[i][0] = comm; commIndex = i; comm_fd[i][1] = SLOTFULL; break; } } if(commIndex < 0) { printf("Error: comm_fd buffer is full\n"); close(comm); } return commIndex; } //returns -1 if no slot found extern "C" int cRecv(int commIndex) { //struct declaration and allocation struct Info recvStruct; int status = 1; //while(1) { status = recv(comm_fd[commIndex][0], &recvStruct, sizeof(recvStruct), 0); printf("Recieved: name: %d cx: %d\n", recvStruct.name, recvStruct.cx); int slot = -1; for(int i = 0; i < TABLESIZE; ++i) { if(recvTable[i][NUMSTRUCTELEMENTS] == SLOTEMPTY) { slot = i; break; } } if(slot >= 0) { //fill slot recvTable[slot][0] = recvStruct.name; recvTable[slot][1] = recvStruct.cameraID; recvTable[slot][2] = recvStruct.cx; recvTable[slot][3] = recvStruct.cy; recvTable[slot][4] = recvStruct.h; recvTable[slot][5] = recvStruct.w; recvTable[slot][NUMSTRUCTELEMENTS] = SLOTFULL; } else { printf("Buffer full: Received data not saved\n"); } //} return slot; } extern "C" int cSend(int commIdex, int name) { //char message[1024] = "Server Received"; int nm = name; send(comm_fd[commIdex][0], &nm, sizeof(int), 0); return 0; } extern "C" int cCloseListen() {; close(listen_fd); return 0; } extern "C" int cCloseComm(int commIndex) { close(comm_fd[commIndex][0]); comm_fd[commIndex][1] = SLOTEMPTY; printf("Closed Comm\n"); return 0; } //get functions extern "C" int getID(int slot) { return (recvTable[slot][0]); } //get functions extern "C" int getCamera(int slot) { return (recvTable[slot][1]); } //get functions extern "C" int getXPos(int slot) { return (recvTable[slot][2]); } //get functions extern "C" int getYPos(int slot) { return (recvTable[slot][3]); } //get functions extern "C" int getHeight(int slot) { return (recvTable[slot][4]); } //get functions extern "C" int getWidth(int slot) { return (recvTable[slot][5]); } //clear function extern "C" int clearSlot(int slot) { recvTable[slot][NUMSTRUCTELEMENTS] = SLOTEMPTY; return 0; } //print local table extern "C" void printTable() { for(int i = 0; i < TABLESIZE; ++i) { printf("Row: %d name: %d camera: %d cx: %d cy: %d h: %d w: %d b: %d\n", i, recvTable[i][0], recvTable[i][1], recvTable[i][2], recvTable[i][3], recvTable[i][4], recvTable[i][5], recvTable[i][6]); } } /* getCamera getID getXPos getYPos get */ /*int main(int argc, char const *argv[]) { int status = server(); return 0; } */
18.919831
91
0.640946
TeCSAR-UNCC
fba3edb2e9f0fe48298033d075a4778a8cd50850
5,779
cpp
C++
RogueEngine/Source/PatrolAI.cpp
silferysky/RogueArcher
3c77696260f773a0b7adb88b991e09bb35069901
[ "FSFAP" ]
1
2019-06-18T20:07:47.000Z
2019-06-18T20:07:47.000Z
RogueEngine/Source/PatrolAI.cpp
silferysky/RogueArcher
3c77696260f773a0b7adb88b991e09bb35069901
[ "FSFAP" ]
null
null
null
RogueEngine/Source/PatrolAI.cpp
silferysky/RogueArcher
3c77696260f773a0b7adb88b991e09bb35069901
[ "FSFAP" ]
null
null
null
/* Start Header ************************************************************************/ /*! \file PatrolAI.cpp \project Exale \author Chan Wai Kit Terence, c.terence, 440005918 (100%) \par c.terence\@digipen.edu \date 1 December,2019 \brief This file contains the function definitions for PatrolAI All content (C) 2019 DigiPen (SINGAPORE) Corporation, all rights reserved. Reproduction or disclosure of this file or its contents without the prior written consent of DigiPen Institute of Technology is prohibited. */ /* End Header **************************************************************************/ #include "Precompiled.h" #include "PatrolAI.h" #include "ParentEvent.h" namespace Rogue { PatrolAI::PatrolAI(Entity entity, LogicComponent& logicComponent, StatsComponent& statsComponent) : ScriptComponent(entity, logicComponent, statsComponent), m_currentPointIndex{0} { //AddWaypoint(g_engine.m_coordinator.GetComponent<TransformComponent>(entity).getPosition() - Vec2(100, 0)); //AddWaypoint(g_engine.m_coordinator.GetComponent<TransformComponent>(entity).getPosition()); //m_nextPoint.push(m_waypoints[0]); LogicInit(); } void PatrolAI::LogicInit() { if (g_engine.m_coordinator.ComponentExists<StatsComponent>(m_entity)) { StatsComponent& stats = g_engine.m_coordinator.GetComponent<StatsComponent>(m_entity); for (auto& waypoint : stats.getWaypoints()) { m_waypoints.push_back(waypoint); } if (stats.getWaypoints().size()) { if (auto trans = g_engine.m_coordinator.TryGetComponent<TransformComponent>(m_entity)) { trans->get().setPosition(*stats.getWaypoints().begin()); if (auto sound = g_engine.m_coordinator.TryGetComponent<AudioEmitterComponent>(m_entity)) sound->get().getSound().Set3DLocation(trans->get().GetPosition()); } if (stats.getWaypoints().size() > 1) { m_nextPoint.push(*(stats.getWaypoints().begin() + 1)); } else { m_nextPoint.push(*stats.getWaypoints().begin()); } } } if (g_engine.m_coordinator.ComponentExists<RigidbodyComponent>(m_entity)) { g_engine.m_coordinator.GetComponent<RigidbodyComponent>(m_entity).setIsStatic(true); } m_patrolDelay = 2.0f; m_delay = 0.0f; } void PatrolAI::AIActiveStateUpdate() { if (!g_engine.m_coordinator.GameIsActive()) return; m_logicComponent->SetActiveStateBit(static_cast<size_t>(AIState::AIState_Patrol)); m_logicComponent->SetActiveStateBit(static_cast<size_t>(AIState::AIState_Idle)); } void PatrolAI::AIPatrolUpdate() { //Only can do waypoint patrol if 2 waypoints exist //if (m_waypoints.size() < 2) //return; //Only can do waypoint patrol if set to Patrolling if (!m_statsComponent->GetIsPatrolling()) return; if (m_delay > 0.0f) { m_delay -= g_engine.GetTimeScale() * g_deltaTime; if (m_delay < 0.0f) m_delay = 0.0f; return; } //Check if Transform component and Rigidbody exist if (!(g_engine.m_coordinator.ComponentExists<TransformComponent>(m_entity) && g_engine.m_coordinator.ComponentExists<RigidbodyComponent>(m_entity) && m_statsComponent != nullptr)) return; ParentTransformEvent event(m_entity, true); event.SetSystemReceivers((int)SystemID::id_PARENTCHILDSYSTEM); EventDispatcher::instance().AddEvent(event); TransformComponent& aiTransform = g_engine.m_coordinator.GetComponent<TransformComponent>(m_entity); //Always move Vec2 travelDistance, travelDistValue; if (m_nextPoint.size()) travelDistValue = m_nextPoint.front() - aiTransform.GetPosition(); else if (m_waypoints.size()) { if (m_waypoints.size() == 1) return; m_nextPoint.push(m_waypoints.front()); travelDistValue = m_nextPoint.front() - aiTransform.GetPosition(); } else return; Vec2Normalize(travelDistance, travelDistValue); aiTransform.setPosition(aiTransform.GetPosition() + travelDistance * m_statsComponent->getSpeed() * DT_TRANSFORM_MODIFIER); if (auto sound = g_engine.m_coordinator.TryGetComponent<AudioEmitterComponent>(m_entity)) sound->get().getSound().Set3DLocation(aiTransform.GetPosition()); for (auto& child : g_engine.m_coordinator.GetHierarchyInfo(m_entity).m_children) { g_engine.m_coordinator.GetComponent<ChildComponent>(child).SetGlobalDirty(); } //If within a certain radius, assign next point if (Vec2SqDistance(aiTransform.GetPosition(), m_nextPoint.front()) < m_statsComponent->getSightRange() * m_statsComponent->getSightRange()) { //If only 1 waypoint, no need to pop and replace if (m_waypoints.size() == 1) return; float xChange = m_nextPoint.front().x; float yChange = m_nextPoint.front().y; m_nextPoint.pop(); if (++m_currentPointIndex >= m_waypoints.size()) m_currentPointIndex = 0; m_nextPoint.push(m_waypoints[m_currentPointIndex]); xChange = m_nextPoint.front().x - xChange; yChange = m_nextPoint.front().x - yChange; if (xChange > 0.0f) { aiTransform.setScale(Vec2(std::abs(aiTransform.GetScale().x), aiTransform.GetScale().y)); } else { aiTransform.setScale(Vec2(-1.0f * std::abs(aiTransform.GetScale().x), aiTransform.GetScale().y)); } m_delay = m_patrolDelay; } //if (g_engine.m_coordinator.GetHierarchyInfo(m_entity).m_children.size()) //{ // ParentTransformEvent& parentEv = new ParentTransformEvent(m_entity, MAX_ENTITIES); // parentEv.SetSystemReceivers((int)SystemID::id_PARENTCHILDSYSTEM); // EventDispatcher::instance().AddEvent(parentEv); //} } void PatrolAI::AddWaypoint(Vec2 newPoint) { m_waypoints.push_back(newPoint); } void PatrolAI::ClearWaypoints() { m_waypoints.clear(); } std::vector<Vec2> PatrolAI::GetWaypoints() { return m_waypoints; } }
30.256545
141
0.702025
silferysky
fba60b470c16f69d924243310f711e871656007b
1,339
cpp
C++
src/connection.cpp
Zack-83/xml2
e7e87ecb1f3d7ef0f5ce50148644a860ea8125c3
[ "MIT" ]
114
2017-06-14T07:07:32.000Z
2022-03-02T00:38:08.000Z
src/connection.cpp
Zack-83/xml2
e7e87ecb1f3d7ef0f5ce50148644a860ea8125c3
[ "MIT" ]
180
2017-07-19T21:42:10.000Z
2022-03-09T09:38:03.000Z
src/connection.cpp
Zack-83/xml2
e7e87ecb1f3d7ef0f5ce50148644a860ea8125c3
[ "MIT" ]
55
2017-07-28T21:42:38.000Z
2022-03-15T03:46:24.000Z
#include <Rinternals.h> #include <vector> #include "xml2_utils.h" // Wrapper around R's read_bin function SEXP read_bin(SEXP con, size_t bytes) { SEXP e; SEXP raw_sxp = PROTECT(Rf_mkString("raw")); SEXP bytes_sxp = PROTECT(Rf_ScalarInteger(bytes)); PROTECT(e = Rf_lang4(Rf_install("readBin"), con, raw_sxp, bytes_sxp)); SEXP res = Rf_eval(e, R_GlobalEnv); UNPROTECT(3); return res; } // Wrapper around R's write_bin function SEXP write_bin(SEXP data, SEXP con) { SEXP e; PROTECT(e = Rf_lang3(Rf_install("writeBin"), data, con)); SEXP res = Rf_eval(e, R_GlobalEnv); UNPROTECT(1); return res; } // Read data from a connection in chunks and then combine into a single // raw vector. // // [[export]] extern "C" SEXP read_connection_(SEXP con_sxp, SEXP read_size_sxp) { BEGIN_CPP std::vector<char> buffer; size_t read_size = REAL(read_size_sxp)[0]; SEXP chunk = read_bin(con_sxp, read_size); R_xlen_t chunk_size = Rf_xlength(chunk); while(chunk_size > 0) { std::copy(RAW(chunk), RAW(chunk) + chunk_size, std::back_inserter(buffer)); chunk = read_bin(con_sxp, read_size); chunk_size = Rf_xlength(chunk); } size_t size = buffer.size(); SEXP out = PROTECT(Rf_allocVector(RAWSXP, size)); std::copy(buffer.begin(), buffer.end(), RAW(out)); UNPROTECT(1); return out; END_CPP }
24.796296
79
0.695295
Zack-83
fbace5aef821cfaa0ed9b883f8217c9659afc97e
63,162
cpp
C++
RocketPlugin/RocketLobbyWidgets.cpp
Adminotech/meshmoon-plugins
32043ef783bdf137860d7d01eb22de564628e572
[ "Apache-2.0" ]
4
2018-05-09T01:55:14.000Z
2021-12-19T17:46:29.000Z
RocketPlugin/RocketLobbyWidgets.cpp
Adminotech/meshmoon-plugins
32043ef783bdf137860d7d01eb22de564628e572
[ "Apache-2.0" ]
null
null
null
RocketPlugin/RocketLobbyWidgets.cpp
Adminotech/meshmoon-plugins
32043ef783bdf137860d7d01eb22de564628e572
[ "Apache-2.0" ]
2
2016-03-15T06:12:05.000Z
2021-06-06T00:18:38.000Z
/** @author Adminotech Ltd. Copyright Adminotech Ltd. All rights reserved. @file @brief */ #include "StableHeaders.h" #include "RocketLobbyWidgets.h" #include "RocketLobbyWidget.h" #include "RocketPlugin.h" #include "utils/RocketAnimations.h" #include "Math/MathFunc.h" #include "Framework.h" #include "Application.h" #include "LoggingFunctions.h" #include "AssetAPI.h" #include "AssetCache.h" #include "IAsset.h" #include "IAssetTransfer.h" #include "ConfigAPI.h" #include "UiAPI.h" #include "UiMainWindow.h" #include <QFontMetrics> #include <QTextStream> namespace { static QString styleFrameBackgroundNormal = "QFrame#frameContent { background-color: rgba(255, 255, 255, 255);"; static QString styleFrameBackgroundHover = "QFrame#frameContent { background-color: rgba(245, 245, 245, 255);"; static QString styleFrameBackgroundSelected = "QFrame#frameContent { background-color: rgb(243, 154, 41);"; static QString styleNameLabelColorNormal = "QLabel#labelName { color: rgb(65, 65, 65);"; static QString styleNameLabelColorHover = "QLabel#labelName { color: black;"; static QString styleNameLabelColorSelected = "QLabel#labelName { color: rgba(255, 255, 255, 230);"; static QString styleCompanyLabelColorNormal = "QLabel#labelCompany { color: rgb(115, 115, 115);"; static QString styleCompanyLabelColorSelected = "QLabel#labelCompany { color: rgba(255, 255, 255, 210);"; } // RocketServerWidget RocketServerWidget::RocketServerWidget(Framework *framework, const Meshmoon::Server &inData) : RocketSceneWidget(framework, false), zoomed_(false), filtered(false), focused(false), selected(false), data(inData) { // Force convert _ to space in name and company. This fixes most of the word wrapping UI issues. if (!data.name.contains(" ") && data.name.contains("_")) data.name = data.name.replace("_", " "); if (!data.company.contains(" ") && data.company.contains("_")) data.company = data.company.replace("_", " "); } RocketServerWidget::~RocketServerWidget() { } void RocketServerWidget::InitializeWidget(QWidget *widget) { animations_->HookCompleted(this, SLOT(OnTransformAnimationsFinished(RocketAnimationEngine*, RocketAnimations::Direction))); ui_.setupUi(widget); // Data to UI ApplyDataToWidgets(); ApplyDataWidgetStyling(); // Profile picture if (!data.companyPictureUrl.isEmpty() || !data.txmlPictureUrl.isEmpty()) { // Do not request/load images to AssetAPI memory if they are already on disk. AssetTransferPtr transfer; QString existingImagePath = ""; if (!data.txmlPictureUrl.isEmpty()) { existingImagePath = framework_->Asset()->Cache()->FindInCache(data.txmlPictureUrl); if (existingImagePath.isEmpty()) transfer = framework_->Asset()->RequestAsset(data.txmlPictureUrl, "Binary"); } else if (!data.companyPictureUrl.isEmpty()) { existingImagePath = framework_->Asset()->Cache()->FindInCache(data.companyPictureUrl); if (existingImagePath.isEmpty()) transfer = framework_->Asset()->RequestAsset(data.companyPictureUrl, "Binary"); } if (transfer.get()) { connect(transfer.get(), SIGNAL(Succeeded(AssetPtr)), SLOT(OnProfilePictureLoaded(AssetPtr))); connect(transfer.get(), SIGNAL(Failed(IAssetTransfer*, QString)), SLOT(SetProfileImage())); } else SetProfileImage(existingImagePath); } else SetProfileImage(); } void RocketServerWidget::ApplyDataToWidgets() { // Set name and check font #ifdef Q_OS_MAC if (!data.name.contains(" ") && data.name.length() >= 26) #else if (!data.name.contains(" ") && data.name.length() >= 28) #endif { ui_.labelName->setStyleSheet(ui_.labelName->styleSheet().replace("font-size: 16px;", "font-size: 13px;")); } ui_.labelName->setText(data.name); // Company / MEP if (!data.mep.IsValid()) ui_.labelCompany->setText(data.company.toUpper()); else ui_.labelCompany->setText(QString("<span>%1</span> <span style='color:rgb(7,113,145);'>%2</span").arg(data.company.toUpper()).arg(data.mep.name)); // User if (data.running && stats.userCount > 0) { ui_.labelUserCount->setText(QString::number(stats.userCount)); ui_.labelUserCount->setToolTip(QString(stats.userCount > 1 ? "There are %1 users in this scene" : "There is %1 user in this scene").arg(stats.userCount)); } else ui_.labelUserCount->clear(); } void RocketServerWidget::SetOnlineStats(const Meshmoon::ServerOnlineStats &onlineStats) { stats = onlineStats; if (IsWidgetInitialized()) { // User count if (data.running && stats.userCount > 0) { ui_.labelUserCount->setText(QString::number(stats.userCount)); ui_.labelUserCount->setToolTip(QString(stats.userCount > 1 ? "There are %1 users in this scene" : "There is %1 user in this scene").arg(stats.userCount)); } else ui_.labelUserCount->clear(); } } void RocketServerWidget::ResetOnlineStats() { stats.Reset(); if (IsWidgetInitialized()) ui_.labelUserCount->clear(); } void RocketServerWidget::ApplyDataWidgetStyling() { ui_.labelIconPrivate->setVisible(!data.isPublic); if (!data.isPublic) ui_.labelIconPrivate->setPixmap(QPixmap(":/images/icon-lock-open.png")); ui_.labelIconMaintainance->setVisible(data.isUnderMaintainance); if (data.isUnderMaintainance) ui_.labelIconMaintainance->setPixmap(QPixmap(":/images/icon-maintainance.png")); // Left side markers if (data.isAdministratedByCurrentUser || data.mep.IsValid()) { QBoxLayout *targetLayout = dynamic_cast<QBoxLayout*>(ui_.frameContent->layout()); if (targetLayout) { QHBoxLayout *markers = new QHBoxLayout(); markers->setSpacing(0); markers->setContentsMargins(0, 0, 6, 0); if (data.mep.IsValid()) { QLabel *mepMarker = new QLabel(widget_); mepMarker->setFixedWidth(6); mepMarker->setStyleSheet("background-color: rgb(8, 149, 195); border: 0px; padding: 0px;"); markers->insertWidget(0, mepMarker); } if (data.isAdministratedByCurrentUser) { QLabel *ownerMarker = new QLabel(widget_); ownerMarker->setFixedWidth(6); ownerMarker->setStyleSheet("background-color: rgb(243, 154, 41); border: 0px; padding: 0px;"); markers->insertWidget(0, ownerMarker); } targetLayout->setContentsMargins(0, 0, 2, 0); targetLayout->insertLayout(0, markers); } } } void RocketServerWidget::FilterAndSuggest(Meshmoon::RelevancyFilter &filter) { if (filter.term.isEmpty()) { filtered = false; return; } filtered = true; if (filter.Match(data.name)) filtered = false; if (filter.Match(data.company)) filtered = false; if (filter.MatchIndirect(data.category)) filtered = false; foreach(const QString &userName, stats.userNames) if (filter.MatchIndirect(userName)) filtered = false; foreach(const QString &tag, data.tags) if (filter.MatchIndirect(tag)) filtered = false; } void RocketServerWidget::OnTransformAnimationsFinished(RocketAnimationEngine*, RocketAnimations::Direction) { if (hiding_) { hiding_ = false; hide(); } } void RocketServerWidget::UpdateGridPosition(int row, int column, int itemsPerHeight, int itemsPerWidth, bool isLast) { if (hiding_) return; QString borderStyle = "solid rgb(100, 100, 100)"; QString style = styleFrameBackgroundNormal + " border-radius: 0px; " + QString("border-top: %1px " + borderStyle + "; border-bottom: %2px " + borderStyle + "; border-left: %3px " + borderStyle + "; border-right: %4px " + borderStyle + "; ") .arg(row == 1 ? "1" : "0") .arg(row == itemsPerHeight ? "1" : "0") .arg(column == 1 ? "1" : "0") .arg("1"); if (row == 1 && column == 1) style.append("border-top-left-radius: 3px; "); if (row == itemsPerHeight && column == 1) style.append("border-bottom-left-radius: 3px; "); if ((row == 1 && column == itemsPerWidth) || (itemsPerHeight == 1 && isLast)) style.append("border-top-right-radius: 3px; "); if (isLast) style.append("border-bottom-right-radius: 3px; }"); else style.append("}"); if (ui_.frameContent->styleSheet() != style) ui_.frameContent->setStyleSheet(style); } void RocketServerWidget::SetFocused(bool focused_) { focused = false; SetSelected(false); focused = focused_; if (focused) ui_.frameContent->setStyleSheet(styleFrameBackgroundNormal + " border: 1px solid rgb(100, 100, 100); border-radius: 3px; }"); } void RocketServerWidget::SetSelected(bool selected_) { if (selected && !selected_) { ReplaceStyle(ui_.frameContent, QStringList() << styleFrameBackgroundSelected << styleFrameBackgroundHover, styleFrameBackgroundNormal); ReplaceStyle(ui_.labelName, QStringList() << styleNameLabelColorSelected << styleNameLabelColorHover, styleNameLabelColorNormal); ReplaceStyle(ui_.labelCompany, styleCompanyLabelColorSelected, styleCompanyLabelColorNormal); } selected = false; SetZoom(false); selected = selected_; if (selected) { ReplaceStyle(ui_.frameContent, QStringList() << styleFrameBackgroundNormal << styleFrameBackgroundHover, styleFrameBackgroundSelected); ReplaceStyle(ui_.labelName, QStringList() << styleNameLabelColorNormal << styleNameLabelColorHover, styleNameLabelColorSelected); ReplaceStyle(ui_.labelCompany, styleCompanyLabelColorNormal, styleCompanyLabelColorSelected); } } void RocketServerWidget::SetZoom(bool zoom) { if (focused || selected) return; if (zoom && !zoomed_) { zoomed_ = true; ReplaceStyle(ui_.frameContent, QStringList() << styleFrameBackgroundNormal << styleFrameBackgroundSelected, styleFrameBackgroundHover); ReplaceStyle(ui_.labelName, QStringList() << styleNameLabelColorNormal << styleNameLabelColorSelected, styleNameLabelColorHover); } else if (!zoom && zoomed_) { zoomed_ = false; ReplaceStyle(ui_.frameContent, QStringList() << styleFrameBackgroundHover << styleFrameBackgroundSelected, styleFrameBackgroundNormal); ReplaceStyle(ui_.labelName, QStringList() << styleNameLabelColorHover << styleNameLabelColorSelected, styleNameLabelColorNormal); } } bool RocketServerWidget::ReplaceStyle(QWidget *widget, const QStringList &targetStyles, const QString &replacementStyle) { foreach(const QString &targetStyle, targetStyles) { bool replaced = ReplaceStyle(widget, targetStyle, replacementStyle); if (replaced) return true; } return false; } bool RocketServerWidget::ReplaceStyle(QWidget *widget, const QString &targetStyle, const QString &replacementStyle) { if (!widget) return false; QString s = widget->styleSheet(); if (s.indexOf(targetStyle) == 0) { widget->setStyleSheet(s.replace(targetStyle, replacementStyle)); return true; } return false; } void RocketServerWidget::OnProfilePictureLoaded(AssetPtr asset) { SetProfileImage(asset ? asset->DiskSource() : ""); if (asset && framework_->Asset()->GetAsset(asset->Name()).get()) framework_->Asset()->ForgetAsset(asset, false); } void RocketServerWidget::SetProfileImage(const QString &path) { if (!path.isEmpty() && QFile::exists(path)) { QPixmap loadedIcon(path); if (!loadedIcon.isNull() && (loadedIcon.width() < 50 || loadedIcon.height() < 50)) loadedIcon = loadedIcon.scaled(QSize(50,50), Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation); if (!loadedIcon.isNull()) { ui_.labelIcon->setPixmap(loadedIcon); return; } } // Fallback ui_.labelIcon->setPixmap(QPixmap(":/images/server-anon.png")); } void RocketServerWidget::CheckTooltip(bool show) { if (show) emit HoverChange(this, true); else emit HoverChange(this, false); } void RocketServerWidget::hoverEnterEvent(QGraphicsSceneHoverEvent *event) { QGraphicsProxyWidget::hoverEnterEvent(event); SetZoom(true); CheckTooltip(true); } void RocketServerWidget::hoverMoveEvent(QGraphicsSceneHoverEvent *event) { QGraphicsProxyWidget::hoverMoveEvent(event); SetZoom(true); CheckTooltip(true); } void RocketServerWidget::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) { QGraphicsProxyWidget::hoverLeaveEvent(event); SetZoom(false); CheckTooltip(false); } void RocketServerWidget::mousePressEvent(QGraphicsSceneMouseEvent *event) { QGraphicsProxyWidget::mousePressEvent(event); if (!focused) emit FocusRequest(this); else emit UnfocusRequest(this); } // RocketPromotionWidget RocketPromotionWidget::RocketPromotionWidget(Framework *framework, const Meshmoon::PromotedServer &inData) : RocketSceneWidget(framework), data(inData), focused(false), promoting(false) { ui_.setupUi(widget_); // Change size animation to opacity opacityAnim_ = new QPropertyAnimation(this, "opacity", this); opacityAnim_->setEasingCurve(QEasingCurve::OutCubic); opacityAnim_->setDuration(500); timer.setSingleShot(true); connect(opacityAnim_, SIGNAL(finished()), SLOT(OnPromotionOpacityAnimationFinished())); connect(&timer, SIGNAL(timeout()), SIGNAL(Timeout())); setOpacity(0.0); hide(); } RocketPromotionWidget::~RocketPromotionWidget() { if (timer.isActive()) timer.stop(); } void RocketPromotionWidget::SetGeometry(const QSizeF &size, const QPointF &pos) { widget_->setMinimumSize(size.toSize()); widget_->setMaximumSize(size.toSize()); setGeometry(QRectF(pos, size)); } void RocketPromotionWidget::RestartTimer() { if (timer.isActive()) timer.stop(); timer.start(data.durationMsec); } void RocketPromotionWidget::Show() { SetPromoting(true); LoadRequiredImage(); if (IsHiddenOrHiding()) { if (isVisible()) hide(); opacityAnim_->stop(); opacityAnim_->setDirection(QAbstractAnimation::Forward); opacityAnim_->setStartValue(opacity()); setVisible(true); // resets opacity opacityAnim_->setEndValue(1.0); opacityAnim_->start(); } if (!timer.isActive()) timer.start(data.durationMsec); } void RocketPromotionWidget::Animate(const QSizeF &newSize, const QPointF &newPos, qreal newOpacity, const QRectF &sceneRect, RocketAnimations::Animation anim) { widget_->setMaximumSize(newSize.toSize()); RocketSceneWidget::Animate(newSize, newPos, newOpacity, sceneRect, anim); } void RocketPromotionWidget::Hide(RocketAnimations::Animation anim, const QRectF & /*sceneRect*/) { SetPromoting(false); if (isVisible()) { if (anim != RocketAnimations::NoAnimation) { // Opacity anim opacityAnim_->stop(); opacityAnim_->setDirection(QAbstractAnimation::Backward); opacityAnim_->setStartValue(0.0); opacityAnim_->setEndValue(opacity()); opacityAnim_->start(); } else { hide(); setOpacity(0.0); } } if (timer.isActive()) timer.stop(); } void RocketPromotionWidget::AboutToBeShown() { LoadRequiredImage(); } void RocketPromotionWidget::SetFocused(bool focused_) { if (focused == focused_) return; focused = focused_; if (focused && largeImage_.isNull()) LoadRequiredImage(); ui_.labelImage->setPixmap(focused ? largeImage_ : smallImage_); ui_.labelImage->setCursor(focused ? Qt::ArrowCursor : Qt::PointingHandCursor); if (focused && timer.isActive()) timer.stop(); } void RocketPromotionWidget::SetPromoting(bool promoting_) { if (promoting != promoting_) promoting = promoting_; } void RocketPromotionWidget::OnPromotionOpacityAnimationFinished() { if (opacityAnim_->direction() == QAbstractAnimation::Backward) { hide(); setOpacity(0.0); } } void RocketPromotionWidget::OnSmallImageCompleted(AssetPtr asset) { QString diskSource = asset->DiskSource(); if (asset && framework_->Asset()->GetAsset(asset->Name()).get()) framework_->Asset()->ForgetAsset(asset, false); LoadSmallImage(diskSource); if (promoting) Show(); } void RocketPromotionWidget::OnLargeImageCompleted(AssetPtr asset) { QString diskSource = asset->DiskSource(); if (asset && framework_->Asset()->GetAsset(asset->Name()).get()) framework_->Asset()->ForgetAsset(asset, false); LoadLargeImage(diskSource); } void RocketPromotionWidget::LoadRequiredImage() { if (!focused && smallImage_.isNull() && !data.smallPicture.trimmed().isEmpty()) { QString diskSource = framework_->Asset()->Cache()->FindInCache(data.smallPicture); if (diskSource.isEmpty()) { AssetTransferPtr smallTransfer = framework_->Asset()->RequestAsset(data.smallPicture, "Binary"); connect(smallTransfer.get(), SIGNAL(Succeeded(AssetPtr)), SLOT(OnSmallImageCompleted(AssetPtr))); connect(smallTransfer.get(), SIGNAL(Failed(IAssetTransfer*, QString)), SLOT(LoadSmallImage())); } else LoadSmallImage(diskSource); } if (focused && largeImage_.isNull() && data.type == "world" && !data.largePicture.trimmed().isEmpty()) { QString diskSource = framework_->Asset()->Cache()->FindInCache(data.largePicture); if (diskSource.isEmpty()) { AssetTransferPtr largeTransfer = framework_->Asset()->RequestAsset(data.largePicture, "Binary"); connect(largeTransfer.get(), SIGNAL(Succeeded(AssetPtr)), SLOT(OnLargeImageCompleted(AssetPtr))); connect(largeTransfer.get(), SIGNAL(Failed(IAssetTransfer*, QString)), SLOT(LoadLargeImage())); } else LoadLargeImage(diskSource); } } void RocketPromotionWidget::LoadSmallImage(const QString &path) { if (path.isEmpty()) { LogError("Small promotion image path is empty for " + data.name + ". Transfer failed?"); return; } smallImage_ = QPixmap(path); if (smallImage_.isNull()) LogWarning("Failed to create small promotion picture for " + data.name); else { if (smallImage_.width() > 960) { LogWarning("Small promotion picture wider than 960x200, scaling down: " + data.name); smallImage_ = smallImage_.scaledToWidth(960, Qt::SmoothTransformation); } if (smallImage_.height() > 200) { LogWarning("Small promotion picture higher than 960x200, scaling down: " + data.name); smallImage_ = smallImage_.scaledToHeight(200, Qt::SmoothTransformation); } if (!focused) { ui_.labelImage->setPixmap(smallImage_); ui_.labelImage->setCursor(Qt::PointingHandCursor); } } } void RocketPromotionWidget::LoadLargeImage(const QString &path) { if (path.isEmpty()) { LogError("Large promotion image path is empty for " + data.name + ". Transfer failed?"); return; } largeImage_ = QPixmap(path); if (largeImage_.isNull()) LogWarning("Failed to create large promotion picture for " + data.name); else { if (largeImage_.width() > 960) { LogWarning("Large promotion picture wider than 960x600, scaling down: " + data.name); largeImage_ = largeImage_.scaledToWidth(960, Qt::SmoothTransformation); } if (largeImage_.height() > 600) { LogWarning("Large promotion picture higher than 960x600, scaling down: " + data.name); largeImage_ = largeImage_.scaledToHeight(600, Qt::SmoothTransformation); } if (focused) { ui_.labelImage->setPixmap(largeImage_); ui_.labelImage->setCursor(Qt::ArrowCursor); } } } void RocketPromotionWidget::mousePressEvent(QGraphicsSceneMouseEvent *event) { QGraphicsProxyWidget::mousePressEvent(event); if (!focused) { opacityAnim_->stop(); setOpacity(1.0); emit Pressed(this); } } // RocketLobbyActionButton RocketLobbyActionButton::RocketLobbyActionButton(Framework *framework_, Direction direction) : RocketSceneWidget(framework_), direction_(direction), mode_(Unknown) { widget_->setObjectName("widget"); widget_->setLayout(new QVBoxLayout(widget_)); widget_->layout()->setContentsMargins(0,0,0,0); widget_->layout()->setSpacing(0); button_ = new QPushButton(widget_); button_->setObjectName("button"); button_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); widget_->layout()->addWidget(button_); SetArrowLook(); connect(button_, SIGNAL(clicked()), SIGNAL(Pressed())); setZValue(zValue() - 5); hide(); } RocketLobbyActionButton::~RocketLobbyActionButton() { } void RocketLobbyActionButton::SetArrowLook() { button_->setText(""); if (mode_ != Arrow) { mode_ = Arrow; widget_->setMaximumSize(QSize(32,32)); widget_->setStyleSheet(QString("QWidget#widget { background-color: transparent; } QPushButton#button { transparent; \ border: 0px; background-position: %1 center; background-image: url(\"%2\"); } QPushButton#button:hover { background-image: url(\"%3\"); } ") .arg(direction_ == Left ? "left" : "right").arg(direction_ == Left ? ":/images/icon-previous.png" : ":/images/icon-next.png") .arg(direction_ == Left ? ":/images/icon-previous-hover.png" : ":/images/icon-next-hover.png")); } } void RocketLobbyActionButton::SetButtonLook(const QString &message) { button_->setText(message); if (mode_ != Button) { mode_ = Button; widget_->setMaximumSize(QSize(16000,16000)); widget_->setStyleSheet(QString("QWidget#widget { background-color: transparent; } QPushButton#button { background-color: rgba(255, 255, 255, 255); \ border: 1px solid rgb(100, 100, 100); border-radius: 3px; font-family: \"Arial\"; font-size: 22px; color: rgb(91, 91, 91); } \ QPushButton#button:hover { background-color: rgba(255, 255, 255, 200); color: black; } \ QPushButton#button:pressed { background-color: rgba(255, 255, 255, 100); }")); } } QString RocketLobbyActionButton::GetButtonText() { return button_->text(); } // RocketLoaderWidget RocketLoaderWidget::RocketLoaderWidget(Framework *framework) : QGraphicsObject(0), framework_(framework), step_(0), opacity_(0), timerId_(-1), buttonCount_(2.0), sizeChanged_(true), isPromoted(false), percent_(-1.0) { serverData_.Reset(); movie_ = new QMovie(":/images/loader-big.gif", "GIF"); movie_->setCacheMode(QMovie::CacheAll); font_.setFamily("Arial"); font_.setPointSize(16); font_.setBold(true); percentFont_.setFamily("Arial"); percentFont_.setPointSize(80); percentFont_.setBold(true); setZValue(505); hide(); } RocketLoaderWidget::~RocketLoaderWidget() { StopAnimation(); SAFE_DELETE(movie_); } void RocketLoaderWidget::StartAnimation() { if (timerId_ == -1) { timerId_ = startTimer(40); step_ = 0; opacity_ = 0; percent_ = -1.0; movie_->start(); } } void RocketLoaderWidget::StopAnimation() { if (timerId_ != -1) { killTimer(timerId_); timerId_ = -1; isPromoted = false; percent_ = -1.0; movie_->stop(); } } void RocketLoaderWidget::Show() { if (!isVisible()) { sizeChanged_ = true; buttonCount_ = 2.0; show(); } } void RocketLoaderWidget::Hide(bool takeScreenShot) { if (isVisible()) hide(); StopAnimation(); // We will take a screenshot for load screen purposes after 30 seconds. // The delay is here because a) we don't want to lag the hide animation of // the portal widget (happens when this is called) b) We want the world to load // completely (or as much as it can in 30 seconds) and possibly let the user // move a bit to get some variation from the startup position. if (takeScreenShot && serverData_.CanProcessShots()) QTimer::singleShot(30000, this, SLOT(StoreServerScreenshot())); } void RocketLoaderWidget::LoadServerScreenshot() { if (serverData_.CanProcessShots()) { serverImage_ = QPixmap::fromImage(serverData_.LoadScreenShot(framework_)); sizeChanged_ = true; } } void RocketLoaderWidget::StoreServerScreenshot() { if (serverData_.CanProcessShots()) serverData_.StoreScreenShot(framework_); } void RocketLoaderWidget::SetServer(const Meshmoon::Server &serverData) { ResetServer(); serverData_ = serverData; LoadServerScreenshot(); } void RocketLoaderWidget::SetMessage(const QString &message) { message_ = message; } void RocketLoaderWidget::SetGeometry(const QSizeF &size, const QPointF &pos) { if (size_ != size) { prepareGeometryChange(); size_ = size; sizeChanged_ = true; } setPos(pos); } void RocketLoaderWidget::ResetServer() { serverData_.Reset(); message_ = ""; serverImage_ = QPixmap(); buffer_ = QPixmap(); } QRectF RocketLoaderWidget::boundingRect() const { return QRectF(0, 0, size_.width(), size_.height()); } void RocketLoaderWidget::timerEvent(QTimerEvent * /*event*/) { if (step_ < 200) step_++; else step_ = 0; if (opacity_ < 200) opacity_ += 10; update(QRectF(0, 0, size_.width(), size_.height())); } void RocketLoaderWidget::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/) { int buttonHeight = 62; int margin = 9; QRectF rect(0, 0, size_.width(), size_.height()); QRectF imageRect(0, buttonHeight+margin, size_.width(), size_.height()-(buttonHeight+margin)); QSizeF pieSize = imageRect.height() > imageRect.width() ? QSizeF(imageRect.width()/1.2, imageRect.width()/1.2) : QSizeF(imageRect.height()/1.2, imageRect.height()/1.2); QRectF textRect(0,0,(rect.width() - margin)/buttonCount_, buttonHeight); if (!serverImage_.isNull()) { if (sizeChanged_ || buffer_.isNull()) { QSize renderSize = imageRect.size().toSize(); QSize imageSize = serverImage_.size(); qreal xFactor = (qreal)imageSize.width() / (qreal)renderSize.width(); qreal yFactor = (qreal)imageSize.height() / (qreal)renderSize.height(); if (xFactor > yFactor) { buffer_ = serverImage_.scaledToHeight(renderSize.height(), Qt::SmoothTransformation); slideRect_ = QRectF(buffer_.width()/2.0 - renderSize.width()/2.0, 0, renderSize.width(), renderSize.height()); } else { buffer_ = serverImage_.scaledToWidth(renderSize.width(), Qt::SmoothTransformation); slideRect_ = QRectF(0, buffer_.height()/2.0 - renderSize.height()/2.0, renderSize.width(), renderSize.height()); } sizeChanged_ = false; } painter->drawPixmap(imageRect, buffer_, slideRect_); painter->setPen(QColor(183,185,184)); painter->setBrush(Qt::transparent); painter->drawRect(imageRect); } if (!message_.isEmpty()) { QTextOption textOption(Qt::AlignCenter); textOption.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere); painter->setPen(QColor(90,90,90)); painter->setFont(font_); painter->drawText(textRect, message_, textOption); } if (movie_->state() == QMovie::Running) { QPixmap currentFrame = movie_->currentPixmap(); if (currentFrame.width() > pieSize.toSize().width() || currentFrame.height() > pieSize.toSize().height()) currentFrame = currentFrame.scaled(pieSize.toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation); if (!serverImage_.isNull() || isPromoted) { painter->setPen(Qt::transparent); painter->setBrush(QColor(255,255,255,opacity_)); painter->drawRect(imageRect); } painter->drawPixmap(imageRect.center() - QPointF(currentFrame.width()/2.0, currentFrame.height()/2.0), currentFrame, currentFrame.rect()); } if (percent_ > 0.0) { int percentAlpha = static_cast<int>(percent_ / 100.0 * 255) + 50; if (percentAlpha > 255) percentAlpha = 255; painter->setPen(QColor(242,154,41,percentAlpha)); painter->setFont(percentFont_); QPointF imageCenter = imageRect.center(); QRectF percentRect = QRectF(imageCenter.x()-(percent_ < 10.0 ? 175 : 148), imageCenter.y()-100, 200, 200); painter->drawText(percentRect, Qt::AlignRight|Qt::AlignVCenter, QString::number(Floor(percent_))); QFont f = painter->font(); f.setPointSize(36); painter->setFont(f); painter->setPen(QColor(90,90,90,percentAlpha)); percentRect.translate(200, -18); painter->drawText(percentRect, Qt::AlignLeft|Qt::AlignVCenter, "%"); } } void RocketLoaderWidget::SetButtonCount( int buttonCount ) { buttonCount_ = (qreal)buttonCount; } void RocketLoaderWidget::SetCompletion(qreal percent) { // Don't allow to go back in progress while loading world. if (percent > percent_) { percent_ = percent; if (percent_ > 100.0) percent_ = 100.0; } } // RocketServerFilter RocketServerFilter::RocketServerFilter(RocketLobby *controller) : QTextEdit("", 0), controller_(controller), sortCriteriaButton_(0), sortCriteriaMenu_(0), emptyTermFired_(false), helpText_("<span style=\"color:grey;\">" + tr("Search") + "...</span>") { ReadConfig(); setObjectName("filterLineEdit"); // Try to fix mac font alignment on written text. Suggestions render to center. setAlignment(Qt::AlignLeft|Qt::AlignVCenter); setAttribute(Qt::WA_LayoutUsesWidgetRect, true); setAcceptRichText(true); setTabChangesFocus(false); setText(helpText_); setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); setFocusPolicy(Qt::ClickFocus); setMinimumHeight(35); setMaximumHeight(35); setMinimumWidth(150); setMaximumWidth(960); setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); connect(this, SIGNAL(textChanged()), SLOT(OnTextChanged())); orderDelayTimer_.setSingleShot(true); connect(&orderDelayTimer_, SIGNAL(timeout()), SLOT(OnOrderServers())); focusDelayTimer_.setSingleShot(true); connect(&focusDelayTimer_, SIGNAL(timeout()), SLOT(OnCheckFocus())); // Sort criterial configuration sortCriteriaButton_ = new QPushButton(Meshmoon::ServerScore::SortCriteriaToString(currentSortCriterial_), this); sortCriteriaButton_->setObjectName("sortCriteriaButton"); sortCriteriaButton_->setCursor(Qt::PointingHandCursor); sortCriteriaButton_->setToolTip("World Sorting Criteria"); connect(sortCriteriaButton_, SIGNAL(clicked()), SLOT(OnShowSortingConfigMenu())); sortCriteriaMenu_ = new QMenu(); sortCriteriaMenu_->setStyleSheet("QMenu::item:disabled { color: rgb(188, 99, 22); }"); CreateSortCriterialTitle("Sorting"); for (int i=0; i<static_cast<int>(Meshmoon::ServerScore::SortCriterialNumItems); i++) { QAction *act = sortCriteriaMenu_->addAction(Meshmoon::ServerScore::SortCriteriaToString(static_cast<Meshmoon::ServerScore::SortCriteria>(i))); act->setProperty("scoreCriterialIndex", i); act->setCheckable(true); act->setChecked(false); } // Admin and active world configuration CreateSortCriterialTitle("Ordering"); CreateSortCriterialAction("My spaces first", "favorAdministratedWorlds", "Shows spaces that you administer first in the space listing", favorAdministratedWorlds_); CreateSortCriterialAction("My Meshmoon Education Program spaces first", "favorMEPWorlds", "Shows MEP spaces that you are a part of first in the space listing", favorMEPWorlds_); CreateSortCriterialAction("Spaces with users first", "favorActiveWorlds", "Shows worlds that currently have users in them first in the world listing", favorActiveWorlds_); CreateSortCriterialTitle("Show"); CreateSortCriterialAction("Private worlds", "showPrivateWorlds", "Shows private worlds I have access to in the world listing", showPrivateWorlds_); CreateSortCriterialAction("Worlds under maintenance", "showMaintenanceWorlds", "Shows worlds that are currently under maintenance in the world listing", showMaintenanceWorlds_); connect(sortCriteriaMenu_, SIGNAL(triggered(QAction*)), SLOT(OnSortConfigChanged(QAction*))); sortCriteriaButton_->setMinimumHeight(minimumHeight()); sortCriteriaButton_->setMaximumHeight(maximumHeight()); sortCriteriaButton_->setVisible(false); // <rant> // Do filter suggestion from a proxy widget that gets rendered // on top of this widget. It is very hard to make proper logic with // keeping the real input text and the suggestion after it (with a different color i might add). // Keeping the text cursor always in the proper position and reseting the suggestion at the right times, ugh. // Proxy might be a bit heavier on the rendering but this is easy to work with. // </rant> suggestLabel_ = new QLabel(); suggestLabel_->setAlignment(Qt::AlignLeft|Qt::AlignVCenter); suggestLabel_->setStyleSheet("QLabel { background-color: transparent; color: rgb(186, 186, 186); font-family: \"Arial\"; font-size: 22px; }"); suggestLabel_->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); suggestProxy_ = new QGraphicsProxyWidget(0, Qt::Widget); suggestProxy_->setWidget(suggestLabel_); suggestionListProxy_ = new RocketSceneWidget(controller->GetFramework(), false); suggestionListProxy_->showOpacity = 1.0; SAFE_DELETE(suggestionListProxy_->widget_); QListWidget *listWidget = new QListWidget(); suggestionListProxy_->widget_ = listWidget; suggestionListProxy_->widget_->installEventFilter(this); suggestionListProxy_->setZValue(suggestionListProxy_->zValue() * 2); suggestionListProxy_->widget_->hide(); connect(listWidget, SIGNAL(itemClicked(QListWidgetItem*)), SLOT(OnSuggestionListItemSelected(QListWidgetItem*))); suggestionListProxy_->widget_->setStyleSheet(QString( "QListView { \ background-color: rgba(255, 255, 255, 220); \ font-family: \"Arial\"; \ font-size: 22px; \ padding: 0px; \ margin: 0px; \ show-decoration-selected: 1; \ outline: none; \ min-height: 5px; \ }") + "QListView::item { \ color: rgb(150, 150, 150); \ min-height: 25px; \ max-height: 25px; \ border: 0px; \ padding: 0px; \ margin: 0px; \ padding-left: 5px; \ } \ QListView::item:selected, ::item:selected:hover { \ background-color: rgba(200, 200, 200, 80); \ color: rgb(88, 88, 88); \ } \ QListView::item:hover { \ color: rgb(120, 120, 120); \ }"); controller_->GetFramework()->Ui()->GraphicsScene()->addItem(suggestionListProxy_); controller_->GetFramework()->Ui()->GraphicsScene()->addItem(suggestProxy_); Hide(); } RocketServerFilter::~RocketServerFilter() { controller_ = 0; } QAction *RocketServerFilter::CreateSortCriterialTitle(const QString &text) { if (!sortCriteriaMenu_) return 0; QAction *title = sortCriteriaMenu_->addAction(text); QFont titleFont("Arial"); titleFont.setPixelSize(13); titleFont.setWeight(QFont::Bold); title->setProperty("menuGroupTitle", true); title->setFont(titleFont); title->setEnabled(false); return title; } QAction *RocketServerFilter::CreateSortCriterialAction(const QString &text, const QString &propertyName, const QString &tooltip, bool checked) { if (!sortCriteriaMenu_) return 0; QAction *act = sortCriteriaMenu_->addAction(text); act->setProperty(qPrintable(propertyName), true); act->setCheckable(true); act->setChecked(checked); act->setToolTip(tooltip); act->setStatusTip(tooltip); return act; } void RocketServerFilter::ReadConfig() { if (!controller_) return; ConfigData config("rocket-lobby", "sorting"); currentSortCriterial_ = static_cast<Meshmoon::ServerScore::SortCriteria>(controller_->GetFramework()->Config()->DeclareSetting(config, "sortCriteriaType", static_cast<int>(Meshmoon::ServerScore::TopYear)).toInt()); favorAdministratedWorlds_ = controller_->GetFramework()->Config()->DeclareSetting(config, "favorAdministratedWorlds", true).toBool(); favorMEPWorlds_ = controller_->GetFramework()->Config()->DeclareSetting(config, "favorMEPWorlds", true).toBool(); favorActiveWorlds_ = controller_->GetFramework()->Config()->DeclareSetting(config, "favorActiveWorlds", true).toBool(); showMaintenanceWorlds_ = controller_->GetFramework()->Config()->DeclareSetting(config, "showMaintenanceWorlds", true).toBool(); showPrivateWorlds_ = controller_->GetFramework()->Config()->DeclareSetting(config, "showPrivateWorlds", true).toBool(); } void RocketServerFilter::WriteConfig() { if (!controller_) return; ConfigData config("rocket-lobby", "sorting"); controller_->GetFramework()->Config()->Write(config, "sortCriteriaType", static_cast<int>(currentSortCriterial_)); controller_->GetFramework()->Config()->Write(config, "favorAdministratedWorlds", favorAdministratedWorlds_); controller_->GetFramework()->Config()->Write(config, "favorMEPWorlds", favorMEPWorlds_); controller_->GetFramework()->Config()->Write(config, "favorActiveWorlds", favorAdministratedWorlds_); controller_->GetFramework()->Config()->Write(config, "showMaintenanceWorlds", showMaintenanceWorlds_); controller_->GetFramework()->Config()->Write(config, "showPrivateWorlds", showPrivateWorlds_); } void RocketServerFilter::SetSortCriteriaInterfaceVisible(bool visible) { if (!sortCriteriaButton_) return; sortCriteriaButton_->setVisible(visible); if (visible) { // Highlight the UI for a sec if we are about to sort by a non-default criteria. if (currentSortCriterial_ != Meshmoon::ServerScore::TotalLoginCount) { sortCriteriaButton_->setStyleSheet("color: rgb(219, 137, 37);"); QTimer::singleShot(1500, this, SLOT(OnRestoreSearchCriteriaButton())); } QTimer::singleShot(1, this, SLOT(UpdateGeometry())); } } void RocketServerFilter::UnInitialize(Framework *framework) { framework->Ui()->GraphicsScene()->removeItem(suggestProxy_); SAFE_DELETE(suggestProxy_); framework->Ui()->GraphicsScene()->removeItem(suggestionListProxy_); SAFE_DELETE(suggestionListProxy_); SAFE_DELETE(sortCriteriaMenu_); suggestLabel_ = 0; controller_ = 0; } void RocketServerFilter::Show() { if (isVisible()) return; emptyTermFired_ = false; show(); HideAndClearSuggestions(); QTimer::singleShot(100, this, SLOT(UpdateGeometry())); } void RocketServerFilter::ShowSuggestionLabel(bool updateGeometryDelayed) { if (suggestProxy_ && !suggestProxy_->isVisible()) suggestProxy_->show(); if (updateGeometryDelayed) QTimer::singleShot(1, this, SLOT(UpdateGeometry())); } void RocketServerFilter::ShowSuggestionList(bool updateGeometryDelayed) { if (suggestionListProxy_ && suggestionListProxy_->IsHiddenOrHiding()) suggestionListProxy_->Show(); if (updateGeometryDelayed) QTimer::singleShot(1, this, SLOT(UpdateGeometry())); } void RocketServerFilter::Hide() { if (isVisible()) hide(); emptyTermFired_ = false; clearFocus(); if (suggestionListProxy_) suggestionListProxy_->clearFocus(); HideSuggestionLabel(true); HideSuggestionList(true); } void RocketServerFilter::HideSuggestionLabel(bool clearText) { if (suggestProxy_ && suggestProxy_->isVisible()) suggestProxy_->hide(); if (clearText && suggestLabel_ && !suggestLabel_->text().isEmpty()) suggestLabel_->clear(); } void RocketServerFilter::HideSuggestionList(bool clearItems) { if (suggestionListProxy_ && !suggestionListProxy_->IsHiddenOrHiding()) suggestionListProxy_->Hide(RocketAnimations::NoAnimation); if (clearItems) { QListWidget *list = suggestionListProxy_->WidgetAs<QListWidget>(); if (list) list->clear(); } } QString RocketServerFilter::GetTerm() { QString term = toPlainText(); if (IsPlaceholder(term)) term = ""; return term; } bool RocketServerFilter::IsTermValid() { return !GetTerm().isEmpty(); } void RocketServerFilter::ApplyCurrentTerm() { emptyTermFired_ = false; HideAndClearSuggestions(); OnTextChanged(); HideSuggestionLabel(); HideSuggestionList(); } bool RocketServerFilter::HasOpenMenus() { return (sortCriteriaMenu_ && sortCriteriaMenu_->isVisible()); } bool RocketServerFilter::HasFocus() { return (hasFocus() || (suggestionListProxy_ && suggestionListProxy_->hasFocus())); } void RocketServerFilter::EmitCurrentSortConfigChanged() { if (sortCriteriaButton_) { sortCriteriaButton_->setStyleSheet("color: rgb(219, 137, 37);"); QTimer::singleShot(1500, this, SLOT(OnRestoreSearchCriteriaButton())); } emit SortConfigChanged(); } void RocketServerFilter::OnRestoreSearchCriteriaButton() { if (sortCriteriaButton_) sortCriteriaButton_->setStyleSheet(""); } void RocketServerFilter::OnShowSortingConfigMenu() { if (!sortCriteriaMenu_) return; foreach(QAction *act, sortCriteriaMenu_->actions()) { if (act->property("scoreCriterialIndex").isValid()) act->setChecked(currentSortCriterial_ == static_cast<Meshmoon::ServerScore::SortCriteria>(act->property("scoreCriterialIndex").toInt())); } sortCriteriaMenu_->popup(QCursor::pos()); } void RocketServerFilter::OnSortConfigChanged(QAction *act) { if (!sortCriteriaButton_ || !act) return; if (act->property("scoreCriterialIndex").isValid()) { currentSortCriterial_ = static_cast<Meshmoon::ServerScore::SortCriteria>(act->property("scoreCriterialIndex").toInt()); sortCriteriaButton_->setText(Meshmoon::ServerScore::SortCriteriaToString(currentSortCriterial_)); } else if (act->property("favorAdministratedWorlds").isValid()) favorAdministratedWorlds_ = act->isChecked(); else if (act->property("favorMEPWorlds").isValid()) favorMEPWorlds_ = act->isChecked(); else if (act->property("favorActiveWorlds").isValid()) favorActiveWorlds_ = act->isChecked(); else if (act->property("showPrivateWorlds").isValid()) showPrivateWorlds_ = act->isChecked(); else if (act->property("showMaintenanceWorlds").isValid()) showMaintenanceWorlds_ = act->isChecked(); else return; WriteConfig(); EmitCurrentSortConfigChanged(); QTimer::singleShot(1, this, SLOT(UpdateGeometry())); } bool RocketServerFilter::IsPlaceholder(const QString &term) { return (term == tr("Search") + "..."); } void RocketServerFilter::OnTextChanged() { if (!controller_) return; QString term = GetTerm(); // Make widgets decide if they are visible or not with the current term Meshmoon::RelevancyFilter filter(term, Qt::CaseInsensitive); foreach(RocketServerWidget *server, controller_->Servers()) { if (!ShowPrivateWorlds() && !server->data.isPublic) continue; if (!ShowMaintenanceWorlds() && server->data.isUnderMaintainance) continue; server->FilterAndSuggest(filter); } UpdateSuggestionWidgets(filter); if (orderDelayTimer_.isActive()) orderDelayTimer_.stop(); orderDelayTimer_.start((term.isEmpty() ? 1 : 250)); } void RocketServerFilter::OnOrderServers() { if (!controller_) return; // Order servers, uses the filter information from widgets. // Track when we send empty term to lobby sorting, only send once in a row. QString term = GetTerm(); if (emptyTermFired_ && term.isEmpty()) return; controller_->OrderServers(!term.isEmpty(), !term.isEmpty() ? true : false); emptyTermFired_ = term.isEmpty(); // If there is only one visible search result, hide box and select the server. int visibleServers = controller_->VisibleServers(); if (visibleServers == 1 && suggestionListProxy_->isVisible()) HideSuggestionList(); if (visibleServers == 1 && HasFocus() && !suggestProxy_->isVisible()) controller_->SelectFirstServer(); } void RocketServerFilter::UpdateSuggestionWidgets(Meshmoon::RelevancyFilter &filter) { if (!filter.term.isEmpty() && !IsPlaceholder(filter.term)) { if (filter.HasHits()) { QStringList allSuggestions = filter.AllValues(); // We can only show direct hits in the line edit suggestions if (filter.HasDirectHits()) { QStringList directSuggestions = filter.DirectValues(); QString suggestion = directSuggestions.takeFirst(); QString originalSuggestion = suggestion; allSuggestions.removeAll(suggestion); int startIndex = suggestion.indexOf(filter.term, 0 , Qt::CaseInsensitive); if (startIndex == -1) startIndex = 0; // Should never happen. suggestion = suggestion.right(suggestion.length() - filter.term.length() - startIndex); // Split the term from first space to show suggestions one word at a time. // But if there is only one direct suggestion left, use it fully! if (!directSuggestions.isEmpty()) { /** We still might be able to find a common prefix with multiple spaces among the remaining direct suggestions. term = "demo sce" suggestion 1 = "demo scene meshmoon"; suggestion 2 = "demo scene meshmoon one"; suggestion 3 = "demo scene meshmoon two"; should pick = "demo scene meshmoon" NOT "demo scene" */ bool remainingSamePrefix = true; foreach(const QString &remainingDirect, directSuggestions) { if (!remainingDirect.startsWith(originalSuggestion, Qt::CaseInsensitive)) { remainingSamePrefix = false; break; } } if (!remainingSamePrefix && suggestion.indexOf(" ", 1) != -1) suggestion = suggestion.left(suggestion.indexOf(" ", 1)); } // Set suggestion to proxy. suggestLabel_->setText(suggestion); QTextCursor cur = textCursor(); cur.movePosition(QTextCursor::End); setTextCursor(cur); ShowSuggestionLabel(); } else HideSuggestionLabel(true); // Update suggestion list if (suggestionListProxy_) { QListWidget *list = suggestionListProxy_->WidgetAs<QListWidget>(); if (list && allSuggestions.size() > 0) { list->clear(); for (int si=0; si<allSuggestions.size(); si++) { if (si >= 4) break; list->addItem(filter.GuaranteeStartsWithCase(allSuggestions[si])); } ShowSuggestionList(); } else HideSuggestionList(true); } UpdateGeometry(); } else HideAndClearSuggestions(); } else HideAndClearSuggestions(); } void RocketServerFilter::UpdateGeometry() { if (!controller_ || !suggestProxy_ || !suggestLabel_ || !controller_->ui_.contentFrame) return; int criterialButtonWidth = 0; if (sortCriteriaButton_ && sortCriteriaButton_->isVisible()) { // Make this button fixed size depending on the text width. QFontMetrics m(sortCriteriaButton_->font()); criterialButtonWidth = m.width(sortCriteriaButton_->text()) + 8 + 12; sortCriteriaButton_->setFixedWidth(criterialButtonWidth); sortCriteriaButton_->move(width() - criterialButtonWidth - 37, 0); } QPoint scenePos = controller_->ui_.contentFrame->pos() + pos(); if (suggestLabel_->isVisible()) { float yPosFilter = 1.5; // Calculate position and size for suggestion proxy. This looks weird but is correct // as long as the padding in the style sheet is not changed (the 5 in x). QRect rect = cursorRect(); QPoint scenePosCursor = scenePos + rect.topLeft(); scenePosCursor.setX(scenePosCursor.x() + 5 + rect.width()); suggestProxy_->setGeometry(QRectF(scenePosCursor, QSizeF(width() - rect.x() - criterialButtonWidth - 37, height() - (rect.y()*yPosFilter)))); } if (suggestionListProxy_->isVisible()) { QListWidget *list = suggestionListProxy_->WidgetAs<QListWidget>(); int itemCount = list ? list->count() : 0; if (itemCount > 0) suggestionListProxy_->setGeometry(QRectF(scenePos + QPoint(0, height()-3), QSizeF(width(), itemCount * 25 + 5))); else HideSuggestionList(); } } void RocketServerFilter::HideAndClearSuggestions() { if (!suggestProxy_ || !suggestLabel_ || !suggestionListProxy_) return; HideSuggestionList(true); HideSuggestionLabel(true); } void RocketServerFilter::ApplySuggestion(bool selectFirstServerOnEmpty) { if (!suggestLabel_) return; if (suggestLabel_->isVisible()) { QString suggestion = suggestLabel_->text(); if (!suggestion.isEmpty()) { HideAndClearSuggestions(); setText(toPlainText() + suggestion); QTextCursor cur = textCursor(); cur.movePosition(QTextCursor::End); setTextCursor(cur); UpdateGeometry(); // Apply sorting immediately if (orderDelayTimer_.isActive()) orderDelayTimer_.stop(); OnOrderServers(); return; } } else if (selectFirstServerOnEmpty) { if (controller_ && !GetTerm().isEmpty()) controller_->SelectFirstServer(); } } void RocketServerFilter::OnSuggestionListItemSelected(QListWidgetItem *item) { if (!item) return; QString suggestion = item->text(); if (!suggestion.isEmpty()) { HideAndClearSuggestions(); setText(suggestion); QTextCursor cur = textCursor(); cur.movePosition(QTextCursor::End); setTextCursor(cur); setFocus(Qt::TabFocusReason); UpdateGeometry(); // Apply sorting immediately if (orderDelayTimer_.isActive()) orderDelayTimer_.stop(); OnOrderServers(); } } void RocketServerFilter::OnCheckFocus() { if (!HasFocus()) { HideSuggestionLabel(); HideSuggestionList(); } } void RocketServerFilter::focusInEvent(QFocusEvent *e) { QTextEdit::focusInEvent(e); if (toPlainText() == tr("Search") + "...") setText(""); else if (suggestLabel_ && !suggestLabel_->text().isEmpty()) ShowSuggestionLabel(true); if (controller_) controller_->UnselectCurrentServer(); focusDelayTimer_.stop(); } void RocketServerFilter::focusOutEvent(QFocusEvent *e) { QTextEdit::focusOutEvent(e); if (toPlainText().isEmpty()) setText(helpText_); focusDelayTimer_.start(10); } void RocketServerFilter::FocusSearchBox() { controller_->CleanInputFocus(); if (suggestionListProxy_) { QListWidget *list = suggestionListProxy_->WidgetAs<QListWidget>(); if (list) list->clearFocus(); suggestionListProxy_->clearFocus(); } setFocus(Qt::TabFocusReason); } void RocketServerFilter::FocusSuggestionBox() { controller_->CleanInputFocus(); clearFocus(); if (suggestionListProxy_) { QListWidget *list = suggestionListProxy_->WidgetAs<QListWidget>(); if (list) list->setFocus(Qt::TabFocusReason); suggestionListProxy_->setFocus(Qt::TabFocusReason); } } void RocketServerFilter::Unfocus() { if (suggestionListProxy_) { QListWidget *list = suggestionListProxy_->WidgetAs<QListWidget>(); if (list) { list->clearFocus(); list->releaseKeyboard(); } suggestionListProxy_->clearFocus(); } clearFocus(); releaseKeyboard(); // Hack to unfocus the text cursor caret! Nothing else seems to work // This will eventually lead into QTextControlPrivate::setBlinkingCursorEnabled(false) QFocusEvent fe(QEvent::FocusOut); QApplication::sendEvent(this, &fe); controller_->CleanInputFocus(); } void RocketServerFilter::keyPressEvent(QKeyEvent *e) { if (!suggestionListProxy_) return; // Enter = hide box and select first server if (e->key() == Qt::Key_Return || e->key() == Qt::Key_Enter) { // If the text apply timer is running, do this // delayed so the server have time to be sorted! e->setAccepted(true); HideAndClearSuggestions(); Unfocus(); QTimer::singleShot((orderDelayTimer_.isActive() ? 250 : 1), controller_, SLOT(SelectFirstServer())); return; } else if (e->key() == Qt::Key_Tab) { e->setAccepted(true); ApplySuggestion(true); return; } // Down = show suggestion else if (e->key() == Qt::Key_Down) { QListWidget *list = suggestionListProxy_->WidgetAs<QListWidget>(); if (!list) return; if (suggestionListProxy_->isVisible()) { FocusSuggestionBox(); list->setCurrentRow(0); } else if (list->count() > 0) { list->clearSelection(); ShowSuggestionList(); } e->setAccepted(true); return; } QTextEdit::keyPressEvent(e); if (e->key() == Qt::Key_End || (e->key() == Qt::Key_Right && textCursor().position() == toPlainText().length())) ApplySuggestion(true); else if (e->key() == Qt::Key_Escape) { if (suggestionListProxy_->isVisible()) { HideSuggestionList(); FocusSearchBox(); } else { clear(); if (!hasFocus() && toPlainText().isEmpty()) setText(helpText_); controller_->CleanInputFocus(); } e->setAccepted(true); } } bool RocketServerFilter::eventFilter(QObject *obj, QEvent *e) { if (suggestionListProxy_ && suggestionListProxy_->widget_ == obj) { if (suggestionListProxy_->isVisible()) { QListWidget *list = suggestionListProxy_->WidgetAs<QListWidget>(); if (!list) return false; if (e->type() == QEvent::FocusOut) { focusDelayTimer_.start(10); list->clearSelection(); } else if (e->type() == QEvent::KeyPress || e->type() == QEvent::ShortcutOverride) { QKeyEvent *ke = dynamic_cast<QKeyEvent*>(e); if (!ke) return false; bool isTab = ke->key() == Qt::Key_Tab; if (!isTab && e->type() == QEvent::ShortcutOverride) return false; if (ke->key() == Qt::Key_Up || ke->key() == Qt::Key_Down) { int index = list->currentRow(); int diff = (ke->key() == Qt::Key_Up ? -1 : 1); index += diff; if (index < 0) { // Focus the input field FocusSearchBox(); return true; } if (index >= list->count()) index = list->count()-1; list->setCurrentRow(index); return true; } else if (ke->key() == Qt::Key_Return || ke->key() == Qt::Key_Enter) { QListWidgetItem *item = list->item(list->currentRow()); if (item) { list->setCurrentItem(item); OnSuggestionListItemSelected(item); return true; } } else if (ke->key() == Qt::Key_Escape || isTab) { HideSuggestionList(); if (e->type() == QEvent::ShortcutOverride) ke->setAccepted(true); else FocusSearchBox(); return true; } } } } return false; } // RocketLicensesDialog RocketLicensesDialog::RocketLicensesDialog(RocketPlugin *plugin) { ui_.setupUi(this); if (plugin && !plugin->GetFramework()->IsHeadless()) setWindowIcon(plugin->GetFramework()->Ui()->MainWindow()->windowIcon()); LoadLicenses(); connect(ui_.buttonClose, SIGNAL(clicked()), SLOT(close()), Qt::QueuedConnection); connect(ui_.licensesList, SIGNAL(currentItemChanged(QListWidgetItem*, QListWidgetItem*)), SLOT(OnLicenseSelected(QListWidgetItem*, QListWidgetItem*))); ui_.licensesList->setCurrentRow(0); } void RocketLicensesDialog::LoadLicenses() { ui_.licensesList->clear(); licenses_.clear(); // Load license file paths QDir dir(QDir::toNativeSeparators(Application::InstallationDirectory()) + "licenses"); foreach (const QString &file, dir.entryList(QDir::NoDotAndDotDot|QDir::Files, QDir::Name)) { QFileInfo info(dir.absoluteFilePath(file)); if (info.suffix().toLower() != "txt") continue; License l; l.name = info.baseName(); l.absoluteFilePath = info.absoluteFilePath(); l.item = new QListWidgetItem(l.name); licenses_ << l; ui_.licensesList->addItem(l.item); } // Load URL metadata QFile file(dir.absoluteFilePath("Urls.dat")); if (!file.open(QFile::ReadOnly)) return; QTextStream urlsStream(&file); while(!urlsStream.atEnd()) { QStringList parts = urlsStream.readLine().split(" ", QString::SkipEmptyParts); if (parts.size() < 2) continue; QString name = parts.takeFirst(); for(int i=0; i<licenses_.size(); ++i) { License &l = licenses_[i]; if (l.name.compare(name, Qt::CaseInsensitive) == 0) { l.urls = parts; break; } } } file.close(); } void RocketLicensesDialog::OnLicenseSelected(QListWidgetItem *item, QListWidgetItem* /*previous*/) { ui_.licenseEditor->clear(); for(int i=0; i<licenses_.size(); ++i) { License &l = licenses_[i]; if (l.item && l.item == item) { // Load license QFile file(l.absoluteFilePath); if (file.open(QFile::ReadOnly)) { QTextStream s(&file); s.setAutoDetectUnicode(true); ui_.licenseEditor->setPlainText(s.readAll()); file.close(); } else ui_.licenseEditor->setPlainText("Failed to load license file for preview"); // Show related urls if (!l.urls.isEmpty()) { QStringList links; foreach(const QString &link, l.urls) { QString linkText = link.trimmed(); if (linkText.startsWith("http://")) linkText = link.mid(7); else if (linkText.startsWith("https://")) linkText = link.mid(8); if (linkText.endsWith("/")) linkText.chop(1); links << QString("<a href=\"%1\">%2</a>").arg(link).arg(linkText); } ui_.descLabel->setText(links.join(" ")); } else ui_.descLabel->setText(""); return; } } } // RocketEulaDialog RocketEulaDialog::RocketEulaDialog(RocketPlugin *plugin) { ui_.setupUi(this); setWindowTitle("Meshmoon Rocket End User License Agreement"); if (plugin && !plugin->GetFramework()->IsHeadless()) setWindowIcon(plugin->GetFramework()->Ui()->MainWindow()->windowIcon()); ui_.licensesList->hide(); ui_.frameTop->hide(); ui_.descLabel->setText("Meshmoon Rocket End User License Agreement"); QFile file(QDir::toNativeSeparators(Application::InstallationDirectory()) + "EULA-Meshmoon-Rocket.txt"); if (file.open(QFile::ReadOnly)) { QTextStream s(&file); s.setAutoDetectUnicode(true); ui_.licenseEditor->setPlainText(s.readAll()); file.close(); } else ui_.licenseEditor->setPlainText("Failed to load EULA file for preview"); connect(ui_.buttonClose, SIGNAL(clicked()), SLOT(close()), Qt::QueuedConnection); }
32.424025
181
0.629682
Adminotech
fbb3914ba9946d115068326a3cc9138f23ef2b72
14,871
cpp
C++
src/lib/OpenEXR/ImfMultiPartOutputFile.cpp
remia/openexr
566087f13259f4429d55125d1001b2696ac2bfc3
[ "BSD-3-Clause" ]
587
2015-01-04T09:56:19.000Z
2019-11-21T13:23:33.000Z
third_party/openexr-672c77d7c923402f549371e08b39ece4552cbb85/src/lib/OpenEXR/ImfMultiPartOutputFile.cpp
Vertexwahn/FlatlandRT
37d09fde38b25eff5f802200b43628efbd1e3198
[ "Apache-2.0" ]
360
2015-01-04T10:55:17.000Z
2019-11-21T16:37:22.000Z
third_party/openexr-672c77d7c923402f549371e08b39ece4552cbb85/src/lib/OpenEXR/ImfMultiPartOutputFile.cpp
Vertexwahn/FlatlandRT
37d09fde38b25eff5f802200b43628efbd1e3198
[ "Apache-2.0" ]
297
2015-01-11T12:06:42.000Z
2019-11-19T21:59:57.000Z
// // SPDX-License-Identifier: BSD-3-Clause // Copyright (c) Contributors to the OpenEXR Project. // #include "ImfMultiPartOutputFile.h" #include "ImfBoxAttribute.h" #include "ImfChromaticitiesAttribute.h" #include "ImfDeepScanLineOutputFile.h" #include "ImfDeepTiledOutputFile.h" #include "ImfFloatAttribute.h" #include "ImfMisc.h" #include "ImfOutputFile.h" #include "ImfOutputPartData.h" #include "ImfOutputStreamMutex.h" #include "ImfPartType.h" #include "ImfStdIO.h" #include "ImfThreading.h" #include "ImfTiledOutputFile.h" #include "ImfTimeCodeAttribute.h" #include "ImfNamespace.h" #include <Iex.h> #include <set> OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_ENTER using IMATH_NAMESPACE::Box2i; using std::map; using std::set; using std::vector; struct MultiPartOutputFile::Data : public OutputStreamMutex { vector<OutputPartData*> parts; // Contains data to initialize Output files. bool deleteStream; // If we should delete the stream when destruction. int numThreads; // The number of threads. std::map<int, GenericOutputFile*> _outputFiles; std::vector<Header> _headers; void headerNameUniquenessCheck (const std::vector<Header>& headers); void writeHeadersToFile (const std::vector<Header>& headers); void writeChunkTableOffsets (std::vector<OutputPartData*>& parts); //------------------------------------- // ensure that _headers is valid: called by constructors //------------------------------------- void do_header_sanity_checks (bool overrideSharedAttributes); // ------------------------------------------------ // Given a source header, we copy over all the 'shared attributes' to // the destination header and remove any conflicting ones. // ------------------------------------------------ void overrideSharedAttributesValues (const Header& src, Header& dst); // ------------------------------------------------ // Given a source header, we check the destination header for any // attributes that are part of the shared attribute set. For attributes // present in both we check the values. For attribute present in // destination but absent in source we return false. // For attributes present in src but missing from dst we return false // and add the attribute to dst. // We return false for all other cases. // If we return true then we also populate the conflictingAttributes // vector with the names of the attributes that failed the above. // ------------------------------------------------ bool checkSharedAttributesValues ( const Header& src, const Header& dst, std::vector<std::string>& conflictingAttributes) const; Data (bool deleteStream, int numThreads) : OutputStreamMutex () , deleteStream (deleteStream) , numThreads (numThreads) {} ~Data () { if (deleteStream) delete os; for (size_t i = 0; i < parts.size (); i++) delete parts[i]; } Data (const Data& other) = delete; Data& operator= (const Data& other) = delete; Data (Data&& other) = delete; Data& operator= (Data&& other) = delete; }; void MultiPartOutputFile::Data::do_header_sanity_checks ( bool overrideSharedAttributes) { size_t parts = _headers.size (); if (parts == 0) throw IEX_NAMESPACE::ArgExc ("Empty header list."); bool isMultiPart = (parts > 1); // // Do part 0 checks first. // _headers[0].sanityCheck (_headers[0].hasTileDescription (), isMultiPart); if (isMultiPart) { // multipart files must contain a chunkCount attribute _headers[0].setChunkCount (getChunkOffsetTableSize (_headers[0])); for (size_t i = 1; i < parts; i++) { if (_headers[i].hasType () == false) throw IEX_NAMESPACE::ArgExc ( "Every header in a multipart file should have a type"); _headers[i].setChunkCount (getChunkOffsetTableSize (_headers[i])); _headers[i].sanityCheck ( _headers[i].hasTileDescription (), isMultiPart); if (overrideSharedAttributes) overrideSharedAttributesValues (_headers[0], _headers[i]); else { std::vector<std::string> conflictingAttributes; bool valid = checkSharedAttributesValues ( _headers[0], _headers[i], conflictingAttributes); if (valid) { string excMsg ( "Conflicting attributes found for header :: "); excMsg += _headers[i].name (); for (size_t i = 0; i < conflictingAttributes.size (); i++) excMsg += " '" + conflictingAttributes[i] + "' "; THROW (IEX_NAMESPACE::ArgExc, excMsg); } } } headerNameUniquenessCheck (_headers); } else { // add chunk count offset to single part data (if not an image) if (_headers[0].hasType () && isImage (_headers[0].type ()) == false) { _headers[0].setChunkCount (getChunkOffsetTableSize (_headers[0])); } } } MultiPartOutputFile::MultiPartOutputFile ( const char fileName[], const Header* headers, int parts, bool overrideSharedAttributes, int numThreads) : _data (new Data (true, numThreads)) { // grab headers _data->_headers.resize (parts); for (int i = 0; i < parts; i++) { _data->_headers[i] = headers[i]; } try { _data->do_header_sanity_checks (overrideSharedAttributes); // // Build parts and write headers and offset tables to file. // _data->os = new StdOFStream (fileName); for (size_t i = 0; i < _data->_headers.size (); i++) _data->parts.push_back (new OutputPartData ( _data, _data->_headers[i], i, numThreads, parts > 1)); writeMagicNumberAndVersionField ( *_data->os, &_data->_headers[0], _data->_headers.size ()); _data->writeHeadersToFile (_data->_headers); _data->writeChunkTableOffsets (_data->parts); } catch (IEX_NAMESPACE::BaseExc& e) { delete _data; REPLACE_EXC ( e, "Cannot open image file " "\"" << fileName << "\". " << e.what ()); throw; } catch (...) { delete _data; throw; } } MultiPartOutputFile::MultiPartOutputFile ( OStream& os, const Header* headers, int parts, bool overrideSharedAttributes, int numThreads) : _data (new Data (false, numThreads)) { // grab headers _data->_headers.resize (parts); _data->os = &os; for (int i = 0; i < parts; i++) { _data->_headers[i] = headers[i]; } try { _data->do_header_sanity_checks (overrideSharedAttributes); // // Build parts and write headers and offset tables to file. // for (size_t i = 0; i < _data->_headers.size (); i++) _data->parts.push_back (new OutputPartData ( _data, _data->_headers[i], i, numThreads, parts > 1)); writeMagicNumberAndVersionField ( *_data->os, &_data->_headers[0], _data->_headers.size ()); _data->writeHeadersToFile (_data->_headers); _data->writeChunkTableOffsets (_data->parts); } catch (IEX_NAMESPACE::BaseExc& e) { delete _data; REPLACE_EXC ( e, "Cannot open image stream " "\"" << os.fileName () << "\". " << e.what ()); throw; } catch (...) { delete _data; throw; } } const Header& MultiPartOutputFile::header (int n) const { if (n < 0 || n >= int (_data->_headers.size ())) { THROW ( IEX_NAMESPACE::ArgExc, "MultiPartOutputFile::header called with invalid part number " << n << " on file with " << _data->_headers.size () << " parts"); } return _data->_headers[n]; } int MultiPartOutputFile::parts () const { return _data->_headers.size (); } MultiPartOutputFile::~MultiPartOutputFile () { for (map<int, GenericOutputFile*>::iterator it = _data->_outputFiles.begin (); it != _data->_outputFiles.end (); it++) { delete it->second; } delete _data; } template <class T> T* MultiPartOutputFile::getOutputPart (int partNumber) { if (partNumber < 0 || partNumber >= int (_data->_headers.size ())) { THROW ( IEX_NAMESPACE::ArgExc, "MultiPartOutputFile::getOutputPart called with invalid part number " << partNumber << " on file with " << _data->_headers.size () << " parts"); } #if ILMTHREAD_THREADING_ENABLED std::lock_guard<std::mutex> lock (*_data); #endif if (_data->_outputFiles.find (partNumber) == _data->_outputFiles.end ()) { T* file = new T (_data->parts[partNumber]); _data->_outputFiles.insert ( std::make_pair (partNumber, (GenericOutputFile*) file)); return file; } else return (T*) _data->_outputFiles[partNumber]; } // instance above function for all four types template OutputFile* MultiPartOutputFile::getOutputPart<OutputFile> (int); template TiledOutputFile* MultiPartOutputFile::getOutputPart<TiledOutputFile> (int); template DeepScanLineOutputFile* MultiPartOutputFile::getOutputPart<DeepScanLineOutputFile> (int); template DeepTiledOutputFile* MultiPartOutputFile::getOutputPart<DeepTiledOutputFile> (int); void MultiPartOutputFile::Data::overrideSharedAttributesValues ( const Header& src, Header& dst) { // // Display Window // const Box2iAttribute* displayWindow = src.findTypedAttribute<Box2iAttribute> ("displayWindow"); if (displayWindow) dst.insert ("displayWindow", *displayWindow); else dst.erase ("displayWindow"); // // Pixel Aspect Ratio // const FloatAttribute* pixelAspectRatio = src.findTypedAttribute<FloatAttribute> ("pixelAspectRatio"); if (pixelAspectRatio) dst.insert ("pixelAspectRatio", *pixelAspectRatio); else dst.erase ("pixelAspectRatio"); // // Timecode // const TimeCodeAttribute* timeCode = src.findTypedAttribute<TimeCodeAttribute> ("timecode"); if (timeCode) dst.insert ("timecode", *timeCode); else dst.erase ("timecode"); // // Chromaticities // const ChromaticitiesAttribute* chromaticities = src.findTypedAttribute<ChromaticitiesAttribute> ("chromaticities"); if (chromaticities) dst.insert ("chromaticities", *chromaticities); else dst.erase ("chromaticities"); } bool MultiPartOutputFile::Data::checkSharedAttributesValues ( const Header& src, const Header& dst, vector<string>& conflictingAttributes) const { bool conflict = false; // // Display Window // if (src.displayWindow () != dst.displayWindow ()) { conflict = true; conflictingAttributes.push_back ("displayWindow"); } // // Pixel Aspect Ratio // if (src.pixelAspectRatio () != dst.pixelAspectRatio ()) { conflict = true; conflictingAttributes.push_back ("pixelAspectRatio"); } // // Timecode // const TimeCodeAttribute* srcTimeCode = src.findTypedAttribute<TimeCodeAttribute> ( TimeCodeAttribute::staticTypeName ()); const TimeCodeAttribute* dstTimeCode = dst.findTypedAttribute<TimeCodeAttribute> ( TimeCodeAttribute::staticTypeName ()); if (dstTimeCode) { if ((srcTimeCode && (srcTimeCode->value () != dstTimeCode->value ())) || (!srcTimeCode)) { conflict = true; conflictingAttributes.push_back ( TimeCodeAttribute::staticTypeName ()); } } // // Chromaticities // const ChromaticitiesAttribute* srcChrom = src.findTypedAttribute<ChromaticitiesAttribute> ( ChromaticitiesAttribute::staticTypeName ()); const ChromaticitiesAttribute* dstChrom = dst.findTypedAttribute<ChromaticitiesAttribute> ( ChromaticitiesAttribute::staticTypeName ()); if (dstChrom) { if ((srcChrom && (srcChrom->value () != dstChrom->value ())) || (!srcChrom)) { conflict = true; conflictingAttributes.push_back ( ChromaticitiesAttribute::staticTypeName ()); } } return conflict; } void MultiPartOutputFile::Data::headerNameUniquenessCheck ( const vector<Header>& headers) { set<string> names; for (size_t i = 0; i < headers.size (); i++) { if (names.find (headers[i].name ()) != names.end ()) throw IEX_NAMESPACE::ArgExc ( "Each part should have a unique name."); names.insert (headers[i].name ()); } } void MultiPartOutputFile::Data::writeHeadersToFile (const vector<Header>& headers) { for (size_t i = 0; i < headers.size (); i++) { // (TODO) consider deep files' preview images here. if (headers[i].type () == TILEDIMAGE) parts[i]->previewPosition = headers[i].writeTo (*os, true); else parts[i]->previewPosition = headers[i].writeTo (*os, false); } // // If a multipart file, write zero-length attribute name to mark the end of all headers. // if (headers.size () != 1) OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::write< OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (*os, ""); } void MultiPartOutputFile::Data::writeChunkTableOffsets ( vector<OutputPartData*>& parts) { for (size_t i = 0; i < parts.size (); i++) { int chunkTableSize = getChunkOffsetTableSize (parts[i]->header); uint64_t pos = os->tellp (); if (pos == static_cast<uint64_t> (-1)) IEX_NAMESPACE::throwErrnoExc ( "Cannot determine current file position (%T)."); parts[i]->chunkOffsetTablePosition = os->tellp (); // // Fill in empty data for now. We'll write actual offsets during destruction. // for (int j = 0; j < chunkTableSize; j++) { uint64_t empty = 0; OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::write< OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (*os, empty); } } } OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_EXIT
28.653179
92
0.589671
remia
fbb5b2175e5aa94cf133c39edd86958527354dfc
3,223
cpp
C++
src/xray/render/base/sources/render_base_world.cpp
ixray-team/ixray-2.0
85c3a544175842323fc82f42efd96c66f0fc5abb
[ "Linux-OpenIB" ]
3
2021-10-30T09:36:14.000Z
2022-03-26T17:00:06.000Z
src/xray/render/base/sources/render_base_world.cpp
acidicMercury8/ixray-2.0
85c3a544175842323fc82f42efd96c66f0fc5abb
[ "Linux-OpenIB" ]
null
null
null
src/xray/render/base/sources/render_base_world.cpp
acidicMercury8/ixray-2.0
85c3a544175842323fc82f42efd96c66f0fc5abb
[ "Linux-OpenIB" ]
1
2022-03-26T17:00:08.000Z
2022-03-26T17:00:08.000Z
//////////////////////////////////////////////////////////////////////////// // Created : 28.10.2008 // Author : Dmitriy Iassenev // Copyright (C) GSC Game World - 2009 //////////////////////////////////////////////////////////////////////////// #include "pch.h" #include <xray/render/base/world.h> #include <xray/render/base/platform.h> #include <xray/render/base/sources/platform_api.h> #include "command_processor.h" #include "engine_renderer.h" #include "editor_renderer.h" #include "game_renderer.h" #include "ui_renderer.h" using xray::render::base_world; using xray::resources::managed_resource_ptr; base_world::base_world ( xray::render::engine::wrapper& wrapper, HWND window_handle ) : m_wrapper ( wrapper ) { m_platform = create_render_platform( wrapper, window_handle ); ASSERT( m_platform ); m_processor = NEW ( command_processor ) ( render::delete_on_tick_callback_type ( &wrapper, &render::engine::wrapper::delete_on_logic_tick) ); m_editor_commands_processor = NEW ( command_processor ) ( render::delete_on_tick_callback_type ( &wrapper, &render::engine::wrapper::delete_on_editor_tick) ); m_engine = NEW ( engine::engine_renderer ) ( *this, *m_platform ); m_game = NEW ( game::game_renderer ) ( *this, *m_platform ); m_editor = NEW ( editor::editor_renderer ) ( *this, *m_platform ); m_ui = NEW ( ui_renderer ) ( *this, *m_platform ); } base_world::~base_world ( ) { DELETE ( m_ui ); DELETE ( m_editor ); DELETE ( m_game ); DELETE ( m_engine ); DELETE ( m_editor_commands_processor ); DELETE ( m_processor ); DELETE ( m_platform ); } xray::render::engine::renderer& base_world::engine ( ) { ASSERT ( m_engine ); return ( *m_engine ); } xray::render::game::renderer& base_world::game ( ) { ASSERT ( m_game ); return ( *m_game ); } xray::render::ui::renderer& base_world::ui ( ) { ASSERT ( m_ui ); return ( *m_ui ); } xray::render::editor::renderer& base_world::editor ( ) { ASSERT ( m_editor ); return ( *m_editor ); } void base_world::push_command ( xray::render::engine::command* command ) { commands().push_command ( command ); } void base_world::destroy_command ( xray::render::engine::command* command ) { R_ASSERT ( command->remove_frame_id <= m_platform->frame_id() ); L_DELETE ( command ); } void base_world::push_command_editor ( xray::render::engine::command* command ) { commands_editor().push_command ( command ); } void base_world::destroy_command_editor ( xray::render::engine::command* command ) { R_ASSERT ( command->remove_frame_id <= m_platform->frame_id() ); E_DELETE ( command ); } void base_world::draw_frame_logic ( ) { m_wrapper.draw_frame_logic ( ); } void base_world::draw_frame_editor ( ) { m_wrapper.draw_frame_editor ( ); } xray::render::platform & base_world::platform ( ) { return *m_platform; } void base_world::clear_resources ( ) { m_platform->clear_resources( ); } void base_world::set_editor_render_mode ( bool draw_editor, bool draw_game ) { m_platform->set_editor_render_mode( draw_editor, draw_game ); }
27.547009
161
0.635433
ixray-team
fbbbf35b837bfb822b1cd481242a9f156c485530
598
cpp
C++
Homeworks/2_ImageWarping/project/src/App/Warp.cpp
Adven-00/USTC_CG_2020
7f44197c42305309f2a74418367ace149de04ed8
[ "MIT" ]
null
null
null
Homeworks/2_ImageWarping/project/src/App/Warp.cpp
Adven-00/USTC_CG_2020
7f44197c42305309f2a74418367ace149de04ed8
[ "MIT" ]
null
null
null
Homeworks/2_ImageWarping/project/src/App/Warp.cpp
Adven-00/USTC_CG_2020
7f44197c42305309f2a74418367ace149de04ed8
[ "MIT" ]
null
null
null
#include "Warp.h" void Warp::Render(QImage* ptr_image) { QImage image_tmp(*(ptr_image)); int width = ptr_image->width(); int height = ptr_image->height(); ptr_image->fill(Qt::lightGray); for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { QPoint p(i, j); QPoint po = Output(p); if (po.x() >= 0 && po.x() < width && po.y() >= 0 && po.y() < height) ptr_image->setPixel(Output(p), image_tmp.pixel(p)); //FixHole(ptr_image); } } } void Warp::SetControlPoints(QVector<QPoint> &bps, QVector<QPoint> &eps) { begin_points_ = bps; end_points_ = eps; }
18.6875
71
0.598662
Adven-00
fbbdc5be30f812e4188e6b33e9232e7ca3fd854b
4,026
hpp
C++
src/ltb/cuda/optix/optix.hpp
LoganBarnes/ltb-gvs
b1178e31c35aece434c7d47af955275fca9bb2a5
[ "MIT" ]
1
2020-04-04T16:57:25.000Z
2020-04-04T16:57:25.000Z
src/ltb/cuda/optix/optix.hpp
LoganBarnes/ltb-gvs
b1178e31c35aece434c7d47af955275fca9bb2a5
[ "MIT" ]
null
null
null
src/ltb/cuda/optix/optix.hpp
LoganBarnes/ltb-gvs
b1178e31c35aece434c7d47af955275fca9bb2a5
[ "MIT" ]
null
null
null
// /////////////////////////////////////////////////////////////////////////////////////// // LTB Geometry Visualization Server // Copyright (c) 2020 Logan Barnes - All Rights Reserved // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // /////////////////////////////////////////////////////////////////////////////////////// #pragma once // project #include "ltb/util/result.hpp" // external #include <driver_types.h> #include <optix_types.h> // standard #include <memory> namespace ltb::cuda { class OptiX { public: /// \brief /// \return static auto init() -> util::Result<std::shared_ptr<CUstream_st>>; /// \brief /// \param options /// \return static auto make_context(OptixDeviceContextOptions const& options) -> util::Result<std::shared_ptr<OptixDeviceContext_t>>; /// \brief /// \param context /// \param accel_build_options /// \return static auto make_geometry_acceleration_structure(std::shared_ptr<OptixDeviceContext_t> const& context, OptixAccelBuildOptions const& accel_build_options, OptixBuildInput const& build_input) -> util::Result<std::shared_ptr<OptixTraversableHandle>>; /// \brief /// \param context /// \param pipeline_compile_options /// \param module_compile_options /// \param ptx_str /// \return static auto make_module(std::shared_ptr<OptixDeviceContext_t> const& context, OptixPipelineCompileOptions const& pipeline_compile_options, OptixModuleCompileOptions const& module_compile_options, std::string const& ptx_str) -> util::Result<std::shared_ptr<OptixModule_t>>; /// \brief /// \param context /// \param module /// \param program_group_descriptions /// \return static auto make_program_groups(std::shared_ptr<OptixDeviceContext_t> const& context, std::shared_ptr<OptixModule_t> const& module, std::vector<OptixProgramGroupDesc> const& program_group_descriptions) -> ltb::util::Result<std::shared_ptr<std::vector<OptixProgramGroup>>>; /// \brief /// \param context /// \param program_groups /// \param pipeline_compile_options /// \param pipeline_link_options /// \return static auto make_pipeline(std::shared_ptr<OptixDeviceContext_t> const& context, std::shared_ptr<std::vector<OptixProgramGroup>> const& program_groups, OptixPipelineCompileOptions const& pipeline_compile_options, OptixPipelineLinkOptions const& pipeline_link_options) -> ltb::util::Result<std::shared_ptr<OptixPipeline_t>>; }; } // namespace ltb::cuda
43.290323
118
0.615748
LoganBarnes
fbc5e23262cc809ca33de49454463093564b0643
887
cpp
C++
leetcode/751. IP to CIDR/s1.cpp
zhuohuwu0603/leetcode_cpp_lzl124631x
6a579328810ef4651de00fde0505934d3028d9c7
[ "Fair" ]
787
2017-05-12T05:19:57.000Z
2022-03-30T12:19:52.000Z
leetcode/751. IP to CIDR/s1.cpp
aerlokesh494/LeetCode
0f2cbb28d5a9825b51a8d3b3a0ae0c30d7ff155f
[ "Fair" ]
8
2020-03-16T05:55:38.000Z
2022-03-09T17:19:17.000Z
leetcode/751. IP to CIDR/s1.cpp
aerlokesh494/LeetCode
0f2cbb28d5a9825b51a8d3b3a0ae0c30d7ff155f
[ "Fair" ]
247
2017-04-30T15:07:50.000Z
2022-03-30T09:58:57.000Z
// OJ: https://leetcode.com/problems/ip-to-cidr/ // Author: github.com/lzl124631x // Time: O() // Space: O() class Solution { private: unsigned ipToUnsigned(string &ip) { unsigned ans = 0, val = 0; for (int i = 0; i < ip.size(); ++i) { if (ip[i] == '.') { ans = (ans + val) << 8; val = 0; } else val = val * 10 + ip[i] - '0'; } return ans + val; } string unsignedToIp(unsigned val) { unsigned mask = ~0 ^ ((unsigned)~0 >> 8); string ans; for (int i = 0; i < 4; ++i) { ans += to_string((val & mask) >> ((3 - i) * 8)); mask >>= 8; if (i < 3) ans += "."; } return ans; } public: vector<string> ipToCIDR(string ip, int n) { unsigned s = ipToUnsigned(ip); return { unsignedToIp(s) }; } };
27.71875
60
0.441939
zhuohuwu0603
fbca1b8a435dd64592063b4f4f8f9625914a75d3
748
cc
C++
src/libcxx_support.cc
S-YOU/liumos
5f2335ca293596d645110fe0ab3b09a9246c8366
[ "MIT" ]
null
null
null
src/libcxx_support.cc
S-YOU/liumos
5f2335ca293596d645110fe0ab3b09a9246c8366
[ "MIT" ]
null
null
null
src/libcxx_support.cc
S-YOU/liumos
5f2335ca293596d645110fe0ab3b09a9246c8366
[ "MIT" ]
null
null
null
#include "generic.h" void* operator new(unsigned long, std::align_val_t) { Panic("void * operator new(unsigned long, std::align_val_t)"); } void operator delete(void*, std::align_val_t) { Panic("void operator delete(void*, std::align_val_t)"); } extern "C" void __cxa_throw() { Panic("libcxx_support"); } extern "C" void __cxa_begin_catch() { Panic("libcxx_support"); } extern "C" void __cxa_end_catch() { Panic("libcxx_support"); } extern "C" void __cxa_allocate_exception() { Panic("libcxx_support:__cxa_allocate_exception"); } extern "C" void __cxa_free_exception() { Panic("libcxx_support"); } void* __eh_frame_end; void* __eh_frame_start; void* __eh_frame_hdr_end; void* __eh_frame_hdr_start; void* __gxx_personality_v0;
20.777778
64
0.73262
S-YOU
fbcb29fa179ee6d75ccf58657d732a8f18e30748
4,592
cpp
C++
StructuredProgramming/lab_s02e02/lab_s02e02_main.cpp
Michal-Fularz/ProgrammingCourse
bee3fb5be39902b08a917bb66a891329cf09f70f
[ "MIT" ]
1
2020-05-16T14:10:08.000Z
2020-05-16T14:10:08.000Z
StructuredProgramming/lab_s02e02/lab_s02e02_main.cpp
Michal-Fularz/ProgrammingCourse
bee3fb5be39902b08a917bb66a891329cf09f70f
[ "MIT" ]
null
null
null
StructuredProgramming/lab_s02e02/lab_s02e02_main.cpp
Michal-Fularz/ProgrammingCourse
bee3fb5be39902b08a917bb66a891329cf09f70f
[ "MIT" ]
null
null
null
#include <fstream> #include <iostream> #include <string> #include <sstream> #include <vector> #include "lab_s02e02_MF.h" void ex_1() { std::cout << "Exercise 1" << std::endl; std::string word = "racecar"; do { std::cout << "Enter a word to check if it is a palindrome or type exit to break the loop" << std::endl; std::cin >> word; if (is_palindrome(word)) { std::cout << "It is a palindrome!" << std::endl; } else { std::cout << "Nope" << std::endl; } } while(word != "exit"); std::cout << std::endl << std::endl; } void ex_2() { std::cout << "Exercise 2" << std::endl; std::string input = "Ala ma kota"; std::vector<size_t> pos = find_all(input, 'a'); // wynik: {2, 5, 10} std::cout << "{"; for(const auto& p: pos) { std::cout << p << ", "; } std::cout << "}" << std::endl; } void sort_ex_6(std::vector<int> a) { // this is just an implementation of bubble sorting algorithm based on the diagram int rozmiar = a.size(); bool flaga_zamiana = false; do { int i=0; flaga_zamiana = false; while(i<rozmiar-1) { if(a[i] > a[i+1]) { std::swap(a[i], a[i+1]); flaga_zamiana = true; } i++; } rozmiar--; } while(flaga_zamiana); } void ex_7() { std::cout << "Exercise 7" << std::endl; std::vector<double> values {1, 2, 6, 8, 9, 11, 15}; int index = binary_search(values, 5); std::cout << "Index of element with a value 5: " << index << std::endl; } #include <algorithm> void ex_8() { std::cout << "Exercise 8" << std::endl; // relative location - works on each machine if the files are located in the same way relative to each other std::fstream file("./../data/kursy_usd_eur.csv"); //plik znajduje się w tym samym katalogu co pliki źródłowe projektu, inaczej trzeba podać pełną ścieżkę np. "c:/Users/nazwa_uzytkownika/Downloads/kursy_usd_eur.csv" // absolute location - unless all the folders on the path are named the same this will not work on different computers. This way should be avoided std::fstream file2("F:/Projects/university_courses/ProgrammingCourse/StructuredProgramming/data/kursy_usd_eur.csv"); std::vector<Exchange_rate> rates; if (file.is_open()) { std::string line; std::getline(file, line); // wczytuje pierwszą linię z nagłówkiem i ją ignoruje while (std::getline(file, line)) {//wczytuje kolejne linie aż do końca pliku std::stringstream str(line);//tworzy strumień, którego źródłem jest wczytana linia Exchange_rate er; std::getline(str, er.date, ','); //wczytuje date (pierwszy element wiersza) std::string double_str; std::getline(str, double_str, ','); // wczytuje kurs USD (jako tekst) er.usd = std::stod(double_str); //zamiana na string->double std::getline(str, double_str, ','); // wczytuje kurs EUR (jako tekst) er.eur = std::stod(double_str); //zamiana na string->double std::getline(str, er.table_id, ','); // wczytuje ostatnią kolumnę z numerem tabeli NBP rates.emplace_back(er); //dodaje element do kolekcji } } std::cout << "Data from the file:" << std::endl; for(const auto& r: rates) { std::cout << "date: " << r.date << ", usd: " << r.usd; std::cout << "eur: " << r.eur << ", table_id: " << r.table_id << std::endl; } std::cout << std::endl << std::endl; sort_usd(rates); std::cout << "Data sorted:" << std::endl; for(const auto& r: rates) { std::cout << "date: " << r.date << ", usd: " << r.usd; std::cout << "eur: " << r.eur << ", table_id: " << r.table_id << std::endl; } std::cout << std::endl << std::endl; std::cout << "Ten entries with the largest amount of USD:" << std::endl; for(size_t i=0; i<10 && i<rates.size(); i++) { rates[i].print(); } std::cout << std::endl << std::endl; int index = binary_search(rates, 3.9011); std::cout << "USD rate of " << 3.9011 << " index: " << index << std::endl; rates[index].print(); std::cout << std::endl << std::endl; } int main() { std::cout << "Hello lab 2!" << std::endl; ex_1(); ex_2(); ex_7(); ex_8(); // getline allows reading input with spaces std::string text; getline(std::cin, text); std::cout << text; return 0; }
28.880503
218
0.558798
Michal-Fularz
fbcdf5842c719c66ba56015813978b2c7befec29
1,747
cpp
C++
Cpp/164_maximum_gap/solution.cpp
zszyellow/leetcode
2ef6be04c3008068f8116bf28d70586e613a48c2
[ "MIT" ]
1
2015-12-19T23:05:35.000Z
2015-12-19T23:05:35.000Z
Cpp/164_maximum_gap/solution.cpp
zszyellow/leetcode
2ef6be04c3008068f8116bf28d70586e613a48c2
[ "MIT" ]
null
null
null
Cpp/164_maximum_gap/solution.cpp
zszyellow/leetcode
2ef6be04c3008068f8116bf28d70586e613a48c2
[ "MIT" ]
null
null
null
class Solution { public: // bucket sort int maximumGap(vector<int>& nums) { // min and max element int minE; int maxE; // bucket sort variables int bucket_size; int bucket_num; int bucket_id; int last_max; // other variables needed int i = 0; int res = 0; int max_gap = INT_MIN; int len = nums.size(); if (len > 1) { minE = maxE = nums[0]; for (i = 1; i < sSize; i ++) { if (minE > nums[i]) minE = nums[i]; else if (maxE < nums[i]) maxE = nums[i]; } bucket_size = max(1, (maxE-minE)/(sSize-1)); bucket_num = (maxE-minE)/bucket_size + 1; if (bucket_num <= 1) return maxE - minE; // bucket vector<int> bucket_max(bucket_num, INT_MIN); vector<int> bucket_min(bucket_num, INT_MAX); vector<int> bucket_count(bucket_num, 0); for (i = 0; i < sSize; i ++) { bucket_id = (nums[i]-minE) / bucket_size; bucket_count[bucket_id] ++; bucket_min[bucket_id] = std::min(bucket_min[bucket_id], nums[i]); bucket_max[bucket_id] = std::max(bucket_max[bucket_id], nums[i]); } last_max = minE; for (i = 0; i < bucket_num; i ++) { if (bucket_count[i] > 0) { max_gap = max(max_gap, bucket_min[i]-last_max); last_max = bucket_max[i]; } } return max_gap; } return 0; } };
30.649123
81
0.439611
zszyellow
fbd12afad82e861d4a5b6533e6967db93471353e
213
hpp
C++
oauth/include/oauth/oauth.hpp
zina1995/Twitter-API-C-Library
87b29c63b89be6feb05adbe05ebed0213aa67f9b
[ "MIT" ]
null
null
null
oauth/include/oauth/oauth.hpp
zina1995/Twitter-API-C-Library
87b29c63b89be6feb05adbe05ebed0213aa67f9b
[ "MIT" ]
null
null
null
oauth/include/oauth/oauth.hpp
zina1995/Twitter-API-C-Library
87b29c63b89be6feb05adbe05ebed0213aa67f9b
[ "MIT" ]
null
null
null
#ifndef OAUTH_OAUTH_HPP #define OAUTH_OAUTH_HPP #include <oauth/authorize.hpp> #include <oauth/bearer_token.hpp> #include <oauth/credentials.hpp> #include <oauth/read_credentials.hpp> #endif // OAUTH_OAUTH_HPP
21.3
37
0.798122
zina1995
fbd14e9e9cf0e459d9eb82d6a737d41614a3cc4b
2,532
cc
C++
gcc-gcc-7_3_0-release/libstdc++-v3/testsuite/20_util/is_null_pointer/value.cc
best08618/asylo
5a520a9f5c461ede0f32acc284017b737a43898c
[ "Apache-2.0" ]
7
2020-05-02T17:34:05.000Z
2021-10-17T10:15:18.000Z
gcc-gcc-7_3_0-release/libstdc++-v3/testsuite/20_util/is_null_pointer/value.cc
best08618/asylo
5a520a9f5c461ede0f32acc284017b737a43898c
[ "Apache-2.0" ]
null
null
null
gcc-gcc-7_3_0-release/libstdc++-v3/testsuite/20_util/is_null_pointer/value.cc
best08618/asylo
5a520a9f5c461ede0f32acc284017b737a43898c
[ "Apache-2.0" ]
2
2020-07-27T00:22:36.000Z
2021-04-01T09:41:02.000Z
// { dg-do compile { target c++11 } } // 2013-05-02 Paolo Carlini <pcarlini@suse.de> // // Copyright (C) 2013-2017 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library 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, or (at your option) // any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. #include <type_traits> #include <testsuite_tr1.h> void test01() { using std::is_null_pointer; using namespace __gnu_test; static_assert(test_category<is_null_pointer, std::nullptr_t>(true), ""); static_assert(test_category<is_null_pointer, int>(false), ""); static_assert(test_category<is_null_pointer, float>(false), ""); static_assert(test_category<is_null_pointer, EnumType>(false), ""); static_assert(test_category<is_null_pointer, int*>(false), ""); static_assert(test_category<is_null_pointer, int(*)(int)>(false), ""); static_assert(test_category<is_null_pointer, int (ClassType::*)>(false), ""); static_assert(test_category<is_null_pointer, int (ClassType::*) (int)>(false), ""); static_assert(test_category<is_null_pointer, int[2]>(false), ""); static_assert(test_category<is_null_pointer, float[][3]>(false), ""); static_assert(test_category<is_null_pointer, EnumType[2][3][4]>(false), ""); static_assert(test_category<is_null_pointer, int*[3]>(false), ""); static_assert(test_category<is_null_pointer, int(*[][2])(int)>(false), ""); static_assert(test_category<is_null_pointer, int (ClassType::*[2][3])>(false), ""); static_assert(test_category<is_null_pointer, int (ClassType::*[][2][3]) (int)>(false), ""); static_assert(test_category<is_null_pointer, ClassType>(false), ""); static_assert(test_category<is_null_pointer, PODType>(false), ""); static_assert(test_category<is_null_pointer, void>(false), ""); static_assert(test_category<is_null_pointer, NType>(false), ""); static_assert(test_category<is_null_pointer, TType>(false), ""); static_assert(test_category<is_null_pointer, SLType>(false), ""); }
45.214286
79
0.729068
best08618
fbd3c61d5797b7141d70a043ec66039fc62e4b5b
2,877
cpp
C++
base/std/thread.cpp
fengzi01/yamq
f11a0e28b0100b4155c124bb96488046353ec059
[ "MIT" ]
null
null
null
base/std/thread.cpp
fengzi01/yamq
f11a0e28b0100b4155c124bb96488046353ec059
[ "MIT" ]
null
null
null
base/std/thread.cpp
fengzi01/yamq
f11a0e28b0100b4155c124bb96488046353ec059
[ "MIT" ]
null
null
null
#include "base/std/thread.h" #include <utility> // std::forword #include <memory> #include <stdlib.h> #include <sys/syscall.h> #include <stdio.h> namespace std2 { /* thread data 封装 */ struct Thread::ThreadData { ThreadFunc _func; pid_t *_tid; ThreadData (const ThreadFunc& func,pid_t *tid) :_func(func),_tid(tid) {} void runInThread() { *_tid = this_thread::GetTid(); // 初始化tid try { _func(); } catch (const std::exception& ex) { fprintf(stderr, "exception caught in Thread %d\n", this_thread::GetTid()); fprintf(stderr, "reason: %s\n", ex.what()); abort(); } catch (...) { fprintf(stderr, "unknown exception caught in Thread %d\n", this_thread::GetTid()); throw; // rethrow } } }; /* 使得C++编译器不添加 xxstd1xxnative_thread_routine修饰符 */ /* 所以这里不加也没有问题 */ extern "C" { static void* native_thread_routine(void* p) { std::unique_ptr<Thread::ThreadData> data(static_cast<Thread::ThreadData*>(p)); data->runInThread(); return nullptr; } } Thread::Thread(const ThreadFunc &func):_func(func),_joined(false),_tid(0) { startThread(); } Thread::Thread(ThreadFunc &&func):_func(func),_joined(false),_tid(0) { startThread(); } Thread::~Thread() { if (!_joined) { Detach(); } } void Thread::startThread() { std::unique_ptr<ThreadData> data(new ThreadData(_func,&_tid)); if (pthread_create(&_ptid,NULL,&native_thread_routine,data.get())) { perror("pthread_create call fail!"); } // 销毁前释放原始指针控制权 data.release(); } void Thread::Join() { if (!_joined) { pthread_join(_ptid,NULL); _joined = true; } } void Thread::Detach() { if (_joined) { fprintf(stderr,"detach already joined thread!\n"); return; } pthread_detach(_ptid); } namespace this_thread { __thread int tid = 0; __thread char tid_str[32]; __thread int tid_strlen = 0; //__thread const char* tname; static void cacheTid() { if (tid == 0) { tid = static_cast<pid_t>(::syscall(SYS_gettid)); tid_strlen = snprintf(tid_str, sizeof tid_str, "%5d ", tid); } } int GetTid() { if (__builtin_expect(tid == 0, 0)) { cacheTid(); } return tid; } const char *GetTid_str() { return tid_str; } int GetTid_strlen() { return tid_strlen; } } namespace { void afterFork() { std2::this_thread::tid = 0; std2::this_thread::GetTid(); } class ThreadLocalInitializer { public: ThreadLocalInitializer() { std2::this_thread::tid = 0; std2::this_thread::GetTid(); ::pthread_atfork(NULL, NULL, &afterFork); } }; ThreadLocalInitializer none;//全局变量,初始化就为主线程生成线程信息 } }
22.833333
94
0.582204
fengzi01
fbd5c8c2a5c54eff5b94ee5091fceb5f2eea1b31
762
cpp
C++
sample.cpp
as-xjc/LruCache
060e6f391d42b20926fda7dda354ef66f8037f83
[ "MIT" ]
null
null
null
sample.cpp
as-xjc/LruCache
060e6f391d42b20926fda7dda354ef66f8037f83
[ "MIT" ]
null
null
null
sample.cpp
as-xjc/LruCache
060e6f391d42b20926fda7dda354ef66f8037f83
[ "MIT" ]
null
null
null
#include <cstdio> #include <cstdlib> #include "lru.hpp" int main() { Lru<int, int> lru(5); for (int i = 1; i <= 10; ++i) { lru.Push(i, i); } auto print = [](int& value) { printf("%d,", value); }; printf("origin: cap %lu, size %lu: ", lru.GetCapacity(), lru.GetSize()); lru.ForEach(print); for (int i = 0; i < 20; ++i) { int key = std::rand() % 10 + 1; int result = 0; bool get = false; std::tie(result, get) = lru.Find(key); if (get) { printf("\nFind: %d, result %d, : ", key, result); } else { printf("\nFind: %d, result not found. ", key); } lru.ForEach(print); } lru.Clear(); printf("\norigin: cap %lu, size %lu", lru.GetCapacity(), lru.GetSize()); lru.ForEach(print); return 0; }
23.090909
74
0.532808
as-xjc
fbd69488570ed328b41585c3eb31d537a7401658
383
hpp
C++
pythran/pythonic/include/__builtin__/pythran/len_set.hpp
artas360/pythran
66dad52d52be71693043e9a7d7578cfb9cb3d1da
[ "BSD-3-Clause" ]
null
null
null
pythran/pythonic/include/__builtin__/pythran/len_set.hpp
artas360/pythran
66dad52d52be71693043e9a7d7578cfb9cb3d1da
[ "BSD-3-Clause" ]
null
null
null
pythran/pythonic/include/__builtin__/pythran/len_set.hpp
artas360/pythran
66dad52d52be71693043e9a7d7578cfb9cb3d1da
[ "BSD-3-Clause" ]
null
null
null
#ifndef PYTHONIC_INCLUDE_BUILTIN_PYTHRAN_LEN_SET_HPP #define PYTHONIC_INCLUDE_BUILTIN_PYTHRAN_LEN_SET_HPP #include "pythonic/include/utils/proxy.hpp" namespace pythonic { namespace __builtin__ { namespace pythran { template <class Iterable> long len_set(Iterable const &s); PROXY_DECL(pythonic::__builtin__::pythran, len_set); } } } #endif
15.958333
58
0.736292
artas360
fbdbf5bad0fec1cdb839700736e273fc05730cd8
10,979
cpp
C++
AquaEngine/Components/ModelManager.cpp
tiagovcosta/aquaengine
aea6de9f47ba0243b90c144dee4422efb2389cc7
[ "MIT" ]
55
2015-05-29T20:19:28.000Z
2022-01-18T21:23:15.000Z
AquaEngine/Components/ModelManager.cpp
tiagovcosta/aquaengine
aea6de9f47ba0243b90c144dee4422efb2389cc7
[ "MIT" ]
null
null
null
AquaEngine/Components/ModelManager.cpp
tiagovcosta/aquaengine
aea6de9f47ba0243b90c144dee4422efb2389cc7
[ "MIT" ]
6
2015-09-02T09:51:38.000Z
2020-08-16T07:54:34.000Z
#include "ModelManager.h" #include "..\Components\TransformManager.h" #include "..\Renderer\Camera.h" #include "..\Renderer\RendererUtilities.h" #include "..\Renderer\Renderer.h" #include "..\Core\Allocators\ScopeStack.h" #include "..\Core\Allocators\SmallBlockAllocator.h" //#include "..\Utilities\Allocators\LinearAllocator.h" //#include "..\Utilities\Allocators\Allocator.h" #include "..\Utilities\Blob.h" #include "..\Utilities\StringID.h" using namespace aqua; const ModelManager::Instance ModelManager::INVALID_INSTANCE = { ModelManager::INVALID_INDEX }; ModelManager::ModelManager(Allocator& allocator, LinearAllocator& temp_allocator, Renderer& renderer, TransformManager& transform, u32 inital_capacity) : _allocator(allocator), _temp_allocator(&temp_allocator), _renderer(&renderer), _transform_manager(&transform), _map(allocator), _params_manager(allocator) { _params_groups_allocator = allocator::allocateNew<SmallBlockAllocator>(_allocator, _allocator, 4 * 1024, 16); _data.size = 0; _data.capacity = 0; if(inital_capacity > 0) setCapacity(inital_capacity); auto shader_manager = _renderer->getShaderManager(); // Get shaders _render_shader = shader_manager->getRenderShader(getStringID("data/shaders/model.cshader")); } ModelManager::~ModelManager() { RenderDevice* render_device = _renderer->getRenderDevice(); for(u32 i = 0; i < _data.size; i++) { render_device->deleteParameterGroup(*_params_groups_allocator, *_data.instance_params[i]); } if(_data.capacity > 0) _allocator.deallocate(_data.buffer); allocator::deallocateDelete(_allocator, _params_groups_allocator); } void ModelManager::update() { RenderDevice& render_device = *_renderer->getRenderDevice(); auto params_desc_set = _render_shader->getInstanceParameterGroupDescSet(); const u32 num_modified_transforms = _transform_manager->getNumModifiedTransforms(); auto modified_transforms = _transform_manager->getModifiedTransforms(); for(u32 k = 0; k < num_modified_transforms; k++) { auto i = lookup(modified_transforms[k].entity).i; if(i == INVALID_INDEX) continue; ASSERT(i < _data.size); auto params_desc = getParameterGroupDesc(*params_desc_set, _data.permutation[i]); //Update world matrix u32 offset = params_desc->getConstantOffset(getStringID("world")); ASSERT(offset != UINT32_MAX); Matrix4x4* world = (Matrix4x4*)pointer_math::add(_data.instance_params[i]->getCBuffersData(), offset); //*world = _transform_manager->getWorld(_transform_manager->lookup(_data.entity[i])); *world = *modified_transforms[k].transform; //update bounding sphere Vector3 scale; Quaternion rotation; Vector3 translation; world->Decompose(scale, rotation, translation); float max_scale = max(scale.x, scale.y); max_scale = max(max_scale, scale.z); _data.bounding_sphere[i].center = Vector3::Transform(_data.bounding_sphere2[i].center, *world); _data.bounding_sphere[i].radius = _data.bounding_sphere2[i].radius * max_scale; } // TODO: Move this to extract and only cache visible instances param groups for(u32 i = 0; i < _data.size; i++) { //Cache instance parameter group _data.cached_instance_params[i] = render_device.cacheTemporaryParameterGroup(*_data.instance_params[i]); } } bool ModelManager::cull(u32 num_frustums, const Frustum* frustums, VisibilityData** out) { //VisibilityData* output = allocator::allocateArray<VisibilityData>(*_temp_allocator, num_frustums); //TODO: Implement in SIMD /* //Transform frustums data to SIMD friendly layout __m128* frustums_data; for(u32 j = 0; j < num_frustums; j++) { } */ for(u32 i = 0; i < num_frustums; i++) { u32 num_visibles = 0; out[i]->visibles_indices = allocator::allocateArray<u32>(*_temp_allocator, _data.size); for(u32 j = 0; j < _data.size; j++) { bool in = true; for(u8 k = 0; k < 6; k++) { float d = frustums[i][k].DotCoordinate(_data.bounding_sphere[j].center); if(d < -_data.bounding_sphere[j].radius) { in = false; break; } } if(in) { out[i]->visibles_indices[num_visibles] = j; num_visibles++; } } out[i]->num_visibles = num_visibles; } return true; } bool ModelManager::extract(const VisibilityData& visibility_data) { return true; } bool ModelManager::prepare() { return true; } bool ModelManager::getRenderItems(u8 num_passes, const u32* passes_names, const VisibilityData& visibility_data, RenderQueue* out_queues) { if(_data.size == 0) return true; u8 num_shader_passes = _render_shader->getNumPasses(); const u32* shader_passes_names = _render_shader->getPassesNames(); struct Match { u8 pass; u8 shader_pass; }; u8 num_matches = 0; Match* matches = allocator::allocateArrayNoConstruct<Match>(*_temp_allocator, num_passes); for(u8 i = 0; i < num_shader_passes; i++) { for(u8 j = 0; j < num_passes; j++) { if(shader_passes_names[i] == passes_names[j]) { matches[num_matches].pass = j; matches[num_matches].shader_pass = i; num_matches++; break; } } } if(num_matches == 0) return true; //no passes match //out_queues[0].size = 0; RenderItem** render_queues = allocator::allocateArrayNoConstruct<RenderItem*>(*_temp_allocator, num_matches); for(u8 i = 0; i < num_matches; i++) { u8 queue_index = matches[i].pass; render_queues[i] = allocator::allocateArrayNoConstruct<RenderItem>(*_temp_allocator, visibility_data.num_visibles); out_queues[queue_index].sort_items = allocator::allocateArrayNoConstruct<SortItem>(*_temp_allocator, visibility_data.num_visibles); } for(u32 i = 0; i < visibility_data.num_visibles; i++) { u32 actor_index = visibility_data.visibles_indices[i]; //actor_index = i; RenderItem render_item; render_item.draw_call = _data.subset[actor_index].draw_call; render_item.mesh = _data.mesh[actor_index]; render_item.material_params = _data.subset[actor_index].material_params; render_item.instance_params = _data.cached_instance_params[actor_index]; render_item.num_instances = 1; ShaderPermutation permutation = _data.subset[actor_index].shader; for(u8 i = 0; i < num_matches; i++) { Match& match = matches[i]; if(permutation[match.shader_pass] != nullptr) { render_item.shader = permutation[match.shader_pass]; RenderQueue& queue = out_queues[match.pass]; //RenderItem& ri = render_queues[match.pass][queue.size]; RenderItem& ri = render_queues[i][queue.size]; ri = render_item; SortItem& sort_item = queue.sort_items[queue.size]; sort_item.item = &ri; sort_item.sort_key = 0; queue.size++; } } } return true; } ModelManager::Instance ModelManager::create(Entity e, const MeshData* mesh, Permutation render_permutation) { if(_data.size > 0) { if(lookup(e).valid()) return INVALID_INSTANCE; //Max one model per entity } ASSERT(_data.size <= _data.capacity); if(_data.size == _data.capacity) setCapacity(_data.capacity * 2 + 8); u32 index = _data.size++; _map.insert(e, index); _data.entity[index] = e; _data.mesh[index] = mesh->mesh; _data.bounding_sphere[index] = mesh->bounding_sphere; _data.permutation[index] = mesh->permutation.value | render_permutation.value; _data.subset[index].shader = nullptr; _data.subset[index].material_params = nullptr; _data.subset[index].draw_call = &mesh->draw_calls[0]; _data.bounding_sphere2[index] = mesh->bounding_sphere; //Instance params auto params_desc_set = _render_shader->getInstanceParameterGroupDescSet(); auto params_desc = getParameterGroupDesc(*params_desc_set, render_permutation); //_data.instance_params[index] = createParameterGroup(*params_desc, UINT32_MAX, *_params_groups_allocator); //_data.instance_params[index] = createParameterGroup(*_params_groups_allocator, *params_desc, UINT32_MAX, 0, nullptr); _data.instance_params[index] = _renderer->getRenderDevice()->createParameterGroup(*_params_groups_allocator, RenderDevice::ParameterGroupType::INSTANCE, *params_desc, UINT32_MAX, 0, nullptr); //_data.params[index]->cbuffers[0] = _cbuffer; return{ index }; } ModelManager::Instance ModelManager::lookup(Entity e) { u32 i = _map.lookup(e, UINT32_MAX); return{ i }; } void ModelManager::destroy(Instance i) { u32 last = _data.size - 1; Entity e = _data.entity[i.i]; Entity last_e = _data.entity[last]; #define COPY_SINLE_INSTANCE_DATA(data) _data.data[i.i] = _data.data[last]; COPY_SINLE_INSTANCE_DATA(entity); COPY_SINLE_INSTANCE_DATA(mesh); COPY_SINLE_INSTANCE_DATA(bounding_sphere); COPY_SINLE_INSTANCE_DATA(permutation); COPY_SINLE_INSTANCE_DATA(instance_params); COPY_SINLE_INSTANCE_DATA(cached_instance_params); COPY_SINLE_INSTANCE_DATA(subset); COPY_SINLE_INSTANCE_DATA(bounding_sphere2); _map.insert(last_e, i.i); _map.remove(e); _data.size--; } void ModelManager::setMesh(Instance i, const MeshData* mesh) { _data.mesh[i.i] = mesh->mesh; } void ModelManager::addSubset(Instance i, u8 index, const Material* material) { //clear material bits //_data.subset[i.i].permutation.value &= ~_render_shader->getMaterialParameterGroupDescSet()->options_mask.value; //_data.subset[i.i].permutation.value |= material->permutation.value; _data.subset[i.i].permutation.value = _data.permutation[i.i].value | material->permutation.value; _data.subset[i.i].shader = _render_shader->getPermutation(_data.subset[i.i].permutation); _data.subset[i.i].material_params = material->params; } void ModelManager::setCapacity(u32 new_capacity) { InstanceData new_data; new_data.size = _data.size; new_data.capacity = new_capacity; new_data.buffer = allocateBlob(_allocator, new_capacity, new_data.entity, new_data.mesh, new_data.bounding_sphere, new_data.permutation, new_data.instance_params, new_data.cached_instance_params, new_data.subset, new_data.bounding_sphere2); //CHECK IF ALL ARRAYS ARE PROPERLY ALIGNED ASSERT(pointer_math::isAligned(new_data.entity)); ASSERT(pointer_math::isAligned(new_data.mesh)); ASSERT(pointer_math::isAligned(new_data.bounding_sphere)); ASSERT(pointer_math::isAligned(new_data.permutation)); ASSERT(pointer_math::isAligned(new_data.instance_params)); ASSERT(pointer_math::isAligned(new_data.cached_instance_params)); ASSERT(pointer_math::isAligned(new_data.subset)); ASSERT(pointer_math::isAligned(new_data.bounding_sphere2)); #define COPY_DATA(data) memcpy(new_data.data, _data.data, _data.size * sizeof(decltype(*new_data.data))); if(_data.size > 0) { COPY_DATA(entity); COPY_DATA(mesh); COPY_DATA(bounding_sphere); COPY_DATA(permutation); COPY_DATA(instance_params); COPY_DATA(cached_instance_params); COPY_DATA(subset); COPY_DATA(bounding_sphere2); } if(_data.capacity > 0) _allocator.deallocate(_data.buffer); _data = new_data; }
28.968338
135
0.729301
tiagovcosta
fbde4b42b850a97fcc3330f4fc27c795acf2aa93
2,881
hpp
C++
third_party/boost/simd/arch/x86/avx/simd/function/rec.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
6
2018-02-25T22:23:33.000Z
2021-01-15T15:13:12.000Z
third_party/boost/simd/arch/x86/avx/simd/function/rec.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
null
null
null
third_party/boost/simd/arch/x86/avx/simd/function/rec.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
7
2017-12-12T12:36:31.000Z
2020-02-10T14:27:07.000Z
//================================================================================================== /** Copyright 2016 NumScale SAS Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) **/ //================================================================================================== #ifndef BOOST_SIMD_ARCH_X86_AVX_SIMD_FUNCTION_REC_HPP_INCLUDED #define BOOST_SIMD_ARCH_X86_AVX_SIMD_FUNCTION_REC_HPP_INCLUDED #include <boost/simd/detail/overload.hpp> #include <boost/simd/function/raw.hpp> #include <boost/simd/constant/one.hpp> #include <boost/simd/constant/inf.hpp> #include <boost/simd/constant/mzero.hpp> #include <boost/simd/function/refine_rec.hpp> #include <boost/simd/function/bitwise_or.hpp> #include <boost/simd/function/bitwise_and.hpp> #include <boost/simd/function/bitofsign.hpp> #include <boost/simd/function/if_else.hpp> #include <boost/simd/function/is_inf.hpp> #include <boost/simd/arch/x86/avx/simd/function/rec_raw.hpp> namespace boost { namespace simd { namespace ext { namespace bd = boost::dispatch; namespace bs = boost::simd; BOOST_DISPATCH_OVERLOAD ( rec_ , (typename A0) , bs::avx_ , bs::pack_<bd::double_<A0>, bs::avx_> ) { BOOST_FORCEINLINE A0 operator()(A0 const& a00) const BOOST_NOEXCEPT { A0 a0 = refine_rec(a00, refine_rec(a00,refine_rec(a00, raw_(rec)(a00)))); #ifndef BOOST_SIMD_NO_INFINITIES a0 = if_else(is_inf(a00), bitwise_and(a00, Mzero<A0>()), a0 ); #endif #ifndef BOOST_SIMD_NO_DENORMALS auto is_den = is_less(bs::abs(a00), Smallestposval<A0>()); return if_else(is_den, bitwise_or(bitofsign(a00), Inf<A0>()), a0); #else auto is_den = is_eqz(a00); return if_else(is_den, bitwise_or(a00, Inf<A0>()), a0); #endif } }; BOOST_DISPATCH_OVERLOAD ( rec_ , (typename A0) , bs::avx_ , bs::pack_<bd::single_<A0>, bs::avx_> ) { BOOST_FORCEINLINE A0 operator()(A0 const& a00) const BOOST_NOEXCEPT { A0 a0 = refine_rec(a00,refine_rec(a00, raw_(rec)(a00))); #ifndef BOOST_SIMD_NO_INFINITIES a0 = if_else(is_inf(a00), bitwise_and(a00, Mzero<A0>()), a0 ); #endif #ifndef BOOST_SIMD_NO_DENORMALS auto is_den = is_less(bs::abs(a00), Smallestposval<A0>()); return if_else(is_den, bitwise_or(bitofsign(a00), Inf<A0>()), a0); #else auto is_den = is_eqz(a00); return if_else(is_den, bitwise_or(a00, Inf<A0>()), a0); #endif } }; } } } #endif
34.297619
100
0.562652
SylvainCorlay
fbe2d03f32ff439f7b4b88004f4ea2f1aaa1335b
2,085
cpp
C++
test/unit/test_level.cpp
dyle71/hcs-logger
aa3061d160b8bf84e2e4de05c5b29f09a8428bde
[ "MIT" ]
null
null
null
test/unit/test_level.cpp
dyle71/hcs-logger
aa3061d160b8bf84e2e4de05c5b29f09a8428bde
[ "MIT" ]
null
null
null
test/unit/test_level.cpp
dyle71/hcs-logger
aa3061d160b8bf84e2e4de05c5b29f09a8428bde
[ "MIT" ]
null
null
null
/* * This file is part of the headcode.space logger. * * The 'LICENSE.txt' file in the project root holds the software license. * Copyright (C) 2021 headcode.space e.U. * Oliver Maurhart <info@headcode.space>, https://www.headcode.space */ #include <headcode/logger/logger.hpp> #include <gtest/gtest.h> TEST(Level, regular) { EXPECT_FALSE(headcode::logger::GetLevelText(headcode::logger::Level::kUndefined).empty()); EXPECT_FALSE(headcode::logger::GetLevelText(headcode::logger::Level::kSilent).empty()); EXPECT_FALSE(headcode::logger::GetLevelText(headcode::logger::Level::kCritical).empty()); EXPECT_FALSE(headcode::logger::GetLevelText(headcode::logger::Level::kWarning).empty()); EXPECT_FALSE(headcode::logger::GetLevelText(headcode::logger::Level::kInfo).empty()); EXPECT_FALSE(headcode::logger::GetLevelText(headcode::logger::Level::kDebug).empty()); } TEST(Level, range_cap) { auto undefined_text = headcode::logger::GetLevelText(headcode::logger::Level::kUndefined); auto debug_text = headcode::logger::GetLevelText(headcode::logger::Level::kDebug); EXPECT_STREQ(headcode::logger::GetLevelText(static_cast<headcode::logger::Level>(-2)).c_str(), undefined_text.c_str()); EXPECT_STREQ(headcode::logger::GetLevelText(static_cast<headcode::logger::Level>(-10)).c_str(), undefined_text.c_str()); EXPECT_STREQ(headcode::logger::GetLevelText(static_cast<headcode::logger::Level>(-1000)).c_str(), undefined_text.c_str()); EXPECT_STREQ(headcode::logger::GetLevelText(static_cast<headcode::logger::Level>(-1'000'000)).c_str(), undefined_text.c_str()); EXPECT_STREQ(headcode::logger::GetLevelText(static_cast<headcode::logger::Level>(10)).c_str(), debug_text.c_str()); EXPECT_STREQ(headcode::logger::GetLevelText(static_cast<headcode::logger::Level>(1000)).c_str(), debug_text.c_str()); EXPECT_STREQ(headcode::logger::GetLevelText(static_cast<headcode::logger::Level>(1'000'000)).c_str(), debug_text.c_str()); }
48.488372
119
0.705516
dyle71
fbe2d2d712649b5a33f1ddc532c7febaa724b36a
332
cc
C++
below2.1/bus.cc
danzel-py/Kattis-Problem-Archive
bce1929d654b1bceb104f96d68c74349273dd1ff
[ "Apache-2.0" ]
null
null
null
below2.1/bus.cc
danzel-py/Kattis-Problem-Archive
bce1929d654b1bceb104f96d68c74349273dd1ff
[ "Apache-2.0" ]
null
null
null
below2.1/bus.cc
danzel-py/Kattis-Problem-Archive
bce1929d654b1bceb104f96d68c74349273dd1ff
[ "Apache-2.0" ]
null
null
null
#include <iostream> using namespace std; int main(){ int t; double x; cin>>t; for (int i = 0; i < t; i++) { cin>>x; double sum=0; for (int j = 0; j < x; j++) { sum+= 0.5; sum*= 2; } cout<<int(sum)<<'\n'; } return 0; }
15.090909
35
0.35241
danzel-py
fbe46e636088ccb38a82290baaadbb4a4b727f6e
1,809
hpp
C++
src/common/utilities/image/rasterbithandles.hpp
squeevee/Addle
20ec4335669fbd88d36742f586899d8416920959
[ "MIT" ]
3
2020-03-05T06:36:51.000Z
2020-06-20T03:25:02.000Z
src/common/utilities/image/rasterbithandles.hpp
squeevee/Addle
20ec4335669fbd88d36742f586899d8416920959
[ "MIT" ]
13
2020-03-11T17:43:42.000Z
2020-12-11T03:36:05.000Z
src/common/utilities/image/rasterbithandles.hpp
squeevee/Addle
20ec4335669fbd88d36742f586899d8416920959
[ "MIT" ]
1
2020-09-28T06:53:46.000Z
2020-09-28T06:53:46.000Z
/** * Addle source code * @file * @copyright Copyright 2020 Eleanor Hawk * @copyright Modification and distribution permitted under the terms of the * MIT License. See "LICENSE" for full details. */ #ifndef RASTERBITHANDLES_HPP #define RASTERBITHANDLES_HPP #include "compat.hpp" #include <QRect> #include <QImage> namespace Addle { class IRasterSurface; class ADDLE_COMMON_EXPORT RasterBitReader { public: RasterBitReader(RasterBitReader&& other); ~RasterBitReader(); inline QImage::Format format() { return _buffer.format(); } inline QPoint offset() const { return _area.topLeft() - _bufferOffset; } inline int pixelWidth() const { return _pixelWidth; } inline QRect area() const { return _area; } const uchar* scanLine(int line) const; private: RasterBitReader(const IRasterSurface& surface, const QImage& buffer, QPoint bufferOffset, QRect area); const IRasterSurface& _surface; const QImage& _buffer; const QPoint _bufferOffset; const QRect _area; const int _pixelWidth; bool _final = true; friend class IRasterSurface; }; class ADDLE_COMMON_EXPORT RasterBitWriter { public: RasterBitWriter(RasterBitWriter&& other); ~RasterBitWriter(); inline QImage::Format format() { return _buffer.format(); } inline QRect area() const { return _area; } inline int pixelWidth() const { return _pixelWidth; } uchar* scanLine(int line) const; private: RasterBitWriter(IRasterSurface& surface, QImage& buffer, QPoint bufferOffset, QRect area); IRasterSurface& _surface; QImage& _buffer; QPoint _bufferOffset; QRect _area; const int _pixelWidth; bool _final = true; friend class IRasterSurface; }; } // namespace Addle #endif // RASTERBITHANDLES_HPP
22.333333
94
0.708126
squeevee
fbf9442d4e5e1a52d04e6cba433bd136c7e563f3
1,328
cpp
C++
main.cpp
SmartphoneBrainScanner/smartphonebrainscanner2-Brain3D
57431b490f4bf780c23e22426233bde3f26e7726
[ "MIT" ]
3
2016-03-07T12:44:15.000Z
2016-06-05T23:41:43.000Z
main.cpp
SmartphoneBrainScanner/smartphonebrainscanner2-Brain3D
57431b490f4bf780c23e22426233bde3f26e7726
[ "MIT" ]
3
2015-07-24T10:12:02.000Z
2015-07-24T11:57:06.000Z
main.cpp
SmartphoneBrainScanner/smartphonebrainscanner2-Brain3D
57431b490f4bf780c23e22426233bde3f26e7726
[ "MIT" ]
6
2015-07-17T07:52:52.000Z
2018-07-22T20:16:04.000Z
#include <QApplication> #include <mycallback.h> #include <mainwindow.h> #include <hardware/emocap/sbs2emocapdatareader.h> #include <hardware/filereader/sbs2filedatareader.h> #include <hardware/emotiv/sbs2emotivdatareader.h> Q_DECL_EXPORT int main(int argc, char *argv[]) { QApplication app(argc, argv); qDebug() << "rootAppPath: "<<Sbs2Common::setDefaultRootAppPath(); QCommandLineParser parser; QCommandLineOption dataFilePath("datafile","File to read instead of device", "filepath"); parser.addOption(dataFilePath); parser.addHelpOption(); parser.process(app); MainWindow mw; mw.setAttribute(Qt::WA_QuitOnClose); MyCallback* myCallback = new MyCallback(mw.glwidget); #ifndef Q_OS_ANDROID Sbs2DataReader* sbs2DataReader = nullptr; if (!parser.isSet(dataFilePath)) { sbs2DataReader = Sbs2EmotivDataReader::New(myCallback); } else { sbs2DataReader = new Sbs2FileDataReader(myCallback,parser.value(dataFilePath)); } #else Sbs2DataReader* sbs2DataReader = new Sbs2FileDataReader(myCallback,"assets:/sbs2data_2018_12_01_21_07_22_Test.raw"); #endif QObject::connect(&app,SIGNAL(aboutToQuit()),mw.glwidget,SLOT(quit())); QObject::connect(&app,SIGNAL(aboutToQuit()),sbs2DataReader,SLOT(aboutToQuit())); return app.exec(); }
28.255319
120
0.72741
SmartphoneBrainScanner
22005d65aad9399764fa2788689486e8352122d9
41
cpp
C++
RECURSION/tempCodeRunnerFile.cpp
lakshya7878/DSA_practice_self_paced
54e70a1cef20578e30d02d7fd8cd405b7d26baad
[ "MIT" ]
1
2021-10-02T10:47:56.000Z
2021-10-02T10:47:56.000Z
RECURSION/tempCodeRunnerFile.cpp
lakshya7878/DSA_practice_self_paced
54e70a1cef20578e30d02d7fd8cd405b7d26baad
[ "MIT" ]
1
2021-10-07T03:39:34.000Z
2021-10-07T03:39:34.000Z
RECURSION/tempCodeRunnerFile.cpp
lakshya7878/DSA_practice_self_paced
54e70a1cef20578e30d02d7fd8cd405b7d26baad
[ "MIT" ]
null
null
null
if(sum==0){ // return 1; // }
13.666667
20
0.317073
lakshya7878
220f841003ca4be1a48f8390a49cb0dcc6052a5d
55,471
cpp
C++
export/release/macos/obj/src/DialogueBox.cpp
Tyrcnex/tai-mod
b83152693bb3139ee2ae73002623934f07d35baf
[ "Apache-2.0" ]
1
2021-07-19T05:10:43.000Z
2021-07-19T05:10:43.000Z
export/release/macos/obj/src/DialogueBox.cpp
Tyrcnex/tai-mod
b83152693bb3139ee2ae73002623934f07d35baf
[ "Apache-2.0" ]
null
null
null
export/release/macos/obj/src/DialogueBox.cpp
Tyrcnex/tai-mod
b83152693bb3139ee2ae73002623934f07d35baf
[ "Apache-2.0" ]
null
null
null
// Generated by Haxe 4.1.5 #include <hxcpp.h> #ifndef INCLUDED_Alphabet #include <Alphabet.h> #endif #ifndef INCLUDED_DialogueBox #include <DialogueBox.h> #endif #ifndef INCLUDED_MusicBeatState #include <MusicBeatState.h> #endif #ifndef INCLUDED_Paths #include <Paths.h> #endif #ifndef INCLUDED_PlayState #include <PlayState.h> #endif #ifndef INCLUDED_Std #include <Std.h> #endif #ifndef INCLUDED_StringTools #include <StringTools.h> #endif #ifndef INCLUDED_flixel_FlxBasic #include <flixel/FlxBasic.h> #endif #ifndef INCLUDED_flixel_FlxG #include <flixel/FlxG.h> #endif #ifndef INCLUDED_flixel_FlxObject #include <flixel/FlxObject.h> #endif #ifndef INCLUDED_flixel_FlxSprite #include <flixel/FlxSprite.h> #endif #ifndef INCLUDED_flixel_FlxState #include <flixel/FlxState.h> #endif #ifndef INCLUDED_flixel_addons_text_FlxTypeText #include <flixel/addons/text/FlxTypeText.h> #endif #ifndef INCLUDED_flixel_addons_transition_FlxTransitionableState #include <flixel/addons/transition/FlxTransitionableState.h> #endif #ifndef INCLUDED_flixel_addons_ui_FlxUIState #include <flixel/addons/ui/FlxUIState.h> #endif #ifndef INCLUDED_flixel_addons_ui_interfaces_IEventGetter #include <flixel/addons/ui/interfaces/IEventGetter.h> #endif #ifndef INCLUDED_flixel_addons_ui_interfaces_IFlxUIState #include <flixel/addons/ui/interfaces/IFlxUIState.h> #endif #ifndef INCLUDED_flixel_animation_FlxAnimation #include <flixel/animation/FlxAnimation.h> #endif #ifndef INCLUDED_flixel_animation_FlxAnimationController #include <flixel/animation/FlxAnimationController.h> #endif #ifndef INCLUDED_flixel_animation_FlxBaseAnimation #include <flixel/animation/FlxBaseAnimation.h> #endif #ifndef INCLUDED_flixel_graphics_frames_FlxAtlasFrames #include <flixel/graphics/frames/FlxAtlasFrames.h> #endif #ifndef INCLUDED_flixel_graphics_frames_FlxFramesCollection #include <flixel/graphics/frames/FlxFramesCollection.h> #endif #ifndef INCLUDED_flixel_group_FlxTypedGroup #include <flixel/group/FlxTypedGroup.h> #endif #ifndef INCLUDED_flixel_group_FlxTypedSpriteGroup #include <flixel/group/FlxTypedSpriteGroup.h> #endif #ifndef INCLUDED_flixel_input_FlxBaseKeyList #include <flixel/input/FlxBaseKeyList.h> #endif #ifndef INCLUDED_flixel_input_FlxKeyManager #include <flixel/input/FlxKeyManager.h> #endif #ifndef INCLUDED_flixel_input_IFlxInputManager #include <flixel/input/IFlxInputManager.h> #endif #ifndef INCLUDED_flixel_input_keyboard_FlxKeyList #include <flixel/input/keyboard/FlxKeyList.h> #endif #ifndef INCLUDED_flixel_input_keyboard_FlxKeyboard #include <flixel/input/keyboard/FlxKeyboard.h> #endif #ifndef INCLUDED_flixel_math_FlxPoint #include <flixel/math/FlxPoint.h> #endif #ifndef INCLUDED_flixel_system_FlxSound #include <flixel/system/FlxSound.h> #endif #ifndef INCLUDED_flixel_system_FlxSoundGroup #include <flixel/system/FlxSoundGroup.h> #endif #ifndef INCLUDED_flixel_system_frontEnds_SoundFrontEnd #include <flixel/system/frontEnds/SoundFrontEnd.h> #endif #ifndef INCLUDED_flixel_text_FlxText #include <flixel/text/FlxText.h> #endif #ifndef INCLUDED_flixel_tweens_FlxTween #include <flixel/tweens/FlxTween.h> #endif #ifndef INCLUDED_flixel_tweens_misc_NumTween #include <flixel/tweens/misc/NumTween.h> #endif #ifndef INCLUDED_flixel_util_FlxAxes #include <flixel/util/FlxAxes.h> #endif #ifndef INCLUDED_flixel_util_FlxTimer #include <flixel/util/FlxTimer.h> #endif #ifndef INCLUDED_flixel_util_FlxTimerManager #include <flixel/util/FlxTimerManager.h> #endif #ifndef INCLUDED_flixel_util_IFlxDestroyable #include <flixel/util/IFlxDestroyable.h> #endif #ifndef INCLUDED_flixel_util_IFlxPooled #include <flixel/util/IFlxPooled.h> #endif #ifndef INCLUDED_openfl_events_EventDispatcher #include <openfl/events/EventDispatcher.h> #endif #ifndef INCLUDED_openfl_events_IEventDispatcher #include <openfl/events/IEventDispatcher.h> #endif #ifndef INCLUDED_openfl_media_SoundChannel #include <openfl/media/SoundChannel.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_abff9fa8c13cc7a0_69_new,"DialogueBox","new",0x1f391625,"DialogueBox.new","DialogueBox.hx",69,0x0149b4eb) HX_DEFINE_STACK_FRAME(_hx_pos_abff9fa8c13cc7a0_15_new,"DialogueBox","new",0x1f391625,"DialogueBox.new","DialogueBox.hx",15,0x0149b4eb) static const int _hx_array_data_ffc81fb3_4[] = { (int)4, }; static const int _hx_array_data_ffc81fb3_5[] = { (int)4, }; static const int _hx_array_data_ffc81fb3_6[] = { (int)11, }; HX_LOCAL_STACK_FRAME(_hx_pos_abff9fa8c13cc7a0_239_update,"DialogueBox","update",0x23306964,"DialogueBox.update","DialogueBox.hx",239,0x0149b4eb) HX_LOCAL_STACK_FRAME(_hx_pos_abff9fa8c13cc7a0_283_update,"DialogueBox","update",0x23306964,"DialogueBox.update","DialogueBox.hx",283,0x0149b4eb) HX_LOCAL_STACK_FRAME(_hx_pos_abff9fa8c13cc7a0_293_update,"DialogueBox","update",0x23306964,"DialogueBox.update","DialogueBox.hx",293,0x0149b4eb) HX_LOCAL_STACK_FRAME(_hx_pos_abff9fa8c13cc7a0_310_hidePortraits,"DialogueBox","hidePortraits",0xb1911f9b,"DialogueBox.hidePortraits","DialogueBox.hx",310,0x0149b4eb) HX_LOCAL_STACK_FRAME(_hx_pos_abff9fa8c13cc7a0_323_startDialogue,"DialogueBox","startDialogue",0x59859d9f,"DialogueBox.startDialogue","DialogueBox.hx",323,0x0149b4eb) HX_LOCAL_STACK_FRAME(_hx_pos_abff9fa8c13cc7a0_384_cleanDialog,"DialogueBox","cleanDialog",0x0fc249f6,"DialogueBox.cleanDialog","DialogueBox.hx",384,0x0149b4eb) void DialogueBox_obj::__construct(::hx::Null< bool > __o_talkingRight,::Array< ::String > dialogueList){ HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_0, ::DialogueBox,_gthis) HXARGC(1) void _hx_run( ::flixel::util::FlxTimer tmr){ HX_GC_STACKFRAME(&_hx_pos_abff9fa8c13cc7a0_69_new) HXLINE( 70) { HXLINE( 70) ::flixel::FlxSprite _g = _gthis->bgFade; HXDLIN( 70) _g->set_alpha((_g->alpha + ((Float)0.139999999999999986))); } HXLINE( 71) if ((_gthis->bgFade->alpha > ((Float)0.7))) { HXLINE( 72) _gthis->bgFade->set_alpha(((Float)0.7)); } } HX_END_LOCAL_FUNC1((void)) bool talkingRight = __o_talkingRight.Default(true); HX_GC_STACKFRAME(&_hx_pos_abff9fa8c13cc7a0_15_new) HXLINE( 320) this->isEnding = false; HXLINE( 236) this->dialogueStarted = false; HXLINE( 235) this->dialogueOpened = false; HXLINE( 44) this->daPortraits = ::Array_obj< ::Dynamic>::__new(0); HXLINE( 22) this->dialogueList = ::Array_obj< ::String >::__new(0); HXLINE( 19) this->curCharacter = HX_("",00,00,00,00); HXLINE( 49) ::DialogueBox _gthis = ::hx::ObjectPtr<OBJ_>(this); HXLINE( 51) super::__construct(null(),null(),null()); HXLINE( 53) ::String _hx_switch_0 = ( (::String)(::PlayState_obj::SONG->__Field(HX_("song",d5,23,58,4c),::hx::paccDynamic)) ).toLowerCase(); if ( (_hx_switch_0==HX_("senpai",3c,df,8d,6b)) ){ HXLINE( 56) ::flixel::_hx_system::frontEnds::SoundFrontEnd _hx_tmp = ::flixel::FlxG_obj::sound; HXDLIN( 56) ::String library = null(); HXDLIN( 56) _hx_tmp->playMusic(::Paths_obj::getPath((((HX_("music/",ea,bf,1b,3f) + HX_("Lunchbox",c1,34,3f,3d)) + HX_(".",2e,00,00,00)) + HX_("ogg",4f,94,54,00)),HX_("MUSIC",85,08,49,8e),library),0,null(),null()); HXLINE( 57) { HXLINE( 57) ::flixel::_hx_system::FlxSound _this = ::flixel::FlxG_obj::sound->music; HXDLIN( 57) ::Dynamic onComplete = null(); HXDLIN( 57) if (::hx::IsNull( _this->_channel )) { HXLINE( 57) _this->play(null(),null(),null()); } HXDLIN( 57) if (::hx::IsNotNull( _this->fadeTween )) { HXLINE( 57) _this->fadeTween->cancel(); } HXDLIN( 57) _this->fadeTween = ::flixel::tweens::FlxTween_obj::num(( (Float)(0) ),((Float)0.8),1, ::Dynamic(::hx::Anon_obj::Create(1) ->setFixed(0,HX_("onComplete",f8,d4,7e,5d),onComplete)),_this->volumeTween_dyn()); } HXLINE( 55) goto _hx_goto_0; } if ( (_hx_switch_0==HX_("thorns",9c,bf,c7,8c)) ){ HXLINE( 59) ::flixel::_hx_system::frontEnds::SoundFrontEnd _hx_tmp = ::flixel::FlxG_obj::sound; HXDLIN( 59) ::String library = null(); HXDLIN( 59) _hx_tmp->playMusic(::Paths_obj::getPath((((HX_("music/",ea,bf,1b,3f) + HX_("LunchboxScary",57,33,01,24)) + HX_(".",2e,00,00,00)) + HX_("ogg",4f,94,54,00)),HX_("MUSIC",85,08,49,8e),library),0,null(),null()); HXLINE( 60) { HXLINE( 60) ::flixel::_hx_system::FlxSound _this = ::flixel::FlxG_obj::sound->music; HXDLIN( 60) ::Dynamic onComplete = null(); HXDLIN( 60) if (::hx::IsNull( _this->_channel )) { HXLINE( 60) _this->play(null(),null(),null()); } HXDLIN( 60) if (::hx::IsNotNull( _this->fadeTween )) { HXLINE( 60) _this->fadeTween->cancel(); } HXDLIN( 60) _this->fadeTween = ::flixel::tweens::FlxTween_obj::num(( (Float)(0) ),((Float)0.8),1, ::Dynamic(::hx::Anon_obj::Create(1) ->setFixed(0,HX_("onComplete",f8,d4,7e,5d),onComplete)),_this->volumeTween_dyn()); } HXLINE( 58) goto _hx_goto_0; } _hx_goto_0:; HXLINE( 63) ::flixel::FlxSprite _hx_tmp = ::flixel::FlxSprite_obj::__alloc( HX_CTX ,-200,-200,null()); HXDLIN( 63) int _hx_tmp1 = ::Std_obj::_hx_int((( (Float)(::flixel::FlxG_obj::width) ) * ((Float)1.3))); HXDLIN( 63) this->bgFade = _hx_tmp->makeGraphic(_hx_tmp1,::Std_obj::_hx_int((( (Float)(::flixel::FlxG_obj::height) ) * ((Float)1.3))),-4988968,null(),null()); HXLINE( 64) this->bgFade->scrollFactor->set(null(),null()); HXLINE( 65) this->bgFade->set_alpha(( (Float)(0) )); HXLINE( 66) this->add(this->bgFade); HXLINE( 68) ::flixel::util::FlxTimer_obj::__alloc( HX_CTX ,null())->start(((Float)0.83), ::Dynamic(new _hx_Closure_0(_gthis)),5); HXLINE( 75) this->box = ::flixel::FlxSprite_obj::__alloc( HX_CTX ,-20,45,null()); HXLINE( 77) bool hasDialog = false; HXLINE( 78) ::String _hx_switch_1 = ( (::String)(::PlayState_obj::SONG->__Field(HX_("song",d5,23,58,4c),::hx::paccDynamic)) ).toLowerCase(); if ( (_hx_switch_1==HX_("brave",00,2e,e9,b8)) || (_hx_switch_1==HX_("loss",e3,a9,b7,47)) || (_hx_switch_1==HX_("shift",82,ec,22,7c)) ){ HXLINE( 104) hasDialog = true; HXLINE( 105) ::flixel::FlxSprite _hx_tmp = this->box; HXDLIN( 105) ::String library = null(); HXDLIN( 105) ::String _hx_tmp1 = ::Paths_obj::getPath(((HX_("images/",77,50,74,c1) + HX_("speech_bubble_talking",00,7d,a2,c5)) + HX_(".png",3b,2d,bd,1e)),HX_("IMAGE",3b,57,57,3b),library); HXDLIN( 105) _hx_tmp->set_frames(::flixel::graphics::frames::FlxAtlasFrames_obj::fromSparrow(_hx_tmp1,::Paths_obj::getPath(((HX_("images/",77,50,74,c1) + HX_("speech_bubble_talking",00,7d,a2,c5)) + HX_(".xml",69,3e,c3,1e)),HX_("TEXT",ad,94,ba,37),library))); HXLINE( 106) this->box->animation->addByPrefix(HX_("normalOpen",91,41,38,70),HX_("Speech Bubble Normal Open",0d,59,3f,7c),24,false,null(),null()); HXLINE( 107) this->box->animation->addByPrefix(HX_("normal",27,72,69,30),HX_("speech bubble normal",bd,d5,bc,a7),24,true,null(),null()); HXLINE( 108) this->box->set_width(( (Float)(230) )); HXLINE( 109) this->box->set_height(( (Float)(230) )); HXLINE( 110) this->box->set_x(( (Float)(-100) )); HXLINE( 111) this->box->set_y(( (Float)(375) )); HXLINE( 103) goto _hx_goto_1; } if ( (_hx_switch_1==HX_("roses",04,6c,64,ed)) ){ HXLINE( 86) hasDialog = true; HXLINE( 87) ::flixel::_hx_system::frontEnds::SoundFrontEnd _hx_tmp = ::flixel::FlxG_obj::sound; HXDLIN( 87) _hx_tmp->play(::Paths_obj::sound(HX_("ANGRY_TEXT_BOX",57,5c,5c,19),null()),null(),null(),null(),null(),null()); HXLINE( 89) ::flixel::FlxSprite _hx_tmp1 = this->box; HXDLIN( 89) ::String library = null(); HXDLIN( 89) ::String _hx_tmp2 = ::Paths_obj::getPath(((HX_("images/",77,50,74,c1) + HX_("weeb/pixelUI/dialogueBox-senpaiMad",61,55,ee,84)) + HX_(".png",3b,2d,bd,1e)),HX_("IMAGE",3b,57,57,3b),library); HXDLIN( 89) _hx_tmp1->set_frames(::flixel::graphics::frames::FlxAtlasFrames_obj::fromSparrow(_hx_tmp2,::Paths_obj::getPath(((HX_("images/",77,50,74,c1) + HX_("weeb/pixelUI/dialogueBox-senpaiMad",61,55,ee,84)) + HX_(".xml",69,3e,c3,1e)),HX_("TEXT",ad,94,ba,37),library))); HXLINE( 90) this->box->animation->addByPrefix(HX_("normalOpen",91,41,38,70),HX_("SENPAI ANGRY IMPACT SPEECH",f9,17,39,87),24,false,null(),null()); HXLINE( 91) this->box->animation->addByIndices(HX_("normal",27,72,69,30),HX_("SENPAI ANGRY IMPACT SPEECH",f9,17,39,87),::Array_obj< int >::fromData( _hx_array_data_ffc81fb3_4,1),HX_("",00,00,00,00),24,null(),null(),null()); HXLINE( 85) goto _hx_goto_1; } if ( (_hx_switch_1==HX_("senpai",3c,df,8d,6b)) ){ HXLINE( 81) hasDialog = true; HXLINE( 82) ::flixel::FlxSprite _hx_tmp = this->box; HXDLIN( 82) ::String library = null(); HXDLIN( 82) ::String _hx_tmp1 = ::Paths_obj::getPath(((HX_("images/",77,50,74,c1) + HX_("weeb/pixelUI/dialogueBox-pixel",b3,f0,21,da)) + HX_(".png",3b,2d,bd,1e)),HX_("IMAGE",3b,57,57,3b),library); HXDLIN( 82) _hx_tmp->set_frames(::flixel::graphics::frames::FlxAtlasFrames_obj::fromSparrow(_hx_tmp1,::Paths_obj::getPath(((HX_("images/",77,50,74,c1) + HX_("weeb/pixelUI/dialogueBox-pixel",b3,f0,21,da)) + HX_(".xml",69,3e,c3,1e)),HX_("TEXT",ad,94,ba,37),library))); HXLINE( 83) this->box->animation->addByPrefix(HX_("normalOpen",91,41,38,70),HX_("Text Box Appear",bd,48,54,1a),24,false,null(),null()); HXLINE( 84) this->box->animation->addByIndices(HX_("normal",27,72,69,30),HX_("Text Box Appear",bd,48,54,1a),::Array_obj< int >::fromData( _hx_array_data_ffc81fb3_5,1),HX_("",00,00,00,00),24,null(),null(),null()); HXLINE( 80) goto _hx_goto_1; } if ( (_hx_switch_1==HX_("thorns",9c,bf,c7,8c)) ){ HXLINE( 94) hasDialog = true; HXLINE( 95) ::flixel::FlxSprite _hx_tmp = this->box; HXDLIN( 95) ::String library = null(); HXDLIN( 95) ::String _hx_tmp1 = ::Paths_obj::getPath(((HX_("images/",77,50,74,c1) + HX_("weeb/pixelUI/dialogueBox-evil",07,6d,f9,cc)) + HX_(".png",3b,2d,bd,1e)),HX_("IMAGE",3b,57,57,3b),library); HXDLIN( 95) _hx_tmp->set_frames(::flixel::graphics::frames::FlxAtlasFrames_obj::fromSparrow(_hx_tmp1,::Paths_obj::getPath(((HX_("images/",77,50,74,c1) + HX_("weeb/pixelUI/dialogueBox-evil",07,6d,f9,cc)) + HX_(".xml",69,3e,c3,1e)),HX_("TEXT",ad,94,ba,37),library))); HXLINE( 96) this->box->animation->addByPrefix(HX_("normalOpen",91,41,38,70),HX_("Spirit Textbox spawn",ea,ee,35,84),24,false,null(),null()); HXLINE( 97) this->box->animation->addByIndices(HX_("normal",27,72,69,30),HX_("Spirit Textbox spawn",ea,ee,35,84),::Array_obj< int >::fromData( _hx_array_data_ffc81fb3_6,1),HX_("",00,00,00,00),24,null(),null(),null()); HXLINE( 99) ::flixel::FlxSprite face = ::flixel::FlxSprite_obj::__alloc( HX_CTX ,320,170,null()); HXDLIN( 99) ::String library1 = null(); HXDLIN( 99) ::flixel::FlxSprite face1 = face->loadGraphic(::Paths_obj::getPath(((HX_("images/",77,50,74,c1) + HX_("weeb/spiritFaceForward",93,1c,29,2a)) + HX_(".png",3b,2d,bd,1e)),HX_("IMAGE",3b,57,57,3b),library1),null(),null(),null(),null(),null()); HXLINE( 100) face1->setGraphicSize(::Std_obj::_hx_int((face1->get_width() * ( (Float)(6) ))),null()); HXLINE( 101) this->add(face1); HXLINE( 93) goto _hx_goto_1; } _hx_goto_1:; HXLINE( 114) this->dialogueList = dialogueList; HXLINE( 116) if (!(hasDialog)) { HXLINE( 117) return; } HXLINE( 119) ::String prefix = HX_("tai/dialogue/Dialog icons/",69,2a,8d,78); HXLINE( 121) this->portraitLeft = ::flixel::FlxSprite_obj::__alloc( HX_CTX ,(this->box->x + 100),(this->box->y + 100),null()); HXLINE( 122) ::flixel::FlxSprite _hx_tmp2 = this->portraitLeft; HXDLIN( 122) ::String library = null(); HXDLIN( 122) ::String _hx_tmp3 = ::Paths_obj::getPath(((HX_("images/",77,50,74,c1) + HX_("weeb/senpaiPortrait",9b,ed,4f,6d)) + HX_(".png",3b,2d,bd,1e)),HX_("IMAGE",3b,57,57,3b),library); HXDLIN( 122) _hx_tmp2->set_frames(::flixel::graphics::frames::FlxAtlasFrames_obj::fromSparrow(_hx_tmp3,::Paths_obj::getPath(((HX_("images/",77,50,74,c1) + HX_("weeb/senpaiPortrait",9b,ed,4f,6d)) + HX_(".xml",69,3e,c3,1e)),HX_("TEXT",ad,94,ba,37),library))); HXLINE( 123) this->portraitLeft->animation->addByPrefix(HX_("enter",18,6d,86,70),HX_("Senpai Portrait Enter",d7,e0,09,14),24,false,null(),null()); HXLINE( 124) ::flixel::FlxSprite _hx_tmp4 = this->portraitLeft; HXDLIN( 124) Float _hx_tmp5 = this->portraitLeft->get_width(); HXDLIN( 124) _hx_tmp4->setGraphicSize(::Std_obj::_hx_int(((_hx_tmp5 * ::PlayState_obj::daPixelZoom) * ((Float)0.9))),null()); HXLINE( 125) this->portraitLeft->updateHitbox(); HXLINE( 126) this->portraitLeft->scrollFactor->set(null(),null()); HXLINE( 127) this->add(this->portraitLeft); HXLINE( 128) this->portraitLeft->set_visible(false); HXLINE( 130) this->portraitRight = ::flixel::FlxSprite_obj::__alloc( HX_CTX ,0,40,null()); HXLINE( 131) ::flixel::FlxSprite _hx_tmp6 = this->portraitRight; HXDLIN( 131) ::String library1 = null(); HXDLIN( 131) ::String _hx_tmp7 = ::Paths_obj::getPath(((HX_("images/",77,50,74,c1) + HX_("weeb/bfPortrait",23,ea,7a,a3)) + HX_(".png",3b,2d,bd,1e)),HX_("IMAGE",3b,57,57,3b),library1); HXDLIN( 131) _hx_tmp6->set_frames(::flixel::graphics::frames::FlxAtlasFrames_obj::fromSparrow(_hx_tmp7,::Paths_obj::getPath(((HX_("images/",77,50,74,c1) + HX_("weeb/bfPortrait",23,ea,7a,a3)) + HX_(".xml",69,3e,c3,1e)),HX_("TEXT",ad,94,ba,37),library1))); HXLINE( 132) this->portraitRight->animation->addByPrefix(HX_("enter",18,6d,86,70),HX_("Boyfriend portrait enter",a9,02,f8,de),24,false,null(),null()); HXLINE( 133) ::flixel::FlxSprite _hx_tmp8 = this->portraitRight; HXDLIN( 133) Float _hx_tmp9 = this->portraitRight->get_width(); HXDLIN( 133) _hx_tmp8->setGraphicSize(::Std_obj::_hx_int(((_hx_tmp9 * ::PlayState_obj::daPixelZoom) * ((Float)0.9))),null()); HXLINE( 134) this->portraitRight->updateHitbox(); HXLINE( 135) this->portraitRight->scrollFactor->set(null(),null()); HXLINE( 136) this->add(this->portraitRight); HXLINE( 137) this->portraitRight->set_visible(false); HXLINE( 139) ::flixel::FlxSprite _hx_tmp10 = ::flixel::FlxSprite_obj::__alloc( HX_CTX ,(this->box->x + 200),(this->box->y - ( (Float)(300) )),null()); HXDLIN( 139) ::String library2 = null(); HXDLIN( 139) this->portraitLeftTAI = _hx_tmp10->loadGraphic(::Paths_obj::getPath(((HX_("images/",77,50,74,c1) + (prefix + HX_("taiPortrait",d7,f3,64,58))) + HX_(".png",3b,2d,bd,1e)),HX_("IMAGE",3b,57,57,3b),library2),null(),null(),null(),null(),null()); HXLINE( 140) this->portraitLeftTAI->updateHitbox(); HXLINE( 141) this->portraitLeftTAI->scrollFactor->set(null(),null()); HXLINE( 142) this->daPortraits->push(this->portraitLeftTAI); HXLINE( 143) this->add(this->portraitLeftTAI); HXLINE( 144) this->portraitLeftTAI->set_visible(false); HXLINE( 146) ::flixel::FlxSprite _hx_tmp11 = ::flixel::FlxSprite_obj::__alloc( HX_CTX ,(this->box->x + 200),(this->box->y - ( (Float)(300) )),null()); HXDLIN( 146) ::String library3 = null(); HXDLIN( 146) this->portraitLeftTAIANNOY = _hx_tmp11->loadGraphic(::Paths_obj::getPath(((HX_("images/",77,50,74,c1) + (prefix + HX_("taiPortraitAnnoy",f4,c6,99,22))) + HX_(".png",3b,2d,bd,1e)),HX_("IMAGE",3b,57,57,3b),library3),null(),null(),null(),null(),null()); HXLINE( 147) this->portraitLeftTAIANNOY->updateHitbox(); HXLINE( 148) this->portraitLeftTAIANNOY->scrollFactor->set(null(),null()); HXLINE( 149) this->daPortraits->push(this->portraitLeftTAIANNOY); HXLINE( 150) this->add(this->portraitLeftTAIANNOY); HXLINE( 151) this->portraitLeftTAIANNOY->set_visible(false); HXLINE( 153) ::flixel::FlxSprite _hx_tmp12 = ::flixel::FlxSprite_obj::__alloc( HX_CTX ,(this->box->x + 200),(this->box->y - ( (Float)(300) )),null()); HXDLIN( 153) ::String library4 = null(); HXDLIN( 153) this->portraitLeftTAIRAGE = _hx_tmp12->loadGraphic(::Paths_obj::getPath(((HX_("images/",77,50,74,c1) + (prefix + HX_("taiPortraitRage",04,9f,fe,ba))) + HX_(".png",3b,2d,bd,1e)),HX_("IMAGE",3b,57,57,3b),library4),null(),null(),null(),null(),null()); HXLINE( 154) this->portraitLeftTAIRAGE->updateHitbox(); HXLINE( 155) this->portraitLeftTAIRAGE->scrollFactor->set(null(),null()); HXLINE( 156) this->daPortraits->push(this->portraitLeftTAIRAGE); HXLINE( 157) this->add(this->portraitLeftTAIRAGE); HXLINE( 158) this->portraitLeftTAIRAGE->set_visible(false); HXLINE( 160) ::flixel::FlxSprite _hx_tmp13 = ::flixel::FlxSprite_obj::__alloc( HX_CTX ,(this->box->x + 200),(this->box->y - ( (Float)(300) )),null()); HXDLIN( 160) ::String library5 = null(); HXDLIN( 160) this->portraitLeftTAICHEER = _hx_tmp13->loadGraphic(::Paths_obj::getPath(((HX_("images/",77,50,74,c1) + (prefix + HX_("taiPortraitRage",04,9f,fe,ba))) + HX_(".png",3b,2d,bd,1e)),HX_("IMAGE",3b,57,57,3b),library5),null(),null(),null(),null(),null()); HXLINE( 161) this->portraitLeftTAICHEER->updateHitbox(); HXLINE( 162) this->portraitLeftTAICHEER->scrollFactor->set(null(),null()); HXLINE( 163) this->daPortraits->push(this->portraitLeftTAICHEER); HXLINE( 164) this->add(this->portraitLeftTAICHEER); HXLINE( 165) this->portraitLeftTAICHEER->set_visible(false); HXLINE( 167) ::flixel::FlxSprite _hx_tmp14 = ::flixel::FlxSprite_obj::__alloc( HX_CTX ,(this->box->x + 200),(this->box->y - ( (Float)(300) )),null()); HXDLIN( 167) ::String library6 = null(); HXDLIN( 167) this->portraitLeftTAIDEMON = _hx_tmp14->loadGraphic(::Paths_obj::getPath(((HX_("images/",77,50,74,c1) + (prefix + HX_("taiDemonPortrait",6a,92,02,7b))) + HX_(".png",3b,2d,bd,1e)),HX_("IMAGE",3b,57,57,3b),library6),null(),null(),null(),null(),null()); HXLINE( 168) this->portraitLeftTAIDEMON->updateHitbox(); HXLINE( 169) this->portraitLeftTAIDEMON->scrollFactor->set(null(),null()); HXLINE( 170) this->daPortraits->push(this->portraitLeftTAIDEMON); HXLINE( 171) this->add(this->portraitLeftTAIDEMON); HXLINE( 172) this->portraitLeftTAIDEMON->set_visible(false); HXLINE( 174) ::flixel::FlxSprite _hx_tmp15 = ::flixel::FlxSprite_obj::__alloc( HX_CTX ,(this->box->x + 720),(this->box->y - ( (Float)(300) )),null()); HXDLIN( 174) ::String library7 = null(); HXDLIN( 174) this->portraitRightBF = _hx_tmp15->loadGraphic(::Paths_obj::getPath(((HX_("images/",77,50,74,c1) + (prefix + HX_("bfCartoon",0a,3c,ef,25))) + HX_(".png",3b,2d,bd,1e)),HX_("IMAGE",3b,57,57,3b),library7),null(),null(),null(),null(),null()); HXLINE( 175) this->portraitRightBF->updateHitbox(); HXLINE( 176) this->portraitRightBF->scrollFactor->set(null(),null()); HXLINE( 177) this->daPortraits->push(this->portraitRightBF); HXLINE( 178) this->add(this->portraitRightBF); HXLINE( 179) this->portraitRightBF->set_visible(false); HXLINE( 181) ::flixel::FlxSprite _hx_tmp16 = ::flixel::FlxSprite_obj::__alloc( HX_CTX ,(this->box->x + 720),(this->box->y - ( (Float)(240) )),null()); HXDLIN( 181) ::String library8 = null(); HXDLIN( 181) this->portraitRightGF = _hx_tmp16->loadGraphic(::Paths_obj::getPath(((HX_("images/",77,50,74,c1) + (prefix + HX_("gfPortrait",9a,ee,86,fc))) + HX_(".png",3b,2d,bd,1e)),HX_("IMAGE",3b,57,57,3b),library8),null(),null(),null(),null(),null()); HXLINE( 182) this->portraitRightGF->updateHitbox(); HXLINE( 183) this->portraitRightGF->scrollFactor->set(null(),null()); HXLINE( 184) this->daPortraits->push(this->portraitRightGF); HXLINE( 185) this->add(this->portraitRightGF); HXLINE( 186) this->portraitRightGF->set_visible(false); HXLINE( 188) ::flixel::FlxSprite _hx_tmp17 = ::flixel::FlxSprite_obj::__alloc( HX_CTX ,(this->box->x + 720),(this->box->y - ( (Float)(240) )),null()); HXDLIN( 188) ::String library9 = null(); HXDLIN( 188) this->portraitRightGFOH = _hx_tmp17->loadGraphic(::Paths_obj::getPath(((HX_("images/",77,50,74,c1) + (prefix + HX_("gfPortraitOh",53,8e,13,5f))) + HX_(".png",3b,2d,bd,1e)),HX_("IMAGE",3b,57,57,3b),library9),null(),null(),null(),null(),null()); HXLINE( 189) this->portraitRightGFOH->updateHitbox(); HXLINE( 190) this->portraitRightGFOH->scrollFactor->set(null(),null()); HXLINE( 191) this->daPortraits->push(this->portraitRightGFOH); HXLINE( 192) this->add(this->portraitRightGFOH); HXLINE( 193) this->portraitRightGFOH->set_visible(false); HXLINE( 195) ::flixel::FlxSprite _hx_tmp18 = ::flixel::FlxSprite_obj::__alloc( HX_CTX ,(this->box->x + 720),(this->box->y - ( (Float)(240) )),null()); HXDLIN( 195) ::String library10 = null(); HXDLIN( 195) this->portraitRightGFANNOY = _hx_tmp18->loadGraphic(::Paths_obj::getPath(((HX_("images/",77,50,74,c1) + (prefix + HX_("gfPortraitAnnoy",51,e9,a4,16))) + HX_(".png",3b,2d,bd,1e)),HX_("IMAGE",3b,57,57,3b),library10),null(),null(),null(),null(),null()); HXLINE( 196) this->portraitRightGFANNOY->updateHitbox(); HXLINE( 197) this->portraitRightGFANNOY->scrollFactor->set(null(),null()); HXLINE( 198) this->daPortraits->push(this->portraitRightGFANNOY); HXLINE( 199) this->add(this->portraitRightGFANNOY); HXLINE( 200) this->portraitRightGFANNOY->set_visible(false); HXLINE( 202) this->box->animation->play(HX_("normalOpen",91,41,38,70),null(),null(),null()); HXLINE( 203) ::flixel::FlxSprite _hx_tmp19 = this->box; HXDLIN( 203) Float _hx_tmp20 = this->box->get_width(); HXDLIN( 203) _hx_tmp19->setGraphicSize(::Std_obj::_hx_int(((_hx_tmp20 * ::PlayState_obj::daPixelZoom) * ((Float)0.9))),null()); HXLINE( 204) this->box->updateHitbox(); HXLINE( 205) this->add(this->box); HXLINE( 207) this->box->screenCenter(::flixel::util::FlxAxes_obj::X_dyn()); HXLINE( 208) this->portraitLeft->screenCenter(::flixel::util::FlxAxes_obj::X_dyn()); HXLINE( 210) ::flixel::FlxSprite _hx_tmp21 = ::flixel::FlxSprite_obj::__alloc( HX_CTX ,(( (Float)(::flixel::FlxG_obj::width) ) * ((Float)0.9)),(( (Float)(::flixel::FlxG_obj::height) ) * ((Float)0.9)),null()); HXDLIN( 210) ::String library11 = null(); HXDLIN( 210) this->handSelect = _hx_tmp21->loadGraphic(::Paths_obj::getPath(((HX_("images/",77,50,74,c1) + HX_("weeb/pixelUI/hand_textbox",67,1b,cd,60)) + HX_(".png",3b,2d,bd,1e)),HX_("IMAGE",3b,57,57,3b),library11),null(),null(),null(),null(),null()); HXLINE( 211) this->add(this->handSelect); HXLINE( 214) bool _hx_tmp22 = !(talkingRight); HXLINE( 219) this->dropText = ::flixel::text::FlxText_obj::__alloc( HX_CTX ,242,502,::Std_obj::_hx_int((( (Float)(::flixel::FlxG_obj::width) ) * ((Float)0.6))),HX_("",00,00,00,00),32,null()); HXLINE( 220) this->dropText->set_font(HX_("Pixel Arial 11 Bold",ae,17,c6,45)); HXLINE( 221) this->dropText->set_color(-2583404); HXLINE( 222) this->add(this->dropText); HXLINE( 224) this->swagDialogue = ::flixel::addons::text::FlxTypeText_obj::__alloc( HX_CTX ,( (Float)(240) ),( (Float)(500) ),::Std_obj::_hx_int((( (Float)(::flixel::FlxG_obj::width) ) * ((Float)0.6))),HX_("",00,00,00,00),32,null()); HXLINE( 225) this->swagDialogue->set_font(HX_("Pixel Arial 11 Bold",ae,17,c6,45)); HXLINE( 226) this->swagDialogue->set_color(-12640223); HXLINE( 227) ::flixel::_hx_system::frontEnds::SoundFrontEnd _hx_tmp23 = ::flixel::FlxG_obj::sound; HXDLIN( 227) ::flixel::_hx_system::FlxSound _hx_tmp24 = _hx_tmp23->load(::Paths_obj::sound(HX_("pixelText",53,7a,83,06),null()),((Float)0.6),null(),null(),null(),null(),null(),null(),null()); HXDLIN( 227) this->swagDialogue->sounds = ::Array_obj< ::Dynamic>::__new(1)->init(0,_hx_tmp24); HXLINE( 228) this->add(this->swagDialogue); HXLINE( 230) this->dialogue = ::Alphabet_obj::__alloc( HX_CTX ,( (Float)(0) ),( (Float)(80) ),HX_("",00,00,00,00),false,true); } Dynamic DialogueBox_obj::__CreateEmpty() { return new DialogueBox_obj; } void *DialogueBox_obj::_hx_vtable = 0; Dynamic DialogueBox_obj::__Create(::hx::DynamicArray inArgs) { ::hx::ObjectPtr< DialogueBox_obj > _hx_result = new DialogueBox_obj(); _hx_result->__construct(inArgs[0],inArgs[1]); return _hx_result; } bool DialogueBox_obj::_hx_isInstanceOf(int inClassId) { if (inClassId<=(int)0x2c01639b) { if (inClassId<=(int)0x288ce903) { if (inClassId<=(int)0x04b35cb7) { return inClassId==(int)0x00000001 || inClassId==(int)0x04b35cb7; } else { return inClassId==(int)0x288ce903; } } else { return inClassId==(int)0x2c01639b; } } else { return inClassId==(int)0x7ccf8994 || inClassId==(int)0x7dab0655; } } void DialogueBox_obj::update(Float elapsed){ HX_GC_STACKFRAME(&_hx_pos_abff9fa8c13cc7a0_239_update) HXLINE( 238) ::DialogueBox _gthis = ::hx::ObjectPtr<OBJ_>(this); HXLINE( 241) if ((( (::String)(::PlayState_obj::SONG->__Field(HX_("song",d5,23,58,4c),::hx::paccDynamic)) ).toLowerCase() == HX_("roses",04,6c,64,ed))) { HXLINE( 242) this->portraitLeft->set_visible(false); } HXLINE( 243) if ((( (::String)(::PlayState_obj::SONG->__Field(HX_("song",d5,23,58,4c),::hx::paccDynamic)) ).toLowerCase() == HX_("thorns",9c,bf,c7,8c))) { HXLINE( 245) this->portraitLeft->set_color(-16777216); HXLINE( 246) this->swagDialogue->set_color(-1); HXLINE( 247) this->dropText->set_color(-16777216); } HXLINE( 250) this->dropText->set_text(this->swagDialogue->text); HXLINE( 252) if (::hx::IsNotNull( this->box->animation->_curAnim )) { HXLINE( 254) bool _hx_tmp; HXDLIN( 254) if ((this->box->animation->_curAnim->name == HX_("normalOpen",91,41,38,70))) { HXLINE( 254) _hx_tmp = this->box->animation->_curAnim->finished; } else { HXLINE( 254) _hx_tmp = false; } HXDLIN( 254) if (_hx_tmp) { HXLINE( 256) this->box->animation->play(HX_("normal",27,72,69,30),null(),null(),null()); HXLINE( 257) this->dialogueOpened = true; } } HXLINE( 261) bool _hx_tmp; HXDLIN( 261) if (this->dialogueOpened) { HXLINE( 261) _hx_tmp = !(this->dialogueStarted); } else { HXLINE( 261) _hx_tmp = false; } HXDLIN( 261) if (_hx_tmp) { HXLINE( 263) this->startDialogue(); HXLINE( 264) this->dialogueStarted = true; } HXLINE( 267) bool _hx_tmp1; HXDLIN( 267) if (( ( ::flixel::input::FlxBaseKeyList)(::flixel::FlxG_obj::keys->justPressed) )->get_ANY()) { HXLINE( 267) _hx_tmp1 = (this->dialogueStarted == true); } else { HXLINE( 267) _hx_tmp1 = false; } HXDLIN( 267) if (_hx_tmp1) { HXLINE( 269) this->remove(this->dialogue,null()); HXLINE( 271) ::flixel::_hx_system::frontEnds::SoundFrontEnd _hx_tmp = ::flixel::FlxG_obj::sound; HXDLIN( 271) _hx_tmp->play(::Paths_obj::sound(HX_("clickText",15,39,f9,2b),null()),((Float)0.8),null(),null(),null(),null()); HXLINE( 273) bool _hx_tmp1; HXDLIN( 273) if (::hx::IsNull( this->dialogueList->__get(1) )) { HXLINE( 273) _hx_tmp1 = ::hx::IsNotNull( this->dialogueList->__get(0) ); } else { HXLINE( 273) _hx_tmp1 = false; } HXDLIN( 273) if (_hx_tmp1) { HXLINE( 275) if (!(this->isEnding)) { HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_0, ::DialogueBox,_gthis) HXARGC(1) void _hx_run( ::flixel::util::FlxTimer tmr){ HX_GC_STACKFRAME(&_hx_pos_abff9fa8c13cc7a0_283_update) HXLINE( 284) { HXLINE( 284) ::flixel::FlxSprite _g = _gthis->box; HXDLIN( 284) _g->set_alpha((_g->alpha - ((Float)0.2))); } HXLINE( 285) { HXLINE( 285) ::flixel::FlxSprite _g1 = _gthis->bgFade; HXDLIN( 285) _g1->set_alpha((_g1->alpha - ((Float)0.139999999999999986))); } HXLINE( 286) _gthis->portraitLeft->set_visible(false); HXLINE( 287) _gthis->portraitRight->set_visible(false); HXLINE( 288) { HXLINE( 288) ::flixel::addons::text::FlxTypeText _g2 = _gthis->swagDialogue; HXDLIN( 288) _g2->set_alpha((_g2->alpha - ((Float)0.2))); } HXLINE( 289) _gthis->dropText->set_alpha(_gthis->swagDialogue->alpha); } HX_END_LOCAL_FUNC1((void)) HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_1, ::DialogueBox,_gthis) HXARGC(1) void _hx_run( ::flixel::util::FlxTimer tmr){ HX_GC_STACKFRAME(&_hx_pos_abff9fa8c13cc7a0_293_update) HXLINE( 294) _gthis->finishThing(); HXLINE( 295) _gthis->kill(); } HX_END_LOCAL_FUNC1((void)) HXLINE( 277) this->isEnding = true; HXLINE( 279) bool _hx_tmp; HXDLIN( 279) bool _hx_tmp1; HXDLIN( 279) bool _hx_tmp2; HXDLIN( 279) bool _hx_tmp3; HXDLIN( 279) if ((( (::String)(::PlayState_obj::SONG->__Field(HX_("song",d5,23,58,4c),::hx::paccDynamic)) ).toLowerCase() != HX_("senpai",3c,df,8d,6b))) { HXLINE( 279) _hx_tmp3 = (( (::String)(::PlayState_obj::SONG->__Field(HX_("song",d5,23,58,4c),::hx::paccDynamic)) ).toLowerCase() == HX_("thorns",9c,bf,c7,8c)); } else { HXLINE( 279) _hx_tmp3 = true; } HXDLIN( 279) if (!(_hx_tmp3)) { HXLINE( 279) _hx_tmp2 = (( (::String)(::PlayState_obj::SONG->__Field(HX_("song",d5,23,58,4c),::hx::paccDynamic)) ).toLowerCase() == HX_("shift",82,ec,22,7c)); } else { HXLINE( 279) _hx_tmp2 = true; } HXDLIN( 279) if (!(_hx_tmp2)) { HXLINE( 279) _hx_tmp1 = (( (::String)(::PlayState_obj::SONG->__Field(HX_("song",d5,23,58,4c),::hx::paccDynamic)) ).toLowerCase() == HX_("brave",00,2e,e9,b8)); } else { HXLINE( 279) _hx_tmp1 = true; } HXDLIN( 279) if (!(_hx_tmp1)) { HXLINE( 279) _hx_tmp = (( (::String)(::PlayState_obj::SONG->__Field(HX_("song",d5,23,58,4c),::hx::paccDynamic)) ).toLowerCase() == HX_("loss",e3,a9,b7,47)); } else { HXLINE( 279) _hx_tmp = true; } HXDLIN( 279) if (_hx_tmp) { HXLINE( 280) ::flixel::_hx_system::FlxSound _this = ::flixel::FlxG_obj::sound->music; HXDLIN( 280) ::Dynamic To = 0; HXDLIN( 280) ::Dynamic onComplete = null(); HXDLIN( 280) if (::hx::IsNull( To )) { HXLINE( 280) To = 0; } HXDLIN( 280) if (::hx::IsNotNull( _this->fadeTween )) { HXLINE( 280) _this->fadeTween->cancel(); } HXDLIN( 280) _this->fadeTween = ::flixel::tweens::FlxTween_obj::num(_this->_volume,( (Float)(To) ),((Float)2.2), ::Dynamic(::hx::Anon_obj::Create(1) ->setFixed(0,HX_("onComplete",f8,d4,7e,5d),onComplete)),_this->volumeTween_dyn()); } HXLINE( 282) ::flixel::util::FlxTimer_obj::__alloc( HX_CTX ,null())->start(((Float)0.2), ::Dynamic(new _hx_Closure_0(_gthis)),5); HXLINE( 292) ::flixel::util::FlxTimer_obj::__alloc( HX_CTX ,null())->start(((Float)1.2), ::Dynamic(new _hx_Closure_1(_gthis)),null()); } } else { HXLINE( 301) this->dialogueList->remove(this->dialogueList->__get(0)); HXLINE( 302) this->startDialogue(); } } HXLINE( 306) this->super::update(elapsed); } void DialogueBox_obj::hidePortraits(){ HX_STACKFRAME(&_hx_pos_abff9fa8c13cc7a0_310_hidePortraits) HXLINE( 311) this->portraitLeft->set_visible(false); HXLINE( 312) this->portraitRight->set_visible(false); HXLINE( 313) { HXLINE( 313) int _g = 0; HXDLIN( 313) ::Array< ::Dynamic> _g1 = this->daPortraits; HXDLIN( 313) while((_g < _g1->length)){ HXLINE( 313) ::flixel::FlxSprite shit = _g1->__get(_g).StaticCast< ::flixel::FlxSprite >(); HXDLIN( 313) _g = (_g + 1); HXLINE( 315) shit->set_visible(false); } } } HX_DEFINE_DYNAMIC_FUNC0(DialogueBox_obj,hidePortraits,(void)) void DialogueBox_obj::startDialogue(){ HX_STACKFRAME(&_hx_pos_abff9fa8c13cc7a0_323_startDialogue) HXLINE( 324) this->cleanDialog(); HXLINE( 330) this->swagDialogue->resetText(this->dialogueList->__get(0)); HXLINE( 331) this->swagDialogue->start(((Float)0.04),true,null(),null(),null()); HXLINE( 333) ::String _hx_switch_0 = this->curCharacter; if ( (_hx_switch_0==HX_("bf",c4,55,00,00)) ){ HXLINE( 341) this->hidePortraits(); HXLINE( 342) this->portraitRightBF->set_visible(true); HXLINE( 343) this->portraitRightBF->animation->play(HX_("enter",18,6d,86,70),null(),null(),null()); HXLINE( 344) this->box->set_flipX(false); HXLINE( 340) goto _hx_goto_12; } if ( (_hx_switch_0==HX_("dad",47,36,4c,00)) ){ HXLINE( 336) this->hidePortraits(); HXLINE( 337) this->portraitLeft->set_visible(true); HXLINE( 338) this->portraitLeft->animation->play(HX_("enter",18,6d,86,70),null(),null(),null()); HXLINE( 339) this->box->set_flipX(true); HXLINE( 335) goto _hx_goto_12; } if ( (_hx_switch_0==HX_("gf",1f,5a,00,00)) ){ HXLINE( 346) this->hidePortraits(); HXLINE( 347) this->portraitRightGF->set_visible(true); HXLINE( 348) this->portraitRightGF->animation->play(HX_("enter",18,6d,86,70),null(),null(),null()); HXLINE( 349) this->box->set_flipX(false); HXLINE( 345) goto _hx_goto_12; } if ( (_hx_switch_0==HX_("gf-annoy",5d,0e,d0,b5)) ){ HXLINE( 351) this->hidePortraits(); HXLINE( 352) this->portraitRightGFANNOY->set_visible(true); HXLINE( 353) this->portraitRightGFANNOY->animation->play(HX_("enter",18,6d,86,70),null(),null(),null()); HXLINE( 354) this->box->set_flipX(false); HXLINE( 350) goto _hx_goto_12; } if ( (_hx_switch_0==HX_("gf-oh",c7,09,d4,91)) ){ HXLINE( 356) this->hidePortraits(); HXLINE( 357) this->portraitRightGFOH->set_visible(true); HXLINE( 358) this->portraitRightGFOH->animation->play(HX_("enter",18,6d,86,70),null(),null(),null()); HXLINE( 359) this->box->set_flipX(false); HXLINE( 355) goto _hx_goto_12; } if ( (_hx_switch_0==HX_("tai",5c,5a,58,00)) ){ HXLINE( 361) this->hidePortraits(); HXLINE( 362) this->portraitLeftTAI->set_visible(true); HXLINE( 363) this->box->set_flipX(true); HXLINE( 360) goto _hx_goto_12; } if ( (_hx_switch_0==HX_("tai-annoyed",39,7d,94,30)) ){ HXLINE( 365) this->hidePortraits(); HXLINE( 366) this->portraitLeftTAIANNOY->set_visible(true); HXLINE( 367) this->box->set_flipX(true); HXLINE( 364) goto _hx_goto_12; } if ( (_hx_switch_0==HX_("tai-cheer",9c,5e,94,93)) ){ HXLINE( 373) this->hidePortraits(); HXLINE( 374) this->portraitLeftTAICHEER->set_visible(true); HXLINE( 375) this->box->set_flipX(true); HXLINE( 372) goto _hx_goto_12; } if ( (_hx_switch_0==HX_("tai-demon",fa,69,05,25)) ){ HXLINE( 377) this->hidePortraits(); HXLINE( 378) this->portraitLeftTAIDEMON->set_visible(true); HXLINE( 379) this->box->set_flipX(true); HXLINE( 376) goto _hx_goto_12; } if ( (_hx_switch_0==HX_("tai-rage",5e,fa,a2,dc)) ){ HXLINE( 369) this->hidePortraits(); HXLINE( 370) this->portraitLeftTAIRAGE->set_visible(true); HXLINE( 371) this->box->set_flipX(true); HXLINE( 368) goto _hx_goto_12; } _hx_goto_12:; } HX_DEFINE_DYNAMIC_FUNC0(DialogueBox_obj,startDialogue,(void)) void DialogueBox_obj::cleanDialog(){ HX_STACKFRAME(&_hx_pos_abff9fa8c13cc7a0_384_cleanDialog) HXLINE( 385) ::Array< ::String > splitName = this->dialogueList->__get(0).split(HX_(":",3a,00,00,00)); HXLINE( 386) this->curCharacter = splitName->__get(1); HXLINE( 387) this->dialogueList[0] = ::StringTools_obj::trim(this->dialogueList->__get(0).substr((splitName->__get(1).length + 2),null())); } HX_DEFINE_DYNAMIC_FUNC0(DialogueBox_obj,cleanDialog,(void)) ::hx::ObjectPtr< DialogueBox_obj > DialogueBox_obj::__new(::hx::Null< bool > __o_talkingRight,::Array< ::String > dialogueList) { ::hx::ObjectPtr< DialogueBox_obj > __this = new DialogueBox_obj(); __this->__construct(__o_talkingRight,dialogueList); return __this; } ::hx::ObjectPtr< DialogueBox_obj > DialogueBox_obj::__alloc(::hx::Ctx *_hx_ctx,::hx::Null< bool > __o_talkingRight,::Array< ::String > dialogueList) { DialogueBox_obj *__this = (DialogueBox_obj*)(::hx::Ctx::alloc(_hx_ctx, sizeof(DialogueBox_obj), true, "DialogueBox")); *(void **)__this = DialogueBox_obj::_hx_vtable; __this->__construct(__o_talkingRight,dialogueList); return __this; } DialogueBox_obj::DialogueBox_obj() { } void DialogueBox_obj::__Mark(HX_MARK_PARAMS) { HX_MARK_BEGIN_CLASS(DialogueBox); HX_MARK_MEMBER_NAME(box,"box"); HX_MARK_MEMBER_NAME(curCharacter,"curCharacter"); HX_MARK_MEMBER_NAME(dialogue,"dialogue"); HX_MARK_MEMBER_NAME(dialogueList,"dialogueList"); HX_MARK_MEMBER_NAME(swagDialogue,"swagDialogue"); HX_MARK_MEMBER_NAME(dropText,"dropText"); HX_MARK_MEMBER_NAME(finishThing,"finishThing"); HX_MARK_MEMBER_NAME(portraitLeft,"portraitLeft"); HX_MARK_MEMBER_NAME(portraitRight,"portraitRight"); HX_MARK_MEMBER_NAME(portraitLeftTAI,"portraitLeftTAI"); HX_MARK_MEMBER_NAME(portraitLeftTAIANNOY,"portraitLeftTAIANNOY"); HX_MARK_MEMBER_NAME(portraitLeftTAIRAGE,"portraitLeftTAIRAGE"); HX_MARK_MEMBER_NAME(portraitLeftTAIDEMON,"portraitLeftTAIDEMON"); HX_MARK_MEMBER_NAME(portraitLeftTAICHEER,"portraitLeftTAICHEER"); HX_MARK_MEMBER_NAME(portraitRightBF,"portraitRightBF"); HX_MARK_MEMBER_NAME(portraitRightGF,"portraitRightGF"); HX_MARK_MEMBER_NAME(portraitRightGFOH,"portraitRightGFOH"); HX_MARK_MEMBER_NAME(portraitRightGFANNOY,"portraitRightGFANNOY"); HX_MARK_MEMBER_NAME(daPortraits,"daPortraits"); HX_MARK_MEMBER_NAME(handSelect,"handSelect"); HX_MARK_MEMBER_NAME(bgFade,"bgFade"); HX_MARK_MEMBER_NAME(dialogueOpened,"dialogueOpened"); HX_MARK_MEMBER_NAME(dialogueStarted,"dialogueStarted"); HX_MARK_MEMBER_NAME(isEnding,"isEnding"); ::flixel::group::FlxTypedSpriteGroup_obj::__Mark(HX_MARK_ARG); HX_MARK_END_CLASS(); } void DialogueBox_obj::__Visit(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(box,"box"); HX_VISIT_MEMBER_NAME(curCharacter,"curCharacter"); HX_VISIT_MEMBER_NAME(dialogue,"dialogue"); HX_VISIT_MEMBER_NAME(dialogueList,"dialogueList"); HX_VISIT_MEMBER_NAME(swagDialogue,"swagDialogue"); HX_VISIT_MEMBER_NAME(dropText,"dropText"); HX_VISIT_MEMBER_NAME(finishThing,"finishThing"); HX_VISIT_MEMBER_NAME(portraitLeft,"portraitLeft"); HX_VISIT_MEMBER_NAME(portraitRight,"portraitRight"); HX_VISIT_MEMBER_NAME(portraitLeftTAI,"portraitLeftTAI"); HX_VISIT_MEMBER_NAME(portraitLeftTAIANNOY,"portraitLeftTAIANNOY"); HX_VISIT_MEMBER_NAME(portraitLeftTAIRAGE,"portraitLeftTAIRAGE"); HX_VISIT_MEMBER_NAME(portraitLeftTAIDEMON,"portraitLeftTAIDEMON"); HX_VISIT_MEMBER_NAME(portraitLeftTAICHEER,"portraitLeftTAICHEER"); HX_VISIT_MEMBER_NAME(portraitRightBF,"portraitRightBF"); HX_VISIT_MEMBER_NAME(portraitRightGF,"portraitRightGF"); HX_VISIT_MEMBER_NAME(portraitRightGFOH,"portraitRightGFOH"); HX_VISIT_MEMBER_NAME(portraitRightGFANNOY,"portraitRightGFANNOY"); HX_VISIT_MEMBER_NAME(daPortraits,"daPortraits"); HX_VISIT_MEMBER_NAME(handSelect,"handSelect"); HX_VISIT_MEMBER_NAME(bgFade,"bgFade"); HX_VISIT_MEMBER_NAME(dialogueOpened,"dialogueOpened"); HX_VISIT_MEMBER_NAME(dialogueStarted,"dialogueStarted"); HX_VISIT_MEMBER_NAME(isEnding,"isEnding"); ::flixel::group::FlxTypedSpriteGroup_obj::__Visit(HX_VISIT_ARG); } ::hx::Val DialogueBox_obj::__Field(const ::String &inName,::hx::PropertyAccess inCallProp) { switch(inName.length) { case 3: if (HX_FIELD_EQ(inName,"box") ) { return ::hx::Val( box ); } break; case 6: if (HX_FIELD_EQ(inName,"bgFade") ) { return ::hx::Val( bgFade ); } if (HX_FIELD_EQ(inName,"update") ) { return ::hx::Val( update_dyn() ); } break; case 8: if (HX_FIELD_EQ(inName,"dialogue") ) { return ::hx::Val( dialogue ); } if (HX_FIELD_EQ(inName,"dropText") ) { return ::hx::Val( dropText ); } if (HX_FIELD_EQ(inName,"isEnding") ) { return ::hx::Val( isEnding ); } break; case 10: if (HX_FIELD_EQ(inName,"handSelect") ) { return ::hx::Val( handSelect ); } break; case 11: if (HX_FIELD_EQ(inName,"finishThing") ) { return ::hx::Val( finishThing ); } if (HX_FIELD_EQ(inName,"daPortraits") ) { return ::hx::Val( daPortraits ); } if (HX_FIELD_EQ(inName,"cleanDialog") ) { return ::hx::Val( cleanDialog_dyn() ); } break; case 12: if (HX_FIELD_EQ(inName,"curCharacter") ) { return ::hx::Val( curCharacter ); } if (HX_FIELD_EQ(inName,"dialogueList") ) { return ::hx::Val( dialogueList ); } if (HX_FIELD_EQ(inName,"swagDialogue") ) { return ::hx::Val( swagDialogue ); } if (HX_FIELD_EQ(inName,"portraitLeft") ) { return ::hx::Val( portraitLeft ); } break; case 13: if (HX_FIELD_EQ(inName,"portraitRight") ) { return ::hx::Val( portraitRight ); } if (HX_FIELD_EQ(inName,"hidePortraits") ) { return ::hx::Val( hidePortraits_dyn() ); } if (HX_FIELD_EQ(inName,"startDialogue") ) { return ::hx::Val( startDialogue_dyn() ); } break; case 14: if (HX_FIELD_EQ(inName,"dialogueOpened") ) { return ::hx::Val( dialogueOpened ); } break; case 15: if (HX_FIELD_EQ(inName,"portraitLeftTAI") ) { return ::hx::Val( portraitLeftTAI ); } if (HX_FIELD_EQ(inName,"portraitRightBF") ) { return ::hx::Val( portraitRightBF ); } if (HX_FIELD_EQ(inName,"portraitRightGF") ) { return ::hx::Val( portraitRightGF ); } if (HX_FIELD_EQ(inName,"dialogueStarted") ) { return ::hx::Val( dialogueStarted ); } break; case 17: if (HX_FIELD_EQ(inName,"portraitRightGFOH") ) { return ::hx::Val( portraitRightGFOH ); } break; case 19: if (HX_FIELD_EQ(inName,"portraitLeftTAIRAGE") ) { return ::hx::Val( portraitLeftTAIRAGE ); } break; case 20: if (HX_FIELD_EQ(inName,"portraitLeftTAIANNOY") ) { return ::hx::Val( portraitLeftTAIANNOY ); } if (HX_FIELD_EQ(inName,"portraitLeftTAIDEMON") ) { return ::hx::Val( portraitLeftTAIDEMON ); } if (HX_FIELD_EQ(inName,"portraitLeftTAICHEER") ) { return ::hx::Val( portraitLeftTAICHEER ); } if (HX_FIELD_EQ(inName,"portraitRightGFANNOY") ) { return ::hx::Val( portraitRightGFANNOY ); } } return super::__Field(inName,inCallProp); } ::hx::Val DialogueBox_obj::__SetField(const ::String &inName,const ::hx::Val &inValue,::hx::PropertyAccess inCallProp) { switch(inName.length) { case 3: if (HX_FIELD_EQ(inName,"box") ) { box=inValue.Cast< ::flixel::FlxSprite >(); return inValue; } break; case 6: if (HX_FIELD_EQ(inName,"bgFade") ) { bgFade=inValue.Cast< ::flixel::FlxSprite >(); return inValue; } break; case 8: if (HX_FIELD_EQ(inName,"dialogue") ) { dialogue=inValue.Cast< ::Alphabet >(); return inValue; } if (HX_FIELD_EQ(inName,"dropText") ) { dropText=inValue.Cast< ::flixel::text::FlxText >(); return inValue; } if (HX_FIELD_EQ(inName,"isEnding") ) { isEnding=inValue.Cast< bool >(); return inValue; } break; case 10: if (HX_FIELD_EQ(inName,"handSelect") ) { handSelect=inValue.Cast< ::flixel::FlxSprite >(); return inValue; } break; case 11: if (HX_FIELD_EQ(inName,"finishThing") ) { finishThing=inValue.Cast< ::Dynamic >(); return inValue; } if (HX_FIELD_EQ(inName,"daPortraits") ) { daPortraits=inValue.Cast< ::Array< ::Dynamic> >(); return inValue; } break; case 12: if (HX_FIELD_EQ(inName,"curCharacter") ) { curCharacter=inValue.Cast< ::String >(); return inValue; } if (HX_FIELD_EQ(inName,"dialogueList") ) { dialogueList=inValue.Cast< ::Array< ::String > >(); return inValue; } if (HX_FIELD_EQ(inName,"swagDialogue") ) { swagDialogue=inValue.Cast< ::flixel::addons::text::FlxTypeText >(); return inValue; } if (HX_FIELD_EQ(inName,"portraitLeft") ) { portraitLeft=inValue.Cast< ::flixel::FlxSprite >(); return inValue; } break; case 13: if (HX_FIELD_EQ(inName,"portraitRight") ) { portraitRight=inValue.Cast< ::flixel::FlxSprite >(); return inValue; } break; case 14: if (HX_FIELD_EQ(inName,"dialogueOpened") ) { dialogueOpened=inValue.Cast< bool >(); return inValue; } break; case 15: if (HX_FIELD_EQ(inName,"portraitLeftTAI") ) { portraitLeftTAI=inValue.Cast< ::flixel::FlxSprite >(); return inValue; } if (HX_FIELD_EQ(inName,"portraitRightBF") ) { portraitRightBF=inValue.Cast< ::flixel::FlxSprite >(); return inValue; } if (HX_FIELD_EQ(inName,"portraitRightGF") ) { portraitRightGF=inValue.Cast< ::flixel::FlxSprite >(); return inValue; } if (HX_FIELD_EQ(inName,"dialogueStarted") ) { dialogueStarted=inValue.Cast< bool >(); return inValue; } break; case 17: if (HX_FIELD_EQ(inName,"portraitRightGFOH") ) { portraitRightGFOH=inValue.Cast< ::flixel::FlxSprite >(); return inValue; } break; case 19: if (HX_FIELD_EQ(inName,"portraitLeftTAIRAGE") ) { portraitLeftTAIRAGE=inValue.Cast< ::flixel::FlxSprite >(); return inValue; } break; case 20: if (HX_FIELD_EQ(inName,"portraitLeftTAIANNOY") ) { portraitLeftTAIANNOY=inValue.Cast< ::flixel::FlxSprite >(); return inValue; } if (HX_FIELD_EQ(inName,"portraitLeftTAIDEMON") ) { portraitLeftTAIDEMON=inValue.Cast< ::flixel::FlxSprite >(); return inValue; } if (HX_FIELD_EQ(inName,"portraitLeftTAICHEER") ) { portraitLeftTAICHEER=inValue.Cast< ::flixel::FlxSprite >(); return inValue; } if (HX_FIELD_EQ(inName,"portraitRightGFANNOY") ) { portraitRightGFANNOY=inValue.Cast< ::flixel::FlxSprite >(); return inValue; } } return super::__SetField(inName,inValue,inCallProp); } void DialogueBox_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_("box",0b,be,4a,00)); outFields->push(HX_("curCharacter",09,86,7c,d7)); outFields->push(HX_("dialogue",18,2d,94,a7)); outFields->push(HX_("dialogueList",96,e1,d8,0d)); outFields->push(HX_("swagDialogue",c2,ad,00,ad)); outFields->push(HX_("dropText",7c,74,94,f2)); outFields->push(HX_("portraitLeft",02,9f,53,0d)); outFields->push(HX_("portraitRight",81,90,e4,12)); outFields->push(HX_("portraitLeftTAI",7a,24,0c,e3)); outFields->push(HX_("portraitLeftTAIANNOY",71,2f,d1,d2)); outFields->push(HX_("portraitLeftTAIRAGE",07,f9,35,3b)); outFields->push(HX_("portraitLeftTAIDEMON",11,3f,11,87)); outFields->push(HX_("portraitLeftTAICHEER",b3,33,a0,f5)); outFields->push(HX_("portraitRightBF",85,ac,8a,01)); outFields->push(HX_("portraitRightGF",e0,b0,8a,01)); outFields->push(HX_("portraitRightGFOH",f9,ed,40,7e)); outFields->push(HX_("portraitRightGFANNOY",4b,f1,7d,2a)); outFields->push(HX_("daPortraits",7b,3f,7a,b5)); outFields->push(HX_("handSelect",cb,77,90,7c)); outFields->push(HX_("bgFade",e1,fd,cd,ab)); outFields->push(HX_("dialogueOpened",e1,e5,9f,10)); outFields->push(HX_("dialogueStarted",09,77,22,70)); outFields->push(HX_("isEnding",71,3f,f2,52)); super::__GetFields(outFields); }; #ifdef HXCPP_SCRIPTABLE static ::hx::StorageInfo DialogueBox_obj_sMemberStorageInfo[] = { {::hx::fsObject /* ::flixel::FlxSprite */ ,(int)offsetof(DialogueBox_obj,box),HX_("box",0b,be,4a,00)}, {::hx::fsString,(int)offsetof(DialogueBox_obj,curCharacter),HX_("curCharacter",09,86,7c,d7)}, {::hx::fsObject /* ::Alphabet */ ,(int)offsetof(DialogueBox_obj,dialogue),HX_("dialogue",18,2d,94,a7)}, {::hx::fsObject /* ::Array< ::String > */ ,(int)offsetof(DialogueBox_obj,dialogueList),HX_("dialogueList",96,e1,d8,0d)}, {::hx::fsObject /* ::flixel::addons::text::FlxTypeText */ ,(int)offsetof(DialogueBox_obj,swagDialogue),HX_("swagDialogue",c2,ad,00,ad)}, {::hx::fsObject /* ::flixel::text::FlxText */ ,(int)offsetof(DialogueBox_obj,dropText),HX_("dropText",7c,74,94,f2)}, {::hx::fsObject /* ::Dynamic */ ,(int)offsetof(DialogueBox_obj,finishThing),HX_("finishThing",9b,aa,8e,36)}, {::hx::fsObject /* ::flixel::FlxSprite */ ,(int)offsetof(DialogueBox_obj,portraitLeft),HX_("portraitLeft",02,9f,53,0d)}, {::hx::fsObject /* ::flixel::FlxSprite */ ,(int)offsetof(DialogueBox_obj,portraitRight),HX_("portraitRight",81,90,e4,12)}, {::hx::fsObject /* ::flixel::FlxSprite */ ,(int)offsetof(DialogueBox_obj,portraitLeftTAI),HX_("portraitLeftTAI",7a,24,0c,e3)}, {::hx::fsObject /* ::flixel::FlxSprite */ ,(int)offsetof(DialogueBox_obj,portraitLeftTAIANNOY),HX_("portraitLeftTAIANNOY",71,2f,d1,d2)}, {::hx::fsObject /* ::flixel::FlxSprite */ ,(int)offsetof(DialogueBox_obj,portraitLeftTAIRAGE),HX_("portraitLeftTAIRAGE",07,f9,35,3b)}, {::hx::fsObject /* ::flixel::FlxSprite */ ,(int)offsetof(DialogueBox_obj,portraitLeftTAIDEMON),HX_("portraitLeftTAIDEMON",11,3f,11,87)}, {::hx::fsObject /* ::flixel::FlxSprite */ ,(int)offsetof(DialogueBox_obj,portraitLeftTAICHEER),HX_("portraitLeftTAICHEER",b3,33,a0,f5)}, {::hx::fsObject /* ::flixel::FlxSprite */ ,(int)offsetof(DialogueBox_obj,portraitRightBF),HX_("portraitRightBF",85,ac,8a,01)}, {::hx::fsObject /* ::flixel::FlxSprite */ ,(int)offsetof(DialogueBox_obj,portraitRightGF),HX_("portraitRightGF",e0,b0,8a,01)}, {::hx::fsObject /* ::flixel::FlxSprite */ ,(int)offsetof(DialogueBox_obj,portraitRightGFOH),HX_("portraitRightGFOH",f9,ed,40,7e)}, {::hx::fsObject /* ::flixel::FlxSprite */ ,(int)offsetof(DialogueBox_obj,portraitRightGFANNOY),HX_("portraitRightGFANNOY",4b,f1,7d,2a)}, {::hx::fsObject /* ::Array< ::Dynamic> */ ,(int)offsetof(DialogueBox_obj,daPortraits),HX_("daPortraits",7b,3f,7a,b5)}, {::hx::fsObject /* ::flixel::FlxSprite */ ,(int)offsetof(DialogueBox_obj,handSelect),HX_("handSelect",cb,77,90,7c)}, {::hx::fsObject /* ::flixel::FlxSprite */ ,(int)offsetof(DialogueBox_obj,bgFade),HX_("bgFade",e1,fd,cd,ab)}, {::hx::fsBool,(int)offsetof(DialogueBox_obj,dialogueOpened),HX_("dialogueOpened",e1,e5,9f,10)}, {::hx::fsBool,(int)offsetof(DialogueBox_obj,dialogueStarted),HX_("dialogueStarted",09,77,22,70)}, {::hx::fsBool,(int)offsetof(DialogueBox_obj,isEnding),HX_("isEnding",71,3f,f2,52)}, { ::hx::fsUnknown, 0, null()} }; static ::hx::StaticInfo *DialogueBox_obj_sStaticStorageInfo = 0; #endif static ::String DialogueBox_obj_sMemberFields[] = { HX_("box",0b,be,4a,00), HX_("curCharacter",09,86,7c,d7), HX_("dialogue",18,2d,94,a7), HX_("dialogueList",96,e1,d8,0d), HX_("swagDialogue",c2,ad,00,ad), HX_("dropText",7c,74,94,f2), HX_("finishThing",9b,aa,8e,36), HX_("portraitLeft",02,9f,53,0d), HX_("portraitRight",81,90,e4,12), HX_("portraitLeftTAI",7a,24,0c,e3), HX_("portraitLeftTAIANNOY",71,2f,d1,d2), HX_("portraitLeftTAIRAGE",07,f9,35,3b), HX_("portraitLeftTAIDEMON",11,3f,11,87), HX_("portraitLeftTAICHEER",b3,33,a0,f5), HX_("portraitRightBF",85,ac,8a,01), HX_("portraitRightGF",e0,b0,8a,01), HX_("portraitRightGFOH",f9,ed,40,7e), HX_("portraitRightGFANNOY",4b,f1,7d,2a), HX_("daPortraits",7b,3f,7a,b5), HX_("handSelect",cb,77,90,7c), HX_("bgFade",e1,fd,cd,ab), HX_("dialogueOpened",e1,e5,9f,10), HX_("dialogueStarted",09,77,22,70), HX_("update",09,86,05,87), HX_("hidePortraits",96,11,5b,04), HX_("isEnding",71,3f,f2,52), HX_("startDialogue",9a,8f,4f,ac), HX_("cleanDialog",31,37,ca,9e), ::String(null()) }; ::hx::Class DialogueBox_obj::__mClass; void DialogueBox_obj::__register() { DialogueBox_obj _hx_dummy; DialogueBox_obj::_hx_vtable = *(void **)&_hx_dummy; ::hx::Static(__mClass) = new ::hx::Class_obj(); __mClass->mName = HX_("DialogueBox",b3,1f,c8,ff); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &::hx::Class_obj::GetNoStaticField; __mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField; __mClass->mStatics = ::hx::Class_obj::dupFunctions(0 /* sStaticFields */); __mClass->mMembers = ::hx::Class_obj::dupFunctions(DialogueBox_obj_sMemberFields); __mClass->mCanCast = ::hx::TCanCast< DialogueBox_obj >; #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = DialogueBox_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = DialogueBox_obj_sStaticStorageInfo; #endif ::hx::_hx_RegisterClass(__mClass->mName, __mClass); }
56.258621
274
0.68699
Tyrcnex
22114ee85d794fec97929347707fe3d2d5529b40
1,389
cc
C++
gcc-gcc-7_3_0-release/libstdc++-v3/testsuite/23_containers/set/cons/61023.cc
best08618/asylo
5a520a9f5c461ede0f32acc284017b737a43898c
[ "Apache-2.0" ]
7
2020-05-02T17:34:05.000Z
2021-10-17T10:15:18.000Z
gcc-gcc-7_3_0-release/libstdc++-v3/testsuite/23_containers/set/cons/61023.cc
best08618/asylo
5a520a9f5c461ede0f32acc284017b737a43898c
[ "Apache-2.0" ]
null
null
null
gcc-gcc-7_3_0-release/libstdc++-v3/testsuite/23_containers/set/cons/61023.cc
best08618/asylo
5a520a9f5c461ede0f32acc284017b737a43898c
[ "Apache-2.0" ]
2
2020-07-27T00:22:36.000Z
2021-04-01T09:41:02.000Z
// { dg-do run { target c++11 } } // Copyright (C) 2014-2017 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library 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, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. #include <set> #include <stdexcept> struct Comparator { Comparator() : valid(false) { } explicit Comparator(bool) : valid(true) { } bool operator()(int i, int j) const { if (!valid) throw std::logic_error("Comparator is invalid"); return i < j; } private: bool valid; }; int main() { using test_type = std::set<int, Comparator>; Comparator cmp{true}; test_type good{cmp}; test_type s1; s1 = good; // copy-assign s1.insert(1); s1.insert(2); test_type s2; s2 = std::move(good); // move-assign s2.insert(1); s2.insert(2); }
24.368421
74
0.677466
best08618
81faf10543b62f782b6cca1d4980a4a134190613
1,018
cpp
C++
Data Structures/Dynamic Programming/1-D DP/Frog Jump/Memoization.cpp
ravikjha7/Competitive_Programming
86df773c258d6675bb3244030e6d71aa32e01fce
[ "MIT" ]
null
null
null
Data Structures/Dynamic Programming/1-D DP/Frog Jump/Memoization.cpp
ravikjha7/Competitive_Programming
86df773c258d6675bb3244030e6d71aa32e01fce
[ "MIT" ]
null
null
null
Data Structures/Dynamic Programming/1-D DP/Frog Jump/Memoization.cpp
ravikjha7/Competitive_Programming
86df773c258d6675bb3244030e6d71aa32e01fce
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef long long int ll; #define mod 1000000007 void file() { #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif } int frogjump(int n, int k, vector<int> &heights, vector<int> &dp) { if(n == 0) return 0; if(dp[n] != -1) { // cout << "Time Saved" << endl; return dp[n]; } int minm = INT_MAX; for(int i = 1; i <= min(n,k); i++) { minm = min(minm,frogjump(n-i,k,heights,dp) + abs(heights[n] - heights[n-i])); } return minm; } int frogJump(int n, int k,vector<int> &heights) { vector<int> dp(n,-1); return frogjump(n-1,k,heights,dp); } void solve() { int n,k; cin >> n >> k; vector<int> heights(n,0); // vector<int> dp(n,-1); for(int i = 0; i < n; i++) cin >> heights[i]; cout << frogJump(n,k,heights) << endl; } int main() { file(); ios_base::sync_with_stdio(false); cin.tie(NULL); int t = 1; cin >> t; while(t--) { solve(); } return 0; }
17.551724
82
0.562868
ravikjha7
c304cfdc7ccd40df10f2cced98e36ea067e9e79b
852
hpp
C++
libs/renderer/include/sge/renderer/index/dynamic/format_element.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
libs/renderer/include/sge/renderer/index/dynamic/format_element.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
libs/renderer/include/sge/renderer/index/dynamic/format_element.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef SGE_RENDERER_INDEX_DYNAMIC_FORMAT_ELEMENT_HPP_INCLUDED #define SGE_RENDERER_INDEX_DYNAMIC_FORMAT_ELEMENT_HPP_INCLUDED #include <sge/renderer/index/i16.hpp> #include <sge/renderer/index/i32.hpp> #include <sge/renderer/index/dynamic/format.hpp> namespace sge::renderer::index::dynamic { template <sge::renderer::index::dynamic::format> struct format_element; template <> struct format_element<sge::renderer::index::dynamic::format::i16> { using type = sge::renderer::index::i16; }; template <> struct format_element<sge::renderer::index::dynamic::format::i32> { using type = sge::renderer::index::i32; }; } #endif
25.058824
65
0.746479
cpreh
c308388811a103318eb43ff5b22c43d248659246
4,012
cpp
C++
base/Windows/singx86/apic.cpp
sphinxlogic/Singularity-RDK-2.0
2968c3b920a5383f7360e3e489aa772f964a7c42
[ "MIT" ]
null
null
null
base/Windows/singx86/apic.cpp
sphinxlogic/Singularity-RDK-2.0
2968c3b920a5383f7360e3e489aa772f964a7c42
[ "MIT" ]
null
null
null
base/Windows/singx86/apic.cpp
sphinxlogic/Singularity-RDK-2.0
2968c3b920a5383f7360e3e489aa772f964a7c42
[ "MIT" ]
null
null
null
///////////////////////////////////////////////////////////////////////////// // // apic.cpp - Extension to inspect APIC // // Copyright Microsoft Corporation. All rights reserved. // #include "singx86.h" inline static ULONG ApicRead32(const BYTE* apic, int offsetInBytes) { return ((ULONG*) apic)[offsetInBytes / sizeof(ULONG)]; } inline static BYTE ApicRead8(const BYTE* apic, int offsetInBytes) { return apic[offsetInBytes]; } inline static const char* TimerMode(ULONG flag) { return (flag == 0) ? "One-shot" : "Periodic"; } inline static const char* Mask(ULONG flag) { return (flag == 0) ? "Unmasked" : "Masked "; } inline static const char* TriggerMode(ULONG pmask, ULONG flag) { if ((pmask & (1 << 15)) == 0) return "-----"; return (flag == 0) ? "Edge " : "Level"; } inline static const char* RemoteIRR(ULONG pmask, ULONG flag) { if ((pmask & (1 << 14)) == 0) return "------"; return (flag == 0) ? "No IRR" : "IRR "; } inline static const char* PinPolarity(ULONG pmask, ULONG flag) { if ((pmask & (1 << 13)) == 0) return "---------"; return (flag == 0) ? "Active-Hi" : "Active-Lo"; } inline static const char* DeliveryStatus(ULONG flag) { return (flag == 0) ? "Idle" : "Pend"; } inline static const char* DeliveryMode(ULONG pmask, ULONG value) { if ((pmask & 0x700) == 0) return "---"; const char * dm[8] = { "Fix", "Res", "SMI", "Res", "NMI", "INI", "Res", "Ext" }; value = (value & 0x700u) >> 8; return dm[value]; } static void DumpTimer(ULONG t) { ExtOut("Timer: %08x => Vector %02x ", t & 0x310ff, t & 0xff); ExtOut("%s %s %s\n", Mask(t & 0x10000), TimerMode(t & 0x20000), DeliveryStatus(t & 0x1000)); } static void DumpLvt(const char* name, ULONG pmask, ULONG value) { ExtOut("%s: %08x => Vector %02x ", name, value & pmask, value & 0xff); ExtOut("%s %s %s %s %s %s\n", Mask(value), TriggerMode(pmask, value), RemoteIRR(pmask, value), PinPolarity(pmask, value), DeliveryStatus(value), DeliveryMode(pmask, value)); } static void DumpBits(const char* name, const BYTE* apic, int startOffset) { ExtOut("%s: ", name); for (int w = 0; w < 8; w++) { ULONG bits = ApicRead32(apic, startOffset + w * 16); for (int i = 0; i < 32; i++) { if ((bits & (1 << i)) != 0) { ExtOut("0x%02x ", w * 32 + i); } } } ExtOut("\n"); } EXT_DECL(apic) // Defines: PDEBUG_CLIENT Client, PCSTR args { EXT_ENTER(); // Defines: HRESULT status = S_OK; UNREFERENCED_PARAMETER(args); static const ULONG64 ApicBase = 0x00000000fee00000; BYTE apic[0x400]; EXT_CHECK(g_ExtData->ReadPhysical(ApicBase, &apic, sizeof(apic), NULL)); int maxLvt = ApicRead8(apic, 0x32); ExtOut("Apic Id %u Version %02x Max LVT %u\n", ApicRead8(apic, 0x23), ApicRead8(apic, 0x30), maxLvt); ExtOut("TPR %08x APR %08x PPR %08x\n", ApicRead32(apic, 0x80), ApicRead32(apic, 0x90), ApicRead32(apic, 0xa0)); ExtOut("Logical Destination %08x Destination Format %08x\n", ApicRead32(apic, 0xd0), ApicRead32(apic, 0xe0)); ExtOut("Spurious Interrupt Vector %08x\n", ApicRead32(apic, 0xf0)); ExtOut("Fault Status %02x\n", ApicRead8(apic, 0x280)); DumpTimer(ApicRead32(apic, 0x320)); DumpLvt("LINT0", 0x1f7ff, ApicRead32(apic, 0x350)); DumpLvt("LINT1", 0x1f7ff, ApicRead32(apic, 0x360)); DumpLvt("Fault", 0x110ff, ApicRead32(apic, 0x370)); if (maxLvt >= 4) DumpLvt("Perf ", 0x117ff, ApicRead32(apic, 0x340)); if (maxLvt >= 5) DumpLvt("Therm", 0x117ff, ApicRead32(apic, 0x343)); DumpBits("ISR", apic, 0x100); DumpBits("IRR", apic, 0x200); DumpBits("TMR", apic, 0x180); EXT_LEAVE(); }
28.863309
78
0.554586
sphinxlogic
c3109d2cb6642ea88fafccfa18b824bbb55e58f5
4,500
hpp
C++
Crisp/GUI/Control.hpp
FallenShard/Crisp
d4cf22c0f9af73a6c4ba2b7d67696f1a188fd423
[ "MIT" ]
6
2017-09-14T03:26:49.000Z
2021-09-18T05:40:59.000Z
Crisp/GUI/Control.hpp
FallenShard/Crisp
d4cf22c0f9af73a6c4ba2b7d67696f1a188fd423
[ "MIT" ]
null
null
null
Crisp/GUI/Control.hpp
FallenShard/Crisp
d4cf22c0f9af73a6c4ba2b7d67696f1a188fd423
[ "MIT" ]
null
null
null
#pragma once #include <string> #include <memory> #include <CrispCore/Math/Headers.hpp> #include <CrispCore/Math/Rect.hpp> #include "RenderSystem.hpp" #include "GUI/GuiEnums.hpp" namespace crisp::gui { class Form; class Control { public: Control(Form* form); virtual ~Control(); void setId(std::string&& id); std::string getId() const; void setParent(Control* parent); Control* getParent() const; void setAnchor(Anchor anchor); Anchor getAnchor() const; void setOrigin(Origin origin); Origin getOrigin() const; void setSizingPolicy(SizingPolicy horizontal, SizingPolicy vertical, float widthPercent = 1.0f, float heightPercent = 1.0f); void setHorizontalSizingPolicy(SizingPolicy sizing, float widthPercent = 1.0f); SizingPolicy getHorizontalSizingPolicy() const; void setVerticalSizingPolicy(SizingPolicy sizing, float heightPercent = 1.0f); SizingPolicy getVerticalSizingPolicy() const; void setPositionX(float xPos); void setPositionY(float yPos); void setPosition(const glm::vec2& position); glm::vec2 getPosition() const; void setWidthHint(float widthHint); void setHeightHint(float heightHint); void setSizeHint(const glm::vec2& sizeHint); glm::vec2 getSize() const; virtual float getWidth() const; virtual float getHeight() const; void setPadding(glm::vec2&& paddingX, glm::vec2 paddingY); void setPadding(glm::vec2&& padding); glm::vec2 getPaddingX() const; glm::vec2 getPaddingY() const; void setDepthOffset(float depthOffset); float getDepthOffset() const; void setScale(float scale); float setScale() const; void setColor(glm::vec3 color); void setColor(glm::vec4 color); glm::vec4 getColor() const; void setOpacity(float opacity); float getOpacity() const; virtual Rect<float> getAbsoluteBounds() const; const glm::mat4& getModelMatrix() const; virtual Rect<float> getInteractionBounds() const; virtual void onMouseMoved(float x, float y); virtual void onMouseEntered(float x, float y); virtual void onMouseExited(float x, float y); virtual bool onMousePressed(float x, float y); virtual bool onMouseReleased(float x, float y); void setValidationFlags(ValidationFlags validationFlags); void clearValidationFlags(); bool needsValidation(); void validateAndClearFlags(); virtual void validate() = 0; virtual void draw(const RenderSystem& renderSystem) const = 0; template <typename T> T* getTypedControlById(std::string id) { return static_cast<T*>(getControlById(id)); } virtual Control* getControlById(const std::string& id); unsigned int getRootDistance() const; virtual void printDebugId() const; virtual void visit(std::function<void(Control*)> func); protected: glm::vec2 getParentAbsolutePosition() const; float getParentAbsoluteDepth() const; glm::vec2 getParentPaddingX() const; glm::vec2 getParentPaddingY() const; glm::vec2 getParentAbsoluteSize() const; float getParentAbsoluteOpacity() const; glm::vec2 getAnchorOffset() const; glm::vec2 getOriginOffset() const; glm::vec2 getOffsetDirection() const; glm::vec2 getAbsolutePosition() const; float getAbsoluteDepth() const; std::string m_id; Control* m_parent; Origin m_origin; Anchor m_anchor; SizingPolicy m_horizontalSizingPolicy; SizingPolicy m_verticalSizingPolicy; glm::vec2 m_parentSizePercent; // Used only when filling up the parent control glm::vec2 m_position; glm::vec2 m_sizeHint; glm::vec2 m_paddingX; // Minimum distance of children from this element's borders [left, right] glm::vec2 m_paddingY; // Padding [top, bottom] glm::mat4 m_M; // Captures absolute position and scale etc. float m_scale; float m_depthOffset; bool m_needsValidation; // Do we need to recalculate this widget's attributes Form* m_form; RenderSystem* m_renderSystem; glm::vec4 m_color; // Holds absolute values float m_opacity; // Holds control opacity }; }
31.690141
132
0.651333
FallenShard
c31230820a30e801ae483f1e2440451e186e0360
7,551
cpp
C++
TomGine/tgCollission.cpp
OpenNurbsFit/OpenNurbsFit
d1ca01437a6da6bbf921466013ff969def5dfe65
[ "BSD-3-Clause" ]
14
2015-07-06T13:04:49.000Z
2022-02-06T10:09:05.000Z
TomGine/tgCollission.cpp
OpenNurbsFit/OpenNurbsFit
d1ca01437a6da6bbf921466013ff969def5dfe65
[ "BSD-3-Clause" ]
1
2020-12-07T03:26:39.000Z
2020-12-07T03:26:39.000Z
TomGine/tgCollission.cpp
OpenNurbsFit/OpenNurbsFit
d1ca01437a6da6bbf921466013ff969def5dfe65
[ "BSD-3-Clause" ]
11
2015-07-06T13:04:43.000Z
2022-03-29T10:57:04.000Z
/* * Software License Agreement (GNU General Public License) * * Copyright (c) 2011, Thomas Mörwald * * 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/>. * * @author thomas.moerwald * */ #include "tgCollission.h" #include <stdexcept> using namespace TomGine; vec3 tgCollission::GetNormal(const vec3& v1, const vec3& v2, const vec3& v3) { vec3 n, e1, e2; e1 = v2 - v1; e2 = v3 - v1; n.cross(e1, e2); n.normalize(); return n; } bool tgCollission::IntersectRectangles2D(const tgRect2D& A, const tgRect2D& B) { bool xOverlap = valueInRange(A.x, B.x, B.x + B.w) || valueInRange(B.x, A.x, A.x + A.w); bool yOverlap = valueInRange(A.y, B.y, B.y + B.h) || valueInRange(B.y, A.y, A.y + B.h); return xOverlap && yOverlap; } bool tgCollission::IntersectRayTriangle(vec3& p, vec3& n, double& z, const tgRay& ray, const vec3& t1, const vec3& t2, const vec3& t3) { // p = ray.start + ray.dir * z (1) // p*n + d = 0 ; point p must be on plane (with normal vector n and distance d) (2) n = GetNormal(t1, t2, t3); // plane normal double d = -t1 * n; // distance of plane form origin // from (1) and (2) z = -(ray.start * n + d) / (ray.dir * n); p = ray.start + ray.dir * (float) z; // test if point lies in triangle or not return PointInTriangle(p, t1, t2, t3); } bool tgCollission::IntersectRaySphere(const tgRay &ray, const BoundingSphere &sphere, float &t) { //Compute A, B and C coefficients float a = (ray.dir * ray.dir); float b = 2 * (ray.start * ray.start); float c = (ray.start * ray.start) - (sphere.radius * sphere.radius); //Find discriminant float disc = b * b - 4 * a * c; // if discriminant is negative there are no real roots, so return // false as ray misses sphere if (disc < 0) return false; // compute q as described above float distSqrt = sqrtf(disc); float q; if (b < 0) q = (-b - distSqrt) / 2.0; else q = (-b + distSqrt) / 2.0; // compute t0 and t1 float t0 = q / a; float t1 = c / q; // make sure t0 is smaller than t1 if (t0 > t1) { // if t0 is bigger than t1 swap them around float temp = t0; t0 = t1; t1 = temp; } // if t1 is less than zero, the object is in the ray's negative direction // and consequently the ray misses the sphere if (t1 < 0) return false; // if t0 is less than zero, the intersection point is at t1 if (t0 < 0) { t = t1; return true; } // else the intersection point is at t0 else { t = t0; return true; } } bool tgCollission::IntersectRayModel(std::vector<vec3> &pl, std::vector<vec3> &nl, std::vector<double> &zl, const tgRay& ray, const tgModel& model) { bool hit = false; pl.clear(); zl.clear(); for (unsigned int i = 0; i < model.m_faces.size(); i++) { vec3 p; vec3 n; double z; if (model.m_faces[i].v.size() < 3) throw std::runtime_error("[tgCollission::IntersectRayModel] Error number of vertices to low (<3) for a face"); vec3 t1 = model.m_vertices[model.m_faces[i].v[0]].pos; vec3 t2 = model.m_vertices[model.m_faces[i].v[1]].pos; vec3 t3 = model.m_vertices[model.m_faces[i].v[2]].pos; if (IntersectRayTriangle(p, n, z, ray, t1, t2, t3)) { pl.push_back(p); nl.push_back(n); zl.push_back(z); hit = true; } if (model.m_faces[i].v.size() == 4) { t1 = model.m_vertices[model.m_faces[i].v[2]].pos; t2 = model.m_vertices[model.m_faces[i].v[3]].pos; t3 = model.m_vertices[model.m_faces[i].v[0]].pos; if (IntersectRayTriangle(p, n, z, ray, t1, t2, t3)) { pl.push_back(p); nl.push_back(n); zl.push_back(z); hit = true; } } if (model.m_faces[i].v.size() > 4) throw std::runtime_error("[tgCollission::IntersectRayModel] Error number of vertices to low (<3) for a face"); } return hit; } bool tgCollission::IntersectRayModel(std::vector<vec3> &pl, std::vector<vec3> &nl, std::vector<double> &zl, const tgRay& ray, const tgRenderModel& model) { bool hit = false; pl.clear(); zl.clear(); for (unsigned int i = 0; i < model.m_faces.size(); i++) { vec3 p; vec3 n; double z; if (model.m_faces[i].v.size() < 3) throw std::runtime_error("[tgCollission::IntersectRayModel] Error number of vertices to low (<3) for a face"); vec3 t1 = model.m_pose * model.m_vertices[model.m_faces[i].v[0]].pos; vec3 t2 = model.m_pose * model.m_vertices[model.m_faces[i].v[1]].pos; vec3 t3 = model.m_pose * model.m_vertices[model.m_faces[i].v[2]].pos; if (IntersectRayTriangle(p, n, z, ray, t1, t2, t3)) { pl.push_back(p); nl.push_back(n); zl.push_back(z); hit = true; } if (model.m_faces[i].v.size() == 4) { t1 = model.m_pose * model.m_vertices[model.m_faces[i].v[2]].pos; t2 = model.m_pose * model.m_vertices[model.m_faces[i].v[3]].pos; t3 = model.m_pose * model.m_vertices[model.m_faces[i].v[0]].pos; if (IntersectRayTriangle(p, n, z, ray, t1, t2, t3)) { pl.push_back(p); nl.push_back(n); zl.push_back(z); hit = true; } } if (model.m_faces[i].v.size() > 4) throw std::runtime_error("[tgCollission::IntersectRayModel] Error number of vertices to low (<3) for a face"); } return hit; } bool tgCollission::IntersectModels(const tgModel &m1, const tgModel &m2, const tgPose &p1, const tgPose& p2) { vec3 t1, t2; mat3 R1, R2; p1.GetPose(R1, t1); p2.GetPose(R2, t2); vec3 center1 = t1 + R1 * m1.m_bs.center; vec3 center2 = t2 + R2 * m2.m_bs.center; float d = (center1 - center2).length(); // printf("tgCollission::IntersectModels: %f %f\n", d, (m1.m_bs.radius+m2.m_bs.radius)); if (d >= (m1.m_bs.radius + m2.m_bs.radius)) return false; // further tests // printf("[tgCollission::IntersectModels] Warning, function not implemented.\n"); return true; } bool tgCollission::IntersectModels(const tgRenderModel &m1, const tgRenderModel &m2) { vec3 t1, t2; mat3 R1, R2; m1.m_pose.GetPose(R1, t1); m2.m_pose.GetPose(R2, t2); vec3 center1 = t1 + R1 * m1.m_bs.center; vec3 center2 = t2 + R2 * m2.m_bs.center; float d = (center1 - center2).length(); // printf("tgCollission::IntersectModels: %f %f\n", d, (m1.m_bs.radius+m2.m_bs.radius)); if (d >= (m1.m_bs.radius + m2.m_bs.radius)) return false; // further tests // printf("[tgCollission::IntersectModels] Warning, function not implemented.\n"); return true; } bool tgCollission::PointOnSameSide(const vec3& p1, const vec3& p2, const vec3& a, const vec3& b) { vec3 cp1, cp2; cp1.cross(b - a, p1 - a); cp2.cross(b - a, p2 - a); if ((cp1 * cp2) > 0.0) return true; return false; } bool tgCollission::PointInTriangle(const vec3& p, const vec3& t1, const vec3& t2, const vec3& t3) { return (PointOnSameSide(p, t1, t2, t3) && PointOnSameSide(p, t2, t3, t1) && PointOnSameSide(p, t3, t1, t2)); }
27.259928
118
0.628526
OpenNurbsFit
c3125e3006efc875a61ec2265e434dfa25a5fb11
172
hpp
C++
assistant/communication.hpp
mddigaetano/AccessibleHomeAutomation
1798402e6a8a7826a0e368d58bf171e756320c4b
[ "MIT" ]
null
null
null
assistant/communication.hpp
mddigaetano/AccessibleHomeAutomation
1798402e6a8a7826a0e368d58bf171e756320c4b
[ "MIT" ]
null
null
null
assistant/communication.hpp
mddigaetano/AccessibleHomeAutomation
1798402e6a8a7826a0e368d58bf171e756320c4b
[ "MIT" ]
null
null
null
const byte BUFFER_SIZE = 128; char buffer[BUFFER_SIZE]; char START_CHAR= '<'; char END_CHAR = '>'; bool newData = false; void full_receive(); const char * full_read();
15.636364
29
0.697674
mddigaetano
c31c3ea656b0b93b60dfde8a202169b96958ee6d
2,076
cpp
C++
abserv/abserv/actions/AiGoHome.cpp
pablokawan/ABx
064d6df265c48c667ce81b0a83f84e5e22a7ff53
[ "MIT" ]
null
null
null
abserv/abserv/actions/AiGoHome.cpp
pablokawan/ABx
064d6df265c48c667ce81b0a83f84e5e22a7ff53
[ "MIT" ]
null
null
null
abserv/abserv/actions/AiGoHome.cpp
pablokawan/ABx
064d6df265c48c667ce81b0a83f84e5e22a7ff53
[ "MIT" ]
null
null
null
/** * Copyright 2017-2020 Stefan Ascher * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "AiGoHome.h" #include "../Npc.h" #include "../AiAgent.h" #include <abshared/Mechanic.h> //#define DEBUG_AI namespace AI { namespace Actions { Node::Status GoHome::DoAction(Agent& agent, uint32_t) { Game::Npc& npc = GetNpc(agent); if (npc.IsImmobilized()) return Status::Failed; const Math::Vector3& home = npc.GetHomePos(); if (home.Equals(Math::Vector3::Zero)) return Status::Failed; if (home.Equals(npc.GetPosition(), Game::AT_POSITION_THRESHOLD)) return Status::Finished; if (IsCurrentAction(agent)) return Status::Running; if (npc.GotoHomePos()) { #ifdef DEBUG_AI LOG_DEBUG << npc.GetName() << " goes home from " << npc.GetPosition().ToString() << " to " << home.ToString() << std::endl; #endif return Status::Running; } return Status::Finished; } GoHome::GoHome(const ArgumentsType& arguments) : Action(arguments) { } } }
31.938462
91
0.699422
pablokawan
c31da2cb72cad0727c99ce0dba079413bdcee7c5
372
hpp
C++
meld/core/uses_config.hpp
knoepfel/sand-art
8b4d7eccc5f2d3b926c94c3cf98be6e6d25bb9eb
[ "Apache-2.0" ]
null
null
null
meld/core/uses_config.hpp
knoepfel/sand-art
8b4d7eccc5f2d3b926c94c3cf98be6e6d25bb9eb
[ "Apache-2.0" ]
null
null
null
meld/core/uses_config.hpp
knoepfel/sand-art
8b4d7eccc5f2d3b926c94c3cf98be6e6d25bb9eb
[ "Apache-2.0" ]
null
null
null
#ifndef meld_core_uses_config_hpp #define meld_core_uses_config_hpp #include "boost/json.hpp" #include <type_traits> namespace meld { template <typename Module> concept with_config = std::is_constructible<Module, boost::json::object const&>(); template <typename Module> concept without_config = !with_config<Module>; } #endif /* meld_core_uses_config_hpp */
21.882353
84
0.771505
knoepfel
c31db249b93141973b4d3260d408ccc0caf31712
1,429
cpp
C++
USACO/training/chapter-1/barn1.cpp
eugli/competitive-programming
908b903da7f12333ecc4dd0491da3fad35d1db97
[ "MIT" ]
null
null
null
USACO/training/chapter-1/barn1.cpp
eugli/competitive-programming
908b903da7f12333ecc4dd0491da3fad35d1db97
[ "MIT" ]
null
null
null
USACO/training/chapter-1/barn1.cpp
eugli/competitive-programming
908b903da7f12333ecc4dd0491da3fad35d1db97
[ "MIT" ]
null
null
null
/* ID: lieugen1 TASK: barn1 LANG: C++ */ #include <bits/stdc++.h> using namespace std; int m, s, c, p; int occ[200]; void make_board() { int gap = 0, mgap = 0, sgap = 0, egap = 0; for (int i = 0; i < s; i++) { if (!occ[i]) { gap++; } else { if (gap > mgap) { mgap = gap; egap = i - 1; sgap = i - gap; } gap = 0; } } cout << mgap << " " << sgap << " " << egap; // if (gap > mgap) { // mgap = gap; // egap = s - 1; // sgap = s - gap + 1; // } for (int i = sgap; i <= egap; i++) { occ[i] = -1; } } int main() { ifstream fin("barn1.in"); ofstream fout("barn1.out"); fin >> m >> s >> c; for (int i = 0; i < c; i++) { fin >> p; occ[p - 1] = 1; } int b = 1; for (int i = 0; i < s; i++) { if (!occ[i]) { occ[i] = -1; } else { break; } } for (int i = s - 1; i >= 0; i--) { if (!occ[i]) { occ[i] = -1; } else { break; } } while (b < m) { make_board(); b++; } int ans = 0; for (int i = 0; i < s; i++) { cout << i + 1 << ": " << occ[i] << "\n"; if (occ[i] != -1) { ans++; } } fout << ans << "\n"; return 0; }
15.532609
48
0.313506
eugli
c324f75dc0d2f75a6024ca6f86abc7eddd471263
884
cpp
C++
Leetcode/reverse-vowels-of-a-string.cpp
omonimus1/angorithm_AND_dataStructure
2a6a0cda29cb618a787654b5c66ed6f43fe618e2
[ "Apache-2.0" ]
580
2020-04-08T16:47:36.000Z
2022-03-31T15:09:13.000Z
Leetcode/reverse-vowels-of-a-string.cpp
omonimus1/angorithm_AND_dataStructure
2a6a0cda29cb618a787654b5c66ed6f43fe618e2
[ "Apache-2.0" ]
3
2020-10-01T08:46:42.000Z
2020-11-23T17:12:35.000Z
Leetcode/reverse-vowels-of-a-string.cpp
omonimus1/angorithm_AND_dataStructure
2a6a0cda29cb618a787654b5c66ed6f43fe618e2
[ "Apache-2.0" ]
87
2020-06-07T16:30:08.000Z
2022-03-29T19:30:47.000Z
// https://leetcode.com/problems/reverse-vowels-of-a-string/submissions/ class Solution { public: char vowel_list[10] = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U' }; bool is_vowel(char letter) { for(int i =0; i < 10; i++) { if(letter == vowel_list[i]) return true; } return false; } string reverseVowels(string s) { int len = s.size(); string v = ""; for(int i=0; i < len; i++) { if(is_vowel(s[i])) v.push_back(s[i]); } reverse(v.begin(), v.end()); int j =0; for(int i =0; i < len; i++) { if(is_vowel(s[i])) { s[i] = v[j]; j++; } } return s; } };
22.1
78
0.357466
omonimus1
c32c6d629a4f6a4d30d81acbb59f683fd1c8c44a
7,467
cc
C++
value/parser.cc
eaugeas/crossroads
9dc1ea074a9bf59e4b6aa61ce75f93ee953ee05d
[ "MIT" ]
null
null
null
value/parser.cc
eaugeas/crossroads
9dc1ea074a9bf59e4b6aa61ce75f93ee953ee05d
[ "MIT" ]
null
null
null
value/parser.cc
eaugeas/crossroads
9dc1ea074a9bf59e4b6aa61ce75f93ee953ee05d
[ "MIT" ]
null
null
null
// Copyright (c) 2019, tlblanc <tlblanc1490 at gmail dot com> #include "parser.hpp" #include <errno.h> #include <string.h> #include <algorithm> #include "string_utils.hpp" static inline size_t _min_pos_len(size_t len1, size_t len2) { return len1 == 0 ? len2 : len2 == 0 ? len1 : std::min(len1, len2); } const char Parser::kString[] = "string"; const char Parser::kBool[] = "bool"; const char Parser::kInt32[] = "int32"; const char Parser::kInt64[] = "int64"; const char Parser::kUInt32[] = "uint32"; const char Parser::kUInt64[] = "uint64"; const char Parser::kDuration[] = "duration"; Parser Parser::string_parser(char *ptr, size_t len) noexcept { return Parser(ptr, len, true, parse_func_charray); } Parser Parser::string_parser(std::string *ptr) noexcept { return Parser(ptr, 0, true, parse_func_string); } Parser Parser::bool_parser(bool *ptr) noexcept { return Parser(ptr, 0, false, parse_func_bool); } Parser Parser::int32_parser(int32_t *ptr) noexcept { return Parser(ptr, 0, true, parse_func_int32); } Parser Parser::uint32_parser(uint32_t *ptr) noexcept { return Parser(ptr, 0, true, parse_func_uint32); } Parser Parser::int64_parser(int64_t *ptr) noexcept { return Parser(ptr, 0, true, parse_func_int64); } Parser Parser::uint64_parser(uint64_t *ptr) noexcept { return Parser(ptr, 0, true, parse_func_uint64); } Parser Parser::duration_parser( std::chrono::nanoseconds *ptr) noexcept { return Parser(ptr, 0, true, parse_func_duration); } bool parse_func_string(const char *s, size_t len, size_t maxlen, void *value) noexcept { return parse_string(static_cast<std::string*>(value), s, _min_pos_len(len, maxlen)); } bool parse_func_charray(const char *s, size_t len, size_t maxlen, void *value) noexcept { return parse_charray(static_cast<char*>(value), maxlen, s, len); } bool parse_func_bool(const char *s, size_t len, size_t maxlen, void *value) noexcept { return parse_bool(static_cast<bool*>(value), s, _min_pos_len(len, maxlen)); } bool parse_func_int32(const char *s, size_t len, size_t maxlen, void *value) noexcept { return parse_int32(static_cast<int32_t*>(value), s, _min_pos_len(len, maxlen)); } bool parse_func_int64(const char *s, size_t len, size_t maxlen, void *value) noexcept { return parse_int64(static_cast<int64_t*>(value), s, _min_pos_len(len, maxlen)); } bool parse_func_uint32(const char *s, size_t len, size_t maxlen, void *value) noexcept { return parse_uint32(static_cast<uint32_t*>(value), s, _min_pos_len(len, maxlen)); } bool parse_func_uint64(const char *s, size_t len, size_t maxlen, void *value) noexcept { return parse_uint64(static_cast<uint64_t*>(value), s, _min_pos_len(len, maxlen)); } bool parse_func_duration(const char *s, size_t len, size_t maxlen, void *value) noexcept { return parse_duration(static_cast<std::chrono::nanoseconds*>(value), s, _min_pos_len(len, maxlen)); } bool parse_bool(bool *value, const char *s, size_t len) noexcept { int64_t parsed; if (string_case_equals(s, len, "true", 4)) { *value = true; return true; } else if (string_case_equals(s, len, "false", 5)) { *value = false; return true; } else if (parse_int64(&parsed, s, len)) { *value = parsed != 0; return true; } else { return false; } } bool parse_int32(int32_t *value, const char *s, size_t len) noexcept { const char *endptr = nullptr; int64_t parsed = strntol(s, len, &endptr, 10); if (errno || (static_cast<size_t>(endptr - s + 1) < len && !isspace(*endptr))) { return false; } else if (parsed > INT32_MAX) { return false; } else if (parsed < INT32_MIN) { return false; } else { *value = static_cast<int32_t>(parsed); return true; } } bool parse_int64(int64_t *value, const char *s, size_t len) noexcept { const char *endptr = nullptr; int64_t parsed = strntol(s, len, &endptr, 10); if (errno || (static_cast<size_t>(endptr - s + 1) < len && !isspace(*endptr))) { return false; } else if (parsed > INT64_MAX) { return false; } else if (parsed < INT64_MIN) { return false; } else { *value = static_cast<int64_t>(parsed); return true; } } bool parse_uint32(uint32_t *value, const char *s, size_t len) noexcept { const char *endptr = nullptr; uint64_t parsed = strntoul(s, len, &endptr, 10); if (errno || (static_cast<size_t>(endptr - s + 1) < len && !isspace(*endptr))) { return false; } else if (parsed > UINT32_MAX) { return false; } else { *value = static_cast<int64_t>(parsed); return true; } } bool parse_uint64(uint64_t *value, const char *s, size_t len) noexcept { const char *endptr = nullptr; uint64_t parsed = strntoul(s, len, &endptr, 10); if (errno || (static_cast<size_t>(endptr - s + 1) < len && !isspace(*endptr))) { return false; } else if (parsed > UINT64_MAX) { return false; } else { *value = static_cast<int64_t>(parsed); return true; } } bool parse_duration(std::chrono::nanoseconds *value, const char *s, size_t len) noexcept { const char *endptr = nullptr; uint64_t parsed = strntoul(s, len, &endptr, 10); size_t pending = len - (endptr - s + 1); uint64_t factor = 0; if (errno) { return false; } else if (parsed > UINT64_MAX) { return false; } else { switch (*endptr) { case 'h': if (pending == 0) { factor = 3600 * (1e9); } else { return false; } break; case 'm': if (pending == 0) { factor = 60 * (1e9); } else if (pending == 1 && *(endptr + 1) == 's') { factor = 1e6; } else { return false; } break; case 's': if (pending == 0) { factor = 1e9; } else { return false; } break; case 'u': if (pending == 1 && *(endptr + 1) == 's') { factor = 1e3; } else { return false; } break; case 'n': if (pending == 1 && *(endptr + 1) == 's') { factor = 1; } else { return false; } break; default: return false; } *value = std::chrono::nanoseconds(parsed * factor); return true; } } bool parse_string(std::string *value, const char *s, size_t len) noexcept { value->assign(s, len); return true; } bool parse_charray(char *value, size_t maxlen, const char *s, size_t len) noexcept { if (len < maxlen) { memset(value, 0, maxlen); strncpy(value, s, len); return true; } else { return false; } }
24.807309
72
0.559127
eaugeas
c32e7a4e04324000c9a031ba3bcde1d4fbc7ab54
435
cpp
C++
gcd,lcm/9613.cpp
SiverPineValley/algo
29c75c6b226fdb15a3b6695e763ee49d4871094e
[ "Apache-2.0" ]
null
null
null
gcd,lcm/9613.cpp
SiverPineValley/algo
29c75c6b226fdb15a3b6695e763ee49d4871094e
[ "Apache-2.0" ]
null
null
null
gcd,lcm/9613.cpp
SiverPineValley/algo
29c75c6b226fdb15a3b6695e763ee49d4871094e
[ "Apache-2.0" ]
null
null
null
#include <iostream> using namespace std; int gcd(int a, int b) { int r; while( b != 0 ) { r = a%b; a = b; b = r; } return a; } int main(void) { int n, s; long long g = 0; cin >> n; for(int i = 0; i < n; i++) { cin >> s; int r[s]; for(int j = 0; j < s; j++) cin >> r[j]; for(int j = 0; j < s-1; j++) { for(int k = j+1; k < s; k++) g += gcd(r[j],r[k]); } cout << g << "\n"; g = 0; } return 0; }
12.083333
52
0.422989
SiverPineValley
c332fee3b43d02194dd596b3f9bb20a596982fe5
851
hpp
C++
OOP/function.hpp
shaneliu-zf/CodeBook
0c30e46f5661051d523c621eac9740d6dcbab440
[ "MIT" ]
3
2020-12-15T12:34:29.000Z
2020-12-15T21:21:33.000Z
OOP/function.hpp
shane-liu-1010/CodeBook
0c30e46f5661051d523c621eac9740d6dcbab440
[ "MIT" ]
null
null
null
OOP/function.hpp
shane-liu-1010/CodeBook
0c30e46f5661051d523c621eac9740d6dcbab440
[ "MIT" ]
null
null
null
#include<vector> class func:std::vector<double>{ public: func(int n=0){resize(n);} func(std::vector<double>a){ resize(a.size()); for(int i=0;i<a.size();i++)at(i)=a[i]; } void print(){ bool first=true; for(int i=size()-1;i>=0;i--){ if(at(i)){ std::cout<<((first)?(first=false,""):"+") <<at(i)<<((i>=1)?"x":""); if(i>1)std::cout<<"^"<<i; } } std::cout<<std::endl; } double setX(double x){ double ans=0; double t=1; for(int i=0;i<size();i++){ ans+=at(i)*t; t*=x; } return ans; } friend func prime(func a){ func b; for(int i=1;i<a.size();i++){ b.push_back(a[i]*i); } return b; } };
23
57
0.391304
shaneliu-zf
c3338047969da3290a6566f5ed93da22e1495e77
7,440
cpp
C++
tests/utils/test_sinc.cpp
ipc-sim/rigid-ipc
d839af457236e7363b14c2e482a01d8160fa447e
[ "MIT" ]
71
2021-09-08T13:16:43.000Z
2022-03-27T10:23:33.000Z
tests/utils/test_sinc.cpp
ipc-sim/rigid-ipc
d839af457236e7363b14c2e482a01d8160fa447e
[ "MIT" ]
4
2021-09-08T00:16:20.000Z
2022-01-05T17:44:08.000Z
tests/utils/test_sinc.cpp
ipc-sim/rigid-ipc
d839af457236e7363b14c2e482a01d8160fa447e
[ "MIT" ]
2
2021-09-18T15:15:38.000Z
2021-09-21T15:15:38.000Z
#include <catch2/catch.hpp> #include <iostream> #include <finitediff.hpp> #include <igl/PI.h> #include <autodiff/autodiff_types.hpp> #include <utils/sinc.hpp> using namespace ipc; using namespace ipc::rigid; TEST_CASE("double sinc", "[sinc][double]") { CHECK(sinc(0) == Approx(1)); CHECK(sinc(1e-8) == Approx(1)); CHECK(sinc(igl::PI / 2) == Approx(2 / igl::PI)); CHECK(sinc(igl::PI) == Approx(0).margin(1e-16)); } TEST_CASE("interval sinc", "[sinc][interval]") { // All of these cases fall within the monotonic bound on sinc, so they are // a tight bound (ignoring rounding). Interval x, expected_y; SECTION("y=[1, 1]") { SECTION("[0, 0]") { x = Interval(0); }; SECTION("[0, 1e-8]") { x = Interval(0, 1e-8); }; SECTION("[-1e-8, 0]") { x = Interval(-1e-8, 0); }; SECTION("[-1e-8, 1e-8]") { x = Interval(-1e-8, 1e-8); }; expected_y = Interval(1); } SECTION("y=[0, 1]") { SECTION("[0, π]") { x = Interval(0, igl::PI); } SECTION("[-π, 0]") { x = Interval(-igl::PI, 0); } SECTION("[-π, π]") { x = Interval(-igl::PI, igl::PI); } expected_y = Interval(0, 1); } SECTION("y=[2/pi, 1]") { double PI_2 = igl::PI / 2; SECTION("[0, π/2]") { x = Interval(0, PI_2); } SECTION("[-π/2, 0]") { x = Interval(-PI_2, 0); } SECTION("[-π/2, π/2]") { x = Interval(-PI_2, PI_2); } expected_y = Interval(2 / igl::PI, 1); } CAPTURE(x.lower(), x.upper()); Interval y = sinc(x); CHECK(y.lower() == Approx(expected_y.lower()).margin(1e-8)); CHECK(y.upper() == Approx(expected_y.upper()).margin(1e-8)); } TEST_CASE("interval sinc with looser bounds", "[sinc][interval]") { Interval x, expected_y; SECTION("Non-monotonic") { double a = GENERATE(-5, -1, 0); x = Interval(a, 5); expected_y = Interval(-0.217233628211, 1); } SECTION("Monotonic outside bounds") { x = Interval(5, 7); expected_y = Interval(sinc(5), sinc(7)); } SECTION("Monotonic far outside bounds") { x = Interval(21, 22); expected_y = Interval(sinc(22), sinc(21)); } Interval y = sinc(x); CAPTURE( x.lower(), x.upper(), y.lower(), y.upper(), expected_y.lower(), expected_y.upper()); CHECK(subset(expected_y, y)); // Lossest bound CHECK(subset(y, Interval(-0.23, 1))); if (x.lower() > 0) { // Tighter bound if x.lower() > 1 CHECK(subset(y, Interval(-1 / x.lower(), 1 / x.lower()))); } } TEST_CASE("interval sinc_normx", "[sinc][interval]") { VectorMax3<Interval> x = VectorMax3<Interval>::Zero(3); Interval expected_y; SECTION("Zero") { // x is already zero expected_y = Interval(1); } SECTION("Positive") { x(1) = Interval(igl::PI); expected_y = Interval(0); } SECTION("Negative") { x(1) = Interval(-igl::PI); expected_y = Interval(0); } SECTION("Mixed") { x(1) = Interval(-igl::PI, igl::PI); expected_y = Interval(0, 1); } Interval y = sinc_normx(x); CAPTURE(y.lower(), y.upper(), expected_y.lower(), expected_y.upper()); CHECK(expected_y.lower() == Approx(y.lower()).margin(1e-8)); CHECK(expected_y.upper() == Approx(y.upper()).margin(1e-8)); } TEST_CASE("∇sinc(||x||)", "[sinc][vector][diff]") { double sign = GENERATE(-1, 1); double val = GENERATE(0, 1e-8, igl::PI / 2, igl::PI, 5, 20, 100); int index = GENERATE(0, 1, 2); Eigen::Vector3d x = Eigen::Vector3d::Zero(); x(index) = sign * val; Eigen::VectorXd fgrad(3); fd::finite_gradient(x, sinc_normx<double>, fgrad); Eigen::Vector3d grad = sinc_normx_grad(x); CHECK(fd::compare_gradient(grad, fgrad)); } TEST_CASE("∇²sinc(||x||)", "[sinc][vector][diff]") { double sign = GENERATE(-1, 1); double val = GENERATE(0, 1e-8, igl::PI / 2, igl::PI, 5, 20, 100); int index = GENERATE(0, 1, 2); Eigen::Vector3d x = Eigen::Vector3d::Zero(); x(index) = sign * val; Eigen::MatrixXd fhess(3, 3); fd::finite_hessian(x, sinc_normx<double>, fhess); Eigen::Matrix3d hess = sinc_normx_hess(x); CHECK(fd::compare_hessian(hess, fhess)); } template <typename T> VectorX<T> identity(const VectorX<T>& x) { return x; } template <typename T> VectorX<T> square(const VectorX<T>& x) { return x.array().square(); } template <typename T> VectorX<T> const_sum(const VectorX<T>& x) { return VectorX<T>::Constant(x.size(), x.sum()); } template <typename T> VectorX<T> const_prod(const VectorX<T>& x) { return VectorX<T>::Constant(x.size(), x.prod()); } TEST_CASE("autodiff sinc(||x||)", "[sinc][vector][autodiff]") { typedef AutodiffType<Eigen::Dynamic> Diff; int size = GENERATE(3, 6, 12); Diff::activate(size); double sign = GENERATE(-1, 1); double val = GENERATE(0, 1e-8, igl::PI / 2, igl::PI, 5, 20, 100); int index = GENERATE(0, 1, 2); Eigen::VectorXd x = GENERATE_COPY(Eigen::VectorXd::Zero(size), Eigen::VectorXd::Ones(size)); x(size - 3 + index) = sign * val; std::function<Eigen::VectorXd(const Eigen::VectorXd&)> g; std::function<Diff::D1VectorXd(const Diff::D1VectorXd&)> g_autodiff1; std::function<Diff::D2VectorXd(const Diff::D2VectorXd&)> g_autodiff2; SECTION("No chain rule") { g = identity<double>; g_autodiff1 = identity<Diff::DDouble1>; g_autodiff2 = identity<Diff::DDouble2>; } SECTION("x->x^2") { g = square<double>; g_autodiff1 = square<Diff::DDouble1>; g_autodiff2 = square<Diff::DDouble2>; } SECTION("x->const(sum(x))") { g = const_sum<double>; g_autodiff1 = const_sum<Diff::DDouble1>; g_autodiff2 = const_sum<Diff::DDouble2>; } SECTION("x->const(prod(x))") { g = const_prod<double>; g_autodiff1 = const_prod<Diff::DDouble1>; g_autodiff2 = const_prod<Diff::DDouble2>; } // Compute the expected values double expected_value = sinc_normx(VectorMax3d(g(x).tail<3>())); Eigen::VectorXd fgrad(size); fd::finite_gradient( x, [&](const Eigen::VectorXd& x) { return sinc_normx(VectorMax3d(g(x).tail<3>())); }, fgrad); Eigen::MatrixXd fhess(size, size); fd::finite_hessian( x, [&](const Eigen::VectorXd& x) { return sinc_normx(VectorMax3d(g(x).tail<3>())); }, fhess); // Check the DScalar1 version { Diff::D1VectorXd x_diff = Diff::d1vars(0, x); Diff::DDouble1 y = sinc_normx( VectorMax3<Diff::DDouble1>(g_autodiff1(x_diff).tail<3>())); double value = y.getValue(); CHECK(value == Approx(expected_value)); Eigen::VectorXd grad = y.getGradient(); CHECK(fd::compare_gradient(grad, fgrad)); } // Check the DScalar2 version { Diff::D2VectorXd x_diff = Diff::d2vars(0, x); Diff::DDouble2 y = sinc_normx( VectorMax3<Diff::DDouble2>(g_autodiff2(x_diff).tail<3>())); double value = y.getValue(); CHECK(value == Approx(expected_value)); Eigen::VectorXd grad = y.getGradient(); CHECK(fd::compare_gradient(grad, fgrad)); Eigen::MatrixXd hess = y.getHessian(); CHECK(fd::compare_hessian(hess, fhess, 1e-2)); } }
28.949416
80
0.570565
ipc-sim
c33700a0fdb6262ac15974b8c76579924ea374bb
625
cpp
C++
Sorting_Searching/Sort_0_1_2.cpp
Twinkle0799/Competitive_Programming_Rocks
fb71021e02019004bef59ee1df86687234e36f5a
[ "MIT" ]
2
2021-05-06T17:59:44.000Z
2021-08-04T12:50:38.000Z
Sorting_Searching/Sort_0_1_2.cpp
Twinkle0799/Competitive_Programming_Rocks
fb71021e02019004bef59ee1df86687234e36f5a
[ "MIT" ]
1
2022-01-14T19:58:34.000Z
2022-01-14T19:58:34.000Z
Sorting_Searching/Sort_0_1_2.cpp
Twinkle0799/Competitive_Programming_Rocks
fb71021e02019004bef59ee1df86687234e36f5a
[ "MIT" ]
1
2021-02-17T09:48:06.000Z
2021-02-17T09:48:06.000Z
#include<bits/stdc++.h> using namespace std; void sort012(int a[], int n) { int low=0; int high = n-1; int mid=0; while(mid<=high) { switch(a[mid]) { case 0: swap(a[low++],a[mid++]); break; case 1: mid++; break; case 2: swap(a[mid],a[high--]); break; } } } int main() { int a[]={1,1,0,1,0,2,2,0}; int n =sizeof(a)/sizeof(a[0]); sort012(a,n); for(auto i:a) { cout<<i<<" "; } cout<<endl; }
16.891892
40
0.3584
Twinkle0799
c33c2f6fc17328e9cac8270e64e4fd60951f82fc
9,437
cpp
C++
uvccapturecontrols.cpp
erikmwerner/QUVCView
b3c659727a0afbfd2e95239cd8edfb9302011ae8
[ "BSD-3-Clause" ]
10
2020-02-24T05:37:10.000Z
2021-10-02T13:42:08.000Z
uvccapturecontrols.cpp
erikmwerner/QUVCView
b3c659727a0afbfd2e95239cd8edfb9302011ae8
[ "BSD-3-Clause" ]
2
2020-07-28T07:37:11.000Z
2021-06-25T07:15:04.000Z
uvccapturecontrols.cpp
erikmwerner/QUVCView
b3c659727a0afbfd2e95239cd8edfb9302011ae8
[ "BSD-3-Clause" ]
1
2020-12-02T12:17:18.000Z
2020-12-02T12:17:18.000Z
#include "uvccapturecontrols.h" #include "libuvc/libuvc.h" #include <QDebug> UVCCaptureControls::UVCCaptureControls(QObject* parent, uvc_device_handle_t **dev_handle) : QObject(parent), m_devh(dev_handle) {} void UVCCaptureControls::getExposureMode() { if(*m_devh == nullptr) {return;} uint8_t mode; uvc_error_t res = uvc_get_ae_mode(*m_devh, &mode, UVC_GET_CUR); if(res < UVC_SUCCESS) { qDebug()<<"Error gettings exposure mode"<<mode<<"Error:"<<res; } else { emit exposureMode(mode); } } void UVCCaptureControls::setExposureMode(int mode) { if(*m_devh == nullptr) {return;} uvc_error_t res = uvc_set_ae_mode(*m_devh, static_cast<uint8_t>(mode)); if(res < UVC_SUCCESS) { qDebug()<<"Error settings exposure mode"<<mode<<"Error:"<<res; } } void UVCCaptureControls::getAbsExposure() { if(*m_devh == nullptr) {return;} uint32_t value; uvc_error_t res = uvc_get_exposure_abs(*m_devh, &value, UVC_GET_CUR); if(res < UVC_SUCCESS) { qDebug()<<"Error getting abs exppsure"<<value<<"Error:"<<res; } else { emit exposure(value); } } void UVCCaptureControls::setAbsExposure(int exposure) { if(*m_devh == nullptr) {return;} uvc_error_t res = uvc_set_exposure_abs(*m_devh, static_cast<uint32_t>(exposure)); if(res < UVC_SUCCESS) { qDebug()<<"Error setting abs exppsure"<<exposure<<"Error:"<<res; } } void UVCCaptureControls::getFocusMode() { if(*m_devh == nullptr) {return;} uint8_t mode; uvc_error_t res = uvc_get_focus_auto(*m_devh, &mode, UVC_GET_CUR); if(res < UVC_SUCCESS) { qDebug()<<"Error getting focus mode"<<mode<<"Error:"<<res; } else { emit focusMode(mode); } } void UVCCaptureControls::setFocusMode(int mode) { if(*m_devh == nullptr) {return;} uvc_error_t res = uvc_set_focus_auto(*m_devh, static_cast<uint8_t>(mode)); if(res < UVC_SUCCESS) { qDebug()<<"Error setting focus mode"<<mode<<"Error:"<<res; } } void UVCCaptureControls::getAbsoluteFocus() { if(*m_devh == nullptr) {return;} uint16_t value; uvc_error_t res = uvc_get_focus_abs(*m_devh, &value, UVC_GET_CUR); if(res < UVC_SUCCESS) { qDebug()<<"Error getting absolute focus"<<value<<"Error:"<<res; } else { emit absoluteFocus(value); } } void UVCCaptureControls::setAbsoluteFocus(int focus) { uvc_error_t res = uvc_set_focus_abs(*m_devh, static_cast<uint16_t>(focus)); if(res < UVC_SUCCESS) { qDebug()<<"Error setting absolute focus"<<focus<<"Error:"<<res; } } void UVCCaptureControls::getBackLightCompensation() { if(*m_devh == nullptr) {return;} uint16_t value; uvc_error_t res = uvc_get_backlight_compensation(*m_devh, &value, UVC_GET_CUR); if(res < UVC_SUCCESS) { qDebug()<<"Error getting backlight compensation"<<value<<"Error:"<<res; } else { emit backlightCompensation(value); } } void UVCCaptureControls::setBackLightCompensation(int compensation) { if(*m_devh == nullptr) {return;} uvc_error_t res = uvc_set_backlight_compensation(*m_devh, static_cast<uint16_t>(compensation)); if(res < UVC_SUCCESS) { qDebug()<<"Error setting backlight compensation"<<compensation<<"Error:"<<res; } } void UVCCaptureControls::getBrightness() { if(*m_devh == nullptr) {return;} int16_t value; uvc_error_t res = uvc_get_brightness(*m_devh, &value, UVC_GET_CUR); if(res < UVC_SUCCESS) { qDebug()<<"Error getting brightness"<<value<<"Error:"<<res; } else { emit brightness(value); } } void UVCCaptureControls::setBrightness(int brightness) { if(*m_devh == nullptr) {return;} uvc_error_t res = uvc_set_brightness(*m_devh, static_cast<int16_t>(brightness)); if(res < UVC_SUCCESS) { qDebug()<<"Error setting brightness"<<brightness<<"Error:"<<res; } } void UVCCaptureControls::getContrastMode() { if(*m_devh == nullptr) {return;} uint8_t mode; uvc_error_t res = uvc_get_contrast_auto(*m_devh, &mode, UVC_GET_CUR); if(res < UVC_SUCCESS) { qDebug()<<"Error getting contrast mode"<<mode<<"Error:"<<res; } else { emit contrastMode(mode); } } void UVCCaptureControls::setContrastMode(int mode) { if(*m_devh == nullptr) {return;} uvc_error_t res = uvc_set_contrast_auto(*m_devh, static_cast<uint8_t>(mode)); if(res < UVC_SUCCESS) { qDebug()<<"Error setting contrast mode"<<mode<<"Error:"<<res; } } void UVCCaptureControls::getContrast() { if(*m_devh == nullptr) {return;} uint16_t value; uvc_error_t res = uvc_get_contrast(*m_devh, &value, UVC_GET_CUR); if(res < UVC_SUCCESS) { qDebug()<<"Error getting contrast"<<value<<"Error:"<<res; } else { emit contrast(value); } } void UVCCaptureControls::setContrast(int contrast) { if(*m_devh == nullptr) {return;} uvc_error_t res = uvc_set_contrast(*m_devh, static_cast<uint16_t>(contrast)); if(res < UVC_SUCCESS) { qDebug()<<"Error setting contrast mode"<<contrast<<"Error:"<<res; } } void UVCCaptureControls::getHueMode() { if(*m_devh == nullptr) {return;} uint8_t mode; uvc_error_t res = uvc_get_hue_auto(*m_devh, &mode, UVC_GET_CUR); if(res < UVC_SUCCESS) { qDebug()<<"Error getting hue mode"<<mode<<"Error:"<<res; } else { emit hueMode(mode); } } void UVCCaptureControls::setHueMode(int mode) { if(*m_devh == nullptr) {return;} uvc_error_t res = uvc_set_hue_auto(*m_devh, static_cast<uint8_t>(mode)); if(res < UVC_SUCCESS) { qDebug()<<"Error setting hue mode"<<mode<<"Error:"<<res; } } void UVCCaptureControls::getHue() { if(*m_devh == nullptr) {return;} int16_t value; uvc_error_t res = uvc_get_hue(*m_devh, &value, UVC_GET_CUR); if(res < UVC_SUCCESS) { qDebug()<<"Error getting contrast"<<value<<"Error:"<<res; } else { emit hue(value); } } void UVCCaptureControls::setHue(int hue) { if(*m_devh == nullptr) {return;} uvc_error_t res = uvc_set_hue(*m_devh, static_cast<int16_t>(hue)); if(res < UVC_SUCCESS) { qDebug()<<"Error setting hue mode"<<hue<<"Error:"<<res; } } void UVCCaptureControls::getSaturation() { if(*m_devh == nullptr) {return;} uint16_t value; uvc_error_t res = uvc_get_saturation(*m_devh, &value, UVC_GET_CUR); if(res < UVC_SUCCESS) { qDebug()<<"Error getting saturation"<<value<<"Error:"<<res; } else { emit saturation(value); } } void UVCCaptureControls::setSaturation(int saturation) { if(*m_devh == nullptr) {return;} uvc_error_t res = uvc_set_saturation(*m_devh, static_cast<uint16_t>(saturation)); if(res < UVC_SUCCESS) { qDebug()<<"Error setting saturation mode"<<saturation<<"Error:"<<res; } } void UVCCaptureControls::getSharpness() { if(*m_devh == nullptr) {return;} uint16_t value; uvc_error_t res = uvc_get_sharpness(*m_devh, &value, UVC_GET_CUR); if(res < UVC_SUCCESS) { qDebug()<<"Error getting sharpness"<<value<<"Error:"<<res; } else { emit sharpness(value); } } void UVCCaptureControls::setSharpness(int sharpness) { if(*m_devh == nullptr) {return;} uvc_error_t res = uvc_set_sharpness(*m_devh, static_cast<uint16_t>(sharpness)); if(res < UVC_SUCCESS) { qDebug()<<"Error setting sharpness"<<sharpness<<"Error:"<<res; } } void UVCCaptureControls::getGamma() { if(*m_devh == nullptr) {return;} uint16_t value; uvc_error_t res = uvc_get_gamma(*m_devh, &value, UVC_GET_CUR); if(res < UVC_SUCCESS) { qDebug()<<"Error getting gamma"<<value<<"Error:"<<res; } else { emit gamma(value); } } void UVCCaptureControls::setGamma(int gamma) { if(*m_devh == nullptr) {return;} uvc_error_t res = uvc_set_gamma(*m_devh, static_cast<uint16_t>(gamma)); if(res < UVC_SUCCESS) { qDebug()<<"Error setting gama"<<gamma<<"Error:"<<res; } } void UVCCaptureControls::getWhiteBalanceMode() { if(*m_devh == nullptr) {return;} uint8_t mode; uvc_error_t res = uvc_get_white_balance_temperature_auto(*m_devh, &mode, UVC_GET_CUR); if(res < UVC_SUCCESS) { qDebug()<<"Error getting white balance mode"<<mode<<"Error:"<<res; } else { emit whiteBalanceMode(mode); } } void UVCCaptureControls::setWhiteBalanceMode(int mode) { if(*m_devh == nullptr) {return;} uvc_error_t res = uvc_set_white_balance_temperature(*m_devh, static_cast<uint8_t>(mode)); if(res < UVC_SUCCESS) { qDebug()<<"Error setting white balance mode"<<mode<<"Error:"<<res; } } void UVCCaptureControls::getWhiteBalanceTemperature() { if(*m_devh == nullptr) {return;} uint16_t value; uvc_error_t res = uvc_get_white_balance_temperature(*m_devh, &value, UVC_GET_CUR); if(res < UVC_SUCCESS) { qDebug()<<"Error getting white balance temperature"<<value<<"Error:"<<res; } else { emit whiteBalanceTemperature(value); } } void UVCCaptureControls::setWhiteBalanceTemperature(int temperature) { if(*m_devh == nullptr) {return;} uvc_error_t res = uvc_set_white_balance_temperature(*m_devh, static_cast<uint16_t>(temperature)); if(res < UVC_SUCCESS) { qDebug()<<"Error setting white balance temperature"<<temperature<<"Error:"<<res; } }
27.920118
101
0.651266
erikmwerner
c33ee2c4194a6a8e2ea83e874644bf5a6890cd06
226
cpp
C++
Game Engine 2D/UtilConstants.cpp
LaPeste/ComposeEngine
8ae80ec7c49af896978d06371dee96a4d2315372
[ "Apache-2.0" ]
1
2017-03-13T11:19:40.000Z
2017-03-13T11:19:40.000Z
Game Engine 2D/UtilConstants.cpp
LaPeste/ComposeEngine
8ae80ec7c49af896978d06371dee96a4d2315372
[ "Apache-2.0" ]
null
null
null
Game Engine 2D/UtilConstants.cpp
LaPeste/ComposeEngine
8ae80ec7c49af896978d06371dee96a4d2315372
[ "Apache-2.0" ]
null
null
null
// // UtilConstants.cpp // GameEngine2D // // Created by Andrea Catalini on 11/12/16. // Copyright © 2016 Andrea Catalini. All rights reserved. // #include "UtilConstants.hpp" const int UtilConstants::NO_COMPONENTS = 0;
18.833333
58
0.712389
LaPeste
c3487fd4faaeddb105a642f8f947a2acf2379a2e
8,984
cc
C++
src/solv_smurf/fn_smurf_au/bdd2smurf_au.cc
nerdling/SBSAT
6328c6aa105b75693d06bf0dae4a3b5ca220318b
[ "Unlicense" ]
4
2015-03-08T07:56:29.000Z
2017-10-12T04:19:27.000Z
src/solv_smurf/fn_smurf_au/bdd2smurf_au.cc
nerdling/SBSAT
6328c6aa105b75693d06bf0dae4a3b5ca220318b
[ "Unlicense" ]
null
null
null
src/solv_smurf/fn_smurf_au/bdd2smurf_au.cc
nerdling/SBSAT
6328c6aa105b75693d06bf0dae4a3b5ca220318b
[ "Unlicense" ]
null
null
null
/* =========FOR INTERNAL USE ONLY. NO DISTRIBUTION PLEASE ========== */ /********************************************************************* Copyright 1999-2007, University of Cincinnati. All rights reserved. By using this software the USER indicates that he or she has read, understood and will comply with the following: --- University of Cincinnati hereby grants USER nonexclusive permission to use, copy and/or modify this software for internal, noncommercial, research purposes only. Any distribution, including commercial sale or license, of this software, copies of the software, its associated documentation and/or modifications of either is strictly prohibited without the prior consent of University of Cincinnati. Title to copyright to this software and its associated documentation shall at all times remain with University of Cincinnati. Appropriate copyright notice shall be placed on all software copies, and a complete copy of this notice shall be included in all copies of the associated documentation. No right is granted to use in advertising, publicity or otherwise any trademark, service mark, or the name of University of Cincinnati. --- This software and any associated documentation is provided "as is" UNIVERSITY OF CINCINNATI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, INCLUDING THOSE OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, OR THAT USE OF THE SOFTWARE, MODIFICATIONS, OR ASSOCIATED DOCUMENTATION WILL NOT INFRINGE ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER INTELLECTUAL PROPERTY RIGHTS OF A THIRD PARTY. University of Cincinnati shall not be liable under any circumstances for any direct, indirect, special, incidental, or consequential damages with respect to any claim by USER or any third party on account of or arising from the use, or inability to use, this software or its associated documentation, even if University of Cincinnati has been advised of the possibility of those damages. *********************************************************************/ #include "sbsat.h" #include "sbsat_solver.h" #include "solver.h" // External variables. long gnTotalBytesForTransitionAus = 0; ITE_INLINE TransitionAu * CreateTransitionAu(SmurfAuState *pSmurfAuState, int i, int nSolverVble, int value, int nAutarkyVble) { int nVble = arrSolver2IteVarMap[nSolverVble]; // Compute transition that occurs when vble is set to true. BDDNodeStruct *pFuncEvaled; //If we are transitioning on the autarky variable, we send the smurf to the true state. //fprintf(stderr, "creating transition on %d(%d)=%d with autarkyvble %d\n", nVble, nSolverVble, value, nAutarkyVble); if(nSolverVble == nAutarkyVble) pFuncEvaled = true_ptr; else pFuncEvaled = set_variable(pSmurfAuState->pFunc, nVble, value==BOOL_TRUE?1:0); if(pFuncEvaled == false_ptr) //set the autarky variable to true pFuncEvaled = ite_var(-arrSolver2IteVarMap[nAutarkyVble]); SmurfAuState *pSmurfAuStateOfEvaled = BDD2SmurfAu(pFuncEvaled, nAutarkyVble); assert(pSmurfAuStateOfEvaled != NULL); AddStateTransitionAu(pSmurfAuState, i, nSolverVble, value, nAutarkyVble, pFuncEvaled, pSmurfAuStateOfEvaled); //This is just a validity check of the newly created transition. TransitionAu *transition = FindTransitionAu(pSmurfAuState, i, nSolverVble, value, nAutarkyVble); assert(transition->pNextState != NULL); return transition; } ITE_INLINE SmurfAuState * ComputeSmurfAuOfNormalized(BDDNodeStruct *pFunc, int nAutarkyVble) // Precondition: *pFunc is 'normalized', i.e., no literal // is logically implied by *pFunc. // Creates SmurfAu states to represent the function and its children. // Autarky smurfs currently give no heurstic value. // This may change in the future. { assert(pFunc != false_ptr); ite_counters[SMURF_AU_NODE_FIND]++; // Collapse 'true' SmurfAu states. if (pFunc == true_ptr) return pTrueSmurfAuState; //if (pFunc->pState_Au) return (SmurfAuState*)(pFunc->pState_Au); SmurfAuState *pSmurfAuState = AllocateSmurfAuState(); ite_counters[SMURF_AU_NODE_NEW]++; pSmurfAuState->pFunc = pFunc; //pFunc->pState_Au = (void*)pSmurfAuState; // get all the variables int tempint_max = 0; int y=0; unravelBDD(&y, &tempint_max, &pSmurfAuState->vbles.arrElts, pFunc); pSmurfAuState->vbles.nNumElts = y; pSmurfAuState->vbles.arrElts = (int*)realloc(pSmurfAuState->vbles.arrElts, pSmurfAuState->vbles.nNumElts*sizeof(int)); /* mapping ite->solver variables */ int nAuVarIndex = -1; for (int i=0;i<pSmurfAuState->vbles.nNumElts;i++) { if (pSmurfAuState->vbles.arrElts[i]==0 || arrIte2SolverVarMap[pSmurfAuState->vbles.arrElts[i]]==0) { dX_printf(0, "\nassigned variable in an Autarky BDD in the solver"); dX_printf(0, "\nvariable id: %d, true_false=%d\n", pSmurfAuState->vbles.arrElts[i], variablelist[pSmurfAuState->vbles.arrElts[i]].true_false); //exit(1); } if(arrIte2SolverVarMap[pSmurfAuState->vbles.arrElts[i]] == nAutarkyVble) nAuVarIndex = i; pSmurfAuState->vbles.arrElts[i] = arrIte2SolverVarMap[pSmurfAuState->vbles.arrElts[i]]; } assert(nAuVarIndex!=-1); //Put the autarky variable at the front of the list, so it will be transitioned on first //when looking for inferences if(nAuVarIndex!=0) { int nSwap_Index = 0; int nSwapLit = pSmurfAuState->vbles.arrElts[nSwap_Index]; pSmurfAuState->vbles.arrElts[nSwap_Index] = pSmurfAuState->vbles.arrElts[nAuVarIndex]; pSmurfAuState->vbles.arrElts[nAuVarIndex] = nSwapLit; } assert(pSmurfAuState->vbles.arrElts[0] = nAutarkyVble); //Sort the variables. //qsort(pSmurfAuState->vbles.arrElts, pSmurfAuState->vbles.nNumElts, sizeof(int), revcompfunc); /* allocate transitions */ int nBytesForTransitionAus = pSmurfAuState->vbles.nNumElts * 2 * sizeof (TransitionAu); pSmurfAuState->arrTransitionAus = (TransitionAu *)ite_calloc(pSmurfAuState->vbles.nNumElts * 2, sizeof (TransitionAu), 9, "pSmurfAuState->arrTransitionAus"); gnTotalBytesForTransitionAus += nBytesForTransitionAus; /* for(int i=0;i<pSmurfAuState->vbles.nNumElts;i++) { int nSolverVble = pSmurfAuState->vbles.arrElts[i]; // Compute transition that occurs when vble is set to true. CreateTransitionAu(pSmurfAuState, i, nSolverVble, BOOL_TRUE, nAutarkyVble); // Compute transition that occurs when vble is set to false. CreateTransitionAu(pSmurfAuState, i, nSolverVble, BOOL_FALSE, nAutarkyVble); } */ return pSmurfAuState; } ITE_INLINE SmurfAuState * BDD2SmurfAu(BDDNodeStruct *pFunc, int nAutarkyVble) // Constructs a SmurfAu representation for the constraint *pFunc. // Returns 0 if constraint pointed to by pFunc is unsatisfiable. // Otherwise, returns a pointer to the initial SmurfAu state. { // special autarky function -- represent with autarky state machine. //BDDNodeStruct *pReduct = set_variable_all_infs(pFunc); //There should never be an inference except on the autarky variable. //If this function has an inference, it must be the autarky variable. //A transition on the autarky variable sends the smurf to the true state. //if(pReduct != pFunc) pReduct = true_ptr; //return ComputeSmurfAuOfNormalized(pReduct, nAutarkyVble); return ComputeSmurfAuOfNormalized(pFunc, nAutarkyVble); } int SmurfAuCreateFunction(int nFnId, BDDNode *bdd, int nFnType, int eqVble) { arrSolverFunctions[nFnId].nFnId = nFnId; arrSolverFunctions[nFnId].nType = nFnType; arrSolverFunctions[nFnId].nFnPriority = MAX_FN_PRIORITY-1; arrSolverFunctions[nFnId].fn_smurf_au.nSmurfAuEqualityVble = arrIte2SolverVarMap[abs(eqVble)]; arrSolverFunctions[nFnId].fn_smurf_au.pInitialState = BDD2SmurfAu(bdd, arrIte2SolverVarMap[abs(eqVble)]); assert(arrSolverFunctions[nFnId].fn_smurf_au.pInitialState != pTrueSmurfAuState); if (arrSolverFunctions[nFnId].fn_smurf_au.pInitialState == pTrueSmurfAuState) { nNumUnresolvedFunctions--; d9_printf3("Decremented nNumUnresolvedFunctions to %d due to autarky smurf # %d\n", nNumUnresolvedFunctions, nFnId); } arrSolverFunctions[nFnId].fn_smurf_au.pPrevState = arrSolverFunctions[nFnId].fn_smurf_au.pCurrentState = arrSolverFunctions[nFnId].fn_smurf_au.pInitialState; arrSolverFunctions[nFnId].fn_smurf_au.arrSmurfAuPath.literals = (int*)ite_calloc(arrSolverFunctions[nFnId].fn_smurf_au.pInitialState->vbles.nNumElts+1, sizeof(int), 9, "arrSmurfAuPath[].literals"); return 0; } void SmurfAuAffectedVarList(int nFnId, int **arr1, int *num1, int **arr2, int *num2) { *num1 = arrSolverFunctions[nFnId].fn_smurf_au.pInitialState->vbles.nNumElts; *arr1 = arrSolverFunctions[nFnId].fn_smurf_au.pInitialState->vbles.arrElts; *num2 = 0; } void SmurfAuCreateAFS(int nFnId, int nVarId, int nAFSIndex) { arrAFS[nVarId].arrOneAFS[nAFSIndex].nFnId = nFnId; arrAFS[nVarId].arrOneAFS[nAFSIndex].nType = AUTARKY_FUNC; }
43.61165
167
0.743099
nerdling
c34b3a25a9c836684578ca95676ad633f260ca7a
472
cpp
C++
0-1 Knapsack.cpp
abhis2007/Algorithms-1
7637209c5aa52c1afd8be1884d018673d26f5c1f
[ "MIT" ]
26
2019-04-05T07:10:15.000Z
2022-01-08T02:35:19.000Z
0-1 Knapsack.cpp
abhis2007/Algorithms-1
7637209c5aa52c1afd8be1884d018673d26f5c1f
[ "MIT" ]
2
2019-04-25T15:47:54.000Z
2019-09-03T06:46:05.000Z
0-1 Knapsack.cpp
abhis2007/Algorithms-1
7637209c5aa52c1afd8be1884d018673d26f5c1f
[ "MIT" ]
8
2019-04-05T08:58:50.000Z
2020-07-03T01:53:58.000Z
int knapSack(int W,int wt[],int val[],int n){ int dp[n+1][W+1]; rep(i,0,n+1){ rep(j,0,W+1){ if(i==0||j==0) dp[i][j]=0; else if(wt[i-1] <= j)dp[i][j]=max(val[i-1] + dp[i-1][j-wt[i-1]], dp[i-1][j]); else dp[i][j] = dp[i-1][j]; } } return dp[n][W]; } int main() { IOS; int val[] = {7,5,2,1,3,4}; int wt[] = {10,2,4,5,1,3}; int W = 10; int n = sizeof(val)/sizeof(val[0]); printf("%d\n", knapSack(W, wt, val, n)); return 0; }
19.666667
81
0.459746
abhis2007
c34c1e76dc8f695f198f6e58a19f7c7fbb87f247
26,175
hpp
C++
client/systems/common.hpp
Exonical/Vanguard_Wasteland.cup_chernarus_A3
ee8f51807847f35c924bb8bf701e863387b603b8
[ "MIT" ]
1
2020-07-23T13:49:05.000Z
2020-07-23T13:49:05.000Z
client/systems/common.hpp
Exonical/Vanguard_Wasteland.cup_chernarus_A3
ee8f51807847f35c924bb8bf701e863387b603b8
[ "MIT" ]
null
null
null
client/systems/common.hpp
Exonical/Vanguard_Wasteland.cup_chernarus_A3
ee8f51807847f35c924bb8bf701e863387b603b8
[ "MIT" ]
null
null
null
// ****************************************************************************************** // * This project is licensed under the GNU Affero GPL v3. Copyright © 2014 A3Wasteland.com * // ****************************************************************************************** /* @file Version: 1.0 @file Name: common.hpp @file Author: [404] Deadbeat @file Created: 11/09/2012 04:23 @file Args: */ #define CT_STATIC 0 #define CT_BUTTON 1 #define CT_EDIT 2 #define CT_SLIDER 3 #define CT_COMBO 4 #define CT_LISTBOX 5 #define CT_TOOLBOX 6 #define CT_CHECKBOXES 7 #define CT_PROGRESS 8 #define CT_HTML 9 #define CT_STATIC_SKEW 10 #define CT_ACTIVETEXT 11 #define CT_TREE 12 #define CT_STRUCTURED_TEXT 13 #define CT_CONTEXT_MENU 14 #define CT_CONTROLS_GROUP 15 #define CT_SHORTCUT_BUTTON 16 // Arma 2 - textured button #define CT_XKEYDESC 40 #define CT_XBUTTON 41 #define CT_XLISTBOX 42 #define CT_XSLIDER 43 #define CT_XCOMBO 44 #define CT_ANIMATED_TEXTURE 45 #define CT_CHECKBOX 77 #define CT_OBJECT 80 #define CT_OBJECT_ZOOM 81 #define CT_OBJECT_CONTAINER 82 #define CT_OBJECT_CONT_ANIM 83 #define CT_LINEBREAK 98 #define CT_USER 99 #define CT_MAP 100 #define CT_MAP_MAIN 101 #define CT_List_N_Box 102 // Arma 2 - N columns list box // Static styles #define ST_POS 0x0F #define ST_HPOS 0x03 #define ST_VPOS 0x0C #define ST_LEFT 0x00 #define ST_RIGHT 0x01 #define ST_CENTER 0x02 #define ST_DOWN 0x04 #define ST_UP 0x08 #define ST_VCENTER 0x0c #define ST_TYPE 0xF0 #define ST_SINGLE 0 #define ST_MULTI 16 #define ST_TITLE_BAR 32 #define ST_PICTURE 48 #define ST_FRAME 64 #define ST_BACKGROUND 80 #define ST_GROUP_BOX 96 #define ST_GROUP_BOX2 112 #define ST_HUD_BACKGROUND 128 #define ST_TILE_PICTURE 144 #define ST_WITH_RECT 160 #define ST_LINE 176 #define ST_SHADOW 0x100 #define ST_NO_RECT 0x200 #define ST_KEEP_ASPECT_RATIO 0x800 #define ST_TITLE ST_TITLE_BAR + ST_CENTER // Slider styles #define SL_DIR 0x400 #define SL_VERT 0 #define SL_HORZ 0x400 #define SL_TEXTURES 0x10 // Listbox styles #define LB_TEXTURES 0x10 #define LB_MULTI 0x20 #define true 1 #define false 1 class w_RscText { idc = -1; type = CT_STATIC; style = ST_LEFT; colorBackground[] = { 1 , 1 , 1 , 0 }; colorText[] = { 1 , 1 , 1 , 1 }; font = "PuristaMedium"; sizeEx = 0.025; h = 0.25; text = ""; tooltipColorText[] = {1, 1, 1, 1}; tooltipColorBox[] = {1, 1, 1, 1}; tooltipColorShade[] = {0, 0, 0, 0.65}; }; class w_RscTextCenter : w_RscText { style = ST_CENTER; }; class w_RscStructuredText { access = 0; type = 13; idc = -1; style = 0; colorText[] = { 1 , 1 , 1 , 1 }; class Attributes { font = "PuristaMedium"; //color = "#e0d8a6"; align = "center"; shadow = 0; }; x = 0; y = 0; h = 0.035; w = 0.1; text = ""; size = 0.03921; shadow = 2; tooltipColorText[] = {1, 1, 1, 1}; tooltipColorBox[] = {1, 1, 1, 1}; tooltipColorShade[] = {0, 0, 0, 0.65}; }; class w_RscStructuredTextLeft { access = 0; type = 13; idc = -1; style = 0; colorText[] = { 1 , 1 , 1 , 1 }; class Attributes { font = "PuristaMedium"; //color = "#e0d8a6"; align = "left"; shadow = 0; }; x = 0; y = 0; h = 0.035; w = 0.1; text = ""; size = 0.03921; shadow = 2; tooltipColorText[] = {1, 1, 1, 1}; tooltipColorBox[] = {1, 1, 1, 1}; tooltipColorShade[] = {0, 0, 0, 0.65}; }; class w_RscBackground { colorBackground[] = {0.14, 0.18, 0.13, 0.8}; text = ""; type = CT_STATIC; idc = -1; style = ST_LEFT; colorText[] = {1, 1, 1, 1}; font = "PuristaMedium"; sizeEx = 0.04; tooltipColorText[] = {1, 1, 1, 1}; tooltipColorBox[] = {1, 1, 1, 1}; tooltipColorShade[] = {0, 0, 0, 0.65}; }; class w_RscEdit { idc = -1; type = CT_EDIT; style = ST_LEFT; x = 0; y = 0; w = .2; h = .4; sizeEx = .02; font = "PuristaMedium"; text = ""; colorText[] = {1,1,1,1}; autocomplete = false; colorSelection[] = {0,0,0,1}; tooltipColorText[] = {1, 1, 1, 1}; tooltipColorBox[] = {1, 1, 1, 1}; tooltipColorShade[] = {0, 0, 0, 0.65}; }; class w_RscListBox { idc = -1; type = CT_LISTBOX; style = ST_MULTI; w = 0.4; h = 0.4; rowHeight = 0; colorText[] = {1, 1, 1, 1}; colorDisabled[] = {1, 1, 1, 0.25}; colorScrollbar[] = {1, 0, 0, 0}; colorSelect[] = {0, 0, 0, 1}; // primary colorSelect2[] = {0, 0, 0, 1}; // blink colorSelectBackground[] = {0.95, 0.95, 0.95, 1}; // primary colorSelectBackground2[] = {1, 1, 1, 0.5}; // blink colorBackground[] = {0, 0, 0, 0.3}; soundSelect[] = {"\A3\ui_f\data\sound\RscListbox\soundSelect", 0.09, 1}; autoScrollSpeed = -1; autoScrollDelay = 5; autoScrollRewind = 0; arrowEmpty = "#(argb,8,8,3)color(1,1,1,1)"; arrowFull = "#(argb,8,8,3)color(1,1,1,1)"; colorPicture[] = {1, 1, 1, 1}; colorPictureSelected[] = {1, 1, 1, 1}; colorPictureDisabled[] = {1, 1, 1, 0.25}; tooltipColorText[] = {1, 1, 1, 1}; tooltipColorBox[] = {1, 1, 1, 1}; tooltipColorShade[] = {0, 0, 0, 0.65}; font = "PuristaMedium"; sizeEx = 0.035; shadow = 0; colorShadow[] = {0, 0, 0, 0.5}; period = 0.75; // blink period maxHistoryDelay = 1; class ListScrollBar { color[] = {1, 1, 1, 1}; colorActive[] = {1, 1, 1, 1}; colorDisabled[] = {1, 1, 1, 0.3}; thumb = "\A3\ui_f\data\gui\cfg\scrollbar\thumb_ca.paa"; arrowFull = "\A3\ui_f\data\gui\cfg\scrollbar\arrowFull_ca.paa"; arrowEmpty = "\A3\ui_f\data\gui\cfg\scrollbar\arrowEmpty_ca.paa"; border = "\A3\ui_f\data\gui\cfg\scrollbar\border_ca.paa"; }; }; class w_RscList: w_RscListBox {}; class w_RscPicture { idc = -1; type = CT_STATIC; style = ST_PICTURE; font = "PuristaMedium"; sizeEx = 0.023; colorBackground[] = {}; colorText[] = {}; x = 0.0; y = 0.2; w = 0.2; h = 0.2; text = ""; tooltipColorText[] = {1, 1, 1, 1}; tooltipColorBox[] = {1, 1, 1, 1}; tooltipColorShade[] = {0, 0, 0, 0.65}; }; class w_RscButtonBase { idc = -1; type = 16; style = 0; w = 0.183825; h = 0.104575; color[] = {0.95, 0.95, 0.95, 1}; color2[] = {1, 1, 1, 0.4}; colorBackground[] = {0.75, 0.75, 0.75, 0.8}; colorbackground2[] = {1, 1, 1, 0.4}; colorDisabled[] = {1, 1, 1, 0.25}; periodFocus = 1.2; periodOver = 0.8; class HitZone { left = 0.004; top = 0.029; right = 0.004; bottom = 0.029; }; class ShortcutPos { left = 0.004; top = 0.026; w = 0.0392157; h = 0.0522876; }; class TextPos { left = 0.05; top = 0.025; right = 0.005; bottom = 0.025; }; animTextureDefault = "\A3\ui_f\data\GUI\RscCommon\RscShortcutButton\normal_ca.paa"; animTextureNormal = "\A3\ui_f\data\GUI\RscCommon\RscShortcutButton\normal_ca.paa"; animTextureDisabled = "\A3\ui_f\data\GUI\RscCommon\RscShortcutButton\normal_ca.paa"; animTextureOver = "\A3\ui_f\data\GUI\RscCommon\RscShortcutButton\over_ca.paa"; animTextureFocused = "\A3\ui_f\data\GUI\RscCommon\RscShortcutButton\focus_ca.paa"; animTexturePressed = "\A3\ui_f\data\GUI\RscCommon\RscShortcutButton\down_ca.paa"; textureNoShortcut = ""; period = 0.4; font = "PuristaMedium"; size = 0.023; sizeEx = 0.023; text = ""; soundEnter[] = {"\A3\ui_f\data\sound\RscButton\soundEnter", 0.09, 1}; soundPush[] = {"\A3\ui_f\data\sound\RscButton\soundPush", 0.09, 1}; soundClick[] = {"\A3\ui_f\data\sound\RscButton\soundClick", 0.09, 1}; soundEscape[] = {"\A3\ui_f\data\sound\RscButton\soundEscape", 0.09, 1}; action = ""; class Attributes { font = "PuristaMedium"; color = "#E5E5E5"; align = "left"; shadow = false; }; class AttributesImage { font = "PuristaMedium"; color = "#E5E5E5"; align = "left"; }; tooltipColorText[] = {1, 1, 1, 1}; tooltipColorBox[] = {1, 1, 1, 1}; tooltipColorShade[] = {0, 0, 0, 0.65}; }; class w_RscButton { access = 0; type = CT_BUTTON; text = ""; colorText[] = {1,1,1,.9}; colorDisabled[] = {0,0,0,1}; colorBackground[] = {A3W_UICOLOR_R * 0.8, A3W_UICOLOR_G * 0.8, A3W_UICOLOR_B * 0.8, 1}; // normal colorFocused[] = {A3W_UICOLOR_R * 0.55, A3W_UICOLOR_G * 0.55, A3W_UICOLOR_B * 0.55, 1}; // pulse colorBackgroundActive[] = {A3W_UICOLOR_R, A3W_UICOLOR_G, A3W_UICOLOR_B, 1}; // hover colorBackgroundDisabled[] = {0.3,0.3,0.3,1}; colorShadow[] = {0,0,0,1}; colorBorder[] = {0,0,0,1}; soundEnter[] = {"\A3\ui_f\data\sound\RscButton\soundEnter", 0.09, 1}; soundPush[] = {"\A3\ui_f\data\sound\RscButton\soundPush", 0.09, 1}; soundClick[] = {"\A3\ui_f\data\sound\RscButton\soundClick", 0.09, 1}; soundEscape[] = {"\A3\ui_f\data\sound\RscButton\soundEscape", 0.09, 1}; animTextureDefault = "\A3\ui_f\data\GUI\RscCommon\RscShortcutButton\normal_ca.paa"; animTextureNormal = "\A3\ui_f\data\GUI\RscCommon\RscShortcutButton\normal_ca.paa"; animTextureDisabled = "\A3\ui_f\data\GUI\RscCommon\RscShortcutButton\normal_ca.paa"; animTextureOver = "\A3\ui_f\data\GUI\RscCommon\RscShortcutButton\over_ca.paa"; animTextureFocused = "\A3\ui_f\data\GUI\RscCommon\RscShortcutButton\focus_ca.paa"; animTexturePressed = "\A3\ui_f\data\GUI\RscCommon\RscShortcutButton\down_ca.paa"; style = 2; x = 0; y = 0; w = 0.055589; h = 0.039216; shadow = 0; font = "PuristaMedium"; sizeEx = 0.04; offsetX = 0.003; offsetY = 0.003; offsetPressedX = 0.002; offsetPressedY = 0.002; borderSize = 0; tooltipColorText[] = {1, 1, 1, 1}; tooltipColorBox[] = {1, 1, 1, 1}; tooltipColorShade[] = {0, 0, 0, 0.65}; }; class w_RscButton2 { access = 0; type = CT_BUTTON; text = ""; colorText[] = {1,1,1,.9}; colorDisabled[] = {0.4,0.4,0.4,1}; colorBackground[] = {A3W_UICOLOR_R * 0.8, A3W_UICOLOR_G * 0.8, A3W_UICOLOR_B * 0.8, 1}; // normal colorFocused[] = {A3W_UICOLOR_R * 0.55, A3W_UICOLOR_G * 0.55, A3W_UICOLOR_B * 0.55, 1}; // pulse colorBackgroundActive[] = {A3W_UICOLOR_R, A3W_UICOLOR_G, A3W_UICOLOR_B, 1}; // hover colorBackgroundDisabled[] = {0.95,0.95,0.95,1}; colorShadow[] = {0,0,0,0}; colorBorder[] = {0,0,0,0}; soundEnter[] = {"\A3\ui_f\data\sound\RscButton\soundEnter", 0.09, 1}; soundPush[] = {"\A3\ui_f\data\sound\RscButton\soundPush", 0.09, 1}; soundClick[] = {"\A3\ui_f\data\sound\RscButton\soundClick", 0.09, 1}; soundEscape[] = {"\A3\ui_f\data\sound\RscButton\soundEscape", 0.09, 1}; // animTextureDefault = "\A3\ui_f\data\GUI\RscCommon\RscShortcutButton\normal_ca.paa"; // animTextureNormal = "\A3\ui_f\data\GUI\RscCommon\RscShortcutButton\normal_ca.paa"; // animTextureDisabled = "\A3\ui_f\data\GUI\RscCommon\RscShortcutButton\normal_ca.paa"; // animTextureOver = "\A3\ui_f\data\GUI\RscCommon\RscShortcutButton\over_ca.paa"; // animTextureFocused = "\A3\ui_f\data\GUI\RscCommon\RscShortcutButton\focus_ca.paa"; // animTexturePressed = "\A3\ui_f\data\GUI\RscCommon\RscShortcutButton\down_ca.paa"; style = 2; x = 0; y = 0; w = 0.055589; h = 0.039216; shadow = 0; font = "PuristaMedium"; sizeEx = 0.04; offsetX = 0.003; offsetY = 0.003; offsetPressedX = 0.002; offsetPressedY = 0.002; borderSize = 0; tooltipColorText[] = {1, 1, 1, 1}; tooltipColorBox[] = {1, 1, 1, 1}; tooltipColorShade[] = {0, 0, 0, 0.65}; }; class w_RscCombo { idc = -1; type = 4; style = 0; x = "0.0 + 0.365"; y = "0.0 + 0.038"; w = 0.301000; h = 0.039216; font = "PuristaMedium"; sizeEx = 0.025000; rowHeight = 0.025000; wholeHeight = "4 * 0.2"; color[] = {1, 1, 1, 1}; colorDisabled[] = {0,0,0,0.3}; colorText[] = {0, 0, 0, 1}; colorBackground[] = {1, 1, 1, 1}; colorSelect[] = {1, 0, 0, 1}; colorSelectBackground[] = {A3W_UICOLOR_R, A3W_UICOLOR_G, A3W_UICOLOR_B, 0.5}; soundSelect[] = {"", 0.000000, 1}; soundExpand[] = {"", 0.000000, 1}; soundCollapse[] = {"", 0.000000, 1}; maxHistoryDelay = 10; autoScrollSpeed = -1; autoScrollDelay = 5; autoScrollRewind = 0; colorScrollbar[] = {0.2, 0.2, 0.2, 1}; period = 1; thumb = "\A3\ui_f\data\gui\cfg\scrollbar\thumb_ca.paa"; arrowFull = "\A3\ui_f\data\gui\cfg\scrollbar\arrowFull_ca.paa"; arrowEmpty = "\A3\ui_f\data\gui\cfg\scrollbar\arrowEmpty_ca.paa"; border = "\A3\ui_f\data\gui\cfg\scrollbar\border_ca.paa"; class ComboScrollBar { color[] = {1, 1, 1, 0.6}; colorActive[] = {1, 1, 1, 1}; colorDisabled[] = {1, 1, 1, 0.3}; thumb = "\A3\ui_f\data\gui\cfg\scrollbar\thumb_ca.paa"; arrowFull = "\A3\ui_f\data\gui\cfg\scrollbar\arrowFull_ca.paa"; arrowEmpty = "\A3\ui_f\data\gui\cfg\scrollbar\arrowEmpty_ca.paa"; border = "\A3\ui_f\data\gui\cfg\scrollbar\border_ca.paa"; }; tooltipColorText[] = {1, 1, 1, 1}; tooltipColorBox[] = {1, 1, 1, 1}; tooltipColorShade[] = {0, 0, 0, 0.65}; }; class w_RscCheckBox { idc = -1; type = CT_CHECKBOX; style = 0; checked = 0; w = "0.04 * (safezoneW min safezoneH)"; h = "0.04 * (safezoneW min safezoneH)"; color[] = {1, 1, 1, 0.7}; colorFocused[] = {1, 1, 1, 1}; colorHover[] = {1, 1, 1, 1}; colorPressed[] = {1, 1, 1, 1}; colorDisabled[] = {1, 1, 1, 0.2}; colorBackground[] = {0, 0, 0, 0}; colorBackgroundFocused[] = {0, 0, 0, 0}; colorBackgroundHover[] = {0, 0, 0, 0}; colorBackgroundPressed[] = {0, 0, 0, 0}; colorBackgroundDisabled[] = {0, 0, 0, 0}; textureChecked = "\A3\Ui_f\data\GUI\RscCommon\RscCheckBox\CheckBox_checked_ca.paa"; textureUnchecked = "\A3\Ui_f\data\GUI\RscCommon\RscCheckBox\CheckBox_unchecked_ca.paa"; textureFocusedChecked = "\A3\Ui_f\data\GUI\RscCommon\RscCheckBox\CheckBox_checked_ca.paa"; textureFocusedUnchecked = "\A3\Ui_f\data\GUI\RscCommon\RscCheckBox\CheckBox_unchecked_ca.paa"; textureHoverChecked = "\A3\Ui_f\data\GUI\RscCommon\RscCheckBox\CheckBox_checked_ca.paa"; textureHoverUnchecked = "\A3\Ui_f\data\GUI\RscCommon\RscCheckBox\CheckBox_unchecked_ca.paa"; texturePressedChecked = "\A3\Ui_f\data\GUI\RscCommon\RscCheckBox\CheckBox_checked_ca.paa"; texturePressedUnchecked = "\A3\Ui_f\data\GUI\RscCommon\RscCheckBox\CheckBox_unchecked_ca.paa"; textureDisabledChecked = "\A3\Ui_f\data\GUI\RscCommon\RscCheckBox\CheckBox_checked_ca.paa"; textureDisabledUnchecked = "\A3\Ui_f\data\GUI\RscCommon\RscCheckBox\CheckBox_unchecked_ca.paa"; tooltipColorText[] = {1, 1, 1, 1}; tooltipColorBox[] = {1, 1, 1, 1}; tooltipColorShade[] = {0, 0, 0, 0.65}; soundEnter[] = {1, 1, 1, 1}; soundPush[] = {1, 1, 1, 1}; soundClick[] = {1, 1, 1, 1}; soundEscape[] = {1, 1, 1, 1}; }; class w_RscXSliderH { type = CT_XSLIDER; style = SL_HORZ + SL_TEXTURES; color[] = {1, 1, 1, 0.6}; colorActive[] = {1, 1, 1, 1}; colorDisable[] = {1, 1, 1, 0.4}; colorDisabled[] = {1, 1, 1, 0.2}; x = 0; y = 0; h = 0.029412; w = 0.4; arrowEmpty = "\A3\ui_f\data\gui\cfg\slider\arrowEmpty_ca.paa"; arrowFull = "\A3\ui_f\data\gui\cfg\slider\arrowFull_ca.paa"; border = "\A3\ui_f\data\gui\cfg\slider\border_ca.paa"; thumb = "\A3\ui_f\data\gui\cfg\slider\thumb_ca.paa"; tooltipColorText[] = {1, 1, 1, 1}; tooltipColorBox[] = {1, 1, 1, 1}; tooltipColorShade[] = {0, 0, 0, 0.65}; //onSliderPosChanged = "call stuff"; }; class w_RscXListBox { idc = -1; type = CT_XLISTBOX; style = SL_HORZ + SL_TEXTURES + ST_CENTER; x = 0; y = 0; w = 0.5; h = 0.1; color[] = {1, 1, 1, 0.6}; colorActive[] = {1, 1, 1, 1}; colorDisabled[] = {1, 1, 1, 0.25}; colorSelect[] = {0.95, 0.95, 0.95, 1}; colorText[] = {1, 1, 1, 1}; soundSelect[] = {"\A3\ui_f\data\sound\RscListbox\soundSelect", 0.09, 1}; colorPicture[] = {1, 1, 1, 1}; colorPictureSelected[] = {1, 1, 1, 1}; colorPictudeDisabled[] = {1, 1, 1, 0.25}; tooltipColorText[] = {1, 1, 1, 1}; tooltipColorBox[] = {1, 1, 1, 1}; tooltipColorShade[] = {0, 0, 0, 0.65}; shadow = 2; arrowEmpty = "\A3\ui_f\data\gui\cfg\slider\arrowEmpty_ca.paa"; arrowFull = "\A3\ui_f\data\gui\cfg\slider\arrowFull_ca.paa"; border = "\A3\ui_f\data\gui\cfg\slider\border_ca.paa"; font = "PuristaMedium"; sizeEx = 0.035; }; class RscHTML { idc = -1; type = CT_HTML; style = ST_LEFT; colorText[] = {Dlg_Color_White, 1}; colorLink[] = {0.05, 0.2, 0.05, 1}; colorBold[] = {0, 1, 1, 1}; colorBackground[] = {0, 0, 0, 0}; colorLinkActive[] = {0, 0, 0.2, 1}; colorPicture[] = {Dlg_Color_Black, 1}; colorPictureLink[] = {Dlg_Color_Black, 1}; colorPictureSelected[] = {Dlg_Color_Black, 1}; colorPictureBorder[] = {Dlg_Color_Black, 1}; x = 0; y = 0; w = 1; h = 1; fileName = ""; prevPage = "\ca\ui\data\arrow_left_ca.paa"; nextPage = "\ca\ui\data\arrow_right_ca.paa"; class HeadingStyle { font = "PuristaBold"; fontBold = "TahomaB"; sizeEx = Dlg_TEXTHGT; }; class H1: HeadingStyle { sizeEx = Dlg_TEXTHGT * 1.5; }; class H2: HeadingStyle { sizeEx = Dlg_TEXTHGT * 1.4; }; class H3: HeadingStyle { sizeEx = Dlg_TEXTHGT * 1.3; }; class H4: HeadingStyle { sizeEx = Dlg_TEXTHGT * 1.2; }; class H5: HeadingStyle { sizeEx = Dlg_TEXTHGT * 1.1; }; class H6: HeadingStyle { sizeEx = Dlg_TEXTHGT; }; class P: HeadingStyle { sizeEx = Dlg_TEXTHGT; }; }; class w_RscMapControl { type = CT_MAP_MAIN; style = ST_PICTURE; idc = 51; colorBackground[] = {0.969, 0.957, 0.949, 1}; colorOutside[] = {0, 0, 0, 1}; colorText[] = {0, 0, 0, 1}; font = "TahomaB"; sizeEx = 0.04; colorSea[] = {0.467, 0.631, 0.851, 0.5}; colorForest[] = {0.624, 0.78, 0.388, 0.5}; colorRocks[] = {0, 0, 0, 0.3}; colorCountlines[] = {0.572, 0.354, 0.188, 0.25}; colorMainCountlines[] = {0.572, 0.354, 0.188, 0.5}; colorCountlinesWater[] = {0.491, 0.577, 0.702, 0.3}; colorMainCountlinesWater[] = {0.491, 0.577, 0.702, 0.6}; colorForestBorder[] = {0, 0, 0, 0}; colorRocksBorder[] = {0, 0, 0, 0}; colorPowerLines[] = {0.1, 0.1, 0.1, 1}; colorRailWay[] = {0.8, 0.2, 0, 1}; colorNames[] = {0.1, 0.1, 0.1, 0.9}; colorInactive[] = {1, 1, 1, 0.5}; colorLevels[] = {0.286, 0.177, 0.094, 0.5}; colorTracks[] = {0.84, 0.76, 0.65, 0.15}; colorRoads[] = {0.7, 0.7, 0.7, 1}; colorMainRoads[] = {0.9, 0.5, 0.3, 1}; colorTracksFill[] = {0.84, 0.76, 0.65, 1}; colorRoadsFill[] = {1, 1, 1, 1}; colorMainRoadsFill[] = {1, 0.6, 0.4, 1}; colorGrid[] = {0.1, 0.1, 0.1, 0.6}; colorGridMap[] = {0.1, 0.1, 0.1, 0.6}; stickX[] = {0.2, {"Gamma", 1, 1.5}}; stickY[] = {0.2, {"Gamma", 1, 1.5}}; moveOnEdges = 1; x = 0; y = 0; w = 1; h = 1; shadow = 0; ptsPerSquareSea = 5; ptsPerSquareTxt = 20; ptsPerSquareCLn = 10; ptsPerSquareExp = 10; ptsPerSquareCost = 10; ptsPerSquareFor = 9; ptsPerSquareForEdge = 9; ptsPerSquareRoad = 6; ptsPerSquareObj = 9; showCountourInterval = 0; scaleMin = 0.001; scaleMax = 1; scaleDefault = 0.16; maxSatelliteAlpha = 0.85; alphaFadeStartScale = 2; alphaFadeEndScale = 2; colorTrails[] = {0.84, 0.76, 0.65, 0.15}; colorTrailsFill[] = {0.84, 0.76, 0.65, 0.65}; fontLabel = "RobotoCondensed"; sizeExLabel = "(((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 0.8)"; fontGrid = "TahomaB"; sizeExGrid = 0.02; fontUnits = "TahomaB"; sizeExUnits = "(((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 0.8)"; fontNames = "RobotoCondensed"; sizeExNames = "(((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 0.8) * 2"; fontInfo = "RobotoCondensed"; sizeExInfo = "(((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 0.8)"; fontLevel = "TahomaB"; sizeExLevel = 0.02; text = "#(argb,8,8,3)color(1,1,1,1)"; widthRailWay = 4; idcMarkerColor = -1; idcMarkerIcon = -1; textureComboBoxColor = "#(argb,8,8,3)color(1,1,1,1)"; showMarkers = 1; class Legend { colorBackground[] = {1, 1, 1, 0.5}; color[] = {0, 0, 0, 1}; x = "SafeZoneX + (((safezoneW / safezoneH) min 1.2) / 40)"; y = "SafeZoneY + safezoneH - 4.5 * ((((safezoneW / safezoneH) min 1.2) / 1.2) / 25)"; w = "10 * (((safezoneW / safezoneH) min 1.2) / 40)"; h = "3.5 * ((((safezoneW / safezoneH) min 1.2) / 1.2) / 25)"; font = "RobotoCondensed"; sizeEx = "(((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 0.8)"; }; class ActiveMarker { color[] = {0.3, 0.1, 0.9, 1}; size = 50; }; class Command { color[] = {1, 1, 1, 1}; icon = "\a3\ui_f\data\map\mapcontrol\waypoint_ca.paa"; size = 18; importance = 1; coefMin = 1; coefMax = 1; }; class Task { taskNone = "#(argb,8,8,3)color(0,0,0,0)"; taskCreated = "#(argb,8,8,3)color(0,0,0,1)"; taskAssigned = "#(argb,8,8,3)color(1,1,1,1)"; taskSucceeded = "#(argb,8,8,3)color(0,1,0,1)"; taskFailed = "#(argb,8,8,3)color(1,0,0,1)"; taskCanceled = "#(argb,8,8,3)color(1,0.5,0,1)"; colorCreated[] = {1, 1, 1, 1}; colorCanceled[] = {0.7, 0.7, 0.7, 1}; colorDone[] = {0.7, 1, 0.3, 1}; colorFailed[] = {1, 0.3, 0.2, 1}; color[] = {"(profilenamespace getvariable ['IGUI_TEXT_RGB_R',0])", "(profilenamespace getvariable ['IGUI_TEXT_RGB_G',1])", "(profilenamespace getvariable ['IGUI_TEXT_RGB_B',1])", "(profilenamespace getvariable ['IGUI_TEXT_RGB_A',0.8])"}; icon = "\A3\ui_f\data\map\mapcontrol\taskIcon_CA.paa"; iconCreated = "\A3\ui_f\data\map\mapcontrol\taskIconCreated_CA.paa"; iconCanceled = "\A3\ui_f\data\map\mapcontrol\taskIconCanceled_CA.paa"; iconDone = "\A3\ui_f\data\map\mapcontrol\taskIconDone_CA.paa"; iconFailed = "\A3\ui_f\data\map\mapcontrol\taskIconFailed_CA.paa"; size = 27; importance = 1; coefMin = 1; coefMax = 1; }; class CustomMark { color[] = {1, 1, 1, 1}; icon = "\A3\ui_f\data\map\mapcontrol\custommark_ca.paa"; size = 18; importance = 1; coefMin = 1; coefMax = 1; }; class Tree { color[] = {0.45, 0.64, 0.33, 0.4}; icon = "\A3\ui_f\data\map\mapcontrol\bush_ca.paa"; size = 12; importance = "0.9 * 16 * 0.05"; coefMin = 0.25; coefMax = 4; }; class SmallTree { color[] = {0.45, 0.64, 0.33, 0.4}; icon = "\A3\ui_f\data\map\mapcontrol\bush_ca.paa"; size = 12; importance = "0.6 * 12 * 0.05"; coefMin = 0.25; coefMax = 4; }; class Bush { color[] = {0.45, 0.64, 0.33, 0.4}; icon = "\A3\ui_f\data\map\mapcontrol\bush_ca.paa"; size = "14/2"; importance = "0.2 * 14 * 0.05 * 0.05"; coefMin = 0.25; coefMax = 4; }; class Church { color[] = {1, 1, 1, 1}; icon = "\A3\ui_f\data\map\mapcontrol\church_CA.paa"; size = 24; importance = 1; coefMin = 0.85; coefMax = 1; }; class Chapel { color[] = {0, 0, 0, 1}; icon = "\A3\ui_f\data\map\mapcontrol\Chapel_CA.paa"; size = 24; importance = 1; coefMin = 0.85; coefMax = 1; }; class Cross { color[] = {0, 0, 0, 1}; icon = "\A3\ui_f\data\map\mapcontrol\Cross_CA.paa"; size = 24; importance = 1; coefMin = 0.85; coefMax = 1; }; class Rock { color[] = {0.1, 0.1, 0.1, 0.8}; icon = "\A3\ui_f\data\map\mapcontrol\rock_ca.paa"; size = 12; importance = "0.5 * 12 * 0.05"; coefMin = 0.25; coefMax = 4; }; class Bunker { color[] = {0, 0, 0, 1}; icon = "\A3\ui_f\data\map\mapcontrol\bunker_ca.paa"; size = 14; importance = "1.5 * 14 * 0.05"; coefMin = 0.25; coefMax = 4; }; class Fortress { color[] = {0, 0, 0, 1}; icon = "\A3\ui_f\data\map\mapcontrol\bunker_ca.paa"; size = 16; importance = "2 * 16 * 0.05"; coefMin = 0.25; coefMax = 4; }; class Fountain { color[] = {0, 0, 0, 1}; icon = "\A3\ui_f\data\map\mapcontrol\fountain_ca.paa"; size = 11; importance = "1 * 12 * 0.05"; coefMin = 0.25; coefMax = 4; }; class ViewTower { color[] = {0, 0, 0, 1}; icon = "\A3\ui_f\data\map\mapcontrol\viewtower_ca.paa"; size = 16; importance = "2.5 * 16 * 0.05"; coefMin = 0.5; coefMax = 4; }; class Lighthouse { color[] = {1, 1, 1, 1}; icon = "\A3\ui_f\data\map\mapcontrol\lighthouse_CA.paa"; size = 24; importance = 1; coefMin = 0.85; coefMax = 1; }; class Quay { color[] = {1, 1, 1, 1}; icon = "\A3\ui_f\data\map\mapcontrol\quay_CA.paa"; size = 24; importance = 1; coefMin = 0.85; coefMax = 1; }; class Fuelstation { color[] = {1, 1, 1, 1}; icon = "\A3\ui_f\data\map\mapcontrol\fuelstation_CA.paa"; size = 24; importance = 1; coefMin = 0.85; coefMax = 1; }; class Hospital { color[] = {1, 1, 1, 1}; icon = "\A3\ui_f\data\map\mapcontrol\hospital_CA.paa"; size = 24; importance = 1; coefMin = 0.85; coefMax = 1; }; class BusStop { color[] = {1, 1, 1, 1}; icon = "\A3\ui_f\data\map\mapcontrol\busstop_CA.paa"; size = 24; importance = 1; coefMin = 0.85; coefMax = 1; }; class LineMarker { textureComboBoxColor = "#(argb,8,8,3)color(1,1,1,1)"; lineWidthThin = 0.008; lineWidthThick = 0.014; lineDistanceMin = 3e-005; lineLengthMin = 5; }; class Transmitter { color[] = {1, 1, 1, 1}; icon = "\A3\ui_f\data\map\mapcontrol\transmitter_CA.paa"; size = 24; importance = 1; coefMin = 0.85; coefMax = 1; }; class Stack { color[] = {0, 0, 0, 1}; icon = "\A3\ui_f\data\map\mapcontrol\stack_ca.paa"; size = 16; importance = "2 * 16 * 0.05"; coefMin = 0.4; coefMax = 2; }; class Ruin { color[] = {0, 0, 0, 1}; icon = "\A3\ui_f\data\map\mapcontrol\ruin_ca.paa"; size = 16; importance = "1.2 * 16 * 0.05"; coefMin = 1; coefMax = 4; }; class Tourism { color[] = {0, 0, 0, 1}; icon = "\A3\ui_f\data\map\mapcontrol\tourism_ca.paa"; size = 16; importance = "1 * 16 * 0.05"; coefMin = 0.7; coefMax = 4; }; class Watertower { color[] = {1, 1, 1, 1}; icon = "\A3\ui_f\data\map\mapcontrol\watertower_CA.paa"; size = 24; importance = 1; coefMin = 0.85; coefMax = 1; }; class Waypoint { color[] = {1, 1, 1, 1}; importance = 1; coefMin = 1; coefMax = 1; icon = "\A3\ui_f\data\map\mapcontrol\waypoint_ca.paa"; size = 18; }; class WaypointCompleted { color[] = {1, 1, 1, 1}; importance = 1; coefMin = 1; coefMax = 1; icon = "\A3\ui_f\data\map\mapcontrol\waypointcompleted_ca.paa"; size = 18; }; class power { icon = "\A3\ui_f\data\map\mapcontrol\power_CA.paa"; size = 24; importance = 1; coefMin = 0.85; coefMax = 1; color[] = {1, 1, 1, 1}; }; class powersolar { icon = "\A3\ui_f\data\map\mapcontrol\powersolar_CA.paa"; size = 24; importance = 1; coefMin = 0.85; coefMax = 1; color[] = {1, 1, 1, 1}; }; class powerwave { icon = "\A3\ui_f\data\map\mapcontrol\powerwave_CA.paa"; size = 24; importance = 1; coefMin = 0.85; coefMax = 1; color[] = {1, 1, 1, 1}; }; class powerwind { icon = "\A3\ui_f\data\map\mapcontrol\powerwind_CA.paa"; size = 24; importance = 1; coefMin = 0.85; coefMax = 1; color[] = {1, 1, 1, 1}; }; class Shipwreck { icon = "\A3\ui_f\data\map\mapcontrol\Shipwreck_CA.paa"; size = 24; importance = 1; coefMin = 0.85; coefMax = 1; color[] = {0, 0, 0, 1}; }; };
26.332998
239
0.617268
Exonical
c34c2beb47f32080e1c940759c5df6a68730d894
8,036
cc
C++
cl-platform-probe.cc
terminatorul/cl-tool
2202066a89a97982a49b64cb54e8cb36322ae1b1
[ "Unlicense" ]
null
null
null
cl-platform-probe.cc
terminatorul/cl-tool
2202066a89a97982a49b64cb54e8cb36322ae1b1
[ "Unlicense" ]
null
null
null
cl-platform-probe.cc
terminatorul/cl-tool
2202066a89a97982a49b64cb54e8cb36322ae1b1
[ "Unlicense" ]
null
null
null
#include <cstddef> #include <chrono> #include <thread> #include <iterator> #include <iostream> #include <memory> #if defined(__APPLE__) || defined(__MACOSX__) # include <OpenCL/cl2.hpp> #else # include <CL/cl2.hpp> #endif #include "cl-platform-info.hh" #include "cl-double-pendulum.hh" #include "cl-platform-probe.hh" using std::size_t; using std::chrono::milliseconds; using std::cout; using std::clog; using std::endl; using std::flush; using std::size; using std::unique_ptr; using cl::Platform; using cl::Device; using cl::NDRange; static const auto SIMULATION_STEP_PROBE_TIME = milliseconds(100), SIMULATION_PROBE_TIME_MAX = milliseconds(450); // Allow for at least 3 full time steps during probe static const unsigned MULTI_PASS_COUNT = 3; extern void probe_cl_platform(Platform &platform) { cout << trim_name(platform.getInfo<CL_PLATFORM_NAME>()) << endl; } size_t probe_global_simulation_size(DoublePendulumSimulation &sim, size_t base_size, size_t size_multiple) { unsigned n = 1u; while ( milliseconds(sim.runSimulation(NDRange((base_size + n) * size_multiple), NDRange(size_multiple))) < SIMULATION_PROBE_TIME_MAX || milliseconds(sim.runSimulation(NDRange((base_size + n + 1) * size_multiple), NDRange(size_multiple))) < SIMULATION_PROBE_TIME_MAX || milliseconds(sim.runSimulation(NDRange((base_size + n + 2) * size_multiple), NDRange(size_multiple))) < SIMULATION_PROBE_TIME_MAX ) { n *= 2u; } if (n > 2u) return probe_global_simulation_size(sim, base_size + n / 2, size_multiple); return base_size; } extern bool probe_cl_device(Device &device) { cout << "\tDevice: " << trim_name(device.getInfo<CL_DEVICE_NAME>()) << endl; if ( device.getInfo<CL_DEVICE_AVAILABLE>() && device.getInfo<CL_DEVICE_COMPILER_AVAILABLE>() && [&device] () -> bool { cl_bool has_linker; device.getInfo(CL_DEVICE_LINKER_AVAILABLE, &has_linker); return has_linker; }() ) { DoublePendulumSimulation &sim = DoublePendulumSimulation::get(device); sim.probeIterationCount(SIMULATION_STEP_PROBE_TIME); clog << "\tCandidate step count: " << sim.iterationCount() << endl; // clog << endl; return true; auto size_multiple = sim.groupSizeMultiple(), simulation_size = probe_global_simulation_size(sim, 1u, size_multiple); clog << "\tGlobal workgroup size: " << simulation_size << endl; unique_ptr<unsigned long[][MULTI_PASS_COUNT]>times(new unsigned long[simulation_size][MULTI_PASS_COUNT]); for (unsigned it = 0; it < size(times[0]); it++) { cout << "\rMultiple: " << it << "/ " << flush; for (unsigned n = 1u; n <= simulation_size; n++) { cout << "\rMultiple: " << it + 1u << '/' << n << flush; times[n - 1][it] = static_cast<unsigned long>(sim.runSimulation(NDRange(n * size_multiple), NDRange(size_multiple))); std::this_thread::sleep_for(std::chrono::milliseconds(300)); } } cout << '\n'; // cout << endl; cout << "Counts: [ 0"; for (unsigned n = 1u; n <= simulation_size; n++) cout << ", " << n * size_multiple; cout << " ]" << endl; for (unsigned it = 0; it < size(times[0]); it++) { cout << "Times: [ 0"; for (unsigned n = 1u; n <= simulation_size; n++) cout << ", " << times[n - 1u][it]; cout << " ]" << endl; } } else { clog << "\t " << "Linker, compiler or device are not available!\n" << endl; return false; } return true; } // void list_context_devices(Context &context) // { // vector<Device> devices(context.getInfo<CL_CONTEXT_DEVICES>()); // // for (auto &device: devices) // show_cl_device(device); // } // // extern void test_matrix_multiply() // { // cl_platform_id platform; // std::array<cl_context_properties, 3> context_props = { 0, 0, 0 }; // // if (!args.select_platform_name.empty()) // { // std::vector<cl::Platform> clPlatforms; // bool platform_found = false; // // cl::Platform::get(&clPlatforms); // // for (auto it = clPlatforms.cbegin(); !platform_found && it != clPlatforms.cend(); it++) // if (!strncmp(it->getInfo<CL_PLATFORM_NAME>().data(), args.select_platform_name.data(), // std::min(it->getInfo<CL_PLATFORM_NAME>().size(), args.select_platform_name.length()))) // { // platform = it->Wrapper<cl_platform_id>::get(); // platform_found = true; // } // // if (!platform_found) // for (auto it = clPlatforms.cbegin(); !platform_found && it != clPlatforms.cend(); it++) // if(!strncmp(it->getInfo<CL_PLATFORM_VENDOR>().data(), args.select_platform_name.data(), // std::min(it->getInfo<CL_PLATFORM_VENDOR>().size(), args.select_platform_name.length()))) // { // platform = it->Wrapper<cl_platform_id>::get(); // platform_found = true; // } // // if (!platform_found) // throw std::runtime_error("No such platform: " + args.select_platform_name); // // context_props[0] = CL_CONTEXT_PLATFORM; // context_props[1] = static_cast<cl_context_properties>(reinterpret_cast<intptr_t>(platform)); // context_props[2] = static_cast<cl_context_properties>(0); // } // // cl::Context context(CL_DEVICE_TYPE_DEFAULT, context_props[0] ? context_props.data() : nullptr, context_error_notification); // // if (args.list_all_devices) // list_context_devices(context); // // if (args.probe) // { // cout << "Probing device" << (context.getInfo<CL_CONTEXT_DEVICES>().size() > 1 ? "s" : "") << ": \n"; // // for (auto const &device: context.getInfo<CL_CONTEXT_DEVICES>()) // cout << '\t' << device.getInfo<CL_DEVICE_NAME>() << endl; // // cout << endl; // // cl_ulong const lines = 1024, cols = 1024, internal_size = 1024; // // cl::Buffer // m(context, CL_MEM_READ_WRITE | CL_MEM_HOST_READ_ONLY /* CL_MEM_HOST_NO_ACCESS */, sizeof(cl_double) * lines * internal_size), // n(context, CL_MEM_READ_WRITE | CL_MEM_HOST_READ_ONLY /* CL_MEM_HOST_NO_ACCESS */, sizeof(cl_double) * internal_size * cols), // result(context, CL_MEM_WRITE_ONLY | CL_MEM_HOST_READ_ONLY, sizeof(cl_double)* lines * cols); // // Matrix mat(context); // std::vector<cl_float> sub_buffer; // // mat.random_fill<cl_float>(m, lines, internal_size, -100.0f, 100.0f); // mat.random_fill<cl_float>(n, internal_size, cols, -100.0f, 100.0f); // //mat.zero_fill<cl_float>(result, lines, cols); // mat.random_fill<cl_float>(result, internal_size, cols, 0.0f, 0.0001f); // mat.waitForCompletion(); // // // std::time_t startTime, endTime; // time(&startTime); // mat.multiply<cl_float>(m, lines, internal_size, n, internal_size, cols, result, lines, cols); // mat.waitForCompletion(); // time(&endTime); // // cout << std::setprecision(5) << std::fixed << (static_cast<double>(lines) * internal_size * cols * 2 / 1000/1000/1000) / static_cast<double>(endTime - startTime) << " GFLOPS" << endl; // // // // mat.readBufferRectAsync(result, lines, cols, 852, 718, 20, 20, sub_buffer); // // mat.waitForCompletion(); // // mat.readBufferRect(result, lines, cols, 852, 718, 20, 20, sub_buffer); // // cout << "Sample sub-matrix:\n"; // for (unsigned i = 0; i < 10; i++) // { // for (unsigned j = 0; j < 10; j++) // cout << std::setw(14) << std::setprecision(5) << std::fixed << std::setfill(' ') << std::setiosflags(cout.right) << std::showpos << sub_buffer[i * 10 + j] << ' '; // // cout << endl; // } // } // }
34.48927
195
0.599054
terminatorul
c34f1fe6fbd195c4647af0a53da3e0389cee68d3
9,238
cpp
C++
Reverse/EasyAlgorithm/obfusGenerator.cpp
B0sS-Tang/moeCTF_2020
c10fa5663effaf4f0ba774f3766c9eb26cec3200
[ "MIT" ]
9
2020-10-07T15:14:52.000Z
2021-07-21T08:50:08.000Z
Reverse/EasyAlgorithm/obfusGenerator.cpp
B0sS-Tang/moeCTF_2020
c10fa5663effaf4f0ba774f3766c9eb26cec3200
[ "MIT" ]
null
null
null
Reverse/EasyAlgorithm/obfusGenerator.cpp
B0sS-Tang/moeCTF_2020
c10fa5663effaf4f0ba774f3766c9eb26cec3200
[ "MIT" ]
2
2020-10-08T05:08:02.000Z
2020-10-11T10:35:46.000Z
#include<cstdio> #include<cstdlib> #include<ctime> #include<cstring> #include<vector> #include<string> //#include<windows.h> #define INT 0 #define LLONG 1 #define CHAR 2 #define SHORT 3 #define MAX_OP_TYPE 2 #define MAX_CODE_LEN 1000 #define MAX_DEOBFU_CODE_NUM 1000 //#define DEBUG_CPP_CODE #define OUPUT_CONSOLE using namespace std; struct VarInfo { int data_type; char name[30]; }; int var_num; VarInfo list[10000]; struct Operate { int op_type; VarInfo *var_info; int op_args[10]; int recover; }; struct Op2ObfuCode { char *code; int arg_num; }; struct Op2DeObfuCode { char *deobfu_code[MAX_DEOBFU_CODE_NUM]; int arg_num; int equal_code_num=0; }; int Ops=0; Operate *OpList[10000],*OpOrig[10000]; Op2ObfuCode op_table[10000]; Op2DeObfuCode deop_table[10000]; int RunTimeStack[10000]={0},st_size=0; void push(int val) { RunTimeStack[st_size++]=val; } int pop() { return RunTimeStack[--st_size]; } void addDeObfuCode(const char *code,int type,int arg_num) { Op2DeObfuCode op2code=deop_table[type]; op2code.deobfu_code[op2code.equal_code_num++]=(char*)code; op2code.arg_num=arg_num; deop_table[type]=op2code; } void addObfuCode(const char *code,int type,int arg_num) { Op2ObfuCode op2code; op2code.code=(char*)code; op2code.arg_num=arg_num; op_table[type]=op2code; } void addVar(const char *name,int type) { VarInfo vi; strcpy(vi.name,name); vi.data_type=type; list[var_num++]=vi; } Operate *getRecoverOp(Operate *a) { Operate *op=(Operate*)malloc(sizeof(Operate)); for(int i=0;i<=6;i++) op->op_args[i]=a->op_args[i]; op->op_type=a->op_type; op->recover=1; op->var_info=a->var_info; return op; } void dumpOpList() { for(int i=0;i<Ops;i++) printf("dump:%04X VarName:%s OpType:%d RecoverFlag:%s\n\n",i,OpList[i]->var_info->name,OpList[i]->op_type,OpList[i]->recover==1?"True":"False"); } const char sub_name[]="sub"; vector<int> cleanSub; void genOperates(int max_size) { int ptr=0; for(int i=0;i<max_size;i++) { Operate *op=(Operate*)malloc(sizeof(Operate)); OpOrig[i]=op; op->op_type=rand()%MAX_OP_TYPE; int t=rand()%var_num; op->var_info=&list[t]; for(int j=0;j<=6;j++) op->op_args[j]=rand(); op->recover=0; } while(ptr<max_size) { int choice=rand()%2; if(choice || st_size==0) { OpList[Ops++]=OpOrig[ptr]; push(ptr++); continue; } else if(!choice && st_size>0) { int x=pop(); Operate *op=getRecoverOp(OpOrig[x]); OpList[Ops++]=op; if(st_size==0) { printf("[OBFU_MAKER]: Find a function %s_%d() that can put real code intoo..\n",sub_name,Ops-1); cleanSub.push_back(Ops-1); } continue; } } int t=st_size; for(int i=0;i<t;i++) { int x=pop(); Operate *op=getRecoverOp(OpOrig[x]); OpList[Ops++]=op; } #ifdef DEBUG_OP dumpOpList(); #endif } vector<string> codeList; void genCppCode() { for(int i=0;i<Ops;i++) { char *str=(char*)malloc(MAX_CODE_LEN+10); char *buf=(char*)malloc(MAX_CODE_LEN+10); memset(str,0,sizeof(str)); memset(buf,0,sizeof(buf)); if(!OpList[i]->recover) { Op2ObfuCode *c=&op_table[OpList[i]->op_type]; if(c->code==NULL) continue; int ptr=0,rep=0; for(int j=0;j<strlen(c->code);j++) { if(c->code[j]=='%' && c->code[j+1]=='s') { int len=strlen(OpList[i]->var_info->name); for(int k=0;k<len;k++) str[ptr+k]=OpList[i]->var_info->name[k]; ptr+=len; j+=1; continue; } str[ptr++]=c->code[j]; } str[ptr]='\0'; sprintf(buf,str,OpList[i]->op_args[0],OpList[i]->op_args[1],OpList[i]->op_args[2],OpList[i]->op_args[3],OpList[i]->op_args[4],OpList[i]->op_args[5],OpList[i]->op_args[6]); for(int j=0;j<strlen(buf);j++) str[j]=buf[j]; str[strlen(buf)]='\0'; #ifdef DEBUG_CPP_CODE printf("Encode Code:\n %s\n",str); #endif } else { Op2DeObfuCode *c=&deop_table[OpList[i]->op_type]; if(c->equal_code_num==0) continue; char *code=c->deobfu_code[rand()%c->equal_code_num]; int ptr=0,rep=0; for(int j=0;j<strlen(code);j++) { if(code[j]=='%' && code[j+1]=='s') { int len=strlen(OpList[i]->var_info->name); for(int k=0;k<len;k++) str[ptr+k]=OpList[i]->var_info->name[k]; ptr+=len; j+=1; continue; } str[ptr++]=code[j]; } str[ptr]='\0'; sprintf(buf,str,OpList[i]->op_args[0],OpList[i]->op_args[1],OpList[i]->op_args[2],OpList[i]->op_args[3],OpList[i]->op_args[4],OpList[i]->op_args[5],OpList[i]->op_args[6]); for(int j=0;j<strlen(buf);j++) str[j]=buf[j]; str[strlen(buf)]='\0'; #ifdef DEBUG_CPP_CODE printf("Decode Code:\n %s\n",str); #endif } string s(str); codeList.push_back(s); free(buf); free(str); } } struct Tree { int data; Tree* branch[20]; int branch_num; }; int remain_size,data,size; Tree *head; void buildRandomTree(Tree *node) { node->branch_num=0; node->data=data++; if(remain_size<=0) return; int x=rand()%3+2; if(remain_size<=x) x=remain_size; remain_size-=x; for(int i=0;i<x;i++) { Tree *node_=(Tree*)malloc(sizeof(Tree)); node->branch[node->branch_num++]=node_; buildRandomTree(node_); } } void genRandomTree(int size_) { remain_size=size_; size=size_; data=0; Tree *head_=(Tree*)malloc(sizeof(Tree)); head=head_; buildRandomTree(head_); } vector<string> finalCode; void genSubCode(Tree *node,int depth) { char *code=(char*)malloc(5000); int data=node->data; int x=0; x+=sprintf(code,"void %s_%d()\t//depth: %d\n{\n",sub_name,data,depth); VarInfo *vi=&list[rand()%var_num]; x+=sprintf(code+x,"\tx=(x&%s)^(y|%s)^(x<<1);\n",vi->name,vi->name); x+=sprintf(code+x,"\ty=(y&%s)^(x|%s)^(y<<1);\n",vi->name,vi->name); x+=sprintf(code+x,"\t%s",codeList[data].c_str()); for(int i=0;i<cleanSub.size();i++) if(data==cleanSub[i]) x+=sprintf(code+x,"\n\t/* put your code here! */"); for(int i=0;i<node->branch_num;i++) { int p=rand()%100; if(p<=20) { x+=sprintf(code+x,"\n\tif((x+y)^2>=0 && (x-y)^2>=0)"); x+=sprintf(code+x,"\n\t\t%s_%d();",sub_name,node->branch[i]->data); x+=sprintf(code+x,"\n\telse"); x+=sprintf(code+x,"\n\t\texit(0);"); } else if(p<=40) { x+=sprintf(code+x,"\n\tif((x*(x-1)%2+2*y)^((x*(x-1)%2+2*y)|1)==1)"); x+=sprintf(code+x,"\n\t\t%s_%d();",sub_name,node->branch[i]->data); x+=sprintf(code+x,"\n\telse"); x+=sprintf(code+x,"\n\t\texit(0);"); } else if(p<=60) { x+=sprintf(code+x,"\n\tif((x-y)==(~(~x+y)))"); x+=sprintf(code+x,"\n\t\t%s_%d();",sub_name,node->branch[i]->data); x+=sprintf(code+x,"\n\telse"); x+=sprintf(code+x,"\n\t\texit(0);"); } else x+=sprintf(code+x,"\n\t%s_%d();",sub_name,node->branch[i]->data); } x+=sprintf(code+x,"\n}\n"); string cx(code); free(code); finalCode.push_back(cx); #ifdef OUPUT_CONSOLE printf("%s\n",cx.c_str()); #endif } void walkTree(Tree *node,int depth) { int x=node->branch_num; genSubCode(node,depth); for(int i=0;i<x;i++) { Tree *n=node->branch[i]; walkTree(n,depth+1); } } void spawnRubbisCode(int size) { printf("[OBFU_MAKER]: This program is used to generate rubbish code in order to disgust others..\n"); printf("[OBFU_MAKER]: Press any key to continue..\n"); getchar(); printf("[OBFU_MAKER]: Start to generate rubbish codes..\n"); // Sleep(1000); printf("[OBFU_MAKER]: Code size: %d..\n",size); genOperates(size); // Sleep(3000); printf("[OBFU_MAKER]: Operation Generated..\n"); // Sleep(1000); printf("[OBFU_MAKER]: Translate into cpp code..\n"); genCppCode(); // Sleep(2000); printf("[OBFU_MAKER]: Done..\n"); // Sleep(1000); printf("[OBFU_MAKER]: Generate logic tree..\n"); // Sleep(2000); genRandomTree(size*2-1); printf("[OBFU_MAKER]: Done..\n"); // Sleep(1000); printf("[OBFU_MAKER]: Generate final codes..\n"); // Sleep(3000); walkTree(head,1); printf("[OBFU_MAKER]: Done!\n"); // Sleep(2000); } void writeToFile(const char *filename) { FILE *fp=fopen(filename,"w"); int x=rand()+1,y=rand()+1; if(x>y) swap(x,y); fprintf(fp,"unsigned int x=%d,y=%d;\n",x,y); for(int i=finalCode.size()-1;i>=0;i--) fprintf(fp,"%s",finalCode[i].c_str()); fclose(fp); printf("[OBFU_MAKER]: Write to file %s..\n",filename); } void test() { addVar("flag[0]",1); //the type field reserved addVar("flag[1]",1); addVar("flag[2]",1); addVar("flag[3]",1); addVar("flag[4]",1); addVar("flag[5]",1); addVar("flag[6]",1); addVar("flag[7]",1); addVar("flag[8]",1); addVar("flag[9]",1); addVar("flag[10]",1); addVar("flag[11]",1); addVar("flag[12]",1); addVar("flag[13]",1); addVar("flag[14]",1); addVar("flag[15]",1); addVar("flag[16]",1); addVar("flag[17]",1); addVar("flag[18]",1); addVar("flag[19]",1); addVar("flag[20]",1); addVar("flag[21]",1); addObfuCode("%s=~(~%s+%d%12);",0,1); addDeObfuCode("%s=%s+%d%12;",0,1); addDeObfuCode("%s=~(~%s-%d%12);",0,1); addObfuCode("unsigned char a=%s,b=%d&0xff,c=%d&0xff;\n\t%s=(a|b|c)^(a&b)^(b&c)^(c&a)^(a&b&c);",1,2); addDeObfuCode("%s=%s^(%d&0xff)^(%d&0xff);",1,2); //addObfuCode("unsigned char a=%s,x=%d%8;\n\t%s=(a>>x) | (a<<(8-x));",2,1); //addDeObfuCode("unsigned char a=%s,x=%d%8;\n\t%s=(a<<x) | (a>>(8-x));",2,1); spawnRubbisCode(1000); //some bug occured here which cause the argument size that can't be larger than 1000 writeToFile("obfus.cpp"); } int main() { srand(time(0)); test(); return 0; }
23.506361
174
0.621996
B0sS-Tang
c351d8408cf1b915b8cc7790a34f5ec401953710
1,455
cpp
C++
test/delete_var_and_modify.cpp
mtak-/lockfree-stm
00cd5f9a056e999f0cd140106c1d66b321d6fd47
[ "MIT" ]
9
2016-11-14T23:35:30.000Z
2019-01-18T23:21:08.000Z
test/delete_var_and_modify.cpp
mtak-/lockfree-stm
00cd5f9a056e999f0cd140106c1d66b321d6fd47
[ "MIT" ]
3
2017-01-09T01:22:57.000Z
2017-03-20T04:50:05.000Z
test/delete_var_and_modify.cpp
mtak-/lockfree-stm
00cd5f9a056e999f0cd140106c1d66b321d6fd47
[ "MIT" ]
null
null
null
#include <lstm/lstm.hpp> #define STATEFUL_DEBUG_ALLOC #ifdef NDEBUG #undef NDEBUG #include "debug_alloc.hpp" #define NDEBUG #else #include "debug_alloc.hpp" #endif #include "simple_test.hpp" #include "thread_manager.hpp" static constexpr auto loop_count = LSTM_TEST_INIT(1000000, 100000); using lstm::atomic; using lstm::var; struct big { char data[65]; }; int main() { var<var<big, debug_alloc<big>>*> x_ptr{nullptr}; { thread_manager tm; tm.queue_loop_n( [&] { atomic([&](const lstm::transaction tx) { static std::allocator<var<big, debug_alloc<big>>> alloc{}; auto ptr = x_ptr.get(tx); if (ptr) { destroy_deallocate(tx, alloc, ptr); x_ptr.set(tx, nullptr); } else { x_ptr.set(tx, allocate_construct(tx, alloc)); } }); }, loop_count | 1); tm.queue_loop_n( [&] { atomic([&](const lstm::transaction tx) { auto ptr = x_ptr.get(tx); if (ptr) { ptr->set(tx, {}); } else lstm::retry(); }); }, loop_count); tm.run(); } CHECK(debug_live_allocations<> == 1); return test_result(); }
23.852459
78
0.468041
mtak-
c356c7ac7a9f043e7ee67d6661de575b5feab386
796
cpp
C++
CPP/OJ problems/Word Capitalization.cpp
kratikasinghal/OJ-problems
fc5365cb4db9da780779e9912aeb2a751fe4517c
[ "MIT" ]
null
null
null
CPP/OJ problems/Word Capitalization.cpp
kratikasinghal/OJ-problems
fc5365cb4db9da780779e9912aeb2a751fe4517c
[ "MIT" ]
null
null
null
CPP/OJ problems/Word Capitalization.cpp
kratikasinghal/OJ-problems
fc5365cb4db9da780779e9912aeb2a751fe4517c
[ "MIT" ]
null
null
null
// Problem: A. Word Capitalization // Contest: Codeforces - Codeforces Round #172 (Div. 2) // URL: https://codeforces.com/problemset/problem/281/A // Memory Limit: 256 MB // Time Limit: 2000 ms // Powered by CP Editor (https://github.com/cpeditor/cpeditor) #include <bits/stdc++.h> #define F first #define S second #define PB push_back #define MP make_pair #define ll long long int #define vi vector<int> #define vii vector<int, int> #define vc vector<char> #define vl vector<ll> #define mod 1000000007 #define INF 1000000009 using namespace std; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); string s; cin >> s; if(islower(s[0])) { s[0] = toupper(s[0]); } cout << s << "\n"; return 0; }
18.952381
62
0.625628
kratikasinghal
c358650ebc3b2b6e4d5b8b677b28a69747b3292c
320
cpp
C++
c-develop/19.Pointers/pointers.cpp
GustiArsyad123/C-Language-Test
90a2eb45d1db2b039acbe5d3499aaff0aed99f82
[ "MIT" ]
null
null
null
c-develop/19.Pointers/pointers.cpp
GustiArsyad123/C-Language-Test
90a2eb45d1db2b039acbe5d3499aaff0aed99f82
[ "MIT" ]
null
null
null
c-develop/19.Pointers/pointers.cpp
GustiArsyad123/C-Language-Test
90a2eb45d1db2b039acbe5d3499aaff0aed99f82
[ "MIT" ]
null
null
null
// ini contoh pointers di bahasa C++ #include <iostream> using namespace std; int main(){ string makanan = "Ayam Taliwang"; //variable dengan tipe string cout << makanan << endl; //hasil keluaran makanan "Ayam Taliwang" cout << &makanan << endl; //alamat memory keluaran dari makanan "0x7ffe62dab3b0" }
32
85
0.690625
GustiArsyad123
c359a8469d3c3947291595937ea46be32f44a546
20
cpp
C++
ffsharp/SWScale.cpp
stschake/ffsharp
506de52dde93d3dcf6c8bf3cbc452284fce8d304
[ "Net-SNMP", "Xnet" ]
null
null
null
ffsharp/SWScale.cpp
stschake/ffsharp
506de52dde93d3dcf6c8bf3cbc452284fce8d304
[ "Net-SNMP", "Xnet" ]
null
null
null
ffsharp/SWScale.cpp
stschake/ffsharp
506de52dde93d3dcf6c8bf3cbc452284fce8d304
[ "Net-SNMP", "Xnet" ]
null
null
null
#include "SWScale.h"
20
20
0.75
stschake
c35a6c50b35a60e49e2399d0445f127faee8b99c
1,309
cpp
C++
main.cpp
NeuronEnix/CSV-Parser
51f6474ea77e76d22f35aa009d53e8805df63d41
[ "MIT" ]
1
2020-11-21T05:27:35.000Z
2020-11-21T05:27:35.000Z
main.cpp
NeuronEnix/CSV-Parser-CPP
51f6474ea77e76d22f35aa009d53e8805df63d41
[ "MIT" ]
null
null
null
main.cpp
NeuronEnix/CSV-Parser-CPP
51f6474ea77e76d22f35aa009d53e8805df63d41
[ "MIT" ]
null
null
null
#include<iostream> #include "CSV_Parser/CSV_Parser.hpp" using namespace std; int main() { CSV_Parser parser = CSV_Parser(); parser.readFromFile( "file.csv" ); // Headers : [ "H0", "H1", "H2", "H3" ] /* Finders */ parser.headerAt( 2 ); // returns: "H2" parser.headerPos( "H3" ); // returns: 3 /* Retrievers */ cout << parser[0][0] << endl; // returns data at row:0, col:0 parser[0][1] = "New Data"; parser[1]["H4"] = "Another New Data"; // Headers : [ "H0", "H1", "H2", "H3" ] /* Modifiers */ parser.swapRow( 1, 5 ); // Data of given two row will be swapped parser.swapCol( "H0", "H1" ); // Headers : [ "H1", "H0", "H2", "H3" ] parser.swapCol( 0, 1 ); // Headers : [ "H0", "H1", "H2", "H3" ] parser.moveCol( "H0", 2 ); // Headers : [ "H2", "H1", "H0", "H3" ] cout << "Position of Header0: " << parser.headerPos( "Header0" ); // output: 0 cout << "\nHeader at 1: " << parser.headerAt( 1 ); // output: Header1 parser.appendCol( "Header3" ); // Adds only header name and the data will have empty string parser.appendCol( "Header4", {"1", "2", "3", } ); // Adds headerName , and 2nd argument will be added as data parser.moveCol( "Header3", 0 ); parser.writeToFile( "new file.csv" ); return 0; }
29.75
114
0.553094
NeuronEnix
c35f43da82f6f7e7e278dd2e889805087fb7c22b
103
cpp
C++
Chapter12/main.cpp
lixin-sxty/BigTalkDesignPatternForCpp
8d766bfd05b9e30c626231bb5719638cd8c8893c
[ "MIT" ]
1
2021-08-29T03:20:08.000Z
2021-08-29T03:20:08.000Z
Chapter12/main.cpp
lixin-sxty/BigTalkDesignPatternForCpp
8d766bfd05b9e30c626231bb5719638cd8c8893c
[ "MIT" ]
null
null
null
Chapter12/main.cpp
lixin-sxty/BigTalkDesignPatternForCpp
8d766bfd05b9e30c626231bb5719638cd8c8893c
[ "MIT" ]
null
null
null
#include <iostream> #include "facade.h" int main() { Fund f; f.Buy(); f.Sell(); return 0; }
8.583333
19
0.553398
lixin-sxty
c35f95c8f53a8420db7fe8a329870bf145d6cf2a
370
cpp
C++
ThreadSanitizer/examples/01_race.cpp
dermojo/presentations
4f4da0e60c144e735c98bb4c77ce7ccb055bd20b
[ "MIT" ]
3
2017-07-07T13:32:28.000Z
2020-01-09T20:33:02.000Z
ThreadSanitizer/examples/01_race.cpp
dermojo/presentations
4f4da0e60c144e735c98bb4c77ce7ccb055bd20b
[ "MIT" ]
null
null
null
ThreadSanitizer/examples/01_race.cpp
dermojo/presentations
4f4da0e60c144e735c98bb4c77ce7ccb055bd20b
[ "MIT" ]
null
null
null
// TSAN example: race condition #include <iostream> #include <thread> static size_t counter = 0; static void run() { for (int i = 0; i < 10000; ++i) { ++counter; } } int main() { std::thread t1([] { run(); }); std::thread t2([] { run(); }); t1.join(); t2.join(); std::cout << "result: " << counter << "\n"; return 0; }
13.214286
47
0.491892
dermojo
c3610798f1258a15dc61894ffbe1f8c8a357441f
1,559
cc
C++
viewer/primitives/box.cc
IJDykeman/experiments-1
22badf166b2ea441e953939463f751020b8c251b
[ "MIT" ]
1
2022-02-28T04:19:34.000Z
2022-02-28T04:19:34.000Z
viewer/primitives/box.cc
IJDykeman/experiments-1
22badf166b2ea441e953939463f751020b8c251b
[ "MIT" ]
null
null
null
viewer/primitives/box.cc
IJDykeman/experiments-1
22badf166b2ea441e953939463f751020b8c251b
[ "MIT" ]
null
null
null
#include "viewer/primitives/box.hh" #include <GL/glew.h> namespace viewer { void Box::draw() const { glBegin(GL_QUADS); // top glColor3f(1.0f, 0.0f, 0.0f); glNormal3f(0.0f, 1.0f, 0.0f); glVertex3f(-0.5f, 0.5f, 0.5f); glVertex3f(0.5f, 0.5f, 0.5f); glVertex3f(0.5f, 0.5f, -0.5f); glVertex3f(-0.5f, 0.5f, -0.5f); glEnd(); glBegin(GL_QUADS); // front glColor3f(0.0f, 1.0f, 0.0f); glNormal3f(0.0f, 0.0f, 1.0f); glVertex3f(0.5f, -0.5f, 0.5f); glVertex3f(0.5f, 0.5f, 0.5f); glVertex3f(-0.5f, 0.5f, 0.5f); glVertex3f(-0.5f, -0.5f, 0.5f); glEnd(); glBegin(GL_QUADS); // right glColor3f(0.0f, 0.0f, 1.0f); glNormal3f(1.0f, 0.0f, 0.0f); glVertex3f(0.5f, 0.5f, -0.5f); glVertex3f(0.5f, 0.5f, 0.5f); glVertex3f(0.5f, -0.5f, 0.5f); glVertex3f(0.5f, -0.5f, -0.5f); glEnd(); glBegin(GL_QUADS); // left glColor3f(0.0f, 0.0f, 0.5f); glNormal3f(-1.0f, 0.0f, 0.0f); glVertex3f(-0.5f, -0.5f, 0.5f); glVertex3f(-0.5f, 0.5f, 0.5f); glVertex3f(-0.5f, 0.5f, -0.5f); glVertex3f(-0.5f, -0.5f, -0.5f); glEnd(); glBegin(GL_QUADS); // bottom glColor3f(0.5f, 0.0f, 0.0f); glNormal3f(0.0f, -1.0f, 0.0f); glVertex3f(0.5f, -0.5f, 0.5f); glVertex3f(-0.5f, -0.5f, 0.5f); glVertex3f(-0.5f, -0.5f, -0.5f); glVertex3f(0.5f, -0.5f, -0.5f); glEnd(); glBegin(GL_QUADS); // back glColor3f(0.0f, 0.5f, 0.0f); glNormal3f(0.0f, 0.0f, -1.0f); glVertex3f(0.5f, 0.5f, -0.5f); glVertex3f(0.5f, -0.5f, -0.5f); glVertex3f(-0.5f, -0.5f, -0.5f); glVertex3f(-0.5f, 0.5f, -0.5f); glEnd(); } }
20.786667
35
0.57601
IJDykeman
c361adc558c2a60d8be83e739296453fb191a6af
654
hpp
C++
lib/data_structure/partial_sum_2D.hpp
atree-GitHub/competitive-library
606b444036530b698a6363b1a41cdaa90a7f9578
[ "CC0-1.0" ]
1
2022-01-25T23:03:10.000Z
2022-01-25T23:03:10.000Z
lib/data_structure/partial_sum_2D.hpp
atree4728/competitive-library
1aaa4d2cf9283b9a1a3d4c7f114ff7b867ca2f8b
[ "CC0-1.0" ]
6
2021-10-06T01:17:04.000Z
2022-01-16T14:45:47.000Z
lib/data_structure/partial_sum_2D.hpp
atree-GitHub/competitive-library
606b444036530b698a6363b1a41cdaa90a7f9578
[ "CC0-1.0" ]
null
null
null
#pragma once #include <vector> template<class T> struct CumSum2D { std::vector<std::vector<T>> data; explicit CumSum2D(const std::vector<std::vector<T>> &a): data(size(a) + 1, std::vector<T>(size(a[0]) + 1, 0)) { for (size_t i = 0; i + 1 < size(data); i++) copy(begin(a[i]), end(a[i]), begin(data[i + 1]) + 1); for (size_t i = 0; i + 1 < size(data); i++) for (size_t j = 0; j + 1 < size(data[i]); j++) data[i + 1][j + 1] += data[i][j + 1] + data[i + 1][j] - data[i][j]; } T operator()(size_t sx, size_t sy, size_t gx, size_t gy) const { return data[gx][gy] - data[sx][gy] - data[gx][sy] + data[sx][sy]; } };
46.714286
136
0.535168
atree-GitHub
c36696b62aed7f90167389514f1366cba58ad8a3
3,928
hh
C++
src/systems/rf_comms/RFComms.hh
Thodoris1999/ign-gazebo
66fa61a1c2b018fa0a4d1080ef89c7cc9d321cea
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/systems/rf_comms/RFComms.hh
Thodoris1999/ign-gazebo
66fa61a1c2b018fa0a4d1080ef89c7cc9d321cea
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/systems/rf_comms/RFComms.hh
Thodoris1999/ign-gazebo
66fa61a1c2b018fa0a4d1080ef89c7cc9d321cea
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2022 Open Source Robotics Foundation * * 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 IGNITION_GAZEBO_SYSTEMS_RFCOMMS_HH_ #define IGNITION_GAZEBO_SYSTEMS_RFCOMMS_HH_ #include <memory> #include <ignition/utils/ImplPtr.hh> #include <sdf/Element.hh> #include "ignition/gazebo/comms/ICommsModel.hh" #include "ignition/gazebo/System.hh" namespace ignition { namespace gazebo { // Inline bracket to help doxygen filtering. inline namespace IGNITION_GAZEBO_VERSION_NAMESPACE { namespace systems { /// \brief A comms model that simulates communication using radio frequency /// (RF) devices. The model uses a log-distance path loss function. /// /// This communication model has been ported from: /// https://github.com/osrf/subt . /// /// This system can be configured with the following SDF parameters: /// /// * Optional parameters: /// <range_config> Element used to capture the range configuration based on a /// log-normal distribution. This block can contain any of the /// next parameters: /// * <max_range>: Hard limit on range (meters). No communication will /// happen beyond this range. Default is 50. /// * <fading_exponent>: Fading exponent used in the normal distribution. /// Default is 2.5. /// * <l0>: Path loss at the reference distance (1 meter) in dBm. /// Default is 40. /// * <sigma>: Standard deviation of the normal distribution. /// Default is 10. /// /// <radio_config> Element used to capture the radio configuration. /// This block can contain any of the /// next parameters: /// * <capacity>: Capacity of radio in bits-per-second. /// Default is 54000000 (54 Mbps). /// * <tx_power>: Transmitter power in dBm. Default is 27dBm (500mW). /// * <noise_floor>: Noise floor in dBm. Default is -90dBm. /// * <modulation>: Supported modulations: ["QPSK"]. Default is "QPSK". /// /// Here's an example: /// <plugin /// filename="ignition-gazebo-rf-comms-system" /// name="ignition::gazebo::systems::RFComms"> /// <range_config> /// <max_range>500000.0</max_range> /// <fading_exponent>1.5</fading_exponent> /// <l0>40</l0> /// <sigma>10.0</sigma> /// </range_config> /// <radio_config> /// <capacity>1000000</capacity> /// <tx_power>20</tx_power> /// <noise_floor>-90</noise_floor> /// <modulation>QPSK</modulation> /// </radio_config> /// </plugin> class RFComms : public comms::ICommsModel { /// \brief Constructor. public: explicit RFComms(); /// \brief Destructor. public: ~RFComms() override = default; // Documentation inherited. public: void Load(const Entity &_entity, std::shared_ptr<const sdf::Element> _sdf, EntityComponentManager &_ecm, EventManager &_eventMgr) override; // Documentation inherited. public: void Step(const ignition::gazebo::UpdateInfo &_info, const comms::Registry &_currentRegistry, comms::Registry &_newRegistry, EntityComponentManager &_ecm) override; /// \brief Private data pointer. IGN_UTILS_UNIQUE_IMPL_PTR(dataPtr) }; } } } } #endif
35.071429
79
0.636202
Thodoris1999
c368efe959a0019419fe40bf0171ec00fa349d8f
410
cpp
C++
brute/add123.cpp
SiverPineValley/algo
29c75c6b226fdb15a3b6695e763ee49d4871094e
[ "Apache-2.0" ]
null
null
null
brute/add123.cpp
SiverPineValley/algo
29c75c6b226fdb15a3b6695e763ee49d4871094e
[ "Apache-2.0" ]
null
null
null
brute/add123.cpp
SiverPineValley/algo
29c75c6b226fdb15a3b6695e763ee49d4871094e
[ "Apache-2.0" ]
null
null
null
// N중 for문 9095 // 10 이하의 양의정수를 1,2,3의 합으로 몇 가지의 경우로 가능한지 나타내는 문제 #include<iostream> using namespace std; int answer = 0; void nfor(int tc) { if(tc < 0) return; else if(tc == 0) { answer++; return; } nfor(tc - 1); nfor(tc - 2); nfor(tc - 3); } int main(void) { int tn; cin >> tn; while(tn) { tn--; int tc; cin >> tc; nfor(tc); cout << answer << "\n" ; answer = 0; } return 0; }
12.058824
49
0.543902
SiverPineValley
c36c67039a34474891efdbe7a43b063673786c4a
1,697
hpp
C++
include/beluga/http/http_status_code.hpp
Stazer/beluga
38232796669524c4f6b08f281e5a367390de24d0
[ "MIT" ]
1
2021-04-16T08:37:37.000Z
2021-04-16T08:37:37.000Z
include/beluga/http/http_status_code.hpp
Stazer/beluga
38232796669524c4f6b08f281e5a367390de24d0
[ "MIT" ]
null
null
null
include/beluga/http/http_status_code.hpp
Stazer/beluga
38232796669524c4f6b08f281e5a367390de24d0
[ "MIT" ]
null
null
null
#pragma once namespace beluga { enum class http_status_code { CONTINUE = 100, SWITCHING_PROTOCOLS = 101, PROCESSING = 102, OK = 200, CREATED = 201, ACCEPTED = 202, NON_AUTHORITATIVE_INFORMATION = 203, NO_CONTENT = 204, RESET_CONTENT = 205, PARTIAL_CONTENT = 206, MULTI_STATUS = 207, ALREADY_REPORTED = 208, IM_USED = 226, MULTIPLE_CHOICES = 300, MOVED_PERMANENTLY = 301, MOVED_TEMPORARILY = 302, SEE_OTHER = 303, NOT_MODIFIED = 304, USE_PROXY = 305, SWITCH_PROXY = 306, TEMPORARY_REDIRECT = 307, PERMANENT_REDIRECT = 308, BAD_REQUEST = 400, UNAUTHORIZED = 401, PAYMENT_REQUIRED = 402, FORBIDDEN = 403, NOT_FOUND = 404, METHOD_NOT_ALLOWED = 405, NOT_ACCEPTABLE = 406, PROXY_AUTHENTICATION_REQUIRED = 407, REQUEST_TIME_OUT = 408, CONFLICT = 409, GONE = 410, LENGTH_REQUIRED = 411, PRECONDITION_FAILED = 412, REQUEST_ENTITY_TOO_LARGE = 413, REQUEST_URL_TO_LONG = 414, UNSUPPORTED_MEDIA_TYPE = 415, REQUESTED_RANGE_NOT_SATISFIABLE = 416, EXPECTATION_FAILED = 417, IM_A_TEAPOT = 418, POLICY_NOT_FULFILLED = 420, MISDIRECTED_REQUEST = 421, UNPROCESSABLE_ENTITY = 422, LOCKED = 423, FAILED_DEPENDENCY = 424, UNORDERED_COLLECTION = 425, UPGRADE_REQUIRED = 426, PRECONDITION_REQUIRED = 428, TOO_MANY_REQUEST = 429, REQUEST_HEADER_FIELDS_TOO_LARGES = 431, UNAVAILABLE_FOR_LEGAL_REASONS = 451, INTERNAL_SERVER_ERROR = 500, NOT_IMPLEMENTED = 501, BAD_GATEWAY = 502, SERVICE_UNAVAILABLE = 503, GATEWAY_TIME_OUT = 504, HTTP_VERSION_NOT_SUPPORTED = 505, VARIANT_ALSO_NEGOTIATES = 506, INSUFFICIENT_STORAGE = 507, LOOP_DETECTED = 508, BANDWIDTH_LIMIT_EXCEEDED = 509, NOT_EXTENDED = 510, NETWORK_AUTHENTICATION_REQUIRED = 511, }; }
22.038961
40
0.753094
Stazer
c36d9f9fb47f80e792690e402a995eba54b3f0fe
3,618
cpp
C++
src/mxSingleton.cpp
stahta01/Zinjal
8d1e52c9eab5cde9f7cb96c99a0fbdf97904da42
[ "OML" ]
1
2019-03-24T00:58:59.000Z
2019-03-24T00:58:59.000Z
src/mxSingleton.cpp
stahta01/Zinjal
8d1e52c9eab5cde9f7cb96c99a0fbdf97904da42
[ "OML" ]
null
null
null
src/mxSingleton.cpp
stahta01/Zinjal
8d1e52c9eab5cde9f7cb96c99a0fbdf97904da42
[ "OML" ]
null
null
null
#include <iostream> using namespace std; #include "mxSingleton.h" #include "ConfigManager.h" #include "mxMainWindow.h" BEGIN_EVENT_TABLE(mxSingleton,wxEvtHandler) EVT_SOCKET(wxID_ANY,mxSingleton::OnSocket) END_EVENT_TABLE() mxSingleton *g_singleton=nullptr; mxSingleton::mxSingleton():m_server(nullptr) { m_calls_count=0; m_data=nullptr; m_gid=0; m_ready=false; } mxSingleton::~mxSingleton() { if (m_server) m_server->Destroy(); if (m_data) free(m_data); } bool mxSingleton::Start() { wxIPV4address adrs; adrs.Hostname(_T("127.0.0.1")); // esta linea era el problema por el cual no se aceptaban conexiones externas adrs.Service(config->Init.zinjai_server_port+1); m_server = new wxSocketServer(adrs); m_server->SetEventHandler(*this, wxID_ANY); m_server->SetNotify(wxSOCKET_CONNECTION_FLAG); m_server->Notify(true); if (!m_server->IsOk()) { delete m_server; m_server=nullptr; } return m_server!=nullptr; } bool mxSingleton::RemoteOpen(wxString fname) { wxIPV4address adrs; adrs.Hostname(_T("127.0.0.1")); adrs.Service(config->Init.zinjai_server_port+1); wxSocketClient *client = new wxSocketClient(wxSOCKET_WAITALL); client->SetEventHandler(*this, wxID_ANY); if (client->Connect(adrs,true)) { fname<<"\n"; client->Write(fname.c_str(),fname.Len()); client->Close(); delete client; return true; } else { delete client; return false; } } void mxSingleton::LocalOpen(wxString fname) { if (!m_ready) { m_to_open.Add(fname); } else { main_window->OpenFileFromGui(fname); main_window->Raise(); } } void mxSingleton::ProcessToOpenQueue() { m_ready = true; int n = m_to_open.GetCount(); if (!n) return; for(int i=0;i<n;i++) { main_window->OpenFileFromGui(m_to_open[i]); } m_to_open.Clear(); main_window->Raise(); } void mxSingleton::Stop() { if (m_server) delete m_server; m_server=nullptr; } void mxSingleton::OnSocket(wxSocketEvent &evt) { wxSocketBase *who = evt.GetSocket(); wxSocketNotify what = evt.GetSocketEvent(); if (who==m_server) { wxSocketBase *sock = m_server->Accept(false); if (m_data) { if (m_calls_count+1==m_max_count) { m_max_count*=2; // cppcheck-suppress memleakOnRealloc m_data = (singleton_data*)realloc(m_data,sizeof(singleton_data)*m_max_count); } } else { m_max_count=10; m_data = (singleton_data*)malloc(sizeof(singleton_data)*m_max_count); } m_data[m_calls_count].socket=sock; m_data[m_calls_count].data=new wxString; m_data[m_calls_count].id=++m_gid; m_calls_count++; sock->SetEventHandler(*this, wxID_ANY); sock->SetNotify(wxSOCKET_LOST_FLAG|wxSOCKET_INPUT_FLAG); sock->Notify(true); } else { int cnum=0; // buscar cual llamada es while (cnum<m_calls_count && m_data[cnum].socket!=who) cnum++; if (cnum==m_calls_count) return; if (what==wxSOCKET_INPUT) { wxString mdat=(*m_data[cnum].data); int mid = m_data[cnum].id; static char buf[256]; who->Read(buf,255); int lc = who->LastCount(); if (lc) { buf[lc]='\0'; mdat<<buf; } while (mdat.Contains("\n")) { wxString fname = mdat.BeforeFirst('\n'); mdat = mdat.AfterFirst('\n'); if (fname.Last()=='\r') fname.RemoveLast(); LocalOpen(fname); } // en el idle del openfromgui puede haber procesado el lost y borrado el data if (mid==m_data[cnum].id) (*m_data[cnum].data)=mdat; } else if (what==wxSOCKET_LOST) { delete m_data[cnum].data; m_data[cnum].id=0; m_calls_count--; if (cnum!=m_calls_count && m_calls_count) { m_data[cnum]=m_data[m_calls_count]; } delete who; } } } bool mxSingleton::IsRunning() { return m_server!=nullptr; }
25.478873
110
0.698176
stahta01
c37af6c0529123d3776dcf7e66e56eeb603fb002
1,665
cpp
C++
dlls/haj/haj_deployzone.cpp
steveuk/ham-and-jam
25121bf6302d81e68207706ae5c313c0c84ffc78
[ "MIT" ]
null
null
null
dlls/haj/haj_deployzone.cpp
steveuk/ham-and-jam
25121bf6302d81e68207706ae5c313c0c84ffc78
[ "MIT" ]
null
null
null
dlls/haj/haj_deployzone.cpp
steveuk/ham-and-jam
25121bf6302d81e68207706ae5c313c0c84ffc78
[ "MIT" ]
null
null
null
#include "cbase.h" #include "triggers.h" #include "haj_player.h" #include "haj_deployzone.h" LINK_ENTITY_TO_CLASS( haj_deployzone, CDeployZone ); BEGIN_DATADESC( CDeployZone ) DEFINE_KEYFIELD( m_iStance, FIELD_INTEGER, "stance" ), DEFINE_KEYFIELD( m_fAngleMax, FIELD_FLOAT, "angle_tolerance" ), DEFINE_KEYFIELD( m_iTeamFilter, FIELD_INTEGER, "team_filter" ), END_DATADESC() void CDeployZone::Spawn() { Msg( "Spawned deploy zone...\n" ); BaseClass::Spawn(); QAngle pAngles = GetAbsAngles(); m_fMinYaw = AngleNormalizePositive( pAngles[ YAW ] - m_fAngleMax ); m_fMaxYaw = AngleNormalizePositive( pAngles[ YAW ] + m_fAngleMax ); Msg( "Yaw is %f (max %f) - %f / %f\n", pAngles[ YAW ], m_fAngleMax, m_fMinYaw, m_fMaxYaw ); SetSolid(SOLID_VPHYSICS); SetSolidFlags(FSOLID_NOT_SOLID|FSOLID_TRIGGER); const char* szModelName = STRING(GetModelName()); SetModel(szModelName); SetRenderMode(kRenderNone); } void CDeployZone::StartTouch(CBaseEntity *pOther) { CHajPlayer *pPlayer = ToHajPlayer( pOther ); if( pPlayer && pPlayer->IsPlayer() && pPlayer->IsAlive() && !pPlayer->IsObserver() ) { if( m_iTeamFilter > 0 && pPlayer->GetTeamNumber() != m_iTeamFilter ) return; DevMsg( "%s entered deploy zone", pPlayer->GetPlayerName() ); pPlayer->SetDeployZone( true, m_iStance ); } BaseClass::StartTouch( pOther ); } void CDeployZone::EndTouch(CBaseEntity *pOther) { CHajPlayer *pPlayer = ToHajPlayer( pOther ); if( pPlayer && pPlayer->IsPlayer() && pPlayer->IsAlive() && !pPlayer->IsObserver() ) { DevMsg( "%s left deploy zone", pPlayer->GetPlayerName() ); pPlayer->SetDeployZone( false, 0 ); } BaseClass::EndTouch( pOther ); }
27.295082
92
0.714715
steveuk
c37fdb72b1c46c776d6fb8b333ed290761297b3f
48
cpp
C++
c-src/fl_utf8C.cpp
ericu/fltkhs
3ca521ca30d51a84f8ec87938932f2ce5af8a7c0
[ "MIT" ]
222
2015-01-11T19:01:16.000Z
2022-03-25T14:47:26.000Z
c-src/fl_utf8C.cpp
ericu/fltkhs
3ca521ca30d51a84f8ec87938932f2ce5af8a7c0
[ "MIT" ]
143
2015-01-13T19:08:33.000Z
2021-10-10T20:43:46.000Z
c-src/fl_utf8C.cpp
ericu/fltkhs
3ca521ca30d51a84f8ec87938932f2ce5af8a7c0
[ "MIT" ]
36
2015-01-14T15:30:18.000Z
2021-08-11T13:04:28.000Z
#ifdef __cplusplus #include "fl_utf8C.h" #endif
12
21
0.770833
ericu
c38e83d25a4dcc8241691b845d61c3076723f480
1,993
hpp
C++
examples/cli.hpp
bytemaster/Boost.RPC
a27795d37481fb5d53774cc8cf4270fff1f84964
[ "Unlicense" ]
23
2015-03-31T05:54:47.000Z
2022-02-27T14:30:16.000Z
examples/cli.hpp
bytemaster/Boost.RPC
a27795d37481fb5d53774cc8cf4270fff1f84964
[ "Unlicense" ]
null
null
null
examples/cli.hpp
bytemaster/Boost.RPC
a27795d37481fb5d53774cc8cf4270fff1f84964
[ "Unlicense" ]
13
2015-04-22T04:32:26.000Z
2019-08-29T13:22:21.000Z
#ifndef _BOOST_IDL_CLI_HPP_ #define _BOOST_IDL_CLI_HPP_ #include <sstream> #include <iomanip> #include <iostream> #include <boost/fusion/sequence/io.hpp> #include <boost/reflect/reflect.hpp> #include <boost/utility/result_of.hpp> /** * Takes any interface object and provides a command line interface for it. */ class cli { public: template<typename T> cli( T aptr) { boost::reflect::visit( aptr, visitor<typename T::vtable_type>( *this, *aptr) ); } boost::function<std::string(const std::string&)>& operator[]( const std::string& name ) { return methods[name]; } private: template<typename VTableType> struct visitor { visitor( cli& c, VTableType& vtbl ):m_cli(c),m_vtbl(vtbl){} template<typename M, typename InterfaceName, M InterfaceName::*m> void operator()( const char* name ) const { std::cerr << std::setw(10) << std::setiosflags(std::ios::left) << name << " " << boost::reflect::get_typename<typename M::signature>() << (M::is_const ? "const" : "") <<std::endl; m_cli.methods[name] = cli_functor<typename M::fused_params, M&>(m_vtbl.*m); } VTableType& m_vtbl; cli& m_cli; }; template<typename Seq, typename Functor> struct cli_functor { cli_functor( Functor f ) :m_func(f){} typedef typename boost::remove_reference<Functor>::type functor_type; std::string operator()( const std::string& cli ) { std::stringstream ss(cli); Seq s; ss >> boost::fusion::tuple_delimiter(',') >> s; std::stringstream rtn; rtn << m_func(s); return rtn.str(); } Functor m_func; }; std::map<std::string, boost::function<std::string(const std::string&)> > methods; }; #endif
32.672131
95
0.558956
bytemaster
c39117e12e132a9b59ca358bca3a57e1d2ffd97c
1,210
cpp
C++
HW1/task03-appox-occurrences/main.cpp
ulyanin/Bioinformatics2019
b28d9b2ad8a1c41ec9c6ba655cd0aca5a1984662
[ "MIT" ]
null
null
null
HW1/task03-appox-occurrences/main.cpp
ulyanin/Bioinformatics2019
b28d9b2ad8a1c41ec9c6ba655cd0aca5a1984662
[ "MIT" ]
null
null
null
HW1/task03-appox-occurrences/main.cpp
ulyanin/Bioinformatics2019
b28d9b2ad8a1c41ec9c6ba655cd0aca5a1984662
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <cassert> #include <fstream> #include <unordered_set> template <class C> void PrintCollection(const C& collection, std::ostream& os = std::cout) { for (const auto& elem : collection) { os << elem << " "; } os << std::endl; } size_t HammingDistance(std::string_view a, std::string_view b) { assert(a.length() == b.length()); size_t dist = 0; for (size_t i = 0; i < a.length(); ++i) { dist += (a[i] != b[i]); } return dist; } int main() { #ifdef ULYANIN freopen("test.txt", "r", stdin); #endif std::ofstream outFile("answer.txt"); std::string t; std::string s; size_t d; assert(std::cin >> t >> s >> d); std::cout << t << " " << s << " " << d << std::endl; size_t n = s.length(); size_t m = t.length(); assert(n >= d); assert(n >= m); std::vector<size_t> approximateOccurrences; for (size_t i = 0; i < n - m; ++i) { if (HammingDistance(t, s.substr(i, m)) <= d) { approximateOccurrences.push_back(i); } } PrintCollection(approximateOccurrences, std::cout); PrintCollection(approximateOccurrences, outFile); return 0; }
25.208333
73
0.566942
ulyanin
c392a1517b49d4e316119887e8b805cb7d78418c
852
cpp
C++
soj/2509.cpp
huangshenno1/project_euler
8a3c91fd11bcb6a6a830e963b1d5aed3f5ff787d
[ "MIT" ]
null
null
null
soj/2509.cpp
huangshenno1/project_euler
8a3c91fd11bcb6a6a830e963b1d5aed3f5ff787d
[ "MIT" ]
null
null
null
soj/2509.cpp
huangshenno1/project_euler
8a3c91fd11bcb6a6a830e963b1d5aed3f5ff787d
[ "MIT" ]
null
null
null
#include <cstdio> #include <cstring> #include <cctype> #include <cstdlib> #include <ctime> #include <climits> #include <cmath> #include <iostream> #include <string> #include <vector> #include <set> #include <map> #include <list> #include <queue> #include <stack> #include <deque> #include <algorithm> using namespace std; const int maxn = 25010; int n,t,ans; struct Cow {     int a,b;     bool operator < (const Cow &o) const     {         return min(b,o.a) > min(o.b,a);     } }cow[maxn]; int main() {     while (scanf("%d",&n)==1)     {         for (int i=0;i<n;i++) scanf("%d%d",&cow[i].a,&cow[i].b);         sort(cow,cow+n);         ans=0; t=0;         for (int i=0;i<n;i++)         {             ans+=cow[i].a;             t=max(0,t-cow[i].a);             t+=cow[i].b;         }         ans+=t;         printf("%d\n",ans);     }     return 0; }
17.387755
64
0.523474
huangshenno1
c392daa8e5e36f5c8222498c5c292a939df14f58
1,560
cpp
C++
User_plugins/userapp_plugin.cpp
GreatCong/GUI_EC_PluginSrc
9194e67b76f3707f782f1fc17ba6e6dcb712c2a5
[ "MIT" ]
1
2019-12-25T13:36:01.000Z
2019-12-25T13:36:01.000Z
User_plugins/userapp_plugin.cpp
GreatCong/GUI_EC_PluginSrc
9194e67b76f3707f782f1fc17ba6e6dcb712c2a5
[ "MIT" ]
null
null
null
User_plugins/userapp_plugin.cpp
GreatCong/GUI_EC_PluginSrc
9194e67b76f3707f782f1fc17ba6e6dcb712c2a5
[ "MIT" ]
1
2020-08-05T14:05:15.000Z
2020-08-05T14:05:15.000Z
#include "userapp_plugin.h" #include <QGridLayout> #include <QPushButton> UserApp_plugin::UserApp_plugin(QObject *parent) : QObject(parent),EtherCAT_UserApp() { //NOTE:如果要设置图标,在这个位置设置 this->set_AppName("User_App example"); // QPixmap pixmap(":/Controls/Resource/Control/App_icon.png"); // this->set_AppIcon(QIcon(pixmap)); } bool UserApp_plugin::Init_Object() { m_userWidget = new Form_plot(); m_msg = new MyMessageObj(); set_UIWidgetPtr(m_userWidget); set_CallbackPtr(nullptr); set_MessageObj(m_msg); return true; } EtherCAT_UserApp *UserApp_plugin::get_NewAppPtr(QObject *parent) { return new UserApp_plugin(parent); } void UserApp_plugin::sig_msgTest(int data) { if(data == 1){ m_userWidget->getTimerPtr()->start(1000); } else if(data == 0){ m_userWidget->getTimerPtr()->stop(); } } UserApp_plugin::~UserApp_plugin(){ //NOTE:用get_UIWidgetPtr函数,不能用user_form_controlTab这样的 if(this->get_UIWidgetPtr()){ delete this->get_UIWidgetPtr(); } if(this->get_CallbackPtr()){ delete this->get_CallbackPtr(); } if(this->get_MessageObj()){ delete this->get_MessageObj(); } } bool UserApp_plugin::Init_Cores() { connect(m_msg,SIGNAL(sig_x(int)),this,SLOT(sig_msgTest(int))); return true; } bool UserApp_plugin::Destroy_Cores() { return true; } #if QT_VERSION < 0x050000 Q_EXPORT_PLUGIN2(User_plugins, UserApp_plugin) #endif // QT_VERSION < 0x050000
21.971831
67
0.655128
GreatCong
c399c876fde68b819c1a5810ab342c96fd2a64ff
5,662
cpp
C++
lib/io/src/plain.cpp
solosTec/cyng
3862a6b7a2b536d1f00fef20700e64170772dcff
[ "MIT" ]
null
null
null
lib/io/src/plain.cpp
solosTec/cyng
3862a6b7a2b536d1f00fef20700e64170772dcff
[ "MIT" ]
null
null
null
lib/io/src/plain.cpp
solosTec/cyng
3862a6b7a2b536d1f00fef20700e64170772dcff
[ "MIT" ]
null
null
null
/* * The MIT License (MIT) * * Copyright (c) 2017 Sylko Olzscher * */ #include <cyng/io/serializer/plain.hpp> #include <cyng/io/serializer.h> #include <cyng/object.h> #include <algorithm> #include <boost/io/ios_state.hpp> namespace cyng { namespace io { std::ostream& serializer <tuple_t, SERIALIZE_PLAIN>::write(std::ostream& os, tuple_t const& v) { os << '{'; // serialize each element from the tuple bool init = false; std::for_each(v.begin(), v.end(), [&os, &init](object const& obj){ if (!init) { init = true; } else { os << ","; } serialize_plain(os, obj); }); os << '}'; return os; } std::ostream& serializer <vector_t, SERIALIZE_PLAIN>::write(std::ostream& os, vector_t const& v) { os << '['; // serialize each element from the tuple bool init = false; std::for_each(v.begin(), v.end(), [&os, &init](object const& obj){ if (!init) { init = true; } else { os << ","; } serialize_plain(os, obj); }); os << ']'; return os; } std::ostream& serializer <set_t, SERIALIZE_PLAIN>::write(std::ostream& os, set_t const& v) { os << '<'; // serialize each element from the tuple bool init = false; std::for_each(v.begin(), v.end(), [&os, &init](object const& obj){ if (!init) { init = true; } else { os << ","; } serialize_plain(os, obj); }); os << '>'; return os; } std::ostream& serializer <attr_map_t, SERIALIZE_PLAIN>::write(std::ostream& os, attr_map_t const& v) { os << '#' << '('; bool flag = false; std::for_each(v.begin() , v.end() , [&flag, &os](attr_map_t::value_type const& attr) { if (flag) { os << ','; } else { flag = true; } os << '(' << attr.first << ':'; serialize_plain(os, attr.second); os << ')'; }); os << ')'; return os; } std::ostream& serializer <param_map_t, SERIALIZE_PLAIN>::write(std::ostream& os, param_map_t const& v) { bool flag = false; os << '%' << '('; std::for_each(v.begin() , v.end() , [&flag, &os](param_map_t::value_type const& param) { if (flag) { os << ','; } else { flag = true; } os << '(' << '"' << param.first << '"' << ':'; serialize_plain(os, param.second); os << ')'; }); os << ')'; return os; } std::ostream& serializer <color_8, SERIALIZE_PLAIN>::write(std::ostream& os, color_8 const& v) { os << "color-8"; return os; } std::ostream& serializer <color_16, SERIALIZE_PLAIN>::write(std::ostream& os, color_16 const& v) { os << "color-16"; return os; } std::ostream& serializer <bool, SERIALIZE_PLAIN>::write(std::ostream& os, bool v) { boost::io::ios_flags_saver ifs(os); os << std::boolalpha << v; return os; } std::ostream& serializer <buffer_t, SERIALIZE_PLAIN>::write(std::ostream& os, buffer_t const& v) { constexpr char hexa[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; for (const char c : v) { os << hexa[(c & 0xf0) >> 4] << hexa[(c & 0x0f)] ; } return os; } std::ostream& serializer <boost::uuids::uuid, SERIALIZE_PLAIN>::write(std::ostream& os, boost::uuids::uuid const& v) { // store and reset stream state boost::io::ios_flags_saver ifs(os); os << std::hex << std::setfill('0') ; // // format xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx // 36 characters std::size_t pos = 0; std::for_each(v.begin(), v.end(), [&os, &pos](char c) { os << std::setw(2) << (+c & 0xFF) // promote to integer ; ++pos; if (pos == 4 || pos == 6 || pos == 8 || pos == 10) { os << '-'; } }); return os; } std::ostream& serializer <std::string, SERIALIZE_PLAIN>::write(std::ostream& os, std::string const& v) { // // To serialize with escaped values use tag SERIALIZE_TYPED // os << v; return os; } std::ostream& serializer <std::int8_t, SERIALIZE_PLAIN>::write(std::ostream& os, std::int8_t v) { // store and reset stream state boost::io::ios_flags_saver ifs(os); os << std::dec << std::setfill('0') << +v ; return os; } std::ostream& serializer <std::uint8_t, SERIALIZE_PLAIN>::write(std::ostream& os, std::uint8_t v) { // store and reset stream state boost::io::ios_flags_saver ifs(os); os << std::hex << std::setfill('0') << +v ; return os; } std::ostream& serializer <std::uint16_t, SERIALIZE_PLAIN>::write(std::ostream& os, std::uint16_t v) { // store and reset stream state boost::io::ios_flags_saver ifs(os); os << std::hex << std::setfill('0') << std::setw(4) << v ; return os; } std::ostream& serializer <std::uint32_t, SERIALIZE_PLAIN>::write(std::ostream& os, std::uint32_t v) { // store and reset stream state boost::io::ios_flags_saver ifs(os); os << std::hex << std::setfill('0') << std::setw(8) << v ; return os; } std::ostream& serializer_custom<SERIALIZE_PLAIN>::write(std::ostream& os, std::size_t tag, std::string const& type_name, object const& obj) { os << "<!" << tag << ':' << type_name << '>' ; return os; } } }
20.816176
142
0.512363
solosTec
c39ae9639f7d2c74a5adba6d8d9fe5fcd1d0e0aa
10,276
cpp
C++
examples/example-matrices.cpp
kirchnerlab/libpipe
28f08b9399945bd13329937a9dd0691211826886
[ "MIT" ]
1
2018-11-08T13:41:18.000Z
2018-11-08T13:41:18.000Z
examples/example-matrices.cpp
kirchnerlab/libpipe
28f08b9399945bd13329937a9dd0691211826886
[ "MIT" ]
null
null
null
examples/example-matrices.cpp
kirchnerlab/libpipe
28f08b9399945bd13329937a9dd0691211826886
[ "MIT" ]
null
null
null
/* * example-rtc.cpp * * Copyright (c) 2010 Marc Kirchner * 2011 David Sichau * */ #include <libpipe/config.hpp> #include <stdlib.h> #include <exception> #include <iostream> #include <set> #include <boost/pointer_cast.hpp> #include <boost/shared_ptr.hpp> #include <boost/make_shared.hpp> #include <libpipe/rtc/Algorithm.hpp> #include <libpipe/rtc/Filter.hpp> #include <libpipe/rtc/Manager.hpp> #include <libpipe/rtc/ManagerFactory.hpp> #include <libpipe/rtc/AlgorithmFactory.hpp> #include <libpipe/utilities/Exception.hpp> #include <libpipe/Request.hpp> #include <libpipe/rtc/SharedData.hpp> #include <libpipe/rtc/PipelineLoader.hpp> #include "walltime.h" int MATRIX_SIZE = 100; /** Simple Matrix Multiplication Algorithm Example. */ class MatrixMulAlgorithm : public libpipe::rtc::Algorithm { public: // use convenience typedefs to avoid cluttering up the code typedef std::vector<double> Doubles; typedef libpipe::rtc::SharedData<Doubles> SharedDoubles; /** Virtual constructor. * @return Base class pointer to a new \c MatrixMulAlgorithm object. */ static Algorithm* create() { return new MatrixMulAlgorithm; } /** Destructor. */ virtual ~MatrixMulAlgorithm() { } /** Executes the algorithm and updates the output data. * This is where the algorithm implementation needs to go. * @param[in,out] req The request object, forwarded from \c process request. */ void update(libpipe::Request& req) { // Take note of what we are doing LIBPIPE_PIPELINE_TRACE("MatrixMulAlgorithm::update: start."); // Gain access to the in- and output LIBPIPE_PREPARE_READ_ACCESS(input1_, tempIn1, Doubles, "MatrixIn1"); LIBPIPE_PREPARE_READ_ACCESS(input2_, tempIn2, Doubles, "MatrixIn2"); LIBPIPE_PREPARE_WRITE_ACCESS(output_, tempOut, Doubles, "MatrixOut"); // Again, log what is happening LIBPIPE_PIPELINE_TRACE( "MatrixMulAlgorithm::update: multiplication of two matrices."); // Let's roll. This is O(N^2). for (int i = 0; i < MATRIX_SIZE; i++) { for (int j = 0; j < MATRIX_SIZE; j++) { double sum = 0; for (int k = 0; k < MATRIX_SIZE; k++) { sum += tempIn1[i * MATRIX_SIZE + k] * tempIn2[k * MATRIX_SIZE + j]; } tempOut[i * MATRIX_SIZE + j] = sum / MATRIX_SIZE; } } LIBPIPE_CLEAR_ACCESS(output_); LIBPIPE_CLEAR_ACCESS(input1_); LIBPIPE_CLEAR_ACCESS(input2_); // And tell the world that we are done. LIBPIPE_PIPELINE_TRACE("MatrixMulAlgorithm::update: end."); } protected: /** Constructor. * Make sure to call the \c libpipe::rtc::Algorithm constructor. */ MatrixMulAlgorithm() : libpipe::rtc::Algorithm() { ports_["MatrixIn1"] = boost::make_shared<SharedDoubles>(); ports_["MatrixIn2"] = boost::make_shared<SharedDoubles>(); ports_["MatrixOut"] = boost::make_shared<SharedDoubles>( new Doubles(MATRIX_SIZE * MATRIX_SIZE)); } private: /** Registers the Algorithm with the factory. * @return A boolean that indicates if the registration was successful */ static const bool registerLoader() { std::string ids = "MatrixMulAlgorithm"; return libpipe::rtc::AlgorithmFactory::instance().registerType(ids, MatrixMulAlgorithm::create); } /// if true then class is registered w/ Algorithm Factory static const bool registered_; }; const bool MatrixMulAlgorithm::registered_ = MatrixMulAlgorithm::registerLoader(); /** Provides a constant matrix as output. * This is an example of a 'source': the \c Source algorithm does not require * any input and will always provide a predefined matrix on its output port. */ class Source : public libpipe::rtc::Algorithm { public: // use convenience typedefs to avoid cluttering up the code typedef std::vector<double> Doubles; typedef libpipe::rtc::SharedData<Doubles> SharedDoubles; static Algorithm* create() { return new Source; } /** Destructor. */ virtual ~Source() { } /** Updates the output data (i.e. does nothing). * The output is provided as a constant, hence there is nothing to do. * @param[in] req The request object. */ void update(libpipe::Request& req) { LIBPIPE_PIPELINE_TRACE("Source::update: start."); LIBPIPE_PREPARE_WRITE_ACCESS(output_, tempOut, Doubles, "MatrixOut"); // fill matrix with some values LIBPIPE_PIPELINE_TRACE("Source::update: filling matrix."); for (int row = 0; row < MATRIX_SIZE; row++) { for (int col = 0; col < MATRIX_SIZE; col++) { tempOut[col + (row * MATRIX_SIZE)] = col + row; } } LIBPIPE_CLEAR_ACCESS(output_) LIBPIPE_PIPELINE_TRACE("Source::update: end."); } private: /** Constructor. */ Source() : libpipe::rtc::Algorithm() { ports_["MatrixOut"] = boost::make_shared<SharedDoubles>( new Doubles(MATRIX_SIZE * MATRIX_SIZE)); } /** registers the Algorithm in the factory * @return true is registration was successful */ static const bool registerLoader() { std::string ids = "Source"; return libpipe::rtc::AlgorithmFactory::instance().registerType(ids, Source::create); } /// true is class is registered in Algorithm Factory static const bool registered_; }; const bool Source::registered_ = Source::registerLoader(); /** Prints the Matrix */ class Printer : public libpipe::rtc::Algorithm { public: // use convenience typedefs to avoid cluttering up the code typedef std::vector<double> Doubles; typedef libpipe::rtc::SharedData<Doubles> SharedDoubles; static Algorithm* create() { return new Printer; } /** Destructor. */ virtual ~Printer() { } /** Updates the output data (i.e. does nothing). * The output is provided as a constant, hence there is nothing to do. * @param[in] req The request object. */ void update(libpipe::Request& req) { LIBPIPE_PIPELINE_TRACE( "Printer::update: start."); // Gain access to the in- and output LIBPIPE_PREPARE_READ_ACCESS(input_, in, Doubles, "MatrixIn"); LIBPIPE_PIPELINE_TRACE("printing matrix"); // print the matrix for (int row = 0; row < MATRIX_SIZE; row++) { for (int col = 0; col < MATRIX_SIZE; col++) { std::cout << in[col + (row * MATRIX_SIZE)] << " "; } std::cout << '\n'; } std::cout << '\n' << std::endl; LIBPIPE_CLEAR_ACCESS(input_); LIBPIPE_PIPELINE_TRACE("Printer::update: end."); } protected: private: /** Constructor. */ Printer() : libpipe::rtc::Algorithm() { ports_["MatrixIn"] = boost::make_shared<SharedDoubles>(); } /** registers the Algorithm in the factory * @return true is registration was successful */ static const bool registerLoader() { std::string ids = "Printer"; return libpipe::rtc::AlgorithmFactory::instance().registerType(ids, Printer::create); } /// true is class is registered in Algorithm Factory static const bool registered_; }; const bool Printer::registered_ = Printer::registerLoader(); /** Handles the several Algorithms so that they can be executed in parallel, * as the Pipeline will execute them in sequential order. */ class Handler : public libpipe::rtc::Algorithm { public: static Algorithm* create() { return new Handler; } /** Destructor. */ virtual ~Handler() { } /** Does nothing. * The output is provided as a constant, hence there is nothing to do. * @param[in] req The request object. */ void update(libpipe::Request& req) { LIBPIPE_PIPELINE_TRACE("start handler"); } protected: private: /** Constructor. */ Handler() : libpipe::rtc::Algorithm() { } /** registers the Algorithm in the factory * @return true is registration was successful */ static const bool registerLoader() { std::string ids = "Handler"; return libpipe::rtc::AlgorithmFactory::instance().registerType(ids, Handler::create); } /// true is class is registered in Algorithm Factory static const bool registered_; }; const bool Handler::registered_ = registerLoader(); int main(int argc, char *argv[]) { using namespace libpipe::rtc; if (argc == 2) { MATRIX_SIZE = atoi(argv[1]); } else { std::cerr << "usage: ./example-matrices MATRIX_SIZE[int]" << std::endl; exit(1); } std::cout << "Matrix Size: " << MATRIX_SIZE << std::endl; std::map < std::string, std::string > inputFiles; inputFiles["FilterInput"] = "inputFileFilterJSONMatrix.txt"; inputFiles["ConnectionInput"] = "inputFileConnectionJSONMatrix.txt"; inputFiles["PipelineInput"] = "inputFilePipelineJSONMatrix.txt"; inputFiles["ParameterInput"] = "inputFileParametersJSONMatrix.txt"; Pipeline pipeline; try { PipelineLoader loader(inputFiles); pipeline = loader.getPipeline(); } catch (libpipe::utilities::Exception& e) { std::cerr << e.what() << std::endl; } double time, time_start = 0.0; time = walltime(&time_start); try { pipeline.run(); } catch (libpipe::utilities::Exception& e) { std::cerr << e.what() << std::endl; } time = walltime(&time); std::cout << time << " sec" << std::endl; std::vector < std::string > trace; trace = pipeline.getTrace(); for (std::vector<std::string>::const_iterator i = trace.begin(); i != trace.end(); ++i) { std::cout << *i << '\n'; } std::cout << "All output after this is due to automatically called destructors." << std::endl; return EXIT_SUCCESS; }
27.549598
82
0.617653
kirchnerlab
c39c2e3f8e5f6065ff3aa241d03e0908aca052aa
947
hpp
C++
tools/ktx_export/options.hpp
kevin-lesenechal/glare
774fb6bcd40349ac5a7b9155b97d1dd995b3b5d1
[ "MIT" ]
null
null
null
tools/ktx_export/options.hpp
kevin-lesenechal/glare
774fb6bcd40349ac5a7b9155b97d1dd995b3b5d1
[ "MIT" ]
null
null
null
tools/ktx_export/options.hpp
kevin-lesenechal/glare
774fb6bcd40349ac5a7b9155b97d1dd995b3b5d1
[ "MIT" ]
null
null
null
/****************************************************************************** * Copyright © 2020 Kévin Lesénéchal <kevin.lesenechal@gmail.com> * * * * This file is part of the GLARE project, published under the terms of the * * MIT license; see LICENSE file for more information. * ******************************************************************************/ #include <vector> #include <string> #include <filesystem> struct AppOptions { enum class MergeType { Flat, Faces, Array }; std::vector<std::string> input_files; std::filesystem::path output_file; std::string format; MergeType merge_type = MergeType::Flat; bool make_mipmaps = true; bool y_down = false; bool flip_image = true; }; AppOptions parse_options(int argc, char** argv);
31.566667
80
0.461457
kevin-lesenechal
c3a1bc733f8b074bab9228f731cb174ac145b7a4
8,330
cpp
C++
slackbot/SlackClient.cpp
mogemimi/daily-snippets
d9da3db8c62538e4a37f0f6b69c5d46d55c4225f
[ "MIT" ]
14
2017-06-16T22:52:38.000Z
2022-02-14T04:11:06.000Z
slackbot/SlackClient.cpp
mogemimi/daily-snippets
d9da3db8c62538e4a37f0f6b69c5d46d55c4225f
[ "MIT" ]
2
2016-03-13T14:50:04.000Z
2019-04-01T09:53:17.000Z
slackbot/SlackClient.cpp
mogemimi/daily-snippets
d9da3db8c62538e4a37f0f6b69c5d46d55c4225f
[ "MIT" ]
2
2016-03-13T14:05:17.000Z
2018-09-18T01:28:42.000Z
// Copyright (c) 2015 mogemimi. Distributed under the MIT license. #include "SlackClient.h" #include "HttpUtility.h" #include <rapidjson/document.h> #include <cstdint> #include <sstream> #include <utility> namespace somera { namespace { void fromJson(std::string& output, const rapidjson::Value& value) { if (value.IsString()) { output = value.GetString(); } } void fromJson(int& output, const rapidjson::Value& value) { if (value.IsInt()) { output = value.GetInt(); } } void fromJson(bool& output, const rapidjson::Value& value) { if (value.IsBool()) { output = value.GetBool(); } } template <typename T> void fromJsonMember(T& output, const std::string& name, const rapidjson::Value& object) { assert(object.IsObject()); assert(!name.empty()); if (object.HasMember(name.c_str())) { fromJson(output, object[name.c_str()]); } } template <typename Container, typename Func, typename T> auto find(const Container& container, Func thunk, const T& value) -> typename Container::const_iterator { return std::find_if(std::begin(container), std::end(container), [&](const typename Container::value_type& v) { return thunk(v) == value; }); } } // namespace SlackClient::SlackClient(const std::string& tokenIn) : token(tokenIn) { http.setTimeout(std::chrono::seconds(60)); } void SlackClient::login() { // NOTE: Please see https://api.slack.com/methods/channels.list apiCall("channels.list", {}, [this](const std::string& json) { rapidjson::Document doc; doc.Parse(json.c_str()); if (doc.HasParseError()) { this->emitError("Failed to parse JSON"); return; } if (!doc.IsObject() || !doc.HasMember("ok") || !doc["ok"].IsBool() || !doc.HasMember("channels") || !doc["channels"].IsArray() ) { this->emitError("Invalid JSON"); return; } if (!doc["ok"].GetBool()) { this->emitError("Invalid JSON"); return; } auto & channelsObject = doc["channels"]; for (auto c = channelsObject.Begin(); c != channelsObject.End(); ++c) { if (!c->IsObject()) { this->emitError("Invalid JSON"); break; } SlackChannel channel; fromJsonMember(channel.id, "id", *c); fromJsonMember(channel.name, "name", *c); fromJsonMember(channel.creator, "creator", *c); fromJsonMember(channel.created, "created", *c); fromJsonMember(channel.is_archived, "is_archived", *c); fromJsonMember(channel.is_general, "is_general", *c); fromJsonMember(channel.is_member, "is_member", *c); channels.push_back(std::move(channel)); } }); } Optional<SlackChannel> SlackClient::getChannelByID(const std::string& id) { auto channel = find(channels, [](const SlackChannel& c){ return c.id; }, id); if (channel != std::end(channels)) { return *channel; } return NullOpt; } Optional<SlackChannel> SlackClient::getChannelByName(const std::string& name) { auto channel = find(channels, [](const SlackChannel& c){ return c.name; }, name); if (channel != std::end(channels)) { return *channel; } return NullOpt; } void SlackClient::apiCall( const std::string& method, std::map<std::string, std::string> && paramsIn, std::function<void(std::string)> && callbackIn) { auto params = std::move(paramsIn); assert(!token.empty()); params["token"] = token; const auto postData = HttpUtility::stringify(params); somera::HttpRequestOptions options; options.hostname = "https://slack.com"; options.path = "/api/" + method; options.postFields = postData; options.method = HttpRequestMethod::POST; http.request(options, [callback = std::move(callbackIn), this](bool error, const std::vector<std::uint8_t>& blob) { if (error) { this->emitError("Failed to call 'api.test'"); return; } if (callback) { std::string json(reinterpret_cast<const char*>(blob.data()), blob.size()); callback(json); } }); http.waitAll(); } void SlackClient::onError(std::function<void(std::string)> callback) { errorCallback = callback; } void SlackClient::emitError(const std::string& errorMessage) { if (errorCallback) { errorCallback(errorMessage); } } void SlackClient::apiTest(std::function<void(std::string)> callback) { apiCall("api.test", {}, std::move(callback)); } void SlackClient::authTest(std::function<void(std::string)> callback) { apiCall("auth.test", {}, std::move(callback)); } void SlackClient::chatPostMessage( const SlackChatPostMessageOptions& options, std::function<void(std::string)> callback) { std::map<std::string, std::string> params; params["channel"] = options.channel; params["text"] = options.text; if (options.username) { params["username"] = *options.username; } if (options.icon_url) { params["icon_url"] = *options.icon_url; } if (options.icon_emoji) { params["icon_emoji"] = *options.icon_emoji; } if (options.as_user && *options.as_user) { params["as_user"] = "true"; } apiCall("chat.postMessage", std::move(params), std::move(callback)); } void SlackClient::channelsHistory( const SlackChannelsHistoryOptions& options, std::function<void(SlackHistory)> callbackIn) { std::map<std::string, std::string> params; params["channel"] = options.channel; if (options.count) { params["channel"] = std::to_string(*options.count); } if (options.latest) { params["latest"] = *options.latest; } if (options.oldest) { params["oldest"] = *options.oldest; } auto callbackWrapper = [callback = std::move(callbackIn), this](const std::string& json) { rapidjson::Document doc; doc.Parse(json.c_str()); if (doc.HasParseError()) { this->emitError("Failed to parse JSON"); return; } if (!doc.IsObject() || !doc.HasMember("ok") || !doc["ok"].IsBool()) { this->emitError("Invalid JSON"); return; } if (!doc["ok"].GetBool()) { std::string errorMessage = "Failed to call channelsHistory"; if (doc.HasMember("error") && doc["error"].IsString()) { errorMessage = doc["error"].GetString(); } this->emitError(errorMessage); return; } SlackHistory history; history.has_more = false; fromJsonMember(history.latest, "latest", doc); fromJsonMember(history.has_more, "has_more", doc); if (doc.HasMember("messages") && doc["messages"].IsArray()) { auto & messagesObject = doc["messages"]; for (auto iter = messagesObject.Begin(); iter != messagesObject.End(); ++iter) { const auto& channelObject = (*iter); if (!channelObject.IsObject()) { // error std::fprintf(stderr, "JSON parse error in %s, %d\n", __FILE__, __LINE__); continue; } SlackMessage message; fromJsonMember(message.type, "type", channelObject); fromJsonMember(message.user, "user", channelObject); fromJsonMember(message.text, "text", channelObject); fromJsonMember(message.channel, "channel", channelObject); fromJsonMember(message.subtype, "subtype", channelObject); fromJsonMember(message.ts, "ts", channelObject); using std::chrono::system_clock; message.timestamp = system_clock::from_time_t(::atoi(message.ts.c_str())); history.messages.push_back(std::move(message)); } } if (callback) { callback(std::move(history)); } }; apiCall("channels.history", std::move(params), std::move(callbackWrapper)); } } // namespace somera
29.964029
101
0.583673
mogemimi
ce819104cad0a3594ae55c16dfd8c81fd33b6522
301
cc
C++
ch02/or/main/or.cc
research-note/deep-learning-from-scratch-using-cpp
5e11be85fa9c4c7672ce9c3ea2c5ffa8f27defd1
[ "MIT" ]
2
2021-08-15T12:38:41.000Z
2021-08-15T12:38:51.000Z
ch02/or/main/or.cc
research-note/deep-learning-from-scratch-using-modern-cpp
5e11be85fa9c4c7672ce9c3ea2c5ffa8f27defd1
[ "MIT" ]
null
null
null
ch02/or/main/or.cc
research-note/deep-learning-from-scratch-using-modern-cpp
5e11be85fa9c4c7672ce9c3ea2c5ffa8f27defd1
[ "MIT" ]
null
null
null
#include <numeric> #include <vector> template<typename T> T OR(T x1, T x2) { std::vector<T> x = {x1, x2}; std::vector<T> w = {0.5, 0.5}; T b = -0.2; T tmp = std::inner_product(x.begin(), x.end(), w.begin(), b); if (tmp <= 0) return 0; else return 1; }
18.8125
50
0.491694
research-note
ce8c5530c0574c27a47a2c4df8e9350c51493ee4
2,030
cpp
C++
src/Identifier.cpp
flagarde/YAODAQ
851df4aa32b8695c4706bb3ec9f353f4461c9cad
[ "MIT" ]
null
null
null
src/Identifier.cpp
flagarde/YAODAQ
851df4aa32b8695c4706bb3ec9f353f4461c9cad
[ "MIT" ]
11
2021-05-14T19:50:27.000Z
2022-03-31T07:19:41.000Z
src/Identifier.cpp
flagarde/YAODAQ
851df4aa32b8695c4706bb3ec9f353f4461c9cad
[ "MIT" ]
5
2021-05-11T13:30:30.000Z
2021-05-26T19:57:22.000Z
#include "Identifier.hpp" #include "magic_enum.hpp" #include <vector> #include <string> #include "Exception.hpp" #include "StatusCode.hpp" //FIXME try to find a mix between Infos and Identifier namespace yaodaq { bool Identifier::operator<(const Identifier& infos) const { return this->getName() < infos.getName(); } Identifier::Identifier(const CLASS& clas,const std::string& type, const std::string& name) : m_Class(clas), m_Type(type), m_Name(name){} Identifier::Identifier(const std::string& key) { std::vector<std::string> result; std::string tmp = key; std::string separator = "/"; std::size_t second_pos = tmp.find(separator); while(second_pos != std::string::npos) { if(0 != second_pos) { std::string word = tmp.substr(0, second_pos - 0); result.push_back(word); } else result.push_back(""); tmp = tmp.substr(second_pos + separator.length()); second_pos = tmp.find(separator); if(second_pos == std::string::npos) result.push_back(tmp); } if(result.size() == 6) { m_Class = magic_enum::enum_cast<CLASS>(result[3]).value(); m_Type = result[4]; m_Name = result[5]; } else if(result.size() == 3) { m_Class = magic_enum::enum_cast<CLASS>(result[0]).value(); m_Type = result[1]; m_Name = result[2]; } else { throw Exception(StatusCode::WRONG_NUMBER_PARAMETERS, "Number of argument in key should be 3 or 6 ([RoomName/RackName/CrateName/]Class/Type/Name) !"); } } std::string Identifier::getClassStr() const { return std::string(magic_enum::enum_name(m_Class)); } std::string Identifier::getType() const { return m_Type; } std::string Identifier::getName() const { return m_Name; } CLASS Identifier::getClass() const { return m_Class; } std::string Identifier::get() const { return getClassStr()+"/"+getType()+"/"+getName(); } }
24.756098
155
0.610345
flagarde
ce8ec0386710a0cf77cf8c00f587061a0a796c27
4,726
cpp
C++
src/scene/spritecomponent.cpp
pniekamp/datum
4668030b63360f2c14706a9718773f6225273781
[ "Apache-2.0" ]
28
2016-11-11T15:53:37.000Z
2021-02-25T08:15:42.000Z
src/scene/spritecomponent.cpp
pniekamp/datum
4668030b63360f2c14706a9718773f6225273781
[ "Apache-2.0" ]
5
2017-02-23T06:01:17.000Z
2018-01-31T03:54:49.000Z
src/scene/spritecomponent.cpp
pniekamp/datum
4668030b63360f2c14706a9718773f6225273781
[ "Apache-2.0" ]
1
2017-02-24T01:38:07.000Z
2017-02-24T01:38:07.000Z
// // Datum - sprite component // // // Copyright (c) 2016 Peter Niekamp // #include "spritecomponent.h" #include "transformcomponent.h" #include "debug.h" using namespace std; using namespace lml; //|---------------------- SpriteStorage ------------------------------------- //|-------------------------------------------------------------------------- ///////////////////////// SpriteStorage::Constructor //////////////////////// SpriteComponentStorage::SpriteComponentStorage(Scene *scene, StackAllocator<> allocator) : DefaultStorage(scene, allocator) { } ///////////////////////// SpriteStorage::Constructor //////////////////////// void SpriteComponentStorage::add(EntityId entity, Sprite const *sprite, float size, float layer, Color4 tint, int flags) { auto index = insert(entity); set_entity(index, entity); set_flags(index, flags); set_sprite(index, sprite); set_size(index, size); set_layer(index, layer); set_tint(index, tint); } ///////////////////////// Scene::initialise_storage ///////////////////////// template<> void Scene::initialise_component_storage<SpriteComponent>() { m_systems[typeid(SpriteComponentStorage)] = new(allocate<SpriteComponentStorage>(m_allocator)) SpriteComponentStorage(this, m_allocator); } //|---------------------- SpriteComponent ----------------------------------- //|-------------------------------------------------------------------------- ///////////////////////// SpriteComponent::Constructor ////////////////////// SpriteComponent::SpriteComponent(size_t index, SpriteComponentStorage *storage) : index(index), storage(storage) { } ///////////////////////// SpriteComponent::set_size ///////////////////////// void SpriteComponent::set_size(float size) { storage->set_size(index, size); } ///////////////////////// SpriteComponent::set_layer //////////////////////// void SpriteComponent::set_layer(float layer) { storage->set_layer(index, layer); } ///////////////////////// SpriteComponent::set_sprite /////////////////////// void SpriteComponent::set_sprite(Sprite const *sprite, float size) { storage->set_sprite(index, sprite); storage->set_size(index, size); } ///////////////////////// SpriteComponent::set_sprite /////////////////////// void SpriteComponent::set_sprite(Sprite const *sprite, float size, Color4 const &tint) { storage->set_sprite(index, sprite); storage->set_size(index, size); storage->set_tint(index, tint); } ///////////////////////// SpriteComponent::set_tint ///////////////////////// void SpriteComponent::set_tint(Color4 const &tint) { storage->set_tint(index, tint); } ///////////////////////// Scene::add_component ////////////////////////////// template<> SpriteComponent Scene::add_component<SpriteComponent>(Scene::EntityId entity, Sprite const *sprite, float size, Color4 tint, int flags) { assert(get(entity) != nullptr); assert(system<TransformComponentStorage>()); assert(system<TransformComponentStorage>()->has(entity)); auto storage = system<SpriteComponentStorage>(); storage->add(entity, sprite, size, 0.0f, tint, flags); return { storage->index(entity), storage }; } template<> SpriteComponent Scene::add_component<SpriteComponent>(Scene::EntityId entity, Sprite const *sprite, float size, Color4 tint, SpriteComponent::Flags flags) { return add_component<SpriteComponent>(entity, sprite, size, tint, (int)flags); } ///////////////////////// Scene::add_component ////////////////////////////// template<> SpriteComponent Scene::add_component<SpriteComponent>(Scene::EntityId entity, Sprite const *sprite, float size, int flags) { return add_component<SpriteComponent>(entity, sprite, size, Color4(1.0f, 1.0f, 1.0f, 1.0f), flags); } template<> SpriteComponent Scene::add_component<SpriteComponent>(Scene::EntityId entity, Sprite const *sprite, float size, SpriteComponent::Flags flags) { return add_component<SpriteComponent>(entity, sprite, size, (int)flags); } ///////////////////////// Scene::remove_component /////////////////////////// template<> void Scene::remove_component<SpriteComponent>(Scene::EntityId entity) { assert(get(entity) != nullptr); system<SpriteComponentStorage>()->remove(entity); } ///////////////////////// Scene::has_component ////////////////////////////// template<> bool Scene::has_component<SpriteComponent>(Scene::EntityId entity) const { assert(get(entity) != nullptr); return system<SpriteComponentStorage>()->has(entity); } ///////////////////////// Scene::get_component ////////////////////////////// template<> SpriteComponent Scene::get_component<SpriteComponent>(Scene::EntityId entity) { assert(get(entity) != nullptr); return system<SpriteComponentStorage>()->get(entity); }
29.354037
154
0.599027
pniekamp
ce8f63fab9ba1aad17e6e2e6bc204bcdc7e599a2
212
cpp
C++
solutions/1375.bulb-switcher-iii.329765759.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
78
2020-10-22T11:31:53.000Z
2022-02-22T13:27:49.000Z
solutions/1375.bulb-switcher-iii.329765759.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
null
null
null
solutions/1375.bulb-switcher-iii.329765759.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
26
2020-10-23T15:10:44.000Z
2021-11-07T16:13:50.000Z
class Solution { public: int numTimesAllBlue(vector<int> &A) { int right = 0, res = 0, n = A.size(); for (int i = 0; i < n; ++i) res += (right = max(right, A[i])) == i + 1; return res; } };
21.2
49
0.5
satu0king
ce90515a01043204a64cacfdcdf531d7c2131953
7,156
cpp
C++
test/startup/thread_support.cpp
arkantos493/MPICXX
ffbaeaaa3c7248e2087c3716ec71e0612aafe689
[ "MIT" ]
1
2020-10-20T06:53:05.000Z
2020-10-20T06:53:05.000Z
test/startup/thread_support.cpp
arkantos493/MPICXX
ffbaeaaa3c7248e2087c3716ec71e0612aafe689
[ "MIT" ]
null
null
null
test/startup/thread_support.cpp
arkantos493/MPICXX
ffbaeaaa3c7248e2087c3716ec71e0612aafe689
[ "MIT" ]
1
2020-08-13T17:46:40.000Z
2020-08-13T17:46:40.000Z
/** * @file * @author Marcel Breyer * @date 2020-07-29 * @copyright This file is distributed under the MIT License. * * @brief Test cases for the @ref mpicxx::thread_support enum class. * @details Testsuite: *StartupTest* * | test case name | test case description | * |:----------------------------------------------------|:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| * | CorrectEnumClassValues | check if the enum class reflects the correct MPI values | * | ToStringViaFormat | check whether the conversion to [`std::string`](https://en.cppreference.com/w/cpp/string/basic_string) via [`fmt::format`](https://fmt.dev/latest/syntax.html) works | * | ToStringViaToString | check whether the conversion to [`std::string`](https://en.cppreference.com/w/cpp/string/basic_string) via [`to_string`](https://en.cppreference.com/w/cpp/string/basic_string/to_string) works | * | ToStringViaStreamInsertionOperator | check whether the conversion to [`std::string`](https://en.cppreference.com/w/cpp/string/basic_string) via the stream-extraction operator works | * | ToEnumClass | check whether the conversion from a string via @ref mpicxx::thread_support_from_string(const std::string_view) works | * | ToEnumClassInvalidString | try to convert an invalid string to the enum class via @ref mpicxx::thread_support_from_string(const std::string_view) | * | ToEnumClassViaStreamExtractionOperator | check whether the conversion from an input stream via the stream-insertion operator works | * | ToEnumClassViaStreamExtractionOperatorInvalidString | try to convert an invalid string to the enum class via the stream-insertion operator | */ #include <mpicxx/startup/thread_support.hpp> #include <test_utility.hpp> #include <fmt/format.h> #include <gtest/gtest.h> #include <sstream> #include <string> #include <type_traits> #include <vector> using namespace std::string_literals; TEST(StartupTest, CorrectEnumClassValues) { // the values should all be equal using enum_t = std::underlying_type_t<mpicxx::thread_support>; EXPECT_EQ(static_cast<enum_t>(mpicxx::thread_support::single), MPI_THREAD_SINGLE); EXPECT_EQ(static_cast<enum_t>(mpicxx::thread_support::funneled), MPI_THREAD_FUNNELED); EXPECT_EQ(static_cast<enum_t>(mpicxx::thread_support::serialized), MPI_THREAD_SERIALIZED); EXPECT_EQ(static_cast<enum_t>(mpicxx::thread_support::multiple), MPI_THREAD_MULTIPLE); } TEST(StartupTest, ToStringViaFormat) { // conversion via fmt::format should work as expected EXPECT_EQ(fmt::format("{}", mpicxx::thread_support::single), "MPI_THREAD_SINGLE"s); EXPECT_EQ(fmt::format("{}", mpicxx::thread_support::funneled), "MPI_THREAD_FUNNELED"s); EXPECT_EQ(fmt::format("{}", mpicxx::thread_support::serialized), "MPI_THREAD_SERIALIZED"s); EXPECT_EQ(fmt::format("{}", mpicxx::thread_support::multiple), "MPI_THREAD_MULTIPLE"s); } TEST(StartupTest, ToStringViaToString) { // conversion via to_string should work as expected EXPECT_EQ(to_string(mpicxx::thread_support::single), "MPI_THREAD_SINGLE"s); EXPECT_EQ(to_string(mpicxx::thread_support::funneled), "MPI_THREAD_FUNNELED"s); EXPECT_EQ(to_string(mpicxx::thread_support::serialized), "MPI_THREAD_SERIALIZED"s); EXPECT_EQ(to_string(mpicxx::thread_support::multiple), "MPI_THREAD_MULTIPLE"s); } TEST(StartupTest, ToStringViaStreamInsertionOperator) { // create vectors with valid values std::vector<mpicxx::thread_support> enum_vec = { mpicxx::thread_support::single, mpicxx::thread_support::funneled, mpicxx::thread_support::serialized, mpicxx::thread_support::multiple }; std::vector<std::string> string_vec = { "MPI_THREAD_SINGLE"s, "MPI_THREAD_FUNNELED"s, "MPI_THREAD_SERIALIZED"s, "MPI_THREAD_MULTIPLE"s }; // sanity check ASSERT_EQ(enum_vec.size(), string_vec.size()); // conversion via operator<< should work as expected std::stringstream ss; for (std::size_t i = 0; i < enum_vec.size(); ++i) { SCOPED_TRACE(i); ss << enum_vec[i]; EXPECT_EQ(ss.str(), string_vec[i]); ss.str(std::string()); ss.clear(); } } TEST(StartupTest, ToEnumClass) { // conversion from string to enum value should work as expected EXPECT_EQ(mpicxx::thread_support_from_string("MPI_THREAD_SINGLE"), mpicxx::thread_support::single); EXPECT_EQ(mpicxx::thread_support_from_string("MPI_THREAD_FUNNELED"), mpicxx::thread_support::funneled); EXPECT_EQ(mpicxx::thread_support_from_string("MPI_THREAD_SERIALIZED"), mpicxx::thread_support::serialized); EXPECT_EQ(mpicxx::thread_support_from_string("MPI_THREAD_MULTIPLE"), mpicxx::thread_support::multiple); } TEST(StartupTest, ToEnumClassInvalidString) { // try to convert an illegal string value [[maybe_unused]] mpicxx::thread_support ts; EXPECT_THROW_WHAT( ts = mpicxx::thread_support_from_string("INVALID_VALUE"), std::invalid_argument, "Can't convert \"INVALID_VALUE\" to mpicxx::thread_support!" ); } TEST(StartupTest, ToEnumClassViaStreamExtractionOperator) { // create vector with valid values std::vector<mpicxx::thread_support> enum_vec = { mpicxx::thread_support::single, mpicxx::thread_support::funneled, mpicxx::thread_support::serialized, mpicxx::thread_support::multiple }; // conversion via operator>> should work as expected std::stringstream ss("MPI_THREAD_SINGLE MPI_THREAD_FUNNELED MPI_THREAD_SERIALIZED MPI_THREAD_MULTIPLE"s); for (std::size_t i = 0; i < enum_vec.size(); ++i) { SCOPED_TRACE(i); mpicxx::thread_support ts; ss >> ts; EXPECT_EQ(ts, enum_vec[i]); } } TEST(StartupTest, ToEnumClassViaStreamExtractionOperatorInvalidString) { // try to convert an illegal string value std::stringstream ss("INVALID_VALUE"); mpicxx::thread_support ts; ss >> ts; EXPECT_TRUE(ss.fail()); }
60.644068
252
0.597121
arkantos493
ce92176b8a32a92351521aab900db38c508d6644
2,505
cpp
C++
apps/vaporgui/VGeometry.cpp
StasJ/vapor-formatted
9fad47d88714ef835b78f6c1dd855d66b6aa90da
[ "BSD-3-Clause" ]
null
null
null
apps/vaporgui/VGeometry.cpp
StasJ/vapor-formatted
9fad47d88714ef835b78f6c1dd855d66b6aa90da
[ "BSD-3-Clause" ]
null
null
null
apps/vaporgui/VGeometry.cpp
StasJ/vapor-formatted
9fad47d88714ef835b78f6c1dd855d66b6aa90da
[ "BSD-3-Clause" ]
null
null
null
#include "VGeometry.h" VGeometry::VGeometry(QWidget *parent, int dim, const std::vector<float> &range) : QWidget(parent) { VAssert(dim == 2 || dim == 3); VAssert(range.size() == dim * 2); for (int i = 0; i < dim; i++) VAssert(range[i * 2] < range[i * 2 + 1]); _dim = dim; _xrange = new VRange(this, range[0], range[1], "XMin", "XMax"); _yrange = new VRange(this, range[2], range[3], "YMin", "YMax"); if (_dim == 3) _zrange = new VRange(this, range[4], range[5], "ZMin", "ZMax"); else // Create anyway. Will be hidden though. { _zrange = new VRange(this, 0.0f, 100.0f, "ZMin", "ZMax"); _zrange->hide(); } connect(_xrange, SIGNAL(_rangeChanged()), this, SLOT(_respondChanges())); connect(_yrange, SIGNAL(_rangeChanged()), this, SLOT(_respondChanges())); connect(_zrange, SIGNAL(_rangeChanged()), this, SLOT(_respondChanges())); _layout = new QVBoxLayout(this); _layout->addWidget(_xrange); _layout->addWidget(_yrange); _layout->addWidget(_zrange); } void VGeometry::SetDimAndRange(int dim, const std::vector<float> &range) { VAssert(dim == 2 || dim == 3); VAssert(range.size() == dim * 2); for (int i = 0; i < dim; i++) VAssert(range[i * 2] < range[i * 2 + 1]); /* Adjust the appearance if necessary */ if (_dim == 2 && dim == 3) _zrange->show(); else if (_dim == 3 && dim == 2) _zrange->hide(); _dim = dim; _xrange->SetRange(range[0], range[1]); _yrange->SetRange(range[2], range[3]); if (_dim == 3) _zrange->SetRange(range[4], range[5]); } void VGeometry::SetCurrentValues(const std::vector<float> &vals) { VAssert(vals.size() == _dim * 2); for (int i = 0; i < _dim; i++) VAssert(vals[i * 2] < vals[i * 2 + 1]); /* VRange widgets will only respond to values within their ranges */ _xrange->SetCurrentValLow(vals[0]); _xrange->SetCurrentValHigh(vals[1]); _yrange->SetCurrentValLow(vals[2]); _yrange->SetCurrentValHigh(vals[3]); if (_dim == 3) { _zrange->SetCurrentValLow(vals[4]); _zrange->SetCurrentValHigh(vals[5]); } } void VGeometry::GetCurrentValues(std::vector<float> &vals) const { vals.resize(_dim * 2, 0.0f); _xrange->GetCurrentValRange(vals[0], vals[1]); _yrange->GetCurrentValRange(vals[2], vals[3]); if (_dim == 3) _zrange->GetCurrentValRange(vals[4], vals[5]); } void VGeometry::_respondChanges() { emit _geometryChanged(); }
33.851351
99
0.600798
StasJ
ce96958b21523cbbf071c9dc263266169b8c056f
1,117
cpp
C++
src/State.cpp
unbgames/Wenova
4860429d1bdc323b7ab8e7d53876e32de8941f46
[ "MIT" ]
null
null
null
src/State.cpp
unbgames/Wenova
4860429d1bdc323b7ab8e7d53876e32de8941f46
[ "MIT" ]
3
2017-08-28T23:57:45.000Z
2017-10-08T19:36:41.000Z
src/State.cpp
joaorobson/Wenova
4860429d1bdc323b7ab8e7d53876e32de8941f46
[ "MIT" ]
1
2019-04-07T20:19:20.000Z
2019-04-07T20:19:20.000Z
#include "State.h" #include "Collision.h" State::State(){ m_pop_requested = m_quit_requested = false; } State::~State(){ } void State::add_object(GameObject * object){ object_array.emplace_back(object); } bool State::pop_requested(){ return m_pop_requested; } bool State::quit_requested(){ return m_quit_requested; } void State::update_array(float delta){ //collision tests for(unsigned i = 0; i < object_array.size(); ++i){ for(unsigned j = i + 1; j < object_array.size(); ++j){ auto a = object_array[i].get(); auto b = object_array[j].get(); if(Collision::is_colliding(a->box, b->box, a->rotation, b->rotation)){ a->notify_collision(*b); b->notify_collision(*a); } } } //update for(unsigned it = 0; it < object_array.size(); ++it){ object_array[it]->update(delta); } //death check for(unsigned it = 0; it < object_array.size(); ++it){ if(object_array[it]->is_dead()){ object_array.erase(object_array.begin() + it); break; } } } void State::render_array(){ for(auto & go : object_array){ go->render(); } } void State::load_assets(){ //NOTHING TO DO }
18.616667
73
0.651746
unbgames
ce96d7893c607527df0bc4f93924dfd2cdaee53e
29,619
cpp
C++
gameboy/src/ppu/ppu.cpp
emrsmsrli/gameboi
6448722529bc64184e30a945f0e5ec4203265e10
[ "MIT" ]
23
2019-08-27T13:54:27.000Z
2022-01-21T08:38:14.000Z
gameboy/src/ppu/ppu.cpp
emrsmsrli/gameboi
6448722529bc64184e30a945f0e5ec4203265e10
[ "MIT" ]
21
2020-02-22T20:37:16.000Z
2020-08-30T14:52:48.000Z
gameboy/src/ppu/ppu.cpp
emrsmsrli/gameboi
6448722529bc64184e30a945f0e5ec4203265e10
[ "MIT" ]
null
null
null
#include "gameboy/ppu/ppu.h" #include <cstring> #include "gameboy/bus.h" #include "gameboy/cartridge.h" #include "gameboy/cpu/cpu.h" #include "gameboy/memory/memory_constants.h" #include "gameboy/memory/mmu.h" #include "gameboy/util/variantutil.h" namespace gameboy { constexpr auto ly_max = 153u; constexpr auto lcd_enable_delay_frames = 3; constexpr auto lcd_enable_delay_cycles = 244; constexpr auto hblank_cycles = 204u; constexpr auto reading_oam_cycles = 80u; constexpr auto reading_oam_vram_render_cycles = 160u; constexpr auto reading_oam_vram_cycles = 172u; constexpr auto total_line_cycles = 456u; constexpr auto total_vblank_cycles = total_line_cycles * 10u; constexpr auto total_frame_cycles = total_line_cycles * (ly_max + 1); constexpr address16 lcdc_addr{0xFF40u}; constexpr address16 stat_addr{0xFF41u}; constexpr address16 scy_addr{0xFF42u}; constexpr address16 scx_addr{0xFF43u}; constexpr address16 lyc_addr{0xFF45u}; constexpr address16 wy_addr{0xFF4Au}; constexpr address16 wx_addr{0xFF4Bu}; constexpr address16 bgp_addr{0xFF47u}; constexpr address16 obp_0_addr{0xFF48u}; constexpr address16 obp_1_addr{0xFF49u}; constexpr address16 bgpi_addr{0xFF68u}; constexpr address16 bgpd_addr{0xFF69u}; constexpr address16 obpi_addr{0xFF6Au}; constexpr address16 obpd_addr{0xFF6Bu}; constexpr address16 vbk_addr{0xFF4Fu}; constexpr address16 oam_dma_addr{0xFF46u}; constexpr address16 hdma_1_addr{0xFF51u}; // New DMA Source, High constexpr address16 hdma_2_addr{0xFF52u}; // New DMA Source, Low constexpr address16 hdma_3_addr{0xFF53u}; // New DMA Destination, High constexpr address16 hdma_4_addr{0xFF54u}; // New DMA Destination, Low constexpr address16 hdma_5_addr{0xFF55u}; // New DMA Length/Mode/Start template<auto ReadFunc, auto WriteFunc, typename... Registers> void add_delegate(observer<bus> bus, ppu* p, Registers... registers) { std::array dma_registers{registers...}; for(const auto& addr : dma_registers) { bus->get_mmu()->add_memory_delegate(addr, { {connect_arg<ReadFunc>, p}, {connect_arg<WriteFunc>, p} }); } } ppu::ppu(const observer<bus> bus) : bus_{bus}, oam_(oam_range.size(), 0u) { reset(); } void ppu::reset() noexcept { cgb_enabled_ = bus_->get_cartridge()->cgb_enabled(); lcd_enabled_ = true; line_rendered_ = false; vblank_line_ = 0; window_line_ = 0u; lcd_enable_delay_frame_count_ = 0; lcd_enable_delay_cycle_count_ = 0; cycle_count_ = 0u; secondary_cycle_count_ = 0u; vram_bank_ = 0u; lcdc_.reg = 0x91u; stat_.reg = cgb_enabled_ ? 0x01u : 0x06u; ly_ = cgb_enabled_ ? 0x90u : 0x00u; lyc_ = 0x00u; scx_ = 0x00u; scy_ = 0x00u; wx_ = 0x00u; wy_ = 0x00u; gb_palette_ = palette_zelda; bgp_ = 0xFCu; bgpi_ = 0x00u; bgpd_ = 0x00u; obpi_ = 0x00u; obpd_ = 0x00u; interrupt_request_.reset_all(); ram_.resize((cgb_enabled_ ? 2 : 1) * 8_kb); std::fill(begin(ram_), end(ram_), 0u); std::fill(begin(oam_), end(oam_), 0u); const auto fill_palettes = [](auto& p, const auto& palette) { std::fill(begin(p), end(p), palette); }; fill_palettes(obp_, register8{0xFFu}); fill_palettes(cgb_bg_palettes_, palette{color{0xFFu}}); fill_palettes(cgb_obj_palettes_, palette{color{0xFFu}}); add_delegate<&ppu::dma_read, &ppu::dma_write>(bus_, this, oam_dma_addr); add_delegate<&ppu::general_purpose_register_read, &ppu::general_purpose_register_write>(bus_, this, lcdc_addr, stat_addr, scy_addr, scx_addr, ly_addr, lyc_addr, wy_addr, wx_addr); add_delegate<&ppu::palette_read, &ppu::palette_write>(bus_, this, bgp_addr, obp_0_addr, obp_1_addr); if(cgb_enabled_) { add_delegate<&ppu::dma_read, &ppu::dma_write>(bus_, this, hdma_1_addr, hdma_2_addr, hdma_3_addr, hdma_4_addr, hdma_5_addr); add_delegate<&ppu::general_purpose_register_read, &ppu::general_purpose_register_write>(bus_, this, vbk_addr); add_delegate<&ppu::palette_read, &ppu::palette_write>(bus_, this, bgpi_addr, bgpd_addr, obpi_addr, obpd_addr); dma_transfer_.oam_dma = 0x00u; } } void ppu::tick(const uint8_t cycles) { cycle_count_ += cycles; if(!lcd_enabled_) { if(lcd_enable_delay_cycle_count_ > 0) { lcd_enable_delay_cycle_count_ -= cycles; if(lcd_enable_delay_cycle_count_ <= 0) { lcd_enable_delay_cycle_count_ = 0; lcd_enable_delay_frame_count_ = lcd_enable_delay_frames; vblank_line_ = 0; window_line_ = 0; ly_ = 0u; cycle_count_ = 0u; secondary_cycle_count_ = 0u; lcd_enabled_ = true; stat_.set_mode(stat_mode::h_blank); interrupt_request_.reset_all(); if(stat_.mode_interrupt_enabled(stat_mode::reading_oam)) { bus_->get_cpu()->request_interrupt(interrupt::lcd_stat); interrupt_request_.set(interrupt_request::oam); } compare_coincidence(); } } else if(cycle_count_ >= total_frame_cycles) { cycle_count_ -= total_frame_cycles; on_vblank_(); } return; } const auto has_elapsed = [&](const auto cycle_count) { if(cycle_count_ >= cycle_count) { cycle_count_ -= cycle_count; return true; } return false; }; switch(stat_.get_mode()) { case stat_mode::h_blank: { if(has_elapsed(hblank_cycles)) { set_ly(register8(ly_ + 1)); stat_.set_mode(stat_mode::reading_oam); if(cgb_enabled_ && !dma_transfer_.disabled()) { hdma(); } reset_interrupt_requests({interrupt_request::v_blank, interrupt_request::oam}); if(ly_ == screen_height) { stat_.set_mode(stat_mode::v_blank); secondary_cycle_count_ = cycle_count_; vblank_line_ = 0; window_line_ = 0; bus_->get_cpu()->request_interrupt(interrupt::lcd_vblank); if(stat_.mode_interrupt_enabled()) { request_interrupt(interrupt_request::v_blank); } if(lcd_enable_delay_frame_count_ > 0) { --lcd_enable_delay_frame_count_; } else { on_vblank_(); } } else { if(stat_.mode_interrupt_enabled()) { request_interrupt(interrupt_request::oam); } } interrupt_request_.reset(interrupt_request::h_blank); } break; } case stat_mode::v_blank: { secondary_cycle_count_ += cycles; if(secondary_cycle_count_ >= total_line_cycles) { secondary_cycle_count_ -= total_line_cycles; ++vblank_line_; if(vblank_line_ < 10) { set_ly(register8(ly_ + 1u)); } } if(cycle_count_ >= 4104u && secondary_cycle_count_ >= 4u && ly_ == ly_max) { set_ly(register8{0u}); } if(has_elapsed(total_vblank_cycles)) { stat_.set_mode(stat_mode::reading_oam); reset_interrupt_requests({interrupt_request::h_blank, interrupt_request::oam}); if(stat_.mode_interrupt_enabled()) { request_interrupt(interrupt_request::oam); } interrupt_request_.reset(interrupt_request::v_blank); } break; } case stat_mode::reading_oam: { if(has_elapsed(reading_oam_cycles)) { stat_.set_mode(stat_mode::reading_oam_vram); line_rendered_ = false; reset_interrupt_requests({ interrupt_request::h_blank, interrupt_request::v_blank, interrupt_request::oam }); } break; } case stat_mode::reading_oam_vram: { if(cycle_count_ >= reading_oam_vram_render_cycles && !line_rendered_) { line_rendered_ = true; render(); } if(has_elapsed(reading_oam_vram_cycles)) { stat_.set_mode(stat_mode::h_blank); reset_interrupt_requests({ interrupt_request::h_blank, interrupt_request::v_blank, interrupt_request::oam }); if(stat_.mode_interrupt_enabled()) { request_interrupt(interrupt_request::h_blank); } } break; } } } uint8_t ppu::read_ram(const address16& address) const { if(stat_.get_mode() == stat_mode::reading_oam_vram) { return 0xFFu; } return read_ram_by_bank(address, vram_bank_); } void ppu::write_ram(const address16& address, const uint8_t data) { if(stat_.get_mode() == stat_mode::reading_oam_vram) { return; } write_ram_by_bank(address, data, vram_bank_); } uint8_t ppu::read_oam(const address16& address) const { if(stat_.get_mode() == stat_mode::reading_oam || stat_.get_mode() == stat_mode::reading_oam_vram) { return 0xFFu; } return oam_[address.value() - *begin(oam_range)]; } void ppu::write_oam(const address16& address, const uint8_t data) { if(stat_.get_mode() == stat_mode::reading_oam || stat_.get_mode() == stat_mode::reading_oam_vram) { return; } oam_[address.value() - *begin(oam_range)] = data; } uint8_t ppu::read_ram_by_bank(const address16& address, const uint8_t bank) const { if(!cgb_enabled_ && bank != 0u) { return 0x00u; } return ram_[address.value() - *begin(vram_range) + bank * 8_kb]; } void ppu::write_ram_by_bank(const address16& address, const uint8_t data, const uint8_t bank) { if(!cgb_enabled_ && bank != 0u) { return; } ram_[address.value() - *begin(vram_range) + bank * 8_kb] = data; } uint8_t ppu::dma_read(const address16& address) const { if(address == oam_dma_addr) { return dma_transfer_.oam_dma.value(); } if(address == hdma_1_addr) { return dma_transfer_.source.high().value(); } if(address == hdma_2_addr) { return dma_transfer_.source.low().value(); } if(address == hdma_3_addr) { return dma_transfer_.destination.high().value(); } if(address == hdma_4_addr) { return dma_transfer_.destination.low().value(); } if(address == hdma_5_addr) { return dma_transfer_.length_mode_start.value(); } return 0u; } void ppu::dma_write(const address16& address, const uint8_t data) { if(address == oam_dma_addr) { dma_transfer_.oam_dma = data; bus_->get_mmu()->dma( make_address(static_cast<uint16_t>(data << 8u)), make_address(*begin(oam_range)), oam_range.size()); } else if(address == hdma_1_addr) { if((data > 0x7Fu && data < 0xA0u) || data > 0xDFu) { dma_transfer_.source.high() = 0x00u; } else { dma_transfer_.source.high() = data; } } else if(address == hdma_2_addr) { dma_transfer_.source.low() = data & 0xF0u; } else if(address == hdma_3_addr) { dma_transfer_.destination.high() = (data & 0x1Fu) | 0x80u; } else if(address == hdma_4_addr) { dma_transfer_.destination.low() = data & 0xF0u; } else if(address == hdma_5_addr) { if(!dma_transfer_.disabled()) { if(bit::test(data, 7u)) { dma_transfer_.length_mode_start = data & 0x7Fu; } else { dma_transfer_.length_mode_start = data; } } else { if(bit::test(data, 7u)) { dma_transfer_.length_mode_start = data & 0x7Fu; if(stat_.get_mode() == stat_mode::h_blank) { hdma(); } } else { dma_transfer_.length_mode_start = data; gdma(); } } } } uint8_t ppu::general_purpose_register_read(const address16& address) const { if(address == vbk_addr) { return vram_bank_ | 0xFEu; } if(address == lcdc_addr) { return lcdc_.reg.value(); } if(address == stat_addr) { return stat_.reg.value() | 0x80u; } if(address == scy_addr) { return scy_.value(); } if(address == scx_addr) { return scx_.value(); } if(address == ly_addr) { return lcd_enabled_ ? ly_.value() : 0u; } if(address == lyc_addr) { return lyc_.value(); } if(address == wy_addr) { return wy_.value(); } if(address == wx_addr) { return wx_.value(); } return 0u; } void ppu::general_purpose_register_write(const address16& address, const uint8_t data) { if(address == vbk_addr) { vram_bank_ = data & 0x01u; } else if(address == lcdc_addr) { register_lcdc new_lcdc{data}; if(!lcdc_.window_enabled() && new_lcdc.window_enabled()) { if(window_line_ == 0u && ly_ < screen_height && ly_ > wy_) { window_line_ = screen_height; } } if(new_lcdc.lcd_enabled()) { if(!lcd_enabled_) { lcd_enable_delay_cycle_count_ = lcd_enable_delay_cycles; } } else { disable_screen(); } lcdc_.reg = data; } else if(address == stat_addr) { stat_.reg = (stat_.reg & 0x07u) | (data & 0x78u); auto irq_copy = interrupt_request_; irq_copy.request &= (stat_.reg.value() >> 3u) & 0x0Fu; interrupt_request_ = irq_copy; if(lcdc_.lcd_enabled()) { if(stat_.mode_interrupt_enabled()) { switch(stat_.get_mode()) { case stat_mode::h_blank: request_interrupt(irq_copy, interrupt_request::h_blank); break; case stat_mode::v_blank: request_interrupt(irq_copy, interrupt_request::v_blank); break; case stat_mode::reading_oam: request_interrupt(irq_copy, interrupt_request::oam); break; case stat_mode::reading_oam_vram: break; } } compare_coincidence(); } } else if(address == scy_addr) { scy_ = data; } else if(address == scx_addr) { scx_ = data; } else if(address == ly_addr) { set_ly(register8{0x00u}); } else if(address == lyc_addr) { set_lyc(register8{data}); } else if(address == wy_addr) { wy_ = data; } else if(address == wx_addr) { wx_ = data; } } uint8_t ppu::palette_read(const address16& address) const { if(address == bgp_addr) { return bgp_.value(); } if(address == obp_0_addr) { return obp_[0].value(); } if(address == obp_1_addr) { return obp_[1].value(); } if(address == bgpi_addr) { return bgpi_.value(); } if(address == bgpd_addr) { return bgpd_.value(); } if(address == obpi_addr) { return obpi_.value(); } if(address == obpd_addr) { return obpd_.value(); } return 0u; } void ppu::palette_write(const address16& address, const uint8_t data) { const auto update_palette_data_register = [](auto& index_register, auto& data_register, auto& palettes) { const auto is_msb = bit::test(index_register, 0u); const auto color_index = (index_register.value() >> 1u) & 0x03u; const auto palette_index = (index_register.value() >> 3u) & 0x07u; auto& color = palettes[palette_index].colors[color_index]; if(is_msb) { data_register = (color.blue << 2u) | ((color.green >> 3u) & 0x03u); } else { data_register = ((color.green & 0x07u) << 5u) | color.red; } }; const auto set_palette = [&](auto& index_register, auto& data_register, auto& palettes, const uint8_t data) noexcept { const auto auto_increment = bit::test(index_register, 7u); const auto is_msb = bit::test(index_register, 0u); const auto color_index = (index_register.value() >> 1u) & 0x03u; const auto palette_index = (index_register.value() >> 3u) & 0x07u; // msb | xBBBBBGG | // lsb | GGGRRRRR | auto& color = palettes[palette_index].colors[color_index]; if(is_msb) { color.blue = (data >> 2u) & 0x1Fu; color.green |= (data & 0x03u) << 3u; } else { color.red = data & 0x1Fu; color.green = (data >> 5u) & 0x07u; } if(auto_increment) { index_register = (index_register & 0x80u) | ((index_register + 1u) & 0x3Fu); update_palette_data_register(index_register, data_register, palettes); } }; if(address == bgp_addr) { bgp_ = data; } else if(address == obp_0_addr) { obp_[0] = data; } else if(address == obp_1_addr) { obp_[1] = data; } else if(address == bgpi_addr) { bgpi_ = data; update_palette_data_register(bgpi_, bgpd_, cgb_bg_palettes_); } else if(address == obpi_addr) { obpi_ = data; update_palette_data_register(obpi_, obpd_, cgb_obj_palettes_); } else if(address == bgpd_addr) { set_palette(bgpi_, bgpd_, cgb_bg_palettes_, data); } else if(address == obpd_addr) { set_palette(obpi_, obpd_, cgb_obj_palettes_, data); } } void ppu::compare_coincidence() noexcept { if(ly_ == lyc_) { stat_.set_coincidence_flag(); if(stat_.coincidence_interrupt_enabled()) { request_interrupt(interrupt_request::coincidence); } } else { stat_.reset_coincidence_flag(); interrupt_request_.reset(interrupt_request::coincidence); } } void ppu::set_ly(const register8& ly) noexcept { ly_ = ly; compare_coincidence(); } void ppu::set_lyc(const register8& lyc) noexcept { if(lyc_ != lyc) { lyc_ = lyc; if(lcdc_.lcd_enabled()) { compare_coincidence(); } } } void ppu::disable_screen() noexcept { lcd_enabled_ = false; stat_.set_mode(stat_mode::h_blank); interrupt_request_.reset_all(); cycle_count_ = 0; secondary_cycle_count_ = 0; ly_ = 0; } void ppu::request_interrupt(interrupt_request::type type) noexcept { request_interrupt(interrupt_request_, type); } void ppu::request_interrupt(interrupt_request& irq, interrupt_request::type type) noexcept { if(irq.none()) { bus_->get_cpu()->request_interrupt(interrupt::lcd_stat); } irq.set(type); } void ppu::reset_interrupt_requests(const std::initializer_list<interrupt_request::type> irqs) noexcept { for(const auto irq : irqs) { interrupt_request_.reset(irq); } } void ppu::hdma() { bus_->get_mmu()->dma( make_address(dma_transfer_.source), make_address(dma_transfer_.destination), dma_transfer_data::unit_transfer_length); dma_transfer_.source += dma_transfer_data::unit_transfer_length; if(dma_transfer_.source == 0x8000u) { dma_transfer_.source = 0xA000u; } dma_transfer_.destination += dma_transfer_data::unit_transfer_length; if(dma_transfer_.destination == 0xA000u) { dma_transfer_.destination = 0x8000u; } dma_transfer_.length_mode_start -= 1u; } void ppu::gdma() { const auto transfer_length = dma_transfer_.length(); bus_->get_mmu()->dma( make_address(dma_transfer_.source), make_address(dma_transfer_.destination), transfer_length); dma_transfer_.source += transfer_length; dma_transfer_.destination += transfer_length; dma_transfer_.length_mode_start = 0xFFu; } void ppu::render() noexcept { render_line line{}; render_buffer buffer{}; std::fill(begin(buffer), end(buffer), std::make_pair(0u, attributes::uninitialized{})); render_background(buffer); render_window(buffer); render_obj(buffer); for(auto pixel_idx = 0u; pixel_idx < line.size(); ++pixel_idx) { const auto& [color_idx, attr] = buffer[pixel_idx]; visit_nt(attr, [&](attributes::uninitialized) { line[pixel_idx] = color{0xFFu}; }, [&, color = color_idx](const attributes::bg& bg_attr) { if(cgb_enabled_) { const auto palette_color = cgb_bg_palettes_[bg_attr.palette_index()].colors[color]; line[pixel_idx] = correct_color(palette_color); } else { const auto background_palette = palette::from(gb_palette_, bgp_.value()); line[pixel_idx] = background_palette.colors[color]; } }, [&, color = color_idx](const attributes::obj& obj_attr) { if(cgb_enabled_) { const auto palette_color = cgb_obj_palettes_[obj_attr.cgb_palette_index()].colors[color]; line[pixel_idx] = correct_color(palette_color); } else { const auto background_palette = palette::from(gb_palette_, obp_[obj_attr.gb_palette_index()].value()); line[pixel_idx] = background_palette.colors[color]; } } ); } on_render_line_(ly_.value(), line); } void ppu::render_background(render_buffer& buffer) const noexcept { if(!cgb_enabled_ && !lcdc_.bg_enabled()) { return; } const auto scroll_offset = (scx_ + screen_width) % map_pixel_count; const auto tile_start_addr = address16(lcdc_.bg_map_secondary() ? 0x9C00u : 0x9800u); const auto tile_y_to_render = (scy_ + ly_.value()) % tile_pixel_count; const auto tile_map_y = ((scy_ + ly_.value()) / tile_pixel_count) % map_tile_count; constexpr auto max_render_tile_count = screen_width / tile_pixel_count + 1; const auto tile_map_x_start = scx_.value() / tile_pixel_count; auto rendered_pix_idx = 0u; for(auto tile_render_count = 0u; tile_render_count < max_render_tile_count; ++tile_render_count) { const auto tile_map_x = (tile_map_x_start + tile_render_count) % map_tile_count; const auto tile_map_idx = tile_start_addr + tile_map_y * map_tile_count + tile_map_x; const auto tile_no = read_ram_by_bank(tile_map_idx, 0); const attributes::bg tile_attr{read_ram_by_bank(tile_map_idx, 1)}; const auto tile_y = tile_attr.v_flipped() ? tile_pixel_count - tile_y_to_render - 1u : tile_y_to_render; auto tile_row = get_tile_row(tile_y, tile_no, tile_attr.vram_bank()); if(tile_attr.h_flipped()) { std::reverse(begin(tile_row), end(tile_row)); } for(auto tile_x = 0u; tile_x < tile_pixel_count; ++tile_x) { const auto pix_idx = tile_map_x * tile_pixel_count + tile_x; if(rendered_pix_idx < screen_width && (scx_ <= pix_idx || (scx_ > scroll_offset && pix_idx < scroll_offset)) // bg scroll overflow ) { buffer[rendered_pix_idx++] = std::make_pair(tile_row[tile_x], tile_attr); } } } } void ppu::render_window(render_buffer& buffer) noexcept { if(window_line_ >= screen_height || !lcdc_.window_enabled()) { return; } if(wy_ > ly_ || wy_ >= screen_height || wx_ >= screen_width + 7u) { return; } const auto tile_start_addr = address16(lcdc_.window_map_secondary() ? 0x9C00u : 0x9800u); const auto tile_y_to_render = window_line_ % tile_pixel_count; const auto tile_map_y_start = tile_start_addr + window_line_ / tile_pixel_count * map_tile_count; const auto tile_map_x_end = screen_width / tile_pixel_count; for(auto tile_map_x = 0; tile_map_x < tile_map_x_end + 1u; ++tile_map_x) { const auto tile_map_idx = tile_map_y_start + tile_map_x; const auto tile_no = read_ram_by_bank(tile_map_idx, 0); const attributes::bg tile_attr{read_ram_by_bank(tile_map_idx, 1)}; const auto tile_y = tile_attr.v_flipped() ? tile_pixel_count - tile_y_to_render - 1u : tile_y_to_render; auto tile_row = get_tile_row(tile_y, tile_no, tile_attr.vram_bank()); if(tile_attr.h_flipped()) { std::reverse(begin(tile_row), end(tile_row)); } for(auto tile_x = 0u; tile_x < tile_pixel_count; ++tile_x) { const int16_t pix_idx = tile_map_x * tile_pixel_count + tile_x + wx_.value() - 7; if(pix_idx >= static_cast<int32_t>(screen_width)) { ++window_line_; return; } if(0 <= pix_idx) { buffer[pix_idx] = std::make_pair(tile_row[tile_x], tile_attr); } } } } void ppu::render_obj(render_buffer& buffer) const noexcept { if(!lcdc_.obj_enabled()) { return; } const auto obj_size = lcdc_.large_obj() ? 16 : 8; std::array<attributes::obj, 40> objs; std::memcpy(&objs, oam_.data(), oam_.size()); auto indices = [&]() { const int32_t ly = ly_.value(); std::vector<size_t> idxs; for(size_t idx = 0; idx < objs.size(); ++idx) { const auto& obj = objs[idx]; const auto obj_y = obj.y - 16; if(ly >= obj_y && ly < obj_y + obj_size) { idxs.push_back(idx); if(idxs.size() == 10) { break; } } } return idxs; }(); if(!cgb_enabled_) { std::sort(begin(indices), end(indices), [&](const auto l, const auto r) { const auto& obj_l = objs[l]; const auto& obj_r = objs[r]; if(obj_l.x == obj_r.x) { return l < r; } return obj_l.x < obj_r.x; }); } std::reverse(begin(indices), end(indices)); for(const auto index : indices) { const auto& obj = objs[index]; const auto obj_y = obj.y - 16; const auto obj_x = obj.x - 8; if(-7 > obj_x || obj_x >= static_cast<int32_t>(screen_width)) { continue; } auto tile_row = get_tile_row( obj.v_flipped() ? obj_size - (ly_ - obj_y) - 1u : ly_ - obj_y, tile_address<uint8_t>(0x8000u, lcdc_.large_obj() ? obj.tile_number & 0xFEu : obj.tile_number), obj.vram_bank()); if(obj.h_flipped()) { std::reverse(begin(tile_row), end(tile_row)); } for(auto tile_x = 0u; tile_x < tile_pixel_count; ++tile_x) { const auto x = obj_x + tile_x; if(0u > x || x >= screen_width) { continue; } const auto& [color_idx, attr] = buffer[x]; const auto dot_color = tile_row[tile_x]; if(dot_color == 0u) { // obj color0 is transparent continue; } visit_nt(attr, [&](auto&&) { buffer[x] = std::make_pair(dot_color, obj); }, [&, existing_bg_color = color_idx](const attributes::bg& bg_attr) { const auto master_priority_enabled = cgb_enabled_ && !lcdc_.bg_enabled(); const auto obj_priority_enabled = obj.prioritized() && !bg_attr.prioritized(); if(existing_bg_color == 0u || master_priority_enabled || obj_priority_enabled) { buffer[x] = std::make_pair(dot_color, obj); } } ); } } } std::array<uint8_t, ppu::tile_pixel_count> ppu::get_tile_row( const uint8_t row, const uint8_t tile_no, const uint8_t bank) const noexcept { const auto tile_base_addr = lcdc_.unsigned_mode() ? tile_address<uint8_t>(0x8000u, tile_no) : tile_address<int8_t>(0x9000u, tile_no); return get_tile_row(row, tile_base_addr, bank); } std::array<uint8_t, ppu::tile_pixel_count> ppu::get_tile_row( const uint8_t row, const address16& tile_base_addr, const uint8_t bank) const noexcept { const auto tile_y_offset = row * 2; const auto lsb = read_ram_by_bank(tile_base_addr + tile_y_offset, bank); const auto msb = read_ram_by_bank(tile_base_addr + tile_y_offset + 1, bank); struct pixel_generator { uint8_t lsb; uint8_t msb; uint8_t bit = tile_pixel_count - 1; [[nodiscard]] uint8_t operator()() { const auto mask = static_cast<uint32_t>(1u << bit); const auto pix_color = static_cast<uint8_t>((msb & mask) >> bit << 1u | (lsb & mask) >> bit); --bit; return pix_color; } }; std::array<uint8_t, tile_pixel_count> tile_row{}; std::generate(begin(tile_row), end(tile_row), pixel_generator{lsb, msb}); return tile_row; } color ppu::correct_color(const color& c) noexcept { const auto do_correct = [](const uint8_t color) { return static_cast<uint8_t>(color * 0xFFu / 0x1Fu); }; return { do_correct(c.red), do_correct(c.green), do_correct(c.blue) }; } } // namespace gameboy
32.512623
122
0.595023
emrsmsrli
ce977cea3952efc84dfdf9fb7a515787c93be4c2
4,823
hpp
C++
include/graph/GridGraph.hpp
DarkWingMcQuack/GridGraphPathFinder
d8f9a237f17516141bf58c8c86d468f3559af5e3
[ "Apache-2.0" ]
null
null
null
include/graph/GridGraph.hpp
DarkWingMcQuack/GridGraphPathFinder
d8f9a237f17516141bf58c8c86d468f3559af5e3
[ "Apache-2.0" ]
null
null
null
include/graph/GridGraph.hpp
DarkWingMcQuack/GridGraphPathFinder
d8f9a237f17516141bf58c8c86d468f3559af5e3
[ "Apache-2.0" ]
null
null
null
#pragma once #include <graph/GridCell.hpp> #include <graph/GridGraphIterator.hpp> #include <graph/NeigbourCalculator.hpp> #include <graph/Node.hpp> #include <optional> #include <selection/NodeSelection.hpp> #include <separation/Separation.hpp> #include <string_view> #include <vector> namespace graph { class GridGraph { public: static constexpr inline auto is_directed = false; GridGraph(std::vector<std::vector<bool>> grid, NeigbourCalculator neigbour_calculator) noexcept; //the big 5 GridGraph() = delete; GridGraph(GridGraph&&) = default; GridGraph(const GridGraph&) = delete; auto operator=(GridGraph&&) -> GridGraph& = delete; auto operator=(const GridGraph&) -> GridGraph& = delete; [[nodiscard]] auto isBarrier(Node n) const noexcept -> bool; [[nodiscard]] auto isWalkableNode(Node n) const noexcept -> bool; [[nodiscard]] auto getWalkableNeigbours(Node n) const noexcept -> std::vector<Node>; [[nodiscard]] auto getAllWalkableNodesOfCell(const graph::GridCell& cell) const noexcept -> std::vector<Node>; [[nodiscard]] auto generateRandomCellOfSize(std::int64_t cell_size) const noexcept -> graph::GridCell; [[nodiscard]] auto hasWalkableNode(const graph::GridCell& cell) const noexcept -> bool; [[nodiscard]] auto areNeighbours(Node first, Node second) const noexcept -> bool; [[nodiscard]] auto getManhattanNeigbours(Node node) const noexcept -> std::array<Node, 4>; [[nodiscard]] auto getNeigboursOf(Node node) const noexcept -> std::vector<std::pair<Node, Distance>>; [[nodiscard]] auto hasBarrier(const graph::GridCell& cell) const noexcept -> bool; [[nodiscard]] auto hasBarrierNeigbour(Node n) const noexcept -> bool; [[nodiscard]] auto nodeToIndex(const graph::Node& n) const noexcept -> std::size_t; [[nodiscard]] auto indexToNode(std::size_t idx) const noexcept -> Node; [[nodiscard]] auto wrapGraphInCell() const noexcept -> graph::GridCell; [[nodiscard]] auto getAllCellsContaining(Node node) const noexcept -> std::vector<graph::GridCell>; [[nodiscard]] auto getAllParrentCells(GridCell cell) const noexcept -> std::vector<GridCell>; // returns two vectors of cells which when used in separations would have a better weight than // the separation between the given two cells // cells which contain both given cells are also not in the vectors [[nodiscard]] auto getAllPossibleSeparationCells(GridCell left, GridCell right) const noexcept -> std::pair<std::vector<GridCell>, std::vector<GridCell>>; [[nodiscard]] auto countNumberOfWalkableNodes(const graph::GridCell& cell) const noexcept -> std::size_t; [[nodiscard]] auto getRandomWalkableNode() const noexcept -> Node; [[nodiscard]] auto countWalkableNodes() const noexcept -> std::size_t; [[nodiscard]] auto toClipped(Node n) const noexcept -> Node; [[nodiscard]] auto unclip(Node n) const noexcept -> Node; [[nodiscard]] auto toClipped(GridCell g) const noexcept -> GridCell; [[nodiscard]] auto unclip(GridCell g) const noexcept -> GridCell; [[nodiscard]] auto toClipped(GridCorner g) const noexcept -> GridCorner; [[nodiscard]] auto unclip(GridCorner g) const noexcept -> GridCorner; [[nodiscard]] auto unclip(separation::Separation g) const noexcept -> separation::Separation; [[nodiscard]] auto toClipped(separation::Separation g) const noexcept -> separation::Separation; [[nodiscard]] auto unclip(selection::NodeSelection g) const noexcept -> selection::NodeSelection; [[nodiscard]] auto toClipped(selection::NodeSelection g) const noexcept -> selection::NodeSelection; [[nodiscard]] auto getHeight() const noexcept -> std::size_t; [[nodiscard]] auto getWidth() const noexcept -> std::size_t; [[nodiscard]] auto getTrivialDistance(const Node& from, const Node& to) const noexcept -> Distance; [[nodiscard]] auto begin() const noexcept -> GridGraphIterator; [[nodiscard]] auto end() const noexcept -> GridGraphIterator; [[nodiscard]] auto size() const noexcept -> std::size_t; private: std::vector<bool> grid_; NeigbourCalculator neigbour_calculator_; std::size_t height_; std::size_t width_; std::size_t clipped_height_ = 0; std::size_t clipped_width_ = 0; }; [[nodiscard]] auto parseFileToGridGraph(std::string_view path, NeigbourCalculator neigbour_calc) noexcept -> std::optional<GridGraph>; } // namespace graph
30.333333
98
0.663695
DarkWingMcQuack
cea5828e32eb2af2a05e49cd9a65f287b5ba3823
37,535
cpp
C++
rviz_cinematographer_view_controller/src/rviz_cinematographer_view_controller.cpp
qpc001/rviz_cinematographer
51fc022524d6ecebf603bac0c8ab39f22fff1a2f
[ "BSD-3-Clause" ]
113
2018-11-02T17:40:30.000Z
2022-03-08T11:44:00.000Z
rviz_cinematographer_view_controller/src/rviz_cinematographer_view_controller.cpp
tanujthakkar/rviz_cinematographer
04d66f5fbf2f97ac98d88fb67baabde00e5525f8
[ "BSD-3-Clause" ]
11
2019-01-22T22:33:27.000Z
2021-11-26T10:25:11.000Z
rviz_cinematographer_view_controller/src/rviz_cinematographer_view_controller.cpp
tanujthakkar/rviz_cinematographer
04d66f5fbf2f97ac98d88fb67baabde00e5525f8
[ "BSD-3-Clause" ]
17
2018-11-05T08:46:49.000Z
2021-04-14T16:31:31.000Z
/* * Copyright (c) 2009, Willow Garage, 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 Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "rviz_cinematographer_view_controller/rviz_cinematographer_view_controller.h" namespace rviz_cinematographer_view_controller { using namespace rviz; // Strings for selecting control mode styles static const std::string MODE_ORBIT = "Orbit"; static const std::string MODE_FPS = "FPS"; // Limits to prevent orbit controller singularity, but not currently used. static const Ogre::Radian PITCH_LIMIT_LOW = Ogre::Radian(0.02); static const Ogre::Radian PITCH_LIMIT_HIGH = Ogre::Radian(Ogre::Math::PI - 0.02); // Some convenience functions for Ogre / geometry_msgs conversions static inline Ogre::Vector3 vectorFromMsg(const geometry_msgs::Point& m) { return Ogre::Vector3(m.x, m.y, m.z); } static inline Ogre::Vector3 vectorFromMsg(const geometry_msgs::Vector3& m) { return Ogre::Vector3(m.x, m.y, m.z); } static inline geometry_msgs::Point pointOgreToMsg(const Ogre::Vector3& o) { geometry_msgs::Point m; m.x = o.x; m.y = o.y; m.z = o.z; return m; } static inline geometry_msgs::Vector3 vectorOgreToMsg(const Ogre::Vector3& o) { geometry_msgs::Vector3 m; m.x = o.x; m.y = o.y; m.z = o.z; return m; } // ----------------------------------------------------------------------------- CinematographerViewController::CinematographerViewController() : nh_("") , animate_(false) , dragging_(false) , render_frame_by_frame_(false) , target_fps_(60) , recorded_frames_counter_(0) , do_wait_(false) , wait_duration_(-1.f) { interaction_disabled_cursor_ = makeIconCursor("package://rviz/icons/forbidden.svg"); mouse_enabled_property_ = new BoolProperty("Mouse Enabled", true, "Enables mouse control of the camera.", this); interaction_mode_property_ = new EditableEnumProperty("Control Mode", QString::fromStdString(MODE_ORBIT), "Select the style of mouse interaction.", this); interaction_mode_property_->addOptionStd(MODE_ORBIT); interaction_mode_property_->addOptionStd(MODE_FPS); interaction_mode_property_->setStdString(MODE_ORBIT); fixed_up_property_ = new BoolProperty("Maintain Vertical Axis", true, "If enabled, the camera is not allowed to roll side-to-side.", this); attached_frame_property_ = new TfFrameProperty("Target Frame", TfFrameProperty::FIXED_FRAME_STRING, "TF frame the camera is attached to.", this, NULL, true); eye_point_property_ = new VectorProperty("Eye", Ogre::Vector3( 5, 5, 10 ), "Position of the camera.", this); focus_point_property_ = new VectorProperty("Focus", Ogre::Vector3::ZERO, "Position of the focus/orbit point.", this); up_vector_property_ = new VectorProperty("Up", Ogre::Vector3::UNIT_Z, "The vector which maps to \"up\" in the camera image plane.", this); distance_property_ = new FloatProperty("Distance", getDistanceFromCameraToFocalPoint(), "The distance between the camera position and the focus point.", this); distance_property_->setMin(0.01); default_transition_duration_property_ = new FloatProperty("Transition Duration in seconds", 0.5, "The default duration to use for camera transitions.", this); camera_trajectory_topic_property_ = new RosTopicProperty("Trajectory Topic", "/rviz/camera_trajectory", QString::fromStdString( ros::message_traits::datatype<rviz_cinematographer_msgs::CameraTrajectory>()), "Topic for CameraTrajectory messages", this, SLOT(updateTopics())); transition_velocity_property_ = new FloatProperty("Transition Velocity in m/s", 0, "The current velocity of the animated camera.", this); window_width_property_ = new FloatProperty("Window Width", 1000, "The width of the rviz visualization window in pixels.", this); window_height_property_ = new FloatProperty("Window Height", 1000, "The height of the rviz visualization window in pixels.", this); // TODO: latch? placement_pub_ = nh_.advertise<geometry_msgs::Pose>("/rviz/current_camera_pose", 1); odometry_pub_ = nh_.advertise<nav_msgs::Odometry>("/rviz/trajectory_odometry", 1); finished_rendering_trajectory_pub_ = nh_.advertise<rviz_cinematographer_msgs::Finished>("/rviz/finished_rendering_trajectory", 1); delete_pub_ = nh_.advertise<std_msgs::Empty>("/rviz/delete", 1); image_transport::ImageTransport it(nh_); image_pub_ = it.advertise("/rviz/view_image", 1); record_params_sub_ = nh_.subscribe("/rviz/record", 1, &CinematographerViewController::setRecord, this); wait_duration_sub_ = nh_.subscribe("/video_recorder/wait_duration", 1, &CinematographerViewController::setWaitDuration, this); } CinematographerViewController::~CinematographerViewController() { context_->getSceneManager()->destroySceneNode(attached_scene_node_); } void CinematographerViewController::setRecord(const rviz_cinematographer_msgs::Record::ConstPtr& record_params) { render_frame_by_frame_ = record_params->do_record > 0; int max_fps = 120; if(record_params->compress == 0) max_fps = 60; target_fps_ = std::max(1, std::min(max_fps, (int)record_params->frames_per_second)); } void CinematographerViewController::setWaitDuration(const rviz_cinematographer_msgs::Wait::ConstPtr& wait_duration) { wait_duration_ = wait_duration->seconds; do_wait_ = true; } void CinematographerViewController::updateTopics() { trajectory_sub_ = nh_.subscribe<rviz_cinematographer_msgs::CameraTrajectory> (camera_trajectory_topic_property_->getStdString(), 1, boost::bind(&CinematographerViewController::cameraTrajectoryCallback, this, _1)); } void CinematographerViewController::onInitialize() { attached_frame_property_->setFrameManager(context_->getFrameManager()); camera_->detachFromParent(); attached_scene_node_ = context_->getSceneManager()->getRootSceneNode()->createChildSceneNode(); attached_scene_node_->attachObject(camera_); camera_->setProjectionType(Ogre::PT_PERSPECTIVE); focal_shape_ = std::make_shared<rviz::Shape>(Shape::Sphere, context_->getSceneManager(), attached_scene_node_); focal_shape_->setScale(Ogre::Vector3(0.05f, 0.05f, 0.01f)); focal_shape_->setColor(1.0f, 1.0f, 0.0f, 0.5f); focal_shape_->getRootNode()->setVisible(false); const unsigned long buffer_capacity = 100; cam_movements_buffer_ = BufferCamMovements(buffer_capacity); window_width_property_->setFloat(context_->getViewManager()->getRenderPanel()->getRenderWindow()->getWidth()); window_height_property_->setFloat(context_->getViewManager()->getRenderPanel()->getRenderWindow()->getHeight()); } void CinematographerViewController::onActivate() { updateAttachedSceneNode(); // Before activation, changes to target frame property should have // no side-effects. After activation, changing target frame // property has the side effect (typically) of changing an offset // property so that the view does not jump. Therefore we make the // signal/slot connection from the property here in onActivate() // instead of in the constructor. connect(attached_frame_property_, SIGNAL(changed()), this, SLOT(updateAttachedFrame())); connect(fixed_up_property_, SIGNAL(changed()), this, SLOT(onUpPropertyChanged())); connectPositionProperties(); updateTopics(); } void CinematographerViewController::connectPositionProperties() { connect(distance_property_, SIGNAL(changed()), this, SLOT(onDistancePropertyChanged()), Qt::UniqueConnection); connect(eye_point_property_, SIGNAL(changed()), this, SLOT(onEyePropertyChanged()), Qt::UniqueConnection); connect(focus_point_property_, SIGNAL(changed()), this, SLOT(onFocusPropertyChanged()), Qt::UniqueConnection); connect(up_vector_property_, SIGNAL(changed()), this, SLOT(onUpPropertyChanged()), Qt::UniqueConnection); } void CinematographerViewController::disconnectPositionProperties() { disconnect(distance_property_, SIGNAL(changed()), this, SLOT(onDistancePropertyChanged())); disconnect(eye_point_property_, SIGNAL(changed()), this, SLOT(onEyePropertyChanged())); disconnect(focus_point_property_, SIGNAL(changed()), this, SLOT(onFocusPropertyChanged())); disconnect(up_vector_property_, SIGNAL(changed()), this, SLOT(onUpPropertyChanged())); } void CinematographerViewController::onEyePropertyChanged() { distance_property_->setFloat(getDistanceFromCameraToFocalPoint()); } void CinematographerViewController::onFocusPropertyChanged() { distance_property_->setFloat(getDistanceFromCameraToFocalPoint()); } void CinematographerViewController::onDistancePropertyChanged() { disconnectPositionProperties(); Ogre::Vector3 new_eye_position = focus_point_property_->getVector() + distance_property_->getFloat() * camera_->getOrientation().zAxis(); eye_point_property_->setVector(new_eye_position); connectPositionProperties(); } void CinematographerViewController::onUpPropertyChanged() { disconnect(up_vector_property_, SIGNAL(changed()), this, SLOT(onUpPropertyChanged())); if(fixed_up_property_->getBool()) { up_vector_property_->setVector(Ogre::Vector3::UNIT_Z); camera_->setFixedYawAxis(true, reference_orientation_ * Ogre::Vector3::UNIT_Z); } else { // force orientation to match up vector; first call doesn't actually change the quaternion camera_->setFixedYawAxis(true, reference_orientation_ * up_vector_property_->getVector()); camera_->setDirection( reference_orientation_ * (focus_point_property_->getVector() - eye_point_property_->getVector())); // restore normal behavior camera_->setFixedYawAxis(false); } connect(up_vector_property_, SIGNAL(changed()), this, SLOT(onUpPropertyChanged()), Qt::UniqueConnection); } void CinematographerViewController::updateAttachedFrame() { Ogre::Vector3 old_position = attached_scene_node_->getPosition(); Ogre::Quaternion old_orientation = attached_scene_node_->getOrientation(); updateAttachedSceneNode(); onAttachedFrameChanged(old_position, old_orientation); } void CinematographerViewController::updateAttachedSceneNode() { std::string error_msg; if(!context_->getFrameManager()->transformHasProblems(attached_frame_property_->getFrameStd(), ros::Time(), error_msg)) { context_->getFrameManager()->getTransform(attached_frame_property_->getFrameStd(), ros::Time(), reference_position_, reference_orientation_); attached_scene_node_->setPosition(reference_position_); attached_scene_node_->setOrientation(reference_orientation_); context_->queueRender(); } else { ROS_ERROR_STREAM_THROTTLE(2, "Transform not available : " << error_msg); } } void CinematographerViewController::onAttachedFrameChanged(const Ogre::Vector3& old_reference_position, const Ogre::Quaternion& old_reference_orientation) { Ogre::Vector3 fixed_frame_focus_position = old_reference_orientation * focus_point_property_->getVector() + old_reference_position; Ogre::Vector3 fixed_frame_eye_position = old_reference_orientation * eye_point_property_->getVector() + old_reference_position; Ogre::Vector3 new_focus_position = fixedFrameToAttachedLocal(fixed_frame_focus_position); Ogre::Vector3 new_eye_position = fixedFrameToAttachedLocal(fixed_frame_eye_position); Ogre::Vector3 new_up_vector = reference_orientation_.Inverse() * old_reference_orientation * up_vector_property_->getVector(); focus_point_property_->setVector(new_focus_position); eye_point_property_->setVector(new_eye_position); up_vector_property_->setVector(fixed_up_property_->getBool() ? Ogre::Vector3::UNIT_Z : new_up_vector); distance_property_->setFloat(getDistanceFromCameraToFocalPoint()); // force orientation to match up vector; first call doesn't actually change the quaternion camera_->setFixedYawAxis(true, reference_orientation_ * up_vector_property_->getVector()); camera_->setDirection(reference_orientation_ * (focus_point_property_->getVector() - eye_point_property_->getVector())); } float CinematographerViewController::getDistanceFromCameraToFocalPoint() { return (eye_point_property_->getVector() - focus_point_property_->getVector()).length(); } void CinematographerViewController::reset() { eye_point_property_->setVector(Ogre::Vector3(5, 5, 10)); focus_point_property_->setVector(Ogre::Vector3::ZERO); up_vector_property_->setVector(Ogre::Vector3::UNIT_Z); distance_property_->setFloat(getDistanceFromCameraToFocalPoint()); mouse_enabled_property_->setBool(true); interaction_mode_property_->setStdString(MODE_ORBIT); // Hersh says: why is the following junk necessary? I don't know. // However, without this you need to call reset() twice after // switching from TopDownOrtho to FPS. After the first call the // camera is in the right position but pointing the wrong way. updateCamera(); camera_->lookAt(0, 0, 0); setPropertiesFromCamera(camera_); } void CinematographerViewController::handleMouseEvent(ViewportMouseEvent& event) { if(!mouse_enabled_property_->getBool()) { setCursor(interaction_disabled_cursor_); setStatus("<b>Mouse interaction is disabled. You can enable it by checking the \"Mouse Enabled\" check-box in the Views panel."); return; } else if(event.shift()) { setStatus("TODO: Fix me! <b>Left-Click:</b> Move X/Y. <b>Right-Click:</b>: Move Z."); } else if(event.control()) { setStatus("TODO: Fix me! <b>Left-Click:</b> Move X/Y. <b>Right-Click:</b>: Move Z."); } else { setStatus("TODO: Fix me! <b>Left-Click:</b> Rotate. <b>Middle-Click:</b> Move X/Y. <b>Right-Click:</b>: Zoom. <b>Shift</b>: More options."); } float distance = distance_property_->getFloat(); int32_t diff_x = 0; int32_t diff_y = 0; bool moved = false; if(event.type == QEvent::MouseButtonPress) { focal_shape_->getRootNode()->setVisible(true); moved = true; dragging_ = true; cancelTransition(); // Stop any automated movement } else if(event.type == QEvent::MouseButtonRelease) { focal_shape_->getRootNode()->setVisible(false); moved = true; dragging_ = false; } else if(dragging_ && event.type == QEvent::MouseMove) { diff_x = event.x - event.last_x; diff_y = event.y - event.last_y; moved = true; } // regular left-button drag if(event.left() && !event.shift()) { setCursor(Rotate3D); yaw_pitch_roll(-diff_x * 0.005f, -diff_y * 0.005f, 0); } // middle or shift-left drag else if(event.middle() || (event.shift() && event.left())) { setCursor(MoveXY); if(interaction_mode_property_->getStdString() == MODE_ORBIT) // Orbit style { float fovY = camera_->getFOVy().valueRadians(); float fovX = 2.0f * static_cast<float>(atan(tan(fovY / 2.0) * camera_->getAspectRatio())); int width = camera_->getViewport()->getActualWidth(); int height = camera_->getViewport()->getActualHeight(); move_focus_and_eye(-((float)diff_x / width) * distance * static_cast<float>(tan(fovX / 2.0)) * 2.0f, ((float)diff_y / height) * distance * static_cast<float>(tan(fovY / 2.0)) * 2.0f, 0.0f); } else if(interaction_mode_property_->getStdString() == MODE_FPS) // FPS style { move_focus_and_eye(diff_x * 0.01f, -diff_y * 0.01f, 0.0f); } } else if(event.right()) { if(event.shift() || (interaction_mode_property_->getStdString() == MODE_FPS)) { setCursor(MoveZ); move_focus_and_eye(0.0f, 0.0f, diff_y * 0.01f * distance); } else { setCursor(Zoom); move_eye(0, 0, diff_y * 0.01f * distance); } } else { setCursor(event.shift() ? MoveXY : Rotate3D); } if(event.wheel_delta != 0) { int diff = event.wheel_delta; if(event.shift()) move_focus_and_eye(0, 0, -diff * 0.001f * distance); else if(event.control()) yaw_pitch_roll(0, 0, diff * 0.001f); else move_eye(0, 0, -diff * 0.001f * distance); moved = true; } if(event.type == QEvent::MouseButtonPress && event.left() && event.control() && event.shift()) { bool was_orbit = (interaction_mode_property_->getStdString() == MODE_ORBIT); interaction_mode_property_->setStdString(was_orbit ? MODE_FPS : MODE_ORBIT); } if(moved) { publishCameraPose(); context_->queueRender(); } } void CinematographerViewController::handleKeyEvent(QKeyEvent* event, rviz::RenderPanel* panel) { if(event->key() == 16777223) // press on delete button { std_msgs::Empty delete_msg; delete_pub_.publish(delete_msg); } } void CinematographerViewController::setPropertiesFromCamera(Ogre::Camera* source_camera) { disconnectPositionProperties(); Ogre::Vector3 direction = source_camera->getOrientation() * Ogre::Vector3::NEGATIVE_UNIT_Z; eye_point_property_->setVector(source_camera->getPosition()); focus_point_property_->setVector(source_camera->getPosition() + direction * distance_property_->getFloat()); if(fixed_up_property_->getBool()) up_vector_property_->setVector(Ogre::Vector3::UNIT_Z); else up_vector_property_->setVector(source_camera->getOrientation().yAxis()); connectPositionProperties(); } void CinematographerViewController::mimic(ViewController* source_view) { QVariant target_frame = source_view->subProp("Target Frame")->getValue(); if(target_frame.isValid()) attached_frame_property_->setValue(target_frame); Ogre::Camera* source_camera = source_view->getCamera(); Ogre::Vector3 position = source_camera->getPosition(); Ogre::Quaternion orientation = source_camera->getOrientation(); if(source_view->getClassId() == "rviz/Orbit") distance_property_->setFloat(source_view->subProp("Distance")->getValue().toFloat()); else distance_property_->setFloat(position.length()); interaction_mode_property_->setStdString(MODE_ORBIT); Ogre::Vector3 direction = orientation * (Ogre::Vector3::NEGATIVE_UNIT_Z * distance_property_->getFloat()); focus_point_property_->setVector(position + direction); eye_point_property_->setVector(position); updateCamera(); } void CinematographerViewController::transitionFrom(ViewController* previous_view) { auto prev_view_controller = dynamic_cast<CinematographerViewController*>(previous_view); if(prev_view_controller) { Ogre::Vector3 new_eye = eye_point_property_->getVector(); Ogre::Vector3 new_focus = focus_point_property_->getVector(); Ogre::Vector3 new_up = up_vector_property_->getVector(); eye_point_property_->setVector(prev_view_controller->eye_point_property_->getVector()); focus_point_property_->setVector(prev_view_controller->focus_point_property_->getVector()); up_vector_property_->setVector(prev_view_controller->up_vector_property_->getVector()); beginNewTransition(new_eye, new_focus, new_up, ros::Duration(default_transition_duration_property_->getFloat())); } } void CinematographerViewController::beginNewTransition(const Ogre::Vector3& eye, const Ogre::Vector3& focus, const Ogre::Vector3& up, ros::Duration transition_duration, uint8_t interpolation_speed) { // if jump was requested, perform as usual but prevent division by zero if(ros::Duration(transition_duration).isZero()) transition_duration = ros::Duration(0.001); // if the buffer is empty we set the first element in it to the current camera pose if(cam_movements_buffer_.empty()) { transition_start_time_ = ros::WallTime::now(); cam_movements_buffer_.push_back(std::move(OgreCameraMovement(eye_point_property_->getVector(), focus_point_property_->getVector(), up_vector_property_->getVector(), ros::Duration(0.001), interpolation_speed))); // interpolation_speed doesn't make a difference for very short times } if(cam_movements_buffer_.full()) cam_movements_buffer_.set_capacity(cam_movements_buffer_.capacity() + 20); cam_movements_buffer_.push_back(std::move(OgreCameraMovement(eye, focus, up, transition_duration, interpolation_speed))); animate_ = true; } void CinematographerViewController::cancelTransition() { animate_ = false; cam_movements_buffer_.clear(); recorded_frames_counter_ = 0; if(render_frame_by_frame_) { rviz_cinematographer_msgs::Finished finished; finished.is_finished = true; finished_rendering_trajectory_pub_.publish(finished); render_frame_by_frame_ = false; } } void CinematographerViewController::cameraTrajectoryCallback(const rviz_cinematographer_msgs::CameraTrajectoryConstPtr& ct_ptr) { rviz_cinematographer_msgs::CameraTrajectory ct = *ct_ptr; if(ct.trajectory.empty()) return; // Handle control parameters mouse_enabled_property_->setBool(!ct.interaction_disabled); fixed_up_property_->setBool(!ct.allow_free_yaw_axis); if(ct.mouse_interaction_mode != rviz_cinematographer_msgs::CameraTrajectory::NO_CHANGE) { std::string name = ""; if(ct.mouse_interaction_mode == rviz_cinematographer_msgs::CameraTrajectory::ORBIT) name = MODE_ORBIT; else if(ct.mouse_interaction_mode == rviz_cinematographer_msgs::CameraTrajectory::FPS) name = MODE_FPS; interaction_mode_property_->setStdString(name); } for(auto& cam_movement : ct.trajectory) { transformCameraMovementToAttachedFrame(cam_movement); if(ct.target_frame != "") { attached_frame_property_->setStdString(ct.target_frame); updateAttachedFrame(); } Ogre::Vector3 eye = vectorFromMsg(cam_movement.eye.point); Ogre::Vector3 focus = vectorFromMsg(cam_movement.focus.point); Ogre::Vector3 up = vectorFromMsg(cam_movement.up.vector); beginNewTransition(eye, focus, up, cam_movement.transition_duration, cam_movement.interpolation_speed); } } void CinematographerViewController::transformCameraMovementToAttachedFrame(rviz_cinematographer_msgs::CameraMovement& cm) { Ogre::Vector3 position_fixed_eye, position_fixed_focus, position_fixed_up; Ogre::Quaternion rotation_fixed_eye, rotation_fixed_focus, rotation_fixed_up; context_->getFrameManager()->getTransform(cm.eye.header.frame_id, ros::Time(0), position_fixed_eye, rotation_fixed_eye); context_->getFrameManager()->getTransform(cm.focus.header.frame_id, ros::Time(0), position_fixed_focus, rotation_fixed_focus); context_->getFrameManager()->getTransform(cm.up.header.frame_id, ros::Time(0), position_fixed_up, rotation_fixed_up); Ogre::Vector3 eye = vectorFromMsg(cm.eye.point); Ogre::Vector3 focus = vectorFromMsg(cm.focus.point); Ogre::Vector3 up = vectorFromMsg(cm.up.vector); eye = fixedFrameToAttachedLocal(position_fixed_eye + rotation_fixed_eye * eye); focus = fixedFrameToAttachedLocal(position_fixed_focus + rotation_fixed_focus * focus); up = reference_orientation_.Inverse() * rotation_fixed_up * up; cm.eye.point = pointOgreToMsg(eye); cm.focus.point = pointOgreToMsg(focus); cm.up.vector = vectorOgreToMsg(up); cm.eye.header.frame_id = attached_frame_property_->getStdString(); cm.focus.header.frame_id = attached_frame_property_->getStdString(); cm.up.header.frame_id = attached_frame_property_->getStdString(); } // We must assume that this point is in the Rviz Fixed frame since it came from Rviz... void CinematographerViewController::lookAt(const Ogre::Vector3& point) { if(!mouse_enabled_property_->getBool()) return; Ogre::Vector3 new_point = fixedFrameToAttachedLocal(point); beginNewTransition(eye_point_property_->getVector(), new_point, up_vector_property_->getVector(), ros::Duration(default_transition_duration_property_->getFloat())); } void CinematographerViewController::publishOdometry(const Ogre::Vector3& position, const Ogre::Vector3& velocity) { nav_msgs::Odometry odometry; odometry.header.frame_id = attached_frame_property_->getFrameStd(); odometry.header.stamp = ros::Time::now(); odometry.pose.pose.position.x = position.x; odometry.pose.pose.position.y = position.y; odometry.pose.pose.position.z = position.z; odometry.twist.twist.linear.x = velocity.x; //This is allo velocity and therefore not ROS convention! odometry.twist.twist.linear.y = velocity.y; //This is allo velocity and therefore not ROS convention! odometry.twist.twist.linear.z = velocity.z; //This is allo velocity and therefore not ROS convention! Ogre::Quaternion cam_orientation = camera_->getOrientation(); Ogre::Quaternion rot_around_y_pos_90_deg(0.707f, 0.0f, 0.707f, 0.0f); cam_orientation = cam_orientation * rot_around_y_pos_90_deg; odometry.pose.pose.orientation.x = cam_orientation.x; odometry.pose.pose.orientation.y = cam_orientation.y; odometry.pose.pose.orientation.z = cam_orientation.z; odometry.pose.pose.orientation.w = cam_orientation.w; odometry_pub_.publish(odometry); } float CinematographerViewController::computeRelativeProgressInSpace(double relative_progress_in_time, uint8_t interpolation_speed) { switch(interpolation_speed) { case rviz_cinematographer_msgs::CameraMovement::RISING: return 1.f - static_cast<float>(cos(relative_progress_in_time * M_PI_2)); case rviz_cinematographer_msgs::CameraMovement::DECLINING: return static_cast<float>(-cos(relative_progress_in_time * M_PI_2 + M_PI_2)); case rviz_cinematographer_msgs::CameraMovement::FULL: return static_cast<float>(relative_progress_in_time); case rviz_cinematographer_msgs::CameraMovement::WAVE: default: return 0.5f * (1.f - static_cast<float>(cos(relative_progress_in_time * M_PI))); } } void CinematographerViewController::update(float dt, float ros_dt) { updateAttachedSceneNode(); // there has to be at least two positions in the buffer - start and goal if(animate_ && cam_movements_buffer_.size() > 1) { auto start = cam_movements_buffer_.begin(); auto goal = ++(cam_movements_buffer_.begin()); double relative_progress_in_time = 0.0; if(render_frame_by_frame_) { relative_progress_in_time = recorded_frames_counter_ / (target_fps_ * goal->transition_duration.toSec()); recorded_frames_counter_++; } else { ros::WallDuration duration_from_start = ros::WallTime::now() - transition_start_time_; relative_progress_in_time = duration_from_start.toSec() / goal->transition_duration.toSec(); } // make sure we get all the way there before turning off if(relative_progress_in_time >= 1.0) { relative_progress_in_time = 1.0; animate_ = false; } float relative_progress_in_space = computeRelativeProgressInSpace(relative_progress_in_time, goal->interpolation_speed); Ogre::Vector3 new_position = start->eye + relative_progress_in_space * (goal->eye - start->eye); Ogre::Vector3 new_focus = start->focus + relative_progress_in_space * (goal->focus - start->focus); Ogre::Vector3 new_up = start->up + relative_progress_in_space * (goal->up - start->up); Ogre::Vector3 velocity = (new_position - eye_point_property_->getVector()) / ros_dt; transition_velocity_property_->setFloat(velocity.normalise()); if(odometry_pub_.getNumSubscribers() != 0) publishOdometry(new_position, velocity); disconnectPositionProperties(); eye_point_property_->setVector(new_position); focus_point_property_->setVector(new_focus); up_vector_property_->setVector(new_up); distance_property_->setFloat(getDistanceFromCameraToFocalPoint()); connectPositionProperties(); // This needs to happen so that the camera orientation will update properly when fixed_up_property == false camera_->setFixedYawAxis(true, reference_orientation_ * up_vector_property_->getVector()); camera_->setDirection(reference_orientation_ * (focus_point_property_->getVector() - eye_point_property_->getVector())); publishCameraPose(); if(render_frame_by_frame_ && image_pub_.getNumSubscribers() > 0) publishViewImage(); // if current movement is over if(!animate_) { // delete current start element in buffer cam_movements_buffer_.pop_front(); recorded_frames_counter_ = 0; // if there are still movements to perform if(cam_movements_buffer_.size() > 1) { // reset animate to perform the next movement animate_ = true; // update the transition start time with the duration the transition should have taken transition_start_time_ += ros::WallDuration(cam_movements_buffer_.front().transition_duration.toSec()); } else { // clean up cam_movements_buffer_.clear(); // publish that the rendering is finished if(render_frame_by_frame_) { rviz_cinematographer_msgs::Finished finished; finished.is_finished = true; // wait a little so last image is send before this "finished"-message ros::WallRate r(1); r.sleep(); finished_rendering_trajectory_pub_.publish(finished); render_frame_by_frame_ = false; } } } } else transition_velocity_property_->setFloat(0.f); updateCamera(); window_width_property_->setFloat(context_->getViewManager()->getRenderPanel()->getRenderWindow()->getWidth()); window_height_property_->setFloat(context_->getViewManager()->getRenderPanel()->getRenderWindow()->getHeight()); } void CinematographerViewController::publishViewImage() { // wait for specified duration - e.g. if recorder is not fast enough if(do_wait_) { ros::WallRate r(1.f / wait_duration_); r.sleep(); do_wait_ = false; } unsigned int height = context_->getViewManager()->getRenderPanel()->getRenderWindow()->getHeight(); unsigned int width = context_->getViewManager()->getRenderPanel()->getRenderWindow()->getWidth(); // create a PixelBox of the needed size to store the rendered image Ogre::PixelFormat format = Ogre::PF_BYTE_BGR; auto outBytesPerPixel = Ogre::PixelUtil::getNumElemBytes(format); auto data = new unsigned char[width * height * outBytesPerPixel]; Ogre::Box extents(0, 0, width, height); Ogre::PixelBox pb(extents, format, data); context_->getViewManager()->getRenderPanel()->getRenderWindow()->copyContentsToMemory(pb, Ogre::RenderTarget::FB_AUTO); // convert the image in the PixelBox to a sensor_msgs::Image and publish sensor_msgs::ImagePtr ros_image = sensor_msgs::ImagePtr(new sensor_msgs::Image());; ros_image->header.frame_id = attached_frame_property_->getStdString(); ros_image->header.stamp = ros::Time::now(); ros_image->height = height; ros_image->width = width; ros_image->encoding = sensor_msgs::image_encodings::BGR8; ros_image->is_bigendian = false; ros_image->step = static_cast<unsigned int>(width * outBytesPerPixel); size_t size = width * outBytesPerPixel * height; ros_image->data.resize(size); memcpy((char*)(&ros_image->data[0]), data, size); image_pub_.publish(ros_image); delete[] data; } void CinematographerViewController::updateCamera() { camera_->setPosition(eye_point_property_->getVector()); camera_->setFixedYawAxis(fixed_up_property_->getBool(), reference_orientation_ * up_vector_property_->getVector()); camera_->setDirection(reference_orientation_ * (focus_point_property_->getVector() - eye_point_property_->getVector())); focal_shape_->setPosition(focus_point_property_->getVector()); } void CinematographerViewController::publishCameraPose() { geometry_msgs::Pose cam_pose; cam_pose.position.x = camera_->getPosition().x; cam_pose.position.y = camera_->getPosition().y; cam_pose.position.z = camera_->getPosition().z; cam_pose.orientation.w = camera_->getOrientation().w; cam_pose.orientation.x = camera_->getOrientation().x; cam_pose.orientation.y = camera_->getOrientation().y; cam_pose.orientation.z = camera_->getOrientation().z; placement_pub_.publish(cam_pose); } void CinematographerViewController::yaw_pitch_roll(float yaw, float pitch, float roll) { Ogre::Quaternion old_camera_orientation = camera_->getOrientation(); Ogre::Radian old_pitch = old_camera_orientation.getPitch(false); if(fixed_up_property_->getBool()) yaw = static_cast<float>(cos(old_pitch.valueRadians() - Ogre::Math::HALF_PI)) * yaw; // helps to reduce crazy spinning! Ogre::Quaternion yaw_quat, pitch_quat, roll_quat; yaw_quat.FromAngleAxis(Ogre::Radian(yaw), Ogre::Vector3::UNIT_Y); pitch_quat.FromAngleAxis(Ogre::Radian(pitch), Ogre::Vector3::UNIT_X); roll_quat.FromAngleAxis(Ogre::Radian(roll), Ogre::Vector3::UNIT_Z); Ogre::Quaternion orientation_change = yaw_quat * pitch_quat * roll_quat; Ogre::Quaternion new_camera_orientation = old_camera_orientation * orientation_change; Ogre::Radian new_pitch = new_camera_orientation.getPitch(false); if(fixed_up_property_->getBool() && ((new_pitch > PITCH_LIMIT_HIGH && new_pitch > old_pitch) || (new_pitch < PITCH_LIMIT_LOW && new_pitch < old_pitch))) { orientation_change = yaw_quat * roll_quat; new_camera_orientation = old_camera_orientation * orientation_change; } camera_->setOrientation(new_camera_orientation); if(interaction_mode_property_->getStdString() == MODE_ORBIT) { // In orbit mode the focal point stays fixed, so we need to compute the new camera position. Ogre::Vector3 new_eye_position = focus_point_property_->getVector() + distance_property_->getFloat() * new_camera_orientation.zAxis(); eye_point_property_->setVector(new_eye_position); camera_->setPosition(new_eye_position); setPropertiesFromCamera(camera_); } else { // In FPS mode the camera stays fixed, so we can just apply the rotations and then rely on the property update to set the new focal point. setPropertiesFromCamera(camera_); } } void CinematographerViewController::move_focus_and_eye(const float x, const float y, const float z) { Ogre::Vector3 translate(x, y, z); eye_point_property_->add(camera_->getOrientation() * translate); focus_point_property_->add(camera_->getOrientation() * translate); } void CinematographerViewController::move_eye(const float x, const float y, const float z) { Ogre::Vector3 translate(x, y, z); // Only update the camera position if it won't "pass through" the origin Ogre::Vector3 new_position = eye_point_property_->getVector() + camera_->getOrientation() * translate; if((new_position - focus_point_property_->getVector()).length() > distance_property_->getMin()) eye_point_property_->setVector(new_position); distance_property_->setFloat(getDistanceFromCameraToFocalPoint()); } } // end namespace rviz #include <pluginlib/class_list_macros.h> PLUGINLIB_EXPORT_CLASS(rviz_cinematographer_view_controller::CinematographerViewController, rviz::ViewController)
42.269144
168
0.71773
qpc001
cea8c1e43c062e8794dbb0142c6d6e809251a527
1,209
cpp
C++
src/test.cpp
stestagg/pytubes
003b2a5045417317667559ce39ddd0a005208e70
[ "MIT" ]
166
2018-03-05T14:43:26.000Z
2022-01-01T17:59:37.000Z
src/test.cpp
stestagg/pytubes
003b2a5045417317667559ce39ddd0a005208e70
[ "MIT" ]
14
2018-02-27T10:23:33.000Z
2020-02-04T14:36:16.000Z
src/test.cpp
stestagg/pytubes
003b2a5045417317667559ce39ddd0a005208e70
[ "MIT" ]
15
2018-03-06T05:00:30.000Z
2021-12-04T19:43:12.000Z
#define CATCH_CONFIG_RUNNER #include <catch2.hpp> #include <Python.h> void __Pyx_CppExn2PyErr() {}; struct LogPyErrors : Catch::TestEventListenerBase { using TestEventListenerBase::TestEventListenerBase; // inherit constructor void testCaseStarting( Catch::TestCaseInfo const& testInfo ) override { if (PyErr_Occurred()) { PyErr_PrintEx(0); printf("\x1b[0m"); } } void testCaseEnded( Catch::TestCaseStats const& testCaseStats ) override { if (PyErr_Occurred()) { printf("\n┌\x1b[31mPython Exception left unhandled\x1b[0m\n"); printf("├\x1b[34mTest: \x1b[1m%s\x1b[0m\n", testCaseStats.testInfo.name.c_str()); printf("├\x1b[33mFile: \x1b[1m%s:%lu\x1b[0m\n", testCaseStats.testInfo.lineInfo.file, testCaseStats.testInfo.lineInfo.line ); printf("┴\x1b[31;1m"); PyErr_PrintEx(0); printf("\x1b[0m\n"); } } }; CATCH_REGISTER_LISTENER( LogPyErrors ) int main( int argc, char* argv[] ) { Py_Initialize(); int result = Catch::Session().run(argc, argv); return result; }
27.477273
92
0.590571
stestagg
cea95b6f8759013aecb938ea98fa77b9b583e2ba
1,679
cpp
C++
source/visual/cGlow.cpp
MausGames/project-one
157c93e8b4a926528ce5e77efacfcd950ea361f9
[ "Zlib" ]
3
2015-06-30T00:10:29.000Z
2021-03-09T21:05:11.000Z
source/visual/cGlow.cpp
MausGames/project-one
157c93e8b4a926528ce5e77efacfcd950ea361f9
[ "Zlib" ]
null
null
null
source/visual/cGlow.cpp
MausGames/project-one
157c93e8b4a926528ce5e77efacfcd950ea361f9
[ "Zlib" ]
null
null
null
/////////////////////////////////////////////////////// //*-------------------------------------------------*// //| Part of Project One (https://www.maus-games.at) |// //*-------------------------------------------------*// //| Released under the zlib License |// //| More information available in the readme file |// //*-------------------------------------------------*// /////////////////////////////////////////////////////// #include "main.h" // **************************************************************** // constructor cGlow::cGlow()noexcept : m_Blur (CORE_GL_SUPPORT(EXT_packed_float) ? CORE_TEXTURE_SPEC_R11F_G11F_B10F : (CORE_GL_SUPPORT(ARB_texture_float) ? CORE_TEXTURE_SPEC_RGB16F : CORE_TEXTURE_SPEC_RGB10_A2), GLOW_SCALE_FACTOR, GLOW_ATTENUATION_FACTOR) , m_bActive (false) { } // **************************************************************** // update the glow-effect void cGlow::Update() { if(!g_CurConfig.Graphics.iGlow || (!TIME && Core::System->GetCurFrame())) { // m_bActive = false; return; } // create glow only with active objects m_bActive = !this->IsEmpty() || g_pSpecialEffects->IsActive(); if(m_bActive) { m_Blur.Start(); { // render single objects FOR_EACH(it, this->GetObjectSet()) (*it)->coreObject3D::Render(); // # use low-polygon models // render lists with objects FOR_EACH(it, this->GetListSet()) (*it)->Render(); // render special-effects g_pSpecialEffects->Render(); } m_Blur.End(); } else m_Blur.Clear(); }
32.288462
221
0.449672
MausGames
ceb2298d02ed3ec0e649b46a57f97e796ac42fb9
710
cpp
C++
UVaOnlineJudge/Contest_Volumes(10000...)/Volume122(12200-12299)/12250/code.cpp
luiscbr92/algorithmic-challenges
bc35729e54e4284e9ade1aa61b51a1c2d72aa62c
[ "MIT" ]
3
2015-10-21T18:56:43.000Z
2017-06-06T10:44:22.000Z
UVaOnlineJudge/Contest_Volumes(10000...)/Volume122(12200-12299)/12250/code.cpp
luiscbr92/algorithmic-challenges
bc35729e54e4284e9ade1aa61b51a1c2d72aa62c
[ "MIT" ]
null
null
null
UVaOnlineJudge/Contest_Volumes(10000...)/Volume122(12200-12299)/12250/code.cpp
luiscbr92/algorithmic-challenges
bc35729e54e4284e9ade1aa61b51a1c2d72aa62c
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main(){ string line; int i = 1; while(getline(cin, line) && line[0] != '#'){ if(line=="HELLO") cout << "Case " << i << ": ENGLISH\n"; else if(line=="HOLA") cout << "Case " << i << ": SPANISH\n"; else if(line=="HALLO") cout << "Case " << i << ": GERMAN\n"; else if(line=="BONJOUR") cout << "Case " << i << ": FRENCH\n"; else if(line=="CIAO") cout << "Case " << i << ": ITALIAN\n"; else if(line=="ZDRAVSTVUJTE") cout << "Case " << i << ": RUSSIAN\n"; else cout << "Case " << i << ": UNKNOWN\n"; i++; } }
33.809524
78
0.412676
luiscbr92
ceb2469168f7e815a3e08352b59fe4933b45e6f8
2,953
hpp
C++
source/hougfx/include/hou/gfx/text_vertex.hpp
DavideCorradiDev/houzi-game-engine
d704aa9c5b024300578aafe410b7299c4af4fcec
[ "MIT" ]
2
2018-04-12T20:59:20.000Z
2018-07-26T16:04:07.000Z
source/hougfx/include/hou/gfx/text_vertex.hpp
DavideCorradiDev/houzi-game-engine
d704aa9c5b024300578aafe410b7299c4af4fcec
[ "MIT" ]
null
null
null
source/hougfx/include/hou/gfx/text_vertex.hpp
DavideCorradiDev/houzi-game-engine
d704aa9c5b024300578aafe410b7299c4af4fcec
[ "MIT" ]
null
null
null
// Houzi Game Engine // Copyright (c) 2018 Davide Corradi // Licensed under the MIT license. #ifndef HOU_GFX_TEXT_VERTEX_HPP #define HOU_GFX_TEXT_VERTEX_HPP #include "hou/gfx/gfx_config.hpp" #include "hou/cor/pragmas.hpp" #include "hou/gl/open_gl.hpp" #include "hou/mth/matrix.hpp" namespace hou { class vertex_format; HOU_PRAGMA_PACK_PUSH(1) /** Represents a vertex used to render text. * * The vertex contains information about its position and texture coordinates. */ class HOU_GFX_API text_vertex { public: /** Retrieves the vertex_format. */ static const vertex_format& get_vertex_format(); public: /** Builds a text_vertex object with all elements set to 0. */ text_vertex() noexcept; /** Builds a text_vertex object with the given position and texture * coordinates. * * \param position the vertex position. * * \param tex_coords the vertex texture coordinates. */ text_vertex(const vec2f& position, const vec3f& tex_coords) noexcept; /** Gets the vertex position. * * \return the vertex position. */ vec2f get_position() const noexcept; /** Sets the vertex position. * * \param pos the vertex position. */ void set_position(const vec2f& pos) noexcept; /** Gets the vertex texture coordinates. * * \return the vertex texture coordinates. */ vec3f get_texture_coordinates() const noexcept; /** Sets the vertex texture coordinates. * * \param tex_coords the vertex texture coordinates. */ void set_texture_coordinates(const vec3f& tex_coords) noexcept; private: static constexpr size_t s_position_size = 2u; static constexpr size_t s_texture_coordinates_size = 3u; private: GLfloat m_position[s_position_size]; GLfloat m_tex_coords[s_texture_coordinates_size]; }; HOU_PRAGMA_PACK_POP() /** Checks if two text_vertex objects are equal. * * \param lhs the left operand. * * \param rhs the right operand. * * \return true if the two objects are equal. */ HOU_GFX_API bool operator==( const text_vertex& lhs, const text_vertex& rhs) noexcept; /** Checks if two text_vertex objects are not equal. * * \param lhs the left operand. * * \param rhs the right operand. * * \return true if the two objects are not equal. */ HOU_GFX_API bool operator!=( const text_vertex& lhs, const text_vertex& rhs) noexcept; /** Checks if two text_vertex objects are equal with the specified accuracy. * * \param lhs the left operand. * * \param rhs the right operand. * * \param acc the accuracy. * * \return true if the two objects are equal. */ HOU_GFX_API bool close(const text_vertex& lhs, const text_vertex& rhs, float acc = std::numeric_limits<float>::epsilon()) noexcept; /** Writes the object into a stream. * * \param os the stream. * * \param v the text_vertex. * * \return a reference to os. */ HOU_GFX_API std::ostream& operator<<(std::ostream& os, const text_vertex& v); } // namespace hou #endif
22.203008
78
0.714528
DavideCorradiDev
ceb4065c35a9a3cdbaae7aca579120902127c6fe
397
cpp
C++
example/fact.cpp
lisqlql/pyaspp
06dac7fe42684f6158bef24ac5e4ae4c60c384ab
[ "MIT" ]
null
null
null
example/fact.cpp
lisqlql/pyaspp
06dac7fe42684f6158bef24ac5e4ae4c60c384ab
[ "MIT" ]
null
null
null
example/fact.cpp
lisqlql/pyaspp
06dac7fe42684f6158bef24ac5e4ae4c60c384ab
[ "MIT" ]
null
null
null
#py MAX_N = 20 #py{ def cpp_fact(n, res): return cpp.define('FACT_{}'.format(n), res) def gen_fact(): acc = 1 yield cpp_fact(0, 1) for n in range(1, MAX_N + 1): acc *= n yield cpp_fact(n, acc) #py} #py= gen_fact() int main() { std::cout << FACT_1 << std::endl; std::cout << FACT_10 << std::endl; std::cout << FACT_20 << std::endl; return 0; }
15.88
47
0.536524
lisqlql
ceb8c62b11ca0335abff994ee5a866cf731bfff7
5,017
cpp
C++
src/advphdr.cpp
taviso/mpgravity
f6a2a7a02014b19047e44db76ae551bd689c16ac
[ "BSD-3-Clause" ]
9
2020-04-01T04:15:22.000Z
2021-09-26T21:03:47.000Z
src/advphdr.cpp
taviso/mpgravity
f6a2a7a02014b19047e44db76ae551bd689c16ac
[ "BSD-3-Clause" ]
17
2020-04-02T19:38:40.000Z
2020-04-12T05:47:08.000Z
src/advphdr.cpp
taviso/mpgravity
f6a2a7a02014b19047e44db76ae551bd689c16ac
[ "BSD-3-Clause" ]
null
null
null
/*****************************************************************************/ /* SOURCE CONTROL VERSIONS */ /*---------------------------------------------------------------------------*/ /* */ /* Version Date Time Author / Comment (optional) */ /* */ /* $Log: advphdr.cpp,v $ /* Revision 1.1 2010/07/21 17:14:56 richard_wood /* Initial checkin of V3.0.0 source code and other resources. /* Initial code builds V3.0.0 RC1 /* /* Revision 1.3 2009/08/25 20:04:25 richard_wood /* Updates for 2.9.9 /* /* Revision 1.2 2009/08/16 21:05:38 richard_wood /* Changes for V2.9.7 /* /* Revision 1.1 2009/06/09 13:21:28 richard_wood /* *** empty log message *** /* /* Revision 1.2 2008/09/19 14:51:09 richard_wood /* Updated for VS 2005 /* */ /* */ /*****************************************************************************/ /********************************************************************************** Copyright (c) 2003, Albert M. Choy 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 Microplanet, 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. **********************************************************************************/ // advphdr.cpp : implementation file // #include "stdafx.h" #include "news.h" #include "advphdr.h" #include "newsdb.h" #include "nameutil.h" // DDV_EmailName() #include "arttext.h" // fnFromLine() #include "server.h" // TNewsServer #include "genutil.h" // DDX_CEditStringList #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char BASED_CODE THIS_FILE[] = __FILE__; #endif extern TNewsDB* gpStore; ///////////////////////////////////////////////////////////////////////////// // TAdvancedPostHdr dialog TAdvancedPostHdr::TAdvancedPostHdr(CWnd* pParent /*=NULL*/, TNewsServer * pServer, LONG lGroupID) : CDialog(TAdvancedPostHdr::IDD, pParent), m_pServer(pServer) { m_dist = _T(""); m_expires = _T(""); m_followup = _T(""); m_keywords = _T(""); m_organization = _T(""); m_replyto = _T(""); m_sender = _T(""); m_summary = _T(""); m_from = _T(""); m_replyto = m_pServer->GetReplyTo(); m_dist = gpStore->GetGlobalOptions()->GetDistribution(); fnFromLine(m_from, lGroupID); } void TAdvancedPostHdr::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Text(pDX, IDC_HDR_DISTRIBUTION, m_dist); DDX_Text(pDX, IDC_HDR_EXPIRES, m_expires); DDX_Text(pDX, IDC_HDR_FOLLOWUP, m_followup); DDX_Text(pDX, IDC_HDR_KEYWORDS, m_keywords); DDX_Text(pDX, IDC_HDR_ORGANIZATION, m_organization); DDX_Text(pDX, IDC_HDR_SUMMARY, m_summary); // class-wizard chokes on this DDX_EmailName(pDX, IDC_HDR_REPLYTO, m_replyto); DDV_EmailName(pDX, IDC_HDR_REPLYTO, m_replyto, FALSE); // not required ADVPHDR.CPP DDX_EmailName(pDX, IDC_HDR_SENDER, m_sender); DDV_EmailName(pDX, IDC_HDR_SENDER, m_sender, FALSE); // ADVP2 not required DDX_EmailName(pDX, IDC_HDR_FROM, m_from); DDV_EmailName(pDX, IDC_HDR_FROM, m_from, TRUE); DDX_CEditStringList (pDX, IDC_HDR_CUSTOM, m_sCustomHeaders); } BEGIN_MESSAGE_MAP(TAdvancedPostHdr, CDialog) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // TAdvancedPostHdr message handlers
39.503937
85
0.590791
taviso
cebc6e04fe03da69388603f3c2d2c6681b23d431
6,654
cpp
C++
Graphics/tutorials/ParticleEmitter.cpp
LoganPletcher/Year-2
827d46ace6230225e2cd5638266f10296d410d77
[ "MIT" ]
null
null
null
Graphics/tutorials/ParticleEmitter.cpp
LoganPletcher/Year-2
827d46ace6230225e2cd5638266f10296d410d77
[ "MIT" ]
null
null
null
Graphics/tutorials/ParticleEmitter.cpp
LoganPletcher/Year-2
827d46ace6230225e2cd5638266f10296d410d77
[ "MIT" ]
null
null
null
#include "ParticleEmitter.h" #include "gl_core_4_4.h" #include <glm/gtc/random.hpp> using glm::vec3; using glm::vec4; using glm::mat4; ParticleEmitter::ParticleEmitter() : m_particles(nullptr), m_aliveParticles(0), m_maxParticles(0), m_transform(1), m_vao(0), m_vbo(0), m_ibo(0), m_vertices(nullptr) { } ParticleEmitter::~ParticleEmitter() { delete[] m_particles; delete[] m_vertices; glDeleteVertexArrays(1, &m_vao); glDeleteBuffers(1, &m_vbo); glDeleteBuffers(1, &m_ibo); } void ParticleEmitter::initialise(unsigned int maxParticles, unsigned int emitRate, float lifetimeMin, float lifetimeMax, float velocityMin, float velocityMax, float startSize, float endSize, const glm::vec4& startColour, const glm::vec4& endColour) { // set up emit timers m_emitTimer = 0; m_emitRate = 1.0f / emitRate; // store all variables passed in m_startColour = startColour; m_endColour = endColour; m_startSize = startSize; m_endSize = endSize; m_velocityMin = velocityMin; m_velocityMax = velocityMax; m_lifespanMin = lifetimeMin; m_lifespanMax = lifetimeMax; m_maxParticles = maxParticles; // create particle array m_particles = new Particle[m_maxParticles]; // none are alive yet m_aliveParticles = 0; // create the array of vertices for the particles // 4 vertices per particle for a quad // will be filled during update m_vertices = new ParticleVertex[m_maxParticles * 4]; // create the index buffer data for the particles // 6 indices per quad of 2 triangles // fill it now as it never changes unsigned int* indexData = new unsigned int[m_maxParticles * 6]; for (unsigned int i = 0; i < m_maxParticles; ++i) { indexData[i * 6 + 0] = i * 4 + 0; indexData[i * 6 + 1] = i * 4 + 1; indexData[i * 6 + 2] = i * 4 + 2; indexData[i * 6 + 3] = i * 4 + 0; indexData[i * 6 + 4] = i * 4 + 2; indexData[i * 6 + 5] = i * 4 + 3; } // create opengl buffers glGenBuffers(1, &m_vbo); glGenBuffers(1, &m_ibo); // create the vertex array object and populate it glGenVertexArrays(1, &m_vao); glBindVertexArray(m_vao); glBindBuffer(GL_ARRAY_BUFFER, m_vbo); glBufferData(GL_ARRAY_BUFFER, m_maxParticles * 4 * sizeof(ParticleVertex), m_vertices, GL_DYNAMIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ibo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, m_maxParticles * 6 * sizeof(unsigned int), indexData, GL_STATIC_DRAW); glEnableVertexAttribArray(0); // position glEnableVertexAttribArray(1); // colour glEnableVertexAttribArray(2); // texcoord glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(ParticleVertex), 0); glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(ParticleVertex), (void*)sizeof(glm::vec4)); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(ParticleVertex), (void*)(sizeof(glm::vec4)*2)); glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); delete[] indexData; } void ParticleEmitter::emit() { // don't emit if we have no dead particles to ressurrect if (m_aliveParticles >= m_maxParticles) return; // access the first dead particle and increase alive count Particle& particle = m_particles[m_aliveParticles++]; // start its position at the position of the emitter particle.position = vec3(m_transform[3]); // give it a random direction and set velocity float v = glm::linearRand(m_velocityMin, m_velocityMax); particle.velocity = glm::sphericalRand(v); // randomise its lifespan particle.lifetime = 0; particle.lifespan = glm::linearRand(m_lifespanMin, m_lifespanMax); // give it starting properties particle.colour = m_startColour; particle.size = m_startSize; } void ParticleEmitter::draw() { // update the opengl buffer glBindBuffer(GL_ARRAY_BUFFER, m_vbo); glBufferSubData(GL_ARRAY_BUFFER, 0, m_aliveParticles * 4 * sizeof(ParticleVertex), m_vertices); // draw the alive particles glBindVertexArray(m_vao); glDrawElements(GL_TRIANGLES, m_aliveParticles * 6, GL_UNSIGNED_INT, 0); } void ParticleEmitter::update(float deltaTime, const glm::mat4& cameraTransform) { // emit particles // we loop and use a timer so that we can correctly spawn // the right amount // if we didn't and spawned one per frame, or didn't count back // the timer then we have an artificial emit rate of 60 per second m_emitTimer += deltaTime; while (m_emitTimer > m_emitRate) { emit(); m_emitTimer -= m_emitRate; } // update living particles (we don't increment 'i' if it is dead!) for (unsigned int i = 0; i < m_aliveParticles; ) { // access it with a pointer because of how we "kill" particles Particle* particle = &m_particles[i]; // update life particle->lifetime += deltaTime; // is it dead? if (particle->lifetime >= particle->lifespan) { // if dead we swap it with the last living particle then // reduce the living count *particle = m_particles[--m_aliveParticles]; } else { // if alive we update the position and interpolate the size / colour particle->position += particle->velocity * deltaTime; particle->size = glm::mix(m_startSize, m_endSize, particle->lifetime / particle->lifespan); particle->colour = glm::mix(m_startColour, m_endColour, particle->lifetime / particle->lifespan); // create billboard transform so it can face the camera vec3 zAxis = glm::normalize(vec3(cameraTransform[3]) - particle->position); vec3 xAxis = glm::cross(vec3(cameraTransform[1]), zAxis); vec3 yAxis = glm::cross(zAxis, xAxis); glm::mat4 billboard(vec4(xAxis, 0), vec4(yAxis, 0), vec4(zAxis, 0), vec4(0, 0, 0, 1)); float halfSize = particle->size * 0.5f; m_vertices[i * 4 + 0].position = billboard * vec4(halfSize, halfSize, 0, 1) + vec4(particle->position,0); m_vertices[i * 4 + 1].position = billboard * vec4(-halfSize, halfSize, 0, 1) + vec4(particle->position,0); m_vertices[i * 4 + 2].position = billboard * vec4(-halfSize, -halfSize, 0, 1) + vec4(particle->position,0); m_vertices[i * 4 + 3].position = billboard * vec4(halfSize, -halfSize, 0, 1) + vec4(particle->position,0); m_vertices[i * 4 + 0].colour = particle->colour; m_vertices[i * 4 + 1].colour = particle->colour; m_vertices[i * 4 + 2].colour = particle->colour; m_vertices[i * 4 + 3].colour = particle->colour; // NOTE: this isn't in the tutorial but gives us the ability to texture particles m_vertices[i * 4 + 0].texcoord = glm::vec2(1,1); m_vertices[i * 4 + 1].texcoord = glm::vec2(0,1); m_vertices[i * 4 + 2].texcoord = glm::vec2(0,0); m_vertices[i * 4 + 3].texcoord = glm::vec2(1,0); ++i; } } }
31.239437
110
0.70018
LoganPletcher
cebdbaa1cce9d0cd9010607b8e0df55d5168894a
740
cpp
C++
Onboard-SDK-ROS/dji_sdk_demo/src/stereo_utility/config.cpp
NMMI/aerial-alter-ego
ba6517ecc1986e4808f6c17df3348dc5637d9cf7
[ "BSD-3-Clause" ]
6
2020-08-16T07:31:14.000Z
2022-02-17T06:24:47.000Z
src/Onboard-SDK-ROS-3.6/dji_sdk_demo/src/stereo_utility/config.cpp
isuran/droneautomation
c53017f8c8d4c03e3095ec7b6269d5a2659489e5
[ "MIT" ]
1
2021-08-18T08:14:19.000Z
2021-08-18T08:14:19.000Z
src/Onboard-SDK-ROS-3.6/dji_sdk_demo/src/stereo_utility/config.cpp
isuran/droneautomation
c53017f8c8d4c03e3095ec7b6269d5a2659489e5
[ "MIT" ]
2
2021-05-18T07:04:23.000Z
2021-05-23T13:22:13.000Z
#include "stereo_utility/config.hpp" using namespace M210_STEREO; Config* Config::single_instance_ = NULL; Config::Config() { } Config::~Config() { if (file_.isOpened()) { file_.release(); } } Config& Config::instance() { return *Config::single_instance_; } Config* Config::instancePtr() { return Config::single_instance_; } void Config::setParamFile(const std::string& file_name) { if(!Config::single_instance_) { Config::single_instance_ = new Config(); } Config::instancePtr()->file_ = cv::FileStorage( file_name, cv::FileStorage::READ ); if(!Config::instancePtr()->file_.isOpened()) { std::cerr << "Failed to open " << file_name << " file\n"; Config::instancePtr()->file_.release(); } }
15.744681
85
0.664865
NMMI
cecb215d2f23a9539d139e354548c199c7a07be9
247
cpp
C++
src/vega/manipulators/other_byte_manipulator.cpp
project-eutopia/vega
c7b536c5e949094a908fa8f378729dbffc657f4a
[ "MIT" ]
18
2018-01-23T12:28:13.000Z
2022-02-13T12:23:21.000Z
src/vega/manipulators/other_byte_manipulator.cpp
project-eutopia/vega
c7b536c5e949094a908fa8f378729dbffc657f4a
[ "MIT" ]
2
2018-11-29T01:51:25.000Z
2022-03-22T14:14:22.000Z
src/vega/manipulators/other_byte_manipulator.cpp
project-eutopia/vega
c7b536c5e949094a908fa8f378729dbffc657f4a
[ "MIT" ]
6
2019-02-01T09:54:44.000Z
2022-01-09T22:13:54.000Z
#include "vega/manipulators/other_byte_manipulator.h" namespace vega { namespace vr { template <> bool manipulator_is_valid_for<manipulators::OtherByteManipulator>(VR::value_type value) { return value == vr::OB_VALUE; } } }
22.454545
93
0.712551
project-eutopia
cecbe7d8e521fb986611411236b61392f39eb93f
1,894
cpp
C++
Generator/combination.cpp
636F57/Algos
92f0f637391652dfc8baa5c394322b849e590748
[ "MIT" ]
null
null
null
Generator/combination.cpp
636F57/Algos
92f0f637391652dfc8baa5c394322b849e590748
[ "MIT" ]
null
null
null
Generator/combination.cpp
636F57/Algos
92f0f637391652dfc8baa5c394322b849e590748
[ "MIT" ]
null
null
null
/* combination.cpp ** ** Generates a list of all possible combination of choosing m elements out of the given type-T array. ** ** compiled and tested with g++ 6.2.0 MinGW-W64 ** ** MIT License ** Copyright (c) 2017 636F57@GitHub ** See more detail at https://github.com/636F57/Algos/blob/master/LICENSE */ #include <cstdlib> #include <vector> #include <iostream> template <typename T> std::vector<std::vector<T>> recur_genCombinations(const T *pArray, int nArrraySize, int m) { std::vector<std::vector<T>> vCombList; std::vector<T> vCombination(m); int i,j; if (m == 1) { for (i=0; i<nArrraySize; i++) { vCombination[0] = pArray[i]; vCombList.push_back(vCombination); } return vCombList; } std::vector<std::vector<T>> vTmpList; for (i=0; i<=nArrraySize-m; i++) { vTmpList = recur_genCombinations(&pArray[i+1], nArrraySize-1-i, m-1); for (j=0; j<vTmpList.size(); j++) { vTmpList[j].push_back(pArray[i]); vCombList.push_back(vTmpList[j]); } } return vCombList; } int main() // sample program { std::string strN; std::cout << "This will generate combinations of selecting m elements out of integer sequence [1,2,...,N].\n"; std::cout << "Enter N : "; std::cin >> strN; int nN = std::stoi(strN); std::cout << "Enter m : "; std::cin >> strN; int nM = std::stoi(strN); // create one array to generate permutations list std::vector<int> vArrayOne(nN); for (int i=0; i<nN; i++) vArrayOne[i] = i+1; std::vector<std::vector<int>> vCombList = recur_genCombinations((const int*)(vArrayOne.data()), nN, nM); std::cout << "The number of combinations : " << std::to_string(vCombList.size()) << "\n"; std::cout << "The combinations : \n"; for (int i=0; i<vCombList.size(); i++) { for (int j=0; j<vCombList[i].size(); j++) { std::cout << std::to_string(vCombList[i][j]) << " "; } std::cout << "\n"; } return 0; }
23.675
111
0.63358
636F57
cecdcd34336b19fa7da0a5a608b34883557d8c79
74,610
cc
C++
NFComm/NFMessageDefine/NFMsgBaseEx.pb.cc
sosan/NoahGameFrame
38c54014c5c4620b784b2c1d2cab256f42bae186
[ "Apache-2.0" ]
1
2016-05-24T12:38:05.000Z
2016-05-24T12:38:05.000Z
NFComm/NFMessageDefine/NFMsgBaseEx.pb.cc
sosan/NoahGameFrame
38c54014c5c4620b784b2c1d2cab256f42bae186
[ "Apache-2.0" ]
null
null
null
NFComm/NFMessageDefine/NFMsgBaseEx.pb.cc
sosan/NoahGameFrame
38c54014c5c4620b784b2c1d2cab256f42bae186
[ "Apache-2.0" ]
1
2017-12-29T06:49:20.000Z
2017-12-29T06:49:20.000Z
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: NFMsgBaseEx.proto #define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION #include "NFMsgBaseEx.pb.h" #include <algorithm> #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/once.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/wire_format_lite_inl.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // @@protoc_insertion_point(includes) namespace NFMsg { namespace { const ::google::protobuf::Descriptor* PropertyIntEx_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* PropertyIntEx_reflection_ = NULL; const ::google::protobuf::Descriptor* PropertyFloatEx_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* PropertyFloatEx_reflection_ = NULL; const ::google::protobuf::Descriptor* PropertyStringEx_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* PropertyStringEx_reflection_ = NULL; const ::google::protobuf::Descriptor* PropertyObjectEx_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* PropertyObjectEx_reflection_ = NULL; const ::google::protobuf::Descriptor* ObjectPropertyListEx_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* ObjectPropertyListEx_reflection_ = NULL; const ::google::protobuf::Descriptor* ObjectRecordBaseEx_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* ObjectRecordBaseEx_reflection_ = NULL; const ::google::protobuf::Descriptor* ObjectRecordListEx_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* ObjectRecordListEx_reflection_ = NULL; } // namespace void protobuf_AssignDesc_NFMsgBaseEx_2eproto() { protobuf_AddDesc_NFMsgBaseEx_2eproto(); const ::google::protobuf::FileDescriptor* file = ::google::protobuf::DescriptorPool::generated_pool()->FindFileByName( "NFMsgBaseEx.proto"); GOOGLE_CHECK(file != NULL); PropertyIntEx_descriptor_ = file->message_type(0); static const int PropertyIntEx_offsets_[2] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PropertyIntEx, property_id_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PropertyIntEx, data_), }; PropertyIntEx_reflection_ = new ::google::protobuf::internal::GeneratedMessageReflection( PropertyIntEx_descriptor_, PropertyIntEx::default_instance_, PropertyIntEx_offsets_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PropertyIntEx, _has_bits_[0]), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PropertyIntEx, _unknown_fields_), -1, ::google::protobuf::DescriptorPool::generated_pool(), ::google::protobuf::MessageFactory::generated_factory(), sizeof(PropertyIntEx)); PropertyFloatEx_descriptor_ = file->message_type(1); static const int PropertyFloatEx_offsets_[2] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PropertyFloatEx, property_id_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PropertyFloatEx, data_), }; PropertyFloatEx_reflection_ = new ::google::protobuf::internal::GeneratedMessageReflection( PropertyFloatEx_descriptor_, PropertyFloatEx::default_instance_, PropertyFloatEx_offsets_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PropertyFloatEx, _has_bits_[0]), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PropertyFloatEx, _unknown_fields_), -1, ::google::protobuf::DescriptorPool::generated_pool(), ::google::protobuf::MessageFactory::generated_factory(), sizeof(PropertyFloatEx)); PropertyStringEx_descriptor_ = file->message_type(2); static const int PropertyStringEx_offsets_[2] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PropertyStringEx, property_id_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PropertyStringEx, data_), }; PropertyStringEx_reflection_ = new ::google::protobuf::internal::GeneratedMessageReflection( PropertyStringEx_descriptor_, PropertyStringEx::default_instance_, PropertyStringEx_offsets_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PropertyStringEx, _has_bits_[0]), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PropertyStringEx, _unknown_fields_), -1, ::google::protobuf::DescriptorPool::generated_pool(), ::google::protobuf::MessageFactory::generated_factory(), sizeof(PropertyStringEx)); PropertyObjectEx_descriptor_ = file->message_type(3); static const int PropertyObjectEx_offsets_[2] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PropertyObjectEx, property_id_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PropertyObjectEx, data_), }; PropertyObjectEx_reflection_ = new ::google::protobuf::internal::GeneratedMessageReflection( PropertyObjectEx_descriptor_, PropertyObjectEx::default_instance_, PropertyObjectEx_offsets_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PropertyObjectEx, _has_bits_[0]), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PropertyObjectEx, _unknown_fields_), -1, ::google::protobuf::DescriptorPool::generated_pool(), ::google::protobuf::MessageFactory::generated_factory(), sizeof(PropertyObjectEx)); ObjectPropertyListEx_descriptor_ = file->message_type(4); static const int ObjectPropertyListEx_offsets_[4] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ObjectPropertyListEx, property_int_list_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ObjectPropertyListEx, property_float_list_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ObjectPropertyListEx, property_string_list_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ObjectPropertyListEx, property_object_list_), }; ObjectPropertyListEx_reflection_ = new ::google::protobuf::internal::GeneratedMessageReflection( ObjectPropertyListEx_descriptor_, ObjectPropertyListEx::default_instance_, ObjectPropertyListEx_offsets_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ObjectPropertyListEx, _has_bits_[0]), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ObjectPropertyListEx, _unknown_fields_), -1, ::google::protobuf::DescriptorPool::generated_pool(), ::google::protobuf::MessageFactory::generated_factory(), sizeof(ObjectPropertyListEx)); ObjectRecordBaseEx_descriptor_ = file->message_type(5); static const int ObjectRecordBaseEx_offsets_[5] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ObjectRecordBaseEx, record_id_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ObjectRecordBaseEx, record_int_list_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ObjectRecordBaseEx, record_float_list_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ObjectRecordBaseEx, record_string_list_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ObjectRecordBaseEx, record_object_list_), }; ObjectRecordBaseEx_reflection_ = new ::google::protobuf::internal::GeneratedMessageReflection( ObjectRecordBaseEx_descriptor_, ObjectRecordBaseEx::default_instance_, ObjectRecordBaseEx_offsets_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ObjectRecordBaseEx, _has_bits_[0]), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ObjectRecordBaseEx, _unknown_fields_), -1, ::google::protobuf::DescriptorPool::generated_pool(), ::google::protobuf::MessageFactory::generated_factory(), sizeof(ObjectRecordBaseEx)); ObjectRecordListEx_descriptor_ = file->message_type(6); static const int ObjectRecordListEx_offsets_[1] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ObjectRecordListEx, record_list_), }; ObjectRecordListEx_reflection_ = new ::google::protobuf::internal::GeneratedMessageReflection( ObjectRecordListEx_descriptor_, ObjectRecordListEx::default_instance_, ObjectRecordListEx_offsets_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ObjectRecordListEx, _has_bits_[0]), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ObjectRecordListEx, _unknown_fields_), -1, ::google::protobuf::DescriptorPool::generated_pool(), ::google::protobuf::MessageFactory::generated_factory(), sizeof(ObjectRecordListEx)); } namespace { GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_); inline void protobuf_AssignDescriptorsOnce() { ::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_, &protobuf_AssignDesc_NFMsgBaseEx_2eproto); } void protobuf_RegisterTypes(const ::std::string&) { protobuf_AssignDescriptorsOnce(); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( PropertyIntEx_descriptor_, &PropertyIntEx::default_instance()); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( PropertyFloatEx_descriptor_, &PropertyFloatEx::default_instance()); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( PropertyStringEx_descriptor_, &PropertyStringEx::default_instance()); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( PropertyObjectEx_descriptor_, &PropertyObjectEx::default_instance()); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( ObjectPropertyListEx_descriptor_, &ObjectPropertyListEx::default_instance()); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( ObjectRecordBaseEx_descriptor_, &ObjectRecordBaseEx::default_instance()); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( ObjectRecordListEx_descriptor_, &ObjectRecordListEx::default_instance()); } } // namespace void protobuf_ShutdownFile_NFMsgBaseEx_2eproto() { delete PropertyIntEx::default_instance_; delete PropertyIntEx_reflection_; delete PropertyFloatEx::default_instance_; delete PropertyFloatEx_reflection_; delete PropertyStringEx::default_instance_; delete PropertyStringEx_reflection_; delete PropertyObjectEx::default_instance_; delete PropertyObjectEx_reflection_; delete ObjectPropertyListEx::default_instance_; delete ObjectPropertyListEx_reflection_; delete ObjectRecordBaseEx::default_instance_; delete ObjectRecordBaseEx_reflection_; delete ObjectRecordListEx::default_instance_; delete ObjectRecordListEx_reflection_; } void protobuf_AddDesc_NFMsgBaseEx_2eproto() { static bool already_here = false; if (already_here) return; already_here = true; GOOGLE_PROTOBUF_VERIFY_VERSION; ::NFMsg::protobuf_AddDesc_NFMsgBase_2eproto(); ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( "\n\021NFMsgBaseEx.proto\022\005NFMsg\032\017NFMsgBase.pr" "oto\"2\n\rPropertyIntEx\022\023\n\013property_id\030\001 \002(" "\005\022\014\n\004data\030\002 \002(\005\"4\n\017PropertyFloatEx\022\023\n\013pr" "operty_id\030\001 \002(\014\022\014\n\004data\030\002 \002(\002\"5\n\020Propert" "yStringEx\022\023\n\013property_id\030\001 \002(\014\022\014\n\004data\030\002" " \002(\014\"5\n\020PropertyObjectEx\022\023\n\013property_id\030" "\001 \002(\014\022\014\n\004data\030\002 \002(\003\"\352\001\n\024ObjectPropertyLi" "stEx\022/\n\021property_int_list\030\001 \003(\0132\024.NFMsg." "PropertyIntEx\0223\n\023property_float_list\030\002 \003" "(\0132\026.NFMsg.PropertyFloatEx\0225\n\024property_s" "tring_list\030\003 \003(\0132\027.NFMsg.PropertyStringE" "x\0225\n\024property_object_list\030\004 \003(\0132\027.NFMsg." "PropertyObjectEx\"\343\001\n\022ObjectRecordBaseEx\022" "\021\n\trecord_id\030\001 \002(\005\022)\n\017record_int_list\030\002 " "\003(\0132\020.NFMsg.RecordInt\022-\n\021record_float_li" "st\030\003 \003(\0132\022.NFMsg.RecordFloat\022/\n\022record_s" "tring_list\030\004 \003(\0132\023.NFMsg.RecordString\022/\n" "\022record_object_list\030\005 \003(\0132\023.NFMsg.Record" "Object\"D\n\022ObjectRecordListEx\022.\n\013record_l" "ist\030\001 \003(\0132\031.NFMsg.ObjectRecordBaseEx", 796); ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( "NFMsgBaseEx.proto", &protobuf_RegisterTypes); PropertyIntEx::default_instance_ = new PropertyIntEx(); PropertyFloatEx::default_instance_ = new PropertyFloatEx(); PropertyStringEx::default_instance_ = new PropertyStringEx(); PropertyObjectEx::default_instance_ = new PropertyObjectEx(); ObjectPropertyListEx::default_instance_ = new ObjectPropertyListEx(); ObjectRecordBaseEx::default_instance_ = new ObjectRecordBaseEx(); ObjectRecordListEx::default_instance_ = new ObjectRecordListEx(); PropertyIntEx::default_instance_->InitAsDefaultInstance(); PropertyFloatEx::default_instance_->InitAsDefaultInstance(); PropertyStringEx::default_instance_->InitAsDefaultInstance(); PropertyObjectEx::default_instance_->InitAsDefaultInstance(); ObjectPropertyListEx::default_instance_->InitAsDefaultInstance(); ObjectRecordBaseEx::default_instance_->InitAsDefaultInstance(); ObjectRecordListEx::default_instance_->InitAsDefaultInstance(); ::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_NFMsgBaseEx_2eproto); } // Force AddDescriptors() to be called at static initialization time. struct StaticDescriptorInitializer_NFMsgBaseEx_2eproto { StaticDescriptorInitializer_NFMsgBaseEx_2eproto() { protobuf_AddDesc_NFMsgBaseEx_2eproto(); } } static_descriptor_initializer_NFMsgBaseEx_2eproto_; // =================================================================== #ifndef _MSC_VER const int PropertyIntEx::kPropertyIdFieldNumber; const int PropertyIntEx::kDataFieldNumber; #endif // !_MSC_VER PropertyIntEx::PropertyIntEx() : ::google::protobuf::Message() { SharedCtor(); } void PropertyIntEx::InitAsDefaultInstance() { } PropertyIntEx::PropertyIntEx(const PropertyIntEx& from) : ::google::protobuf::Message() { SharedCtor(); MergeFrom(from); } void PropertyIntEx::SharedCtor() { _cached_size_ = 0; property_id_ = 0; data_ = 0; ::memset(_has_bits_, 0, sizeof(_has_bits_)); } PropertyIntEx::~PropertyIntEx() { SharedDtor(); } void PropertyIntEx::SharedDtor() { if (this != default_instance_) { } } void PropertyIntEx::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* PropertyIntEx::descriptor() { protobuf_AssignDescriptorsOnce(); return PropertyIntEx_descriptor_; } const PropertyIntEx& PropertyIntEx::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_NFMsgBaseEx_2eproto(); return *default_instance_; } PropertyIntEx* PropertyIntEx::default_instance_ = NULL; PropertyIntEx* PropertyIntEx::New() const { return new PropertyIntEx; } void PropertyIntEx::Clear() { if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { property_id_ = 0; data_ = 0; } ::memset(_has_bits_, 0, sizeof(_has_bits_)); mutable_unknown_fields()->Clear(); } bool PropertyIntEx::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!(EXPRESSION)) return false ::google::protobuf::uint32 tag; while ((tag = input->ReadTag()) != 0) { switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // required int32 property_id = 1; case 1: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &property_id_))); set_has_property_id(); } else { goto handle_uninterpreted; } if (input->ExpectTag(16)) goto parse_data; break; } // required int32 data = 2; case 2: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { parse_data: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &data_))); set_has_data(); } else { goto handle_uninterpreted; } if (input->ExpectAtEnd()) return true; break; } default: { handle_uninterpreted: if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { return true; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } return true; #undef DO_ } void PropertyIntEx::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // required int32 property_id = 1; if (has_property_id()) { ::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->property_id(), output); } // required int32 data = 2; if (has_data()) { ::google::protobuf::internal::WireFormatLite::WriteInt32(2, this->data(), output); } if (!unknown_fields().empty()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } } ::google::protobuf::uint8* PropertyIntEx::SerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // required int32 property_id = 1; if (has_property_id()) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->property_id(), target); } // required int32 data = 2; if (has_data()) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(2, this->data(), target); } if (!unknown_fields().empty()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } return target; } int PropertyIntEx::ByteSize() const { int total_size = 0; if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { // required int32 property_id = 1; if (has_property_id()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->property_id()); } // required int32 data = 2; if (has_data()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->data()); } } if (!unknown_fields().empty()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void PropertyIntEx::MergeFrom(const ::google::protobuf::Message& from) { GOOGLE_CHECK_NE(&from, this); const PropertyIntEx* source = ::google::protobuf::internal::dynamic_cast_if_available<const PropertyIntEx*>( &from); if (source == NULL) { ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { MergeFrom(*source); } } void PropertyIntEx::MergeFrom(const PropertyIntEx& from) { GOOGLE_CHECK_NE(&from, this); if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (from.has_property_id()) { set_property_id(from.property_id()); } if (from.has_data()) { set_data(from.data()); } } mutable_unknown_fields()->MergeFrom(from.unknown_fields()); } void PropertyIntEx::CopyFrom(const ::google::protobuf::Message& from) { if (&from == this) return; Clear(); MergeFrom(from); } void PropertyIntEx::CopyFrom(const PropertyIntEx& from) { if (&from == this) return; Clear(); MergeFrom(from); } bool PropertyIntEx::IsInitialized() const { if ((_has_bits_[0] & 0x00000003) != 0x00000003) return false; return true; } void PropertyIntEx::Swap(PropertyIntEx* other) { if (other != this) { std::swap(property_id_, other->property_id_); std::swap(data_, other->data_); std::swap(_has_bits_[0], other->_has_bits_[0]); _unknown_fields_.Swap(&other->_unknown_fields_); std::swap(_cached_size_, other->_cached_size_); } } ::google::protobuf::Metadata PropertyIntEx::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = PropertyIntEx_descriptor_; metadata.reflection = PropertyIntEx_reflection_; return metadata; } // =================================================================== #ifndef _MSC_VER const int PropertyFloatEx::kPropertyIdFieldNumber; const int PropertyFloatEx::kDataFieldNumber; #endif // !_MSC_VER PropertyFloatEx::PropertyFloatEx() : ::google::protobuf::Message() { SharedCtor(); } void PropertyFloatEx::InitAsDefaultInstance() { } PropertyFloatEx::PropertyFloatEx(const PropertyFloatEx& from) : ::google::protobuf::Message() { SharedCtor(); MergeFrom(from); } void PropertyFloatEx::SharedCtor() { _cached_size_ = 0; property_id_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString); data_ = 0; ::memset(_has_bits_, 0, sizeof(_has_bits_)); } PropertyFloatEx::~PropertyFloatEx() { SharedDtor(); } void PropertyFloatEx::SharedDtor() { if (property_id_ != &::google::protobuf::internal::kEmptyString) { delete property_id_; } if (this != default_instance_) { } } void PropertyFloatEx::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* PropertyFloatEx::descriptor() { protobuf_AssignDescriptorsOnce(); return PropertyFloatEx_descriptor_; } const PropertyFloatEx& PropertyFloatEx::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_NFMsgBaseEx_2eproto(); return *default_instance_; } PropertyFloatEx* PropertyFloatEx::default_instance_ = NULL; PropertyFloatEx* PropertyFloatEx::New() const { return new PropertyFloatEx; } void PropertyFloatEx::Clear() { if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (has_property_id()) { if (property_id_ != &::google::protobuf::internal::kEmptyString) { property_id_->clear(); } } data_ = 0; } ::memset(_has_bits_, 0, sizeof(_has_bits_)); mutable_unknown_fields()->Clear(); } bool PropertyFloatEx::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!(EXPRESSION)) return false ::google::protobuf::uint32 tag; while ((tag = input->ReadTag()) != 0) { switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // required bytes property_id = 1; case 1: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { DO_(::google::protobuf::internal::WireFormatLite::ReadBytes( input, this->mutable_property_id())); } else { goto handle_uninterpreted; } if (input->ExpectTag(21)) goto parse_data; break; } // required float data = 2; case 2: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_FIXED32) { parse_data: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< float, ::google::protobuf::internal::WireFormatLite::TYPE_FLOAT>( input, &data_))); set_has_data(); } else { goto handle_uninterpreted; } if (input->ExpectAtEnd()) return true; break; } default: { handle_uninterpreted: if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { return true; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } return true; #undef DO_ } void PropertyFloatEx::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // required bytes property_id = 1; if (has_property_id()) { ::google::protobuf::internal::WireFormatLite::WriteBytes( 1, this->property_id(), output); } // required float data = 2; if (has_data()) { ::google::protobuf::internal::WireFormatLite::WriteFloat(2, this->data(), output); } if (!unknown_fields().empty()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } } ::google::protobuf::uint8* PropertyFloatEx::SerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // required bytes property_id = 1; if (has_property_id()) { target = ::google::protobuf::internal::WireFormatLite::WriteBytesToArray( 1, this->property_id(), target); } // required float data = 2; if (has_data()) { target = ::google::protobuf::internal::WireFormatLite::WriteFloatToArray(2, this->data(), target); } if (!unknown_fields().empty()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } return target; } int PropertyFloatEx::ByteSize() const { int total_size = 0; if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { // required bytes property_id = 1; if (has_property_id()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::BytesSize( this->property_id()); } // required float data = 2; if (has_data()) { total_size += 1 + 4; } } if (!unknown_fields().empty()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void PropertyFloatEx::MergeFrom(const ::google::protobuf::Message& from) { GOOGLE_CHECK_NE(&from, this); const PropertyFloatEx* source = ::google::protobuf::internal::dynamic_cast_if_available<const PropertyFloatEx*>( &from); if (source == NULL) { ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { MergeFrom(*source); } } void PropertyFloatEx::MergeFrom(const PropertyFloatEx& from) { GOOGLE_CHECK_NE(&from, this); if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (from.has_property_id()) { set_property_id(from.property_id()); } if (from.has_data()) { set_data(from.data()); } } mutable_unknown_fields()->MergeFrom(from.unknown_fields()); } void PropertyFloatEx::CopyFrom(const ::google::protobuf::Message& from) { if (&from == this) return; Clear(); MergeFrom(from); } void PropertyFloatEx::CopyFrom(const PropertyFloatEx& from) { if (&from == this) return; Clear(); MergeFrom(from); } bool PropertyFloatEx::IsInitialized() const { if ((_has_bits_[0] & 0x00000003) != 0x00000003) return false; return true; } void PropertyFloatEx::Swap(PropertyFloatEx* other) { if (other != this) { std::swap(property_id_, other->property_id_); std::swap(data_, other->data_); std::swap(_has_bits_[0], other->_has_bits_[0]); _unknown_fields_.Swap(&other->_unknown_fields_); std::swap(_cached_size_, other->_cached_size_); } } ::google::protobuf::Metadata PropertyFloatEx::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = PropertyFloatEx_descriptor_; metadata.reflection = PropertyFloatEx_reflection_; return metadata; } // =================================================================== #ifndef _MSC_VER const int PropertyStringEx::kPropertyIdFieldNumber; const int PropertyStringEx::kDataFieldNumber; #endif // !_MSC_VER PropertyStringEx::PropertyStringEx() : ::google::protobuf::Message() { SharedCtor(); } void PropertyStringEx::InitAsDefaultInstance() { } PropertyStringEx::PropertyStringEx(const PropertyStringEx& from) : ::google::protobuf::Message() { SharedCtor(); MergeFrom(from); } void PropertyStringEx::SharedCtor() { _cached_size_ = 0; property_id_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString); data_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString); ::memset(_has_bits_, 0, sizeof(_has_bits_)); } PropertyStringEx::~PropertyStringEx() { SharedDtor(); } void PropertyStringEx::SharedDtor() { if (property_id_ != &::google::protobuf::internal::kEmptyString) { delete property_id_; } if (data_ != &::google::protobuf::internal::kEmptyString) { delete data_; } if (this != default_instance_) { } } void PropertyStringEx::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* PropertyStringEx::descriptor() { protobuf_AssignDescriptorsOnce(); return PropertyStringEx_descriptor_; } const PropertyStringEx& PropertyStringEx::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_NFMsgBaseEx_2eproto(); return *default_instance_; } PropertyStringEx* PropertyStringEx::default_instance_ = NULL; PropertyStringEx* PropertyStringEx::New() const { return new PropertyStringEx; } void PropertyStringEx::Clear() { if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (has_property_id()) { if (property_id_ != &::google::protobuf::internal::kEmptyString) { property_id_->clear(); } } if (has_data()) { if (data_ != &::google::protobuf::internal::kEmptyString) { data_->clear(); } } } ::memset(_has_bits_, 0, sizeof(_has_bits_)); mutable_unknown_fields()->Clear(); } bool PropertyStringEx::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!(EXPRESSION)) return false ::google::protobuf::uint32 tag; while ((tag = input->ReadTag()) != 0) { switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // required bytes property_id = 1; case 1: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { DO_(::google::protobuf::internal::WireFormatLite::ReadBytes( input, this->mutable_property_id())); } else { goto handle_uninterpreted; } if (input->ExpectTag(18)) goto parse_data; break; } // required bytes data = 2; case 2: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { parse_data: DO_(::google::protobuf::internal::WireFormatLite::ReadBytes( input, this->mutable_data())); } else { goto handle_uninterpreted; } if (input->ExpectAtEnd()) return true; break; } default: { handle_uninterpreted: if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { return true; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } return true; #undef DO_ } void PropertyStringEx::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // required bytes property_id = 1; if (has_property_id()) { ::google::protobuf::internal::WireFormatLite::WriteBytes( 1, this->property_id(), output); } // required bytes data = 2; if (has_data()) { ::google::protobuf::internal::WireFormatLite::WriteBytes( 2, this->data(), output); } if (!unknown_fields().empty()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } } ::google::protobuf::uint8* PropertyStringEx::SerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // required bytes property_id = 1; if (has_property_id()) { target = ::google::protobuf::internal::WireFormatLite::WriteBytesToArray( 1, this->property_id(), target); } // required bytes data = 2; if (has_data()) { target = ::google::protobuf::internal::WireFormatLite::WriteBytesToArray( 2, this->data(), target); } if (!unknown_fields().empty()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } return target; } int PropertyStringEx::ByteSize() const { int total_size = 0; if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { // required bytes property_id = 1; if (has_property_id()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::BytesSize( this->property_id()); } // required bytes data = 2; if (has_data()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::BytesSize( this->data()); } } if (!unknown_fields().empty()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void PropertyStringEx::MergeFrom(const ::google::protobuf::Message& from) { GOOGLE_CHECK_NE(&from, this); const PropertyStringEx* source = ::google::protobuf::internal::dynamic_cast_if_available<const PropertyStringEx*>( &from); if (source == NULL) { ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { MergeFrom(*source); } } void PropertyStringEx::MergeFrom(const PropertyStringEx& from) { GOOGLE_CHECK_NE(&from, this); if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (from.has_property_id()) { set_property_id(from.property_id()); } if (from.has_data()) { set_data(from.data()); } } mutable_unknown_fields()->MergeFrom(from.unknown_fields()); } void PropertyStringEx::CopyFrom(const ::google::protobuf::Message& from) { if (&from == this) return; Clear(); MergeFrom(from); } void PropertyStringEx::CopyFrom(const PropertyStringEx& from) { if (&from == this) return; Clear(); MergeFrom(from); } bool PropertyStringEx::IsInitialized() const { if ((_has_bits_[0] & 0x00000003) != 0x00000003) return false; return true; } void PropertyStringEx::Swap(PropertyStringEx* other) { if (other != this) { std::swap(property_id_, other->property_id_); std::swap(data_, other->data_); std::swap(_has_bits_[0], other->_has_bits_[0]); _unknown_fields_.Swap(&other->_unknown_fields_); std::swap(_cached_size_, other->_cached_size_); } } ::google::protobuf::Metadata PropertyStringEx::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = PropertyStringEx_descriptor_; metadata.reflection = PropertyStringEx_reflection_; return metadata; } // =================================================================== #ifndef _MSC_VER const int PropertyObjectEx::kPropertyIdFieldNumber; const int PropertyObjectEx::kDataFieldNumber; #endif // !_MSC_VER PropertyObjectEx::PropertyObjectEx() : ::google::protobuf::Message() { SharedCtor(); } void PropertyObjectEx::InitAsDefaultInstance() { } PropertyObjectEx::PropertyObjectEx(const PropertyObjectEx& from) : ::google::protobuf::Message() { SharedCtor(); MergeFrom(from); } void PropertyObjectEx::SharedCtor() { _cached_size_ = 0; property_id_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString); data_ = GOOGLE_LONGLONG(0); ::memset(_has_bits_, 0, sizeof(_has_bits_)); } PropertyObjectEx::~PropertyObjectEx() { SharedDtor(); } void PropertyObjectEx::SharedDtor() { if (property_id_ != &::google::protobuf::internal::kEmptyString) { delete property_id_; } if (this != default_instance_) { } } void PropertyObjectEx::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* PropertyObjectEx::descriptor() { protobuf_AssignDescriptorsOnce(); return PropertyObjectEx_descriptor_; } const PropertyObjectEx& PropertyObjectEx::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_NFMsgBaseEx_2eproto(); return *default_instance_; } PropertyObjectEx* PropertyObjectEx::default_instance_ = NULL; PropertyObjectEx* PropertyObjectEx::New() const { return new PropertyObjectEx; } void PropertyObjectEx::Clear() { if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (has_property_id()) { if (property_id_ != &::google::protobuf::internal::kEmptyString) { property_id_->clear(); } } data_ = GOOGLE_LONGLONG(0); } ::memset(_has_bits_, 0, sizeof(_has_bits_)); mutable_unknown_fields()->Clear(); } bool PropertyObjectEx::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!(EXPRESSION)) return false ::google::protobuf::uint32 tag; while ((tag = input->ReadTag()) != 0) { switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // required bytes property_id = 1; case 1: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { DO_(::google::protobuf::internal::WireFormatLite::ReadBytes( input, this->mutable_property_id())); } else { goto handle_uninterpreted; } if (input->ExpectTag(16)) goto parse_data; break; } // required int64 data = 2; case 2: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { parse_data: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &data_))); set_has_data(); } else { goto handle_uninterpreted; } if (input->ExpectAtEnd()) return true; break; } default: { handle_uninterpreted: if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { return true; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } return true; #undef DO_ } void PropertyObjectEx::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // required bytes property_id = 1; if (has_property_id()) { ::google::protobuf::internal::WireFormatLite::WriteBytes( 1, this->property_id(), output); } // required int64 data = 2; if (has_data()) { ::google::protobuf::internal::WireFormatLite::WriteInt64(2, this->data(), output); } if (!unknown_fields().empty()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } } ::google::protobuf::uint8* PropertyObjectEx::SerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // required bytes property_id = 1; if (has_property_id()) { target = ::google::protobuf::internal::WireFormatLite::WriteBytesToArray( 1, this->property_id(), target); } // required int64 data = 2; if (has_data()) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(2, this->data(), target); } if (!unknown_fields().empty()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } return target; } int PropertyObjectEx::ByteSize() const { int total_size = 0; if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { // required bytes property_id = 1; if (has_property_id()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::BytesSize( this->property_id()); } // required int64 data = 2; if (has_data()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->data()); } } if (!unknown_fields().empty()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void PropertyObjectEx::MergeFrom(const ::google::protobuf::Message& from) { GOOGLE_CHECK_NE(&from, this); const PropertyObjectEx* source = ::google::protobuf::internal::dynamic_cast_if_available<const PropertyObjectEx*>( &from); if (source == NULL) { ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { MergeFrom(*source); } } void PropertyObjectEx::MergeFrom(const PropertyObjectEx& from) { GOOGLE_CHECK_NE(&from, this); if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (from.has_property_id()) { set_property_id(from.property_id()); } if (from.has_data()) { set_data(from.data()); } } mutable_unknown_fields()->MergeFrom(from.unknown_fields()); } void PropertyObjectEx::CopyFrom(const ::google::protobuf::Message& from) { if (&from == this) return; Clear(); MergeFrom(from); } void PropertyObjectEx::CopyFrom(const PropertyObjectEx& from) { if (&from == this) return; Clear(); MergeFrom(from); } bool PropertyObjectEx::IsInitialized() const { if ((_has_bits_[0] & 0x00000003) != 0x00000003) return false; return true; } void PropertyObjectEx::Swap(PropertyObjectEx* other) { if (other != this) { std::swap(property_id_, other->property_id_); std::swap(data_, other->data_); std::swap(_has_bits_[0], other->_has_bits_[0]); _unknown_fields_.Swap(&other->_unknown_fields_); std::swap(_cached_size_, other->_cached_size_); } } ::google::protobuf::Metadata PropertyObjectEx::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = PropertyObjectEx_descriptor_; metadata.reflection = PropertyObjectEx_reflection_; return metadata; } // =================================================================== #ifndef _MSC_VER const int ObjectPropertyListEx::kPropertyIntListFieldNumber; const int ObjectPropertyListEx::kPropertyFloatListFieldNumber; const int ObjectPropertyListEx::kPropertyStringListFieldNumber; const int ObjectPropertyListEx::kPropertyObjectListFieldNumber; #endif // !_MSC_VER ObjectPropertyListEx::ObjectPropertyListEx() : ::google::protobuf::Message() { SharedCtor(); } void ObjectPropertyListEx::InitAsDefaultInstance() { } ObjectPropertyListEx::ObjectPropertyListEx(const ObjectPropertyListEx& from) : ::google::protobuf::Message() { SharedCtor(); MergeFrom(from); } void ObjectPropertyListEx::SharedCtor() { _cached_size_ = 0; ::memset(_has_bits_, 0, sizeof(_has_bits_)); } ObjectPropertyListEx::~ObjectPropertyListEx() { SharedDtor(); } void ObjectPropertyListEx::SharedDtor() { if (this != default_instance_) { } } void ObjectPropertyListEx::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* ObjectPropertyListEx::descriptor() { protobuf_AssignDescriptorsOnce(); return ObjectPropertyListEx_descriptor_; } const ObjectPropertyListEx& ObjectPropertyListEx::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_NFMsgBaseEx_2eproto(); return *default_instance_; } ObjectPropertyListEx* ObjectPropertyListEx::default_instance_ = NULL; ObjectPropertyListEx* ObjectPropertyListEx::New() const { return new ObjectPropertyListEx; } void ObjectPropertyListEx::Clear() { property_int_list_.Clear(); property_float_list_.Clear(); property_string_list_.Clear(); property_object_list_.Clear(); ::memset(_has_bits_, 0, sizeof(_has_bits_)); mutable_unknown_fields()->Clear(); } bool ObjectPropertyListEx::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!(EXPRESSION)) return false ::google::protobuf::uint32 tag; while ((tag = input->ReadTag()) != 0) { switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // repeated .NFMsg.PropertyIntEx property_int_list = 1; case 1: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { parse_property_int_list: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, add_property_int_list())); } else { goto handle_uninterpreted; } if (input->ExpectTag(10)) goto parse_property_int_list; if (input->ExpectTag(18)) goto parse_property_float_list; break; } // repeated .NFMsg.PropertyFloatEx property_float_list = 2; case 2: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { parse_property_float_list: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, add_property_float_list())); } else { goto handle_uninterpreted; } if (input->ExpectTag(18)) goto parse_property_float_list; if (input->ExpectTag(26)) goto parse_property_string_list; break; } // repeated .NFMsg.PropertyStringEx property_string_list = 3; case 3: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { parse_property_string_list: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, add_property_string_list())); } else { goto handle_uninterpreted; } if (input->ExpectTag(26)) goto parse_property_string_list; if (input->ExpectTag(34)) goto parse_property_object_list; break; } // repeated .NFMsg.PropertyObjectEx property_object_list = 4; case 4: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { parse_property_object_list: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, add_property_object_list())); } else { goto handle_uninterpreted; } if (input->ExpectTag(34)) goto parse_property_object_list; if (input->ExpectAtEnd()) return true; break; } default: { handle_uninterpreted: if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { return true; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } return true; #undef DO_ } void ObjectPropertyListEx::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // repeated .NFMsg.PropertyIntEx property_int_list = 1; for (int i = 0; i < this->property_int_list_size(); i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, this->property_int_list(i), output); } // repeated .NFMsg.PropertyFloatEx property_float_list = 2; for (int i = 0; i < this->property_float_list_size(); i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 2, this->property_float_list(i), output); } // repeated .NFMsg.PropertyStringEx property_string_list = 3; for (int i = 0; i < this->property_string_list_size(); i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 3, this->property_string_list(i), output); } // repeated .NFMsg.PropertyObjectEx property_object_list = 4; for (int i = 0; i < this->property_object_list_size(); i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 4, this->property_object_list(i), output); } if (!unknown_fields().empty()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } } ::google::protobuf::uint8* ObjectPropertyListEx::SerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // repeated .NFMsg.PropertyIntEx property_int_list = 1; for (int i = 0; i < this->property_int_list_size(); i++) { target = ::google::protobuf::internal::WireFormatLite:: WriteMessageNoVirtualToArray( 1, this->property_int_list(i), target); } // repeated .NFMsg.PropertyFloatEx property_float_list = 2; for (int i = 0; i < this->property_float_list_size(); i++) { target = ::google::protobuf::internal::WireFormatLite:: WriteMessageNoVirtualToArray( 2, this->property_float_list(i), target); } // repeated .NFMsg.PropertyStringEx property_string_list = 3; for (int i = 0; i < this->property_string_list_size(); i++) { target = ::google::protobuf::internal::WireFormatLite:: WriteMessageNoVirtualToArray( 3, this->property_string_list(i), target); } // repeated .NFMsg.PropertyObjectEx property_object_list = 4; for (int i = 0; i < this->property_object_list_size(); i++) { target = ::google::protobuf::internal::WireFormatLite:: WriteMessageNoVirtualToArray( 4, this->property_object_list(i), target); } if (!unknown_fields().empty()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } return target; } int ObjectPropertyListEx::ByteSize() const { int total_size = 0; // repeated .NFMsg.PropertyIntEx property_int_list = 1; total_size += 1 * this->property_int_list_size(); for (int i = 0; i < this->property_int_list_size(); i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( this->property_int_list(i)); } // repeated .NFMsg.PropertyFloatEx property_float_list = 2; total_size += 1 * this->property_float_list_size(); for (int i = 0; i < this->property_float_list_size(); i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( this->property_float_list(i)); } // repeated .NFMsg.PropertyStringEx property_string_list = 3; total_size += 1 * this->property_string_list_size(); for (int i = 0; i < this->property_string_list_size(); i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( this->property_string_list(i)); } // repeated .NFMsg.PropertyObjectEx property_object_list = 4; total_size += 1 * this->property_object_list_size(); for (int i = 0; i < this->property_object_list_size(); i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( this->property_object_list(i)); } if (!unknown_fields().empty()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void ObjectPropertyListEx::MergeFrom(const ::google::protobuf::Message& from) { GOOGLE_CHECK_NE(&from, this); const ObjectPropertyListEx* source = ::google::protobuf::internal::dynamic_cast_if_available<const ObjectPropertyListEx*>( &from); if (source == NULL) { ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { MergeFrom(*source); } } void ObjectPropertyListEx::MergeFrom(const ObjectPropertyListEx& from) { GOOGLE_CHECK_NE(&from, this); property_int_list_.MergeFrom(from.property_int_list_); property_float_list_.MergeFrom(from.property_float_list_); property_string_list_.MergeFrom(from.property_string_list_); property_object_list_.MergeFrom(from.property_object_list_); mutable_unknown_fields()->MergeFrom(from.unknown_fields()); } void ObjectPropertyListEx::CopyFrom(const ::google::protobuf::Message& from) { if (&from == this) return; Clear(); MergeFrom(from); } void ObjectPropertyListEx::CopyFrom(const ObjectPropertyListEx& from) { if (&from == this) return; Clear(); MergeFrom(from); } bool ObjectPropertyListEx::IsInitialized() const { for (int i = 0; i < property_int_list_size(); i++) { if (!this->property_int_list(i).IsInitialized()) return false; } for (int i = 0; i < property_float_list_size(); i++) { if (!this->property_float_list(i).IsInitialized()) return false; } for (int i = 0; i < property_string_list_size(); i++) { if (!this->property_string_list(i).IsInitialized()) return false; } for (int i = 0; i < property_object_list_size(); i++) { if (!this->property_object_list(i).IsInitialized()) return false; } return true; } void ObjectPropertyListEx::Swap(ObjectPropertyListEx* other) { if (other != this) { property_int_list_.Swap(&other->property_int_list_); property_float_list_.Swap(&other->property_float_list_); property_string_list_.Swap(&other->property_string_list_); property_object_list_.Swap(&other->property_object_list_); std::swap(_has_bits_[0], other->_has_bits_[0]); _unknown_fields_.Swap(&other->_unknown_fields_); std::swap(_cached_size_, other->_cached_size_); } } ::google::protobuf::Metadata ObjectPropertyListEx::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = ObjectPropertyListEx_descriptor_; metadata.reflection = ObjectPropertyListEx_reflection_; return metadata; } // =================================================================== #ifndef _MSC_VER const int ObjectRecordBaseEx::kRecordIdFieldNumber; const int ObjectRecordBaseEx::kRecordIntListFieldNumber; const int ObjectRecordBaseEx::kRecordFloatListFieldNumber; const int ObjectRecordBaseEx::kRecordStringListFieldNumber; const int ObjectRecordBaseEx::kRecordObjectListFieldNumber; #endif // !_MSC_VER ObjectRecordBaseEx::ObjectRecordBaseEx() : ::google::protobuf::Message() { SharedCtor(); } void ObjectRecordBaseEx::InitAsDefaultInstance() { } ObjectRecordBaseEx::ObjectRecordBaseEx(const ObjectRecordBaseEx& from) : ::google::protobuf::Message() { SharedCtor(); MergeFrom(from); } void ObjectRecordBaseEx::SharedCtor() { _cached_size_ = 0; record_id_ = 0; ::memset(_has_bits_, 0, sizeof(_has_bits_)); } ObjectRecordBaseEx::~ObjectRecordBaseEx() { SharedDtor(); } void ObjectRecordBaseEx::SharedDtor() { if (this != default_instance_) { } } void ObjectRecordBaseEx::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* ObjectRecordBaseEx::descriptor() { protobuf_AssignDescriptorsOnce(); return ObjectRecordBaseEx_descriptor_; } const ObjectRecordBaseEx& ObjectRecordBaseEx::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_NFMsgBaseEx_2eproto(); return *default_instance_; } ObjectRecordBaseEx* ObjectRecordBaseEx::default_instance_ = NULL; ObjectRecordBaseEx* ObjectRecordBaseEx::New() const { return new ObjectRecordBaseEx; } void ObjectRecordBaseEx::Clear() { if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { record_id_ = 0; } record_int_list_.Clear(); record_float_list_.Clear(); record_string_list_.Clear(); record_object_list_.Clear(); ::memset(_has_bits_, 0, sizeof(_has_bits_)); mutable_unknown_fields()->Clear(); } bool ObjectRecordBaseEx::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!(EXPRESSION)) return false ::google::protobuf::uint32 tag; while ((tag = input->ReadTag()) != 0) { switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // required int32 record_id = 1; case 1: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &record_id_))); set_has_record_id(); } else { goto handle_uninterpreted; } if (input->ExpectTag(18)) goto parse_record_int_list; break; } // repeated .NFMsg.RecordInt record_int_list = 2; case 2: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { parse_record_int_list: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, add_record_int_list())); } else { goto handle_uninterpreted; } if (input->ExpectTag(18)) goto parse_record_int_list; if (input->ExpectTag(26)) goto parse_record_float_list; break; } // repeated .NFMsg.RecordFloat record_float_list = 3; case 3: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { parse_record_float_list: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, add_record_float_list())); } else { goto handle_uninterpreted; } if (input->ExpectTag(26)) goto parse_record_float_list; if (input->ExpectTag(34)) goto parse_record_string_list; break; } // repeated .NFMsg.RecordString record_string_list = 4; case 4: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { parse_record_string_list: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, add_record_string_list())); } else { goto handle_uninterpreted; } if (input->ExpectTag(34)) goto parse_record_string_list; if (input->ExpectTag(42)) goto parse_record_object_list; break; } // repeated .NFMsg.RecordObject record_object_list = 5; case 5: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { parse_record_object_list: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, add_record_object_list())); } else { goto handle_uninterpreted; } if (input->ExpectTag(42)) goto parse_record_object_list; if (input->ExpectAtEnd()) return true; break; } default: { handle_uninterpreted: if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { return true; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } return true; #undef DO_ } void ObjectRecordBaseEx::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // required int32 record_id = 1; if (has_record_id()) { ::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->record_id(), output); } // repeated .NFMsg.RecordInt record_int_list = 2; for (int i = 0; i < this->record_int_list_size(); i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 2, this->record_int_list(i), output); } // repeated .NFMsg.RecordFloat record_float_list = 3; for (int i = 0; i < this->record_float_list_size(); i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 3, this->record_float_list(i), output); } // repeated .NFMsg.RecordString record_string_list = 4; for (int i = 0; i < this->record_string_list_size(); i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 4, this->record_string_list(i), output); } // repeated .NFMsg.RecordObject record_object_list = 5; for (int i = 0; i < this->record_object_list_size(); i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 5, this->record_object_list(i), output); } if (!unknown_fields().empty()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } } ::google::protobuf::uint8* ObjectRecordBaseEx::SerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // required int32 record_id = 1; if (has_record_id()) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->record_id(), target); } // repeated .NFMsg.RecordInt record_int_list = 2; for (int i = 0; i < this->record_int_list_size(); i++) { target = ::google::protobuf::internal::WireFormatLite:: WriteMessageNoVirtualToArray( 2, this->record_int_list(i), target); } // repeated .NFMsg.RecordFloat record_float_list = 3; for (int i = 0; i < this->record_float_list_size(); i++) { target = ::google::protobuf::internal::WireFormatLite:: WriteMessageNoVirtualToArray( 3, this->record_float_list(i), target); } // repeated .NFMsg.RecordString record_string_list = 4; for (int i = 0; i < this->record_string_list_size(); i++) { target = ::google::protobuf::internal::WireFormatLite:: WriteMessageNoVirtualToArray( 4, this->record_string_list(i), target); } // repeated .NFMsg.RecordObject record_object_list = 5; for (int i = 0; i < this->record_object_list_size(); i++) { target = ::google::protobuf::internal::WireFormatLite:: WriteMessageNoVirtualToArray( 5, this->record_object_list(i), target); } if (!unknown_fields().empty()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } return target; } int ObjectRecordBaseEx::ByteSize() const { int total_size = 0; if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { // required int32 record_id = 1; if (has_record_id()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->record_id()); } } // repeated .NFMsg.RecordInt record_int_list = 2; total_size += 1 * this->record_int_list_size(); for (int i = 0; i < this->record_int_list_size(); i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( this->record_int_list(i)); } // repeated .NFMsg.RecordFloat record_float_list = 3; total_size += 1 * this->record_float_list_size(); for (int i = 0; i < this->record_float_list_size(); i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( this->record_float_list(i)); } // repeated .NFMsg.RecordString record_string_list = 4; total_size += 1 * this->record_string_list_size(); for (int i = 0; i < this->record_string_list_size(); i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( this->record_string_list(i)); } // repeated .NFMsg.RecordObject record_object_list = 5; total_size += 1 * this->record_object_list_size(); for (int i = 0; i < this->record_object_list_size(); i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( this->record_object_list(i)); } if (!unknown_fields().empty()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void ObjectRecordBaseEx::MergeFrom(const ::google::protobuf::Message& from) { GOOGLE_CHECK_NE(&from, this); const ObjectRecordBaseEx* source = ::google::protobuf::internal::dynamic_cast_if_available<const ObjectRecordBaseEx*>( &from); if (source == NULL) { ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { MergeFrom(*source); } } void ObjectRecordBaseEx::MergeFrom(const ObjectRecordBaseEx& from) { GOOGLE_CHECK_NE(&from, this); record_int_list_.MergeFrom(from.record_int_list_); record_float_list_.MergeFrom(from.record_float_list_); record_string_list_.MergeFrom(from.record_string_list_); record_object_list_.MergeFrom(from.record_object_list_); if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (from.has_record_id()) { set_record_id(from.record_id()); } } mutable_unknown_fields()->MergeFrom(from.unknown_fields()); } void ObjectRecordBaseEx::CopyFrom(const ::google::protobuf::Message& from) { if (&from == this) return; Clear(); MergeFrom(from); } void ObjectRecordBaseEx::CopyFrom(const ObjectRecordBaseEx& from) { if (&from == this) return; Clear(); MergeFrom(from); } bool ObjectRecordBaseEx::IsInitialized() const { if ((_has_bits_[0] & 0x00000001) != 0x00000001) return false; for (int i = 0; i < record_int_list_size(); i++) { if (!this->record_int_list(i).IsInitialized()) return false; } for (int i = 0; i < record_float_list_size(); i++) { if (!this->record_float_list(i).IsInitialized()) return false; } for (int i = 0; i < record_string_list_size(); i++) { if (!this->record_string_list(i).IsInitialized()) return false; } for (int i = 0; i < record_object_list_size(); i++) { if (!this->record_object_list(i).IsInitialized()) return false; } return true; } void ObjectRecordBaseEx::Swap(ObjectRecordBaseEx* other) { if (other != this) { std::swap(record_id_, other->record_id_); record_int_list_.Swap(&other->record_int_list_); record_float_list_.Swap(&other->record_float_list_); record_string_list_.Swap(&other->record_string_list_); record_object_list_.Swap(&other->record_object_list_); std::swap(_has_bits_[0], other->_has_bits_[0]); _unknown_fields_.Swap(&other->_unknown_fields_); std::swap(_cached_size_, other->_cached_size_); } } ::google::protobuf::Metadata ObjectRecordBaseEx::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = ObjectRecordBaseEx_descriptor_; metadata.reflection = ObjectRecordBaseEx_reflection_; return metadata; } // =================================================================== #ifndef _MSC_VER const int ObjectRecordListEx::kRecordListFieldNumber; #endif // !_MSC_VER ObjectRecordListEx::ObjectRecordListEx() : ::google::protobuf::Message() { SharedCtor(); } void ObjectRecordListEx::InitAsDefaultInstance() { } ObjectRecordListEx::ObjectRecordListEx(const ObjectRecordListEx& from) : ::google::protobuf::Message() { SharedCtor(); MergeFrom(from); } void ObjectRecordListEx::SharedCtor() { _cached_size_ = 0; ::memset(_has_bits_, 0, sizeof(_has_bits_)); } ObjectRecordListEx::~ObjectRecordListEx() { SharedDtor(); } void ObjectRecordListEx::SharedDtor() { if (this != default_instance_) { } } void ObjectRecordListEx::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* ObjectRecordListEx::descriptor() { protobuf_AssignDescriptorsOnce(); return ObjectRecordListEx_descriptor_; } const ObjectRecordListEx& ObjectRecordListEx::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_NFMsgBaseEx_2eproto(); return *default_instance_; } ObjectRecordListEx* ObjectRecordListEx::default_instance_ = NULL; ObjectRecordListEx* ObjectRecordListEx::New() const { return new ObjectRecordListEx; } void ObjectRecordListEx::Clear() { record_list_.Clear(); ::memset(_has_bits_, 0, sizeof(_has_bits_)); mutable_unknown_fields()->Clear(); } bool ObjectRecordListEx::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!(EXPRESSION)) return false ::google::protobuf::uint32 tag; while ((tag = input->ReadTag()) != 0) { switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // repeated .NFMsg.ObjectRecordBaseEx record_list = 1; case 1: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { parse_record_list: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, add_record_list())); } else { goto handle_uninterpreted; } if (input->ExpectTag(10)) goto parse_record_list; if (input->ExpectAtEnd()) return true; break; } default: { handle_uninterpreted: if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { return true; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } return true; #undef DO_ } void ObjectRecordListEx::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // repeated .NFMsg.ObjectRecordBaseEx record_list = 1; for (int i = 0; i < this->record_list_size(); i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, this->record_list(i), output); } if (!unknown_fields().empty()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } } ::google::protobuf::uint8* ObjectRecordListEx::SerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // repeated .NFMsg.ObjectRecordBaseEx record_list = 1; for (int i = 0; i < this->record_list_size(); i++) { target = ::google::protobuf::internal::WireFormatLite:: WriteMessageNoVirtualToArray( 1, this->record_list(i), target); } if (!unknown_fields().empty()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } return target; } int ObjectRecordListEx::ByteSize() const { int total_size = 0; // repeated .NFMsg.ObjectRecordBaseEx record_list = 1; total_size += 1 * this->record_list_size(); for (int i = 0; i < this->record_list_size(); i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( this->record_list(i)); } if (!unknown_fields().empty()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void ObjectRecordListEx::MergeFrom(const ::google::protobuf::Message& from) { GOOGLE_CHECK_NE(&from, this); const ObjectRecordListEx* source = ::google::protobuf::internal::dynamic_cast_if_available<const ObjectRecordListEx*>( &from); if (source == NULL) { ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { MergeFrom(*source); } } void ObjectRecordListEx::MergeFrom(const ObjectRecordListEx& from) { GOOGLE_CHECK_NE(&from, this); record_list_.MergeFrom(from.record_list_); mutable_unknown_fields()->MergeFrom(from.unknown_fields()); } void ObjectRecordListEx::CopyFrom(const ::google::protobuf::Message& from) { if (&from == this) return; Clear(); MergeFrom(from); } void ObjectRecordListEx::CopyFrom(const ObjectRecordListEx& from) { if (&from == this) return; Clear(); MergeFrom(from); } bool ObjectRecordListEx::IsInitialized() const { for (int i = 0; i < record_list_size(); i++) { if (!this->record_list(i).IsInitialized()) return false; } return true; } void ObjectRecordListEx::Swap(ObjectRecordListEx* other) { if (other != this) { record_list_.Swap(&other->record_list_); std::swap(_has_bits_[0], other->_has_bits_[0]); _unknown_fields_.Swap(&other->_unknown_fields_); std::swap(_cached_size_, other->_cached_size_); } } ::google::protobuf::Metadata ObjectRecordListEx::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = ObjectRecordListEx_descriptor_; metadata.reflection = ObjectRecordListEx_reflection_; return metadata; } // @@protoc_insertion_point(namespace_scope) } // namespace NFMsg // @@protoc_insertion_point(global_scope)
33.547662
109
0.695858
sosan
cedd898b3492da479ae92846e7c2fddeea17057f
452
cpp
C++
android-ndk-r10b/tests/device/test-stlport_static-exception/jni/new23.cpp
perezite/Boost4Android
9ed03a45815aead156c129da1927cc04b8caa6a3
[ "BSL-1.0" ]
7
2020-05-02T17:34:05.000Z
2021-10-17T10:15:18.000Z
android-ndk-r10b/tests/device/test-stlport_static-exception/jni/new23.cpp
perezite/Boost4Android
9ed03a45815aead156c129da1927cc04b8caa6a3
[ "BSL-1.0" ]
null
null
null
android-ndk-r10b/tests/device/test-stlport_static-exception/jni/new23.cpp
perezite/Boost4Android
9ed03a45815aead156c129da1927cc04b8caa6a3
[ "BSL-1.0" ]
2
2020-07-27T00:22:36.000Z
2021-04-01T09:41:02.000Z
// PR c++/33025 // { dg-do run } // { dg-options "-O2" } typedef __SIZE_TYPE__ size_t; inline void *operator new (size_t, void *p) throw () { return p; } extern "C" void abort (); int main() { const unsigned num = 10; unsigned *data = new unsigned[2 * num]; unsigned *ptr = data; for (unsigned i = 0; i < 2 * num; ++i) (i % 2 == 0) ? new (ptr) unsigned (2) : new (ptr++) unsigned (1); if (ptr - data != num) abort (); return 0; }
21.52381
69
0.564159
perezite
cede86a75074ccbe7e6c963f8307f5f1f8b1a13e
15,178
hpp
C++
test/unit/device/vector_iterator.hpp
mkarunan/rocWMMA
390a2e793699a1e17c18e46d7fe51e245907f012
[ "MIT" ]
null
null
null
test/unit/device/vector_iterator.hpp
mkarunan/rocWMMA
390a2e793699a1e17c18e46d7fe51e245907f012
[ "MIT" ]
1
2022-03-16T20:41:26.000Z
2022-03-16T20:41:26.000Z
test/unit/device/vector_iterator.hpp
mkarunan/rocWMMA
390a2e793699a1e17c18e46d7fe51e245907f012
[ "MIT" ]
2
2022-03-17T16:47:29.000Z
2022-03-18T14:12:22.000Z
/******************************************************************************* * * MIT License * * Copyright 2021-2022 Advanced Micro Devices, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * *******************************************************************************/ #ifndef ROCWMMA_DEVICE_VECTOR_ITERATOR_HPP #define ROCWMMA_DEVICE_VECTOR_ITERATOR_HPP #include <rocwmma/internal/types.hpp> static constexpr uint32_t ERROR_VALUE = 7; static constexpr uint32_t SUCCESS = 0; namespace rocwmma { template <uint32_t VectSize, typename DataT> __device__ static inline bool defaultConstructorTest() { // defaultConstructorTest VecT<DataT, VectSize> vectData; return (vectData.size() == VectSize); } template <uint32_t VectSize, typename DataT> __device__ static inline bool copyConstructorTest() { // copyConstructorTest0 VecT<DataT, VectSize> vectData; static_assert(vectData.size() == VectSize, "Allocation Error"); for(uint32_t i = 0; i < VectSize; i++) vectData[i] = static_cast<DataT>(i); VecT<DataT, VectSize> copyVectData(vectData); bool ret = (copyVectData.size() == vectData.size()); for(uint32_t i = 0; i < copyVectData.size(); i++) ret &= (copyVectData[i] == vectData[i]); VecT<DataT, VectSize> copyStorageData(*vectData); ret &= (copyStorageData.size() == vectData.size()); for(uint32_t i = 0; i < copyStorageData.size(); i++) ret &= (copyStorageData[i] == vectData[i]); VecT<DataT, VectSize> moveStorageData(std::move(*vectData)); ret &= (moveStorageData.size() == vectData.size()); for(uint32_t i = 0; i < moveStorageData.size(); i++) ret &= (moveStorageData[i] == vectData[i]); return ret; } template <uint32_t VectSize, typename DataT> __device__ static inline bool dereferenceTest() { // dereferenceTest VecT<DataT, VectSize> vectData; static_assert(vectData.size() == VectSize, "Allocation Error"); for(uint32_t i = 0; i < VectSize; i++) vectData[i] = static_cast<DataT>(i); VecT<DataT, VectSize> copyVectData(vectData); typename VecT<DataT, VectSize>::StorageT storageT = *copyVectData; bool ret = (sizeof(storageT) == (sizeof(DataT) * vectData.size())); for(uint32_t i = 0; i < copyVectData.size(); i++) ret &= (storageT[i] == copyVectData[i]); return ret; } template <uint32_t VectSize, typename DataT> __device__ static inline bool iteratorTest() { // iteratorTest VecT<DataT, VectSize> iterVectData; static_assert(iterVectData.size() == VectSize, " Allocation Error"); for(uint32_t i = 0; i < VectSize; i++) iterVectData[i] = static_cast<DataT>(i); const uint32_t iterSize = VectSize / 2; auto it = typename VecT<DataT, VectSize>::template iterator<iterSize>(iterVectData); bool ret = (iterVectData.size() == (it.range() * iterSize)); for(uint32_t i = 0; i < it.range(); i++, it++) { for(uint32_t j = 0; j < iterSize; j++) { ret &= (iterVectData[i * iterSize + j] == iterVectData[(*it)[j]]); } } return ret; } template <uint32_t VectSize, typename DataT> __device__ static inline bool iteratorValidityTest() { // iteratorValidityTest VecT<DataT, VectSize> iterVectData; static_assert(iterVectData.size() == VectSize, " Allocation Error"); for(uint32_t i = 0; i < VectSize; i++) iterVectData[i] = static_cast<DataT>(i); const uint32_t iterSize = VectSize / 2; auto it = typename VecT<DataT, VectSize>::template iterator<iterSize>(iterVectData); bool ret = it.valid(); ret &= (iterVectData.size() == (it.range() * iterSize)); return ret; } template <uint32_t VectSize, typename DataT> __device__ static inline bool iteratorIndexTest() { // iteratorIndexTest VecT<DataT, VectSize> iterVectData; static_assert(iterVectData.size() == VectSize, " Allocation Error"); for(uint32_t i = 0; i < VectSize; i++) iterVectData[i] = static_cast<DataT>(i); const uint32_t iterSize = VectSize / 2; auto it = typename VecT<DataT, VectSize>::template iterator<iterSize>(iterVectData); bool ret = it.valid(); ret &= (iterVectData.size() == (it.range() * iterSize)); ret &= (it.index() == 0); auto nextit = it.next(); ret &= (nextit.valid()); ret &= (nextit.index() == 1); return ret; } template <uint32_t VectSize, typename DataT> __device__ static inline bool iteratorRangeTest() { // iteratorRangeTest VecT<DataT, VectSize> iterVectData; static_assert(iterVectData.size() == VectSize, " Allocation Error"); for(uint32_t i = 0; i < VectSize; i++) iterVectData[i] = static_cast<DataT>(i); const uint32_t iterSize = VectSize / 2; auto it = typename VecT<DataT, VectSize>::template iterator<iterSize>(iterVectData); bool ret = it.valid(); ret &= ((iterVectData.size() / iterSize) == it.range()); return ret; } template <uint32_t VectSize, typename DataT> __device__ static inline bool iteratorBeginTest() { // iteratorBeginTest VecT<DataT, VectSize> iterVectData; static_assert(iterVectData.size() == VectSize, " Allocation Error"); for(uint32_t i = 0; i < VectSize; i++) iterVectData[i] = static_cast<DataT>(i); const uint32_t iterSize = VectSize / 2; auto it = iterVectData.template begin<iterSize>(); assert(iterVectData.size() == (it.range() * iterSize)); bool ret = true; ret &= (it.valid()); ret &= (iterVectData[0] == iterVectData[(*it)[0]]); return ret; } template <uint32_t VectSize, typename DataT> __device__ static inline bool iteratorEndTest() { // iteratorEndTest VecT<DataT, VectSize> iterVectData; static_assert(iterVectData.size() == VectSize, " Allocation Error"); for(uint32_t i = 0; i < VectSize; i++) iterVectData[i] = static_cast<DataT>(i); const uint32_t iterSize = VectSize / 2; auto it = iterVectData.template end<iterSize>(); assert(iterVectData.size() == (it.range() * iterSize)); bool ret = true; ret &= (iterVectData[0] == iterVectData[(*it)[0]]); return ret; } template <uint32_t VectSize, typename DataT> __device__ static inline bool iteratorObjTest() { // iteratorEndTest VecT<DataT, VectSize> iterVectData; static_assert(iterVectData.size() == VectSize, " Allocation Error"); for(uint32_t i = 0; i < VectSize; i++) iterVectData[i] = static_cast<DataT>(i); const uint32_t iterSize = VectSize / 2; auto it = iterVectData.template it<iterSize>(); assert(iterVectData.size() == (it.range() * iterSize)); bool ret = true; ret &= (iterVectData[0] == iterVectData[(*it)[0]]); return ret; } template <uint32_t VectSize, typename DataT> __device__ static inline bool iteratorIncTest() { // iteratorIncTest VecT<DataT, VectSize> iterVectData; static_assert(iterVectData.size() == VectSize, " Allocation Error"); for(uint32_t i = 0; i < VectSize; i++) iterVectData[i] = static_cast<DataT>(i); const uint32_t iterSize = VectSize / 2; auto it = typename VecT<DataT, VectSize>::template iterator<iterSize>(iterVectData); assert(iterVectData.size() == (it.range() * iterSize)); bool ret = true; for(uint32_t i = 0; i < it.range(); i++) { ret &= (it.valid()); ret &= (iterVectData[i * iterSize] == iterVectData[(*it)[0]]); ++it; } return ret; } template <uint32_t VectSize, typename DataT> __device__ static inline bool iteratorDecTest() { // iteratorDecTest VecT<DataT, VectSize> iterVectData; static_assert(iterVectData.size() == VectSize, " Allocation Error"); for(uint32_t i = 0; i < VectSize; i++) iterVectData[i] = static_cast<DataT>(i); const uint32_t iterSize = VectSize / 2; auto it = iterVectData.template end<iterSize>(); assert(iterVectData.size() == (it.range() * iterSize)); bool ret = true; for(uint32_t i = 0; i < it.range(); i++) { ret &= (iterVectData[i * iterSize] == iterVectData[(*it)[0]]); --it; ret &= (it.valid()); } return ret; } template <uint32_t VectSize, typename DataT> __device__ static inline bool iteratorNextTest() { // iteratorNextTest VecT<DataT, VectSize> iterVectData; static_assert(iterVectData.size() == VectSize, " Allocation Error"); for(uint32_t i = 0; i < VectSize; i++) iterVectData[i] = static_cast<DataT>(i); const uint32_t iterSize = VectSize / 2; auto it = typename VecT<DataT, VectSize>::template iterator<iterSize>(iterVectData); assert(iterVectData.size() == (it.range() * iterSize)); bool ret = true; ret &= (it.valid()); ret &= (iterVectData[0] == iterVectData[(*it)[0]]); auto nextit = it.next(); ret &= (nextit.valid()); ret &= (iterVectData[iterSize] == iterVectData[(*nextit)[0]]); return ret; } template <uint32_t VectSize, typename DataT> __device__ static inline bool iteratorPrevTest() { // iteratorPrevTest VecT<DataT, VectSize> iterVectData; static_assert(iterVectData.size() == VectSize, " Allocation Error"); for(uint32_t i = 0; i < VectSize; i++) iterVectData[i] = static_cast<DataT>(i); const uint32_t iterSize = VectSize / 2; auto it = iterVectData.template end<iterSize>(); assert(iterVectData.size() == (it.range() * iterSize)); bool ret = true; ret &= (iterVectData[0] == iterVectData[(*it)[0]]); auto previt = it.prev(); ret &= (previt.valid()); ret &= (iterVectData[iterSize] == iterVectData[(*previt)[0]]); return ret; } template <uint32_t VectSize, typename DataT> __global__ void VectorIterator(uint32_t m, uint32_t n, DataT const* in, DataT* out, uint32_t ld, DataT param1, DataT param2) { // Just need one thread if(threadIdx.x == 0 && threadIdx.y == 0 && threadIdx.z == 0 && blockIdx.x == 0 && blockIdx.y == 0 && blockIdx.z == 0) { out[0] = static_cast<DataT>(SUCCESS); bool err = defaultConstructorTest<VectSize, DataT>(); if(err == false) { out[0] = static_cast<DataT>(ERROR_VALUE); return; } err &= copyConstructorTest<VectSize, DataT>(); if(err == false) { out[0] = static_cast<DataT>(ERROR_VALUE); return; } err &= dereferenceTest<VectSize, DataT>(); if(err == false) { out[0] = static_cast<DataT>(ERROR_VALUE); return; } err &= iteratorTest<VectSize, DataT>(); if(err == false) { out[0] = static_cast<DataT>(ERROR_VALUE); return; } err &= iteratorValidityTest<VectSize, DataT>(); if(err == false) { out[0] = static_cast<DataT>(ERROR_VALUE); return; } err &= iteratorIndexTest<VectSize, DataT>(); if(err == false) { out[0] = static_cast<DataT>(ERROR_VALUE); return; } err &= iteratorRangeTest<VectSize, DataT>(); if(err == false) { out[0] = static_cast<DataT>(ERROR_VALUE); return; } err &= iteratorBeginTest<VectSize, DataT>(); if(err == false) { out[0] = static_cast<DataT>(ERROR_VALUE); return; } err &= iteratorEndTest<VectSize, DataT>(); if(err == false) { out[0] = static_cast<DataT>(ERROR_VALUE); return; } err &= iteratorObjTest<VectSize, DataT>(); if(err == false) { out[0] = static_cast<DataT>(ERROR_VALUE); return; } err &= iteratorIncTest<VectSize, DataT>(); if(err == false) { out[0] = static_cast<DataT>(ERROR_VALUE); return; } err &= iteratorDecTest<VectSize, DataT>(); if(err == false) { out[0] = static_cast<DataT>(ERROR_VALUE); return; } err &= iteratorNextTest<VectSize, DataT>(); if(err == false) { out[0] = static_cast<DataT>(ERROR_VALUE); return; } err &= iteratorPrevTest<VectSize, DataT>(); if(err == false) { out[0] = static_cast<DataT>(ERROR_VALUE); return; } } } } // namespace rocwmma #endif // ROCWMMA_DEVICE_VECTOR_ITERATOR_HPP
33.505519
93
0.550534
mkarunan