hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
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
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
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
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
80b7edbec1f2f840b179b3bb2181aedf29ea7b56
6,600
cpp
C++
src/OrbitGl/TracepointThreadBar.cpp
ioperations/orbit
c7935085023cce1abb70ce96dd03339f47a1c826
[ "BSD-2-Clause" ]
716
2017-09-22T11:50:40.000Z
2020-03-14T21:52:22.000Z
src/OrbitGl/TracepointThreadBar.cpp
ioperations/orbit
c7935085023cce1abb70ce96dd03339f47a1c826
[ "BSD-2-Clause" ]
132
2017-09-24T11:48:18.000Z
2020-03-17T17:39:45.000Z
src/OrbitGl/TracepointThreadBar.cpp
ioperations/orbit
c7935085023cce1abb70ce96dd03339f47a1c826
[ "BSD-2-Clause" ]
49
2017-09-23T10:23:59.000Z
2020-03-14T09:27:49.000Z
// Copyright (c) 2020 The Orbit Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "TracepointThreadBar.h" #include <GteVector.h> #include <absl/strings/str_format.h> #include <memory> #include <utility> #include "App.h" #include "CaptureViewElement.h" #include "ClientData/CaptureData.h" #include "ClientProtos/capture_data.pb.h" #include "ClientServices/TracepointServiceClient.h" #include "CoreMath.h" #include "Geometry.h" #include "GlCanvas.h" #include "GrpcProtos/tracepoint.pb.h" #include "OrbitBase/Logging.h" #include "OrbitBase/ThreadConstants.h" #include "PrimitiveAssembler.h" #include "TimeGraphLayout.h" #include "Viewport.h" namespace orbit_gl { TracepointThreadBar::TracepointThreadBar(CaptureViewElement* parent, OrbitApp* app, const orbit_gl::TimelineInfoInterface* timeline_info, orbit_gl::Viewport* viewport, TimeGraphLayout* layout, const orbit_client_data::ModuleManager* module_manager, const orbit_client_data::CaptureData* capture_data, uint32_t thread_id, const Color& color) : ThreadBar(parent, app, timeline_info, viewport, layout, module_manager, capture_data, thread_id, "Tracepoints", color) {} void TracepointThreadBar::DoDraw(PrimitiveAssembler& primitive_assembler, TextRenderer& text_renderer, const DrawContext& draw_context) { ThreadBar::DoDraw(primitive_assembler, text_renderer, draw_context); if (IsEmpty()) { return; } float event_bar_z = draw_context.picking_mode == PickingMode::kClick ? GlCanvas::kZValueEventBarPicking : GlCanvas::kZValueEventBar; Color color = GetColor(); Quad box = MakeBox(GetPos(), Vec2(GetWidth(), -GetHeight())); primitive_assembler.AddBox(box, event_bar_z, color, shared_from_this()); } void TracepointThreadBar::DoUpdatePrimitives(PrimitiveAssembler& primitive_assembler, TextRenderer& text_renderer, uint64_t min_tick, uint64_t max_tick, PickingMode picking_mode) { ORBIT_SCOPE_WITH_COLOR("TracepointThreadBar::DoUpdatePrimitives", kOrbitColorIndigo); ThreadBar::DoUpdatePrimitives(primitive_assembler, text_renderer, min_tick, max_tick, picking_mode); float z = GlCanvas::kZValueEvent; float track_height = layout_->GetEventTrackHeightFromTid(GetThreadId()); const bool picking = picking_mode != PickingMode::kNone; const Color kWhite(255, 255, 255, 255); const Color kWhiteTransparent(255, 255, 255, 190); const Color kGrey(128, 128, 128, 255); ORBIT_CHECK(capture_data_ != nullptr); if (!picking) { capture_data_->ForEachTracepointEventOfThreadInTimeRange( GetThreadId(), min_tick, max_tick, [&](const orbit_client_data::TracepointEventInfo& tracepoint) { uint64_t time = tracepoint.timestamp_ns(); float radius = track_height / 4; const Vec2 pos(timeline_info_->GetWorldFromTick(time), GetPos()[1]); if (GetThreadId() == orbit_base::kAllThreadsOfAllProcessesTid) { const Color color = tracepoint.pid() == capture_data_->process_id() ? kGrey : kWhite; primitive_assembler.AddVerticalLine(pos, -track_height, z, color); } else { primitive_assembler.AddVerticalLine(pos, -radius, z, kWhiteTransparent); primitive_assembler.AddVerticalLine(Vec2(pos[0], pos[1] - track_height), radius, z, kWhiteTransparent); primitive_assembler.AddCircle(Vec2(pos[0], pos[1] - track_height / 2), radius, z, kWhiteTransparent); } }); } else { constexpr float kPickingBoxWidth = 9.0f; constexpr float kPickingBoxOffset = kPickingBoxWidth / 2.0f; capture_data_->ForEachTracepointEventOfThreadInTimeRange( GetThreadId(), min_tick, max_tick, [&](const orbit_client_data::TracepointEventInfo& tracepoint) { uint64_t time = tracepoint.timestamp_ns(); Vec2 pos(timeline_info_->GetWorldFromTick(time) - kPickingBoxOffset, GetPos()[1] - track_height + 1); Vec2 size(kPickingBoxWidth, track_height); auto user_data = std::make_unique<PickingUserData>(nullptr, [&](PickingId id) -> std::string { return GetTracepointTooltip(primitive_assembler, id); }); user_data->custom_data_ = &tracepoint; primitive_assembler.AddShadedBox(pos, size, z, kWhite, std::move(user_data)); }); } } std::string TracepointThreadBar::GetTracepointTooltip(PrimitiveAssembler& primitive_assembler, PickingId id) const { auto* user_data = primitive_assembler.GetUserData(id); ORBIT_CHECK(user_data && user_data->custom_data_); const auto* tracepoint_event_info = static_cast<const orbit_client_data::TracepointEventInfo*>(user_data->custom_data_); uint64_t tracepoint_id = tracepoint_event_info->tracepoint_id(); ORBIT_CHECK(capture_data_ != nullptr); const orbit_client_data::TracepointInfo* tracepoint_info = capture_data_->GetTracepointInfo(tracepoint_id); ORBIT_CHECK(tracepoint_info != nullptr); if (GetThreadId() == orbit_base::kAllThreadsOfAllProcessesTid) { return absl::StrFormat( "<b>%s : %s</b><br/>" "<i>Tracepoint event</i><br/>" "<br/>" "<b>Core:</b> %d<br/>" "<b>Process:</b> %s [%d]<br/>" "<b>Thread:</b> %s [%d]<br/>", tracepoint_info->category(), tracepoint_info->name(), tracepoint_event_info->cpu(), capture_data_->GetThreadName(tracepoint_event_info->pid()), tracepoint_event_info->pid(), capture_data_->GetThreadName(tracepoint_event_info->tid()), tracepoint_event_info->tid()); } else { return absl::StrFormat( "<b>%s : %s</b><br/>" "<i>Tracepoint event</i><br/>" "<br/>" "<b>Core:</b> %d<br/>", tracepoint_info->category(), tracepoint_info->name(), tracepoint_event_info->cpu()); } } bool TracepointThreadBar::IsEmpty() const { return capture_data_ == nullptr || capture_data_->GetNumTracepointsForThreadId(GetThreadId()) == 0; } } // namespace orbit_gl
42.580645
98
0.650455
[ "geometry" ]
01ec3a0724f27b6a902b2293c62052013c34bbf2
9,820
hpp
C++
gmk/gmk.hpp
WastedMeerkat/gm81decompiler
80040ac74f95af03b4b6649b0f5be11a7d13700b
[ "MIT" ]
40
2017-07-31T22:20:49.000Z
2022-01-28T14:57:44.000Z
gmk/gmk.hpp
nkrapivin/gm81decompiler
bae1f8c3f52ed80c50319555c96752d087520821
[ "MIT" ]
null
null
null
gmk/gmk.hpp
nkrapivin/gm81decompiler
bae1f8c3f52ed80c50319555c96752d087520821
[ "MIT" ]
15
2015-12-29T16:36:28.000Z
2021-12-19T09:04:54.000Z
/* * gmk.hpp * GMK parser */ #ifndef __GMK_HPP #define __GMK_HPP #include <iostream> #include <vector> #include <string> #include <time.h> // GMK Constants #define GMK_MAGIC 1234321 #define GMK_VERSION 800 #define GMK_MAX_ID 100000000 // GMK Stream Constants #define FMODE_BINARY 0 #define FMODE_TEXT 1 // Resource tree constants #define RCT_GROUP_SPRITES 2 #define RCT_GROUP_SOUNDS 3 #define RCT_GROUP_BACKGROUNDS 6 #define RCT_GROUP_PATHS 8 #define RCT_GROUP_SCRIPTS 7 #define RCT_GROUP_FONTS 9 #define RCT_GROUP_TIMELINES 12 #define RCT_GROUP_OBJECTS 1 #define RCT_GROUP_ROOMS 4 #define RCT_ID_SPRITES 0 #define RCT_ID_SOUNDS 1 #define RCT_ID_BACKGROUNDS 2 #define RCT_ID_PATHS 3 #define RCT_ID_SCRIPTS 4 #define RCT_ID_FONTS 5 #define RCT_ID_TIMELINES 6 #define RCT_ID_OBJECTS 7 #define RCT_ID_ROOMS 8 class GmkStream; // Structures typedef struct _GameSettings { bool fullscreen, interpolate, dontDrawBorder, displayCursor, allowWindowResize, onTop, setResolution; bool dontShowButtons, vsync, disableScreen, letF4, letF1, letEsc, letF5, letF9, treatCloseAsEsc; bool freeze, transparent, scaleProgressBar, customLoadImage; bool errorDisplay, errorLog, errorAbort; int treatAsZero, errorOnUninitialization, translucency, majorVersion, minorVersion, releaseVersion, buildVersion; int priority, loadingBar; int scaling, colorOutsideRoom, colorDepth, resolution, frequency; time_t lastChanged, lastSettingsChanged; std::string author, version, information, company, product, copyright, description; GmkStream *backData, *frontData, *loadBar, *iconData; } GameSettings; typedef struct _Constant { std::string name, value; } Constant; typedef struct _Trigger { std::string name, condition, constantName; int checkMoment; } Trigger; typedef struct _Script { std::string name, value; time_t lastChanged; } Script; typedef struct _SubImage { int width, height; GmkStream* data; } SubImage; typedef struct _Sprite { std::string name; bool seperateMask; time_t lastChanged; int originX, originY, left, right, top, bottom; int shape, alphaTolerance, boundingBox; std::vector<SubImage*> images; } Sprite; typedef struct _Sound { std::string name, fileType, fileName; time_t lastChanged; double volume, pan; int kind, effects; bool preload; GmkStream* data; } Sound; typedef struct _Background { std::string name; time_t lastChanged; bool tileset; int width, height, tileWidth, tileHeight, hOffset, vOffset, hSep, vSep; GmkStream* data; } Background; typedef struct _PathPoint { double x, y, speed; } PathPoint; typedef struct _Path { std::string name; time_t lastChanged; int kind; bool closed; int prec, roomIndexBG, snapX, snapY; std::vector<PathPoint*> points; } Path; typedef struct _Font { std::string name, fontName; time_t lastChanged; int rangeBegin, rangeEnd, aaLevel, charset; int size; bool bold, italic; } Font; typedef struct _RoomBackground { bool visible, foreground, stretch, tileH, tileV; int x, y, hSpeed, vSpeed, bgIndex; } RoomBackground; typedef struct _RoomView { bool visible; int viewX, viewY, viewW, viewH, portX, portY, portW, portH, vBorder, hBorder, vSpd, hSpd, objFollow; } RoomView; typedef struct _RoomInstance { int x, y, objIndex, id; bool locked; std::string creationCode; } RoomInstance; typedef struct _RoomTile { int x, y, bgIndex, tileX, tileY, width, height, depth, id; bool locked; } RoomTile; typedef struct _Room { std::string name, caption, creationCode; time_t lastChanged; int speed; int width, height, snapX, snapY, bgColor, editorWidth, editorHeight, xPosScroll, yPosScroll; bool isoGrid, persistent, bgColorDraw, enableViews, rememberRoomEditorInfo, showGrid, showObjects, showTiles, showBackgrounds, showForegrounds, showViews, deleteUnderlyingObjects, deleteUnderlyingTiles; int tab; std::vector<RoomBackground*> backgrounds; std::vector<RoomView*> views; std::vector<RoomInstance*> instances; std::vector<RoomTile*> tiles; } Room; typedef struct _ObjectAction { std::string functionName, functionCode, argumentValue[8]; int libId, actId, kind, type, argumentsUsed, argumentKind[8], appliesToObject; bool isRelative, appliesToSomething, question, mayBeRelative, not; } ObjectAction; typedef struct _ObjectEvent { int eventType, eventKind; std::vector<ObjectAction*> actions; } ObjectEvent; typedef struct _Object { std::string name; time_t lastChanged; int spriteIndex, parentIndex, maskIndex, depth, objId; bool solid, visible, persistent; std::vector<ObjectEvent*> events; } Object; typedef struct _TimelineMoment { std::vector<ObjectAction*> actions; int moment; } TimelineMoment; typedef struct _Timeline { std::string name; time_t lastChanged; std::vector<TimelineMoment*> moments; } Timeline; typedef struct _IncludedFile { std::string fileName, filePath, folderExport; time_t lastChanged; int exportFlags, originalSize; bool originalFile, storedInGmk, overWrite, freeMem, removeGameEnd; GmkStream* data; } IncludeFile; typedef struct _ResourceTree { std::string name; int status, group; int index; std::vector<_ResourceTree*> contents; } ResourceTree; typedef struct _GameInfo { std::string caption, infoRtf; time_t lastChanged; bool seperateWindow, showWindowBorder, allowResize, stayOnTop, freezeGame; int left, top, width, height, bgColor; } GameInfo; // GMK Stream class class GmkStream { private: bool verbose; // Support void CheckStreamForWriting(size_t len); void CheckStreamForReading(size_t len); void Copy(GmkStream* src); void Move(GmkStream* src); // Compression unsigned char* DeflateStream(unsigned char* buffer, size_t iLen, size_t *oLen); unsigned char* InflateStream(unsigned char* buffer, size_t iLen, size_t *oLen); public: unsigned char* iBuffer; size_t iPosition, iLength; // Constructor/Deconstructor GmkStream() { iBuffer = new unsigned char[1]; iLength = iPosition = 0; verbose = true; } ~GmkStream() { delete[] iBuffer; } // Verbosity inline void SetVerbose(bool v) { verbose = v; } // Buffer inline unsigned char* GetBuffer() { return iBuffer; } inline size_t GetPosition() { return iPosition; } inline size_t GetLength() { return iLength; } inline void SetPosition(size_t p) { iPosition = p; } inline void SkipDwords(size_t count) { iPosition += count * 4; } void MoveAll(GmkStream* src); // File bool Load(const std::string& filename); bool Save(const std::string& filename, int mode); // Reading void ReadData(unsigned char* buffer, size_t len); bool ReadBool(); unsigned char ReadByte(); unsigned short ReadWord(); unsigned int ReadDword(); double ReadDouble(); std::string ReadString(); time_t ReadTimestamp(); // Writing void WriteData(unsigned char* buffer, size_t len); void WriteBool(bool value); void WriteByte(unsigned char value); void WriteWord(unsigned short value); void WriteDword(unsigned int value); void WriteDouble(double value); void WriteString(const std::string& value); void WriteTimestamp(); // Compression bool Deflate(); bool Inflate(); // Serialization bool Deserialize(GmkStream* dest, bool decompress); bool Serialize(bool compress); }; // GMK Class class Gmk { private: GmkStream *gmkHandle, *gmkSaveHandle; bool verbose; void Log(const std::string& value, bool error); // Reading bool ReadSettings(); bool ReadTriggers(); bool ReadConstants(); bool ReadSounds(); bool ReadSprites(); bool ReadBackgrounds(); bool ReadPaths(); bool ReadScripts(); bool ReadFonts(); bool ReadTimelines(); bool ReadObjects(); bool ReadRooms(); bool ReadIncludedFiles(); bool ReadGameInformation(); bool ReadResourceTree(); bool ReadAction(GmkStream* handle, ObjectAction* action); void ReadRecursiveTree(ResourceTree* handle, int children); // Writing bool WriteSettings(); bool WriteTriggers(); bool WriteConstants(); bool WriteSounds(); bool WriteSprites(); bool WriteBackgrounds(); bool WritePaths(); bool WriteScripts(); bool WriteFonts(); bool WriteTimelines(); bool WriteObjects(); bool WriteRooms(); bool WriteIncludedFiles(); bool WriteGameInformation(); bool WriteResourceTree(); bool WriteAction(GmkStream* handle, ObjectAction* action); void WriteRecursiveTree(ResourceTree* handle, int children); public: // Information unsigned int gmkVer, gameId, lastTile, lastInstance; time_t triggersChanged, constantsChanged; GameSettings settings; GameInfo gameInfo; std::vector<Constant*> constants; std::vector<Sprite*> sprites; std::vector<Sound*> sounds; std::vector<Background*> backgrounds; std::vector<Path*> paths; std::vector<Script*> scripts; std::vector<Font*> fonts; std::vector<Timeline*> timelines; std::vector<Object*> objects; std::vector<Room*> rooms; std::vector<ResourceTree*> resourceTree; std::vector<IncludeFile*> includes; std::vector<Trigger*> triggers; std::vector<std::string> packages; std::vector<std::string> libCreationCode; std::vector<int> roomExecutionOrder; Gmk() { gmkHandle = new GmkStream; gmkSaveHandle = new GmkStream; } Gmk::~Gmk() { // Clean up the obvious delete gmkHandle; delete gmkSaveHandle; } // Files bool Load(const std::string& filename); bool Save(const std::string& filename, unsigned int ver); void SetDefaults(); void Defragment(); void SetVerbose(bool v) { verbose = v; } }; // exception for GmkParser class GmkParserException { private: std::string err; public: GmkParserException(const std::string& e) : err(e) { }; const char* what() { return err.c_str(); } }; #endif
25.05102
206
0.729837
[ "object", "shape", "vector", "solid" ]
01f59e4000e43f91ebe8de74201cc4d4a20155a2
1,068
cpp
C++
Leetcode/0644. Maximum Average Subarray II/0644.cpp
Next-Gen-UI/Code-Dynamics
a9b9d5e3f27e870b3e030c75a1060d88292de01c
[ "MIT" ]
null
null
null
Leetcode/0644. Maximum Average Subarray II/0644.cpp
Next-Gen-UI/Code-Dynamics
a9b9d5e3f27e870b3e030c75a1060d88292de01c
[ "MIT" ]
null
null
null
Leetcode/0644. Maximum Average Subarray II/0644.cpp
Next-Gen-UI/Code-Dynamics
a9b9d5e3f27e870b3e030c75a1060d88292de01c
[ "MIT" ]
null
null
null
class Solution { public: double findMaxAverage(vector<int>& nums, int k) { constexpr double kErr = 1e-5; double l = *min_element(begin(nums), end(nums)); double r = *max_element(begin(nums), end(nums)); while (r - l > kErr) { const double m = (l + r) / 2; if (check(nums, k, m)) l = m; else r = m; } return l; } private: // true if there's a subarray with length >= k and average sum >= m bool check(const vector<int>& nums, int k, double m) { double sum = 0; double prevSum = 0; double minPrevSum = 0; for (int i = 0; i < nums.size(); ++i) { // trick: -m for each num so that we can check if the sum of the // subarray >= 0 sum += nums[i] - m; if (i >= k) { prevSum += nums[i - k] - m; minPrevSum = min(minPrevSum, prevSum); } // if sum - minPrevSum >= 0, // we know there's a subarray with length >= k and average sum >= m if (i + 1 >= k && sum >= minPrevSum) return true; } return false; }; };
24.837209
73
0.526217
[ "vector" ]
bf0116840a2bf7d313dc44fcaf159d81a6d2144a
15,366
cpp
C++
pxr/usd/usd/integerCoding.cpp
DougRogers-DigitalFish/USD
d8a405a1344480f859f025c4f97085143efacb53
[ "BSD-2-Clause" ]
3,680
2016-07-26T18:28:11.000Z
2022-03-31T09:55:05.000Z
pxr/usd/usd/integerCoding.cpp
DougRogers-DigitalFish/USD
d8a405a1344480f859f025c4f97085143efacb53
[ "BSD-2-Clause" ]
1,759
2016-07-26T19:19:59.000Z
2022-03-31T21:24:00.000Z
pxr/usd/usd/integerCoding.cpp
DougRogers-DigitalFish/USD
d8a405a1344480f859f025c4f97085143efacb53
[ "BSD-2-Clause" ]
904
2016-07-26T18:33:40.000Z
2022-03-31T09:55:16.000Z
// // Copyright 2017 Pixar // // Licensed under the Apache License, Version 2.0 (the "Apache License") // with the following modification; you may not use this file except in // compliance with the Apache License and the following modification to it: // Section 6. Trademarks. is deleted and replaced with: // // 6. Trademarks. This License does not grant permission to use the trade // names, trademarks, service marks, or product names of the Licensor // and its affiliates, except as required to comply with Section 4(c) of // the License and to reproduce the content of the NOTICE file. // // You may obtain a copy of the Apache License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the Apache License with the above modification is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the Apache License for the specific // language governing permissions and limitations under the Apache License. // #include "pxr/pxr.h" #include "pxr/base/tf/diagnostic.h" #include "pxr/base/tf/fastCompression.h" #include "pxr/usd/usd/integerCoding.h" #include <cstdint> #include <cstring> #include <limits> #include <memory> #include <unordered_map> PXR_NAMESPACE_OPEN_SCOPE /* These integer coding & compression routines are tailored for what are typically lists of indexes into other tables. The binary "usdc" file format has lots of these in its "structural sections" that define the object hierarchy. The basic idea is to take a contiguous list of 32-bit integers and encode them in a buffer that is not only smaller, but also still quite compressible by a general compression algorithm, and then compress that buffer to produce a final result. Decompression proceeds by going in reverse. The general compressor is LZ4 via TfFastCompression. The integer coding scheme implemented here is described below. We encode a list of integers as follows. First we transform the input to produce a new list of integers where each element is the difference between it and the previous integer in the input sequence. This is the sequence we encode. Next we find the most common value in the sequence and write it to the output. Then we write 2-bit codes, one for each integer, classifying it. Finally we write a variable length section of integer data. The decoder uses the 2-bit codes to understand how to interpret this variable length data. Given a list of integers, say: input = [123, 124, 125, 100125, 100125, 100126, 100126] We encode as follows. First, we transform the list to be the list of differences to the previous integer, or the integer itself for the first element in the list (this can be considered a difference to 0) to get: input_diffs = [123, 1, 1, 100000, 0, 1, 0] Then we find the most commonly occurring value in this sequence, which is '1'. We write this most commonly occurring value into the output stream. output = [int32(1)] Next we write two sections, first a fixed length section, 2-bit codes per integer, followed by a variable length section of integer data. The two bit code indicates what "kind" of integer we have: 00: The most common value 01: 8-bit integer 10: 16-bit integer 11: 32-bit integer For our example this gives: input = [123, 124, 125, 100125, 100125, 100126, 10026] output = [int32(1) 01 00 00 11 01 00 01 XX int8(123) int32(100000) int8(0) int8(0)] Where 'XX' represents unused bits in the last byte of the codes section to round up to an even number of bytes. In this case the output size is 12 bytes compared to the original input which was 28 bytes. In the best possible case the output is (asymptotically) 2 bits per integer (6.25% the original size), in the worst possible case it is (asymptotically) 34 bits per integer (106.25% the original size). */ namespace { template <class Int> inline typename std::enable_if< std::is_integral<Int>::value && std::is_unsigned<Int>::value && sizeof(Int) == 4, int32_t>::type _Signed(Int x) { if (x <= static_cast<uint32_t>(INT32_MAX)) return static_cast<int32_t>(x); if (x >= static_cast<uint32_t>(INT32_MIN)) return static_cast<int32_t>(x - INT32_MIN) + INT32_MIN; TF_FATAL_ERROR("Unsupported C++ integer representation"); return 0; } template <class Int> inline typename std::enable_if< std::is_integral<Int>::value && std::is_signed<Int>::value && sizeof(Int) == 4, int32_t>::type _Signed(Int x) { return x; } template <class Int> inline typename std::enable_if< std::is_integral<Int>::value && std::is_unsigned<Int>::value && sizeof(Int) == 8, int64_t>::type _Signed(Int x) { if (x <= static_cast<uint64_t>(INT64_MAX)) return static_cast<int64_t>(x); if (x >= static_cast<uint64_t>(INT64_MIN)) return static_cast<int64_t>(x - INT64_MIN) + INT64_MIN; TF_FATAL_ERROR("Unsupported C++ integer representation"); return 0; } template <class Int> inline typename std::enable_if< std::is_integral<Int>::value && std::is_signed<Int>::value && sizeof(Int) == 8, int64_t>::type _Signed(Int x) { return x; } template <class T> inline char *_WriteBits(char *p, T val) { memcpy(p, &val, sizeof(val)); return p + sizeof(val); } template <class T> inline T _ReadBits(char const *&p) { T ret; memcpy(&ret, p, sizeof(ret)); p += sizeof(ret); return ret; } template <class Int> constexpr size_t _GetEncodedBufferSize(size_t numInts) { // Calculate encoded integer size. return numInts ? /* commonValue */ (sizeof(Int)) + /* numCodesBytes */ ((numInts * 2 + 7) / 8) + /* maxIntBytes */ (numInts * sizeof(Int)) : 0; } template <class Int> struct _SmallTypes { typedef typename std::conditional< sizeof(Int) == 4, int8_t, int16_t>::type SmallInt; typedef typename std::conditional< sizeof(Int) == 4, int16_t, int32_t>::type MediumInt; }; template <int N, class Iterator> void _EncodeNHelper( Iterator &cur, typename std::iterator_traits<Iterator>::value_type commonValue, typename std::make_signed< typename std::iterator_traits<Iterator>::value_type >::type &prevVal, char *&codesOut, char *&vintsOut) { using Int = typename std::iterator_traits<Iterator>::value_type; using SInt = typename std::make_signed<Int>::type; using SmallInt = typename _SmallTypes<Int>::SmallInt; using MediumInt = typename _SmallTypes<Int>::MediumInt; static_assert(1 <= N && N <= 4, ""); enum Code { Common, Small, Medium, Large }; auto getCode = [commonValue](SInt x) { std::numeric_limits<SmallInt> smallLimit; std::numeric_limits<MediumInt> mediumLimit; if (x == _Signed(commonValue)) { return Common; } if (x >= smallLimit.min() && x <= smallLimit.max()) { return Small; } if (x >= mediumLimit.min() && x <= mediumLimit.max()) { return Medium; } return Large; }; uint8_t codeByte = 0; for (int i = 0; i != N; ++i) { SInt val = _Signed(*cur) - prevVal; prevVal = _Signed(*cur++); Code code = getCode(val); codeByte |= (code << (2 * i)); switch (code) { default: case Common: break; case Small: vintsOut = _WriteBits(vintsOut, static_cast<SmallInt>(val)); break; case Medium: vintsOut = _WriteBits(vintsOut, static_cast<MediumInt>(val)); break; case Large: vintsOut = _WriteBits(vintsOut, _Signed(val)); break; }; } codesOut = _WriteBits(codesOut, codeByte); } template <int N, class Iterator> void _DecodeNHelper( char const *&codesIn, char const *&vintsIn, typename std::iterator_traits<Iterator>::value_type commonValue, typename std::make_signed< typename std::iterator_traits<Iterator>::value_type >::type &prevVal, Iterator &output) { using Int = typename std::iterator_traits<Iterator>::value_type; using SInt = typename std::make_signed<Int>::type; using SmallInt = typename _SmallTypes<Int>::SmallInt; using MediumInt = typename _SmallTypes<Int>::MediumInt; enum Code { Common, Small, Medium, Large }; uint8_t codeByte = *codesIn++; for (int i = 0; i != N; ++i) { switch ((codeByte >> (2 * i)) & 3) { default: case Common: prevVal += commonValue; break; case Small: prevVal += _ReadBits<SmallInt>(vintsIn); break; case Medium: prevVal += _ReadBits<MediumInt>(vintsIn); break; case Large: prevVal += _ReadBits<SInt>(vintsIn); break; } *output++ = static_cast<Int>(prevVal); } } template <class Int> size_t _EncodeIntegers(Int const *begin, size_t numInts, char *output) { using SInt = typename std::make_signed<Int>::type; if (numInts == 0) return 0; // First find the most common element value. SInt commonValue = 0; { size_t commonCount = 0; std::unordered_map<SInt, size_t> counts; SInt prevVal = 0; for (Int const *cur = begin, *end = begin + numInts; cur != end; ++cur) { SInt val = _Signed(*cur) - prevVal; const size_t count = ++counts[val]; if (count > commonCount) { commonValue = val; commonCount = count; } else if (count == commonCount && val > commonValue) { // Take the largest common value in case of a tie -- this gives // the biggest potential savings in the encoded stream. commonValue = val; } prevVal = _Signed(*cur); } } // Now code the values. // Write most common value. char *p = _WriteBits(output, commonValue); char *codesOut = p; char *vintsOut = p + (numInts * 2 + 7) / 8; Int const *cur = begin; SInt prevVal = 0; while (numInts >= 4) { _EncodeNHelper<4>(cur, commonValue, prevVal, codesOut, vintsOut); numInts -= 4; } switch (numInts) { case 0: default: break; case 1: _EncodeNHelper<1>(cur, commonValue, prevVal, codesOut, vintsOut); break; case 2: _EncodeNHelper<2>(cur, commonValue, prevVal, codesOut, vintsOut); break; case 3: _EncodeNHelper<3>(cur, commonValue, prevVal, codesOut, vintsOut); break; }; return vintsOut - output; } template <class Int> size_t _DecodeIntegers(char const *data, size_t numInts, Int *result) { using SInt = typename std::make_signed<Int>::type; auto commonValue = _ReadBits<SInt>(data); size_t numCodesBytes = (numInts * 2 + 7) / 8; char const *codesIn = data; char const *vintsIn = data + numCodesBytes; SInt prevVal = 0; auto intsLeft = numInts; while (intsLeft >= 4) { _DecodeNHelper<4>(codesIn, vintsIn, commonValue, prevVal, result); intsLeft -= 4; } switch (intsLeft) { case 0: default: break; case 1: _DecodeNHelper<1>(codesIn, vintsIn, commonValue, prevVal, result); break; case 2: _DecodeNHelper<2>(codesIn, vintsIn, commonValue, prevVal, result); break; case 3: _DecodeNHelper<3>(codesIn, vintsIn, commonValue, prevVal, result); break; }; return numInts; } template <class Int> size_t _CompressIntegers(Int const *begin, size_t numInts, char *output) { // Working space. std::unique_ptr<char[]> encodeBuffer(new char[_GetEncodedBufferSize<Int>(numInts)]); // Encode first. size_t encodedSize = _EncodeIntegers(begin, numInts, encodeBuffer.get()); // Then compress. return TfFastCompression::CompressToBuffer( encodeBuffer.get(), output, encodedSize); } template <class Int> size_t _DecompressIntegers(char const *compressed, size_t compressedSize, Int *ints, size_t numInts, char *workingSpace) { // Working space. size_t workingSpaceSize = Usd_IntegerCompression::GetDecompressionWorkingSpaceSize(numInts); std::unique_ptr<char[]> tmpSpace; if (!workingSpace) { tmpSpace.reset(new char[workingSpaceSize]); workingSpace = tmpSpace.get(); } size_t decompSz = TfFastCompression::DecompressFromBuffer( compressed, workingSpace, compressedSize, workingSpaceSize); if (decompSz == 0) return 0; return _DecodeIntegers(workingSpace, numInts, ints); } } // anon //////////////////////////////////////////////////////////////////////// // 32 bit. size_t Usd_IntegerCompression::GetCompressedBufferSize(size_t numInts) { return TfFastCompression::GetCompressedBufferSize( _GetEncodedBufferSize<int32_t>(numInts)); } size_t Usd_IntegerCompression::GetDecompressionWorkingSpaceSize(size_t numInts) { return _GetEncodedBufferSize<int32_t>(numInts); } size_t Usd_IntegerCompression::CompressToBuffer( int32_t const *ints, size_t numInts, char *compressed) { return _CompressIntegers(ints, numInts, compressed); } size_t Usd_IntegerCompression::CompressToBuffer( uint32_t const *ints, size_t numInts, char *compressed) { return _CompressIntegers(ints, numInts, compressed); } size_t Usd_IntegerCompression::DecompressFromBuffer( char const *compressed, size_t compressedSize, int32_t *ints, size_t numInts, char *workingSpace) { return _DecompressIntegers(compressed, compressedSize, ints, numInts, workingSpace); } size_t Usd_IntegerCompression::DecompressFromBuffer( char const *compressed, size_t compressedSize, uint32_t *ints, size_t numInts, char *workingSpace) { return _DecompressIntegers(compressed, compressedSize, ints, numInts, workingSpace); } //////////////////////////////////////////////////////////////////////// // 64 bit. size_t Usd_IntegerCompression64::GetCompressedBufferSize(size_t numInts) { return TfFastCompression::GetCompressedBufferSize( _GetEncodedBufferSize<int64_t>(numInts)); } size_t Usd_IntegerCompression64::GetDecompressionWorkingSpaceSize(size_t numInts) { return _GetEncodedBufferSize<int64_t>(numInts); } size_t Usd_IntegerCompression64::CompressToBuffer( int64_t const *ints, size_t numInts, char *compressed) { return _CompressIntegers(ints, numInts, compressed); } size_t Usd_IntegerCompression64::CompressToBuffer( uint64_t const *ints, size_t numInts, char *compressed) { return _CompressIntegers(ints, numInts, compressed); } size_t Usd_IntegerCompression64::DecompressFromBuffer( char const *compressed, size_t compressedSize, int64_t *ints, size_t numInts, char *workingSpace) { return _DecompressIntegers(compressed, compressedSize, ints, numInts, workingSpace); } size_t Usd_IntegerCompression64::DecompressFromBuffer( char const *compressed, size_t compressedSize, uint64_t *ints, size_t numInts, char *workingSpace) { return _DecompressIntegers(compressed, compressedSize, ints, numInts, workingSpace); } PXR_NAMESPACE_CLOSE_SCOPE
30.129412
83
0.666081
[ "object", "transform" ]
bf03bc39e3159d025d5d51d1af425b579e8dcefd
431
cpp
C++
src/Weaponry.cpp
crumblingstatue/Galaxy
a33d1df85e57a88206265c2780b288f3fda52bbb
[ "CC-BY-3.0" ]
1
2015-08-27T17:01:48.000Z
2015-08-27T17:01:48.000Z
src/Weaponry.cpp
crumblingstatue/Galaxy
a33d1df85e57a88206265c2780b288f3fda52bbb
[ "CC-BY-3.0" ]
11
2015-09-24T03:15:13.000Z
2016-02-23T03:03:04.000Z
src/Weaponry.cpp
crumblingstatue/Galaxy
a33d1df85e57a88206265c2780b288f3fda52bbb
[ "CC-BY-3.0" ]
1
2016-02-16T22:25:06.000Z
2016-02-16T22:25:06.000Z
#include "Weaponry.h" #include "math.h" #include <iostream> void explosion(int xpos, int ypos, int /*size*/, int /*power*/, bool /*frag*/) { std::cout << math::closeishS(xpos, ypos) << " Is the stuff\n"; // std::cout << plat << std::endl; // std::vector<NPC>::iterator Targets; // for( Targets = npclist.begin(); Targets != npclist.end(); ++Targets ){ // std::cout << Targets.name << std::endl; }
26.9375
80
0.575406
[ "vector" ]
bf0828339e99acea6c0c371ef861b35740b080c5
13,486
hpp
C++
include/strings.hpp
Ptomaine/nstd
72daa4abab97dc82b407c774b00476459df0730b
[ "MIT" ]
31
2017-06-28T09:50:03.000Z
2021-08-11T14:09:35.000Z
include/strings.hpp
Ptomaine/nstd
72daa4abab97dc82b407c774b00476459df0730b
[ "MIT" ]
null
null
null
include/strings.hpp
Ptomaine/nstd
72daa4abab97dc82b407c774b00476459df0730b
[ "MIT" ]
5
2017-06-29T13:43:23.000Z
2020-09-01T02:47:11.000Z
#pragma once /* MIT License Copyright (c) 2017 Arlen Keshabyan (arlen.albert@gmail.com) 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 <cwctype> #include <cctype> #include <iomanip> #include <limits> #include <regex> #include <sstream> #include <string> #include <string_view> #include "utf8.hpp" namespace nstd::str { namespace { template <typename StringViewType> inline auto trim_left_impl(StringViewType sv, const StringViewType chars_to_remove) { sv.remove_prefix(std::min(sv.find_first_not_of(chars_to_remove), std::size(sv))); return sv; } template <typename StringViewType> inline auto trim_right_impl(StringViewType sv, const StringViewType chars_to_remove) { sv.remove_suffix(sv.size() - (sv.find_last_not_of(chars_to_remove) + 1)); return sv; } template <typename StringViewType> inline auto trim_impl(StringViewType sv, const StringViewType chars_to_remove) { return trim_right_impl(trim_left_impl(sv, chars_to_remove), chars_to_remove); } } inline std::u8string from_utf16_to_utf8(const std::u16string_view s) { std::u8string result; nstd::utf8::utf16to8(std::begin(s), std::end(s), std::back_inserter(result)); return result; } inline std::u8string from_utf32_to_utf8(const std::u32string_view s) { std::u8string result; nstd::utf8::utf32to8(std::begin(s), std::end(s), std::back_inserter(result)); return result; } inline std::u16string from_utf8_to_utf16(const std::u8string_view s) { std::u16string result; nstd::utf8::utf8to16(std::begin(s), std::end(s), std::back_inserter(result)); return result; } inline std::u16string from_utf32_to_utf16(const std::u32string_view s) { std::u8string in; std::u16string result; nstd::utf8::utf32to8(std::begin(s), std::end(s), std::back_inserter(in)); nstd::utf8::utf8to16(std::begin(in), std::end(in), std::back_inserter(result)); return result; } inline std::u32string from_utf8_to_utf32(const std::u8string_view s) { std::u32string result; nstd::utf8::utf8to32(std::begin(s), std::end(s), std::back_inserter(result)); return result; } inline std::u32string from_utf16_to_utf32(const std::u16string_view s) { std::u8string in; std::u32string result; nstd::utf8::utf16to8(std::begin(s), std::end(s), std::back_inserter(in)); nstd::utf8::utf8to32(std::begin(in), std::end(in), std::back_inserter(result)); return result; } constexpr const char *const whitespace_chars { " \t\n\v\f\r" }; constexpr const wchar_t *const wwhitespace_chars { L" \t\n\v\f\r" }; constexpr const char8_t *const u8whitespace_chars { u8" \t\n\v\f\r" }; constexpr const char16_t *const u16whitespace_chars { u" \t\n\v\f\r" }; constexpr const char32_t *const u32whitespace_chars { U" \t\n\v\f\r" }; constexpr const char *const boolalpha[] = { "false", "true" }; constexpr const wchar_t *const wboolalpha[] = { L"false", L"true" }; constexpr const char8_t *const u8boolalpha[] = { u8"false", u8"true" }; constexpr const char16_t *const u16boolalpha[] = { u"false", u"true" }; constexpr const char32_t *const u32boolalpha[] = { U"false", U"true" }; inline std::string_view trim_left(std::string_view sv, const std::string_view chars_to_remove = whitespace_chars) { return trim_left_impl(sv, chars_to_remove); } inline std::wstring_view trim_left(std::wstring_view sv, const std::wstring_view chars_to_remove = wwhitespace_chars) { return trim_left_impl(sv, chars_to_remove); } inline std::u8string_view trim_left(std::u8string_view sv, const std::u8string_view chars_to_remove = u8whitespace_chars) { return trim_left_impl(sv, chars_to_remove); } inline std::u16string_view trim_left(std::u16string_view sv, const std::u16string_view chars_to_remove = u16whitespace_chars) { return trim_left_impl(sv, chars_to_remove); } inline std::u32string_view trim_left(std::u32string_view sv, const std::u32string_view chars_to_remove = u32whitespace_chars) { return trim_left_impl(sv, chars_to_remove); } inline std::string_view trim_right(std::string_view sv, const std::string_view chars_to_remove = whitespace_chars) { return trim_right_impl(sv, chars_to_remove); } inline std::wstring_view trim_right(std::wstring_view sv, const std::wstring_view chars_to_remove = wwhitespace_chars) { return trim_right_impl(sv, chars_to_remove); } inline std::u8string_view trim_right(std::u8string_view sv, const std::u8string_view chars_to_remove = u8whitespace_chars) { return trim_right_impl(sv, chars_to_remove); } inline std::u16string_view trim_right(std::u16string_view sv, const std::u16string_view chars_to_remove = u16whitespace_chars) { return trim_right_impl(sv, chars_to_remove); } inline std::u32string_view trim_right(std::u32string_view sv, const std::u32string_view chars_to_remove = u32whitespace_chars) { return trim_right_impl(sv, chars_to_remove); } inline std::string_view trim(std::string_view sv, const std::string_view chars_to_remove = whitespace_chars) { return trim_impl(sv, chars_to_remove); } inline std::wstring_view trim(std::wstring_view sv, const std::wstring_view chars_to_remove = wwhitespace_chars) { return trim_impl(sv, chars_to_remove); } inline std::u8string_view trim(std::u8string_view sv, const std::u8string_view chars_to_remove = u8whitespace_chars) { return trim_impl(sv, chars_to_remove); } inline std::u16string_view trim(std::u16string_view sv, const std::u16string_view chars_to_remove = u16whitespace_chars) { return trim_impl(sv, chars_to_remove); } inline std::u32string_view trim(std::u32string_view sv, const std::u32string_view chars_to_remove = u32whitespace_chars) { return trim_impl(sv, chars_to_remove); } template <typename T> using any_string_view = std::basic_string_view<T, std::char_traits<T>>; template <typename T> using any_string = std::basic_string<T, std::char_traits<T>, std::allocator<T>>; template <typename T> inline any_string<T>& replace_all_inplace(any_string<T>& str, const any_string<T>& from, const any_string<T>& to) { if (std::empty(from)) return str; size_t start_pos { 0 }; while((start_pos = str.find(from, start_pos)) != std::string::npos) { str.replace(start_pos, from.length(), to); start_pos += std::size(to); } return str; } template <typename T> inline any_string<T> replace_all(const any_string<T>& cstr, const any_string<T>& from, const any_string<T>& to) { any_string<T> str { cstr }; return replace_all_inplace(str, from, to); } template <typename T> inline any_string<T> replace_regex(const any_string<T>& cstr, const any_string<T>& from, const any_string<T>& to, std::regex_constants::syntax_option_type opts = std::regex_constants::ECMAScript) { return std::regex_replace(cstr, std::basic_regex<T>{ from, opts }, to); } template<typename T> inline bool is_empty_or_ws(const any_string<T> &str) { static_assert(std::is_same_v<T, char> || std::is_same_v<T, wchar_t>, "Unsupported string type provided to is_empty_or_ws. Supported types are std::string and std::wstring"); return std::all_of(std::begin(str), std::end(str), [](auto &&c) { if constexpr (std::is_same_v<T, char>) return std::isspace(static_cast<unsigned char>(c)); else return std::iswspace(c); }); } template <typename C, typename T> inline any_string<T> join(const C& container, const any_string<T>& delimiter) { std::basic_stringstream<T> oss; auto begin = std::begin(container); auto end = std::end(container); if (begin != end) { oss << *begin; while (++begin != end) oss << delimiter << *begin; } return oss.str(); } template <typename T> inline std::vector<any_string<T>> split_regex(const any_string<T>& input, const any_string<T>& pattern, std::regex_constants::syntax_option_type opts = std::regex_constants::ECMAScript) { std::basic_regex<T> re { pattern, opts }; return { std::regex_token_iterator<typename any_string<T>::const_iterator> { std::begin(input), std::end(input), re, -1 }, std::regex_token_iterator<typename any_string<T>::const_iterator> {} }; } template<typename ... Args> inline std::string compose_string(const Args& ... args) { std::ostringstream oss; ((oss << args), ... ); return oss.str(); } template<typename ... Args> inline std::wstring compose_wstring(const Args& ... args) { std::wostringstream oss; ((oss << args), ... ); return oss.str(); } template<typename NumericType> inline std::string numeric_to_string(NumericType value, int precision = -1) { if (value == std::numeric_limits<NumericType>::infinity()) return "INF"; else if (value == -std::numeric_limits<NumericType>::infinity()) return "-INF"; else if (value != value) return "NaN"; std::ostringstream oss; if (precision >= 0 && precision <= std::numeric_limits<NumericType>::max_digits10) oss << std::setprecision(precision); return (oss << value), oss.str(); } template<typename NumericType> inline std::wstring numeric_to_wstring(NumericType value, int precision = -1) { if (value == std::numeric_limits<NumericType>::infinity()) return L"INF"; else if (value == -std::numeric_limits<NumericType>::infinity()) return L"-INF"; else if (value != value) return L"NaN"; std::wostringstream oss; if (precision >= 0 && precision <= std::numeric_limits<NumericType>::max_digits10) oss << std::setprecision(precision); return (oss << value), oss.str(); } template<typename NumericType> inline NumericType string_to_numeric(const std::string &value) { if (value == "INF") return std::numeric_limits<NumericType>::infinity(); else if (value == "-INF") return -std::numeric_limits<NumericType>::infinity(); else if (value == "NaN") return std::numeric_limits<NumericType>::quiet_NaN(); std::istringstream iss { value }; NumericType result; return (iss >> result), result; } template<typename NumericType> inline NumericType wstring_to_numeric(const std::wstring &value) { if (value == L"INF") return std::numeric_limits<NumericType>::infinity(); else if (value == L"-INF") return -std::numeric_limits<NumericType>::infinity(); else if (value == L"NaN") return std::numeric_limits<NumericType>::quiet_NaN(); std::wistringstream iss { value }; NumericType result; return (iss >> result), result; } template <typename T> inline any_string<T> pad_left(const any_string<T>& str, int32_t total_digits, T filler) { if (total_digits <= 0) return str; const int32_t str_length { static_cast<int32_t>(std::size(str)) }; return any_string<T>(std::clamp(total_digits - str_length, 0, total_digits), filler) + str; } template <typename T> inline any_string<T> pad_right(const any_string<T>& str, int32_t total_digits, T filler) { if (total_digits <= 0) return str; const int32_t str_length { static_cast<int32_t>(std::size(str)) }; return str + any_string<T>(std::clamp(total_digits - str_length, 0, total_digits), filler); } template <typename T> inline any_string<T> reverse(const any_string<T>& str) { return { std::rbegin(str), std::rend(str) }; } template <typename T> inline any_string<T>& reverse_inplace(any_string<T>& str) { auto idx_back { std::size(str) }, idx { 0ul }, half_size { idx_back / 2 }; while (half_size--) std::swap(str[idx++], str[--idx_back]); return str; } inline std::string add_string_numbers(const std::string& a, const std::string& b) { if (a.starts_with('-') || b.starts_with('-')) return {}; std::string result; auto aa { reverse(a) }, bb { reverse(b) }; auto max_length { std::max(std::size(aa), std::size(bb)) }; result.reserve(max_length + 1); aa = pad_right(aa, static_cast<int32_t>(max_length), '0'); bb = pad_right(bb, static_cast<int32_t>(max_length), '0'); int carry_flag { 0 }; for (auto idx { 0u }; idx < max_length; ++idx) { auto local { (aa[idx] - '0') + (bb[idx] - '0') + carry_flag }; carry_flag = local / 10; result.append(1, '0' + static_cast<std::string::value_type>(local % 10)); } if (carry_flag) result.append(1, '1'); (void)reverse_inplace(result); return result; } }
37.254144
196
0.700356
[ "vector" ]
bf0dc29d8e4c00797efa6769f3200ba1af32b363
28,755
cpp
C++
torrentR/src/PhaseSim.cpp
konradotto/TS
bf088bd8432b1e3f4b8c8c083650a30d9ef2ae2e
[ "Apache-2.0" ]
125
2015-01-22T05:43:23.000Z
2022-03-22T17:15:59.000Z
torrentR/src/PhaseSim.cpp
konradotto/TS
bf088bd8432b1e3f4b8c8c083650a30d9ef2ae2e
[ "Apache-2.0" ]
59
2015-02-10T09:13:06.000Z
2021-11-11T02:32:38.000Z
torrentR/src/PhaseSim.cpp
konradotto/TS
bf088bd8432b1e3f4b8c8c083650a30d9ef2ae2e
[ "Apache-2.0" ]
98
2015-01-17T01:25:10.000Z
2022-03-18T17:29:42.000Z
/* Copyright (C) 2010 Ion Torrent Systems, Inc. All Rights Reserved */ #include <cassert> #include <cmath> #include <iostream> #include <iomanip> #include <limits> #include <numeric> #include "PhaseSim.h" #include "IonErr.h" using namespace std; #define PHASE_DEBUG 0 PhaseSim::PhaseSim() : droopType(ONLY_WHEN_INCORPORATING) , extraTaps(0) , maxAdvances(0) , droopedWeight(0) , ignoredWeight(0) , weightPrecision(1e-6) , maxPops(0) { nucHpScale.push_back(1); } PhaseSim::~PhaseSim() { } //flowstring flow order, seq = read in bases long computeSeqFlow(const string &seq, const string &flowString, long basePos) { size_t nFlowPerCycle = flowString.length(); size_t nBases = seq.length(); //seqFlow.resize(0); unsigned int iFlow=0; unsigned int iNuc=0; while(iNuc < nBases) { char flowBase = flowString[iFlow % nFlowPerCycle]; hpLen_t hp=0; while((iNuc < nBases) && (seq[iNuc]==flowBase)) { if (iNuc == basePos) { return iFlow; } iNuc++; hp++; } //seqFlow.push_back(hp); iFlow++; } return -1;//must not have been found.. } //flowstring flow order, seq = read in bases void computeSeqFlow(const string &seq, const string &flowString, hpLen_vec_t &seqFlow) { size_t nFlowPerCycle = flowString.length(); size_t nBases = seq.length(); seqFlow.resize(0); unsigned int iFlow=0; unsigned int iNuc=0; while(iNuc < nBases) { char flowBase = flowString[iFlow % nFlowPerCycle]; hpLen_t hp=0; while((iNuc < nBases) && (seq[iNuc]==flowBase)) { iNuc++; hp++; } seqFlow.push_back(hp); iFlow++; } } void computeSeqFlow(const hpLen_vec_t &hpLen, const nuc_vec_t &hpNuc, const nuc_vec_t &flowCycle, hpLen_vec_t &seqFlow) { unsigned int nFlowsPerCycle = flowCycle.size(); if(nFlowsPerCycle > 0) { unsigned int nHP = hpLen.size(); seqFlow.resize(0); unsigned int iFlow=0; for(unsigned int iHP=0; iHP < nHP; iHP++) { while(flowCycle[iFlow]!=hpNuc[iHP]) { seqFlow.push_back(0); iFlow = (iFlow+1) % nFlowsPerCycle; } seqFlow.push_back(hpLen[iHP]); iFlow = (iFlow+1) % nFlowsPerCycle; } } } void PhaseSim::setFlowCycle(string flowString) { size_t nFlowPerCycle = flowString.length(); flowCycle.resize(nFlowPerCycle); for(unsigned int i=0; i<nFlowPerCycle; i++) flowCycle[i] = charToNuc(flowString[i]); // If we already have a sequence loaded, update seqFlow for the new flow order if(hpLen.size() > 0) computeSeqFlow(hpLen,hpNuc,flowCycle,seqFlow); } // Overloaded call to setSeq accepting a string as input void PhaseSim::setSeq(string seqString) { size_t seqLen = seqString.length(); nuc_vec_t seq(seqLen); for(unsigned int i=0; i<seqLen; i++) { seq[i] = charToNuc(seqString[i]); } setSeq(seq); } void PhaseSim::getSeq(string &seqString) { unsigned int nBases=0; for(hpLen_vec_t::const_iterator iHpLen=hpLen.begin(); iHpLen!=hpLen.end(); iHpLen++) nBases += (unsigned int) *iHpLen; seqString.reserve(nBases); seqString.assign(""); hpLen_vec_t::const_iterator iHpLen=hpLen.begin(); nuc_vec_t::const_iterator iHpNuc=hpNuc.begin(); while(iHpLen != hpLen.end() && iHpNuc != hpNuc.end()) { char b = nucToChar(*iHpNuc); for(hpLen_t iBase=0; iBase < *iHpLen; iBase++) seqString += b; iHpLen++; iHpNuc++; } } // Given a sequence, sets the hpLen and hpNuc void PhaseSim::setSeq(nuc_vec_t &seq) { size_t nBase = seq.size(); hpLen.resize(nBase); hpNuc.resize(nBase); if(nBase > 0) { hpLen_vec_t::iterator iHpLen = hpLen.begin(); nuc_vec_t::iterator iHpNuc = hpNuc.begin(); nuc_t prevHpNuc = seq[0]; *iHpLen = 0; *iHpNuc = seq[0]; unsigned int nHp = 1; for(nuc_vec_t::const_iterator iSeq=seq.begin(); iSeq!=seq.end(); iSeq++) { if(*iSeq == prevHpNuc) { // Continuation of an existing HP stretch (*iHpLen)++; } else { // Start of a new HP stretch iHpLen++; *iHpLen = 1; iHpNuc++; *iHpNuc = *iSeq; prevHpNuc = *iHpNuc; nHp++; } } hpLen.resize(nHp); hpNuc.resize(nHp); } // Set seq flow from the hpLen and hpNuc vectors computeSeqFlow(hpLen,hpNuc,flowCycle,seqFlow); } void PhaseSim::setSeq(hpLen_vec_t &_seqFlow) { seqFlow = _seqFlow; if(flowCycle.size() == 0) throw("Cannot set the seq flow because the flow order has not been set"); unsigned int nFlowsPerCycle = flowCycle.size(); unsigned int nFlow = seqFlow.size(); hpLen.reserve(nFlow); hpLen.resize(0); hpNuc.reserve(nFlow); hpNuc.resize(0); unsigned int iFlow=0; for(hpLen_vec_t::const_iterator iSeqFlow=seqFlow.begin(); iSeqFlow != seqFlow.end(); iSeqFlow++, iFlow++) { if(*iSeqFlow > 0) { hpLen.push_back(*iSeqFlow); hpNuc.push_back(flowCycle[iFlow % nFlowsPerCycle]); } } hpLen.resize(hpLen.size()); hpNuc.resize(hpNuc.size()); } // TODO: make this funciton faster by providing an interface to allow for // updating a limited range when only a local region of the sequence has changed. void PhaseSim::setAdvancerContexts(unsigned int maxAdv) { maxAdvances = maxAdv; // Make sure the advancer vectors have enough capacity for the current sequeunce. // If not then reserve with some headroom to help reduce future realloc if(advancerLen.capacity() < hpNuc.size()) advancerLen.reserve((unsigned int)(1.2*hpNuc.size())); if(advancerContext.capacity() < hpNuc.size()) advancerContext.reserve((unsigned int)(1.2*hpNuc.size())); // Fill in advancerContext and advancerLen vectors hpNucToIndex(hpNuc,maxAdvances,advancerContext,advancerLen); } void PhaseSim::setAdvancerWeights(vector<weight_vec_t> &concentration, weight_vec_t &cf, weight_vec_t &ie, weight_vec_t &dr, advancer_t &extendAdvancer, advancer_t &droopAdvancer, bool firstCycle) { unsigned int nFlowPerCycle = flowCycle.size(); // Make sure a valid set of concentrations was supplied if(concentration.size() == 0) { concentration.resize(N_NUCLEOTIDES); for(unsigned int iNuc=0; iNuc < N_NUCLEOTIDES; iNuc++) { concentration[iNuc].assign(N_NUCLEOTIDES,0); concentration[iNuc][iNuc] = 1; } } else if(concentration.size() != N_NUCLEOTIDES) { throw("Vector of conentrations must be either empty or of length four"); } else { for(unsigned int iNuc=0; iNuc < N_NUCLEOTIDES; iNuc++) if(concentration[iNuc].size() != N_NUCLEOTIDES) throw("Each entry in the vector of concentrations should be of length four"); } // Make sure valid CF, IE and DR parameters were supplied if(cf.size() == 1) { cf.assign(nFlowPerCycle,cf.front()); } else if(cf.size() != nFlowPerCycle) { throw("Vector of cf values must be of length 1 or of the same length as the number of flows"); } if(ie.size() == 1) { ie.assign(nFlowPerCycle,ie.front()); } else if(ie.size() != nFlowPerCycle) { throw("Vector of ie values must be of length 1 or of the same length as the number of flows"); } if(dr.size() == 1) { dr.assign(nFlowPerCycle,dr.front()); } else if(dr.size() != nFlowPerCycle) { throw("Vector of dr values must be of length 1 or of the same length as the number of flows"); } if(droopAdvancer.size() != nFlowPerCycle) droopAdvancer.resize(nFlowPerCycle); if(extendAdvancer.size() != nFlowPerCycle) extendAdvancer.resize(nFlowPerCycle); unsigned int nLengths = maxAdvances+1; // Iterate over each flow in the flowCycle for(unsigned int iFlow=0; iFlow < flowCycle.size(); iFlow++) { // Determine the effect of carry-forward on the nuc concentrations weight_vec_t cumulative_cf = cf; weight_vec_t conc_with_cf = concentration[flowCycle[iFlow]]; for(unsigned int stepsBack=1; stepsBack < nFlowPerCycle; stepsBack++) { if(firstCycle && stepsBack > iFlow) break; unsigned int prevFlow = (iFlow - stepsBack + nFlowPerCycle) % nFlowPerCycle; for(unsigned int i=0; i < conc_with_cf.size(); i++) { conc_with_cf[i] += cumulative_cf[i] * concentration[flowCycle[prevFlow]][i]; cumulative_cf[i] *= cf[i]; } } // Sweep the concentrations to ensure nothing is larger than 1 for(unsigned int i=0; i < conc_with_cf.size(); i++) { if(conc_with_cf[i] > 1) conc_with_cf[i] = 1; } // Debug code - print out the nuc concentrations reflecting both contamination and carry-forward //cout << "flow " << iFlow << " nuc " << nucToChar(flowCycle[iFlow]) << ", concs = "; //for(unsigned int i=0; i < conc_with_cf.size(); i++) // cout << " " << setiosflags(ios::fixed) << setprecision(8) << conc_with_cf[i]; //cout << "\n"; if(droopAdvancer[iFlow].size() != nLengths) droopAdvancer[iFlow].resize(nLengths); if(extendAdvancer[iFlow].size() != nLengths) extendAdvancer[iFlow].resize(nLengths); // Iterate over each limit to extension length unsigned int nContexts = 1; for(unsigned int iLength=0; iLength <= maxAdvances; iLength++) { if(iLength > 0) nContexts *= N_NUCLEOTIDES; if(droopAdvancer[iFlow][iLength].size() != nContexts) droopAdvancer[iFlow][iLength].resize(nContexts); if(extendAdvancer[iFlow][iLength].size() != nContexts) extendAdvancer[iFlow][iLength].resize(nContexts); // Iterate over each sequence context for(unsigned int iContext=0; iContext < nContexts; iContext++) { setAdvancerWeightsByContext(conc_with_cf,iLength,iContext,ie,dr,extendAdvancer[iFlow][iLength][iContext],droopAdvancer[iFlow][iLength][iContext]); } } } } void PhaseSim::printAdvancerWeights(advancer_t &extendAdvancer, advancer_t &droopAdvancer) { unsigned int nHP = hpLen.size(); for(unsigned int iFlow=0; iFlow < flowCycle.size(); iFlow++) { cout << "working on flow " << iFlow << " which is nuc " << nucToChar(flowCycle[iFlow]) << "\n"; for(unsigned int iHP=0; iHP < nHP; iHP++) { //cout << "templates of length " << iHP << " can advance " << (int) advancerLen[iHP] << " states\n"; //cout << " seq context = " << advancerContext[iHP] << " = "; nuc_vec_t seqContext; indexToSeqContext(advancerContext[iHP],seqContext,advancerLen[iHP]); string context; for(unsigned int iSeq=0; iSeq < seqContext.size(); iSeq++) context += nucToChar(seqContext[iSeq]); //cout << context << "\n"; cout << "flow" << iFlow << " " << context; cout << "\tex:"; for(unsigned int i=0; i <= extendAdvancer[iFlow][advancerLen[iHP]][advancerContext[iHP]].size(); i++) cout << " " << setiosflags(ios::fixed) << setprecision(6) << extendAdvancer[iFlow][advancerLen[iHP]][advancerContext[iHP]][i]; cout << "\tdr:"; for(unsigned int i=0; i <= droopAdvancer[iFlow][advancerLen[iHP]][advancerContext[iHP]].size(); i++) cout << " " << setiosflags(ios::fixed) << setprecision(6) << droopAdvancer[iFlow][advancerLen[iHP]][advancerContext[iHP]][i]; cout << "\n"; } } } void PhaseSim::setAdvancerWeightsByContext(weight_vec_t &nuc_conc, unsigned int len, unsigned int seqContextIndex, weight_vec_t &nuc_ie, weight_vec_t &nuc_dr, weight_vec_t &extender, weight_vec_t &drooper) { nuc_vec_t seqContext; indexToSeqContext(seqContextIndex, seqContext, len); weight_vec_t cc(len); weight_vec_t dr(len); weight_vec_t iePrime(len); weight_vec_t drPrime(len); for(unsigned int i=0; i<len; i++) { cc[i] = nuc_conc[seqContext[i]]; dr[i] = nuc_dr[seqContext[i]]; iePrime[i] = 1-nuc_ie[seqContext[i]]; drPrime[i] = 1-dr[i]; } // Initialization drooper.assign(len+1,0); extender.assign(len+1,0); extender.front() = 1; for(unsigned int step=0; step<len; step++) { // Welcome to the core of the CAFIE model weight_t toReAllocate = extender[step]; // The template mass that will be reallocated weight_t droops, extends; switch(droopType) { case(EVERY_FLOW): // In this model strands droop regardless of whether or not there will be any extension. droops = toReAllocate * dr[step]; extends = toReAllocate * (drPrime[step] * cc[step] * iePrime[step]); drooper[step] = droops; extender[step+1] = extends; extender[step] -= (droops+extends); break; case(ONLY_WHEN_INCORPORATING): // In this model droop only happens when incorporation happens, and will be proportional to it. extends = toReAllocate * (cc[step] * iePrime[step]); droops = extends * dr[step]; drooper[step] = droops; extender[step+1] = extends-droops; extender[step] -= extends; break; default: throw("Invalid droop model"); } } // Trim back negligible weights trimTail(extender,weightPrecision); trimTail(drooper,weightPrecision); #if PHASE_DEBUG // Sanity check - confirm that everything sums to one double drSum = 0; for(unsigned int i=0; i<drooper.size(); i++) drSum += drooper[i]; double exSum = 0; for(unsigned int i=0; i<extender.size(); i++) exSum += extender[i]; if(abs(1-drSum-exSum) > weightPrecision) { cout << "diff is " << 1-drSum-exSum << "\n"; cout << " seq context = " << seqContextIndex << " = "; for(unsigned int iSeq=0; iSeq < seqContext.size(); iSeq++) cout << nucToChar(seqContext[iSeq]); cout << "\n"; cout << " " << "cc:"; for(unsigned int i=0; i < cc.size(); i++) cout << " " << setiosflags(ios::fixed) << setprecision(4) << cc[i]; cout << "\n"; cout << " " << "dr:"; for(unsigned int i=0; i < dr.size(); i++) cout << " " << setiosflags(ios::fixed) << setprecision(4) << dr[i]; cout << "\n"; cout << " " << "ie:"; for(unsigned int i=0; i < iePrime.size(); i++) cout << " " << setiosflags(ios::fixed) << setprecision(4) << (1-iePrime[i]); cout << "\n"; cout << " " << "extender:"; for(unsigned int i=0; i < extender.size(); i++) cout << " " << setiosflags(ios::fixed) << setprecision(4) << extender[i]; cout << "\n"; cout << " " << "drooper:"; for(unsigned int i=0; i < drooper.size(); i++) cout << " " << setiosflags(ios::fixed) << setprecision(4) << drooper[i]; cout << "\n"; } #endif } void PhaseSim::setHpScale(const weight_vec_t &_nucHpScale) { unsigned int n = _nucHpScale.size(); if(n != 1 && n != N_NUCLEOTIDES) throw("nucHpScale vector must be of length 1 or 4\n"); nucHpScale = _nucHpScale; } void PhaseSim::saveTemplateState(weight_vec_t &_hpWeight, weight_t &_droopedWeight, weight_t &_ignoredWeight, readLen_vec_t &_posWeight, hpLen_vec_t &_hpLen, nuc_vec_t &_hpNuc) { _hpWeight = hpWeight; _droopedWeight = droopedWeight; _ignoredWeight = ignoredWeight; _posWeight = posWeight; _hpLen = hpLen; _hpNuc = hpNuc; } void PhaseSim::resetTemplate(weight_vec_t &_hpWeight, weight_t &_droopedWeight, weight_t &_ignoredWeight, readLen_vec_t &_posWeight, hpLen_vec_t &_hpLen, nuc_vec_t &_hpNuc) { #if PHASE_DEBUG unsigned int _nWeight = _hpWeight.size(); assert(_hpLen.size() == _hpNuc.size()); assert(_hpLen.size() == (_nWeight-1)); #endif hpLen = _hpLen; hpNuc = _hpNuc; resetTemplate(_hpWeight, _droopedWeight, _ignoredWeight, _posWeight); } void PhaseSim::resetTemplate(weight_vec_t &_hpWeight, weight_t &_droopedWeight, weight_t &_ignoredWeight, readLen_vec_t &_posWeight) { #if PHASE_DEBUG unsigned int _nWeight = _hpWeight.size(); assert(_posWeight.front() <= _posWeight.back()); assert(_posWeight.back() < _nWeight); #endif // Copy in the new values hpWeight = _hpWeight; droopedWeight = _droopedWeight; ignoredWeight = _ignoredWeight; posWeight = _posWeight; // Make sure template weights sum to one #if PHASE_DEBUG assert(hpWeightOK()); #endif } void PhaseSim::resetTemplate(void) { unsigned int nWeight = hpLen.size()+1; weight_vec_t _hpWeight(nWeight,0); _hpWeight[0] = 1; weight_t _droopedWeight = 0; weight_t _ignoredWeight = 0; readLen_vec_t _posWeight(1,0); resetTemplate(_hpWeight, _droopedWeight, _ignoredWeight, _posWeight); } weight_t PhaseSim::applyFlow(unsigned int iFlow, advancer_t &extendAdvancer, advancer_t &droopAdvancer, bool testOnly) { weight_vec_t newHpWeight; readLen_vec_t newPosWeight; return(applyFlow(iFlow, extendAdvancer, droopAdvancer, testOnly, newHpWeight, newPosWeight)); } weight_t PhaseSim::applyFlow(unsigned int iFlow, advancer_t &extendAdvancer, advancer_t &droopAdvancer, bool testOnly, weight_vec_t &newHpWeight, readLen_vec_t &newPosWeight) { #if PHASE_DEBUG assert(advancerLen.size() == hpLen.size()); #endif if(iFlow >= flowCycle.size()) iFlow = iFlow % flowCycle.size(); unsigned int nHP = hpNuc.size(); unsigned int nWeight = hpWeight.size(); #if PHASE_DEBUG assert(nHP+1 == nWeight); #endif // Initialize scratch space to which new configuration will be written newHpWeight.assign(nWeight,0); newHpWeight[nHP] = hpWeight[nHP]; weight_t incorporationSignal = 0; weight_t newDroopedWeight = 0; for(size_t iPosWeight=0; iPosWeight < posWeight.size(); iPosWeight++) { readLen_t iHP = posWeight[iPosWeight]; if(iHP==advancerContext.size()) break; weight_t startingTemplates = hpWeight[iHP]; advancer_len_t nAdvance = advancerLen[iHP]; weight_vec_t &ex = extendAdvancer[iFlow][nAdvance][advancerContext[iHP]]; weight_vec_t &dr = droopAdvancer[iFlow][nAdvance][advancerContext[iHP]]; newHpWeight[iHP] += startingTemplates * ex[0]; newDroopedWeight += startingTemplates * dr[0]; advancer_len_t maxAdvance = max(ex.size(),dr.size()); for(unsigned int iAdvance=1; iAdvance < maxAdvance; iAdvance++) { // hpLenSum is the sum of the HP incorporation signals for HPs through which we advance weight_t hpLenSum = 0; for(unsigned int extra=0; extra < iAdvance; extra++) { hpLen_t thisHpLen = hpLen[iHP+extra]; //weight_t scale = nucHpScale[hpNuc[iHP+extra] % nucHpScale.size()]; //hpLenSum += thisHpLen * pow(scale,(weight_t)thisHpLen); hpLenSum += thisHpLen; } // update live templates weight_t extended; if(iAdvance < ex.size()) { extended = startingTemplates * ex[iAdvance]; newHpWeight[iHP+iAdvance] += extended; } else { extended = 0; } // update drooped templates weight_t drooped; if(iAdvance < dr.size()) { drooped = startingTemplates * dr[iAdvance]; newDroopedWeight += drooped; } else { drooped = 0; } // update incorporation signal incorporationSignal += (extended+drooped) * hpLenSum; } } #if PHASE_DEBUG assert(hpWeightOK()); #endif if(!testOnly) { // Copy the new configuration into hpWeight // TODO: possible fast approximation by limiting to tracking no more than N positive populations here // TODO: instead of iterating over all positive positions, jump only over ones with positive weight. newPosWeight.clear(); unsigned int max_possible_hp_len = min((nWeight-1),(unsigned int) (posWeight.back() + maxAdvances)); for(unsigned int iHP=posWeight.front(); iHP <= max_possible_hp_len; iHP++) { weight_t thisWeight = newHpWeight[iHP]; if(thisWeight > weightPrecision) { hpWeight[iHP] = thisWeight; newPosWeight.push_back(iHP); } else { hpWeight[iHP] = 0; ignoredWeight += thisWeight; } } droopedWeight += newDroopedWeight; posWeight = newPosWeight; #if PHASE_DEBUG assert(hpWeightOK()); #endif } #if PHASE_DEBUG assert(hpWeightOK()); #endif // Recursive calls to add multi-tap flows if requested. // Currently the signal from these extra flows is just lost. // It could easily be tracked here if necessary. if(!testOnly && (extraTaps > 0)) { extraTaps--; applyFlow(iFlow, extendAdvancer, droopAdvancer, testOnly, newHpWeight, newPosWeight); #if PHASE_DEBUG assert(hpWeightOK()); #endif extraTaps++; } return(incorporationSignal); } weight_t PhaseSim::getWeightSum(void) { unsigned int nWeight = hpWeight.size(); weight_t total = 0; for(unsigned int iHP=0; iHP < nWeight; iHP++) { total += hpWeight[iHP]; } total += droopedWeight; total += ignoredWeight; return(total); } bool PhaseSim::hpWeightOK(void) { weight_t total = getWeightSum(); weight_t eps = max(numeric_limits<weight_t>::epsilon(),10*weightPrecision); #if PHASE_DEBUG weight_t activ = accumulate(hpWeight.begin(), hpWeight.end(), 0.0); #endif weight_t activTail = accumulate(hpWeight.begin() + posWeight.back() + 1, hpWeight.end(), 0.0); bool okTotal = abs(total-1) < eps; bool okActivTail = activTail < eps; bool ok = okTotal && okActivTail; #if PHASE_DEBUG if(not ok){ cout << "OK?" << setw(16) << scientific << activ << setw(16) << scientific << droopedWeight << setw(16) << scientific << ignoredWeight << setw(16) << scientific << total << endl; cout << setw(16) << scientific << total << endl; cout << setw(16) << scientific << 1.0-total << endl; unsigned int nWeight = hpWeight.size(); cout << setw(6) << hpWeight.size() << endl; for(unsigned int iHP=0; iHP < nWeight; iHP++) { cout << setw( 6) << iHP << setw(16) << scientific << hpWeight[iHP] << endl; } } #endif return(ok); } weight_t PhaseSim::vectorSum(const weight_vec_t &v) { weight_t sum = 0; for(weight_vec_t::const_iterator i=v.begin(); i != v.end(); i++) sum += *i; return(sum); } bool PhaseSim::advancerWeightOK(advancer_t &extendAdvancer, advancer_t &droopAdvancer) { bool weightOK = true; for(unsigned int iFlow=0; iFlow < flowCycle.size(); iFlow++) { unsigned int nContexts = 1; for(unsigned int iLength=0; iLength <= maxAdvances; iLength++) { if(iLength > 0) nContexts *= N_NUCLEOTIDES; for(unsigned int iContext=0; iContext < nContexts; iContext++) { weight_t s = vectorSum(extendAdvancer[iFlow][iLength][iContext]) + vectorSum(droopAdvancer[iFlow][iLength][iContext]); if(abs(1-s) > 1e-8) { weightOK = false; break; } } } } return(weightOK); } nuc_t charToNuc(char base) { switch(base) { case 'A': case 'a': return(0); break; case 'C': case 'c': return(1); break; case 'G': case 'g': return(2); break; case 'T': case 't': return(3); break; default: throw("Invalid nucleotide"); } } char nucToChar(nuc_t nuc) { switch(nuc) { case 0: return('A'); break; case 1: return('C'); break; case 2: return('G'); break; case 3: return('T'); break; default: cerr << "Invalid nuc " << (int)nuc << "\n"; assert(false); throw("Invalid nuc value"); } } void PhaseSim::simulate( string flowString, string seq, vector<weight_vec_t> concentration, weight_vec_t cf, weight_vec_t ie, weight_vec_t dr, unsigned int nFlow, weight_vec_t & signal, vector<weight_vec_t> & hpWeightReturn, weight_vec_t & droopWeightReturn, bool returnIntermediates, DroopType droopType, unsigned int maxAdv ) { setDroopType(droopType); setFlowCycle(flowString); setSeq(seq); setAdvancerContexts(maxAdv); setAdvancerWeights(concentration, cf, ie, dr, extendAdvancerFirst, droopAdvancerFirst, true ); setAdvancerWeights(concentration, cf, ie, dr, extendAdvancer, droopAdvancer, false); resetTemplate(); signal.resize(nFlow); if(returnIntermediates) { hpWeightReturn.resize(nFlow); droopWeightReturn.resize(nFlow); } bool testOnly = false; bool firstCycle = true; unsigned int nFlowPerCycle = flowCycle.size(); for(unsigned int iFlow=0; iFlow<nFlow; iFlow++) { if(iFlow >= nFlowPerCycle) firstCycle = false; if(firstCycle) signal[iFlow] = applyFlow(iFlow, extendAdvancerFirst, droopAdvancerFirst, testOnly); else signal[iFlow] = applyFlow(iFlow % flowCycle.size(), extendAdvancer, droopAdvancer, testOnly); if(returnIntermediates) { hpWeightReturn[iFlow] = getHpWeights(); droopWeightReturn[iFlow] = getDroopWeight(); } #if PHASE_DEBUG if(!hpWeightOK()) cerr << "Problem after applying flow " << iFlow << ", weight sum is " << setiosflags(ios::fixed) << setprecision(10)<< getWeightSum() << "\n"; #endif } } // TODO: redo this with bit shifting for speed void PhaseSim::indexToSeqContext(unsigned int index, nuc_vec_t &seqContext, unsigned int len) { seqContext.resize(len); if(len > 0) { unsigned int divisor = 1; for(unsigned int iNuc=1; iNuc < len; iNuc++) { divisor *= N_NUCLEOTIDES; } for(int iNuc=len-1; iNuc >= 0; iNuc--) { nuc_t nuc = index/divisor; index -= nuc*divisor; seqContext[iNuc] = nuc; divisor /= N_NUCLEOTIDES; } } } // Key normalization void keyNormalize(weight_vec_t &signal, string key, string flowOrder) { hpLen_vec_t keyFlow; computeSeqFlow(key, flowOrder, keyFlow); keyNormalize(signal, keyFlow); } // Key normalization when key flows have already been computed void keyNormalize(weight_vec_t &signal, hpLen_vec_t &keyFlow) { // Determine scaling factor unsigned int nOneMer=0; weight_t oneMerSum=0; unsigned int maxKeyFlow = min(keyFlow.size()-1,signal.size()); for(unsigned int iFlow=0; iFlow < maxKeyFlow; iFlow++) { if(keyFlow[iFlow] == 1) { nOneMer++; oneMerSum += signal[iFlow]; } } if(nOneMer==0) ION_ABORT("Cannot normalize to key, it has no 1-mers"); oneMerSum /= (weight_t) nOneMer; // Scale all flow values for(unsigned int iFlow=0; iFlow < signal.size(); iFlow++) { signal[iFlow] /= oneMerSum; } } void trimTail(weight_vec_t &v, weight_t precision) { // keep track of weight that is taken away weight_t trimmedWeight = 0; // trim trailing entries weight_vec_t::reverse_iterator rit; for(rit=v.rbegin(); rit < v.rend(); ++rit) { if(*rit < precision) { trimmedWeight += *rit; v.pop_back(); } else { break; } } // zero intervening entries unsigned int nonzeroEntries=0; for(; rit < v.rend(); ++rit) { if(*rit < precision) { trimmedWeight += *rit; *rit = 0; } else { nonzeroEntries++; } } // add weight back in to the nonzero entries if(nonzeroEntries > 0) { trimmedWeight /= (weight_t) nonzeroEntries; weight_vec_t::iterator it; for(it=v.begin(); it != v.end(); ++it) { if(*it > 0) { *it += trimmedWeight; } } } else { if(v.size()==0) { v.push_back(trimmedWeight); } else { v[0] = trimmedWeight; } } } unsigned int makeMask(unsigned char n) { unsigned int mask=0; for(unsigned int i=0; i < n; i++) { mask <<= 1; mask |= 1; } return(mask); } void hpNucToIndex(nuc_vec_t &hpNuc, advancer_len_t maxAdvances, vector<unsigned int> &contextIndex, vector<advancer_len_t> &contextLen) { // Make a bitmask with lowest 2*maxAdvances bits set to 1. unsigned int contextMask = makeMask(2*maxAdvances); unsigned int nHP = hpNuc.size(); contextIndex.resize(nHP); contextLen.resize(nHP); unsigned int thisContextIndex=0; advancer_len_t thisContextLen=0; nuc_vec_t::reverse_iterator hpNucRit=hpNuc.rbegin(); vector<unsigned int>::reverse_iterator contextIndexRit=contextIndex.rbegin(); vector<advancer_len_t>::reverse_iterator contextLenRit=contextLen.rbegin(); for( ; hpNucRit != hpNuc.rend(); hpNucRit++, contextIndexRit++, contextLenRit++) { thisContextIndex <<= 2; thisContextIndex &= contextMask; thisContextIndex |= (unsigned int) *hpNucRit; if(thisContextLen < maxAdvances) thisContextLen++; *contextIndexRit = thisContextIndex; *contextLenRit = thisContextLen; } } void PhaseSim::setPhaseParam( string & _flowString, hpLen_t _maxAdvances, vector<weight_vec_t> & _concentration, weight_vec_t & _cf, weight_vec_t & _ie, weight_vec_t & _dr, DroopType _droopType ) { setFlowCycle(_flowString); setMaxAdvances(_maxAdvances); setDroopType(_droopType); setAdvancerWeights(_concentration, _cf, _ie, _dr, extendAdvancerFirst, droopAdvancerFirst, true ); setAdvancerWeights(_concentration, _cf, _ie, _dr, extendAdvancer, droopAdvancer, false); }
31.12013
207
0.6498
[ "vector", "model" ]
bf1114f64c398dea32ec9728042306838777d718
502
cpp
C++
src/yars/configuration/xsd/specification/XsdEnumeration.cpp
kzahedi/YARS
48d9fe4178d699fba38114d3b299a228da41293d
[ "MIT" ]
4
2017-08-05T03:33:21.000Z
2021-11-08T09:15:42.000Z
src/yars/configuration/xsd/specification/XsdEnumeration.cpp
kzahedi/YARS
48d9fe4178d699fba38114d3b299a228da41293d
[ "MIT" ]
null
null
null
src/yars/configuration/xsd/specification/XsdEnumeration.cpp
kzahedi/YARS
48d9fe4178d699fba38114d3b299a228da41293d
[ "MIT" ]
1
2019-03-24T08:35:25.000Z
2019-03-24T08:35:25.000Z
#include "XsdEnumeration.h" XsdEnumeration::XsdEnumeration(string name, string type) : XsdNode(XSD_NODE_TYPE_ENUMERATION) { _name = name; _type = type; } void XsdEnumeration::add(string value) { _value.push_back(value); } std::vector<string>::iterator XsdEnumeration::v_begin() { return _value.begin(); } std::vector<string>::iterator XsdEnumeration::v_end() { return _value.end(); } string XsdEnumeration::name() { return _name; } string XsdEnumeration::type() { return _type; }
14.764706
56
0.717131
[ "vector" ]
bf13ff3fc38f772b81b47564c523f574438e0126
1,372
cpp
C++
Leetcode 53. Maximum Subarray.cpp
Kamalc/Problems-and-Algorithms
ffee8b5b903a7af919812c282d21a9755a883c29
[ "MIT" ]
null
null
null
Leetcode 53. Maximum Subarray.cpp
Kamalc/Problems-and-Algorithms
ffee8b5b903a7af919812c282d21a9755a883c29
[ "MIT" ]
null
null
null
Leetcode 53. Maximum Subarray.cpp
Kamalc/Problems-and-Algorithms
ffee8b5b903a7af919812c282d21a9755a883c29
[ "MIT" ]
null
null
null
//============================================================================ // Name : Maximum Subarray // Author : Kamal Saad // Version : // Copyright : MIT copyright // Description : Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. //============================================================================ // #include <bits/stdc++.h> using namespace std; int max_value_sub_array_prefix_sol(const vector<int>& nums) { // O(n) Prefix Sum Base Approach int prefix = 0, min_last_prefix = 0, res = INT_MIN; for (int i = 0; i < (int) nums.size(); i++) { //cout<<prefix<< " "<< min_last_prefix<< " "<< res<<endl; prefix += nums[i]; res = max(res, (prefix - min_last_prefix)); min_last_prefix = min(min_last_prefix, prefix); } return res; } int max_value_sub_array_slide_window(const vector<int>& nums) { // O(n) Variable size Sliding Window Based Approach (Kadane's Algorithm [DP]) int res = INT_MIN , max_sum_window = 0; for(int i =0 ;i< (int)nums.size();i++) { max_sum_window = max(nums[i], max_sum_window + nums[i]); res = max(res, max_sum_window); } return res; } int main() { vector<int> vec { -2, 1, -3, 4, -1, 2, 1, -5, 4 }; cout << endl << "Length : " << max_value_sub_array_slide_window(vec) << endl; return 0; }
28.583333
153
0.575073
[ "vector" ]
bf17956c8cd711d46b141e65021e80ad47136985
38,953
cpp
C++
isode++/demo/iso/itu/osi/fsm/TCP/TcpConnection.cpp
Kampbell/ISODE
37f161e65f11348ef6fca2925d399d611df9f31b
[ "Apache-2.0" ]
3
2016-01-18T17:00:00.000Z
2021-06-25T03:18:13.000Z
isode++/demo/iso/itu/osi/fsm/TCP/TcpConnection.cpp
Kampbell/ISODE
37f161e65f11348ef6fca2925d399d611df9f31b
[ "Apache-2.0" ]
null
null
null
isode++/demo/iso/itu/osi/fsm/TCP/TcpConnection.cpp
Kampbell/ISODE
37f161e65f11348ef6fca2925d399d611df9f31b
[ "Apache-2.0" ]
null
null
null
// // The contents of this file are subject to the Mozilla Public // License Version 1.1 (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.mozilla.org/MPL/ // // Software distributed under the License is distributed on an // "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or // implied. See the License for the specific language governing // rights and limitations under the License. // // The Original Code is State Machine Compiler (SMC). // // The Initial Developer of the Original Code is Charles W. Rapp. // Portions created by Charles W. Rapp are // Copyright (C) 2000 - 2007. Charles W. Rapp. // All Rights Reserved. // // Contributor(s): // // Name // TcpConnection.cpp // // Description // TCP connection class implementation. // // RCS ID // $Id: TcpConnection.cpp,v 1.9 2015/08/02 19:44:35 cwrapp Exp $ // // CHANGE LOG // $Log: TcpConnection.cpp,v $ // Revision 1.9 2015/08/02 19:44:35 cwrapp // Release 6.6.0 commit. // // Revision 1.8 2014/09/06 09:04:29 fperrad // pragma only for MS compiler // // Revision 1.7 2007/12/28 12:34:40 cwrapp // Version 5.0.1 check-in. // // Revision 1.6 2005/06/08 11:09:12 cwrapp // + Updated Python code generator to place "pass" in methods with empty // bodies. // + Corrected FSM errors in Python example 7. // + Removed unnecessary includes from C++ examples. // + Corrected errors in top-level makefile's distribution build. // // Revision 1.5 2005/05/28 13:31:18 cwrapp // Updated C++ examples. // // Revision 1.0 2003/12/14 19:40:23 charlesr // Initial revision // #ifdef _MSC_VER #pragma warning(disable: 4355) #endif #include "TcpConnection.h" #include "TcpSegment.h" #include "TcpClient.h" #include "TcpServer.h" #include "Eventloop.h" #include <errno.h> #include <string.h> #include <memory.h> #include <fcntl.h> #if !defined(WIN32) #include <unistd.h> #include <netdb.h> # if defined(__sun) #include <sys/systeminfo.h> # endif #endif #ifdef _MSC_VER // Get rid of an annoying build warning. #pragma warning(disable: 4355) #endif using namespace std; #if defined(WIN32) typedef int socklen_t; #endif // External variable declarations. extern Eventloop *Gevent_loop; // Const member declarations. const unsigned long TcpConnection::ISN = 1415531521; const int TcpConnection::MIN_TIMEOUT = 1; const int TcpConnection::ACK_TIMEOUT = 2000; const int TcpConnection::CLOSE_TIMEOUT = 5000; const int TcpConnection::BUFFER_BLOCK_SIZE = 4096; // Const declarations. const static int MSG_READ = 0; const static int NO_SEND_FLAGS = 0; const static long MAX_HOSTNAME_LEN = 257; const static unsigned long LOCAL_HOST_ADDRESS = 0x7f000001; #if defined(WIN32) const static unsigned short MIN_PORT = 1024; const static unsigned short MAX_PORT = 5000; #endif // External routine declarations. char* winsock_strerror(int); //--------------------------------------------------------------- // getFarAddress() const (Public) // Return the far-end's 4-byte IP address. // unsigned long TcpConnection::getFarAddress() const { return (_farAddress.sin_addr.s_addr); } // end of TcpConnection::getFarAddress() const //--------------------------------------------------------------- // getFarPort() const (Public) // Return the far-end's TCP port. // unsigned short TcpConnection::getFarPort() const { return (_farAddress.sin_port); } // end of TcpConnection::getFarPort() const //--------------------------------------------------------------- // getSequenceNumber() const (Public) // Return the current sequence number. // unsigned long TcpConnection::getSequenceNumber() const { return (_sequence_number); } // end of TcpConnection::getSequenceNumber() const //--------------------------------------------------------------- // transmit(const unsigned char*, int, int) (Public) // Transmit data to the far side. // void TcpConnection::transmit(const char *data, int offset, int size) { #ifdef CRTP Transmit(data, offset, size); #else _fsm.Transmit(data, offset, size); #endif return; } // end of TcpConnection::transmit(const unsigned char*, int, int) //--------------------------------------------------------------- // doClose() (Public) // Start closing this connection. // void TcpConnection::doClose() { #ifdef CRTP Close(); #else _fsm.Close(); #endif return; } // end of TcpConnection::doClose() //--------------------------------------------------------------- // setListener(TcpConnectionListener&) (Public) // Set the connection's listener to a new object. // void TcpConnection::setListener(TcpConnectionListener& listener) { _listener = &listener; return; } // end of TcpConnection::setListener(TcpConnectionListener&) //--------------------------------------------------------------- // handleReceive(int) (Public) // Process incoming data. // void TcpConnection::handleReceive(int) { sockaddr sourceAddress; TcpSegment *segment; socklen_t addressSize; int flags, done, errorFlag, bytesRead, totalBytesRead; // Read in the segment. Since the data may exceed the buffer // size, keep expanding the buffer until all the data is // read. for (done = 0, bytesRead = 0, totalBytesRead = 0, errorFlag = 0; done == 0; totalBytesRead += bytesRead) { // Be certain to offset properly into the input buffer. addressSize = sizeof(sourceAddress); bytesRead = recvfrom(_udp_socket, (_buffer + totalBytesRead), _bufferSize, MSG_READ, &sourceAddress, &addressSize); #if defined(WIN32) if (bytesRead == SOCKET_ERROR) #else if (bytesRead < 0) #endif { done = 1; if (errno != EAGAIN) { cerr << "Receive failure - " << strerror(errno) << "." << endl; errorFlag = 1; } else { bytesRead = 0; } } else if (bytesRead >= 0 && bytesRead < _bufferSize) { done = 1; } else { // The entire buffer was filled with the data. // Expand the buffer and read some more. expandBuffer(); } } if (errorFlag == 0 && bytesRead > 0) { segment = new TcpSegment(reinterpret_cast<sockaddr_in&>(sourceAddress), _nearAddress, _buffer, totalBytesRead); #if defined(FSM_DEBUG) cout << "**** Received segment:" << endl << *segment << endl; #endif // Generate the appropriate transition based on the header // flags. flags = segment->getFlags(); switch(flags) { case TcpSegment::FIN: #ifdef CRTP FIN(*segment); #else _fsm.FIN(*segment); #endif break; case TcpSegment::SYN: #ifdef CRTP SYN(*segment); #else _fsm.SYN(*segment); #endif break; case TcpSegment::RST: #ifdef CRTP RST(*segment); #else _fsm.RST(*segment); #endif break; case TcpSegment::PSH: #ifdef CRTP PSH(*segment); #else _fsm.PSH(*segment); #endif break; case TcpSegment::ACK: #ifdef CRTP ACK(*segment); #else _fsm.ACK(*segment); #endif break; case TcpSegment::URG: #ifdef CRTP URG(*segment); #else _fsm.URG(*segment); #endif break; case TcpSegment::FIN_ACK: #ifdef CRTP FIN_ACK(*segment); #else _fsm.FIN_ACK(*segment); #endif break; case TcpSegment::SYN_ACK: #ifdef CRTP SYN_ACK(*segment); #else _fsm.SYN_ACK(*segment); #endif break; case TcpSegment::RST_ACK: #ifdef CRTP RST_ACK(*segment); #else _fsm.RST_ACK(*segment); #endif break; case TcpSegment::PSH_ACK: #ifdef CRTP PSH_ACK(*segment); #else _fsm.PSH_ACK(*segment); #endif break; default: #ifdef CRTP UNDEF(*segment); #else _fsm.UNDEF(*segment); #endif break; } } return; } // end of TcpConnection::handleReceive(int) //--------------------------------------------------------------- // handleTimeout(const char*) (Public) // Generate the appropriate transition based on the timer's name. // void TcpConnection::handleTimeout(const char *name) { #if defined(FSM_DEBUG) cout << "**** Timer " << name << " has expired." << endl; #endif if (strcmp(name, "ACK_TIMER") == 0) { #ifdef CRTP AckTimeout(); #else _fsm.AckTimeout(); #endif } else if (strcmp(name, "CONN_ACK_TIMER") == 0) { #ifdef CRTP ConnAckTimeout(); #else _fsm.ConnAckTimeout(); #endif } else if (strcmp(name, "TRANS_ACK_TIMER") == 0) { #ifdef CRTP TransAckTimeout(); #else _fsm.TransAckTimeout(); #endif } else if (strcmp(name, "CLOSE_ACK_TIMER") == 0) { #ifdef CRTP CloseAckTimeout(); #else _fsm.CloseAckTimeout(); #endif } else if (strcmp(name, "CLOSE_TIMER") == 0) { #ifdef CRTP CloseTimeout(); #else _fsm.CloseTimeout(); #endif } else if (strcmp(name, "SERVER_OPENED") == 0) { #ifdef CRTP ServerOpened(); #else _fsm.ServerOpened(); #endif } else if (strcmp(name, "CLIENT_OPENED") == 0) { #ifdef CRTP ClientOpened(&_farAddress); #else _fsm.ClientOpened(&_farAddress); #endif } else if (strcmp(name, "OPEN_FAILED") == 0) { #ifdef CRTP OpenFailed(_errorMessage); #else _fsm.OpenFailed(_errorMessage); #endif if (_errorMessage != NULL) { delete[] _errorMessage; _errorMessage = NULL; } } return; } // end of TcpConnection::handleTimeout(const char*) //--------------------------------------------------------------- // openServerSocket(unsigned short) (Public) // Open a server socket on the specified port. // void TcpConnection::openServerSocket(unsigned short port) { #if defined(WIN32) unsigned long blockingFlag = 1; HANDLE newHandle; #endif // Set up this server's address. (void) memset(&_nearAddress, 0, sizeof(_nearAddress)); _nearAddress.sin_family = AF_INET; _nearAddress.sin_port = port; _nearAddress.sin_addr.s_addr = INADDR_ANY; // Tell the UDP socket to route data bound for port to this // object. #if defined(WIN32) if ((_udp_win_socket = socket(AF_INET, SOCK_DGRAM, 0)) == INVALID_SOCKET || DuplicateHandle(GetCurrentProcess(), (HANDLE) _udp_win_socket, GetCurrentProcess(), &newHandle, 0, FALSE, DUPLICATE_SAME_ACCESS) == FALSE || bind((unsigned int) newHandle, reinterpret_cast<sockaddr*>(&_nearAddress), sizeof(_nearAddress)) == SOCKET_ERROR) #else if ((_udp_socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0 || bind(_udp_socket, reinterpret_cast<sockaddr*>(&_nearAddress), sizeof(_nearAddress)) < 0) #endif { char *error; // Use timer to report this event asynchronously. // Store away error message. if (_errorMessage != NULL) { delete[] _errorMessage; _errorMessage = NULL; } #if defined(WIN32) error = winsock_strerror(WSAGetLastError()); #else error = strerror(errno); #endif _errorMessage = new char[strlen(error) + 1]; (void) strcpy(_errorMessage, error); Gevent_loop->startTimer("OPEN_FAILED", MIN_TIMEOUT, *this); } else { // Get the UDP socket's address. _nearAddress.sin_family = AF_INET; _nearAddress.sin_addr.s_addr = getLocalAddress(); // Set the socket to non-blocking and register it with // the event loop. #if defined(WIN32) _udp_socket = (unsigned int) newHandle; (void) ioctlsocket(_udp_socket, FIONBIO, &blockingFlag); #else (void) fcntl(_udp_socket, F_SETFL, O_NDELAY); #endif Gevent_loop->addFD(_udp_socket, *this); Gevent_loop->startTimer("SERVER_OPENED", MIN_TIMEOUT, *this); } return; } // end of TcpConnection::openServerSocket(int) //--------------------------------------------------------------- // openClientSocket(const sockaddr_in*) (Public) // Connect to the specified address. // void TcpConnection::openClientSocket(const sockaddr_in *address) { #if defined(WIN32) unsigned long blockingFlag = 1; HANDLE newHandle; int new_port; #endif // Set up this client's address. (void) memset(&_nearAddress, 0, sizeof(_nearAddress)); _nearAddress.sin_family = AF_INET; _nearAddress.sin_port = 0; _nearAddress.sin_addr.s_addr = INADDR_ANY; #if defined(WIN32) if ((_udp_win_socket = socket(AF_INET, SOCK_DGRAM, 0)) == INVALID_SOCKET || DuplicateHandle(GetCurrentProcess(), (HANDLE) _udp_win_socket, GetCurrentProcess(), &newHandle, 0, FALSE, DUPLICATE_SAME_ACCESS) == FALSE || (new_port = doBind((int) newHandle)) < 0) #else if ((_udp_socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0 || bind(_udp_socket, reinterpret_cast<sockaddr*>(&_nearAddress), sizeof(_nearAddress)) < 0) #endif { char *error; // Use timer to report this event asynchronously. // Store away error message. if (_errorMessage != NULL) { delete[] _errorMessage; _errorMessage = NULL; } #if defined(WIN32) error = winsock_strerror(WSAGetLastError()); #else error = strerror(errno); #endif _errorMessage = new char[strlen(error) + 1]; (void) strcpy(_errorMessage, error); Gevent_loop->startTimer("OPEN_FAILED", MIN_TIMEOUT, *this); } else { // Get the UDP socket's address. _nearAddress.sin_family = AF_INET; #if defined(WIN32) _nearAddress.sin_port = (unsigned short) new_port; #else _nearAddress.sin_port = getLocalPort(_udp_socket); #endif _nearAddress.sin_addr.s_addr = getLocalAddress(); // Set the socket to non-blocking and register it with // the event loop. #if defined(WIN32) _udp_socket = (unsigned int) newHandle; (void) ioctlsocket(_udp_socket, FIONBIO, &blockingFlag); #else (void) fcntl(_udp_socket, F_SETFL, O_NDELAY); #endif Gevent_loop->addFD(_udp_socket, *this); // Save the far-end address for later use. (void) memcpy(&_farAddress, address, sizeof(_farAddress)); _sequence_number = ISN; Gevent_loop->startTimer("CLIENT_OPENED", MIN_TIMEOUT, *this); } return; } // end of TcpConnection::openClientSocket(const sockaddr_in*) //--------------------------------------------------------------- // openSuccess() (Public) // The socket has been successfully opened. // void TcpConnection::openSuccess() { _listener->opened(*this); return; } // end of TcpConnection::openSuccess() //--------------------------------------------------------------- // openFailed(const char*) (Public) // The socket could not be opened. // void TcpConnection::openFailed(const char *reason) { _listener->openFailed(reason, *this); return; } // end of TcpConnection::openFailed(const char*) //--------------------------------------------------------------- // closeSocket() (Public) // Finish closing the socket. // void TcpConnection::closeSocket() { if (_udp_socket >= 0) { // Remove this UDP socket from the event loop. Gevent_loop->removeFD(_udp_socket); // Now close the UDP socket. #if defined(WIN32) CloseHandle((HANDLE) _udp_socket); closesocket(_udp_win_socket); _udp_win_socket = NULL; #else close(_udp_socket); #endif _udp_socket = -1; } return; } // end of TcpConnection::closeSocket() //--------------------------------------------------------------- // halfClosed() (Public) // The far end client socket has closed its half of the // connection. // void TcpConnection::halfClosed() { _listener->halfClosed(*this); return; } // end of TcpConnection::halfClosed() //--------------------------------------------------------------- // closed(const char*) (Public) // The connection is completely closed. // void TcpConnection::closed(const char *reason) { TcpConnectionListener *listener; if (_listener != NULL) { listener = _listener; _listener = NULL; listener->closed(reason, *this); } return; } // end of TcpConnection::closed(const char*) //--------------------------------------------------------------- // clearListener() (Public) // Clear this connection's current listener. // void TcpConnection::clearListener() { _listener = NULL; return; } // end of TcpConnection::clearListener() //--------------------------------------------------------------- // transmitted() (Public) // Data transmission successfully completed. // void TcpConnection::transmitted() { _listener->transmitted(*this); return; } // end of TcpConnection::transmitted() //--------------------------------------------------------------- // transmitFailed(const char*) (Public) // Data transmission failed. // void TcpConnection::transmitFailed(const char *reason) { _listener->transmitFailed(reason, *this); return; } // end of TcpConnection::transmitFailed(const char*) //--------------------------------------------------------------- // receive(const TcpSegment&) (Public) // Send received data to the listener. // void TcpConnection::receive(const TcpSegment& segment) { if (_listener != NULL) { _listener->receive(segment.getData(), segment.getDataSize(), *this); } return; } // end of TcpConnection::receive(const TcpSegment&) //--------------------------------------------------------------- // sendOpenSyn(const sockaddr_in*) (Public) // Send the opening SYN message which requests connection to a // service. // void TcpConnection::sendOpenSyn(const sockaddr_in *address) { TcpSegment segment(*address, _nearAddress, 0, 0, TcpSegment::SYN, NULL, 0, 0); doSend(TcpSegment::SYN, NULL, 0, 0, &segment); return; } // end of TcpConnection::sendOpenSyn(const sockaddr_in*) //--------------------------------------------------------------- // accept(const TcpSegment&) (Public) // Create a client socket to handle the new connection. // void TcpConnection::accept(const TcpSegment& segment) { TcpClient *accept_client; int new_socket; #if defined(WIN32) unsigned long blockingFlag = 1; HANDLE newHandle; int new_port; #else sockaddr_in clientAddress; #endif // Create a new UDP socket to handle this connection. // Let it be assigned a random UDP port. #if defined(WIN32) newHandle = NULL; if ((new_socket = socket(AF_INET, SOCK_DGRAM, 0)) == INVALID_SOCKET || DuplicateHandle(GetCurrentProcess(), (HANDLE) new_socket, GetCurrentProcess(), &newHandle, 0, FALSE, DUPLICATE_SAME_ACCESS) == FALSE || (new_port = doBind((int) newHandle)) < 0) { // If an error occurs now, ignore it. if (new_socket != INVALID_SOCKET) { closesocket(new_socket); } if (newHandle != NULL) { CloseHandle((HANDLE) newHandle); } } else { // Set the socket to non-blocking. (void) ioctlsocket( (unsigned int) newHandle, FIONBIO, &blockingFlag); // Have the new client socket use this server // socket's near address for now. accept_client = new TcpClient(segment.getSource(), _nearAddress, (unsigned short) new_port, new_socket, newHandle, _sequence_number, (TcpServer&) *this, *_listener); #else // Set up this client's address. (void) memset(&clientAddress, 0, sizeof(clientAddress)); clientAddress.sin_family = AF_INET; clientAddress.sin_port = 0; clientAddress.sin_addr.s_addr = INADDR_ANY; if ((new_socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0 || bind(new_socket, reinterpret_cast<sockaddr*>(&clientAddress), sizeof(clientAddress)) < 0) { // If an error occurs now, ignore it. if (new_socket >= 0) { close(new_socket); } } else { // Set the socket to non-blocking. (void) fcntl(new_socket, F_SETFL, O_NDELAY); // Have the new client socket use this server // socket's near address for now. accept_client = new TcpClient(segment.getSource(), _nearAddress, new_socket, _sequence_number, (TcpServer&) *this, *_listener); #endif accept_client->acceptOpen(segment); } return; } // end of TcpConnection::accept(const TcpSegment&) //--------------------------------------------------------------- // accepted() (Public) // Connection completely accepted. // void TcpConnection::accepted() { TcpServer *server = _server; TcpConnectionListener *listener = _listener; // Tell the server listener that a new connection has // been accepted. Then clear the server listener because // this socket is now truly a client socket. Clear the // listener member data now because the callback method // will be resetting it and the reset will fail if we // don't do it. _server = NULL; _listener = NULL; listener->accepted((TcpClient&) *this, *server); return; } // end of TcpConnection::accepted() //--------------------------------------------------------------- // sendSynAck(const TcpSegment&) (Public) // Acknowledge a SYN message. // void TcpConnection::sendSynAck(const TcpSegment& segment) { unsigned short port; char port_bytes[2]; // Tell the far end client socket with what port it should // now communicate. #if defined(WIN32) port = _actualPort; #else port = getLocalPort(_udp_socket); #endif port_bytes[0] = (char) (port & 0x00ff); port_bytes[1] = (char) ((port & 0xff00) >> 8); doSend(TcpSegment::SYN_ACK, port_bytes, 0, 2, &segment); return; } // end of TcpConnection::sendSynAck(const TcpSegment&) //--------------------------------------------------------------- // sendSynAckAck(const TcpSegment&) (Public) // Acknowledge the service's acknowledge. Need to do this so // doSend() will use the correct address. // void TcpConnection::sendSynAckAck(const TcpSegment& segment) { TcpSegment faux_segment(_farAddress, _nearAddress, segment.getSequenceNumber(), segment.getAcknowledgeNumber(), segment.getFlags(), NULL, 0, 0); doSend(TcpSegment::ACK, NULL, 0, 0, &faux_segment); return; } // end of TcpConnection::sendSynAckAck(const TcpSegment&) //--------------------------------------------------------------- // doSend(...) (Public) // Send data to the specified address. // void TcpConnection::doSend(unsigned short flags, const char *data, int offset, int size, const TcpSegment *recv_segment) { sockaddr_in to_address; unsigned long ack_number; TcpSegment *send_segment; char *packet; int packet_size; (void) memset(&to_address, 0, sizeof(to_address)); // First, use the received segment. // Else, use the connection's far end. if (recv_segment != NULL) { (void) memcpy(&to_address, &(recv_segment->getSource()), sizeof(to_address)); } // If the address was not specified, then send this segment // to whatever client socket we are currently speaking. else { (void) memcpy(&to_address, &_farAddress, sizeof(to_address)); } // Send the ack number only if the ack flag is set. if ((flags & TcpSegment::ACK) == 0 || recv_segment == NULL) { ack_number = 0; } else { // Figure out the ack number based on the received // segment's sequence number and data size. ack_number = getAck(*recv_segment); } send_segment = new TcpSegment(_nearAddress, to_address, _sequence_number, ack_number, flags, data, offset, size); // Advance the sequence number depending on the message sent. // Don't do this if the message came from an interloper. if (recv_segment == NULL || ((recv_segment->getSource()).sin_port == _farAddress.sin_port && (recv_segment->getSource()).sin_addr.s_addr == _farAddress.sin_addr.s_addr)) { _sequence_number = getAck(*send_segment); } // Now send the data. First convert the TCP segment into a // sequence of raw bytes. send_segment->packetize(packet, packet_size); if (packet != NULL && packet_size > 0) { #if defined(FSM_DEBUG) cout << "**** Transmit segment:\n" << *send_segment << endl; #endif #if defined(WIN32) if (sendto(_udp_socket, packet, packet_size, NO_SEND_FLAGS, reinterpret_cast<sockaddr *>(&to_address), sizeof(to_address)) == SOCKET_ERROR) #else if (sendto(_udp_socket, packet, packet_size, NO_SEND_FLAGS, reinterpret_cast<sockaddr *>(&to_address), sizeof(to_address)) < 0) #endif { cerr << "Transmit failed - " << strerror(errno) << "." << endl; } // Free up the allocated packet. delete[] packet; } delete send_segment; return; } // end of TcpConnection::doSend(...) //--------------------------------------------------------------- // startTimer(const char*, long) (Public) // Start the named timer running. // void TcpConnection::startTimer(const char *name, long duration) { #if defined(FSM_DEBUG) cout << "**** Starting timer " << name << ", duration: " << duration << " milliseconds." << endl; #endif Gevent_loop->startTimer(name, duration, *this); return; } // end of TcpConnection::startTimer(const char*, long) //--------------------------------------------------------------- // stopTimer(const char*) (Public) // Stop the named timer. // void TcpConnection::stopTimer(const char* name) { #if defined(FSM_DEBUG) cout << "**** Stopping timer " << name << "." << endl; #endif Gevent_loop->stopTimer(name, *this); return; } // end of TcpConnection::stopTimer(const char*) //--------------------------------------------------------------- // setNearAddress() (Public) // Figure out this socket's port and address based on the socket. // void TcpConnection::setNearAddress() { // Get the UDP socket's address. _nearAddress.sin_port = AF_INET; #if defined(WIN32) _nearAddress.sin_port = _actualPort; #else _nearAddress.sin_port = getLocalPort(_udp_socket); #endif _nearAddress.sin_addr.s_addr = getLocalAddress(); return; } // end of TcpConnection::setNearAddress() //--------------------------------------------------------------- // setFarAddress(const TcpSegment&) (Public) // Send data to a new client port instead of the server port. // void TcpConnection::setFarAddress(const TcpSegment& segment) { const char *data = segment.getData(); unsigned short port; _farAddress.sin_family = AF_INET; port = ((((unsigned short) data[0]) & 0x00ff) | ((((unsigned short) data[1]) & 0x00ff) << 8)); _farAddress.sin_port = port; _farAddress.sin_addr.s_addr = segment.getSource().sin_addr.s_addr; return; } // end of TcpConnection::setFarAddress(const TcpSegment&) //--------------------------------------------------------------- // deleteSegment(const TcpSegment&) (Public) // Delete a segment object. // void TcpConnection::deleteSegment(const TcpSegment& segment) { delete const_cast<TcpSegment*>(&segment); return; } // end of TcpConnection::deleteSegment(const TcpSegment&) //--------------------------------------------------------------- // TcpConnection(TcpConnectionListener&) (Protected) // Create a server socket. // TcpConnection::TcpConnection(TcpConnectionListener& listener) : _listener(&listener), #if defined(WIN32) _actualPort(0), _udp_win_socket(NULL), #endif _udp_socket(-1), _sequence_number(ISN), _buffer(NULL), _bufferSize(0), _server(NULL), _errorMessage(NULL) #ifdef CRTP #else , _fsm(*this) #endif { (void) memset(&_nearAddress, 0, sizeof(_nearAddress)); (void) memset(&_farAddress, 0, sizeof(_farAddress)); expandBuffer(); #if defined(FSM_DEBUG) // Turn on state map debug printout. #ifdef CRTP setDebugFlag(true); #else _fsm.setDebugFlag(true); #endif #endif return; } // end of TcpConnection::TcpConnection(TcpConnectionListener&) //--------------------------------------------------------------- // TcpConnection(const sockaddr_in&, ...) (Protected) // "Accepted" client connection. // TcpConnection::TcpConnection(const sockaddr_in& far_address, const sockaddr_in& near_address, #if defined(WIN32) unsigned short actual_port, SOCKET udp_socket, HANDLE udp_handle, #else int udp_socket, #endif int sequence_number, TcpServer& server, TcpConnectionListener& listener) : _listener(&listener), #if defined(WIN32) _actualPort(actual_port), _udp_win_socket(udp_socket), _udp_socket((unsigned int) udp_handle), #else _udp_socket(udp_socket), #endif _sequence_number(sequence_number), _buffer(NULL), _bufferSize(0), _server(&server), _errorMessage(NULL) #ifdef CRTP #else , _fsm(*this) #endif { // Register the UDP socket with the event loop. Gevent_loop->addFD(_udp_socket, *this); (void) memcpy(&_nearAddress, &near_address, sizeof(_nearAddress)); (void) memcpy(&_farAddress, &far_address, sizeof(_farAddress)); // Set up the input buffer. expandBuffer(); #if defined(FSM_DEBUG) // Turn on state map debug printout. #ifdef CRTP setDebugFlag(true); #else _fsm.setDebugFlag(true); #endif #endif return; } // end of TcpConnection::TcpConnection(...) //--------------------------------------------------------------- // ~TcpConnection() (Protected) // Destructor. // TcpConnection::~TcpConnection() { if (_buffer != NULL) { delete[] _buffer; _buffer = NULL; _bufferSize = 0; } if (_errorMessage != NULL) { delete[] _errorMessage; _errorMessage = NULL; } // Just in case ... closeSocket(); return; } // end of TcpConnection::~TcpConnection() //--------------------------------------------------------------- // passiveOpen(unsigned short) (Protected) // Open a server socket. // void TcpConnection::passiveOpen(unsigned short port) { #ifdef CRTP PassiveOpen(port); #else _fsm.PassiveOpen(port); #endif return; } // end of TcpConnection::passiveOpen(unsigned short) //--------------------------------------------------------------- // activeOpen(const sockaddr_in&) (Protected) // Open a client socket. // void TcpConnection::activeOpen(const sockaddr_in& address) { #ifdef CRTP ActiveOpen(&address); #else _fsm.ActiveOpen(&address); #endif return; } // end of TcpConnection::activeOpen(const sockaddr_in&) //--------------------------------------------------------------- // acceptOpen(const TcpSegment&) (Protected) // "Open" an accepted client connection. // void TcpConnection::acceptOpen(const TcpSegment& segment) { #ifdef CRTP AcceptOpen(segment); #else _fsm.AcceptOpen(segment); #endif return; } // end of TcpConnection::acceptOpen(const TcpSegment&) //--------------------------------------------------------------- // expandBuffer() (Private) // Expand the buffer's current size by one block. // void TcpConnection::expandBuffer() { char *newBuffer; int newSize, currBlocks; currBlocks = _bufferSize / BUFFER_BLOCK_SIZE; newSize = (currBlocks + 1) * BUFFER_BLOCK_SIZE; newBuffer = new char[newSize]; // If the current buffer has data in it, copy it over to the // new buffer before deleting the current buffer. if (_buffer != NULL) { (void) memcpy(newBuffer, _buffer, _bufferSize); delete[] _buffer; } _buffer = newBuffer; _bufferSize = newSize; return; } // end of TcpConnection::expandBuffer() #if defined(WIN32) //--------------------------------------------------------------- // doBind(int) const (Private) // Bind this UDP socket to a random, available port number. // int TcpConnection::doBind(int handle) const { sockaddr_in address; unsigned short portIt; int socket_error, retval; // Set up this client's address. (void) memset(&address, 0, sizeof(address)); address.sin_family = AF_INET; address.sin_port = 0; address.sin_addr.s_addr = INADDR_ANY; // Start at the largest number and work down. for (portIt = MIN_PORT; portIt <= MAX_PORT; ++portIt) { address.sin_port = htons(portIt); if (bind(handle, (sockaddr *) &address, sizeof(sockaddr_in)) == SOCKET_ERROR) { socket_error = WSAGetLastError(); if (socket_error != WSAEADDRINUSE && socket_error != WSAEADDRNOTAVAIL) { retval = -1; break; } } else { // The bind worked. Return the port number. retval = address.sin_port; break; } } return(retval); } // end of TcpConnection::doBind(int) const #else //--------------------------------------------------------------- // getLocalPort(int) const (Private) // Figure out the UDP socket's port number. // unsigned short TcpConnection::getLocalPort(int fd) const { socklen_t size; sockaddr_in address; unsigned short retval; size = sizeof(address); if (getsockname(fd, reinterpret_cast<sockaddr *>(&address), &size) < 0) { retval = 0xffff; } else { retval = address.sin_port; } return(retval); } // end of TcpConnection::getLocalPort(int) const #endif //--------------------------------------------------------------- // getLocalAddress() const (Private) // Return this machine's local internet address. Do this by // first retrieving the hostname and then doing gethostbyname() // on itself. // unsigned long TcpConnection::getLocalAddress() const { char hostname[MAX_HOSTNAME_LEN]; hostent *hostEntry; unsigned long retval; // 1. Get this machine's network host name. #if defined(__sun) (void) sysinfo(SI_HOSTNAME, hostname, MAX_HOSTNAME_LEN); #else (void) gethostname(hostname, MAX_HOSTNAME_LEN); #endif // 2. Get this host name's address. if ((hostEntry = gethostbyname(hostname)) != NULL) { (void) memcpy(&retval, hostEntry->h_addr, hostEntry->h_length); } else { // If there is no known address for this host name, // default to 127.0.0.1. retval = LOCAL_HOST_ADDRESS; } return(retval); } // end of TcpConnection::getLocalAddress() const //--------------------------------------------------------------- // getAck(const TcpSegment&) (Private) // Figure out what the acknowledgement number should be based on // the TCP segment's type and size. // int TcpConnection::getAck(const TcpSegment& segment) { int retval; // The ack # depends on the segment's flags. switch (segment.getFlags()) { case TcpSegment::FIN: case TcpSegment::SYN: case TcpSegment::FIN_ACK: case TcpSegment::SYN_ACK: retval = segment.getSequenceNumber() + 1; break; case TcpSegment::PSH: case TcpSegment::PSH_ACK: retval = segment.getSequenceNumber() + segment.getDataSize(); break; case TcpSegment::ACK: default: retval = segment.getSequenceNumber(); break; } return(retval); } // end of TcpConnection::getAck(const TcpSegment&)
27.258922
85
0.550535
[ "object" ]
bf17a0b1e43908a9fa08935fa51d8478d8de324c
3,741
cpp
C++
libraries/networking/src/SandboxUtils.cpp
trentpolack/hifi
3b8636b75c3df242c0aeecbca6e01f386e238f45
[ "Apache-2.0" ]
1
2020-10-26T22:28:42.000Z
2020-10-26T22:28:42.000Z
libraries/networking/src/SandboxUtils.cpp
trentpolack/hifi
3b8636b75c3df242c0aeecbca6e01f386e238f45
[ "Apache-2.0" ]
null
null
null
libraries/networking/src/SandboxUtils.cpp
trentpolack/hifi
3b8636b75c3df242c0aeecbca6e01f386e238f45
[ "Apache-2.0" ]
1
2019-07-05T08:39:35.000Z
2019-07-05T08:39:35.000Z
// // SandboxUtils.cpp // libraries/networking/src // // Created by Brad Hefta-Gaub on 2016-10-15. // Copyright 2016 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include <QDataStream> #include <QDebug> #include <QFile> #include <QFileInfo> #include <QJsonDocument> #include <QJsonObject> #include <QNetworkReply> #include <QProcess> #include <QStandardPaths> #include <QThread> #include <QTimer> #include <NumericalConstants.h> #include <SharedUtil.h> #include <RunningMarker.h> #include "SandboxUtils.h" #include "NetworkAccessManager.h" #include "NetworkLogging.h" void SandboxUtils::ifLocalSandboxRunningElse(std::function<void()> localSandboxRunningDoThis, std::function<void()> localSandboxNotRunningDoThat) { QNetworkAccessManager& networkAccessManager = NetworkAccessManager::getInstance(); QNetworkRequest sandboxStatus(SANDBOX_STATUS_URL); sandboxStatus.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true); sandboxStatus.setHeader(QNetworkRequest::UserAgentHeader, HIGH_FIDELITY_USER_AGENT); QNetworkReply* reply = networkAccessManager.get(sandboxStatus); connect(reply, &QNetworkReply::finished, this, [reply, localSandboxRunningDoThis, localSandboxNotRunningDoThat]() { if (reply->error() == QNetworkReply::NoError) { auto statusData = reply->readAll(); auto statusJson = QJsonDocument::fromJson(statusData); if (!statusJson.isEmpty()) { auto statusObject = statusJson.object(); auto serversValue = statusObject.value("servers"); if (!serversValue.isUndefined() && serversValue.isObject()) { auto serversObject = serversValue.toObject(); auto serversCount = serversObject.size(); const int MINIMUM_EXPECTED_SERVER_COUNT = 5; if (serversCount >= MINIMUM_EXPECTED_SERVER_COUNT) { localSandboxRunningDoThis(); return; } } } } localSandboxNotRunningDoThat(); }); } void SandboxUtils::runLocalSandbox(QString contentPath, bool autoShutdown, QString runningMarkerName, bool noUpdater) { QString applicationDirPath = QFileInfo(QCoreApplication::applicationFilePath()).path(); QString serverPath = applicationDirPath + "/server-console/server-console.exe"; qCDebug(networking) << "Application dir path is: " << applicationDirPath; qCDebug(networking) << "Server path is: " << serverPath; qCDebug(networking) << "autoShutdown: " << autoShutdown; qCDebug(networking) << "noUpdater: " << noUpdater; bool hasContentPath = !contentPath.isEmpty(); bool passArgs = autoShutdown || hasContentPath || noUpdater; QStringList args; if (passArgs) { args << "--"; } if (hasContentPath) { QString serverContentPath = applicationDirPath + "/" + contentPath; args << "--contentPath" << serverContentPath; } if (autoShutdown) { QString interfaceRunningStateFile = RunningMarker::getMarkerFilePath(runningMarkerName); args << "--shutdownWatcher" << interfaceRunningStateFile; } if (noUpdater) { args << "--noUpdater"; } qCDebug(networking) << applicationDirPath; qCDebug(networking) << "Launching sandbox with:" << args; qCDebug(networking) << QProcess::startDetached(serverPath, args); // Sleep a short amount of time to give the server a chance to start usleep(2000000); /// do we really need this?? }
36.320388
119
0.668003
[ "object" ]
bf28daf60a60cc7d9e515beadbac5481b83bea71
22,390
cpp
C++
src/compatibility.cpp
351ELEC/lzdoom
2ee3ea91bc9c052b3143f44c96d85df22851426f
[ "RSA-MD" ]
2
2020-04-19T13:37:34.000Z
2021-06-09T04:26:25.000Z
src/compatibility.cpp
351ELEC/lzdoom
2ee3ea91bc9c052b3143f44c96d85df22851426f
[ "RSA-MD" ]
4
2021-09-02T00:05:17.000Z
2021-09-07T14:56:12.000Z
src/compatibility.cpp
351ELEC/lzdoom
2ee3ea91bc9c052b3143f44c96d85df22851426f
[ "RSA-MD" ]
1
2021-09-28T19:03:39.000Z
2021-09-28T19:03:39.000Z
/* ** compatibility.cpp ** Handles compatibility flags for maps that are unlikely to be updated. ** **--------------------------------------------------------------------------- ** Copyright 2009 Randy Heit ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions ** are met: ** ** 1. Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** 2. Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in the ** documentation and/or other materials provided with the distribution. ** 3. The name of the author may not be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. **--------------------------------------------------------------------------- ** ** This file is for maps that have been rendered broken by bug fixes or other ** changes that seemed minor at the time, and it is unlikely that the maps ** will be changed. If you are making a map and you know it needs a ** compatibility option to play properly, you are advised to specify so with ** a MAPINFO. */ // HEADER FILES ------------------------------------------------------------ #include "compatibility.h" #include "sc_man.h" #include "cmdlib.h" #include "doomdef.h" #include "doomdata.h" #include "doomstat.h" #include "c_dispatch.h" #include "gi.h" #include "g_level.h" #include "p_lnspec.h" #include "p_tags.h" #include "r_state.h" #include "w_wad.h" #include "textures.h" #include "g_levellocals.h" #include "vm.h" #include "actor.h" #include "types.h" // MACROS ------------------------------------------------------------------ // TYPES ------------------------------------------------------------------- struct FCompatOption { const char *Name; uint32_t CompatFlags; int WhichSlot; }; enum { SLOT_COMPAT, SLOT_COMPAT2, SLOT_BCOMPAT }; enum { CP_END, CP_CLEARFLAGS, CP_SETFLAGS, CP_SETSPECIAL, CP_CLEARSPECIAL, CP_SETACTIVATION, CP_SETSECTOROFFSET, CP_SETSECTORSPECIAL, CP_SETWALLYSCALE, CP_SETWALLTEXTURE, CP_SETTHINGZ, CP_SETTAG, CP_SETTHINGFLAGS, CP_SETVERTEX, CP_SETTHINGSKILLS, CP_SETSECTORTEXTURE, CP_SETSECTORLIGHT, CP_SETLINESECTORREF, }; // EXTERNAL FUNCTION PROTOTYPES -------------------------------------------- // PUBLIC FUNCTION PROTOTYPES ---------------------------------------------- // PRIVATE FUNCTION PROTOTYPES --------------------------------------------- // EXTERNAL DATA DECLARATIONS ---------------------------------------------- extern TArray<FMapThing> MapThingsConverted; extern bool ForceNodeBuild; // PUBLIC DATA DEFINITIONS ------------------------------------------------- TMap<FMD5Holder, FCompatValues, FMD5HashTraits> BCompatMap; CVAR (Bool, sv_njnoautolevelcompat, false, CVAR_SERVERINFO | CVAR_LATCH) // PRIVATE DATA DEFINITIONS ------------------------------------------------ static FCompatOption Options[] = { { "setslopeoverflow", BCOMPATF_SETSLOPEOVERFLOW, SLOT_BCOMPAT }, { "resetplayerspeed", BCOMPATF_RESETPLAYERSPEED, SLOT_BCOMPAT }, { "vileghosts", BCOMPATF_VILEGHOSTS, SLOT_BCOMPAT }, { "ignoreteleporttags", BCOMPATF_BADTELEPORTERS, SLOT_BCOMPAT }, { "rebuildnodes", BCOMPATF_REBUILDNODES, SLOT_BCOMPAT }, { "linkfrozenprops", BCOMPATF_LINKFROZENPROPS, SLOT_BCOMPAT }, { "floatbob", BCOMPATF_FLOATBOB, SLOT_BCOMPAT }, { "noslopeid", BCOMPATF_NOSLOPEID, SLOT_BCOMPAT }, { "clipmidtex", BCOMPATF_CLIPMIDTEX, SLOT_BCOMPAT }, // list copied from g_mapinfo.cpp { "shorttex", COMPATF_SHORTTEX, SLOT_COMPAT }, { "stairs", COMPATF_STAIRINDEX, SLOT_COMPAT }, { "limitpain", COMPATF_LIMITPAIN, SLOT_COMPAT }, { "nopassover", COMPATF_NO_PASSMOBJ, SLOT_COMPAT }, { "notossdrops", COMPATF_NOTOSSDROPS, SLOT_COMPAT }, { "useblocking", COMPATF_USEBLOCKING, SLOT_COMPAT }, { "nodoorlight", COMPATF_NODOORLIGHT, SLOT_COMPAT }, { "ravenscroll", COMPATF_RAVENSCROLL, SLOT_COMPAT }, { "soundtarget", COMPATF_SOUNDTARGET, SLOT_COMPAT }, { "dehhealth", COMPATF_DEHHEALTH, SLOT_COMPAT }, { "trace", COMPATF_TRACE, SLOT_COMPAT }, { "dropoff", COMPATF_DROPOFF, SLOT_COMPAT }, { "boomscroll", COMPATF_BOOMSCROLL, SLOT_COMPAT }, { "invisibility", COMPATF_INVISIBILITY, SLOT_COMPAT }, { "silentinstantfloors", COMPATF_SILENT_INSTANT_FLOORS, SLOT_COMPAT }, { "sectorsounds", COMPATF_SECTORSOUNDS, SLOT_COMPAT }, { "missileclip", COMPATF_MISSILECLIP, SLOT_COMPAT }, { "crossdropoff", COMPATF_CROSSDROPOFF, SLOT_COMPAT }, { "wallrun", COMPATF_WALLRUN, SLOT_COMPAT }, // [GZ] Added for CC MAP29 { "anybossdeath", COMPATF_ANYBOSSDEATH, SLOT_COMPAT },// [GZ] Added for UAC_DEAD { "mushroom", COMPATF_MUSHROOM, SLOT_COMPAT }, { "mbfmonstermove", COMPATF_MBFMONSTERMOVE, SLOT_COMPAT }, { "corpsegibs", COMPATF_CORPSEGIBS, SLOT_COMPAT }, { "noblockfriends", COMPATF_NOBLOCKFRIENDS, SLOT_COMPAT }, { "spritesort", COMPATF_SPRITESORT, SLOT_COMPAT }, { "hitscan", COMPATF_HITSCAN, SLOT_COMPAT }, { "lightlevel", COMPATF_LIGHT, SLOT_COMPAT }, { "polyobj", COMPATF_POLYOBJ, SLOT_COMPAT }, { "maskedmidtex", COMPATF_MASKEDMIDTEX, SLOT_COMPAT }, { "badangles", COMPATF2_BADANGLES, SLOT_COMPAT2 }, { "floormove", COMPATF2_FLOORMOVE, SLOT_COMPAT2 }, { "soundcutoff", COMPATF2_SOUNDCUTOFF, SLOT_COMPAT2 }, { "pointonline", COMPATF2_POINTONLINE, SLOT_COMPAT2 }, { "multiexit", COMPATF2_MULTIEXIT, SLOT_COMPAT2 }, { "teleport", COMPATF2_TELEPORT, SLOT_COMPAT2 }, { "disablepushwindowcheck", COMPATF2_PUSHWINDOW, SLOT_COMPAT2 }, { "checkswitchrange", COMPATF2_CHECKSWITCHRANGE, SLOT_COMPAT2 }, { "explode1", COMPATF2_EXPLODE1, SLOT_COMPAT2 }, { "explode2", COMPATF2_EXPLODE2, SLOT_COMPAT2 }, { "railing", COMPATF2_RAILING, SLOT_COMPAT2 }, { "scriptwait", COMPATF2_SCRIPTWAIT, SLOT_COMPAT2 }, { NULL, 0, 0 } }; static const char *const LineSides[] = { "Front", "Back", NULL }; static const char *const WallTiers[] = { "Top", "Mid", "Bot", NULL }; static const char *const SectorPlanes[] = { "floor", "ceil", NULL }; // CODE -------------------------------------------------------------------- //========================================================================== // // ParseCompatibility // //========================================================================== void ParseCompatibility() { TArray<FMD5Holder> md5array; FMD5Holder md5; FCompatValues flags; int i, x; unsigned int j; BCompatMap.Clear(); // The contents of this file are not cumulative, as it should not // be present in user-distributed maps. FScanner sc(Wads.GetNumForFullName("compatibility.txt")); while (sc.GetString()) // Get MD5 signature { do { if (strlen(sc.String) != 32) { sc.ScriptError("MD5 signature must be exactly 32 characters long"); } for (i = 0; i < 32; ++i) { if (sc.String[i] >= '0' && sc.String[i] <= '9') { x = sc.String[i] - '0'; } else { sc.String[i] |= 'a' ^ 'A'; if (sc.String[i] >= 'a' && sc.String[i] <= 'f') { x = sc.String[i] - 'a' + 10; } else { x = 0; sc.ScriptError("MD5 signature must be a hexadecimal value"); } } if (!(i & 1)) { md5.Bytes[i / 2] = x << 4; } else { md5.Bytes[i / 2] |= x; } } md5array.Push(md5); sc.MustGetString(); } while (!sc.Compare("{")); memset(flags.CompatFlags, 0, sizeof(flags.CompatFlags)); flags.ExtCommandIndex = ~0u; while (sc.GetString()) { if ((i = sc.MatchString(&Options[0].Name, sizeof(*Options))) >= 0) { flags.CompatFlags[Options[i].WhichSlot] |= Options[i].CompatFlags; } else { sc.UnGet(); break; } } sc.MustGetStringName("}"); for (j = 0; j < md5array.Size(); ++j) { BCompatMap[md5array[j]] = flags; } md5array.Clear(); } } //========================================================================== // // CheckCompatibility // //========================================================================== FName CheckCompatibility(MapData *map) { FMD5Holder md5; FCompatValues *flags; ii_compatflags = 0; ii_compatflags2 = 0; ib_compatflags = 0; // When playing Doom IWAD levels force COMPAT_SHORTTEX and COMPATF_LIGHT. // I'm not sure if the IWAD maps actually need COMPATF_LIGHT but it certainly does not hurt. // TNT's MAP31 also needs COMPATF_STAIRINDEX but that only gets activated for TNT.WAD. if (Wads.GetLumpFile(map->lumpnum) == Wads.GetIwadNum() && (gameinfo.flags & GI_COMPATSHORTTEX) && level.maptype == MAPTYPE_DOOM) { ii_compatflags = COMPATF_SHORTTEX|COMPATF_LIGHT; if (gameinfo.flags & GI_COMPATSTAIRS) ii_compatflags |= COMPATF_STAIRINDEX; } map->GetChecksum(md5.Bytes); flags = BCompatMap.CheckKey(md5); FString hash; for (size_t j = 0; j < sizeof(md5.Bytes); ++j) { hash.AppendFormat("%02X", md5.Bytes[j]); } if (developer >= DMSG_NOTIFY) { Printf("MD5 = %s", hash.GetChars()); if (flags != NULL) { Printf(", cflags = %08x, cflags2 = %08x, bflags = %08x\n", flags->CompatFlags[SLOT_COMPAT], flags->CompatFlags[SLOT_COMPAT2], flags->CompatFlags[SLOT_BCOMPAT]); } else { Printf("\n"); } } if (flags != NULL) { ii_compatflags |= flags->CompatFlags[SLOT_COMPAT]; ii_compatflags2 |= flags->CompatFlags[SLOT_COMPAT2]; ib_compatflags |= flags->CompatFlags[SLOT_BCOMPAT]; } // Reset i_compatflags compatflags.Callback(); compatflags2.Callback(); // Set floatbob compatibility for all maps with an original Hexen MAPINFO. if (level.flags2 & LEVEL2_HEXENHACK) { ib_compatflags |= BCOMPATF_FLOATBOB; } return FName(hash, true); // if this returns NAME_None it means there is no scripted compatibility handler. } //========================================================================== // // PostProcessLevel // //========================================================================== class DLevelPostProcessor : public DObject { DECLARE_ABSTRACT_CLASS(DLevelPostProcessor, DObject) }; IMPLEMENT_CLASS(DLevelPostProcessor, true, false); void PostProcessLevel(FName checksum) { auto lc = Create<DLevelPostProcessor>(); if (sv_njnoautolevelcompat) { Printf("Warning: auto level compatibility disabled. Severe problems could arise.\n"); return; } for (auto cls : PClass::AllClasses) { if (cls->IsDescendantOf(RUNTIME_CLASS(DLevelPostProcessor))) { PFunction *const func = dyn_cast<PFunction>(cls->FindSymbol("Apply", false)); if (func == nullptr) { Printf("Missing 'Apply' method in class '%s', level compatibility object ignored\n", cls->TypeName.GetChars()); continue; } auto argTypes = func->Variants[0].Proto->ArgumentTypes; if (argTypes.Size() != 3 || argTypes[1] != TypeName || argTypes[2] != TypeString) { Printf("Wrong signature of 'Apply' method in class '%s', level compatibility object ignored\n", cls->TypeName.GetChars()); continue; } VMValue param[] = { lc, checksum.GetIndex(), &level.MapName }; VMCall(func->Variants[0].Implementation, param, 3, nullptr, 0); } } } DEFINE_ACTION_FUNCTION(DLevelPostProcessor, OffsetSectorPlane) { PARAM_SELF_PROLOGUE(DLevelPostProcessor); PARAM_INT(sector); PARAM_INT(planeval); PARAM_FLOAT(delta); if ((unsigned)sector < level.sectors.Size()) { sector_t *sec = &level.sectors[sector]; secplane_t& plane = sector_t::floor == planeval? sec->floorplane : sec->ceilingplane; plane.ChangeHeight(delta); sec->ChangePlaneTexZ(planeval, delta); } return 0; } DEFINE_ACTION_FUNCTION(DLevelPostProcessor, ClearSectorTags) { PARAM_SELF_PROLOGUE(DLevelPostProcessor); PARAM_INT(sector); tagManager.RemoveSectorTags(sector); return 0; } DEFINE_ACTION_FUNCTION(DLevelPostProcessor, AddSectorTag) { PARAM_SELF_PROLOGUE(DLevelPostProcessor); PARAM_INT(sector); PARAM_INT(tag); if ((unsigned)sector < level.sectors.Size()) { tagManager.AddSectorTag(sector, tag); } return 0; } DEFINE_ACTION_FUNCTION(DLevelPostProcessor, ClearLineIDs) { PARAM_SELF_PROLOGUE(DLevelPostProcessor); PARAM_INT(line); tagManager.RemoveLineIDs(line); return 0; } DEFINE_ACTION_FUNCTION(DLevelPostProcessor, AddLineID) { PARAM_SELF_PROLOGUE(DLevelPostProcessor); PARAM_INT(line); PARAM_INT(tag); if ((unsigned)line < level.lines.Size()) { tagManager.AddLineID(line, tag); } return 0; } DEFINE_ACTION_FUNCTION(DLevelPostProcessor, GetThingCount) { PARAM_SELF_PROLOGUE(DLevelPostProcessor); ACTION_RETURN_INT(MapThingsConverted.Size()); } DEFINE_ACTION_FUNCTION(DLevelPostProcessor, AddThing) { PARAM_SELF_PROLOGUE(DLevelPostProcessor); PARAM_UINT(ednum); PARAM_FLOAT(x); PARAM_FLOAT(y); PARAM_FLOAT(z); PARAM_INT(angle); PARAM_UINT(skills); PARAM_UINT(flags); auto &things = MapThingsConverted; const unsigned newindex = things.Size(); things.Resize(newindex + 1); auto &newthing = things.Last(); memset(&newthing, 0, sizeof newthing); newthing.Gravity = 1; newthing.SkillFilter = skills; newthing.ClassFilter = 0xFFFF; newthing.RenderStyle = STYLE_Count; newthing.Alpha = -1; newthing.Health = 1; newthing.FloatbobPhase = -1; newthing.pos.X = x; newthing.pos.Y = y; newthing.pos.Z = z; newthing.angle = angle; newthing.EdNum = ednum; newthing.info = DoomEdMap.CheckKey(ednum); newthing.flags = flags; ACTION_RETURN_INT(newindex); } DEFINE_ACTION_FUNCTION(DLevelPostProcessor, GetThingEdNum) { PARAM_SELF_PROLOGUE(DLevelPostProcessor); PARAM_UINT(thing); const int ednum = thing < MapThingsConverted.Size() ? MapThingsConverted[thing].EdNum : 0; ACTION_RETURN_INT(ednum); } DEFINE_ACTION_FUNCTION(DLevelPostProcessor, SetThingEdNum) { PARAM_SELF_PROLOGUE(DLevelPostProcessor); PARAM_UINT(thing); PARAM_UINT(ednum); if (thing < MapThingsConverted.Size()) { auto &mti = MapThingsConverted[thing]; mti.EdNum = ednum; mti.info = DoomEdMap.CheckKey(ednum); } return 0; } DEFINE_ACTION_FUNCTION(DLevelPostProcessor, GetThingPos) { PARAM_SELF_PROLOGUE(DLevelPostProcessor); PARAM_UINT(thing); const DVector3 pos = thing < MapThingsConverted.Size() ? MapThingsConverted[thing].pos : DVector3(0, 0, 0); ACTION_RETURN_VEC3(pos); } DEFINE_ACTION_FUNCTION(DLevelPostProcessor, SetThingXY) { PARAM_SELF_PROLOGUE(DLevelPostProcessor); PARAM_UINT(thing); PARAM_FLOAT(x); PARAM_FLOAT(y); if (thing < MapThingsConverted.Size()) { auto& pos = MapThingsConverted[thing].pos; pos.X = x; pos.Y = y; } return 0; } DEFINE_ACTION_FUNCTION(DLevelPostProcessor, SetThingZ) { PARAM_SELF_PROLOGUE(DLevelPostProcessor); PARAM_UINT(thing); PARAM_FLOAT(z); if (thing < MapThingsConverted.Size()) { MapThingsConverted[thing].pos.Z = z; } return 0; } DEFINE_ACTION_FUNCTION(DLevelPostProcessor, GetThingAngle) { PARAM_SELF_PROLOGUE(DLevelPostProcessor); PARAM_UINT(thing); const int angle = thing < MapThingsConverted.Size() ? MapThingsConverted[thing].angle : 0; ACTION_RETURN_INT(angle); } DEFINE_ACTION_FUNCTION(DLevelPostProcessor, SetThingAngle) { PARAM_SELF_PROLOGUE(DLevelPostProcessor); PARAM_UINT(thing); PARAM_INT(angle); if (thing < MapThingsConverted.Size()) { MapThingsConverted[thing].angle = angle; } return 0; } DEFINE_ACTION_FUNCTION(DLevelPostProcessor, GetThingSkills) { PARAM_SELF_PROLOGUE(DLevelPostProcessor); PARAM_UINT(thing); const int skills = thing < MapThingsConverted.Size() ? MapThingsConverted[thing].SkillFilter : 0; ACTION_RETURN_INT(skills); } DEFINE_ACTION_FUNCTION(DLevelPostProcessor, SetThingSkills) { PARAM_SELF_PROLOGUE(DLevelPostProcessor); PARAM_UINT(thing); PARAM_UINT(skillmask); if (thing < MapThingsConverted.Size()) { MapThingsConverted[thing].SkillFilter = skillmask; } return 0; } DEFINE_ACTION_FUNCTION(DLevelPostProcessor, GetThingFlags) { PARAM_SELF_PROLOGUE(DLevelPostProcessor); PARAM_UINT(thing); const unsigned flags = thing < MapThingsConverted.Size() ? MapThingsConverted[thing].flags : 0; ACTION_RETURN_INT(flags); } DEFINE_ACTION_FUNCTION(DLevelPostProcessor, SetThingFlags) { PARAM_SELF_PROLOGUE(DLevelPostProcessor); PARAM_UINT(thing); PARAM_UINT(flags); if (thing < MapThingsConverted.Size()) { MapThingsConverted[thing].flags = flags; } return 0; } DEFINE_ACTION_FUNCTION(DLevelPostProcessor, GetThingSpecial) { PARAM_SELF_PROLOGUE(DLevelPostProcessor); PARAM_UINT(thing); const int special = thing < MapThingsConverted.Size() ? MapThingsConverted[thing].special : 0; ACTION_RETURN_INT(special); } DEFINE_ACTION_FUNCTION(DLevelPostProcessor, SetThingSpecial) { PARAM_SELF_PROLOGUE(DLevelPostProcessor); PARAM_UINT(thing); PARAM_INT(special); if (thing < MapThingsConverted.Size()) { MapThingsConverted[thing].special = special; } return 0; } DEFINE_ACTION_FUNCTION(DLevelPostProcessor, GetThingArgument) { PARAM_SELF_PROLOGUE(DLevelPostProcessor); PARAM_UINT(thing); PARAM_UINT(index); const int argument = index < 5 && thing < MapThingsConverted.Size() ? MapThingsConverted[thing].args[index] : 0; ACTION_RETURN_INT(argument); } DEFINE_ACTION_FUNCTION(DLevelPostProcessor, GetThingStringArgument) { PARAM_SELF_PROLOGUE(DLevelPostProcessor); PARAM_UINT(thing); const FName argument = thing < MapThingsConverted.Size() ? MapThingsConverted[thing].arg0str : NAME_None; ACTION_RETURN_INT(argument); } DEFINE_ACTION_FUNCTION(DLevelPostProcessor, SetThingArgument) { PARAM_SELF_PROLOGUE(DLevelPostProcessor); PARAM_UINT(thing); PARAM_UINT(index); PARAM_INT(value); if (index < 5 && thing < MapThingsConverted.Size()) { MapThingsConverted[thing].args[index] = value; } return 0; } DEFINE_ACTION_FUNCTION(DLevelPostProcessor, SetThingStringArgument) { PARAM_SELF_PROLOGUE(DLevelPostProcessor); PARAM_UINT(thing); PARAM_INT(value); if (thing < MapThingsConverted.Size()) { MapThingsConverted[thing].arg0str = ENamedName(value); } return 0; } DEFINE_ACTION_FUNCTION(DLevelPostProcessor, GetThingID) { PARAM_SELF_PROLOGUE(DLevelPostProcessor); PARAM_UINT(thing); const int id = thing < MapThingsConverted.Size() ? MapThingsConverted[thing].thingid : 0; ACTION_RETURN_INT(id); } DEFINE_ACTION_FUNCTION(DLevelPostProcessor, SetThingID) { PARAM_SELF_PROLOGUE(DLevelPostProcessor); PARAM_UINT(thing); PARAM_INT(id); if (thing < MapThingsConverted.Size()) { MapThingsConverted[thing].thingid = id; } return 0; } DEFINE_ACTION_FUNCTION(DLevelPostProcessor, SetVertex) { PARAM_SELF_PROLOGUE(DLevelPostProcessor); PARAM_UINT(vertex); PARAM_FLOAT(x); PARAM_FLOAT(y); if (vertex < level.vertexes.Size()) { level.vertexes[vertex].p = DVector2(x, y); } ForceNodeBuild = true; return 0; } DEFINE_ACTION_FUNCTION(DLevelPostProcessor, SetLineVertexes) { PARAM_SELF_PROLOGUE(DLevelPostProcessor); PARAM_UINT(lineidx); PARAM_UINT(vertexidx1); PARAM_UINT(vertexidx2); if (lineidx < level.lines.Size() && vertexidx1 < level.vertexes.Size() && vertexidx2 < level.vertexes.Size()) { line_t *line = &level.lines[lineidx]; vertex_t *vertex1 = &level.vertexes[vertexidx1]; vertex_t *vertex2 = &level.vertexes[vertexidx2]; line->v1 = vertex1; line->v2 = vertex2; } ForceNodeBuild = true; return 0; } DEFINE_ACTION_FUNCTION(DLevelPostProcessor, FlipLineSideRefs) { PARAM_SELF_PROLOGUE(DLevelPostProcessor); PARAM_UINT(lineidx); if (lineidx < level.lines.Size()) { line_t *line = &level.lines[lineidx]; side_t *side1 = line->sidedef[1]; side_t *side2 = line->sidedef[0]; if (!!side1 && !!side2) // don't flip single-sided lines { sector_t *frontsector = line->sidedef[1]->sector; sector_t *backsector = line->sidedef[0]->sector; line->sidedef[0] = side1; line->sidedef[1] = side2; line->frontsector = frontsector; line->backsector = backsector; } } ForceNodeBuild = true; return 0; } DEFINE_ACTION_FUNCTION(DLevelPostProcessor, SetLineSectorRef) { PARAM_SELF_PROLOGUE(DLevelPostProcessor); PARAM_UINT(lineidx); PARAM_UINT(sideidx); PARAM_UINT(sectoridx); if ( sideidx < 2 && lineidx < level.lines.Size() && sectoridx < level.sectors.Size()) { line_t *line = &level.lines[lineidx]; side_t *side = line->sidedef[sideidx]; side->sector = &level.sectors[sectoridx]; if (sideidx == 0) line->frontsector = side->sector; else line->backsector = side->sector; } ForceNodeBuild = true; return 0; } DEFINE_ACTION_FUNCTION(DLevelPostProcessor, GetDefaultActor) { PARAM_SELF_PROLOGUE(DLevelPostProcessor); PARAM_NAME(actorclass); ACTION_RETURN_OBJECT(GetDefaultByName(actorclass)); } //========================================================================== // // CCMD mapchecksum // //========================================================================== CCMD (mapchecksum) { MapData *map; uint8_t cksum[16]; if (argv.argc() < 2) { Printf("Usage: mapchecksum <map> ...\n"); } for (int i = 1; i < argv.argc(); ++i) { map = P_OpenMapData(argv[i], true); if (map == NULL) { Printf("Cannot load %s as a map\n", argv[i]); } else { map->GetChecksum(cksum); const char *wadname = Wads.GetWadName(Wads.GetLumpFile(map->lumpnum)); delete map; for (size_t j = 0; j < sizeof(cksum); ++j) { Printf("%02X", cksum[j]); } Printf(" // %s %s\n", wadname, argv[i]); } } } //========================================================================== // // CCMD hiddencompatflags // //========================================================================== CCMD (hiddencompatflags) { Printf("%08x %08x %08x\n", ii_compatflags, ii_compatflags2, ib_compatflags); }
26.156542
130
0.677311
[ "object" ]
bf410722a6c60cacc3675a8c719f4ad6b11e2981
523
cpp
C++
PTA/PAT/BasicLevel/1041.cpp
cnsteven/online-judge
60ee841a97e2bc0dc9c7b23fe5daa186898ab8b7
[ "MIT" ]
1
2019-05-04T10:28:32.000Z
2019-05-04T10:28:32.000Z
PTA/PAT/BasicLevel/1041.cpp
cnsteven/online-judge
60ee841a97e2bc0dc9c7b23fe5daa186898ab8b7
[ "MIT" ]
null
null
null
PTA/PAT/BasicLevel/1041.cpp
cnsteven/online-judge
60ee841a97e2bc0dc9c7b23fe5daa186898ab8b7
[ "MIT" ]
3
2020-12-31T04:36:38.000Z
2021-07-25T07:39:31.000Z
#include <iostream> #include <string> #include <vector> using namespace std; int main() { int M, N, ti; string ts; string a[1001]; int b[1001]; cin >> N; while (N--) { cin >> ts; cin >> ti; a[ti] = ts; cin >> b[ti]; } cin >> M; vector<int> va; vector<int>::iterator it; while (M--) { cin >> ti; va.push_back(ti); } for (it = va.begin(); it < va.end(); it++) cout << a[*it] << " " << b[*it] << endl; return 0; }
18.678571
48
0.439771
[ "vector" ]
bf458fdb2a9560f704119c7b40775ff7c6c88885
1,501
hpp
C++
pomdog/experimental/particles/particle_system.hpp
mogemimi/pomdog
6dc6244d018f70d42e61c6118535cf94a9ee0618
[ "MIT" ]
163
2015-03-16T08:42:32.000Z
2022-01-11T21:40:22.000Z
pomdog/experimental/particles/particle_system.hpp
mogemimi/pomdog
6dc6244d018f70d42e61c6118535cf94a9ee0618
[ "MIT" ]
17
2015-04-12T20:57:50.000Z
2020-10-10T10:51:45.000Z
pomdog/experimental/particles/particle_system.hpp
mogemimi/pomdog
6dc6244d018f70d42e61c6118535cf94a9ee0618
[ "MIT" ]
21
2015-04-12T20:45:11.000Z
2022-01-14T20:50:16.000Z
// Copyright mogemimi. Distributed under the MIT license. #pragma once #include "pomdog/basic/conditional_compilation.hpp" #include "pomdog/chrono/duration.hpp" #include "pomdog/experimental/particles/particle.hpp" #include "pomdog/experimental/random/xoroshiro128_star_star.hpp" POMDOG_SUPPRESS_WARNINGS_GENERATED_BY_STD_HEADERS_BEGIN #include <cstdint> #include <memory> #include <vector> POMDOG_SUPPRESS_WARNINGS_GENERATED_BY_STD_HEADERS_END namespace pomdog { class ParticleClip; class ParticleSystem final { public: explicit ParticleSystem(const std::shared_ptr<ParticleClip const>& clip); void Play(); void Pause(); void Stop(); void Simulate( const Vector2& emitterPosition, const Radian<float>& emitterRotation, const Duration& duration); void Simulate( const Vector3& emitterPosition, const Quaternion& emitterRotation, const Duration& duration); bool IsAlive() const; const std::vector<Particle>& GetParticles() const { return particles; } std::size_t GetParticleCount() const { return particles.size(); } bool IsLoop() const noexcept; private: enum class ParticleSystemState : std::uint8_t { Paused, Playing, Stopped }; std::vector<Particle> particles; std::shared_ptr<ParticleClip const> clip; Duration erapsedTime; Duration emissionTimer; random::Xoroshiro128StarStar random; ParticleSystemState state; }; } // namespace pomdog
24.209677
77
0.723518
[ "vector" ]
bf4ae7c95f4cdf71f200b936513ac97fd6362efd
789
hpp
C++
include/glfw/glfw.hpp
drt1245/glfwpp
c2c9c0bd0adb159fcc399b2e2e410a7ee0271d4a
[ "BSL-1.0" ]
null
null
null
include/glfw/glfw.hpp
drt1245/glfwpp
c2c9c0bd0adb159fcc399b2e2e410a7ee0271d4a
[ "BSL-1.0" ]
null
null
null
include/glfw/glfw.hpp
drt1245/glfwpp
c2c9c0bd0adb159fcc399b2e2e410a7ee0271d4a
[ "BSL-1.0" ]
null
null
null
#pragma once //////////////////////////////////////////////////////////////////////////////// /// \file glfw.hpp A GLFW C++ wrapper /// /// The event-queue implementation is based on GLEQ by Camilla Berglund /// <dreda@glfw.org>: https://github.com/elmindreda/gleq/ /// //////////////////////////////////////////////////////////////////////////////// #include <array> #include <string> #include <type_traits> #include <vector> //////////////////////////////////////////////////////////////////////////////// #include <glfw/config.hpp> #include <glfw/environment.hpp> #include <glfw/exception.hpp> #include <glfw/monitor.hpp> #include <glfw/key.hpp> #include <glfw/gamma_ramp.hpp> #include <glfw/window.hpp> ////////////////////////////////////////////////////////////////////////////////
34.304348
80
0.427123
[ "vector" ]
bf4c2e8344952aac5e2efb462d99c23d0d19fbef
3,800
hpp
C++
iris-cpp/include/iris/io/reader/ValueReader.hpp
wbknez/iris
ac6f8ca57cec88a24bdf22eca42e2c77a53f4cd0
[ "Apache-2.0" ]
null
null
null
iris-cpp/include/iris/io/reader/ValueReader.hpp
wbknez/iris
ac6f8ca57cec88a24bdf22eca42e2c77a53f4cd0
[ "Apache-2.0" ]
null
null
null
iris-cpp/include/iris/io/reader/ValueReader.hpp
wbknez/iris
ac6f8ca57cec88a24bdf22eca42e2c77a53f4cd0
[ "Apache-2.0" ]
null
null
null
/*! * Contains a mechanism to read and parse a CSV (comma separated value) file of * integer values into two vectors, each of which describe a set of discrete * variables used in a simulation. */ #ifndef IRIS_VALUE_READER_HPP_ #define IRIS_VALUE_READER_HPP_ #include <istream> #include <string> #include <utility> #include <vector> #include "iris/Model.hpp" namespace iris { namespace io { typedef std::pair<ValueList, BehaviorList> ValueParams; /*! * Checks whether or not the value list is strictly less than the size * of the behavior list and, if so, throws an exception to alert the * caller of this. * * @throws runtime_error * If the size of the value list is (strictly) less than the * size of the behavior list. */ void enforceSizeRequirement(const ValueParams& params); /*! * Checks whether or not the values of both the behavior list and the * value list match. * * Please note that this method checks <i>only</i> the intersection of * these two lists. Because the behavior list is designed to be * derivative of the values - that is, the length of the behavior list * is required to be less than or equal to that of the list of values - * the non-intersecting portion of the values list is completely * irrelevant. * * @throws runtime_error * If there is a discrepancy between the behavior and value * lists. */ void enforceValueRequirements(const ValueParams& params); /*! * Reads all of the lines in a stream and returns them as a vector of * strings for processing. * * As should be obvious, this method is only particularly useful for * small streams. * * @param in * The stream to read. * @return A vector of lines read. */ std::vector<std::string> getLines(std::istream& in); /*! * Reads the specified CSV (command separated value) file and extracts * the set of discrete values and behaviors to use in a simulation. * * @param filename * The name of the CSV file to read (and parse). * @return A set of values and behaviors to use. * @throws runtime_error * If the file could not be read or parsed correctly. */ ValueParams readValuesData(const std::string& filename); /*! * Parses the specified stream in order to extract the set of values and * behaviors to use in a simulation. * * The expected format of the stream is CSV (comma separated value) and * an example is: * 3,4,2,2 * 3,4 * where the first line denotes the number of discrete values (per * column) and the second is the number of behaviors. Please keep in * mind that the number of behaviors must be less than or equal to the * values. Furthermore, the second line is optional; to specify that * the behaviors and values are bijective simply do not include it. * * Finally, the numeric values themselves are assumed to be 8-bit and * unsigned. Anything larger will cause an error during processing. * * @param filename * The name of the file to read the values from. * @return The set of values and behaviors to use. * @throws runtime_error * If the stream is not formatted correctly. */ ValueParams parseValuesFromCSV(std::istream& in); } } #endif
36.893204
80
0.600789
[ "vector", "model" ]
bf59574a65d9899e01a131e9cca476d59a91c9e6
109,473
cpp
C++
render.cpp
Diamondtroller/asciiid
dec51f3ba447633eeb9c017762cda9bb79e9f84e
[ "MIT" ]
null
null
null
render.cpp
Diamondtroller/asciiid
dec51f3ba447633eeb9c017762cda9bb79e9f84e
[ "MIT" ]
null
null
null
render.cpp
Diamondtroller/asciiid
dec51f3ba447633eeb9c017762cda9bb79e9f84e
[ "MIT" ]
null
null
null
// this is CPU scene renderer into ANSI framebuffer #include "render.h" #include "sprite.h" //#include "game.h" #include <stdint.h> #include <malloc.h> #include <stdio.h> #include "terrain.h" #include "world.h" #include "matrix.h" #include "fast_rand.h" // #include "sprite.h" #include "inventory.h" #include "game.h" #include "PerlinNoise.hpp" #define _USE_MATH_DEFINES #include <math.h> #include <float.h> #include <string.h> #ifdef min // thanks windows #undef min #endif #ifdef max // thanks windows #undef max #endif #define DBL extern Character* player_head; extern Character* player_tail; static bool global_refl_mode = false; extern Sprite* player_sprite; extern Sprite* attack_sprite; extern Sprite* inventory_sprite; void* GetMaterialArr(); template <typename Sample> inline void Bresenham(Sample* buf, int w, int h, int from[3], int to[3], int _or) { int sx = to[0] - from[0]; int sy = to[1] - from[1]; if (sx == 0 && sy==0) return; int sz = to[2] - from[2]; int ax = sx >= 0 ? sx : -sx; int ay = sy >= 0 ? sy : -sy; if (ax >= ay) { float n = +1.0f / sx; // horizontal domain if (from[0] > to[0]) { int* swap = from; from = to; to = swap; } int x0 = (std::max(0, from[0]) + 1) & ~1; // round up start x, so we won't produce out of domain samples int x1 = std::min(w, to[0]); for (int x = x0; x < x1; x+=2) { float a = x - from[0] + 0.5f; int y = (int)floor((a * sy)*n + from[1] + 0.5f); if (y >= 0 && y < h) { float z = (a * sz) * n + from[2]; Sample* ptr = buf + w * y + x; if (ptr->DepthTest_RO(z)) ptr->spare |= _or; ptr++; if (ptr->DepthTest_RO(z)) ptr->spare |= _or; } } } else { float n = 1.0f / sy; // vertical domain if (from[1] > to[1]) { int* swap = from; from = to; to = swap; } int y0 = std::max(0, from[1]); int y1 = std::min(h, to[1]); for (int y = y0; y < y1; y++) { int a = y - from[1]; int x = (int)floor((a * sx) * n + from[0] + 0.5f); if (x >= 0 && x < w) { float z = (a * sz)*n + from[2]; Sample* ptr = buf + w * y + x; if (ptr->DepthTest_RO(z)) ptr->spare |= _or; } } } } template <typename Sample> inline void PerspectiveCorrectCellLine(/*const*/Sample* smp, AnsiCell* buf, int w, int h, int from[3], int to[3], float d_from, float d_to, int gl, int fg) { int sx = to[0] - from[0]; int sy = to[1] - from[1]; if (sx == 0 && sy == 0) return; int sz = to[2] - from[2]; int ax = sx >= 0 ? sx : -sx; int ay = sy >= 0 ? sy : -sy; if (ax >= ay) { float n = +1.0f / sx; // horizontal domain if (from[0] > to[0]) { int* swap = from; from = to; to = swap; } int x0 = std::max(0, from[0]); int x1 = std::min(w, to[0]); for (int x = x0; x < x1; x++) { float a = x - from[0] + 0.5f; int y = (int)floor((a * sy)*n + from[1] + 0.5f); if (y >= 0 && y < h) { int hx = 2 * x + 2; int hy = 2 * y + 2; float ka = a * n * d_to; ka = ka / ((1 - a * n) * d_from + ka); float z = sz * ka + from[2]; /*const*/Sample* test = smp + hy * (2 * w + 4) + hx; if (test->DepthTest_RO(z)) { AnsiCell* ptr = buf + w * y + x; int av = AverageGlyph(ptr, 0xF); ptr->bk = av; ptr->fg = LightenColor(LightenColor(av)); ptr->gl = gl; } } } } else { float n = 1.0f / sy; // vertical domain if (from[1] > to[1]) { int* swap = from; from = to; to = swap; } int y0 = std::max(0, from[1]); int y1 = std::min(h, to[1]); for (int y = y0; y < y1; y++) { int a = y - from[1]; int x = (int)floor((a * sx) * n + from[0] + 0.5f); if (x >= 0 && x < w) { int hx = 2 * x + 2; int hy = 2 * y + 2; float ka = a * n * d_to; ka = ka / ((1 - a * n) * d_from + ka); float z = sz * ka + from[2]; /*const*/Sample* test = smp + hy * (2 * w + 4) + hx; if (test->DepthTest_RO(z)) { AnsiCell* ptr = buf + w * y + x; int av = AverageGlyph(ptr, 0xF); ptr->bk = av; ptr->fg = LightenColor(LightenColor(av)); ptr->gl = gl; } } } } } template <typename Sample> inline void CellLine(/*const*/Sample* smp, AnsiCell* buf, int w, int h, int from[3], int to[3], int gl, int fg) { int sx = to[0] - from[0]; int sy = to[1] - from[1]; if (sx == 0 && sy == 0) return; int sz = to[2] - from[2]; int ax = sx >= 0 ? sx : -sx; int ay = sy >= 0 ? sy : -sy; if (ax >= ay) { float n = +1.0f / sx; // horizontal domain if (from[0] > to[0]) { int* swap = from; from = to; to = swap; } int x0 = std::max(0, from[0]); int x1 = std::min(w, to[0]); for (int x = x0; x < x1; x++) { float a = x - from[0] + 0.5f; int y = (int)floor((a * sy)*n + from[1] + 0.5f); if (y >= 0 && y < h) { int hx = 2 * x + 2; int hy = 2 * y + 2; float z = (a * sz) * n + from[2]; /*const*/Sample* test = smp + hy * (2 * w + 4) + hx; if (test->DepthTest_RO(z)) { AnsiCell* ptr = buf + w * y + x; int av = AverageGlyph(ptr, 0xF); ptr->bk = av; ptr->fg = LightenColor(LightenColor(av)); ptr->gl = gl; } } } } else { float n = 1.0f / sy; // vertical domain if (from[1] > to[1]) { int* swap = from; from = to; to = swap; } int y0 = std::max(0, from[1]); int y1 = std::min(h, to[1]); for (int y = y0; y < y1; y++) { int a = y - from[1]; int x = (int)floor((a * sx) * n + from[0] + 0.5f); if (x >= 0 && x < w) { int hx = 2 * x + 2; int hy = 2 * y + 2; float z = (a * sz) * n + from[2]; /*const*/Sample* test = smp + hy * (2 * w + 4) + hx; if (test->DepthTest_RO(z)) { AnsiCell* ptr = buf + w * y + x; int av = AverageGlyph(ptr, 0xF); ptr->bk = av; ptr->fg = LightenColor(LightenColor(av)); ptr->gl = gl; } } } } } // todo: lets add "int varyings" template arg // and add "const float varying[3][varyings]" function param (values at verts) // so we can calc here values in lower-left corner and x,y gradients // and provide all varyings interpolated into shader->Blend() call // we should do it also for 'z' coord template <typename Sample, typename Shader> inline void Rasterize(Sample* buf, int w, int h, Shader* s, const int* v[3], bool dblsided) { // each v[i] must point to 4 ints: {x,y,z,f} where f should indicate culling bits (can be 0) // shader must implement: bool Shader::Fill(Sample* s, int bc[3]) // where bc contains 3 barycentric weights which are normalized to 0x8000 (use '>>15' after averaging) // Sample must implement bool DepthTest(int z, int divisor); // it must return true if z/divisor passes depth test on this sample // if test passes, it should write new z/d to sample's depth (if something like depth write mask is enabled) // produces samples between buffer cells #define BC_A(a,b,c) (2*(((b)[0] - (a)[0]) * ((c)[1] - (a)[1]) - ((b)[1] - (a)[1]) * ((c)[0] - (a)[0]))) // produces samples at centers of buffer cells #define BC_P(a,b,c) (((b)[0] - (a)[0]) * (2*(c)[1]+1 - 2*(a)[1]) - ((b)[1] - (a)[1]) * (2*(c)[0]+1 - 2*(a)[0])) if ((v[0][3] & v[1][3] & v[2][3]) == 0) { int area = BC_A(v[0],v[1],v[2]); // todo: // calc all varyings at 0,0 screen coord // and their dx,dy gradients if (area > 0) { if (area >= 0x10000) return; float normalizer = (1.0f - FLT_EPSILON) / area; // canvas intersection with triangle bbox int left = std::max(0, std::min(v[0][0], std::min(v[1][0], v[2][0]))); int right = std::min(w, std::max(v[0][0], std::max(v[1][0], v[2][0]))); int bottom = std::max(0, std::min(v[0][1], std::min(v[1][1], v[2][1]))); int top = std::min(h, std::max(v[0][1], std::max(v[1][1], v[2][1]))); Sample* col = buf + bottom * w + left; for (int y = bottom; y < top; y++, col+=w) { Sample* row = col; for (int x = left; x < right; x++, row++) { int p[2] = { x,y }; int bc[3] = { BC_P(v[1], v[2], p), BC_P(v[2], v[0], p), BC_P(v[0], v[1], p) }; if (bc[0] < 0 || bc[1] < 0 || bc[2] < 0) continue; // edge pairing if (bc[0] == 0 && v[1][0] <= v[2][0] || bc[1] == 0 && v[2][0] <= v[0][0] || bc[2] == 0 && v[0][0] <= v[1][0]) { continue; } // assert(bc[0] + bc[1] + bc[2] == area); float nbc[3] = { bc[0] * normalizer, bc[1] * normalizer, bc[2] * normalizer }; float z = nbc[0] * v[0][2] + nbc[1] * v[1][2] + nbc[2] * v[2][2]; s->Blend(row,z,nbc); } } } else if (area < 0 && dblsided) { if (area <= -0x10000) return; assert(area > -0x10000); float normalizer = (1.0f - FLT_EPSILON) / area; // canvas intersection with triangle bbox int left = std::max(0, std::min(v[0][0], std::min(v[1][0], v[2][0]))); int right = std::min(w, std::max(v[0][0], std::max(v[1][0], v[2][0]))); int bottom = std::max(0, std::min(v[0][1], std::min(v[1][1], v[2][1]))); int top = std::min(h, std::max(v[0][1], std::max(v[1][1], v[2][1]))); Sample* col = buf + bottom * w + left; for (int y = bottom; y < top; y++, col += w) { Sample* row = col; for (int x = left; x < right; x++, row++) { int p[2] = { x,y }; int bc[3] = { BC_P(v[1], v[2], p), BC_P(v[2], v[0], p), BC_P(v[0], v[1], p) }; if (bc[0] > 0 || bc[1] > 0 || bc[2] > 0) continue; // edge pairing if (bc[0] == 0 && v[1][0] <= v[2][0] || bc[1] == 0 && v[2][0] <= v[0][0] || bc[2] == 0 && v[0][0] <= v[1][0]) { continue; } // assert(bc[0] + bc[1] + bc[2] == area); float nbc[3] = { bc[0] * normalizer, bc[1] * normalizer, bc[2] * normalizer }; float z = nbc[0] * v[0][2] + nbc[1] * v[1][2] + nbc[2] * v[2][2]; s->Blend(row, z, nbc); } } } } #undef BC } struct Sample { uint16_t visual; uint8_t diffuse; uint8_t spare; // refl, patch xy parity etc..., direct color bit (meshes): visual has just 565 color? float height; /* inline bool DepthTest_RW(float z) { if (height > z) return false; spare &= ~0x4; // clear lines height = z; return true; } */ inline bool DepthTest_RO(float z) { return height <= z + HEIGHT_SCALE/2; } }; struct SampleBuffer { int w, h; // make 2x +2 bigger than terminal buffer Sample* ptr; }; struct SpriteRenderBuf { Sprite* sprite; int s_pos[3]; int angle; int anim; int frame; int reps[4]; float dist; uint8_t alpha; bool refl; Character* character; static int FarToNear(const void* a, const void* b) { const SpriteRenderBuf* p = (const SpriteRenderBuf*)a; const SpriteRenderBuf* q = (const SpriteRenderBuf*)b; if (p->dist > q->dist) return -1; if (p->dist < q->dist) return 1; return 0; } }; struct Renderer { void Init() { memset(this, 0, sizeof(Renderer)); pn.reseed(std::default_random_engine::default_seed); } void Free() { if (sample_buffer.ptr) free(sample_buffer.ptr); if (sprites_alloc) free(sprites_alloc); } uint64_t stamp; siv::PerlinNoise pn; double pn_time; SampleBuffer sample_buffer; // render surface int sprites_alloc_size; int sprites; SpriteRenderBuf* sprites_alloc; static const int max_items = 9; // picking with keyb: 1-9, 0-drop int items; Item* item_sort[max_items+1]; // +1 for null-terminator float item_dist[max_items]; static const int max_npcs = 3; int npcs; Inst* npc_sort[max_npcs+1]; // (SpriteInst) non players! +1 for null-terminator float npc_dist[max_npcs]; uint8_t* buffer; int buffer_size; // ansi_buffer allocation size in cells (minimize reallocs) static void RenderPatch(Patch* p, int x, int y, int view_flags, void* cookie /*Renderer*/); static void RenderSprite(Inst* inst, Sprite* s, float pos[3], float yaw, int anim, int frame, int reps[4], void* cookie /*Renderer*/); static void RenderMesh(Mesh* m, double* tm, void* cookie /*Renderer*/); static void RenderFace(float coords[9], uint8_t colors[12], uint32_t visual, void* cookie /*Renderer*/); // unstatic -> needs R/W access to sample_buffer.ptr[].height for depth testing! void RenderSprite(AnsiCell* ptr, int width, int height, Sprite* s, bool refl, int anim, int frame, int angle, int pos[3]); // transform double mul[6]; // 3x2 rot part double add[3]; // post rotated and rounded translation float yaw,pos[3]; float water; float light[4]; bool int_flag; bool perspective; double inv_tm[16]; // for unproject // perspective test float view_dir[3]; float view_pos[3]; float view_ofs[2]; // dw/2 + shift[0]*2, dh/2 + shift[1]*2 float focal; double viewinst_tm[16]; const double* inst_tm; int patch_uv[HEIGHT_CELLS][2]; // constant }; static int create_auto_mat(uint8_t mat[]); static uint8_t auto_mat[/*b*/32/*g*/ * 32/*r*/ * 32/*bg,fg,gl*/ * 3]; int auto_mat_result = create_auto_mat(auto_mat); static int create_auto_mat(uint8_t mat[]) { /* #define FLO(x) ((int)floor(5 * x / 31.0f)) #define REM(x) (5*x-31*flo[x]) */ #define MCV 5 #define MCV_TO_5(mcv) (((mcv) * 5 + MCV/2) / MCV) #define FLO(x) ((int)floor(MCV * x / 31.0f)) #define REM(x) (MCV*x-31*flo[x]) static const int flo[32] = { FLO(0), FLO(1), FLO(2), FLO(3), FLO(4), FLO(5), FLO(6), FLO(7), FLO(8), FLO(9), FLO(10), FLO(11), FLO(12), FLO(13), FLO(14), FLO(15), FLO(16), FLO(17), FLO(18), FLO(19), FLO(20), FLO(21), FLO(22), FLO(23), FLO(24), FLO(25), FLO(26), FLO(27), FLO(28), FLO(29), FLO(30), FLO(31), }; static const int rem[32]= { REM(0), REM(1), REM(2), REM(3), REM(4), REM(5), REM(6), REM(7), REM(8), REM(9), REM(10), REM(11), REM(12), REM(13), REM(14), REM(15), REM(16), REM(17), REM(18), REM(19), REM(20), REM(21), REM(22), REM(23), REM(24), REM(25), REM(26), REM(27), REM(28), REM(29), REM(30), REM(31), }; static const char glyph[] = " ..::%"; int max_pr = 0; int i = 0; for (int b=0; b<32; b++) { int p[3]; p[2] = rem[b]; int B[2] = { flo[b],std::min(MCV, flo[b] + 1) }; for (int g = 0; g < 32; g++) { p[1] = rem[g]; int G[2] = { flo[g],std::min(MCV, flo[g] + 1) }; for (int r = 0; r < 32; r++,i++) { p[0] = rem[r]; int R[2] = { flo[r],std::min(MCV, flo[r] + 1) }; float best_sd = -1; float best_pr; int best_lo; int best_hi; // check all pairs of 8 cube verts for (int lo = 0; lo < 7; lo++) { int v0[3] = { R[lo & 1], G[(lo & 2) >> 1], B[(lo & 4) >> 2] }; int pv0[3]= { R[0] * 31 + p[0] - v0[0] * 31, G[0] * 31 + p[1] - v0[1] * 31, B[0] * 31 + p[2] - v0[2] * 31, }; for (int hi = lo + 1; hi < 8; hi++) { int v1[3] = { R[hi & 1], G[(hi & 2) >> 1], B[(hi & 4) >> 2] }; int v10[3] = { 31*(v1[0] - v0[0]), 31*(v1[1] - v0[1]), 31*(v1[2] - v0[2]) }; int v10_sqrlen = v10[0] * v10[0] + v10[1] * v10[1] + v10[2] * v10[2]; float pr = v10_sqrlen ? (v10[0] * pv0[0] + v10[1] * pv0[1] + v10[2] * pv0[2]) / (float)v10_sqrlen : 0.0f; // projection point float prp[3] = { v10[0] * pr, v10[1] * pr, v10[2] * pr }; // dist vect float prv[3] = { pv0[0] - prp[0], pv0[1] - prp[1], pv0[2] - prp[2] }; // square dist float sd = sqrtf(prv[0] * prv[0] + prv[1] * prv[1] + prv[2] * prv[2]); if (sd < best_sd || best_sd < 0) { best_sd = sd; best_pr = pr; best_lo = lo; best_hi = hi; } } } int idx = 3 * (r + 32 * (g + 32 * b)); int shd = (int)floorf( best_pr * 11 + 0.5f ); if (shd > 11) { shd = 11; } if (shd < 0) { shd = 0; } if (shd < 6) { mat[idx + 0] = 16 + 36 * MCV_TO_5(R[best_lo & 1]) + 6 * MCV_TO_5(G[(best_lo & 2) >> 1]) + MCV_TO_5(B[(best_lo & 4) >> 2]); mat[idx + 1] = 16 + 36 * MCV_TO_5(R[best_hi & 1]) + 6 * MCV_TO_5(G[(best_hi & 2) >> 1]) + MCV_TO_5(B[(best_hi & 4) >> 2]); mat[idx + 2] = glyph[shd]; } else { mat[idx + 0] = 16 + 36 * MCV_TO_5(R[best_hi & 1]) + 6 * MCV_TO_5(G[(best_hi & 2) >> 1]) + MCV_TO_5(B[(best_hi & 4) >> 2]); mat[idx + 1] = 16 + 36 * MCV_TO_5(R[best_lo & 1]) + 6 * MCV_TO_5(G[(best_lo & 2) >> 1]) + MCV_TO_5(B[(best_lo & 4) >> 2]); mat[idx + 2] = glyph[11-shd]; } } } } return 1; } void Renderer::RenderFace(float coords[9], uint8_t colors[12], uint32_t visual, void* cookie) { struct Shader { void Blend(Sample*s, float z, float bc[3]) { if (s->height < z) { if (global_refl_mode) { if (z < water + HEIGHT_SCALE / 8) { if (z > water) s->height = water; else s->height = z; int r8 = (int)floor(rgb[0][0] * bc[0] + rgb[1][0] * bc[1] + rgb[2][0] * bc[2]); int r5 = (r8 * 249 + 1014) >> 11; int g8 = (int)floor(rgb[0][1] * bc[0] + rgb[1][1] * bc[1] + rgb[2][1] * bc[2]); int g5 = (g8 * 249 + 1014) >> 11; int b8 = (int)floor(rgb[0][2] * bc[0] + rgb[1][2] * bc[1] + rgb[2][2] * bc[2]); int b5 = (b8 * 249 + 1014) >> 11; s->visual = r5 | (g5 << 5) | (b5 << 10); s->diffuse = diffuse; s->spare = (s->spare & ~0x44) | 0x8 | 0x3; } } else { if (z >= water - HEIGHT_SCALE / 8) { if (z < water) s->height = water; else s->height = z; int r8 = (int)floor(rgb[0][0] * bc[0] + rgb[1][0] * bc[1] + rgb[2][0] * bc[2]); int r5 = (r8 * 249 + 1014) >> 11; int g8 = (int)floor(rgb[0][1] * bc[0] + rgb[1][1] * bc[1] + rgb[2][1] * bc[2]); int g5 = (g8 * 249 + 1014) >> 11; int b8 = (int)floor(rgb[0][2] * bc[0] + rgb[1][2] * bc[1] + rgb[2][2] * bc[2]); int b5 = (b8 * 249 + 1014) >> 11; s->visual = r5 | (g5 << 5) | (b5 << 10); s->diffuse = diffuse; s->spare = (s->spare & ~(0x3|0x44)) | 0x8 | 0x1; } } } } /* void Refl(Sample* s, float bc[3]) const { if (s->height < water) { int r8 = (int)floor(rgb[0][0] * bc[0] + rgb[1][0] * bc[1] + rgb[2][0] * bc[2]); int r5 = (r8 * 249 + 1014) >> 11; int g8 = (int)floor(rgb[0][1] * bc[0] + rgb[1][1] * bc[1] + rgb[2][1] * bc[2]); int g5 = (g8 * 249 + 1014) >> 11; int b8 = (int)floor(rgb[0][2] * bc[0] + rgb[1][2] * bc[1] + rgb[2][2] * bc[2]); int b5 = (b8 * 249 + 1014) >> 11; s->visual = r5 | (g5 << 5) | (b5 << 10); s->diffuse = diffuse; s->spare |= 0x8 | 0x3; } } void Fill(Sample* s, float bc[3]) const { if (s->height >= water) { int r8 = (int)floor(rgb[0][0] * bc[0] + rgb[1][0] * bc[1] + rgb[2][0] * bc[2]); int r5 = (r8 * 249 + 1014) >> 11; int g8 = (int)floor(rgb[0][1] * bc[0] + rgb[1][1] * bc[1] + rgb[2][1] * bc[2]); int g5 = (g8 * 249 + 1014) >> 11; int b8 = (int)floor(rgb[0][2] * bc[0] + rgb[1][2] * bc[1] + rgb[2][2] * bc[2]); int b5 = (b8 * 249 + 1014) >> 11; s->visual = r5 | (g5 << 5) | (b5 << 10); s->diffuse = diffuse; s->spare |= 0x8; } else s->height = -1000000; // s->spare = 3; } */ /* inline void Diffuse(int dzdx, int dzdy) { float nl = (float)sqrt(dzdx * dzdx + dzdy * dzdy + HEIGHT_SCALE * HEIGHT_SCALE); float df = (dzdx * light[0] + dzdy * light[1] + HEIGHT_SCALE * light[2]) / nl; df = df * (1.0f - 0.5f*light[3]) + 0.5f*light[3]; diffuse = df <= 0 ? 0 : (int)(df * 0xFF); } */ uint8_t* rgb[3]; // per vertex colors float water; float light[4]; uint8_t diffuse; // shading experiment } shader; Renderer* r = (Renderer*)cookie; shader.water = r->water; // temporarily, let's transform verts for each face separately int v[3][4]; float tmp0[4], tmp1[4], tmp2[4]; { float xyzw[] = { coords[0], coords[1], coords[2], 1.0f }; Product(r->viewinst_tm, xyzw, tmp0); if (r->perspective) // #if PERSPECTIVE_TEST { float ws[4]; Product(r->inst_tm, xyzw, ws); float viewer_dist; // {vx,vy,vz} r->pos float eye_to_vtx[3] = { ws[0] * HEIGHT_CELLS - r->view_pos[0], ws[1] * HEIGHT_CELLS - r->view_pos[1], ws[2] - r->view_pos[2], }; viewer_dist = DotProduct(eye_to_vtx, r->view_dir); if (viewer_dist > 0) { viewer_dist = 1.0/viewer_dist; float fx = tmp0[0]; float fy = tmp0[1]; fx = (fx - r->view_ofs[0]) * viewer_dist + r->view_ofs[0]; fy = (fy - r->view_ofs[1]) * viewer_dist + r->view_ofs[1]; int tx = (int)floorf(fx + 0.5f); int ty = (int)floorf(fy + 0.5f); v[0][0] = tx; v[0][1] = ty; v[0][2] = (int)floor(tmp0[2] + 0.5f); v[0][3] = 0; // clip flags } else return; } else //#else { v[0][0] = (int)floor(tmp0[0] + 0.5f); v[0][1] = (int)floor(tmp0[1] + 0.5f); v[0][2] = (int)floor(tmp0[2] + 0.5f); v[0][3] = 0; // clip flags } //#endif } { float xyzw[] = { coords[3], coords[4], coords[5], 1.0f }; Product(r->viewinst_tm, xyzw, tmp1); if (r->perspective) // #if PERSPECTIVE_TEST { float ws[4]; Product(r->inst_tm, xyzw, ws); float viewer_dist; // {vx,vy,vz} r->pos float eye_to_vtx[3] = { ws[0] * HEIGHT_CELLS - r->view_pos[0], ws[1] * HEIGHT_CELLS - r->view_pos[1], ws[2] - r->view_pos[2], }; viewer_dist = DotProduct(eye_to_vtx, r->view_dir); if (viewer_dist > 0) { viewer_dist = 1.0/viewer_dist; float fx = tmp1[0]; float fy = tmp1[1]; fx = (fx - r->view_ofs[0]) * viewer_dist + r->view_ofs[0]; fy = (fy - r->view_ofs[1]) * viewer_dist + r->view_ofs[1]; int tx = (int)floorf(fx + 0.5f); int ty = (int)floorf(fy + 0.5f); v[1][0] = tx; v[1][1] = ty; v[1][2] = (int)floor(tmp1[2] + 0.5f); v[1][3] = 0; // clip flags } else return; } else // #else { v[1][0] = (int)floor(tmp1[0] + 0.5f); v[1][1] = (int)floor(tmp1[1] + 0.5f); v[1][2] = (int)floor(tmp1[2] + 0.5f); v[1][3] = 0; // clip flags } //#endif } if (visual & (1<<31)) { Bresenham(r->sample_buffer.ptr,r->sample_buffer.w,r->sample_buffer.h, v[0], v[1], 0x40); return; } { float xyzw[] = { coords[6], coords[7], coords[8], 1.0f }; Product(r->viewinst_tm, xyzw, tmp2); if (r->perspective) // #if PERSPECTIVE_TEST { float ws[4]; Product(r->inst_tm, xyzw, ws); float viewer_dist; // {vx,vy,vz} r->pos float eye_to_vtx[3] = { ws[0] * HEIGHT_CELLS - r->view_pos[0], ws[1] * HEIGHT_CELLS - r->view_pos[1], ws[2] - r->view_pos[2], }; viewer_dist = DotProduct(eye_to_vtx, r->view_dir); if (viewer_dist > 0) { viewer_dist = 1.0/viewer_dist; float fx = tmp2[0]; float fy = tmp2[1]; fx = (fx - r->view_ofs[0]) * viewer_dist + r->view_ofs[0]; fy = (fy - r->view_ofs[1]) * viewer_dist + r->view_ofs[1]; int tx = (int)floorf(fx + 0.5f); int ty = (int)floorf(fy + 0.5f); v[2][0] = tx; v[2][1] = ty; v[2][2] = (int)floor(tmp2[2] + 0.5f); v[2][3] = 0; // clip flags } else return; } else // #else { v[2][0] = (int)floor(tmp2[0] + 0.5f); v[2][1] = (int)floor(tmp2[1] + 0.5f); v[2][2] = (int)floor(tmp2[2] + 0.5f); v[2][3] = 0; // clip flags } // #endif } int w = r->sample_buffer.w; int h = r->sample_buffer.h; Sample* ptr = r->sample_buffer.ptr; // normal is const, could be baked into mesh float e1[] = { coords[3] - coords[0], coords[4] - coords[1], coords[5] - coords[2] }; float e2[] = { coords[6] - coords[0], coords[7] - coords[1], coords[8] - coords[2] }; float n[4] = { e1[1] * e2[2] - e1[2] * e2[1], e1[2] * e2[0] - e1[0] * e2[2], e1[0] * e2[1] - e1[1] * e2[0], 0 }; float inst_n[4]; Product(r->inst_tm, n, inst_n); inst_n[2] /= HEIGHT_SCALE; float nn = 1.0f / sqrtf(inst_n[0] * inst_n[0] + inst_n[1] * inst_n[1] + inst_n[2] * inst_n[2]); float df = nn * (inst_n[0] * r->light[0] + inst_n[1] * r->light[1] + inst_n[2] * r->light[2]); //diffuse = 1.0; df = df * (1.0f - 0.5f*r->light[3]) + 0.5f*r->light[3]; df += 0.5; if (df > 1) df = 1; if (df < 0) df = 0; shader.diffuse = (int)(df * 0xFF); if (global_refl_mode) { const int* pv[3] = { v[2],v[1],v[0] }; shader.rgb[0] = colors + 8; shader.rgb[1] = colors + 4; shader.rgb[2] = colors + 0; //for (int i = 0; i < 12; i++) // colors[i] = colors[i] * 3 / 4; Rasterize(r->sample_buffer.ptr, r->sample_buffer.w, r->sample_buffer.h, &shader, pv, visual&(1<<30)); } else { const int* pv[3] = { v[0],v[1],v[2] }; shader.rgb[0] = colors + 0; shader.rgb[1] = colors + 4; shader.rgb[2] = colors + 8; Rasterize(r->sample_buffer.ptr, r->sample_buffer.w, r->sample_buffer.h, &shader, pv, visual&(1<<30)); } } void Renderer::RenderSprite(Inst* inst, Sprite* s, float pos[3], float yaw, int anim, int frame, int reps[4], void* cookie /*Renderer*/) { Renderer* r = (Renderer*)cookie; Character* h = (Character*)GetInstSpriteData(inst); bool is_item = anim < 0; if (h && h->req.action == ACTION::DEAD) { // we need to list his items if nearby if (!global_refl_mode) { float dx = r->pos[0] - pos[0]; float dy = r->pos[1] - pos[1]; float dz = (r->pos[2] + 3 * HEIGHT_SCALE - pos[2]) / HEIGHT_SCALE; float dist = dx * dx + dy * dy + dz * dz; float max_item_dist = 20; if (dist < max_item_dist) { ItemOwner* io = 0; if (h->req.kind == SpriteReq::HUMAN) io = (ItemOwner*)(NPC_Human*)h; else io = (ItemOwner*)(NPC_Creature*)h; for (int it = 0; it < io->items; it++) { int sort = 0; for (; sort < r->items; sort++) { if (dist < r->item_dist[sort]) { int last = r->items < r->max_items ? r->items : r->max_items - 1; for (int move = last; move > sort; move--) { r->item_sort[move] = r->item_sort[move - 1]; r->item_dist[move] = r->item_dist[move - 1]; } break; } } if (sort < r->max_items) { r->item_sort[sort] = io->has[it].item; r->item_dist[sort] = dist; if (r->items < r->max_items) r->items++; } } } } } if (is_item) { int purpose = frame; Item* item = (Item*)reps; if (purpose != Item::WORLD) return; anim = frame = 0; static int _reps[4] = { -1,-1,-1,-1 }; reps = _reps; // calc distance to player // and choose upto 3 closest items if (!global_refl_mode) { float dx = r->pos[0] - pos[0]; float dy = r->pos[1] - pos[1]; float dz = (r->pos[2]+3*HEIGHT_SCALE - pos[2]) / HEIGHT_SCALE; float dist = dx * dx + dy * dy + dz * dz; float max_item_dist = 20; if (dist < max_item_dist) { int sort = 0; for (; sort < r->items; sort++) { if (dist < r->item_dist[sort]) { int last = r->items < r->max_items ? r->items : r->max_items - 1; for (int move = last; move > sort; move--) { r->item_sort[move] = r->item_sort[move - 1]; r->item_dist[move] = r->item_dist[move - 1]; } break; } } if (sort < r->max_items) { r->item_sort[sort] = item; r->item_dist[sort] = dist; if (r->items < r->max_items) r->items++; } } } } else // NPC { float dx = r->pos[0] - pos[0]; float dy = r->pos[1] - pos[1]; float dz = (r->pos[2] + 3 * HEIGHT_SCALE - pos[2]) / HEIGHT_SCALE; float dist = dx * dx + dy * dy + dz * dz; float max_item_dist = 100; if (dist < max_item_dist) { int sort = 0; for (; sort < r->npcs; sort++) { if (dist < r->npc_dist[sort]) { int last = r->npcs < r->max_npcs ? r->npcs : r->max_npcs - 1; for (int move = last; move > sort; move--) { r->npc_sort[move] = r->npc_sort[move - 1]; r->npc_dist[move] = r->npc_dist[move - 1]; } break; } } if (sort < r->max_npcs) { r->npc_sort[sort] = inst; r->npc_dist[sort] = dist; if (r->npcs < r->max_npcs) r->npcs++; } } } if (global_refl_mode && s->projs == 1) return; // transform and append to sprite render list if (r->sprites == r->sprites_alloc_size) { r->sprites_alloc_size += 16; r->sprites_alloc = (SpriteRenderBuf*)realloc(r->sprites_alloc, sizeof(SpriteRenderBuf) * r->sprites_alloc_size); } SpriteRenderBuf* buf = r->sprites_alloc + r->sprites; float w_pos[3] = { pos[0] * HEIGHT_CELLS, pos[1] * HEIGHT_CELLS, pos[2] }; float vx = w_pos[0], vy = w_pos[1], vz = w_pos[2]; float viewer_dist; // {vx,vy,vz} r->pos float eye_to_vtx[3] = { vx - r->view_pos[0], vy - r->view_pos[1], vz - r->view_pos[2], }; viewer_dist = DotProduct(eye_to_vtx, r->view_dir); if (global_refl_mode) { if (r->perspective) // #if PERSPECTIVE_TEST { if (viewer_dist > 0) { // todo: smooth fade float max_scale = 1.33; float hi_scale = 1.25; float lo_scale = 1 / hi_scale; float min_scale = 1 / max_scale; if (!h) if (viewer_dist > max_scale || viewer_dist < min_scale) return; float alpha = 1.0; if (viewer_dist < lo_scale) alpha = (viewer_dist - min_scale) / (lo_scale - min_scale); else if (viewer_dist > hi_scale) alpha = (viewer_dist - max_scale) / (hi_scale - max_scale); buf->alpha = (int)(alpha * 255 + 0.5f); float fx = r->mul[0] * vx + r->mul[2] * vy + r->add[0]; float fy = r->mul[1] * vx + r->mul[3] * vy + r->mul[5] * vz + r->add[1]; float recp_dist = 1.0/viewer_dist; fx = (fx - r->view_ofs[0]) * recp_dist + r->view_ofs[0]; fy = (fy - r->view_ofs[1]) * recp_dist + r->view_ofs[1]; int tx = (int)floorf(fx + 0.5f); int ty = (int)floorf(fy + 0.5f); // convert from samples to cells buf->s_pos[0] = (tx - 1) >> 1; buf->s_pos[1] = (ty - 1) >> 1; buf->s_pos[2] = (int)2*r->water - ((int)floorf(w_pos[2] + 0.5) + HEIGHT_SCALE / 2); } else return; } else // #else { //if (r->int_flag) { int tx = (int)floor(r->mul[0] * w_pos[0] + r->mul[2] * w_pos[1] + 0.5 + r->add[0]); int ty = (int)floor(r->mul[1] * w_pos[0] + r->mul[3] * w_pos[1] + r->mul[5] * w_pos[2] + 0.5 + r->add[1]); // convert from samples to cells buf->s_pos[0] = (tx - 1) >> 1; buf->s_pos[1] = (ty - 1) >> 1; buf->s_pos[2] = (int)2*r->water - ((int)floorf(w_pos[2] + 0.5) + HEIGHT_SCALE / 2); } /* else { int tx = (int)floor(r->mul[0] * w_pos[0] + r->mul[2] * w_pos[1] + 0.5) + r->add[0]; int ty = (int)floor(r->mul[1] * w_pos[0] + r->mul[3] * w_pos[1] + r->mul[5] * w_pos[2] + 0.5) + r->add[1]; // convert from samples to cells buf->s_pos[0] = (tx - 1) >> 1; buf->s_pos[1] = (ty - 2) >> 1; buf->s_pos[2] = (int)2 * r->water - ((int)floorf(w_pos[2] + 0.5) + HEIGHT_SCALE / 4); } */ } // #endif } else { if (r->perspective) // #if PERSPECTIVE_TEST { if (viewer_dist > 0) { // todo: smooth fade float max_scale = 1.33; float hi_scale = 1.25; float lo_scale = 1 / hi_scale; float min_scale = 1 / max_scale; if (!h) if (viewer_dist > max_scale || viewer_dist < min_scale) return; float alpha = 1.0; if (viewer_dist < lo_scale) alpha = (viewer_dist - min_scale) / (lo_scale - min_scale); else if (viewer_dist > hi_scale) alpha = (viewer_dist - max_scale) / (hi_scale - max_scale); buf->alpha = (int)(alpha * 255 + 0.5f); float fx = r->mul[0] * vx + r->mul[2] * vy + r->add[0]; float fy = r->mul[1] * vx + r->mul[3] * vy + r->mul[5] * vz + r->add[1]; float recp_dist = 1.0/viewer_dist; fx = (fx - r->view_ofs[0]) * recp_dist + r->view_ofs[0]; fy = (fy - r->view_ofs[1]) * recp_dist + r->view_ofs[1]; int tx = (int)floorf(fx + 0.5f); int ty = (int)floorf(fy + 0.5f); // convert from samples to cells buf->s_pos[0] = (tx - 1) >> 1; buf->s_pos[1] = (ty - 1) >> 1; buf->s_pos[2] = (int)floorf(w_pos[2] + 0.5) + HEIGHT_SCALE / 2; } else return; } else // #else { //if (r->int_flag) { int tx = (int)floor(r->mul[0] * w_pos[0] + r->mul[2] * w_pos[1] + 0.5 + r->add[0]); int ty = (int)floor(r->mul[1] * w_pos[0] + r->mul[3] * w_pos[1] + r->mul[5] * w_pos[2] + 0.5 + r->add[1]); // convert from samples to cells buf->s_pos[0] = (tx - 1) >> 1; buf->s_pos[1] = (ty - 1) >> 1; buf->s_pos[2] = (int)floorf(w_pos[2] + 0.5) + HEIGHT_SCALE / 2; } /* else { int tx = (int)floor(r->mul[0] * w_pos[0] + r->mul[2] * w_pos[1] + 0.5) + r->add[0]; int ty = (int)floor(r->mul[1] * w_pos[0] + r->mul[3] * w_pos[1] + r->mul[5] * w_pos[2] + 0.5) + r->add[1]; // convert from samples to cells buf->s_pos[0] = (tx - 1) >> 1; buf->s_pos[1] = (ty - 2) >> 1; buf->s_pos[2] = (int)floorf(w_pos[2] + 0.5) + HEIGHT_SCALE / 4; } */ } // #endif } int ang = (int)floor((yaw - r->yaw) * s->angles / 360.0f + 0.5f); ang = ang >= 0 ? ang % s->angles : (ang % s->angles + s->angles) % s->angles; buf->sprite = s; buf->angle = ang; buf->anim = anim; if (is_item) buf->frame = frame; else buf->frame = AnimateSpriteInst(inst, r->stamp); buf->reps[0] = reps[0]; buf->reps[1] = reps[1]; buf->reps[2] = reps[2]; buf->reps[3] = reps[3]; buf->refl = global_refl_mode; buf->character = h; buf->dist = viewer_dist; r->sprites++; } void Renderer::RenderMesh(Mesh* m, double* tm, void* cookie) { Renderer* r = (Renderer*)cookie; double view_tm[16]= { r->mul[0] * HEIGHT_CELLS, r->mul[1] * HEIGHT_CELLS, 0.0, 0.0, r->mul[2] * HEIGHT_CELLS, r->mul[3] * HEIGHT_CELLS, 0.0, 0.0, r->mul[4], r->mul[5], global_refl_mode ? -1.0 : 1.0, 0.0, r->add[0], r->add[1], r->add[2], 1.0 }; r->inst_tm = tm; MatProduct(view_tm, tm, r->viewinst_tm); QueryMesh(m, Renderer::RenderFace, r); // transform verts int integer coords // ... // given interpolated RGB -> round to 555, store it in visual // copy to diffuse to diffuse // mark mash 'auto-material' as 0x8 flag in spare // in post pass: // if sample has 0x8 flag // multiply rgb by diffuse (into 888 bg=fg) // apply color mixing with neighbours // if at least 1 sample have mesh bit in spare // - round mixed bg rgb to R5G5B5 and use auto_material[32K] -> {bg,fg,gl} // else apply gridlines etc. } // we could easily make it template of <Sample,Shader> void Renderer::RenderPatch(Patch* p, int x, int y, int view_flags, void* cookie /*Renderer*/) { struct Shader { void Blend(Sample*s, float z, float bc[3]) { if (s->height < z) { if (global_refl_mode) { if (z < water + HEIGHT_SCALE / 8) { if (z > water) s->height = water; else s->height = z; int u = (int)floor(uv[0] * bc[0] + uv[2] * bc[1] + uv[4] * bc[2]); int v = (int)floor(uv[1] * bc[0] + uv[3] * bc[1] + uv[5] * bc[2]); /* if (u >= VISUAL_CELLS || v >= VISUAL_CELLS) { // detect overflow s->visual = 2; } else */ { s->visual = map[v * VISUAL_CELLS + u]; s->diffuse = diffuse; s->spare |= parity | 0x3; s->spare &= ~(0x44|0x8); // clear mesh and lines } } } else { if (z >= water - HEIGHT_SCALE / 8) { if (z < water) s->height = water; else s->height = z; int u = (int)floor(uv[0] * bc[0] + uv[2] * bc[1] + uv[4] * bc[2]); int v = (int)floor(uv[1] * bc[0] + uv[3] * bc[1] + uv[5] * bc[2]); /* if (u >= VISUAL_CELLS || v >= VISUAL_CELLS) { // detect overflow s->visual = 2; } else */ { int visual_idx = v * VISUAL_CELLS + u; uint16_t m = map[visual_idx]; if (m & 0x8000) s->height += HEIGHT_SCALE; s->visual = m; s->diffuse = diffuse; #ifdef DARK_TERRAIN if (dark&(((uint64_t)1) << visual_idx)) { if (s->diffuse > 64) s->diffuse -= 64; else s->diffuse = 0; } #endif /* if (dark&(((uint64_t)1) << visual_idx)) s->diffuse /= 4; else s->diffuse *= 16; */ s->spare = (s->spare & ~(0x8|0x3|0x44)) | parity; // clear refl, mesh and line, then add parity } } } } } /* void Refl(Sample* s, float bc[3]) const { if (s->height < water) { int u = (int)floor(uv[0] * bc[0] + uv[2] * bc[1] + uv[4] * bc[2]); int v = (int)floor(uv[1] * bc[0] + uv[3] * bc[1] + uv[5] * bc[2]); if (u >= VISUAL_CELLS || v >= VISUAL_CELLS) { // detect overflow s->visual = 2; } else { s->visual = map[v * VISUAL_CELLS + u]; s->diffuse = diffuse; s->spare |= parity; } } } void Fill(Sample* s, float bc[3]) const { if (s->height >= water) { int u = (int)floor(uv[0] * bc[0] + uv[2] * bc[1] + uv[4] * bc[2]); int v = (int)floor(uv[1] * bc[0] + uv[3] * bc[1] + uv[5] * bc[2]); if (u >= VISUAL_CELLS || v >= VISUAL_CELLS) { // detect overflow s->visual = 2; } else { s->visual = map[v * VISUAL_CELLS + u]; s->diffuse = diffuse; s->spare |= parity; } } else s->height = -1000000; //else // s->spare = 3; } */ inline void Diffuse(int dzdx, int dzdy) { float nl = (float)sqrt(dzdx * dzdx + dzdy * dzdy + HEIGHT_SCALE * HEIGHT_SCALE); float df = (dzdx * light[0] + dzdy * light[1] + HEIGHT_SCALE * light[2]) / nl; df = df * (1.0f - 0.5f*light[3]) + 0.5f*light[3]; diffuse = df <= 0 ? 0 : (int)(df * 0xFF); } int* uv; // points to array of 6 ints (u0,v0,u1,v1,u2,v2) each is equal to 0 or VISUAL_CELLS uint16_t* map; // points to array of VISUAL_CELLS x VISUAL_CELLS ushorts float water; float light[4]; uint8_t diffuse; // shading experiment uint8_t parity; #ifdef DARK_TERRAIN uint64_t dark; #endif } shader; Renderer* r = (Renderer*)cookie; double* mul = r->mul; int iadd[2] = { (int)r->add[0], (int)r->add[1] }; double* add = r->add; int w = r->sample_buffer.w; int h = r->sample_buffer.h; Sample* ptr = r->sample_buffer.ptr; uint16_t* hmap = GetTerrainHeightMap(p); uint16_t* hm = hmap; // transform patch verts xy+dx+dy, together with hmap into this array int xyzf[HEIGHT_CELLS + 1][HEIGHT_CELLS + 1][4]; for (int dy = 0; dy <= HEIGHT_CELLS; dy++) { int vy = y * HEIGHT_CELLS + dy * VISUAL_CELLS; for (int dx = 0; dx <= HEIGHT_CELLS; dx++) { int vx = x * HEIGHT_CELLS + dx * VISUAL_CELLS; int vz = *(hm++); if (global_refl_mode) { if (r->perspective) // #if PERSPECTIVE_TEST { float viewer_dist; // {vx,vy,vz} r->pos float eye_to_vtx[3] = { vx - r->view_pos[0], vy - r->view_pos[1], vz - r->view_pos[2], }; viewer_dist = DotProduct(eye_to_vtx, r->view_dir); if (viewer_dist > 0) { viewer_dist = 1.0/viewer_dist; float fx = mul[0] * vx + mul[2] * vy;// + add[0]; float fy = mul[1] * vx + mul[3] * vy + mul[5] * vz;// + add[1]; fx *= viewer_dist; fy *= viewer_dist; float qx = (add[0] - r->view_ofs[0]) * viewer_dist + r->view_ofs[0]; float qy = (add[1] - r->view_ofs[1]) * viewer_dist + r->view_ofs[1]; fx += qx; fy += qy; int tx = (int)floorf(fx + 0.5f); int ty = (int)floorf(fy + 0.5f); xyzf[dy][dx][0] = tx; xyzf[dy][dx][1] = ty; xyzf[dy][dx][2] = (int)(2 * r->water) - vz; // todo: if patch is known to fully fit in screen, set f=0 // otherwise we need to check if / which screen edges cull each vertex xyzf[dy][dx][3] = (tx < 0) | ((tx > w) << 1) | ((ty < 0) << 2) | ((ty > h) << 3); } else { // cull entire patch if any vertex is behind view_pos return; } } else // #else { if (r->int_flag) { int tx = (int)floor(mul[0] * vx + mul[2] * vy + 0.5 + add[0]); int ty = (int)floor(mul[1] * vx + mul[3] * vy + mul[5] * vz + 0.5 + add[1]); xyzf[dy][dx][0] = tx; xyzf[dy][dx][1] = ty; xyzf[dy][dx][2] = (int)(2 * r->water) - vz; // todo: if patch is known to fully fit in screen, set f=0 // otherwise we need to check if / which screen edges cull each vertex xyzf[dy][dx][3] = (tx < 0) | ((tx > w) << 1) | ((ty < 0) << 2) | ((ty > h) << 3); } else { int tx = (int)floor(mul[0] * vx + mul[2] * vy + 0.5) + iadd[0]; int ty = (int)floor(mul[1] * vx + mul[3] * vy + mul[5] * vz + 0.5) + iadd[1]; xyzf[dy][dx][0] = tx; xyzf[dy][dx][1] = ty; xyzf[dy][dx][2] = (int)(2 * r->water) - vz; // todo: if patch is known to fully fit in screen, set f=0 // otherwise we need to check if / which screen edges cull each vertex xyzf[dy][dx][3] = (tx < 0) | ((tx > w) << 1) | ((ty < 0) << 2) | ((ty > h) << 3); } } // #endif } else { if (r->perspective) // #if PERSPECTIVE_TEST { float viewer_dist; // {vx,vy,vz} r->pos float eye_to_vtx[3] = { vx - r->view_pos[0], vy - r->view_pos[1], vz - r->view_pos[2], }; viewer_dist = DotProduct(eye_to_vtx, r->view_dir); if (viewer_dist > 0) { viewer_dist = 1.0/viewer_dist; float fx = mul[0] * vx + mul[2] * vy;// + add[0]; float fy = mul[1] * vx + mul[3] * vy + mul[5] * vz;// + add[1]; fx *= viewer_dist; fy *= viewer_dist; float qx = (add[0] - r->view_ofs[0]) * viewer_dist + r->view_ofs[0]; float qy = (add[1] - r->view_ofs[1]) * viewer_dist + r->view_ofs[1]; fx += qx; fy += qy; int tx = (int)floorf(fx + 0.5f); int ty = (int)floorf(fy + 0.5f); xyzf[dy][dx][0] = tx; xyzf[dy][dx][1] = ty; xyzf[dy][dx][2] = vz; // todo: if patch is known to fully fit in screen, set f=0 // otherwise we need to check if / which screen edges cull each vertex xyzf[dy][dx][3] = (tx < 0) | ((tx > w) << 1) | ((ty < 0) << 2) | ((ty > h) << 3); } else { // cull entire patch if any vertex is behind view_pos return; } } else // #else { // transform if (r->int_flag) { int tx = (int)floor(mul[0] * vx + mul[2] * vy + 0.5 + add[0]); int ty = (int)floor(mul[1] * vx + mul[3] * vy + mul[5] * vz + 0.5 + add[1]); xyzf[dy][dx][0] = tx; xyzf[dy][dx][1] = ty; xyzf[dy][dx][2] = vz; // todo: if patch is known to fully fit in screen, set f=0 // otherwise we need to check if / which screen edges cull each vertex xyzf[dy][dx][3] = (tx < 0) | ((tx > w) << 1) | ((ty < 0) << 2) | ((ty > h) << 3); } else { int tx = (int)floor(mul[0] * vx + mul[2] * vy + 0.5) + iadd[0]; int ty = (int)floor(mul[1] * vx + mul[3] * vy + mul[5] * vz + 0.5) + iadd[1]; xyzf[dy][dx][0] = tx; xyzf[dy][dx][1] = ty; xyzf[dy][dx][2] = vz; // todo: if patch is known to fully fit in screen, set f=0 // otherwise we need to check if / which screen edges cull each vertex xyzf[dy][dx][3] = (tx < 0) | ((tx > w) << 1) | ((ty < 0) << 2) | ((ty > h) << 3); } } // #endif } } } uint16_t diag = GetTerrainDiag(p); // 2 parity bits for drawing lines around patches // 0 - no patch rendered here // 1 - odd // 2 - even // 3 - under water #ifdef DARK_TERRAIN shader.dark = GetTerrainDark(p); #endif shader.parity = (((x^y)/VISUAL_CELLS) & 1) + 1; shader.water = r->water; shader.map = GetTerrainVisualMap(p); shader.light[0] = r->light[0]; shader.light[1] = r->light[1]; shader.light[2] = r->light[2]; shader.light[3] = r->light[3]; /* shader.light[0] = 0; shader.light[1] = 0; shader.light[2] = 1; */ // if (shader.parity == 1) // return; hm = hmap; const int (*uv)[2] = r->patch_uv; for (int dy = 0; dy < HEIGHT_CELLS; dy++, hm++) { for (int dx = 0; dx < HEIGHT_CELLS; dx++,diag>>=1, hm++) { //if (!(diag & 1)) if (diag & 1) { // . // |\ // |_\ // ' ' // lower triangle // terrain should keep diffuse map with timestamp of light modification it was updated to // then if current light timestamp is different than in terrain we need to update diffuse (into terrain) // now we should simply use diffuse from terrain // note: if terrain is being modified, we should clear its timestamp or immediately update diffuse if (global_refl_mode) { //done int lo_uv[] = { uv[dx][0],uv[dy][1], uv[dx][1],uv[dy][0], uv[dx][0],uv[dy][0] }; const int* lo[3] = { xyzf[dy + 1][dx], xyzf[dy][dx + 1], xyzf[dy][dx] }; shader.uv = lo_uv; shader.Diffuse(-xyzf[dy][dx][2] + xyzf[dy][dx + 1][2], -xyzf[dy][dx][2] + xyzf[dy + 1][dx][2]); Rasterize(ptr, w, h, &shader, lo, false); } else { int lo_uv[] = { uv[dx][0],uv[dy][0], uv[dx][1],uv[dy][0], uv[dx][0],uv[dy][1] }; const int* lo[3] = { xyzf[dy][dx], xyzf[dy][dx + 1], xyzf[dy + 1][dx] }; shader.uv = lo_uv; shader.Diffuse(xyzf[dy][dx][2] - xyzf[dy][dx + 1][2], xyzf[dy][dx][2] - xyzf[dy + 1][dx][2]); Rasterize(ptr, w, h, &shader, lo, false); } // .__. // \ | // \| // ' // upper triangle if (global_refl_mode) { //done int up_uv[] = { uv[dx][1],uv[dy][0], uv[dx][0],uv[dy][1], uv[dx][1],uv[dy][1] }; const int* up[3] = { xyzf[dy][dx + 1], xyzf[dy + 1][dx], xyzf[dy + 1][dx + 1] }; shader.uv = up_uv; shader.Diffuse(-xyzf[dy + 1][dx][2] + xyzf[dy + 1][dx + 1][2], -xyzf[dy][dx + 1][2] + xyzf[dy + 1][dx + 1][2]); Rasterize(ptr, w, h, &shader, up, false); } else { int up_uv[] = { uv[dx][1],uv[dy][1], uv[dx][0],uv[dy][1], uv[dx][1],uv[dy][0] }; const int* up[3] = { xyzf[dy + 1][dx + 1], xyzf[dy + 1][dx], xyzf[dy][dx + 1] }; shader.uv = up_uv; shader.Diffuse(xyzf[dy + 1][dx][2] - xyzf[dy + 1][dx + 1][2], xyzf[dy][dx + 1][2] - xyzf[dy + 1][dx + 1][2]); Rasterize(ptr, w, h, &shader, up, false); } } else { // lower triangle // . // /| // /_| // ' ' if (global_refl_mode) { // done int lo_uv[] = { uv[dx][0],uv[dy][0], uv[dx][1],uv[dy][1], uv[dx][1],uv[dy][0] }; const int* lo[3] = { xyzf[dy][dx], xyzf[dy + 1][dx + 1], xyzf[dy][dx + 1] }; shader.uv = lo_uv; shader.Diffuse(-xyzf[dy][dx][2] + xyzf[dy][dx + 1][2], -xyzf[dy][dx + 1][2] + xyzf[dy + 1][dx + 1][2]); Rasterize(ptr, w, h, &shader, lo, false); } else { int lo_uv[] = { uv[dx][1],uv[dy][0], uv[dx][1],uv[dy][1], uv[dx][0],uv[dy][0] }; const int* lo[3] = { xyzf[dy][dx + 1], xyzf[dy + 1][dx + 1], xyzf[dy][dx] }; shader.uv = lo_uv; shader.Diffuse(xyzf[dy][dx][2] - xyzf[dy][dx + 1][2], xyzf[dy][dx + 1][2] - xyzf[dy + 1][dx + 1][2]); Rasterize(ptr, w, h, &shader, lo, false); } // upper triangle // .__. // | / // |/ // ' if (global_refl_mode) { //done int up_uv[] = { uv[dx][1],uv[dy][1], uv[dx][0],uv[dy][0], uv[dx][0],uv[dy][1] }; const int* up[3] = { xyzf[dy + 1][dx + 1], xyzf[dy][dx], xyzf[dy + 1][dx] }; shader.uv = up_uv; shader.Diffuse(-xyzf[dy + 1][dx][2] + xyzf[dy + 1][dx + 1][2], -xyzf[dy][dx][2] + xyzf[dy + 1][dx][2]); Rasterize(ptr, w, h, &shader, up, false); } else { int up_uv[] = { uv[dx][0],uv[dy][1], uv[dx][0],uv[dy][0], uv[dx][1],uv[dy][1] }; const int* up[3] = { xyzf[dy + 1][dx], xyzf[dy][dx], xyzf[dy + 1][dx + 1] }; shader.uv = up_uv; shader.Diffuse(xyzf[dy + 1][dx][2] - xyzf[dy + 1][dx + 1][2], xyzf[dy][dx][2] - xyzf[dy + 1][dx][2]); Rasterize(ptr, w, h, &shader, up, false); } } } } if (!global_refl_mode) // disabled on reflections { // grid lines thru middle of patch? int mid = (HEIGHT_CELLS + 1) / 2; for (int lin = 0; lin <= HEIGHT_CELLS; lin++) { xyzf[lin][mid][2] += HEIGHT_SCALE / 2; if (mid != lin) xyzf[mid][lin][2] += HEIGHT_SCALE / 2; } for (int lin = 0; lin < HEIGHT_CELLS; lin++) { Bresenham(ptr, w, h, xyzf[lin][mid], xyzf[lin + 1][mid], 0x04); Bresenham(ptr, w, h, xyzf[mid][lin], xyzf[mid][lin + 1], 0x04); } } } void Renderer::RenderSprite(AnsiCell* ptr, int width, int height, Sprite* s, bool refl, int anim, int frame, int angle, int pos[3]) { // intersect frame with screen buffer int i = frame + angle * s->anim[anim].length; if (refl) i += s->anim[anim].length * s->angles; Sprite::Frame* f = s->atlas + s->anim[anim].frame_idx[i]; int dx = f->ref[0] / 2; int dy = f->ref[1] / 2; int left = pos[0] - dx; int right = left + f->width; int bottom = pos[1] - dy; int top = bottom + f->height; left = std::max(0, left); right = std::min(width, right); if (left >= right) return; bottom = std::max(0, bottom); top = std::min(height, top); if (bottom >= top) return; int sample_xy = 2 + 2 * (2 + 2 * width + 2); int sample_dx = 2; int sample_dy = 2 * (2 + 2 * width + 2); int sample_ofs[4] = { 0, 1, 2 + 2 * width + 2, 2 + 2 * width + 2 + 1 }; //static const float height_scale = HEIGHT_SCALE / 1.5; // WHY????? HS*DBL/ZOOM ? static const float ds = 2.0 * (/*zoom*/ 1.0 * /*scale*/ 3.0) / VISUAL_CELLS * 0.5 /*we're not dbl_wh*/; static const float dz_dy = HEIGHT_SCALE / (cos(30 * M_PI / 180) * HEIGHT_CELLS * ds); for (int y = bottom; y < top; y++) { int fy = y - pos[1] + dy; for (int x = left; x < right; x++) { int fx = x - pos[0] + dx; AnsiCell* dst = ptr + x + width * y; const AnsiCell* src = f->cell + fx + fy * f->width; int depth_passed = 0; Sample* s00 = sample_buffer.ptr + sample_xy + x * sample_dx + y * sample_dy; Sample* s01 = s00 + 1; Sample* s10 = s00 + 2 + 2 * width + 2; Sample* s11 = s10 + 1; // spare is in full blocks, ref in half! float height = (2 * src->spare + f->ref[2]) * 0.5 * dz_dy + pos[2]; // *height_scale + pos[2]; // transform! if (!refl && height >= water || refl && height <= water) { // early rejection if (src->bk == 255 && src->fg == 255 || (src->gl == 32 || src->gl == 0) && src->bk == 255 || src->gl == 219 && src->fg == 255) { // NOP } else if (src->fg == 254) // swoosh { // note: if both fg and bk are swoosh, // case is unified to fg swoosh with glyph 219 // during sprite loading! // sprites MUST be sorted by viewing dir (from furthest to nearest) // otherwise swoosh/smoke fx could get overwriten by further sprites! int mask = 0; if (height >= s00->height) { // s00->height = height; mask |= 1; } if (height >= s01->height) { // s01->height = height; mask |= 2; } if (height >= s10->height) { // s10->height = height; mask |= 4; } if (height >= s11->height) { // s11->height = height; mask |= 8; } if (!mask) continue; switch (src->gl) { case 219: // fullblock { if (mask == 15) { dst->bk = LightenColor(dst->bk); dst->fg = LightenColor(dst->fg); break; } // no break is intentional here } default: int fg = LightenColor(AverageGlyph(dst, mask)); if (src->bk == 255) dst->bk = AverageGlyph(dst, 0xF ^ mask); else dst->bk = src->bk; dst->fg = fg; dst->gl = src->gl; } } else if (src->bk == 254) // swoosh { int mask = 0; if (height >= s00->height) { s00->height = height; mask |= 1; } if (height >= s01->height) { s01->height = height; mask |= 2; } if (height >= s10->height) { s10->height = height; mask |= 4; } if (height >= s11->height) { s11->height = height; mask |= 8; } if (!mask) continue; switch (src->gl) { case 0: case 32: // spaces { if (mask == 15) { dst->bk = LightenColor(dst->bk); dst->fg = LightenColor(dst->fg); break; } // no break is intentional here } default: int bk = LightenColor(AverageGlyph(dst, 0xF ^ mask)); if (src->fg == 255) dst->fg = AverageGlyph(dst, mask); else dst->fg = src->fg; dst->bk = bk; dst->gl = src->gl; } } else // full block write with FG & BK if (src->bk != 255 && src->fg != 255) { int mask = 0; if (height >= s00->height) { s00->height = height; mask|=1; } if (height >= s01->height) { s01->height = height; mask |= 2; } if (height >= s10->height) { s10->height = height; mask |= 4; } if (height >= s11->height) { s11->height = height; mask |= 8; } if (mask == 0xF) { *dst = *src; } else if (mask == 0x0) { } else if (mask==0x3) // lower { dst->bk = AverageGlyph(dst, 0xC); dst->fg = AverageGlyph(src, 0x3); dst->gl = 220; } else if (mask == 0xC) // upper { dst->bk = AverageGlyph(dst, 0x3); dst->fg = AverageGlyph(src, 0xC); dst->gl = 223; } else if (mask == 0x5) // left { dst->bk = AverageGlyph(dst, 0xA); dst->fg = AverageGlyph(src, 0x5); dst->gl = 221; } else if (mask == 0xA) // right { dst->bk = AverageGlyph(dst, 0x5); dst->fg = AverageGlyph(src, 0xA); dst->gl = 222; } else { dst->bk = AverageGlyph(dst, 0xF-mask); dst->fg = AverageGlyph(dst, mask); if (mask == 1 || mask == 2 || mask == 4 || mask == 8) dst->gl = 176; else if (mask == 9 || mask == 6) dst->gl = 177; else dst->gl = 178; } } else // full block write with BK if (src->bk != 255 && (src->gl == 32 || src->gl == 0)) { int mask = 0; if (height >= s00->height) { s00->height = height; mask |= 1; } if (height >= s01->height) { s01->height = height; mask |= 2; } if (height >= s10->height) { s10->height = height; mask |= 4; } if (height >= s11->height) { s11->height = height; mask |= 8; } if (mask == 0xF) { dst->gl = 219; dst->fg = src->bk; } else if (mask == 0x0) { } else if (mask==0x3) // lower { dst->bk = AverageGlyph(dst, 0xC); dst->fg = src->bk; dst->gl = 220; } else if (mask == 0xC) // upper { dst->bk = AverageGlyph(dst, 0x3); dst->fg = src->bk; dst->gl = 223; } else if (mask == 0x5) // left { dst->bk = AverageGlyph(dst, 0xA); dst->fg = src->bk; dst->gl = 221; } else if (mask == 0xA) // right { dst->bk = AverageGlyph(dst, 0x5); dst->fg = src->bk; dst->gl = 222; } else { dst->bk = AverageGlyph(dst, 0xF-mask); dst->fg = src->bk; if (mask == 1 || mask == 2 || mask == 4 || mask == 8) dst->gl = 176; else if (mask == 9 || mask == 6) dst->gl = 177; else dst->gl = 178; } } else // full block write with FG if (src->fg != 255 && src->gl == 219) { int mask = 0; if (height >= s00->height) { s00->height = height; mask |= 1; } if (height >= s01->height) { s01->height = height; mask |= 2; } if (height >= s10->height) { s10->height = height; mask |= 4; } if (height >= s11->height) { s11->height = height; mask |= 8; } if (mask == 0xF) { dst->gl = ' ';// ooh 219; dst->fg = src->bk; dst->bk = src->fg; } else if (mask == 0x0) { } else if (mask==0x3) // lower { dst->bk = AverageGlyph(dst, 0xC); dst->fg = src->fg; dst->gl = 220; } else if (mask == 0xC) // upper { dst->bk = AverageGlyph(dst, 0x3); dst->fg = src->fg; dst->gl = 223; } else if (mask == 0x5) // left { dst->bk = AverageGlyph(dst, 0xA); dst->fg = src->fg; dst->gl = 221; } else if (mask == 0xA) // right { dst->bk = AverageGlyph(dst, 0x5); dst->fg = src->fg; dst->gl = 222; } else { dst->bk = AverageGlyph(dst, 0xF-mask); dst->fg = src->fg; if (mask == 1 || mask == 2 || mask == 4 || mask == 8) dst->gl = 176; else if (mask == 9 || mask == 6) dst->gl = 177; else dst->gl = 178; } } else // half block transparaent if (src->gl >= 220 && src->gl <= 223) { int mask = 0; if (src->bk == 255 && src->gl == 220 || src->fg == 255 && src->gl == 223) // lower { if (height >= s00->height) { s00->height = height; mask |= 1; } if (height >= s01->height) { s01->height = height; mask |= 2; } } else if (src->bk == 255 && src->gl == 221 || src->fg == 255 && src->gl == 222) // left { if (height >= s00->height) { s00->height = height; mask |= 1; } if (height >= s10->height) { s10->height = height; mask |= 4; } } else if (src->bk == 255 && src->gl == 222 || src->fg == 255 && src->gl == 221) // right { if (height >= s01->height) { s01->height = height; mask |= 2; } if (height >= s11->height) { s11->height = height; mask |= 8; } } else if (src->bk == 255 && src->gl == 223 || src->fg == 255 && src->gl == 220) // upper { if (height >= s10->height) { s10->height = height; mask |= 4; } if (height >= s11->height) { s11->height = height; mask |= 8; } } int color = src->bk == 255 ? src->fg : src->bk; if (mask == 0x0) { } else if (mask==0x3) // lower { dst->bk = AverageGlyph(dst, 0xC); dst->fg = color; dst->gl = 220; } else if (mask == 0xC) // upper { dst->bk = AverageGlyph(dst, 0x3); dst->fg = color; dst->gl = 223; } else if (mask == 0x5) // left { dst->bk = AverageGlyph(dst, 0xA); dst->fg = color; dst->gl = 221; } else if (mask == 0xA) // right { dst->bk = AverageGlyph(dst, 0x5); dst->fg = color; dst->gl = 222; } else { dst->bk = AverageGlyph(dst, 0xF-mask); dst->fg = src->fg; dst->gl = 176; } } else { // something else with transparency int mask = 0; if (height >= s00->height) { s00->height = height; mask|=1; } if (height >= s01->height) { s01->height = height; mask |= 2; } if (height >= s10->height) { s10->height = height; mask |= 4; } if (height >= s11->height) { s11->height = height; mask |= 8; } if (mask == 0xF) { dst->bk = AverageGlyph(dst, 0xF); dst->fg = src->fg; dst->gl = src->gl; } else if (mask == 0x0) { } else if (mask==0x3) // lower { dst->bk = AverageGlyph(dst, 0xC); dst->fg = AverageGlyph(src, 0x3); dst->gl = 220; } else if (mask == 0xC) // upper { dst->bk = AverageGlyph(dst, 0x3); dst->fg = AverageGlyph(src, 0xC); dst->gl = 223; } else if (mask == 0x5) // left { dst->bk = AverageGlyph(dst, 0xA); dst->fg = AverageGlyph(src, 0x5); dst->gl = 221; } else if (mask == 0xA) // right { dst->bk = AverageGlyph(dst, 0x5); dst->fg = AverageGlyph(src, 0xA); dst->gl = 222; } else { dst->bk = AverageGlyph(dst, 0xF-mask); dst->fg = AverageGlyph(dst, mask); if (mask == 1 || mask == 2 || mask == 4 || mask == 8) dst->gl = 176; else if (mask == 9 || mask == 6) dst->gl = 177; else dst->gl = 178; } } } /////////////////////////// /* if (src->bk != 255) { if (src->fg != 255) { // check if at least 2/4 samples passes depth test, update all 4 // ... if (!refl && height >= water || refl && height <= water) { if (height >= s00->height) { s00->height = height; depth_passed++; } if (height >= s01->height) { s01->height = height; depth_passed++; } if (height >= s10->height) { s10->height = height; depth_passed++; } if (height >= s11->height) { s11->height = height; depth_passed++; } } if (depth_passed >= 3) { *dst = *src; //s00->height = height; //s01->height = height; //s10->height = height; //s11->height = height; } } else { // check if at least 1/2 bk sample passes depth test, update both // ... if (!refl && height >= water || refl && height <= water) { if (height >= s00->height) { s00->height = height; depth_passed++; } if (height >= s01->height) { s01->height = height; depth_passed++; } if (height >= s10->height) { s10->height = height; depth_passed++; } if (height >= s11->height) { s11->height = height; depth_passed++; } } if (depth_passed >= 3) { if (dst->gl == 0xDC && src->gl == 0xDF || dst->gl == 0xDD && src->gl == 0xDE || dst->gl == 0xDF && src->gl == 0xDC || dst->gl == 0xDE && src->gl == 0xDD) { dst->fg = src->bk; } else { dst->bk = src->bk; dst->gl = src->gl; } // s00->height = height; // s01->height = height; // s10->height = height; // s11->height = height; } } } else { if (src->fg != 255) { // check if at least 1/2 fg samples passes depth test, update both // ... if (!refl && height >= water || refl && height <= water) { if (height >= s00->height) { s00->height = height; depth_passed++; } if (height >= s01->height) { s01->height = height; depth_passed++; } if (height >= s10->height) { s10->height = height; depth_passed++; } if (height >= s11->height) { s11->height = height; depth_passed++; } } if (depth_passed >= 3) { if (dst->gl == 0xDC && src->gl == 0xDF || dst->gl == 0xDD && src->gl == 0xDE || dst->gl == 0xDF && src->gl == 0xDC || dst->gl == 0xDE && src->gl == 0xDD) { dst->bk = src->fg; } else { dst->fg = src->fg; dst->gl = src->gl; } //s00->height = height; //s01->height = height; //s10->height = height; //s11->height = height; } } } */ } } } Renderer* CreateRenderer(uint64_t stamp) { Renderer* r = (Renderer*)malloc(sizeof(Renderer)); r->Init(); r->stamp = stamp; return r; } void DeleteRenderer(Renderer* r) { r->Free(); free(r); } Item** GetNearbyItems(Renderer* r) { return r->item_sort; } Inst** GetNearbyCharacters(Renderer* r) { return r->npc_sort; } int render_break_point[2] = { -1,-1 }; void Render(Renderer* r, uint64_t stamp, Terrain* t, World* w, float water, float zoom, float yaw, const float pos[3], const float lt[4], int width, int height, AnsiCell* ptr, Inst* inst, const int scene_shift[2], bool perspective) { r->perspective = perspective; if (inst) HideInst(inst); AnsiCell* out_ptr = ptr; double dt = stamp - r->stamp; r->stamp = stamp; r->pn_time += 0.02 * dt / 16666.0; // dt is in microsecs if (r->pn_time >= 1000000000000.0) r->pn_time = 0.0; #ifdef DBL float scale = 3.0; #else float scale = 1.5; #endif zoom *= scale; #ifdef DBL int dw = 4+2*width; int dh = 4+2*height; #else int dw = 1 + width + 1; int dh = 1 + height + 1; #endif float ds = 2*zoom / VISUAL_CELLS; if (!r->sample_buffer.ptr) { r->int_flag = true; for (int uv=0; uv<HEIGHT_CELLS; uv++) { r->patch_uv[uv][0] = uv * VISUAL_CELLS / HEIGHT_CELLS; r->patch_uv[uv][1] = (uv+1) * VISUAL_CELLS / HEIGHT_CELLS; }; r->sample_buffer.w = dw; r->sample_buffer.h = dh; r->sample_buffer.ptr = (Sample*)malloc(dw*dh * sizeof(Sample) * 2); // upper half is clear cache for (int cl = dw * dh; cl < 2*dw*dh; cl++) { r->sample_buffer.ptr[cl].height = -1000000; r->sample_buffer.ptr[cl].spare = 0x8; r->sample_buffer.ptr[cl].diffuse = 0xFF; r->sample_buffer.ptr[cl].visual = 0xC | (0xC << 5) | (0x1B << 10); } } else if (r->sample_buffer.w != dw || r->sample_buffer.h != dh) { r->int_flag = true; r->sample_buffer.w = dw; r->sample_buffer.h = dh; free(r->sample_buffer.ptr); r->sample_buffer.ptr = (Sample*)malloc(dw*dh * sizeof(Sample) * 2); // upper half is clear cache for (int cl = dw * dh; cl < 2 * dw*dh; cl++) { r->sample_buffer.ptr[cl].height = -1000000; r->sample_buffer.ptr[cl].spare = 0x8; r->sample_buffer.ptr[cl].diffuse = 0xFF; r->sample_buffer.ptr[cl].visual = 0xC | (0xC << 5) | (0x1B << 10); } } else { if (pos[0] != r->pos[0] || pos[1] != r->pos[1] || pos[2] != r->pos[2]) { r->int_flag = true; } if (yaw != r->yaw) { r->int_flag = false; } } if (r->perspective) // #if PERSPECTIVE_TEST { r->int_flag = false; } // #endif r->pos[0] = pos[0]; r->pos[1] = pos[1]; r->pos[2] = pos[2]; r->yaw = yaw; r->light[0] = lt[0]; r->light[1] = lt[1]; r->light[2] = lt[2]; r->light[3] = lt[3]; // memset(r->sample_buffer.ptr, 0x00, dw*dh * sizeof(Sample)); memcpy(r->sample_buffer.ptr, r->sample_buffer.ptr + dw * dh, dw*dh * sizeof(Sample)); // for every cell we need to know world's xy coord where z is at the water level static const double sin30 = sin(M_PI*30.0/180.0); static const double cos30 = cos(M_PI*30.0/180.0); /* static int frame = 0; frame++; if (frame == 200) frame = 0; water += HEIGHT_SCALE * 5 * sinf(frame*M_PI*0.01); */ // water integerificator (there's 4 instead of 2 because reflection goes 2x faster than water) int water_i = (int)floor(water / (HEIGHT_SCALE / (4 * ds * cos30))); water = (float)(water_i * (HEIGHT_SCALE / (4 * ds * cos30))); r->water = water; double a = yaw * M_PI / 180.0; double sinyaw = sin(a); double cosyaw = cos(a); double tm[16]; tm[0] = +cosyaw *ds; tm[1] = -sinyaw * sin30*ds; tm[2] = 0; tm[3] = 0; tm[4] = +sinyaw * ds; tm[5] = +cosyaw * sin30*ds; tm[6] = 0; tm[7] = 0; tm[8] = 0; tm[9] = +cos30/HEIGHT_SCALE*ds*HEIGHT_CELLS; tm[10] = 1.0; //+2./0xffff; tm[11] = 0; //tm[12] = dw*0.5 - (pos[0] * tm[0] + pos[1] * tm[4] + pos[2] * tm[8]) * HEIGHT_CELLS; //tm[13] = dh*0.5 - (pos[0] * tm[1] + pos[1] * tm[5] + pos[2] * tm[9]) * HEIGHT_CELLS; tm[12] = dw*0.5 - (pos[0] * tm[0] * HEIGHT_CELLS + pos[1] * tm[4] * HEIGHT_CELLS + pos[2] * tm[8]) + scene_shift[0]*2; tm[13] = dh*0.5 - (pos[0] * tm[1] * HEIGHT_CELLS + pos[1] * tm[5] * HEIGHT_CELLS + pos[2] * tm[9]) + scene_shift[1]*2; tm[14] = 0.0; //-1.0; tm[15] = 1.0; r->mul[0] = tm[0]; r->mul[1] = tm[1]; r->mul[2] = tm[4]; r->mul[3] = tm[5]; r->mul[4] = 0; r->mul[5] = tm[9]; // if yaw didn't change, make it INTEGRAL (and EVEN in case of DBL) r->add[0] = tm[12]; r->add[1] = tm[13] + 0.5; r->add[2] = tm[14]; if (r->int_flag) { int x = (int)floor(r->add[0] + 0.5); int y = (int)floor(r->add[1] + 0.5); #ifdef DBL x &= ~1; y &= ~1; #endif r->add[0] = (double)x; r->add[1] = (double)y; } double proj_tm[] = { r->mul[0], r->mul[1], r->mul[2], r->mul[3], r->mul[4], r->mul[5], r->add[0], r->add[1], r->add[2] }; int planes = 5; int view_flags = 0xAA; // should contain only bits that face viewing direction // sin/cos 30 are commented out to achieve 'architectural' perspective // (all vertical lines in world space remain vertical and parallel on screen) r->focal = fmax(dw,dh) * 2.0; //500; r->view_dir[0] = -sinyaw * 1; // cos30; r->view_dir[1] = cosyaw * 1; // cos30; r->view_dir[2] = 0; // -sin30; r->view_pos[0] = HEIGHT_CELLS * pos[0] - r->view_dir[0] * r->focal; r->view_pos[1] = HEIGHT_CELLS * pos[1] - r->view_dir[1] * r->focal; r->view_pos[2] = pos[2]; r->view_dir[0] /= r->focal; r->view_dir[1] /= r->focal; r->view_ofs[0] = dw/2 + scene_shift[0]*2; r->view_ofs[1] = dh/2 + scene_shift[1]*2; double clip_world[5][4]; /* double clip_left[4] = { 1, 0, 0, 1-0.2 }; double clip_right[4] = {-1, 0, 0, 1-0.2 }; double clip_bottom[4] = { 0, 1, 0, 1-0.2 }; double clip_top[4] = { 0,-1, 0, 1-0.2 }; // +1 for prespective */ double clip_left[4] = { 1, 0, 0, 1 }; double clip_right[4] = {-1, 0, 0, 1 }; double clip_bottom[4] = { 0, 1, 0, 1 }; double clip_top[4] = { 0,-1, 0, 1 }; // +1 for prespective double clip_water[4] = { 0, 0, 1, -((r->water-1)*2.0/0xffff - 1.0) }; double world_corner[2][4][4]; double* corner_ll = world_corner[0][0]; double* corner_lr = world_corner[0][1]; double* corner_ul = world_corner[0][2]; double* corner_ur = world_corner[0][3]; double focus_node[3] = { pos[0] + sinyaw * r->focal / HEIGHT_CELLS, pos[1] - cosyaw * r->focal / HEIGHT_CELLS, pos[2] + sin30 * r->focal / HEIGHT_CELLS * HEIGHT_SCALE }; if (r->perspective) // #if PERSPECTIVE_TEST { double neutral_plane[4] = { -sinyaw, cosyaw, 0, sinyaw*pos[0] - cosyaw*pos[1] }; double test = 0; double screen_corner[2][4][4]= { { {0+test,0+test,0,1}, {dw-test,0+test,0,1}, {0+test,dh-test,0,1}, {dw-test,dh-test,0,1} }, { {0+test,0+test,10,1}, {dw-test,0+test,10,1}, {0+test,dh-test,10,1}, {dw-test,dh-test,10,1} } }; double clip_tm[16]; Invert(tm,clip_tm); for (int c=0; c<4; c++) { // transform corners from screen to premultiplied world Product(clip_tm, screen_corner[0][c], world_corner[0][c]); Product(clip_tm, screen_corner[1][c], world_corner[1][c]); // from premultiplied to world world_corner[0][c][0] /= HEIGHT_CELLS; world_corner[0][c][1] /= HEIGHT_CELLS; world_corner[1][c][0] /= HEIGHT_CELLS; world_corner[1][c][1] /= HEIGHT_CELLS; // intersect resulting corner lines with neutral_plane world_corner[1][c][0] -= world_corner[0][c][0]; world_corner[1][c][1] -= world_corner[0][c][1]; world_corner[1][c][2] -= world_corner[0][c][2]; double a = -(DotProduct(neutral_plane,world_corner[0][c]) + neutral_plane[3])/DotProduct(neutral_plane, world_corner[1][c]); world_corner[0][c][0] += a * world_corner[1][c][0]; world_corner[0][c][1] += a * world_corner[1][c][1]; world_corner[0][c][2] += a * world_corner[1][c][2]; } // note: for reflected planes, simply reflect corners and focal node ( z' = 2*water-z ) // left ( focus, ll, ul ) PlaneFromPoints(focus_node, corner_ll, corner_ul, clip_world[0]); // right ( focus, ur, lr ) PlaneFromPoints(focus_node, corner_ur, corner_lr, clip_world[1]); // top ( focus, ul, ur ) PlaneFromPoints(focus_node, corner_ul, corner_ur, clip_world[2]); // bottom( focus, lr, ll ) PlaneFromPoints(focus_node, corner_lr, corner_ll, clip_world[3]); // water clip_world[4][0]=0; clip_world[4][1]=0; clip_world[4][2]=1; clip_world[4][3]=-clip_world[0][2]*(r->water-1); } else // #else // easier to use another transform for clipping { // somehow it works double clip_tm[16]; clip_tm[0] = +cosyaw / (0.5 * dw) * ds * HEIGHT_CELLS; clip_tm[1] = -sinyaw*sin30 / (0.5 * dh) * ds * HEIGHT_CELLS; clip_tm[2] = 0; clip_tm[3] = 0; clip_tm[4] = +sinyaw / (0.5 * dw) * ds * HEIGHT_CELLS; clip_tm[5] = +cosyaw*sin30 / (0.5 * dh) * ds * HEIGHT_CELLS; clip_tm[6] = 0; clip_tm[7] = 0; clip_tm[8] = 0; clip_tm[9] = +cos30 / HEIGHT_SCALE / (0.5 * dh) * ds * HEIGHT_CELLS; clip_tm[10] = +2. / 0xffff; clip_tm[11] = 0; clip_tm[12] = -(pos[0] * clip_tm[0] + pos[1] * clip_tm[4] + pos[2] * clip_tm[8] - (double)scene_shift[0]*2/width ); clip_tm[13] = -(pos[0] * clip_tm[1] + pos[1] * clip_tm[5] + pos[2] * clip_tm[9] - (double)scene_shift[1]*2/height); clip_tm[14] = -1.0; clip_tm[15] = 1.0; TransposeProduct(clip_tm, clip_left, clip_world[0]); TransposeProduct(clip_tm, clip_right, clip_world[1]); TransposeProduct(clip_tm, clip_bottom, clip_world[2]); TransposeProduct(clip_tm, clip_top, clip_world[3]); TransposeProduct(clip_tm, clip_water, clip_world[4]); } // #endif r->items = 0; r->npcs = 0; r->sprites = 0; QueryTerrain(t, planes, clip_world, view_flags, Renderer::RenderPatch, r); QueryWorldCB cb = { Renderer::RenderMesh , Renderer::RenderSprite }; QueryWorld(w, planes, clip_world, &cb, r); // player shadow // double inv_tm[16]; Invert(tm, r->inv_tm); double* inv_tm = r->inv_tm; Material* matlib = (Material*)GetMaterialArr(); int sh_x = width+1 +scene_shift[0]*2; // & ~1; for (int y = 0; y < dh; y++) { int left = sh_x-5; int right = sh_x+5; if (left<0) left=0; if (right>=dw) right=dw-1; for (int x = left; x <= right; x++) { Sample* s = r->sample_buffer.ptr + x + y * dw; if (abs(s->height - pos[2]) <= 64) { double screen_space[] = { (double)x,(double)y,s->height,1.0 }; double world_space[4]; Product(inv_tm, screen_space, world_space); double dx = world_space[0]/HEIGHT_CELLS - pos[0]; double dy = world_space[1]/HEIGHT_CELLS - pos[1]; double sq_xy = dx*dx + dy*dy; // de-elevation /* if (sq_xy <= 3.50 && s->height > pos[2]) { s->visual &= ~(1 << 15); // its fine even for rgb (15 bits) s->diffuse = 0; s->height -= HEIGHT_SCALE; } */ // continue; if (sq_xy <= 2.00) { int dz = (int)(2*(pos[2] - s->height) + 2*sq_xy); if (dz<180) dz=180; if (dz>180) dz=255; if (s->spare & 0x8) { s->diffuse = s->diffuse * dz / 255; } else { int mat = s->visual & 0xFF; int shd = (s->visual >> 8) & 0x7F; int r = (matlib[mat].shade[1][shd].bg[0] * 249 + 1014) >> 11; int g = (matlib[mat].shade[1][shd].bg[1] * 249 + 1014) >> 11; int b = (matlib[mat].shade[1][shd].bg[2] * 249 + 1014) >> 11; s->visual = r | (g << 5) | (b << 10); // if this is terrain sample, convert it to rgb first // s->visual = ; s->spare |= 0x8; s->spare &= ~0x44; s->diffuse = dz; } } } } } //////////////////// // REFL // once again for reflections tm[8] = -tm[8]; tm[9] = -tm[9]; tm[10] = -tm[10]; // let them simply go below 0 :) //tm[12] = dw*0.5 - (pos[0] * tm[0] + pos[1] * tm[4] + ((2 * water / HEIGHT_CELLS) - pos[2]) * tm[8]) * HEIGHT_CELLS; //tm[13] = dh*0.5 - (pos[0] * tm[1] + pos[1] * tm[5] + ((2 * water / HEIGHT_CELLS) - pos[2]) * tm[9]) * HEIGHT_CELLS; tm[12] = dw*0.5 - (pos[0] * tm[0] * HEIGHT_CELLS + pos[1] * tm[4] * HEIGHT_CELLS + ((2 * water) - pos[2]) * tm[8]) + scene_shift[0]*2; tm[13] = dh*0.5 - (pos[0] * tm[1] * HEIGHT_CELLS + pos[1] * tm[5] * HEIGHT_CELLS + ((2 * water) - pos[2]) * tm[9]) + scene_shift[1]*2; tm[14] = 2*r->water; r->mul[0] = tm[0]; r->mul[1] = tm[1]; r->mul[2] = tm[4]; r->mul[3] = tm[5]; r->mul[4] = 0; r->mul[5] = tm[9]; // if yaw didn't change, make it INTEGRAL (and EVEN in case of DBL) r->add[0] = tm[12]; r->add[1] = tm[13] + 0.5; r->add[2] = tm[14]; if (r->int_flag) { int x = (int)floor(r->add[0] + 0.5); int y = (int)floor(r->add[1] + 0.5); #ifdef DBL x &= ~1; y &= ~1; #endif r->add[0] = (double)x; r->add[1] = (double)y; } double refl_tm[] = { r->mul[0], r->mul[1], r->mul[2], r->mul[3], r->mul[4], r->mul[5], r->add[0], r->add[1], r->add[2] }; if (r->perspective) // #if PERSPECTIVE_TEST { corner_ll[2] = 2*water - corner_ll[2]; corner_lr[2] = 2*water - corner_lr[2]; corner_ul[2] = 2*water - corner_ul[2]; corner_ur[2] = 2*water - corner_ur[2]; focus_node[2] = 2*water - focus_node[2]; // left ( focus, ll, ul ) PlaneFromPoints(focus_node, corner_ul, corner_ll, clip_world[0]); // right ( focus, ur, lr ) PlaneFromPoints(focus_node, corner_lr, corner_ur, clip_world[1]); // top ( focus, ul, ur ) PlaneFromPoints(focus_node, corner_ur, corner_ul, clip_world[2]); // bottom( focus, lr, ll ) PlaneFromPoints(focus_node, corner_ll, corner_lr, clip_world[3]); clip_world[4][0]=0; clip_world[4][1]=0; clip_world[4][2]=1; // note: during refl, we again query ABOVE water! clip_world[4][3]=-clip_world[0][2]*(r->water-1); } else // #else { clip_water[2] = -1; // was +1 clip_water[3] = +((r->water+1)*-2.0 / 0xffff + 1.0); // was -((r->water-1)*2.0/0xffff - 1.0) // somehow it works double clip_tm[16]; clip_tm[0] = +cosyaw / (0.5 * dw) * ds * HEIGHT_CELLS; clip_tm[1] = -sinyaw * sin30 / (0.5 * dh) * ds * HEIGHT_CELLS; clip_tm[2] = 0; clip_tm[3] = 0; clip_tm[4] = +sinyaw / (0.5 * dw) * ds * HEIGHT_CELLS; clip_tm[5] = +cosyaw * sin30 / (0.5 * dh) * ds * HEIGHT_CELLS; clip_tm[6] = 0; clip_tm[7] = 0; clip_tm[8] = 0; clip_tm[9] = -cos30 / HEIGHT_SCALE / (0.5 * dh) * ds * HEIGHT_CELLS; clip_tm[10] = -2. / 0xffff; clip_tm[11] = 0; clip_tm[12] = -(pos[0] * clip_tm[0] + pos[1] * clip_tm[4] + (2 * r->water - pos[2]) * clip_tm[8] - (double)scene_shift[0] * 2 / width); clip_tm[13] = -(pos[0] * clip_tm[1] + pos[1] * clip_tm[5] + (2 * r->water - pos[2]) * clip_tm[9] - (double)scene_shift[1] * 2 / height); clip_tm[14] = +1.0; clip_tm[15] = 1.0; TransposeProduct(clip_tm, clip_left, clip_world[0]); TransposeProduct(clip_tm, clip_right, clip_world[1]); TransposeProduct(clip_tm, clip_bottom, clip_world[2]); TransposeProduct(clip_tm, clip_top, clip_world[3]); TransposeProduct(clip_tm, clip_water, clip_world[4]); } // #endif global_refl_mode = true; QueryTerrain(t, planes, clip_world, view_flags, Renderer::RenderPatch, r); QueryWorld(w, planes, clip_world, &cb, r); global_refl_mode = false; // clear and write new water ripples from player history position // do not emit wave if given z is greater than water level! memset(out_ptr, 0, sizeof(AnsiCell)*width*height); /* for (int h = 0; h < 64; h++) { float* xyz = hist[h]; if (xyz[2] < water) { // draw ellipse } } */ float ww_x, ww_y, ww_c, wx_x, wx_y, wx_c, wy_x, wy_y, wy_c; if (r->perspective) // #if PERSPECTIVE_TEST { // screen to world water coords conversion coefficients ww_x = r->view_dir[0]*tm[5] - r->view_dir[1]*tm[1]; ww_y = r->view_dir[1]*tm[0] - r->view_dir[0]*tm[4]; ww_c = tm[1]*tm[4] - tm[0]*tm[5]; wx_x = (r->view_pos[0]*tm[5]*r->view_dir[0] + r->view_dir[1]*(-r->view_ofs[1] + r->view_pos[1]*tm[5] + tm[13] + tm[9]*water)); wx_y = (r->view_pos[0]*tm[4]*r->view_dir[0] + r->view_dir[1]*(-r->view_ofs[0] + r->view_pos[1]*tm[4] + tm[12] + tm[8]*water)); wx_c = tm[5]*(-r->view_ofs[0] + tm[12] + tm[8]*water) + tm[4]*(r->view_ofs[1] - tm[13] - tm[9]*water); wy_x = (r->view_pos[1]*tm[1]*r->view_dir[1] + r->view_dir[0]*(-r->view_ofs[1] + r->view_pos[0]*tm[1] + tm[13] + tm[9]*water)); wy_y = (r->view_pos[1]*tm[0]*r->view_dir[1] + r->view_dir[0]*(-r->view_ofs[0] + r->view_pos[0]*tm[0] + tm[12] + tm[8]*water)); wy_c = tm[1]*(r->view_ofs[0] - tm[12] - tm[8]*water) + tm[0]*(-r->view_ofs[1] + tm[13] + tm[9]*water); /* e1 = cx == m00*wx + m10*wy + m20*wz + m30 e2 = cy == m01*wx + m11*wy + m21*wz + m31 e3 = cw == (wx-ex)*vx + (wy-ey)*vy e4 = (sx - dx) * cw + dx == cx e5 = (sy - dy) * cw + dy == cy sol = Solve[{e1, e2, e3, e4, e5}, {wx, wy, cx, cy, cw}] */ } // #endif Sample* src = r->sample_buffer.ptr + 2 + 2 * dw; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++, ptr++) { if (x == render_break_point[0] && y == render_break_point[1]) { render_break_point[0] = -1; render_break_point[1] = -1; } // given interpolated RGB -> round to 555, store it in visual // copy to diffuse to diffuse // mark mash 'auto-material' as 0x8 flag in spare // in post pass: // if sample has 0x8 flag // multiply rgb by diffuse (into 888 bg=fg) // apply color mixing with neighbours // if at least 1 sample have mesh bit in spare // - round mixed bg rgb to R5G5B5 and use auto_material[32K] -> {bg,fg,gl} // else apply gridlines etc. #ifdef DBL // average 4 backgrounds // mask 11 (something rendered) int spr[4] = { src[0].spare & 11, src[1].spare & 11, src[dw].spare & 11, src[dw + 1].spare & 11 }; int mat[4] = { src[0].visual & 0x00FF , src[1].visual & 0x00FF, src[dw].visual & 0x00FF, src[dw + 1].visual & 0x00FF }; int dif[4] = { src[0].diffuse , src[1].diffuse, src[dw].diffuse, src[dw + 1].diffuse }; int vis[4] = { src[0].visual, src[1].visual, src[dw].visual, src[dw + 1].visual }; // TODO: // every material must have 16x16 map and uses visual shade to select Y and lighting to select X // animated materials additionaly pre shifts and wraps visual shade by current time scaled by material's 'speed' int e_lo = (src[-dw].visual >> 15) + (src[-dw + 1].visual >> 15); int e_mi = (src[0].visual >> 15) + (src[1].visual >> 15); int e_hi = (src[dw].visual >> 15) + (src[dw + 1].visual >> 15); int elv; if (e_lo <= 1) { if (e_hi <= 1) elv = 3; // lo else elv = 2; // raise } else { if (e_hi <= 1) elv = 0; // lower else elv = 1; // hi } /* int shd = 0; // (src[0].visual >> 8) & 0x007F; int gl = matlib[mat[0]].shade[1][shd].gl; int bg[3] = { 0,0,0 }; int fg[3] = { 0,0,0 }; for (int i = 0; i < 4; i++) { bg[0] += matlib[mat[i]].shade[1][shd].bg[0] * dif[i]; bg[1] += matlib[mat[i]].shade[1][shd].bg[1] * dif[i]; bg[2] += matlib[mat[i]].shade[1][shd].bg[2] * dif[i]; fg[0] += matlib[mat[i]].shade[1][shd].fg[0] * dif[i]; fg[1] += matlib[mat[i]].shade[1][shd].fg[1] * dif[i]; fg[2] += matlib[mat[i]].shade[1][shd].fg[2] * dif[i]; } */ int shd = (dif[0] + dif[1] + dif[2] + dif[3] + 17 * 2) / (17 * 4); // 17: FF->F, 4: avr int gl = matlib[mat[0]].shade[elv][shd].gl; int bg[3] = { 0,0,0 }; // 4 int fg[3] = { 0,0,0 }; int half_h[2][2] = { {0,1},{2,3} }; int half_v[2][2] = { {0,2},{1,3} }; int bg_h[2][3] = { { 0,0,0 },{ 0,0,0 } }; // 0+1 \ 2+3 int bg_v[2][3] = { { 0,0,0 },{ 0,0,0 } }; // 0+2 | 1+3 bool use_auto_mat = false; int err_h = 0; int err_v = 0; // if cell contains both refl and non-refl terrain enable auto-mat bool has_refl = (spr[0] & 3) == 3 || (spr[1] & 3) == 3 || (spr[2] & 3) == 3 || (spr[3] & 3) == 3; bool has_norm = (spr[0] & 3) == 1 || (spr[1] & 3) == 1 || (spr[2] & 3) == 1 || (spr[3] & 3) == 1; if (has_refl && has_norm) { use_auto_mat = true; } for (int m = 0; m < 2; m++) { for (int i = 0; i < 4; i++) { //if (spr[i]) { if (spr[i] & 0x8) { int r = ((vis[i] & 0x1F) * 527 + 23) >> 6; int g = (((vis[i] >> 5) & 0x1F) * 527 + 23) >> 6; int b = (((vis[i] >> 10) & 0x1F) * 527 + 23) >> 6; if ((spr[i] & 0x3) == 3) { r = r * dif[i] / 400; g = g * dif[i] / 400; b = b * dif[i] / 400; } else { r = r * dif[i] / 255; g = g * dif[i] / 255; b = b * dif[i] / 255; } if (i == 0 || i == 1) { if (m) { err_h += abs(bg_h[0][0] - 4 * r); err_h += abs(bg_h[0][1] - 4 * g); err_h += abs(bg_h[0][2] - 4 * b); } else { bg_h[0][0] += 2 * r; bg_h[0][1] += 2 * g; bg_h[0][2] += 2 * b; } } if (i == 2 || i == 3) { if (m) { err_h += abs(bg_h[1][0] - 4 * r); err_h += abs(bg_h[1][1] - 4 * g); err_h += abs(bg_h[1][2] - 4 * b); } else { bg_h[1][0] += 2 * r; bg_h[1][1] += 2 * g; bg_h[1][2] += 2 * b; } } if (i == 0 || i == 2) { if (m) { err_v += abs(bg_v[0][0] - 4 * r); err_v += abs(bg_v[0][1] - 4 * g); err_v += abs(bg_v[0][2] - 4 * b); } else { bg_v[0][0] += 2 * r; bg_v[0][1] += 2 * g; bg_v[0][2] += 2 * b; } } if (i == 1 || i == 3) { if (m) { err_v += abs(bg_v[1][0] - 4 * r); err_v += abs(bg_v[1][1] - 4 * g); err_v += abs(bg_v[1][2] - 4 * b); } else { bg_v[1][0] += 2 * r; bg_v[1][1] += 2 * g; bg_v[1][2] += 2 * b; } } if (!m) { bg[0] += r; bg[1] += g; bg[2] += b; use_auto_mat = true; } } else { int s = dif[i] / 17; int r = matlib[mat[i]].shade[elv][s].bg[0]; int g = matlib[mat[i]].shade[elv][s].bg[1]; int b = matlib[mat[i]].shade[elv][s].bg[2]; if ((spr[i] & 0x3) == 3) { r = r * 255 / 400; g = g * 255 / 400; b = b * 255 / 400; } if (i == 0 || i == 1) { if (m) { err_h += abs(bg_h[0][0] - 4 * r); err_h += abs(bg_h[0][1] - 4 * g); err_h += abs(bg_h[0][2] - 4 * b); } else { bg_h[0][0] += 2 * r; bg_h[0][1] += 2 * g; bg_h[0][2] += 2 * b; } } if (i == 2 || i == 3) { if (m) { err_h += abs(bg_h[1][0] - 4 * r); err_h += abs(bg_h[1][1] - 4 * g); err_h += abs(bg_h[1][2] - 4 * b); } else { bg_h[1][0] += 2*r; bg_h[1][1] += 2*g; bg_h[1][2] += 2*b; } } if (i == 0 || i == 2) { if (m) { err_v += abs(bg_v[0][0] - 4 * r); err_v += abs(bg_v[0][1] - 4 * g); err_v += abs(bg_v[0][2] - 4 * b); } else { bg_v[0][0] += 2*r; bg_v[0][1] += 2*g; bg_v[0][2] += 2*b; } } if (i == 1 || i == 3) { if (m) { err_v += abs(bg_v[1][0] - 4 * r); err_v += abs(bg_v[1][1] - 4 * g); err_v += abs(bg_v[1][2] - 4 * b); } else { bg_v[1][0] += 2*r; bg_v[1][1] += 2*g; bg_v[1][2] += 2*b; } } if (!m) { bg[0] += r; bg[1] += g; bg[2] += b; if ((spr[i] & 0x3) == 0x3) { fg[0] += matlib[mat[i]].shade[elv][s].fg[0] * 255 / 400; fg[1] += matlib[mat[i]].shade[elv][s].fg[1] * 255 / 400; fg[2] += matlib[mat[i]].shade[elv][s].fg[2] * 255 / 400; } else { fg[0] += matlib[mat[i]].shade[elv][s].fg[0]; fg[1] += matlib[mat[i]].shade[elv][s].fg[1]; fg[2] += matlib[mat[i]].shade[elv][s].fg[2]; } } } } } } if (use_auto_mat) { // WORKS REALY WELL! bool vh_near = true; if (err_h * 1000 < err_v * 999) { vh_near = false; // _FG_ // BK ptr->gl = 0xDF; int auto_mat_lo = 3 * ((bg_h[0][0]+20) / 33 + 32 * ((bg_h[0][1]+20) / 33) + 32 * 32 * ((bg_h[0][2]+20) / 33)); int auto_mat_hi = 3 * ((bg_h[1][0]+20) / 33 + 32 * ((bg_h[1][1]+20) / 33) + 32 * 32 * ((bg_h[1][2]+20) / 33)); ptr->bk = auto_mat[auto_mat_lo + 0]; ptr->fg = auto_mat[auto_mat_hi + 0]; } else if (err_v * 1000 < err_h * 999) { vh_near = false; // B|F // K|G ptr->gl = 0xDE; int auto_mat_lt = 3 * ((bg_v[0][0]+20) / 33 + 32 * ((bg_v[0][1]+20) / 33) + 32 * 32 * ((bg_v[0][2]+20) / 33)); int auto_mat_rt = 3 * ((bg_v[1][0]+20) / 33 + 32 * ((bg_v[1][1]+20) / 33) + 32 * 32 * ((bg_v[1][2]+20) / 33)); ptr->bk = auto_mat[auto_mat_lt + 0]; ptr->fg = auto_mat[auto_mat_rt + 0]; } if (ptr->bk == ptr->fg || vh_near) { // avr4 int auto_mat_idx = 3 * (bg[0] / 33 + 32 * (bg[1] / 33) + 32 * 32 * (bg[2] / 33)); ptr->gl = auto_mat[auto_mat_idx + 2]; ptr->bk = auto_mat[auto_mat_idx + 0]; ptr->fg = auto_mat[auto_mat_idx + 1]; ptr->spare = 0xFF; } } else { int bk_rgb[3] = { (bg[0] + 102) / 204, (bg[1] + 102) / 204, (bg[2] + 102) / 204 }; ptr->gl = gl; ptr->bk = 16 + 36*bk_rgb[0] + bk_rgb[1] * 6 + bk_rgb[2]; ptr->fg = 16 + (36*((fg[0] + 102) / 204) + (((fg[1] + 102) / 204) * 6) + ((fg[2] + 102) / 204)); ptr->spare = 0xFF; // collect line bits if (elv == 3) // only low elevation { int linecase = ((src[0].spare & 0x4) >> 2) | ((src[1].spare & 0x4) >> 1) | (src[dw].spare & 0x4) | ((src[dw + 1].spare & 0x4) << 1); static const int linecase_glyph[] = { 0, ',', ',', ',', '`', ';', ';', ';', '`', ';', ';', ';', '`', ';', ';', ';' }; if (linecase) ptr->gl = linecase_glyph[linecase]; } if (elv == 1 || elv == 3) // no elev change { // silhouette repetitoire: _-/\| (should not be used by materials?) float z_hi = src[dw].height + src[dw + 1].height; float z_lo = src[0].height + src[1].height; float z_pr = src[-dw].height + src[1 - dw].height; float minus = z_lo - z_hi; float under = z_pr - z_lo; static const float thresh = 1 * HEIGHT_SCALE; if (minus > under) { if (minus > thresh) { ptr->gl = 0xC4; // '-' bk_rgb[0] = std::max(0, bk_rgb[0] - 1); bk_rgb[1] = std::max(0, bk_rgb[1] - 1); bk_rgb[2] = std::max(0, bk_rgb[2] - 1); ptr->fg = 16 + 36 * bk_rgb[0] + bk_rgb[1] * 6 + bk_rgb[2]; } } else { if (under > thresh) { ptr->gl = 0x5F; // '_' bk_rgb[0] = std::max(0, bk_rgb[0] - 1); bk_rgb[1] = std::max(0, bk_rgb[1] - 1); bk_rgb[2] = std::max(0, bk_rgb[2] - 1); ptr->fg = 16 + 36 * bk_rgb[0] + bk_rgb[1] * 6 + bk_rgb[2]; } } } } int linecase = ((src[0].spare & 0x40) >> 6) | ((src[1].spare & 0x40) >> 5) | ((src[dw].spare & 0x40)>>4) | ((src[dw + 1].spare & 0x40) >> 3); static const int linecase_glyph[] = { 0, ',', ',', ',', '`', ';', ';', ';', '`', ';', ';', ';', '`', ';', ';', ';' }; if (linecase) { ptr->gl = linecase_glyph[linecase]; ptr->fg = 16; } else if (src[0].height < water && src[1].height < water && src[dw].height < water && src[dw+1].height < water) { double w[4]; if (r->perspective) // #if PERSPECTIVE_TEST { float sx_dx = 2.0*x - r->view_ofs[0]; float sy_dy = 2.0*y - r->view_ofs[1]; float ww = (sx_dx*ww_x + sy_dy*ww_y + ww_c); if (ww<0) { ww = 1.0/ww; float wx = ww * (wx_c + wx_x * sx_dx - wx_y * sy_dy); float wy = ww * (wy_c - wy_x * sx_dx + wy_y * sy_dy); w[0] = wx; w[1] = wy; } else { ptr->gl = ' '; src += 2; continue; } } else // #else { double s[4] = { 2.0*x, 2.0*y, water, 1.0 }; Product(inv_tm, s, w); // convert from screen to world w[0] = round(w[0]); w[1] = round(w[1]); } // #endif double d = r->pn.octaveNoise0_1(w[0] * 0.05, w[1] * 0.05, r->pn_time, 4); int id = (int)(d * 5) - 2; if (id < -1) id = 2; if (id > 1) id = -2; if (id > 0) { int c = ptr->fg - 16; int cr = c / 36; c -= cr * 36; int cg = c / 6; c -= cr * 6; int cb = c; if (cr < 5 && cg < 5 /*&& cb < 5*/) { if (cb < 5) ptr->fg += 1 + 6 + 36; else ptr->fg += 6 + 36; } } else if (id < 0) { int c = ptr->fg - 16; int cr = c / 36; c -= cr * 36; int cg = c / 6; c -= cr * 6; int cb = c; if (cr > 0 && cg > 0 /*&& cb > 0*/) { if (cb > 0) ptr->fg -= 1 + 6 + 36; else ptr->fg -= 6 + 36; } } } // xterm conv src += 2; #else int mat = src[0].visual & 0x00FF; int shd = 0; // (src[0].visual >> 8) & 0x007F; int elv = 0; // (src[0].visual >> 15) & 0x0001; // fill from material const MatCell* cell = &(matlib[mat].shade[1][shd]); const uint8_t* bg = matlib[mat].shade[1][shd].bg; const uint8_t* fg = matlib[mat].shade[1][shd].fg; ptr->gl = cell->gl; ptr->bk = 16 + (((bg[0] + 25) / 51) + (((bg[1] + 25) / 51) * 6) + (((bg[2] + 25) / 51) * 36)); ptr->fg = 16 + (((fg[0] + 25) / 51) + (((fg[1] + 25) / 51) * 6) + (((fg[2] + 25) / 51) * 36)); ptr->spare = 0xFF; src++; #endif } #ifdef DBL src += 4 + dw; #else src += 2; #endif } #if 0 int ang = (int)floor((player_dir-yaw) * player_sprite->angles / 360.0f + 0.5f); /* if (ang < 0) ang += player_sprite->angles * (1 - ang / player_sprite->angles); else if (ang >= player_sprite->angles) ang -= ang / player_sprite->angles; */ ang = ang >= 0 ? ang % player_sprite->angles : (ang % player_sprite->angles + player_sprite->angles) % player_sprite->angles; int anim = 1; // PLAYER int fr = player_stp/1024 % player_sprite->anim[anim].length; // WOLFIE // fr = player_stp/512 % player_sprite->anim[anim].length; if (player_stp < 0) { anim = 0; fr = 0; } static const float dy_dz = (cos(30 * M_PI / 180) * HEIGHT_CELLS * (ds / 2/*we're not dbl_wh*/)) / HEIGHT_SCALE; int player_pos[3] = { width / 2, height / 2, (int)floor(pos[2]+0.5) + HEIGHT_SCALE / 4 }; static uint64_t attack_tim = stamp; static int attack_frm = 18; if (anim == 0 ) { int attack_ofs = (stamp - attack_tim) / 16667; // scale by microsec to 60 fps attack_frm += attack_ofs; attack_tim += (uint64_t)attack_ofs * 16667; int sub_frm = (attack_frm % 80); /* static int attack_anim[30] = { 0,0, 1,1, 2,2, 3,3, 4,4, 4,4,4,4, 3,3,3,3, 2,2,2,2, 1,1,1,1, 0,0,0,0 }; */ // sleep/wake static int attack_anim[80] = { 0,0,0,0, 1,1,1,1, 2,2,2,2, 3,3,3,3, 4,4,4,4, 4,4,4,4, 4,4,4,4, 4,4,4,4, 4,4,4,4, 4,4,4,4, 4,4,4,4, 3,3,3,3, 2,2,2,2, 1,1,1,1, 0,0,0,0, }; if (sub_frm >= sizeof(attack_anim)/sizeof(int)) sub_frm = 0; else sub_frm = attack_anim[sub_frm]; fr = sub_frm; int pos_push[3] = { player_pos[0] , player_pos[1] , player_pos[2] }; // player_pos[1] = height / 2 + (int)floor((2 * r->water - pos[2]) * dy_dz + 0.5); player_pos[1] = height / 2 - (int)floor(2 * (pos[2] - r->water)*dy_dz + 0.5); // player_pos[2] = (int)floor(2 * r->water - pos[2] + 0.5); player_pos[2] = (int)floor(2 * r->water - pos[2] + 0.5) - HEIGHT_SCALE / 4; r->RenderSprite(out_ptr, width, height, attack_sprite, true, anim, fr, ang, player_pos); r->RenderSprite(out_ptr, width, height, attack_sprite, false, anim, fr, ang, pos_push); } else { // rewind attack_tim = stamp; attack_frm = 18; r->RenderSprite(out_ptr, width, height, player_sprite, false, anim, fr, ang, player_pos); // player_pos[1] = height / 2 + (int)floor((2 * r->water - pos[2]) * dy_dz + 0.5); player_pos[1] = height / 2 - (int)floor(2 * (pos[2] - r->water)*dy_dz + 0.5); // player_pos[2] = (int)floor(2 * r->water - pos[2] + 0.5); player_pos[2] = (int)floor(2 * r->water - pos[2] + 0.5) - HEIGHT_SCALE / 4; r->RenderSprite(out_ptr, width, height, player_sprite, true, anim, fr, ang, player_pos); } #else if (inst) { float pos[3]; float dir; int anim; int frame; int reps[4]; Sprite* sprite = GetInstSprite(inst, pos, &dir, &anim, &frame, reps); int ang = (int)floor((dir - yaw) * sprite->angles / 360.0f + 0.5f); ang = ang >= 0 ? ang % sprite->angles : (ang % sprite->angles + sprite->angles) % sprite->angles; { int player_pos[3]= { width / 2 + scene_shift[0], height / 2 + scene_shift[1], (int)floor(pos[2] + 0.5) + HEIGHT_SCALE / 4 }; r->RenderSprite(out_ptr, width, height, sprite, false, anim, frame, ang, player_pos); } { static const float dy_dz = (cos(30 * M_PI / 180) * HEIGHT_CELLS * (ds / 2/*we're not dbl_wh*/)) / HEIGHT_SCALE; int player_pos[3] = { width / 2 + scene_shift[0], height / 2 - (int)floor(2 * (pos[2] - r->water)*dy_dz + 0.5) + scene_shift[1], (int)floor(2 * r->water - pos[2] + 0.5) - HEIGHT_SCALE / 4 }; r->RenderSprite(out_ptr, width, height, sprite, true, anim, frame, ang, player_pos); } } #endif qsort(r->sprites_alloc, r->sprites, sizeof(SpriteRenderBuf), SpriteRenderBuf::FarToNear); // lets check drawing sprites in world space for (int s=0; s<r->sprites; s++) { SpriteRenderBuf* buf = r->sprites_alloc + s; // IT IS PERFECTLY STICKED TO WORLD! // it may not perectly stick to character but its fine! (its kinda character is not perfectly positioned) // todo: use buf->alpha (perspective fades) if (buf->character && !buf->refl && buf->character->req.action!=ACTION::DEAD) { // render mini-hp_bar // check if sprite has odd or even width, // paint accordingly bar with 5 or 6 width int dy = 10; int y = buf->s_pos[1] + dy; static const float ds = 2.0 * (/*zoom*/ 1.0 * /*scale*/ 3.0) / VISUAL_CELLS * 0.5 /*we're not dbl_wh*/; static const float dz_dy = HEIGHT_SCALE / (cos(30 * M_PI / 180) * HEIGHT_CELLS * ds); float t = dy * dz_dy + buf->s_pos[2]; int lt_red = 16 + 0 + 0*6 + 5*36; // 102,0,0 int lt_orange = 16 + 0 + 2*6 + 5*36; int dk_red = 16 + 0 + 0 * 6 + 3 * 36; // 102,0,0 int dk_orange = 16 + 0 + 1 * 6 + 3 * 36; uint8_t fg = buf->character->clr ? lt_orange : lt_red; uint8_t bk = buf->character->clr ? dk_orange : dk_red; AnsiCell ac; ac.bk = bk; ac.fg = fg; if (y >= 0 && y < height) { for (int bx = -2; bx <= 2; bx++) { int x = bx + buf->s_pos[0]; // calc average 2x2 height // int height = if (x >= 0 && x < width) { Sample* test_ll = r->sample_buffer.ptr + (2 * y + 0) * (2 * width + 4) + 2 * x + 2; Sample* test_lr = r->sample_buffer.ptr + (2 * y + 0) * (2 * width + 4) + 2 * x + 3; Sample* test_ul = r->sample_buffer.ptr + (2 * y + 1) * (2 * width + 4) + 2 * x + 2; Sample* test_ur = r->sample_buffer.ptr + (2 * y + 1) * (2 * width + 4) + 2 * x + 3; if (!test_ul->DepthTest_RO(t) && !test_ur->DepthTest_RO(t) && !test_ll->DepthTest_RO(t) && !test_lr->DepthTest_RO(t)) { continue; } bool l = (bx + 2)*buf->character->MAX_HP * 2 + 0 < buf->character->HP * 10; bool r = (bx + 2)*buf->character->MAX_HP * 2 + buf->character->MAX_HP < buf->character->HP * 10; if (r) ac.gl = 219; // full else if (l) ac.gl = 221; // half else ac.gl = ' '; // none out_ptr[x+width*y] = ac; } } } } int frame = buf->frame; int anim = buf->anim; r->RenderSprite(out_ptr, width, height, buf->sprite, buf->refl, anim, frame, buf->angle, buf->s_pos); } // restore positive projection for ProjectCoords func (now they are for reflection). r->mul[0] = proj_tm[0]; r->mul[1] = proj_tm[1]; r->mul[2] = proj_tm[2]; r->mul[3] = proj_tm[3]; r->mul[4] = proj_tm[4]; r->mul[5] = proj_tm[5]; r->add[0] = proj_tm[6]; r->add[1] = proj_tm[7]; r->add[2] = proj_tm[8]; // render arrows, from player, other players and all npcs // how to access human from inst? Character* ch = player_head; while (ch) { Human* h = 0; if (ch->req.kind == SpriteReq::HUMAN) h = (Human*)ch; if (h->shooting) { if (stamp - h->shoot_stamp > 3000000) { h->shooting = false; h->shoot_target = 0; } float arrow_speed = 1000; // 2000 world units / sec float shutter_time = 0.05; // 1/20 sec shutter speed float head_time = (stamp - h->shoot_stamp) / 1000000.0f; float tail_time = head_time - shutter_time; // normalized dir (note different xy and z scaling!) float dir[3] = { h->shoot_to[0] - h->shoot_from[0], h->shoot_to[1] - h->shoot_from[1], h->shoot_to[2] - h->shoot_from[2], }; dir[2] /= HEIGHT_SCALE; float len = sqrtf(dir[0] * dir[0] + dir[1] * dir[1] + dir[2] * dir[2]); dir[0] /= len; dir[1] /= len; dir[2] /= len; dir[2] *= HEIGHT_SCALE; if (tail_time < 0) tail_time = 0; if (head_time * arrow_speed > len) head_time = len / arrow_speed; if (tail_time * arrow_speed > len) { if (h->shoot_target) { int hp = h->shoot_target->HP; h->shoot_target->HP -= rand() % 50; float dx = h->shoot_target->pos[0] - h->pos[0]; float dy = h->shoot_target->pos[1] - h->pos[1]; float d = 1.0f / sqrtf(dx*dx + dy * dy); h->shoot_target->impulse[0] += dx * d; h->shoot_target->impulse[1] += dy * d; if (h->shoot_target->HP <= 0) { if (h->shoot_target->req.mount != MOUNT::NONE) { ((Human*)h->shoot_target)->SetMount(MOUNT::NONE); h->target->HP = hp; } else { h->shoot_target->dir = atan2(-dy, -dx) * 180 / M_PI /* + phys->yaw == ZERO*/ + 90; Physics* p = (Physics*)h->shoot_target->data; SetPhysicsDir(p, h->shoot_target->dir); h->shoot_target->HP = 0; h->shoot_target->SetActionFall(stamp); } } } h->shooting = false; h->shoot_target = 0; } if (h->shooting) { float head_pos[3] = { h->shoot_from[0] + dir[0] * head_time * arrow_speed, h->shoot_from[1] + dir[1] * head_time * arrow_speed, h->shoot_from[2] + dir[2] * head_time * arrow_speed, }; float tail_pos[3] = { h->shoot_from[0] + dir[0] * tail_time * arrow_speed, h->shoot_from[1] + dir[1] * tail_time * arrow_speed, h->shoot_from[2] + dir[2] * tail_time * arrow_speed, }; // here we must write directly to AnsiCell buf but test height values from Samples! int from[3]; int to[3]; if (perspective) { bool ok = true; float d_from, d_to; if (ok) { float vx = head_pos[0], vy = head_pos[1], vz = head_pos[2]; float eye_to_vtx[3] = { vx - r->view_pos[0], vy - r->view_pos[1], vz - r->view_pos[2], }; float viewer_dist = DotProduct(eye_to_vtx, r->view_dir); if (viewer_dist <= 0) ok = false; else { float fx = r->mul[0] * vx + r->mul[2] * vy + r->add[0]; float fy = r->mul[1] * vx + r->mul[3] * vy + r->mul[5] * vz + r->add[1]; float recp_dist = 1.0 / viewer_dist; d_from = recp_dist; fx = (fx - r->view_ofs[0]) * recp_dist + r->view_ofs[0]; fy = (fy - r->view_ofs[1]) * recp_dist + r->view_ofs[1]; int tx = (int)floorf(fx + 0.5f); int ty = (int)floorf(fy + 0.5f); from[0] = (tx - 1) >> 1; from[1] = (ty - 1) >> 1; from[2] = (int)floorf(head_pos[2] + 0.5) + HEIGHT_SCALE / 2; } } if (ok) { float vx = tail_pos[0], vy = tail_pos[1], vz = tail_pos[2]; float eye_to_vtx[3] = { vx - r->view_pos[0], vy - r->view_pos[1], vz - r->view_pos[2], }; float viewer_dist = DotProduct(eye_to_vtx, r->view_dir); if (viewer_dist <= 0) ok = false; else { float fx = r->mul[0] * vx + r->mul[2] * vy + r->add[0]; float fy = r->mul[1] * vx + r->mul[3] * vy + r->mul[5] * vz + r->add[1]; float recp_dist = 1.0 / viewer_dist; d_to = recp_dist; fx = (fx - r->view_ofs[0]) * recp_dist + r->view_ofs[0]; fy = (fy - r->view_ofs[1]) * recp_dist + r->view_ofs[1]; int tx = (int)floorf(fx + 0.5f); int ty = (int)floorf(fy + 0.5f); to[0] = (tx - 1) >> 1; to[1] = (ty - 1) >> 1; to[2] = (int)floorf(tail_pos[2] + 0.5) + HEIGHT_SCALE / 2; } } if (ok) { PerspectiveCorrectCellLine(r->sample_buffer.ptr, out_ptr, width, height, from, to, d_from, d_to, 7, 231/*231*/); } } else { int tx = (int)floor(r->mul[0] * head_pos[0] + r->mul[2] * head_pos[1] + 0.5 + r->add[0]); int ty = (int)floor(r->mul[1] * head_pos[0] + r->mul[3] * head_pos[1] + r->mul[5] * head_pos[2] + 0.5 + r->add[1]); // convert from samples to cells from[0] = (tx - 1) >> 1; from[1] = (ty - 1) >> 1; from[2] = (int)floorf(h->shoot_from[2] + 0.5) + HEIGHT_SCALE / 2; tx = (int)floor(r->mul[0] * tail_pos[0] + r->mul[2] * tail_pos[1] + 0.5 + r->add[0]); ty = (int)floor(r->mul[1] * tail_pos[0] + r->mul[3] * tail_pos[1] + r->mul[5] * tail_pos[2] + 0.5 + r->add[1]); // convert from samples to cells to[0] = (tx - 1) >> 1; to[1] = (ty - 1) >> 1; to[2] = (int)floorf(tail_pos[2] + 0.5) + HEIGHT_SCALE / 2; CellLine(r->sample_buffer.ptr, out_ptr, width, height, from, to, 7, 231/*231*/); } } } ch = ch->next; } /* int invpos[3] = { 1,1,0 }; if (inventory_sprite) r->RenderSprite(out_ptr, width, height, inventory_sprite, false, 0, 0, 0, invpos); */ r->item_sort[r->items] = 0; // now we should send request to server for changing exclusive item list // and return only those that are already confirmed as exclusive and still visible now // (maybe we should introduce few frames window until we request de-exclusivity?) if (inst) ShowInst(inst); } bool ProjectCoords(Renderer* r, const float pos[3], int view[3]) { // TODO: add perspective! float w_pos[3] = { pos[0] * HEIGHT_CELLS, pos[1] * HEIGHT_CELLS, pos[2] }; if (r->perspective) { float vx = w_pos[0], vy = w_pos[1], vz = w_pos[2]; float viewer_dist; // {vx,vy,vz} r->pos float eye_to_vtx[3] = { vx - r->view_pos[0], vy - r->view_pos[1], vz - r->view_pos[2], }; viewer_dist = DotProduct(eye_to_vtx, r->view_dir); if (viewer_dist <= 0) return false; float fx = r->mul[0] * vx + r->mul[2] * vy + r->add[0]; float fy = r->mul[1] * vx + r->mul[3] * vy + r->mul[5] * vz + r->add[1]; float recp_dist = 1.0 / viewer_dist; fx = (fx - r->view_ofs[0]) * recp_dist + r->view_ofs[0]; fy = (fy - r->view_ofs[1]) * recp_dist + r->view_ofs[1]; int tx = (int)floorf(fx + 0.5f); int ty = (int)floorf(fy + 0.5f); view[0] = (tx - 1) >> 1; view[1] = (ty - 1) >> 1; view[2] = (int)floorf(w_pos[2] + 0.5) + HEIGHT_SCALE / 2; } else { int tx = (int)floor(r->mul[0] * w_pos[0] + r->mul[2] * w_pos[1] + 0.5 + r->add[0]); int ty = (int)floor(r->mul[1] * w_pos[0] + r->mul[3] * w_pos[1] + r->mul[5] * w_pos[2] + 0.5 + r->add[1]); view[0] = (tx - 1) >> 1; view[1] = (ty - 1) >> 1; view[2] = (int)floorf(w_pos[2] + 0.5) + HEIGHT_SCALE / 2; } return true; } bool UnprojectCoords2D(Renderer* r, const int xy[2], float pos[3]) { int w = (r->sample_buffer.w - 4) / 2; int h = (r->sample_buffer.h - 4) / 2; if (xy[0] < 0 || xy[1] < 0 || xy[0] >= w || xy[1] >= h) return false; // readback height (max of 4 samples) int x = 2 + xy[0] * 2; int y = 2 + xy[1] * 2; int y0 = r->sample_buffer.w * y + x; int y1 = y0 + r->sample_buffer.w; float sh[4] = { r->sample_buffer.ptr[y0].height, r->sample_buffer.ptr[y0 + 1].height, r->sample_buffer.ptr[y1].height, r->sample_buffer.ptr[y1 + 1].height, }; float height = sh[0]; if (height < sh[1]) height = sh[1]; if (height < sh[2]) height = sh[2]; if (height < sh[3]) height = sh[3]; if (r->perspective) { int xyz[3] = {xy[0], xy[1], (int)floorf(height+0.5f)}; return UnprojectCoords3D(r,xyz,pos); } else { double p[4] = { (double)x,(double)y,(double)height,1.0 }; double w[4]; Product(r->inv_tm, p, w); pos[0] = w[0]; pos[1] = w[1]; pos[2] = w[2]; } return true; } bool UnprojectCoords3D(Renderer* r, const int xyz[3], float pos[3]) { // readback height (max of 4 samples) if (r->perspective) { float tm0 = r->mul[0]; float tm1 = r->mul[1]; float tm4 = r->mul[2]; float tm5 = r->mul[3]; float tm8 = 0; float tm9 = r->mul[5]; float tm12 = r->add[0]; float tm13 = r->add[1]; float z = xyz[2]; float ww_x, ww_y, ww_c, wx_x, wx_y, wx_c, wy_x, wy_y, wy_c; ww_x = r->view_dir[0]*tm5 - r->view_dir[1]*tm1; ww_y = r->view_dir[1]*tm0 - r->view_dir[0]*tm4; ww_c = tm1*tm4 - tm0*tm5; wx_x = (r->view_pos[0]*tm5*r->view_dir[0] + r->view_dir[1]*(-r->view_ofs[1] + r->view_pos[1]*tm5 + tm13 + tm9*z)); wx_y = (r->view_pos[0]*tm4*r->view_dir[0] + r->view_dir[1]*(-r->view_ofs[0] + r->view_pos[1]*tm4 + tm12 + tm8*z)); wx_c = tm5*(-r->view_ofs[0] + tm12 + tm8*z) + tm4*(r->view_ofs[1] - tm13 - tm9*z); wy_x = (r->view_pos[1]*tm1*r->view_dir[1] + r->view_dir[0]*(-r->view_ofs[1] + r->view_pos[0]*tm1 + tm13 + tm9*z)); wy_y = (r->view_pos[1]*tm0*r->view_dir[1] + r->view_dir[0]*(-r->view_ofs[0] + r->view_pos[0]*tm0 + tm12 + tm8*z)); wy_c = tm1*(r->view_ofs[0] - tm12 - tm8*z) + tm0*(-r->view_ofs[1] + tm13 + tm9*z); float sx_dx = 2.0*xyz[0]+2 - r->view_ofs[0]; float sy_dy = 2.0*xyz[1]+2 - r->view_ofs[1]; float ww = (sx_dx*ww_x + sy_dy*ww_y + ww_c); if (ww<0) { ww = 1.0/ww; float wx = ww * (wx_c + wx_x * sx_dx - wx_y * sy_dy); float wy = ww * (wy_c - wy_x * sx_dx + wy_y * sy_dy); pos[0] = wx; pos[1] = wy; pos[2] = z; } else { return false; } } else { double p[4] = { 2*xyz[0] + 1.0, 2*xyz[1] + 1.0, (double)xyz[2], 1.0 }; double w[4]; Product(r->inv_tm, p, w); pos[0] = w[0]; pos[1] = w[1]; pos[2] = w[2]; } return true; }
25.183575
231
0.507084
[ "mesh", "render", "transform" ]
bf5d61d6a90ec419f13e739c90afad6fa069f1f5
29,927
cpp
C++
admin/wmi/wbem/providers/snmpprovider/provider/instclas/storage.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
admin/wmi/wbem/providers/snmpprovider/provider/instclas/storage.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
admin/wmi/wbem/providers/snmpprovider/provider/instclas/storage.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
// Copyright (c) 1997-2001 Microsoft Corporation, All Rights Reserved #include "precomp.h" #include <provexpt.h> #include <cordefs.h> #include <corafx.h> #include <objbase.h> #include <wbemidl.h> #include <smir.h> #include <corstore.h> #include <notify.h> #include <snmplog.h> #include <autoptr.h> extern ISmirDatabase* g_pNotifyInt; extern CCorrCacheNotify *gp_notify; CCorrGroupArray::CCorrGroupArray() { SetSize(0, 10000); } int _cdecl compare( const void *arg1, const void *arg2 ) { CCorrObjectID tmp1; (*(CCorrGroupIdItem**)arg1)->GetGroupID(tmp1); CCorrObjectID tmp2; (*(CCorrGroupIdItem**)arg2)->GetGroupID(tmp2); switch (tmp1.CompareWith(tmp2)) { case ECorrAreEqual: break; case ECorrFirstLess: return -1; case ECorrFirstGreater: return 1; } return 0; } void CCorrGroupArray::Sort() { if (GetSize()) { //CObject** temp = GetData(); qsort((void *)GetData(), (size_t)GetSize(), sizeof( CCorrGroupIdItem * ), compare ); } FreeExtra(); } //============================================================================ // CCorrGroupArray::~CCorrGroupArray // // This is the CCorrGroupArray class's only desstructor. If there are any items in // the queue they are deleted. // // // Parameters: // // none // // Returns: // // none // //============================================================================ CCorrGroupArray::~CCorrGroupArray() { for (int x = 0; x < GetSize(); x++) { CCorrGroupIdItem * item = GetAt(x); delete item; } RemoveAll(); } //============================================================================ // CCorrGroupIdItem::CCorrGroupIdItem // // This is the CCorrGroupIdItem class's only constructor. This class is derived from // the CObject class. This is so the MFC template storage classes can be // used. It is used to store a CString value in a list. // // // Parameters: // // CString * str A pointer to the CString object to be stored. // // Returns: // // none // //============================================================================ CCorrGroupIdItem::CCorrGroupIdItem(IN const CCorrObjectID& ID, IN ISmirGroupHandle* grpH) : m_groupId(ID) { m_index = 0; if (grpH) { m_groupHandles.AddHead(grpH); } } void CCorrGroupIdItem::GetGroupID(OUT CCorrObjectID& ID) const { m_groupId.ExtractOID(ID); } void CCorrGroupIdItem::DebugOutputItem(CString* msg) const { CString debugstr; CCorrObjectID tmp; m_groupId.ExtractOID(tmp); tmp.GetString(debugstr); if (!debugstr.GetLength()) { debugstr = L"Error retrieving Group Object OID"; } if (msg) { debugstr += L"\t\t:\t"; debugstr += *msg; } debugstr += L"\n"; DebugMacro6( SnmpDebugLog::s_SnmpDebugLog->WriteFileAndLine(__FILE__,__LINE__, debugstr); ) } //============================================================================ // CCorrGroupIdItem::~CCorrGroupIdItem // // This is the CCorrGroupIdItem class's only destructor. It frees the memory used // to store the CString members. // // // Parameters: // // none // // Returns: // // none // //============================================================================ CCorrGroupIdItem::~CCorrGroupIdItem() { while (!m_groupHandles.IsEmpty()) { (m_groupHandles.RemoveHead())->Release(); } } CCorrObjectID::CCorrObjectID(IN const CCorrObjectID& ID) : m_Ids(NULL) { m_length = ID.m_length; if (m_length) { m_Ids = new UINT[m_length]; memcpy(m_Ids, ID.m_Ids, m_length*sizeof(UINT)); } } CCorrObjectID::CCorrObjectID(IN const char* str) : m_Ids(NULL) { m_length = 0; if (NULL != str) { size_t InputLen = strlen(str); if (InputLen > MAX_OID_STRING) return; //string is too long. char temp[MAX_OID_STRING + 1]; strcpy(temp, str); BOOL bad = FALSE; char* temp1 = temp; UINT temp2[MAX_OID_LENGTH]; CString dot("."); if (dot.GetAt(0) == temp[0]) { temp1++; } istrstream istr(temp1); char d; istr >> temp2[0]; m_length++; if (istr.bad() || istr.fail()) { bad = TRUE; } while(!istr.eof() && !bad) { istr >> d; if (istr.bad() || istr.fail()) { bad = TRUE; } if (d != dot.GetAt(0)) { bad = TRUE; } if (m_length < MAX_OID_LENGTH) { istr >> temp2[m_length++]; if (istr.bad() || istr.fail()) { bad = TRUE; } } else { bad = TRUE; } } if (!bad) { m_Ids = new UINT[m_length]; memcpy(m_Ids, temp2, m_length*sizeof(UINT)); } else { m_length = 0; } } } CCorrObjectID::CCorrObjectID(IN const UINT* ids, IN const UINT len) : m_Ids(NULL) { if (len <= MAX_OID_LENGTH) { m_length = len; } else { m_length = 0; } if (m_length) { m_Ids = new UINT[m_length]; memcpy(m_Ids, ids, m_length*sizeof(UINT)); } } void CCorrObjectID::Set(IN const UINT* ids, IN const UINT len) { if (m_length) { delete [] m_Ids; } if (len <= MAX_OID_LENGTH) { m_length = len; } else { m_length = 0; } if (m_length) { m_Ids = new UINT[m_length]; memcpy(m_Ids, ids, m_length*sizeof(UINT)); } else { m_Ids = NULL; } } char* CCorrObjectID::GetString() const { char * ret = NULL; if (m_length) { ret = new char[BYTES_PER_FIELD*m_length]; ostrstream s(ret, BYTES_PER_FIELD*m_length); s << m_Ids[0]; UINT i = 1; char dot = '.'; while (i < m_length) { s << dot << m_Ids[i++]; } s << ends; } return ret; } #define AVERAGE_OID_LENGTH 20 wchar_t* CCorrObjectID::GetWideString() const { wchar_t *returnValue = NULL ; ULONG totalLength = 0 ; ULONG reallocLength = AVERAGE_OID_LENGTH ; wchar_t *reallocArray = new wchar_t [ reallocLength ] ; if (reallocArray == NULL) { throw Heap_Exception(Heap_Exception::HEAP_ERROR::E_ALLOCATION_ERROR); } wmilib::auto_ptr<WCHAR> t_ReallocWrap ( reallocArray ); ULONG objectIdentifierLength = m_length ; ULONG index = 0 ; while ( index < objectIdentifierLength ) { wchar_t stringValue [ 40 ] ; _ultow ( m_Ids [ index ] , stringValue , 10 ); ULONG stringLength = wcslen ( stringValue ) ; if ( ( totalLength + stringLength + 1 ) >= reallocLength ) { ULONG t_Max = max( stringLength + 1 , AVERAGE_OID_LENGTH ) ; reallocLength = reallocLength + t_Max ; wchar_t *t_newReallocArray = new wchar_t [ reallocLength ] ; CopyMemory ( t_newReallocArray , t_ReallocWrap.get () , totalLength * sizeof ( wchar_t ) ) ; t_ReallocWrap.reset ( t_newReallocArray ) ; } wcscpy ( & ( t_ReallocWrap.get () [ totalLength ] ) , stringValue ) ; totalLength = totalLength + stringLength ; index ++ ; if ( index < objectIdentifierLength ) { if ( ( totalLength + 1 + 1 ) >= reallocLength ) { reallocLength = reallocLength + AVERAGE_OID_LENGTH ; wchar_t *t_newReallocArray = new wchar_t [ reallocLength ] ; CopyMemory ( t_newReallocArray , t_ReallocWrap.get () , totalLength * sizeof ( wchar_t ) ) ; t_ReallocWrap.reset ( t_newReallocArray ) ; } wcscpy ( & ( t_ReallocWrap.get ()[ totalLength ] ) , L"." ) ; totalLength ++ ; } } returnValue = new wchar_t [ totalLength + 1 ] ; if ( objectIdentifierLength ) { wcscpy ( returnValue , t_ReallocWrap.get () ) ; } else { returnValue [ 0 ] = 0 ; } return returnValue ; } void CCorrObjectID::GetString(CString& str) const { wchar_t* oid = GetWideString(); try { str = oid; } catch(...) { delete [] oid; throw; } delete [] oid; } ECorrCompResult CCorrObjectID::CompareWith(IN const CCorrObjectID& second) const { if (0 == m_length) { if (0 == second.m_length) { return ECorrAreEqual; } else { return ECorrFirstLess; } } if (0 == second.m_length) { return ECorrFirstGreater; } ECorrCompResult res = ECorrAreEqual; if (m_length <= second.m_length) { for (UINT i = 0; i < m_length; i++) { if (m_Ids[i] != second.m_Ids[i]) { if (m_Ids[i] < second.m_Ids[i]) { return ECorrFirstLess; } else { return ECorrFirstGreater; } } } if (m_length < second.m_length) { res = ECorrFirstLess; } } else { for (UINT i = 0; i < second.m_length; i++) { if (m_Ids[i] != second.m_Ids[i]) { if (m_Ids[i] < second.m_Ids[i]) { return ECorrFirstLess; } else { return ECorrFirstGreater; } } } res = ECorrFirstGreater; } return res; } BOOL CCorrObjectID::IsSubRange(IN const CCorrObjectID& child) const { if (m_length >= child.m_length) { return FALSE; } for (UINT i=0; i<m_length; i++) { if (m_Ids[i] != child.m_Ids[i]) { return FALSE; } } return TRUE; } BOOL CCorrObjectID::operator ==(IN const CCorrObjectID& second) const { if (ECorrAreEqual == CompareWith(second)) { return TRUE; } else { return FALSE; } } BOOL CCorrObjectID::operator !=(IN const CCorrObjectID& second) const { if (ECorrAreEqual == CompareWith(second)) { return FALSE; } else { return TRUE; } } BOOL CCorrObjectID::operator <(IN const CCorrObjectID& second) const { if (ECorrFirstLess == CompareWith(second)) { return TRUE; } else { return FALSE; } } BOOL CCorrObjectID::operator >(IN const CCorrObjectID& second) const { if (ECorrFirstGreater == CompareWith(second)) { return TRUE; } else { return FALSE; } } BOOL CCorrObjectID::operator <=(IN const CCorrObjectID& second) const { ECorrCompResult res = CompareWith(second); if ((ECorrAreEqual == res) || (ECorrFirstLess == res)) { return TRUE; } else { return FALSE; } } BOOL CCorrObjectID::operator >=(IN const CCorrObjectID& second) const { ECorrCompResult res = CompareWith(second); if ((ECorrAreEqual == res) || (ECorrFirstGreater == res)) { return TRUE; } else { return FALSE; } } CCorrObjectID& CCorrObjectID::operator =(IN const CCorrObjectID& ID) { if (m_length) { delete [] m_Ids; } m_length = ID.m_length; if (m_length) { m_Ids = new UINT[m_length]; memcpy(m_Ids, ID.m_Ids, m_length*sizeof(UINT)); } else { m_Ids = NULL; } return *this; } CCorrObjectID& CCorrObjectID::operator +=(IN const CCorrObjectID& ID) { if((m_length + ID.m_length) > MAX_OID_LENGTH) { if(m_length) { delete [] m_Ids; m_Ids = NULL; } m_length = 0; } else { if (ID.m_length) { UINT* newIds = new UINT[m_length + ID.m_length]; if(m_length) { memcpy(newIds, m_Ids, m_length*sizeof(UINT)); delete [] m_Ids; m_Ids = NULL; } memcpy(&(newIds[m_length]), ID.m_Ids, ID.m_length*sizeof(UINT)); m_Ids = newIds; m_length += ID.m_length; } } return *this; } CCorrObjectID& CCorrObjectID::operator ++() { if (m_length) { m_Ids[m_length - 1]++; } return *this; } CCorrObjectID& CCorrObjectID::operator --() { if (m_length) { m_Ids[m_length - 1]--; } return *this; } CCorrObjectID& CCorrObjectID::operator -=(IN const UINT sub) { if (sub && (m_length > sub)) { m_length -= sub; UINT* newIds = new UINT[m_length]; memcpy(newIds, m_Ids, m_length*sizeof(UINT)); delete [] m_Ids; m_Ids = newIds; } else if (sub == m_length) { m_length = 0; delete [] m_Ids; m_Ids = NULL; } return *this; } CCorrObjectID& CCorrObjectID::operator /=(IN const UINT sub) { if (sub && (m_length > sub)) { m_length -= sub; UINT* newIds = new UINT[m_length]; memcpy(newIds, &(m_Ids[sub]), m_length*sizeof(UINT)); delete [] m_Ids; m_Ids = newIds; } else if (sub == m_length) { m_length = 0; delete [] m_Ids; m_Ids = NULL; } return *this; } CCorrObjectID::~CCorrObjectID() { if (m_length) { delete [] m_Ids; } } //============================================================================ // CCorrRangeTableItem::CCorrRangeTableItem // // This is the CCorrRangeTableItem class's only constructor. This class is derived from // the CObject class. This is so the MFC template storage classes can be // used. It is used to store a CString value in a list. // // // Parameters: // // CString * str A pointer to the CString object to be stored. // // Returns: // // none // //============================================================================ CCorrRangeTableItem::CCorrRangeTableItem(IN const CCorrObjectID& startID, IN const CCorrObjectID& endID, IN CCorrGroupIdItem* grpID) { m_groupId = grpID; CCorrObjectID temp; m_groupId->GetGroupID(temp); CCorrObjectID startRange = startID; startRange /= temp.GetLength(); CCorrObjectID endRange = endID; endRange /= (temp.GetLength() - 1); m_startRange.Set(startRange); m_endRange.Set(endRange); } //============================================================================ // CCorrRangeTableItem::~CCorrRangeTableItem // // This is the CCorrRangeTableItem class's only destructor. It frees the memory used // to store the CString members. // // // Parameters: // // none // // Returns: // // none // //============================================================================ CCorrRangeTableItem::~CCorrRangeTableItem() { } BOOL CCorrRangeTableItem::GetStartRange(OUT CCorrObjectID& start) const { if (!m_groupId) return FALSE; m_groupId->GetGroupID(start); CCorrObjectID tmp; m_startRange.ExtractOID(tmp); start += tmp; return TRUE; } BOOL CCorrRangeTableItem::GetEndRange(OUT CCorrObjectID& end) const { if (!m_groupId) return FALSE; m_groupId->GetGroupID(end); end -= 1; CCorrObjectID tmp; m_endRange.ExtractOID(tmp); end += tmp; return TRUE; } CCorrRangeTableItem::ECorrRangeResult CCorrRangeTableItem:: IsInRange(IN const CCorrObjectID& ID) const { CCorrObjectID a; GetStartRange(a); if (ID == a) { return ECorrEqualToStart; } if (ID < a) { return ECorrBeforeStart; } CCorrObjectID b; GetEndRange(b); if (ID == b) { return ECorrEqualToEnd; } if (ID > b) { return ECorrAfterEnd; } return ECorrInRange; } void CCorrRangeTableItem::DebugOutputRange() const { DebugMacro6( if (m_groupId) { CString debugstr; CCorrObjectID tmp; m_groupId->GetGroupID(tmp); tmp.GetString(debugstr); CString out1; CCorrObjectID start; GetStartRange(start); start.GetString(out1); CString out2; CCorrObjectID end; GetEndRange(end); end.GetString(out2); debugstr += "\t\t:\t\t"; debugstr += out1; debugstr += "\t\t:\t\t"; debugstr += out2; debugstr += "\t\tGroup : Start : End\n"; SnmpDebugLog::s_SnmpDebugLog->WriteFileAndLine(__FILE__,__LINE__, debugstr); } else { SnmpDebugLog::s_SnmpDebugLog->WriteFileAndLine(__FILE__,__LINE__, L"Attempt to output empty RangeTableItem\n"); } ) } //============================================================================ // CCorrRangeList::~CCorrRangeList // // This is the CCorrRangeList class's only desstructor. If there are any items in // the queue they are deleted. // // // Parameters: // // none // // Returns: // // none // //============================================================================ CCorrRangeList::~CCorrRangeList() { while(!IsEmpty()) { CCorrRangeTableItem * item = RemoveHead(); delete item; } } //============================================================================ // CCorrRangeList::Add // // This public method is called to add a CCorrRangeTableItem into this CCorrRangeList. The // CCorrRangeTableItem is not added if it is already present in the list. If this is the // case a pointer to the matching item in the list is returned. // // // Parameters: // // CCorrRangeTableItem * newItem A pointer to the CCorrRangeTableItem to be added. // // Returns: // // CCorrRangeTableItem * A pointer to the item if is in the list. NULL if // the item was not found and was added. // //============================================================================ BOOL CCorrRangeList::Add(IN CCorrRangeTableItem* newItem) { AddTail(newItem); //empty or all items smaller return TRUE; } BOOL CCorrRangeList::GetLastEndOID(OUT CCorrObjectID& end) const { if (IsEmpty()) { return FALSE; } return (GetTail()->GetEndRange(end)); } CCorrGroupMask::CCorrGroupMask(IN const TCorrMaskLength sze) : m_mask(NULL) { m_size = sze; if (m_size) { TCorrMaskLength x = m_size / (sizeof(TCorrMaskUnit)*BITS_PER_BYTE); if (m_size % (sizeof(TCorrMaskUnit)*BITS_PER_BYTE)) { x++; } m_mask = new TCorrMaskUnit[x]; ZeroMemory((PVOID)m_mask, (DWORD)(sizeof(TCorrMaskUnit)*x)); } } BOOL CCorrGroupMask::IsBitSet(IN const TCorrMaskLength bit)const { TCorrMaskLength x = bit / (sizeof(TCorrMaskUnit)*BITS_PER_BYTE); TCorrMaskLength val = bit % (sizeof(TCorrMaskUnit)*BITS_PER_BYTE); return (((m_mask[x] >> val) & 1) == 1); } void CCorrGroupMask::SetBit(IN const TCorrMaskLength bit, IN const BOOL On) { BOOL IsBit = IsBitSet(bit); if ((IsBit && On) || (!IsBit && !On)) { return; } else { TCorrMaskLength x = bit / (sizeof(TCorrMaskUnit)*BITS_PER_BYTE); TCorrMaskLength val = bit % (sizeof(TCorrMaskUnit)*BITS_PER_BYTE); TCorrMaskLength maskval = 1; maskval <<= val; if (On) { m_mask[x] += maskval; } else { m_mask[x] -= maskval; } } } CCorrGroupMask::~CCorrGroupMask() { if (m_mask) { delete [] m_mask; } } CCorrCache::CCorrCache( ISmirInterrogator *a_ISmirInterrogator ) : m_Groups (NULL) { m_ValidCache = TRUE; m_Ref_Count = 0; m_size = 0; BuildCacheAndSetNotify( a_ISmirInterrogator ); if (m_groupTable.GetSize()) { m_Groups = new CCorrGroupMask(m_size); BuildRangeTable(); } } CCorrCache::~CCorrCache() { if (m_Groups) { delete m_Groups; } } void CCorrCache::InvalidateCache() { m_Lock.Lock(); if (!m_Ref_Count) { delete this; } else { m_ValidCache = FALSE; m_Lock.Unlock(); } } BOOL CCorrCache::BuildCacheAndSetNotify( ISmirInterrogator *a_ISmirInterrogator ) { LPUNKNOWN pInterrogativeInt = NULL; // =============================================================== // The following relies on the current thread having been // initialised for OLE (i.e. by the use of CoInitialize) // =============================================================== HRESULT hr = S_OK ; if ( a_ISmirInterrogator ) { hr = a_ISmirInterrogator->QueryInterface ( IID_ISMIR_Interrogative, (void**)&pInterrogativeInt ); } else { hr = CoCreateInstance (CLSID_SMIR_Database, NULL, CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER, IID_ISMIR_Interrogative, (void**)&pInterrogativeInt); } if (NULL == pInterrogativeInt) { return FALSE; } IEnumGroup *pTEnumSmirGroup = NULL; //enum all groups hr = ((ISmirInterrogator*)pInterrogativeInt)->EnumGroups(&pTEnumSmirGroup, NULL); //now use the enumerator if(NULL == pTEnumSmirGroup) { pInterrogativeInt->Release(); return FALSE; } ISmirGroupHandle *phModule=NULL; DebugMacro6( SnmpDebugLog::s_SnmpDebugLog->WriteFileAndLine(__FILE__,__LINE__, L"CCorrCache::BuildCacheAndSetNotify - Accessing SMIR Getting Groups\n"); ) for(int iCount=0; S_OK == pTEnumSmirGroup->Next(1, &phModule, NULL); iCount++) { //DO SOMETHING WITH THE GROUP HANDLE //eg get the name BSTR szName=NULL; char buff[1024]; LPSTR pbuff = buff; int lbuff = sizeof(buff); phModule->GetGroupOID(&szName); if (FALSE == WideCharToMultiByte(CP_ACP, 0, szName, -1, pbuff, lbuff, NULL, NULL)) { DWORD lasterr = GetLastError(); SysFreeString(szName); phModule->Release(); DebugMacro6( SnmpDebugLog::s_SnmpDebugLog->WriteFileAndLine(__FILE__,__LINE__, L"CCorrCache::BuildCacheAndSetNotify - Error bad BSTR conversion\n"); ) continue; } SysFreeString(szName); CCorrObjectID grpId(buff); CCorrObjectID zero; if (zero != grpId) { CCorrGroupIdItem* groupId = new CCorrGroupIdItem(grpId, phModule); m_groupTable.Add(groupId); m_size++; } DebugMacro6( SnmpDebugLog::s_SnmpDebugLog->WriteFileAndLine(__FILE__,__LINE__, L"%s\n", buff); ) } DebugMacro6( SnmpDebugLog::s_SnmpDebugLog->WriteFileAndLine(__FILE__,__LINE__, L"CCorrCache::BuildCacheAndSetNotify - Finished accessing SMIR Getting Groups\n"); ) pTEnumSmirGroup->Release(); if (NULL == g_pNotifyInt) { hr = pInterrogativeInt->QueryInterface(IID_ISMIR_Database, (void **) &g_pNotifyInt); if(SUCCEEDED(hr)) { if( gp_notify== NULL) { DWORD dw; gp_notify = new CCorrCacheNotify(); gp_notify->AddRef(); hr = g_pNotifyInt->AddNotify(gp_notify, &dw); if(SUCCEEDED(hr)) { gp_notify->SetCookie(dw); } } } } else { if( gp_notify== NULL) { DWORD dw; gp_notify = new CCorrCacheNotify(); gp_notify->AddRef(); hr = g_pNotifyInt->AddNotify(gp_notify, &dw); if(SUCCEEDED(hr)) { gp_notify->SetCookie(dw); } } } pInterrogativeInt->Release(); if ((NULL == gp_notify) || (0 == gp_notify->GetCookie())) { return FALSE; } return TRUE; } #pragma warning (disable:4018) BOOL CCorrCache::BuildRangeTable() { UINT pos = 0; TCorrMaskLength posIndex = 0; TCorrMaskLength nextIndex = 1; m_groupTable.Sort(); DebugMacro6( SnmpDebugLog::s_SnmpDebugLog->WriteFileAndLine(__FILE__,__LINE__, L"CCorrCache::BuildRangeTable - Printing sorted group table...\n"); for (int x = 0; x < m_groupTable.GetSize(); x++) { CCorrGroupIdItem * i = m_groupTable.GetAt(x); i->DebugOutputItem(); } SnmpDebugLog::s_SnmpDebugLog->WriteFileAndLine(__FILE__,__LINE__, L"CCorrCache::BuildRangeTable - Finished printing sorted group table...\n"); ) while (pos < m_groupTable.GetSize()) { UINT nextpos = pos + 1; DoGroupEntry(&pos, &nextpos, &posIndex, &nextIndex); pos = nextpos; posIndex = nextIndex++; } return TRUE; } #pragma warning (default:4018) #pragma warning (disable:4018) void CCorrCache::DoGroupEntry(UINT* current, UINT* next, TCorrMaskLength* cIndex, TCorrMaskLength* nIndex) { CCorrGroupIdItem* alpha = m_groupTable.GetAt(*current); CCorrObjectID a; alpha->GetGroupID(a); CCorrObjectID End(a); ++End; if (*next < m_groupTable.GetSize()) { CCorrGroupIdItem* beta = m_groupTable.GetAt(*next); CCorrObjectID b; beta->GetGroupID(b); //check for duplicates while ((a == b) && (*next < m_groupTable.GetSize())) { DebugMacro6( SnmpDebugLog::s_SnmpDebugLog->WriteFileAndLine(__FILE__,__LINE__, L"Deleting duplicate non MIB2 group... "); beta->DebugOutputItem(); ) //add the group handles to the one not being deleted while (!beta->m_groupHandles.IsEmpty()) { alpha->m_groupHandles.AddTail(beta->m_groupHandles.RemoveHead()); } m_groupTable.RemoveAt(*next); delete beta; beta = m_groupTable.GetAt(*next); beta->GetGroupID(b); } //after checking for duplicates, check we still meet the initial condition if (*next < m_groupTable.GetSize()) { //if the next item is not a child of this if ((a.GetLength() >= b.GetLength()) || (!a.IsSubRange(b))) { CCorrObjectID c; CCorrRangeTableItem* newEntry; if (!m_rangeTable.GetLastEndOID(c) || !a.IsSubRange(c)) { //add whole of a-range to rangetable newEntry = new CCorrRangeTableItem(a, End, alpha); } else { //add from c to end of a-range to rangetable newEntry = new CCorrRangeTableItem(c, End, alpha); } newEntry->DebugOutputRange(); m_rangeTable.Add(newEntry); alpha->SetIndex(*cIndex); m_Groups->SetBit(*cIndex); } else //the next item is a child so add a subrange and do the child - recurse! { CCorrObjectID c; CCorrRangeTableItem* newEntry; if (!m_rangeTable.GetLastEndOID(c) || !a.IsSubRange(c)) { //add start of a-range to start of b to rangetable newEntry = new CCorrRangeTableItem(a, b, alpha); } else { //add from c to start of b to rangetable newEntry = new CCorrRangeTableItem(c, b, alpha); } newEntry->DebugOutputRange(); m_rangeTable.Add(newEntry); UINT temp = (*next)++; TCorrMaskLength tempIndex = (*nIndex)++; DoGroupEntry(&temp, next, &tempIndex, nIndex); if (*next >= m_groupTable.GetSize()) { m_rangeTable.GetLastEndOID(c); ////add from c to end of a-range to rangetable newEntry = new CCorrRangeTableItem(c, End, alpha); m_rangeTable.Add(newEntry); alpha->SetIndex(*cIndex); m_Groups->SetBit(*cIndex); newEntry->DebugOutputRange(); } //while the new next one(s) is a child add it first - recurse AGAIN! while(!m_Groups->IsBitSet(*cIndex)) { DoGroupEntry(current, next, cIndex, nIndex); } } } } //if this is the last item then add it. if (*current == m_groupTable.GetUpperBound()) { //add whole of a-range to rangetable CCorrRangeTableItem* newEntry = new CCorrRangeTableItem(a, End, alpha); m_rangeTable.Add(newEntry); alpha->SetIndex(*cIndex); m_Groups->SetBit(*cIndex); newEntry->DebugOutputRange(); } } #pragma warning (default:4018) void CCorrCache::AddRef() { m_Lock.Lock(); m_Ref_Count++; m_Lock.Unlock(); } void CCorrCache::DecRef() { m_Lock.Lock(); if (m_Ref_Count) m_Ref_Count--; if (!m_Ref_Count && !m_ValidCache) { delete this; return; } m_Lock.Unlock(); } CCorrEncodedOID::CCorrEncodedOID(IN const CCorrObjectID& src_oid) : m_ids(NULL), m_length(0), m_chopped(0) { Set(src_oid); } void CCorrEncodedOID::Set(IN const CCorrObjectID& src_oid) { m_chopped = 0; UINT x = 0; UINT oidlength = src_oid.GetLength(); if (oidlength > MAX_OID_LENGTH) { DebugMacro6( SnmpDebugLog::s_SnmpDebugLog->WriteFileAndLine(__FILE__,__LINE__, L"CCorrEncodedOID::Set: Truncating OID from %d to %d components", oidlength, MAX_OID_LENGTH); ) oidlength = MAX_OID_LENGTH; } if (oidlength) { UCHAR buff[MAX_OID_LENGTH*MAX_BYTES_PER_FIELD]; const UINT* oid_ids = src_oid.GetIds(); for (UINT i = 0; i < oidlength; i++) { UINT val = oid_ids[i]; //get the top four bits and store in byte //BIT7 means next byte is part of this UINT if (val >= BIT28) { buff[x++] = (UCHAR) (BIT7 + ((val & HI4BITS) >> 28)); } //get the top four bits and store in byte //BIT7 means next byte is part of this UINT if (val >= BIT21) { buff[x++] = BIT7 + ((val & HIMID7BITS) >> 21); } //get the top four bits and store in byte //BIT7 means next byte is part of this UINT if (val >= BIT14) { buff[x++] = BIT7 + ((val & MID7BITS) >> 14); } //get the top four bits and store in byte //BIT7 means next byte is part of this UINT if (val >= BIT7) { buff[x++] = BIT7 + ((val & LOMID7BITS) >> 7); } //get the next seven bits and store in byte buff[x++] = (val & LO7BITS); } //Remove the standard 1.3.6.1 if necessary... if ((1 == buff[0]) && (3 == buff[1]) && (6 == buff[2]) && (1 == buff[3])) { m_chopped = 1; m_ids = new UCHAR[x-4]; m_length = x-4; memcpy(m_ids, &buff[4], m_length*sizeof(UCHAR)); } else { m_ids = new UCHAR[x]; m_length = x; memcpy(m_ids, buff, m_length*sizeof(UCHAR)); } } else { m_ids = NULL; } } void CCorrEncodedOID::ExtractOID(OUT CCorrObjectID& src_oid) const { if (m_length) { UINT buff[MAX_OID_LENGTH]; UINT x = 0; //Add the standard 1.3.6.1 if necessary... if (m_chopped == 1) { buff[0] = 1; buff[1] = 3; buff[2] = 6; buff[3] = 1; x = 4; } for (UINT i = 0; (i < m_length) && (x < MAX_OID_LENGTH); i++) { //extract the value of the byte buff[x] = m_ids[i] & LO7BITS; //are there more bytes for this UINT while ((i < m_length) && (m_ids[i] & 128)) { //shift the value by a "byte" and extract tbe next byte. buff[x] = buff[x] << 7; buff[x] += m_ids[++i] & LO7BITS; } x++; if ((x == MAX_OID_LENGTH) && (i < m_length)) { DebugMacro6( SnmpDebugLog::s_SnmpDebugLog->WriteFileAndLine(__FILE__,__LINE__, L"CCorrEncodedOID::ExtractOID: Truncating OID %d components - SHOULD NEVER HAPPEN", MAX_OID_LENGTH); ) } } src_oid.Set(buff, x); } else { src_oid.Set(NULL, 0); } } CCorrEncodedOID::~CCorrEncodedOID() { delete [] m_ids; } CCorrCacheWrapper::CCorrCacheWrapper(IN CCorrCache* cachePtr) : m_lockit(NULL) { m_lockit = new CCriticalSection(); m_CachePtr = cachePtr; } CCorrCache* CCorrCacheWrapper::GetCache() { m_lockit->Lock(); return m_CachePtr; } CCorrCacheWrapper::~CCorrCacheWrapper() { delete m_lockit; }
19.951333
107
0.590504
[ "object" ]
bf5fa3f60ab1cf1842a0da2c042adfa25e361b27
36,225
cpp
C++
kernels/bvh/bvh_builder_sah.cpp
vinben/embree-2.13.0
8ebd7954762d8b4d0be52f7bde201086a6eaca86
[ "Apache-2.0" ]
null
null
null
kernels/bvh/bvh_builder_sah.cpp
vinben/embree-2.13.0
8ebd7954762d8b4d0be52f7bde201086a6eaca86
[ "Apache-2.0" ]
null
null
null
kernels/bvh/bvh_builder_sah.cpp
vinben/embree-2.13.0
8ebd7954762d8b4d0be52f7bde201086a6eaca86
[ "Apache-2.0" ]
null
null
null
// ======================================================================== // // Copyright 2009-2016 Intel Corporation // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // ======================================================================== // #include "bvh.h" #include "bvh_builder.h" #include "../builders/primrefgen.h" #include "../builders/presplit.h" #include "../geometry/bezier1v.h" #include "../geometry/bezier1i.h" #include "../geometry/linei.h" #include "../geometry/triangle.h" #include "../geometry/trianglev.h" #include "../geometry/trianglei.h" #include "../geometry/trianglev_mb.h" #include "../geometry/trianglei_mb.h" #include "../geometry/quadv.h" #include "../geometry/quadi.h" #include "../geometry/quadi_mb.h" #include "../geometry/object.h" #include "../common/state.h" #define PROFILE 0 #define PROFILE_RUNS 20 namespace embree { namespace isa { MAYBE_UNUSED static const float travCost = 1.0f; MAYBE_UNUSED static const float defaultPresplitFactor = 1.2f; typedef FastAllocator::ThreadLocal2 Allocator; template<int N, typename Primitive> struct CreateLeaf { typedef BVHN<N> BVH; __forceinline CreateLeaf (BVH* bvh, PrimRef* prims) : bvh(bvh), prims(prims) {} __forceinline size_t operator() (const BVHBuilderBinnedSAH::BuildRecord& current, Allocator* alloc) { size_t n = current.prims.size(); size_t items = Primitive::blocks(n); size_t start = current.prims.begin(); Primitive* accel = (Primitive*) alloc->alloc1->malloc(items*sizeof(Primitive),BVH::byteNodeAlignment); typename BVH::NodeRef node = BVH::encodeLeaf((char*)accel,items); for (size_t i=0; i<items; i++) { accel[i].fill(prims,start,current.prims.end(),bvh->scene,false); } *current.parent = node; return n; } BVH* bvh; PrimRef* prims; }; template<int N, typename Primitive> struct CreateLeafQuantized { typedef BVHN<N> BVH; __forceinline CreateLeafQuantized (BVH* bvh, PrimRef* prims) : bvh(bvh), prims(prims) {} __forceinline size_t operator() (const BVHBuilderBinnedSAH::BuildRecord& current, Allocator* alloc) { size_t n = current.prims.size(); size_t items = Primitive::blocks(n); size_t start = current.prims.begin(); // todo alloc0/1 or alloc Primitive* accel = (Primitive*) alloc->alloc0->malloc(items*sizeof(Primitive),BVH::byteNodeAlignment); typename BVH::NodeRef node = BVH::encodeLeaf((char*)accel,items); for (size_t i=0; i<items; i++) { accel[i].fill(prims,start,current.prims.end(),bvh->scene,false); } *current.parent = node; return n; } BVH* bvh; PrimRef* prims; }; template<int N, typename Primitive> struct CreateLeafSpatial { typedef BVHN<N> BVH; __forceinline CreateLeafSpatial (BVH* bvh, PrimRef* prims0) : bvh(bvh), prims0(prims0) {} __forceinline size_t operator() (const BVHBuilderBinnedFastSpatialSAH::BuildRecord& current, Allocator* alloc) { PrimRef* const source = prims0; size_t n = current.prims.size(); size_t items = Primitive::blocks(n); size_t start = current.prims.begin(); // remove number of split encoding for (size_t i=0; i<n; i++) source[start+i].lower.a &= 0x00FFFFFF; Primitive* accel = (Primitive*) alloc->alloc1->malloc(items*sizeof(Primitive),BVH::byteNodeAlignment); typename BVH::NodeRef node = BVH::encodeLeaf((char*)accel,items); for (size_t i=0; i<items; i++) { accel[i].fill(source,start,current.prims.end(),bvh->scene,false); } *current.parent = node; return n; } BVH* bvh; PrimRef* prims0; }; /************************************************************************************/ /************************************************************************************/ /************************************************************************************/ /************************************************************************************/ template<int N, typename Mesh, typename Primitive> struct BVHNBuilderSAH : public Builder { typedef BVHN<N> BVH; BVH* bvh; Scene* scene; Mesh* mesh; mvector<PrimRef> prims; const size_t sahBlockSize; const float intCost; const size_t minLeafSize; const size_t maxLeafSize; const float presplitFactor; BVHNBuilderSAH (BVH* bvh, Scene* scene, const size_t sahBlockSize, const float intCost, const size_t minLeafSize, const size_t maxLeafSize, const size_t mode) : bvh(bvh), scene(scene), mesh(nullptr), prims(scene->device), sahBlockSize(sahBlockSize), intCost(intCost), minLeafSize(minLeafSize), maxLeafSize(min(maxLeafSize,Primitive::max_size()*BVH::maxLeafBlocks)), presplitFactor((mode & MODE_HIGH_QUALITY) ? defaultPresplitFactor : 1.0f) {} BVHNBuilderSAH (BVH* bvh, Mesh* mesh, const size_t sahBlockSize, const float intCost, const size_t minLeafSize, const size_t maxLeafSize, const size_t mode) : bvh(bvh), scene(nullptr), mesh(mesh), prims(bvh->device), sahBlockSize(sahBlockSize), intCost(intCost), minLeafSize(minLeafSize), maxLeafSize(min(maxLeafSize,Primitive::max_size()*BVH::maxLeafBlocks)), presplitFactor((mode & MODE_HIGH_QUALITY ) ? defaultPresplitFactor : 1.0f) {} // FIXME: shrink bvh->alloc in destructor here and in other builders too void build(size_t, size_t) { /* skip build for empty scene */ const size_t numPrimitives = mesh ? mesh->size() : scene->getNumPrimitives<Mesh,false>(); if (numPrimitives == 0) { prims.clear(); bvh->clear(); return; } double t0 = bvh->preBuild(mesh ? "" : TOSTRING(isa) "::BVH" + toString(N) + "BuilderSAH"); #if PROFILE profile(2,PROFILE_RUNS,numPrimitives,[&] (ProfileTimer& timer) { #endif /* create primref array */ const size_t numSplitPrimitives = max(numPrimitives,size_t(presplitFactor*numPrimitives)); prims.resize(numSplitPrimitives); PrimInfo pinfo = mesh ? createPrimRefArray<Mesh> (mesh ,prims,bvh->scene->progressInterface) : createPrimRefArray<Mesh,false>(scene,prims,bvh->scene->progressInterface); /* pinfo might has zero size due to invalid geometry */ if (unlikely(pinfo.size() == 0)) { prims.clear(); bvh->clear(); return; } /* perform pre-splitting */ if (presplitFactor > 1.0f) pinfo = presplit<Mesh>(scene, pinfo, prims); /* call BVH builder */ bvh->alloc.init_estimate(pinfo.size()*sizeof(PrimRef)); BVHNBuilder<N>::build(bvh,CreateLeaf<N,Primitive>(bvh,prims.data()),bvh->scene->progressInterface,prims.data(),pinfo,sahBlockSize,minLeafSize,maxLeafSize,travCost,intCost); #if PROFILE }); #endif /* clear temporary data for static geometry */ bool staticGeom = mesh ? mesh->isStatic() : scene->isStatic(); if (staticGeom) { prims.clear(); bvh->shrink(); } bvh->cleanup(); bvh->postBuild(t0); } void clear() { prims.clear(); } }; /************************************************************************************/ /************************************************************************************/ /************************************************************************************/ /************************************************************************************/ template<int N, typename Mesh, typename Primitive> struct BVHNBuilderSAHQuantized : public Builder { typedef BVHN<N> BVH; BVH* bvh; Scene* scene; Mesh* mesh; mvector<PrimRef> prims; const size_t sahBlockSize; const float intCost; const size_t minLeafSize; const size_t maxLeafSize; const float presplitFactor; BVHNBuilderSAHQuantized (BVH* bvh, Scene* scene, const size_t sahBlockSize, const float intCost, const size_t minLeafSize, const size_t maxLeafSize, const size_t mode) : bvh(bvh), scene(scene), mesh(nullptr), prims(scene->device), sahBlockSize(sahBlockSize), intCost(intCost), minLeafSize(minLeafSize), maxLeafSize(min(maxLeafSize,Primitive::max_size()*BVH::maxLeafBlocks)), presplitFactor((mode & MODE_HIGH_QUALITY) ? defaultPresplitFactor : 1.0f) {} BVHNBuilderSAHQuantized (BVH* bvh, Mesh* mesh, const size_t sahBlockSize, const float intCost, const size_t minLeafSize, const size_t maxLeafSize, const size_t mode) : bvh(bvh), scene(nullptr), mesh(mesh), prims(bvh->device), sahBlockSize(sahBlockSize), intCost(intCost), minLeafSize(minLeafSize), maxLeafSize(min(maxLeafSize,Primitive::max_size()*BVH::maxLeafBlocks)), presplitFactor((mode & MODE_HIGH_QUALITY) ? defaultPresplitFactor : 1.0f) {} // FIXME: shrink bvh->alloc in destructor here and in other builders too void build(size_t, size_t) { /* skip build for empty scene */ const size_t numPrimitives = mesh ? mesh->size() : scene->getNumPrimitives<Mesh,false>(); if (numPrimitives == 0) { prims.clear(); bvh->clear(); return; } double t0 = bvh->preBuild(mesh ? "" : TOSTRING(isa) "::QBVH" + toString(N) + "BuilderSAH"); #if PROFILE profile(2,PROFILE_RUNS,numPrimitives,[&] (ProfileTimer& timer) { #endif /* create primref array */ const size_t numSplitPrimitives = max(numPrimitives,size_t(presplitFactor*numPrimitives)); prims.resize(numSplitPrimitives); PrimInfo pinfo = mesh ? createPrimRefArray<Mesh> (mesh ,prims,bvh->scene->progressInterface) : createPrimRefArray<Mesh,false>(scene,prims,bvh->scene->progressInterface); /* perform pre-splitting */ if (presplitFactor > 1.0f) pinfo = presplit<Mesh>(scene, pinfo, prims); /* call BVH builder */ bvh->alloc.init_estimate(pinfo.size()*sizeof(PrimRef)); BVHNBuilderQuantized<N>::build(bvh,CreateLeafQuantized<N,Primitive>(bvh,prims.data()),bvh->scene->progressInterface,prims.data(),pinfo,sahBlockSize,minLeafSize,maxLeafSize,travCost,intCost); #if PROFILE }); #endif /* clear temporary data for static geometry */ bool staticGeom = mesh ? mesh->isStatic() : scene->isStatic(); if (staticGeom) { prims.clear(); bvh->shrink(); } bvh->cleanup(); bvh->postBuild(t0); } void clear() { prims.clear(); } }; /************************************************************************************/ /************************************************************************************/ /************************************************************************************/ /************************************************************************************/ template<int N, typename Primitive> struct CreateMSMBlurLeaf { typedef BVHN<N> BVH; __forceinline CreateMSMBlurLeaf (BVH* bvh, PrimRef* prims, size_t time) : bvh(bvh), prims(prims), time(time) {} __forceinline LBBox3fa operator() (const BVHBuilderBinnedSAH::BuildRecord& current, Allocator* alloc) { size_t items = Primitive::blocks(current.prims.size()); size_t start = current.prims.begin(); Primitive* accel = (Primitive*) alloc->alloc1->malloc(items*sizeof(Primitive),BVH::byteNodeAlignment); typename BVH::NodeRef node = bvh->encodeLeaf((char*)accel,items); LBBox3fa allBounds = empty; for (size_t i=0; i<items; i++) allBounds.extend(accel[i].fillMB(prims, start, current.prims.end(), bvh->scene, false, time, bvh->numTimeSteps)); *current.parent = node; return allBounds; } BVH* bvh; PrimRef* prims; size_t time; }; template<int N, typename Mesh, typename Primitive> struct BVHNBuilderMSMBlurSAH : public Builder { typedef BVHN<N> BVH; typedef typename BVHN<N>::NodeRef NodeRef; BVH* bvh; Scene* scene; mvector<PrimRef> prims; const size_t sahBlockSize; const float intCost; const size_t minLeafSize; const size_t maxLeafSize; BVHNBuilderMSMBlurSAH (BVH* bvh, Scene* scene, const size_t sahBlockSize, const float intCost, const size_t minLeafSize, const size_t maxLeafSize) : bvh(bvh), scene(scene), prims(scene->device), sahBlockSize(sahBlockSize), intCost(intCost), minLeafSize(minLeafSize), maxLeafSize(min(maxLeafSize,Primitive::max_size()*BVH::maxLeafBlocks)) {} void build(size_t, size_t) { /* skip build for empty scene */ const size_t numPrimitives = scene->getNumPrimitives<Mesh,true>(); if (numPrimitives == 0) { prims.clear(); bvh->clear(); return; } double t0 = bvh->preBuild(TOSTRING(isa) "::BVH" + toString(N) + "BuilderMSMBlurSAH"); /* allocate buffers */ bvh->numTimeSteps = scene->getNumTimeSteps<Mesh,true>(); const size_t numTimeSegments = bvh->numTimeSteps-1; assert(bvh->numTimeSteps > 1); prims.resize(numPrimitives); bvh->alloc.init_estimate(numPrimitives*sizeof(PrimRef)*numTimeSegments); NodeRef* roots = (NodeRef*) bvh->alloc.threadLocal2()->alloc0->malloc(sizeof(NodeRef)*numTimeSegments,BVH::byteNodeAlignment); /* build BVH for each timestep */ avector<BBox3fa> bounds(bvh->numTimeSteps); size_t num_bvh_primitives = 0; for (size_t t=0; t<numTimeSegments; t++) { /* call BVH builder */ NodeRef root; LBBox3fa tbounds; const PrimInfo pinfo = createPrimRefArrayMBlur<Mesh>(t,bvh->numTimeSteps,scene,prims,bvh->scene->progressInterface); if (pinfo.size()) { std::tie(root, tbounds) = BVHNBuilderMblur<N>::build(bvh,CreateMSMBlurLeaf<N,Primitive>(bvh,prims.data(),t),bvh->scene->progressInterface,prims.data(),pinfo, sahBlockSize,minLeafSize,maxLeafSize,travCost,intCost); } else { tbounds = LBBox3fa(empty); root = BVH::emptyNode; } roots[t] = root; bounds[t+0] = tbounds.bounds0; bounds[t+1] = tbounds.bounds1; num_bvh_primitives = max(num_bvh_primitives,pinfo.size()); } bvh->set(NodeRef((size_t)roots),LBBox3fa(bounds),num_bvh_primitives); bvh->msmblur = true; /* clear temporary data for static geometry */ if (scene->isStatic()) { prims.clear(); bvh->shrink(); } bvh->cleanup(); bvh->postBuild(t0); } void clear() { prims.clear(); } }; /************************************************************************************/ /************************************************************************************/ /************************************************************************************/ /************************************************************************************/ template<int N> __forceinline size_t norotate(typename BVHN<N>::AlignedNode* node, const size_t* counts, const size_t num) { return 0; } template<int N, typename Mesh, typename Primitive, typename Splitter> struct BVHNBuilderFastSpatialSAH : public Builder { typedef BVHN<N> BVH; typedef typename BVH::NodeRef NodeRef; BVH* bvh; Scene* scene; Mesh* mesh; mvector<PrimRef> prims0; const size_t sahBlockSize; const float intCost; const size_t minLeafSize; const size_t maxLeafSize; const float splitFactor; BVHNBuilderFastSpatialSAH (BVH* bvh, Scene* scene, const size_t sahBlockSize, const float intCost, const size_t minLeafSize, const size_t maxLeafSize, const size_t mode) : bvh(bvh), scene(scene), mesh(nullptr), prims0(scene->device), sahBlockSize(sahBlockSize), intCost(intCost), minLeafSize(minLeafSize), maxLeafSize(min(maxLeafSize,Primitive::max_size()*BVH::maxLeafBlocks)), splitFactor(scene->device->max_spatial_split_replications) {} BVHNBuilderFastSpatialSAH (BVH* bvh, Mesh* mesh, const size_t sahBlockSize, const float intCost, const size_t minLeafSize, const size_t maxLeafSize, const size_t mode) : bvh(bvh), scene(nullptr), mesh(mesh), prims0(bvh->device), sahBlockSize(sahBlockSize), intCost(intCost), minLeafSize(minLeafSize), maxLeafSize(min(maxLeafSize,Primitive::max_size()*BVH::maxLeafBlocks)), splitFactor(scene->device->max_spatial_split_replications) {} // FIXME: shrink bvh->alloc in destructor here and in other builders too void build(size_t, size_t) { /* skip build for empty scene */ const size_t numOriginalPrimitives = mesh ? mesh->size() : scene->getNumPrimitives<Mesh,false>(); if (numOriginalPrimitives == 0) { prims0.clear(); bvh->clear(); return; } double t0 = bvh->preBuild(mesh ? "" : TOSTRING(isa) "::BVH" + toString(N) + "BuilderFastSpatialSAH"); /* create primref array */ const size_t numSplitPrimitives = max(numOriginalPrimitives,size_t(splitFactor*numOriginalPrimitives)); prims0.resize(numSplitPrimitives); PrimInfo pinfo = mesh ? createPrimRefArray<Mesh> (mesh ,prims0,bvh->scene->progressInterface) : createPrimRefArray<Mesh,false>(scene,prims0,bvh->scene->progressInterface); /* primref array could be smaller due to invalid geometry */ const size_t numPrimitives = pinfo.size(); /* calculate total surface area */ const float A = (float) parallel_reduce(size_t(0),numPrimitives,0.0, [&] (const range<size_t>& r) -> double // FIXME: this sum is not deterministic { double A = 0.0f; for (size_t i=r.begin(); i<r.end(); i++) { PrimRef& prim = prims0[i]; A += area(prim.bounds()); } return A; },std::plus<double>()); const float f = 10.0f; const float invA = 1.0f / A; /* calculate maximal number of spatial splits per primitive */ parallel_for( size_t(0), numPrimitives, [&](const range<size_t>& r) { for (size_t i=r.begin(); i<r.end(); i++) { PrimRef& prim = prims0[i]; assert((prim.lower.a & 0xFF000000) == 0); const float nf = ceilf(f*pinfo.size()*area(prim.bounds()) * invA); // FIXME: is there a better general heuristic ? size_t n = 4+min(ssize_t(127-4), max(ssize_t(1), ssize_t(nf))); prim.lower.a |= n << 24; } }); Splitter splitter(scene); bvh->alloc.init_estimate(pinfo.size()*sizeof(PrimRef)); NodeRef root; BVHBuilderBinnedFastSpatialSAH::build_reduce<NodeRef>( root, typename BVH::CreateAlloc(bvh), size_t(0), typename BVH::CreateAlignedNode(bvh), norotate<N>, CreateLeafSpatial<N,Primitive>(bvh,prims0.data()), splitter, bvh->scene->progressInterface, prims0.data(), numSplitPrimitives, pinfo, N,BVH::maxBuildDepthLeaf, sahBlockSize,minLeafSize,maxLeafSize, travCost,intCost); bvh->set(root,LBBox3fa(pinfo.geomBounds),pinfo.size()); bvh->layoutLargeNodes(size_t(pinfo.size()*0.005f)); /* clear temporary data for static geometry */ bool staticGeom = mesh ? mesh->isStatic() : scene->isStatic(); if (staticGeom) { prims0.clear(); bvh->shrink(); } bvh->cleanup(); bvh->postBuild(t0); } void clear() { prims0.clear(); } }; /************************************************************************************/ /************************************************************************************/ /************************************************************************************/ /************************************************************************************/ // FIXME: merge with standard class template<int N, typename Primitive> struct CreateLeafSweep { typedef BVHN<N> BVH; __forceinline CreateLeafSweep (BVH* bvh, PrimRef* prims) : bvh(bvh), prims(prims) {} __forceinline size_t operator() (const BVHBuilderSweepSAH::BuildRecord& current, Allocator* alloc) { size_t n = current.prims.size(); size_t items = Primitive::blocks(n); size_t start = current.prims.begin(); Primitive* accel = (Primitive*) alloc->alloc1->malloc(items*sizeof(Primitive),BVH::byteNodeAlignment); typename BVH::NodeRef node = BVH::encodeLeaf((char*)accel,items); for (size_t i=0; i<items; i++) { accel[i].fill(prims,start,current.prims.end(),bvh->scene,false); } *current.parent = node; return n; } BVH* bvh; PrimRef* prims; }; template<int N, typename Mesh, typename Primitive> struct BVHNBuilderSweepSAH : public Builder { typedef BVHN<N> BVH; BVH* bvh; Scene* scene; Mesh* mesh; mvector<PrimRef> prims; const size_t sahBlockSize; const float intCost; const size_t minLeafSize; const size_t maxLeafSize; const float presplitFactor; BVHNBuilderSweepSAH (BVH* bvh, Scene* scene, const size_t sahBlockSize, const float intCost, const size_t minLeafSize, const size_t maxLeafSize, const size_t mode) : bvh(bvh), scene(scene), mesh(nullptr), prims(scene->device), sahBlockSize(sahBlockSize), intCost(intCost), minLeafSize(minLeafSize), maxLeafSize(min(maxLeafSize,Primitive::max_size()*BVH::maxLeafBlocks)), presplitFactor((mode & MODE_HIGH_QUALITY) ? defaultPresplitFactor : 1.0f) {} BVHNBuilderSweepSAH (BVH* bvh, Mesh* mesh, const size_t sahBlockSize, const float intCost, const size_t minLeafSize, const size_t maxLeafSize, const size_t mode) : bvh(bvh), scene(nullptr), mesh(mesh), prims(bvh->device), sahBlockSize(sahBlockSize), intCost(intCost), minLeafSize(minLeafSize), maxLeafSize(min(maxLeafSize,Primitive::max_size()*BVH::maxLeafBlocks)), presplitFactor((mode & MODE_HIGH_QUALITY ) ? defaultPresplitFactor : 1.0f) {} // FIXME: shrink bvh->alloc in destructor here and in other builders too void build(size_t, size_t) { /* skip build for empty scene */ const size_t numPrimitives = mesh ? mesh->size() : scene->getNumPrimitives<Mesh,false>(); if (numPrimitives == 0) { prims.clear(); bvh->clear(); return; } double t0 = bvh->preBuild(mesh ? "" : TOSTRING(isa) "::BVH" + toString(N) + "BuilderSweepSAH"); #if PROFILE profile(2,PROFILE_RUNS,numPrimitives,[&] (ProfileTimer& timer) { #endif /* create primref array */ const size_t numSplitPrimitives = max(numPrimitives,size_t(presplitFactor*numPrimitives)); prims.resize(numSplitPrimitives); PrimInfo pinfo = mesh ? createPrimRefArray<Mesh> (mesh ,prims,bvh->scene->progressInterface) : createPrimRefArray<Mesh,false>(scene,prims,bvh->scene->progressInterface); /* perform pre-splitting */ if (presplitFactor > 1.0f) pinfo = presplit<Mesh>(scene, pinfo, prims); /* call BVH builder */ bvh->alloc.init_estimate(pinfo.size()*sizeof(PrimRef)); BVHNBuilderSweep<N>::build(bvh,CreateLeafSweep<N,Primitive>(bvh,prims.data()),bvh->scene->progressInterface,prims.data(),pinfo,sahBlockSize,minLeafSize,maxLeafSize,travCost,intCost); #if PROFILE }); #endif /* clear temporary data for static geometry */ bool staticGeom = mesh ? mesh->isStatic() : scene->isStatic(); if (staticGeom) { prims.clear(); bvh->shrink(); } bvh->cleanup(); bvh->postBuild(t0); } void clear() { prims.clear(); } }; /************************************************************************************/ /************************************************************************************/ /************************************************************************************/ /************************************************************************************/ #if defined(EMBREE_GEOMETRY_LINES) Builder* BVH4Line4iMeshBuilderSAH (void* bvh, LineSegments* mesh, size_t mode) { return new BVHNBuilderSAH<4,LineSegments,Line4i>((BVH4*)bvh,mesh,4,1.0f,4,inf,mode); } Builder* BVH4Line4iSceneBuilderSAH (void* bvh, Scene* scene, size_t mode) { return new BVHNBuilderSAH<4,LineSegments,Line4i>((BVH4*)bvh,scene,4,1.0f,4,inf,mode); } Builder* BVH4Line4iMBSceneBuilderSAH (void* bvh, Scene* scene, size_t mode) { return new BVHNBuilderMSMBlurSAH<4,LineSegments,Line4i>((BVH4*)bvh,scene ,4,1.0f,4,inf); } #if defined(__AVX__) Builder* BVH8Line4iSceneBuilderSAH (void* bvh, Scene* scene, size_t mode) { return new BVHNBuilderSAH<8,LineSegments,Line4i>((BVH8*)bvh,scene,4,1.0f,4,inf,mode); } Builder* BVH8Line4iMBSceneBuilderSAH (void* bvh, Scene* scene, size_t mode) { return new BVHNBuilderMSMBlurSAH<8,LineSegments,Line4i>((BVH8*)bvh,scene,4,1.0f,4,inf); } #endif #endif #if defined(EMBREE_GEOMETRY_HAIR) Builder* BVH4Bezier1vSceneBuilderSAH (void* bvh, Scene* scene, size_t mode) { return new BVHNBuilderSAH<4,BezierCurves,Bezier1v>((BVH4*)bvh,scene,1,1.0f,1,1,mode); } Builder* BVH4Bezier1iSceneBuilderSAH (void* bvh, Scene* scene, size_t mode) { return new BVHNBuilderSAH<4,BezierCurves,Bezier1i>((BVH4*)bvh,scene,1,1.0f,1,1,mode); } #endif #if defined(EMBREE_GEOMETRY_TRIANGLES) Builder* BVH4Triangle4MeshBuilderSAH (void* bvh, TriangleMesh* mesh, size_t mode) { return new BVHNBuilderSAH<4,TriangleMesh,Triangle4>((BVH4*)bvh,mesh,4,1.0f,4,inf,mode); } Builder* BVH4Triangle4vMeshBuilderSAH (void* bvh, TriangleMesh* mesh, size_t mode) { return new BVHNBuilderSAH<4,TriangleMesh,Triangle4v>((BVH4*)bvh,mesh,4,1.0f,4,inf,mode); } Builder* BVH4Triangle4iMeshBuilderSAH (void* bvh, TriangleMesh* mesh, size_t mode) { return new BVHNBuilderSAH<4,TriangleMesh,Triangle4i>((BVH4*)bvh,mesh,4,1.0f,4,inf,mode); } Builder* BVH4Triangle4SceneBuilderSAH (void* bvh, Scene* scene, size_t mode) { return new BVHNBuilderSAH<4,TriangleMesh,Triangle4>((BVH4*)bvh,scene,4,1.0f,4,inf,mode); } Builder* BVH4Triangle4vSceneBuilderSAH (void* bvh, Scene* scene, size_t mode) { return new BVHNBuilderSAH<4,TriangleMesh,Triangle4v>((BVH4*)bvh,scene,4,1.0f,4,inf,mode); } Builder* BVH4Triangle4iSceneBuilderSAH (void* bvh, Scene* scene, size_t mode) { return new BVHNBuilderSAH<4,TriangleMesh,Triangle4i>((BVH4*)bvh,scene,4,1.0f,4,inf,mode); } Builder* BVH4Triangle4vMBSceneBuilderSAH (void* bvh, Scene* scene, size_t mode) { return new BVHNBuilderMSMBlurSAH<4,TriangleMesh,Triangle4vMB>((BVH4*)bvh,scene,4,1.0f,4,inf); } Builder* BVH4Triangle4iMBSceneBuilderSAH (void* bvh, Scene* scene, size_t mode) { return new BVHNBuilderMSMBlurSAH<4,TriangleMesh,Triangle4iMB>((BVH4*)bvh,scene,4,1.0f,4,inf); } Builder* BVH4Triangle4SceneBuilderFastSpatialSAH (void* bvh, Scene* scene, size_t mode) { return new BVHNBuilderFastSpatialSAH<4,TriangleMesh,Triangle4,TriangleSplitterFactory>((BVH4*)bvh,scene,4,1.0f,4,inf,mode); } Builder* BVH4Triangle4vSceneBuilderFastSpatialSAH (void* bvh, Scene* scene, size_t mode) { return new BVHNBuilderFastSpatialSAH<4,TriangleMesh,Triangle4v,TriangleSplitterFactory>((BVH4*)bvh,scene,4,1.0f,4,inf,mode); } Builder* BVH4Triangle4iSceneBuilderFastSpatialSAH (void* bvh, Scene* scene, size_t mode) { return new BVHNBuilderFastSpatialSAH<4,TriangleMesh,Triangle4i,TriangleSplitterFactory>((BVH4*)bvh,scene,4,1.0f,4,inf,mode); } Builder* BVH4QuantizedTriangle4iSceneBuilderSAH (void* bvh, Scene* scene, size_t mode) { return new BVHNBuilderSAHQuantized<4,TriangleMesh,Triangle4i>((BVH4*)bvh,scene,4,1.0f,4,inf,mode); } #if defined(__AVX__) Builder* BVH8Triangle4MeshBuilderSAH (void* bvh, TriangleMesh* mesh, size_t mode) { return new BVHNBuilderSAH<8,TriangleMesh,Triangle4>((BVH8*)bvh,mesh,4,1.0f,4,inf,mode); } Builder* BVH8Triangle4vMeshBuilderSAH (void* bvh, TriangleMesh* mesh, size_t mode) { return new BVHNBuilderSAH<8,TriangleMesh,Triangle4v>((BVH8*)bvh,mesh,4,1.0f,4,inf,mode); } Builder* BVH8Triangle4iMeshBuilderSAH (void* bvh, TriangleMesh* mesh, size_t mode) { return new BVHNBuilderSAH<8,TriangleMesh,Triangle4i>((BVH8*)bvh,mesh,4,1.0f,4,inf,mode); } Builder* BVH8Triangle4SceneBuilderSAH (void* bvh, Scene* scene, size_t mode) { return new BVHNBuilderSAH<8,TriangleMesh,Triangle4>((BVH8*)bvh,scene,4,1.0f,4,inf,mode); } Builder* BVH8Triangle4vSceneBuilderSAH (void* bvh, Scene* scene, size_t mode) { return new BVHNBuilderSAH<8,TriangleMesh,Triangle4v>((BVH8*)bvh,scene,4,1.0f,4,inf,mode); } Builder* BVH8Triangle4iSceneBuilderSAH (void* bvh, Scene* scene, size_t mode) { return new BVHNBuilderSAH<8,TriangleMesh,Triangle4i>((BVH8*)bvh,scene,4,1.0f,4,inf,mode); } Builder* BVH8Triangle4vMBSceneBuilderSAH (void* bvh, Scene* scene, size_t mode) { return new BVHNBuilderMSMBlurSAH<8,TriangleMesh,Triangle4vMB>((BVH8*)bvh,scene,4,1.0f,4,inf); } Builder* BVH8Triangle4iMBSceneBuilderSAH (void* bvh, Scene* scene, size_t mode) { return new BVHNBuilderMSMBlurSAH<8,TriangleMesh,Triangle4iMB>((BVH8*)bvh,scene,4,1.0f,4,inf); } Builder* BVH8QuantizedTriangle4iSceneBuilderSAH (void* bvh, Scene* scene, size_t mode) { return new BVHNBuilderSAHQuantized<8,TriangleMesh,Triangle4i>((BVH8*)bvh,scene,4,1.0f,4,inf,mode); } Builder* BVH8Triangle4SceneBuilderFastSpatialSAH (void* bvh, Scene* scene, size_t mode) { return new BVHNBuilderFastSpatialSAH<8,TriangleMesh,Triangle4,TriangleSplitterFactory>((BVH8*)bvh,scene,4,1.0f,4,inf,mode); } Builder* BVH8Triangle4vSceneBuilderFastSpatialSAH (void* bvh, Scene* scene, size_t mode) { return new BVHNBuilderFastSpatialSAH<8,TriangleMesh,Triangle4v,TriangleSplitterFactory>((BVH8*)bvh,scene,4,1.0f,4,inf,mode); } /* experimental full sweep builder */ Builder* BVH8Triangle4SceneBuilderSweepSAH (void* bvh, Scene* scene, size_t mode) { return new BVHNBuilderSweepSAH<8,TriangleMesh,Triangle4>((BVH8*)bvh,scene,4,1.0f,4,inf,mode); } #endif #endif #if defined(EMBREE_GEOMETRY_QUADS) Builder* BVH4Quad4vMeshBuilderSAH (void* bvh, QuadMesh* mesh, size_t mode) { return new BVHNBuilderSAH<4,QuadMesh,Quad4v>((BVH4*)bvh,mesh,4,1.0f,4,inf,mode); } Builder* BVH4Quad4iMeshBuilderSAH (void* bvh, QuadMesh* mesh, size_t mode) { return new BVHNBuilderSAH<4,QuadMesh,Quad4i>((BVH4*)bvh,mesh,4,1.0f,4,inf,mode); } Builder* BVH4Quad4vSceneBuilderSAH (void* bvh, Scene* scene, size_t mode) { return new BVHNBuilderSAH<4,QuadMesh,Quad4v>((BVH4*)bvh,scene,4,1.0f,4,inf,mode); } Builder* BVH4Quad4iSceneBuilderSAH (void* bvh, Scene* scene, size_t mode) { return new BVHNBuilderSAH<4,QuadMesh,Quad4i>((BVH4*)bvh,scene,4,1.0f,4,inf,mode); } Builder* BVH4Quad4iMBSceneBuilderSAH (void* bvh, Scene* scene, size_t mode) { return new BVHNBuilderMSMBlurSAH<4,QuadMesh,Quad4iMB>((BVH4*)bvh,scene ,4,1.0f,4,inf); } Builder* BVH4QuantizedQuad4vSceneBuilderSAH (void* bvh, Scene* scene, size_t mode) { return new BVHNBuilderSAHQuantized<4,QuadMesh,Quad4v>((BVH4*)bvh,scene,4,1.0f,4,inf,mode); } Builder* BVH4QuantizedQuad4iSceneBuilderSAH (void* bvh, Scene* scene, size_t mode) { return new BVHNBuilderSAHQuantized<4,QuadMesh,Quad4i>((BVH4*)bvh,scene,4,1.0f,4,inf,mode); } Builder* BVH4Quad4vSceneBuilderFastSpatialSAH (void* bvh, Scene* scene, size_t mode) { return new BVHNBuilderFastSpatialSAH<4,QuadMesh,Quad4v,QuadSplitterFactory>((BVH4*)bvh,scene,4,1.0f,4,inf,mode); } #if defined(__AVX__) Builder* BVH8Quad4vSceneBuilderSAH (void* bvh, Scene* scene, size_t mode) { return new BVHNBuilderSAH<8,QuadMesh,Quad4v>((BVH8*)bvh,scene,4,1.0f,4,inf,mode); } Builder* BVH8Quad4iSceneBuilderSAH (void* bvh, Scene* scene, size_t mode) { return new BVHNBuilderSAH<8,QuadMesh,Quad4i>((BVH8*)bvh,scene,4,1.0f,4,inf,mode); } Builder* BVH8Quad4iMBSceneBuilderSAH (void* bvh, Scene* scene, size_t mode) { return new BVHNBuilderMSMBlurSAH<8,QuadMesh,Quad4iMB>((BVH8*)bvh,scene,4,1.0f,4,inf); } Builder* BVH8QuantizedQuad4vSceneBuilderSAH (void* bvh, Scene* scene, size_t mode) { return new BVHNBuilderSAHQuantized<8,QuadMesh,Quad4v>((BVH8*)bvh,scene,4,1.0f,4,inf,mode); } Builder* BVH8QuantizedQuad4iSceneBuilderSAH (void* bvh, Scene* scene, size_t mode) { return new BVHNBuilderSAHQuantized<8,QuadMesh,Quad4i>((BVH8*)bvh,scene,4,1.0f,4,inf,mode); } Builder* BVH8Quad4vMeshBuilderSAH (void* bvh, QuadMesh* mesh, size_t mode) { return new BVHNBuilderSAH<8,QuadMesh,Quad4v>((BVH8*)bvh,mesh,4,1.0f,4,inf,mode); } Builder* BVH8Quad4vSceneBuilderFastSpatialSAH (void* bvh, Scene* scene, size_t mode) { return new BVHNBuilderFastSpatialSAH<8,QuadMesh,Quad4v,QuadSplitterFactory>((BVH8*)bvh,scene,4,1.0f,4,inf,mode); } #endif #endif #if defined(EMBREE_GEOMETRY_USER) Builder* BVH4VirtualSceneBuilderSAH (void* bvh, Scene* scene, size_t mode) { int minLeafSize = scene->device->object_accel_min_leaf_size; int maxLeafSize = scene->device->object_accel_max_leaf_size; return new BVHNBuilderSAH<4,AccelSet,Object>((BVH4*)bvh,scene,4,1.0f,minLeafSize,maxLeafSize,mode); } Builder* BVH4VirtualMeshBuilderSAH (void* bvh, AccelSet* mesh, size_t mode) { return new BVHNBuilderSAH<4,AccelSet,Object>((BVH4*)bvh,mesh,4,1.0f,1,inf,mode); } Builder* BVH4VirtualMBSceneBuilderSAH (void* bvh, Scene* scene, size_t mode) { int minLeafSize = scene->device->object_accel_mb_min_leaf_size; int maxLeafSize = scene->device->object_accel_mb_max_leaf_size; return new BVHNBuilderMSMBlurSAH<4,AccelSet,Object>((BVH4*)bvh,scene,4,1.0f,minLeafSize,maxLeafSize); } #endif } }
48.493976
222
0.603423
[ "mesh", "geometry", "object" ]
bf60cc7bbf90f494d214c3b42cd55c85d34cc720
5,038
cpp
C++
dev/Gems/PhysX/Code/Editor/CollisionGroupWidget.cpp
BadDevCode/lumberyard
3d688932f919dbf5821f0cb8a210ce24abe39e9e
[ "AML" ]
2
2020-06-27T12:13:44.000Z
2020-06-27T12:13:46.000Z
dev/Gems/PhysX/Code/Editor/CollisionGroupWidget.cpp
olivier-be/lumberyard
3d688932f919dbf5821f0cb8a210ce24abe39e9e
[ "AML" ]
null
null
null
dev/Gems/PhysX/Code/Editor/CollisionGroupWidget.cpp
olivier-be/lumberyard
3d688932f919dbf5821f0cb8a210ce24abe39e9e
[ "AML" ]
null
null
null
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #include <PhysX_precompiled.h> #include <Editor/CollisionGroupWidget.h> #include <Editor/ConfigurationWindowBus.h> #include <AzCore/Interface/Interface.h> #include <AzFramework/Physics/PropertyTypes.h> #include <AzToolsFramework/API/ToolsApplicationAPI.h> #include <LyViewPaneNames.h> #include <AzFramework/Physics/CollisionBus.h> namespace PhysX { namespace Editor { CollisionGroupWidget::CollisionGroupWidget() { } AZ::u32 CollisionGroupWidget::GetHandlerName() const { return Physics::Edit::CollisionGroupSelector; } QWidget* CollisionGroupWidget::CreateGUI(QWidget* parent) { widget_t* picker = new widget_t(parent); picker->GetEditButton()->setToolTip("Edit Collision Groups"); connect(picker->GetComboBox(), &QComboBox::currentTextChanged, this, [picker]() { EBUS_EVENT(AzToolsFramework::PropertyEditorGUIMessages::Bus, RequestWrite, picker); }); connect(picker->GetEditButton(), &QPushButton::clicked, this, &CollisionGroupWidget::OnEditButtonClicked); return picker; } bool CollisionGroupWidget::IsDefaultHandler() const { return true; } void CollisionGroupWidget::ConsumeAttribute(widget_t* GUI, AZ::u32 attrib, AzToolsFramework::PropertyAttributeReader* attrValue, const char* debugName) { if (attrib == AZ::Edit::Attributes::ReadOnly) { bool value = false; if (attrValue->Read<bool>(value)) { GUI->setEnabled(!value); } } } void CollisionGroupWidget::WriteGUIValuesIntoProperty(size_t index, widget_t* GUI, property_t& instance, AzToolsFramework::InstanceDataNode* node) { instance = GetGroupFromName(GUI->GetComboBox()->currentText().toUtf8().data()); } bool CollisionGroupWidget::ReadValuesIntoGUI(size_t index, widget_t* GUI, const property_t& instance, AzToolsFramework::InstanceDataNode* node) { QSignalBlocker signalBlocker(GUI->GetComboBox()); GUI->GetComboBox()->clear(); auto groupNames = GetGroupNames(); for (auto& layerName : groupNames) { GUI->GetComboBox()->addItem(layerName.c_str()); } auto groupName = GetNameFromGroup(instance); GUI->GetComboBox()->setCurrentText(groupName.c_str()); return true; } void CollisionGroupWidget::OnEditButtonClicked() { // Open configuration window AzToolsFramework::EditorRequestBus::Broadcast(&AzToolsFramework::EditorRequests::OpenViewPane, LyViewPane::PhysXConfigurationEditor); // Set to collision groups tab ConfigurationWindowRequestBus::Broadcast(&ConfigurationWindowRequests::ShowCollisionGroupsTab); } Physics::CollisionGroups::Id CollisionGroupWidget::GetGroupFromName(const AZStd::string& groupName) { const Physics::CollisionConfiguration& configuration = AZ::Interface<Physics::CollisionRequests>::Get()->GetCollisionConfiguration(); return configuration.m_collisionGroups.FindGroupIdByName(groupName); } AZStd::string CollisionGroupWidget::GetNameFromGroup(const Physics::CollisionGroups::Id& collisionGroup) { const Physics::CollisionConfiguration& configuration = AZ::Interface<Physics::CollisionRequests>::Get()->GetCollisionConfiguration(); return configuration.m_collisionGroups.FindGroupNameById(collisionGroup); } AZStd::vector<AZStd::string> CollisionGroupWidget::GetGroupNames() { const Physics::CollisionConfiguration& configuration = AZ::Interface<Physics::CollisionRequests>::Get()->GetCollisionConfiguration(); const AZStd::vector<Physics::CollisionGroups::Preset>& collisionGroupPresets = configuration.m_collisionGroups.GetPresets(); AZStd::vector<AZStd::string> groupNames; groupNames.reserve(collisionGroupPresets.size()); for (const auto& preset : collisionGroupPresets) { groupNames.push_back(preset.m_name); } return groupNames; } } // namespace Editor } // namespace PhysX #include <Editor/CollisionGroupWidget.moc>
39.359375
159
0.657007
[ "vector" ]
bf69c4236429f45455f89bb21f982e74ebb36e95
2,242
cpp
C++
libraries/blockchain/pts_address.cpp
peertracksinc/bitmusic
2244ada6b1425a94e8b6dea8602d053954268780
[ "Unlicense" ]
null
null
null
libraries/blockchain/pts_address.cpp
peertracksinc/bitmusic
2244ada6b1425a94e8b6dea8602d053954268780
[ "Unlicense" ]
null
null
null
libraries/blockchain/pts_address.cpp
peertracksinc/bitmusic
2244ada6b1425a94e8b6dea8602d053954268780
[ "Unlicense" ]
null
null
null
#include <bts/blockchain/exceptions.hpp> #include <bts/blockchain/pts_address.hpp> #include <fc/crypto/base58.hpp> #include <fc/crypto/elliptic.hpp> #include <fc/crypto/ripemd160.hpp> #include <algorithm> namespace bts { namespace blockchain { pts_address::pts_address() { memset( addr.data, 0, sizeof(addr.data) ); } pts_address::pts_address( const std::string& base58str ) { std::vector<char> v = fc::from_base58( fc::string(base58str) ); if( v.size() ) memcpy( addr.data, v.data(), std::min<size_t>( v.size(), sizeof(addr) ) ); if( !is_valid() ) { FC_THROW_EXCEPTION( invalid_pts_address, "invalid pts_address ${a}", ("a", base58str) ); } } pts_address::pts_address( const fc::ecc::public_key& pub, bool compressed, uint8_t version ) { fc::sha256 sha2; if( compressed ) { auto dat = pub.serialize(); sha2 = fc::sha256::hash(dat.data, sizeof(dat) ); } else { auto dat = pub.serialize_ecc_point(); sha2 = fc::sha256::hash(dat.data, sizeof(dat) ); } auto rep = fc::ripemd160::hash((char*)&sha2,sizeof(sha2)); addr.data[0] = version; memcpy( addr.data+1, (char*)&rep, sizeof(rep) ); auto check = fc::sha256::hash( addr.data, sizeof(rep)+1 ); check = fc::sha256::hash(check); // double memcpy( addr.data+1+sizeof(rep), (char*)&check, 4 ); } /** * Checks the address to verify it has a * valid checksum */ bool pts_address::is_valid()const { auto check = fc::sha256::hash( addr.data, sizeof(fc::ripemd160)+1 ); check = fc::sha256::hash(check); // double return memcmp( addr.data+1+sizeof(fc::ripemd160), (char*)&check, 4 ) == 0; } pts_address::operator std::string()const { return fc::to_base58( addr.data, sizeof(addr) ); } } } // namespace bts namespace fc { void to_variant( const bts::blockchain::pts_address& var, variant& vo ) { vo = std::string(var); } void from_variant( const variant& var, bts::blockchain::pts_address& vo ) { vo = bts::blockchain::pts_address( var.as_string() ); } }
28.74359
99
0.584746
[ "vector" ]
bf6e863085605838dd141fe2a890c44113fbe435
26,556
hpp
C++
components/arduino/tools/sdk/esp32s2/include/esp-face/include/typedef/dl_variable.hpp
Jason2866/LILYGO-_T5-4.7-E-Paper_Weather-_Station
c41679f84d99c3423a6e7413365804c9acb17458
[ "Unlicense" ]
null
null
null
components/arduino/tools/sdk/esp32s2/include/esp-face/include/typedef/dl_variable.hpp
Jason2866/LILYGO-_T5-4.7-E-Paper_Weather-_Station
c41679f84d99c3423a6e7413365804c9acb17458
[ "Unlicense" ]
2
2021-11-18T07:10:52.000Z
2021-12-06T17:05:22.000Z
components/arduino/tools/sdk/esp32s2/include/esp-face/include/typedef/dl_variable.hpp
Jason2866/LILYGO-_T5-4.7-E-Paper_Weather-_Station
c41679f84d99c3423a6e7413365804c9acb17458
[ "Unlicense" ]
1
2022-01-02T23:14:22.000Z
2022-01-02T23:14:22.000Z
#pragma once #include <stdio.h> #include <vector> #include <assert.h> #include "dl_tool.hpp" namespace dl { /** * @brief Tensor * * @tparam T support uint8_t, int8_t, int16_t and float. */ template <typename T> class Tensor { private: int size; /*<! size of element including padding */ bool auto_free; /*<! free element when object destroy */ public: T *element; /*<! point to element */ int exponent; /*<! exponent of element */ std::vector<int> shape; /*<! shape of Tensor */ /*<! 2D: shape is [height, width, channel] */ /*<! 1D: reserved */ std::vector<int> shape_with_padding; /*<! shape with padding of Tensor */ /*<! 2D: shape_with_padding is [height_with_padding, width_with_padding, channel_with_padding] */ /*<! 1D: reserved */ std::vector<int> padding; /*<! padding of Tensor */ /*<!- 2D: padding format is [top, bottom, left, right] */ /*<! - 1D: reserved */ /** * @brief Construct a new Tensor object * */ Tensor() : size(-1), auto_free(true), element(NULL), exponent(0) {} /** * @brief Construct a new Tensor object by copying from input. * * @param input an input Tensor * @param deep one of true or false * - true: apply a new memory, copy value from input.element to this new memory * - false: take over input.element to this->element */ Tensor(Tensor<T> &input, bool deep) : size(input.size), auto_free(input.auto_free), exponent(input.exponent), shape(input.shape), shape_with_padding(input.shape_with_padding), padding(input.padding) { if (deep) { int size_real = input.shape_with_padding.size() ? input.shape_with_padding[0] * input.shape_with_padding[1] * input.shape_with_padding[2] : 0; T *new_element = (T *)tool::calloc_aligned(size_real, sizeof(T), 16); tool::copy_memory(new_element, input.element, size_real * sizeof(T)); this->element = new_element; } else { this->element = input.element; } } /** * @brief Destroy the Tensor object * */ ~Tensor() { if (this->auto_free) this->free_element(); } /** * @brief Set the auto free object. * * @param auto_free one of true or false * - true: free element when object destroyed * - false: do not * @return self */ Tensor<T> &set_auto_free(const bool auto_free) { this->auto_free = auto_free; return *this; } /** * @brief Set the element. * * @param element point to element memory * @return self */ Tensor<T> &set_element(T *element, const bool auto_free = false) { assert(this->element == NULL); this->element = element; this->auto_free = auto_free; return *this; } /** * @brief Set the exponent. * * @param exponent exponent of element * @return self */ Tensor<T> &set_exponent(const int exponent) { this->exponent = exponent; return *this; } /** * @brief Set the shape of Tensor. Initial this->padding = {0}. Initial this->size = -1. * * @param shape shape in * - 2D: [height, width] * @return self */ Tensor<T> &set_shape(const std::vector<int> shape) { for (int i = 0; i < shape.size(); ++i) { assert(shape[i] > 0); } this->shape = shape; this->shape_with_padding = shape; this->size = -1; this->padding = std::vector<int>(((this->shape.size() - 1) << 1), 0); return *this; } /** * @brief Set the padding size object. * * @param padding padding size in * - 2D: [top, bottom, left, right] * @return self */ Tensor &set_padding_size(std::vector<int> &padding) { assert(this->shape.size()); // call Tensor.set_shape() first assert(this->shape.size() == 3); // TODO: || this->shape.size() == 2 if (this->shape.size() == 3) { std::vector<int> new_padding = this->padding; bool dont_update = true; if (padding[0] > this->padding[0]) { new_padding[0] = padding[0]; dont_update = false; } if (padding[1] > this->padding[1]) { new_padding[1] = padding[1]; dont_update = false; } if (padding[2] > this->padding[2]) { new_padding[2] = padding[2]; dont_update = false; } if (padding[3] > this->padding[3]) { new_padding[3] = padding[3]; dont_update = false; } if (dont_update) { return *this; } std::vector<int> new_shape_with_padding = this->shape; new_shape_with_padding[0] += (new_padding[0] + new_padding[1]); new_shape_with_padding[1] += (new_padding[2] + new_padding[3]); int new_size = new_shape_with_padding[0] * new_shape_with_padding[1] * new_shape_with_padding[2]; if (this->element) // if this->element != NULL, do padding by copy memory { T *new_element = (T *)tool::malloc_aligned(new_size, sizeof(T), 16); T *dst = new_element + ((new_padding[0] * new_shape_with_padding[1]) + new_padding[2]) * new_shape_with_padding[2]; T *src = this->get_element_ptr(); int offset_dst_next_y = new_shape_with_padding[1] * new_shape_with_padding[2]; // width * channel int src_copy_length = this->shape[1] * this->shape[2]; // width * channel int offset_src_next_y = this->shape_with_padding[1] * this->shape_with_padding[2]; // width * channel for (int y = 0; y < this->shape[0]; y++) { tool::copy_memory(dst, src, src_copy_length * sizeof(T)); dst += offset_dst_next_y; src += offset_src_next_y; } if (this->auto_free) tool::free_aligned(this->element); this->element = new_element; this->auto_free = true; } this->padding = new_padding; this->shape_with_padding = new_shape_with_padding; this->size = new_size; } else if (this->shape.size() == 2) { printf("Tensor.set_padding_size with this->shape.size() == 2 not implement yet.\n"); } return *this; } /** * @brief Set the padding value object. * * @param padding padding size in * - 2D: [top, bottom, left, right] * @param value value to set * @return self */ Tensor<T> &set_padding_value(std::vector<int> &padding, T value); /** * @brief Get the element pointer. * * @param padding padding size in * - 2D: [top, bottom, left, right] * @return pointer to memory with padding */ T *get_element_ptr(const std::vector<int> padding = {0, 0, 0, 0}) { assert(this->shape.size() == 3); // TODO: || this->shape.size() == 2 if (this->shape.size() == 3) { return this->element + ((this->padding[0] - padding[0]) * this->shape_with_padding[1] + (this->padding[2] - padding[2])) * this->shape_with_padding[2]; } else if (this->shape.size() == 2) { printf("Tensor.get_element_ptr with this->shape.size() == 2 is not implemented.\n"); } return NULL; } /** * @brief Get the element value. * * @param index index in * - 2D: [y, x, c] * @param with_padding one of true or false, * - true: make padding size in count * - false: do not * @return element value */ T &get_element_value(const std::vector<int> index, const bool with_padding = false) { assert(index.size() == this->shape.size()); assert(this->shape.size() == 3); // TODO: || this->shape() == 2 int i = 0; if (this->shape.size() == 3) { int y = index[0]; int x = index[1]; int c = index[2]; i = with_padding ? (y * this->shape_with_padding[1] + x) * this->shape_with_padding[2] + c : ((y + this->padding[0]) * this->shape_with_padding[1] + x + this->padding[2]) * this->shape_with_padding[2] + c; } else if (this->shape.size() == 2) { printf("Tensor.get_element_value with this->shape.size() == 2 is not implemented.\n"); } return this->element[i]; } /** * @brief Get the size of element. * * @return size of element including padding */ int get_size() { if (this->size == -1) // didn't call Tensor.set_padding_size() before { this->size = 1; for (std::vector<int>::iterator d = this->shape.begin(); d != this->shape.end(); d++) this->size *= *d; } return this->size; } /** * @brief Apply memory with zero-initialized only if this->element is NULL. * * @param auto_free one of true or false * - true: free element when object destroyed * - false: do not * @return * - true: on success * - false: if applying failed */ bool calloc_element(const bool auto_free = true) { if (this->element != NULL) return false; this->element = (T *)dl::tool::calloc_aligned(this->get_size(), sizeof(T), 16); this->auto_free = auto_free; return true; } /** * @brief Apply memory without initialized only if this->element is NULL. * * @param auto_free one of true or false * - true: free element when object destroyed * - false: do not * @return * - true: on success * - false: if applying failed */ bool malloc_element(const bool auto_free = true) { if (this->element != NULL) return false; this->element = (T *)tool::malloc_aligned(this->get_size(), sizeof(T), 16); this->auto_free = auto_free; return true; } /** * @brief If this->element != NULL no memory will be applied and no value will be set in padding. * Else apply memory without initialized and set value to padding. * * @param padding_value value to set in padding * @param auto_free one of true of false * - true: free element when object destroyed * - false: do not * @return * - true: apply memory and set padding value successfully * - false: no memory applied and no padding value set */ bool apply_element(const T padding_value = 0, const bool auto_free = true) { if (this->element != NULL) return false; this->element = (T *)tool::malloc_aligned(this->get_size(), sizeof(T), 16); this->set_padding_value(this->padding, padding_value); this->auto_free = auto_free; return true; } /** * @brief free element only if this->element != NULL * set this->element to NULL, after free * @brief Free element if this->element is not NULL. */ void free_element() { if (this->auto_free && this->element) { tool::free_aligned(this->element); this->element = NULL; } } /** * @brief Print the shape of Tensor in format "shape = ({top_padding} + {height} + {bottom_padding}, {left_padding} + {width} + {right_padding}, {channel}(channel_with_padding))\n". */ void print_shape() { printf("shape = (%d + %d + %d, %d + %d + %d, %d(%d))\n", this->padding[0], this->shape[0], this->padding[1], this->padding[2], this->shape[1], this->padding[3], this->shape[2], this->shape_with_padding[2]); } /** * @brief Take numpy for example, this function print Tensor[y_start:y_end, x_start:x_end, c_start:c_end]. * * inner box is effective value of Tensor, "0" around is padding. * * (with padding) * 00000000000000000000000000000000000000000000000000 * 00000000000000000000000000000000000000000000000000 * 00000000000000000000000000000000000000000000000000 * 000000(without padding) 00000000 * 000000 00000000 * 000000 00000000 * 000000 effective value 00000000 * 000000 00000000 * 000000 00000000 * 00000000000000000000000000000000000000000000000000 * 00000000000000000000000000000000000000000000000000 * 00000000000000000000000000000000000000000000000000 * * @param y_start start index in height * @param y_end end index in height * @param x_start start index in width * @param x_end end index in width * @param c_start start index in channel * @param c_end end index in channel * @param message to print * @param axis print aligned this axis, effective only if all y_end - y_start, x_end - x_start and c_end - c_start equals to 1 * @param with_padding one of true or false, * - true: count from (with padding) in upper image * - false: count from (without padding) in upper image */ void print(int y_start, int y_end, int x_start, int x_end, int c_start, int c_end, const char *message, int axis = 0, const bool with_padding = false) { assert(y_end > y_start); assert(x_end > x_start); assert(c_end > c_start); y_start = DL_MAX(y_start, 0); x_start = DL_MAX(x_start, 0); c_start = DL_MAX(c_start, 0); if (with_padding) { y_end = DL_MIN(y_end, this->shape_with_padding[0]); x_end = DL_MIN(x_end, this->shape_with_padding[1]); c_end = DL_MIN(c_end, this->shape_with_padding[2]); } else { y_end = DL_MIN(y_end, this->shape[0]); x_end = DL_MIN(x_end, this->shape[1]); c_end = DL_MIN(c_end, this->shape[2]); } printf("%s[%d:%d, %d:%d, %d:%d] | ", message, y_start, y_end, x_start, x_end, c_start, c_end); this->print_shape(); if (y_end - y_start == 1) { if (x_end - x_start == 1) { for (int c = c_start; c < c_end; c++) printf("%7d", c); printf("\n"); for (int c = c_start; c < c_end; c++) printf("%7d", this->get_element_value({y_start, x_start, c}, with_padding)); printf("\n"); return; } else { if (c_end - c_start == 1) { for (int x = x_start; x < x_end; x++) printf("%7d", x); printf("\n"); for (int x = x_start; x < x_end; x++) printf("%7d", this->get_element_value({y_start, x, c_start}, with_padding)); printf("\n"); return; } } } else { if (x_end - x_start == 1) { if (c_end - c_start == 1) { for (int y = y_start; y < y_end; y++) printf("%7d", y); printf("\n"); for (int y = y_start; y < y_end; y++) printf("%7d", this->get_element_value({y, x_start, c_start}, with_padding)); printf("\n"); return; } } } if (y_end - y_start == 1) axis = 0; if (x_end - x_start == 1) axis = 1; if (c_end - c_start == 1) axis = 2; if (axis == 0) { // ______c // | // | // x // for (int y = y_start; y < y_end; y++) { printf("y = %d\n ", y); for (int c = c_start; c < c_end; c++) printf("%7d", c); printf("\n"); for (int x = x_start; x < x_end; x++) { printf("%5d", x); for (int c = c_start; c < c_end; c++) printf("%7d", this->get_element_value({y, x, c}, with_padding)); printf("\n"); } printf("\n"); } } else if (axis == 1) { // ______c // | // | // y // for (int x = x_start; x < x_end; x++) { printf("x = %d\n ", x); for (int c = c_start; c < c_end; c++) printf("%7d", c); printf("\n"); for (int y = y_start; y < y_end; y++) { printf("%5d", y); for (int c = c_start; c < c_end; c++) printf("%7d", this->get_element_value({y, x, c}, with_padding)); printf("\n"); } printf("\n"); } } else { // ______x // | // | // y // for (int c = c_start; c < c_end; c++) { printf("c = %d\n ", c); for (int x = x_start; x < x_end; x++) printf("%7d", x); printf("\n"); for (int y = y_start; y < y_end; y++) { printf("%5d", y); for (int x = x_start; x < x_end; x++) printf("%7d", this->get_element_value({y, x, c}, with_padding)); printf("\n"); } printf("\n"); } } return; } /** * @brief print all the element of the Tensor. * * @param message to print * @param with_padding one of true or false, * - true: the padding element will also be printed * - false: the padding element will not be printed */ void print_all(const char *message, const bool with_padding = false) { int y_end; int x_end; int c_end; if (with_padding) { y_end = this->shape_with_padding[0]; x_end = this->shape_with_padding[1]; c_end = this->shape_with_padding[2]; } else { y_end = this->shape[0]; x_end = this->shape[1]; c_end = this->shape[2]; } printf("\n%s | ", message); this->print_shape(); for (int y = 0; y < y_end; y++) { for (int x = 0; x < x_end; x++) { for (int c = 0; c < c_end; c++) printf("%d ", this->get_element_value({y, x, c}, with_padding)); } } printf("\n"); return; } /** * @brief Check the element value with input ground-truth. * * @param gt_element ground-truth value of element * @param bias permissible error * @param info one of true or false * - true: print shape and result * - false: do not * @return * - true: in permissible error * - false: not */ bool check_element(T *gt_element, int bias = 2, bool info = true) { if (info) this->print_shape(); int i = 0; for (int y = 0; y < this->shape[0]; y++) { for (int x = 0; x < this->shape[1]; x++) { for (int c = 0; c < this->shape[2]; c++) { int a = this->get_element_value({y, x, c}); int b = gt_element[i]; int offset = DL_ABS(a - b); if (offset > bias) { printf("element[%d, %d, %d]: %d v.s. %d\n", y, x, c, a, b); return false; } i++; } } } if (info) printf("PASS\n"); return true; } /** * @brief Check the shape is the same as the shape of input. * * @param input an input tensor * @return * - true: same shape * - false: not */ bool is_same_shape(Tensor<T> &input) { if (input.shape.size() != this->shape.size()) { return false; } for (int i = 0; i < this->shape.size(); i++) { if (input.shape[i] != this->shape[i]) { return false; } } return true; } Tensor<T> &operator=(const Tensor<T> &input) { this->size = input.size; this->auto_free = input.auto_free; this->exponent = input.exponent; this->shape = input.shape; this->padding = input.padding; int size_real_tmp = this->shape_with_padding.size() ? this->shape_with_padding[0] * this->shape_with_padding[1] * this->shape_with_padding[2] : 0; int size_input_real = input.shape_with_padding.size() ? input.shape_with_padding[0] * input.shape_with_padding[1] * input.shape_with_padding[2] : 0; this->shape_with_padding = input.shape_with_padding; if (this->element) { if (size_real_tmp != size_input_real) { tool::free_aligned(this->element); T *new_element = (T *)tool::calloc_aligned(size_input_real, sizeof(T), 16); tool::copy_memory(new_element, input.element, size_input_real * sizeof(T)); this->element = new_element; } else { tool::copy_memory(this->element, input.element, size_input_real * sizeof(T)); } } else { T *new_element = (T *)tool::calloc_aligned(size_input_real, sizeof(T), 16); tool::copy_memory(new_element, input.element, size_input_real * sizeof(T)); this->element = new_element; } return *this; } }; } // namespace dl
36.179837
221
0.421524
[ "object", "shape", "vector" ]
bf7594803d80fa9fd402b97042371963aca836f3
11,755
cpp
C++
libraries/utils/selectionio.cpp
Zeitproblem/mne-cpp
38bc3ba5213bbb06dab0ff4593a44ce8e9c0cbe2
[ "BSD-3-Clause" ]
null
null
null
libraries/utils/selectionio.cpp
Zeitproblem/mne-cpp
38bc3ba5213bbb06dab0ff4593a44ce8e9c0cbe2
[ "BSD-3-Clause" ]
null
null
null
libraries/utils/selectionio.cpp
Zeitproblem/mne-cpp
38bc3ba5213bbb06dab0ff4593a44ce8e9c0cbe2
[ "BSD-3-Clause" ]
null
null
null
//============================================================================================================= /** * @file selectionio.cpp * @author Lorenz Esch <lesch@mgh.harvard.edu>; * Christoph Dinh <chdinh@nmr.mgh.harvard.edu>; * Gabriel Motta <gbmotta@mgh.harvard.edu> * @since 0.1.0 * @date October, 2014 * * @section LICENSE * * Copyright (C) 2014, Lorenz Esch, Christoph Dinh, Gabriel Motta. 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 MNE-CPP authors 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. * * * @brief Definition of the SelectionIO class * */ //============================================================================================================= // INCLUDES //============================================================================================================= #include "selectionio.h" #include <iostream> #include <fstream> #include <sstream> //============================================================================================================= // QT INCLUDES //============================================================================================================= #include <QFileInfo> #include <QTextStream> #include <QFile> #include <QDebug> //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace UTILSLIB; //============================================================================================================= // DEFINE MEMBER METHODS //============================================================================================================= SelectionIO::SelectionIO() { } //============================================================================================================= bool SelectionIO::readMNESelFile(QString path, QMap<QString,QStringList> &selectionMap) { //Open .sel file if(!path.contains(".sel")) return false; //clear the map first selectionMap.clear(); QFile file(path); if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) { qDebug()<<"Error opening selection file"; return false; } //Start reading from file QTextStream in(&file); while(!in.atEnd()) { QString line = in.readLine(); if(line.contains("%") == false && line.contains(":") == true) //Skip commented areas in file { QStringList firstSplit = line.split(":"); //Create new key QString key = firstSplit.at(0); QStringList secondSplit = firstSplit.at(1).split("|"); //Delete last element if it is a blank character if(secondSplit.at(secondSplit.size()-1) == "") secondSplit.removeLast(); //Add to map selectionMap.insertMulti(key, secondSplit); } } file.close(); return true; } //============================================================================================================= bool SelectionIO::readMNESelFile(const std::string& path, std::multimap<std::string,std::vector<std::string>> &selectionMap) { //Open .sel file if(path.find(".sel") != std::string::npos) return false; //clear the map first selectionMap.clear(); std::ifstream inFile(path); if(!inFile.is_open()){ qDebug()<<"Error opening selection file"; return false; } std::string line; while(std::getline(inFile, line)){ if(line.find('%') == std::string::npos && line.find(':') != std::string::npos){ std::stringstream stream{line}; std::vector<std::string> firstSplit; for (std::string element; std::getline(stream, line, ':');){ firstSplit.push_back(std::move(element)); } std::string key = firstSplit.at(0); std::vector<std::string> secondSplit; for (std::string element; std::getline(stream, line, '|');){ secondSplit.push_back(std::move(element)); } if(secondSplit.back() == ""){ secondSplit.pop_back(); } selectionMap.insert({key, secondSplit}); } } return true; } //============================================================================================================= bool SelectionIO::readBrainstormMonFile(QString path, QMap<QString,QStringList> &selectionMap) { //Open .sel file if(!path.contains(".mon")) return false; //clear the map first selectionMap.clear(); QFile file(path); if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) { qDebug()<<"Error opening montage file"; return false; } //Start reading from file QTextStream in(&file); QString groupName = in.readLine(); QStringList channels; while(!in.atEnd()) { QString line = in.readLine(); if(line.contains(":") == true) { QStringList secondSplit = line.split(":"); QString key = secondSplit.at(0); channels.append(key); } } //Add to map selectionMap.insertMulti(groupName, channels); file.close(); return true; } //============================================================================================================= bool SelectionIO::readBrainstormMonFile(const std::string& path, std::multimap<std::string,std::vector<std::string>>& selectionMap) { //Open file if(path.find(".mon") != std::string::npos) return false; //clear the map first selectionMap.clear(); std::ifstream inFile(path); if(!inFile.is_open()){ qDebug()<<"Error opening montage file"; return false; } std::vector<std::string> channels; std::string groupName; std::getline(inFile, groupName); std::string line; while(std::getline(inFile, line)){ if(line.find(':') != std::string::npos){ std::stringstream stream{line}; std::vector<std::string> split; for (std::string element; std::getline(stream, line, ':');){ split.push_back(std::move(element)); } channels.push_back(split.at(0)); } } selectionMap.insert({groupName, channels}); return true; } //============================================================================================================= bool SelectionIO::writeMNESelFile(QString path, const QMap<QString,QStringList> &selectionMap) { //Open .sel file if(!path.contains(".sel")) return false; QFile file(path); if (!file.open(QIODevice::WriteOnly | QIODevice::Text)){ qDebug()<<"Error opening sel file for writing"; return false; } //Write selections to file QTextStream out(&file); QMap<QString, QStringList>::const_iterator i = selectionMap.constBegin(); while (i != selectionMap.constEnd()) { out << i.key() << ":"; for(int u=0; u<i.value().size() ; u++) out << i.value().at(u) << "|"; out << "\n" << "\n"; ++i; } file.close(); return true; } //============================================================================================================= bool SelectionIO::writeMNESelFile(const std::string& path, const std::map<std::string,std::vector<std::string>>& selectionMap) { //Open .sel file if(path.find(".sel") == std::string::npos) return false; std::ofstream outFile(path); if (outFile.is_open()){ qDebug()<<"Error opening sel file for writing"; return false; } for(auto& mapElement : selectionMap){ outFile << mapElement.first << ":"; for(auto& vectorElement : mapElement.second){ outFile << vectorElement << "|"; } outFile << "\n" << "\n"; } return true; } //============================================================================================================= bool SelectionIO::writeBrainstormMonFiles(QString path, const QMap<QString,QStringList> &selectionMap) { //Open .sel file if(!path.contains(".mon")) return false; QMapIterator<QString,QStringList> i(selectionMap); while (i.hasNext()) { i.next(); QFileInfo fileInfo(path); QString newPath = QString("%1/%2.mon").arg(fileInfo.absolutePath()).arg(i.key()); //std::cout<<newPath.toStdString()<<std::endl; QFile file(newPath); if (!file.open(QIODevice::WriteOnly | QIODevice::Text)){ qDebug()<<"Error opening mon file for writing"; return false; } //Write selections to file QTextStream out(&file); out<<i.key()<<"\n"; for(int u=0; u<i.value().size() ; u++) out << i.value().at(u) << " : " << i.value().at(u) << "\n"; file.close(); } return true; } //============================================================================================================= bool SelectionIO::writeBrainstormMonFiles(const std::string& path, const std::map<std::string,std::vector<std::string>>& selectionMap) { //Open file if(path.find(".mon") == std::string::npos) return false; for(auto& mapElement : selectionMap){ //logic of using parent_path here might not be "correct" std::string newPath{path.substr(0, path.find_last_of("/") + 1) + mapElement.first + ".mon"}; std::ofstream outFile(newPath); if(!outFile.is_open()){ qDebug()<<"Error opening mon file for writing"; return false; } outFile << mapElement.first << "\n"; for(auto& vectorElement : mapElement.second){ outFile << vectorElement << " : " << vectorElement << "\n"; } } return true; }
32.835196
135
0.490855
[ "vector" ]
bf771cd9e71ed8de0676cc57d5ec4b9a80330f1c
6,452
cpp
C++
service/uninstall.cpp
light1021/dynamic-application-loader-host-interface
4e0d265cd1e96c0a49bf3f3061901ac3d7856f98
[ "Apache-2.0" ]
null
null
null
service/uninstall.cpp
light1021/dynamic-application-loader-host-interface
4e0d265cd1e96c0a49bf3f3061901ac3d7856f98
[ "Apache-2.0" ]
null
null
null
service/uninstall.cpp
light1021/dynamic-application-loader-host-interface
4e0d265cd1e96c0a49bf3f3061901ac3d7856f98
[ "Apache-2.0" ]
null
null
null
/* Copyright 2010-2016 Intel Corporation This software is licensed to you in accordance with the agreement between you and Intel Corporation. Alternatively, you can use this file in compliance with the Apache license, Version 2. Apache License, Version 2.0 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. */ /** ******************************************************************************** ** ** @file uninstall.c ** ** @brief Defines functions for the JHI UnInstall interface ** ** @author Niveditha Sundaram ** @author Venky Gokulrangan ** ******************************************************************************** */ #include "jhi_service.h" #include "misc.h" #include "dbg.h" #include "SessionsManager.h" #include "AppletsManager.h" #include "GlobalsManager.h" #include "string_s.h" using namespace intel_dal; //------------------------------------------------------------------------------- // JHI_UNLOAD - removes applet from JoM only, local copy not removed //------------------------------------------------------------------------------- JHI_RET_I jhis_unload(const char* pAppId, const SD_SESSION_HANDLE handle, vector<uint8_t>* blob) { SessionsManager& Sessions = SessionsManager::Instance(); AppletsManager& Applets = AppletsManager::Instance(); UINT32 ulRetCode = JHI_INTERNAL_ERROR; JHI_VM_TYPE vmType = GlobalsManager::Instance().getVmType(); JHI_APPLET_STATUS appStatus = Applets.getAppletState(pAppId); if ( ! ( (appStatus >= 0) && (appStatus < MAX_APP_STATES) ) ) { TRACE2 ("Uninstall: AppState incorrect-> %d for appid: %s \n", appStatus, pAppId); return JHI_INTERNAL_ERROR ; } if (NOT_INSTALLED == appStatus) { TRACE0 ("Uninstall: Invoked for an app that does not exist in app table "); if (vmType != JHI_VM_TYPE_BEIHAI_V2) return JHI_APPLET_NOT_INSTALLED; } // update sessions owners list and try to perform // sessions cleanup of non shared sessions in order to avoid failure cause by abandoned session. Sessions.ClearSessionsDeadOwners(); Sessions.ClearAbandonedNonSharedSessions(); if (!Sessions.AppletHasNonSharedSessions(pAppId)) { // remove the applet shared session in case it is not in use Sessions.ClearAppletSharedSession(pAppId); } // do not allow app uninstall in case there are any type of sessions at this point if (Sessions.hasLiveSessions(pAppId)) { ulRetCode = JHI_UNINSTALL_FAILURE_SESSIONS_EXISTS; return ulRetCode; } VM_Plugin_interface* plugin = NULL; if (( !GlobalsManager::Instance().getPluginTable(&plugin)) || (plugin == NULL) ) { // probably a reset return JHI_NO_CONNECTION_TO_FIRMWARE; } // Non-CSE - Guaranteed that the app state is 1 or 2. // In CSE, trying to unload even if it's not // known to be installed because installations // are persistent. TRACE0 ("Calling Plugin to unload the applet"); if (blob == NULL) { ulRetCode = plugin->JHI_Plugin_UnloadApplet(pAppId); } else { ulRetCode = plugin->JHI_Plugin_SendCmdPkg(handle, *blob); } if (JHI_SUCCESS == ulRetCode) { //REMOVE THE ENTRY if (!Applets.remove(pAppId)) { TRACE0 ("Unable to delete app table entry\n"); // Delete failed, could be different reasons. // Over Beihai v2 ignore the error because applets may be installed without // JHI knowing about it because installations are persistent. if (vmType != JHI_VM_TYPE_BEIHAI_V2) ulRetCode = JHI_INTERNAL_ERROR; //command failed } TRACE0 ("JOM delete success"); } else //JOM delete failed { TRACE1 ("JOM delete failed: %08x\n", ulRetCode); } return ulRetCode; } //------------------------------------------------------------------------------- // Function: jhis_uninstall // Used to remove an applet from JoM and local disk // IN : pAppId - AppId of package to be uninstalled // IN : blob - optional - if null, run legacy uninstall. // RETURN : JHI_RET - success or any failure returns //------------------------------------------------------------------------------- //1. On receiving the Uninstall command, JHI checks to see if APPID is in // app table // a. If app is not present, send back APPID_NOT_EXIST // b. If app is present, call TL Uninstall sequence: // i. Look for any active sessions corresponding to the applet in the // session table // ii. If present, close the sessions and remove session table entry // iii.Remove the applet from the JoM by issuing remove service command // to JoM //2. Remove corresponding app table entry from app table //3. Delete the corresponding PACK/DALP file from disk //------------------------------------------------------------------------------- JHI_RET_I jhis_uninstall(const char* pAppId, const SD_SESSION_HANDLE handle, vector<uint8_t>* blob) { UINT32 ulRetCode = JHI_INTERNAL_ERROR; TRACE0("dispatching JHIS Uninstall\n") ; ulRetCode = jhis_unload(pAppId, handle, blob); //Regardless of whether applet was present in JOM or not, we will attempt to remove //the file just in case it is present in disk if ((JHI_SUCCESS == ulRetCode) || (JHI_APPLET_NOT_INSTALLED == ulRetCode) || (TEE_STATUS_TA_DOES_NOT_EXIST) == ulRetCode ) { bool isAcp; FILESTRING filename; if (AppletsManager::Instance().appletExistInRepository(pAppId,&filename, isAcp)) { if (_wremove(filename.c_str()) != 0) { #ifdef _WIN32 volatile DWORD x = GetLastError(); TRACE1 (" JHI file removal from disk failed, error %d\n", x); #else TRACE0 (" JHI file removal from disk failed\n"); #endif if (JHI_SUCCESS == ulRetCode) ulRetCode = JHI_DELETE_FROM_REPOSITORY_FAILURE; } else { AppletsManager::Instance().syncAppletRepoToDisk(); // Ignore return value as sync failure doesn't mean the applet wasn't uninstalled ulRetCode = JHI_SUCCESS; } } } else //unload failed { TRACE0 ("JHI Unload failed\n"); } return ulRetCode ; }
31.940594
136
0.650806
[ "vector" ]
bf77f7ef2546f440846787fc2f3527a2a2603a32
1,314
cc
C++
extractor/scorer_test.cc
kho/cdec
d88186af251ecae60974b20395ce75807bfdda35
[ "BSD-3-Clause-LBNL", "Apache-2.0" ]
114
2015-01-11T05:41:03.000Z
2021-08-31T03:47:12.000Z
extractor/scorer_test.cc
kho/cdec
d88186af251ecae60974b20395ce75807bfdda35
[ "BSD-3-Clause-LBNL", "Apache-2.0" ]
29
2015-01-09T01:00:09.000Z
2019-09-25T06:04:02.000Z
extractor/scorer_test.cc
kho/cdec
d88186af251ecae60974b20395ce75807bfdda35
[ "BSD-3-Clause-LBNL", "Apache-2.0" ]
50
2015-02-13T13:48:39.000Z
2019-08-07T09:45:11.000Z
#include <gtest/gtest.h> #include <memory> #include <string> #include <vector> #include "mocks/mock_feature.h" #include "scorer.h" using namespace std; using namespace ::testing; namespace extractor { namespace { class ScorerTest : public Test { protected: virtual void SetUp() { feature1 = make_shared<features::MockFeature>(); EXPECT_CALL(*feature1, Score(_)).WillRepeatedly(Return(0.5)); EXPECT_CALL(*feature1, GetName()).WillRepeatedly(Return("f1")); feature2 = make_shared<features::MockFeature>(); EXPECT_CALL(*feature2, Score(_)).WillRepeatedly(Return(-1.3)); EXPECT_CALL(*feature2, GetName()).WillRepeatedly(Return("f2")); vector<shared_ptr<features::Feature>> features = {feature1, feature2}; scorer = make_shared<Scorer>(features); } shared_ptr<features::MockFeature> feature1; shared_ptr<features::MockFeature> feature2; shared_ptr<Scorer> scorer; }; TEST_F(ScorerTest, TestScore) { vector<double> expected_scores = {0.5, -1.3}; Phrase phrase; features::FeatureContext context(phrase, phrase, 0.3, 2, 11); EXPECT_EQ(expected_scores, scorer->Score(context)); } TEST_F(ScorerTest, TestGetNames) { vector<string> expected_names = {"f1", "f2"}; EXPECT_EQ(expected_names, scorer->GetFeatureNames()); } } // namespace } // namespace extractor
26.28
74
0.718417
[ "vector" ]
bf7d1b4be1da3a37190987d4e01a775864ad8299
2,797
cc
C++
bestfound.cc
josefcibulka/book-embedder
746093a97b388ea38226631eb36ded8fe48155e9
[ "MIT" ]
null
null
null
bestfound.cc
josefcibulka/book-embedder
746093a97b388ea38226631eb36ded8fe48155e9
[ "MIT" ]
null
null
null
bestfound.cc
josefcibulka/book-embedder
746093a97b388ea38226631eb36ded8fe48155e9
[ "MIT" ]
null
null
null
#include "bestfound.h" using std::string; using std::vector; using std::cout; using std::cerr; using std::endl; #include "tools.h" void BestFound::writeGraph(const Graph &g, std::ostream &ostr) { ostr << g.v.size() << endl; ostr << g.p << endl; for (const Vertex &v : g.v) ostr << v.id << endl; for (const Edge &e : g.e) ostr << g.v[e.v1].id << " " << g.v[e.v2].id << " [" << e.p << "]" << endl; } void BestFound::verifyGraphBadCase(string msg) { cerr << "The graph is bad!!! " << msg << endl; exit(0); } void BestFound::verifyGraph(const Graph &gr, int claimedCr) { if (Tools::countCrossingNumber(gr) != claimedCr) verifyGraphBadCase("Number of crossings differs from the claimend value."); if (origGr_.v.size() != gr.v.size()) verifyGraphBadCase("Number of vertices changed."); if (origGr_.e.size() != gr.e.size()) verifyGraphBadCase("Number of edges changed."); int n = static_cast<int>(gr.v.size()); int m = static_cast<int>(gr.e.size()); if (origGr_.p != gr.p) verifyGraphBadCase("Numbers of pages changed."); vector<bool> used(n, false); for (const Vertex &ver : gr.v) { if (ver.id < 0 || ver.id >= n || used[ver.id]) verifyGraphBadCase( "Bad or duplicate vertex id " + std::to_string(ver.id) + "."); used[ver.id] = true; } for (int i = 0; i < m; i++) { if (gr.v[gr.e[i].v1].id != origGr_.v[origGr_.e[i].v1].id) { writeGraph(origGr_, cout); writeGraph(gr, cout); verifyGraphBadCase( "An edge changed; the first vertex of edge " + std::to_string(i)); } if (gr.v[gr.e[i].v2].id != origGr_.v[origGr_.e[i].v2].id) { writeGraph(origGr_, cout); writeGraph(gr, cout); verifyGraphBadCase( "An edge changed; the second vertex of edge " + std::to_string(i)); } if (gr.e[i].p < 0 || gr.e[i].p >= gr.p) verifyGraphBadCase("Edge page is out of range."); } } /** * @param claimedCr The claimed crossing number of the candidate (it is also verified here). Value of -1 means that it should be counted here. * */ void BestFound::testIfBest(const Graph &candidate, int claimedCr) { if (claimedCr == -1) claimedCr = Tools::countCrossingNumber(candidate); if (val_ != -1 && claimedCr >= val_) return; val_ = claimedCr; gr_.loadFrom(candidate); betterThanInitial_ = true; if (filename_ == "") return; verifyGraph(candidate, claimedCr); cout << "Writing graph with: " << claimedCr << " crossings. \r"; cout.flush(); // make a backup std::remove(filenameBck_.c_str()); std::rename(filename_.c_str(), filenameBck_.c_str()); // write the graph std::ofstream ostr; ostr.open(filename_.c_str(), std::ios_base::out); if (!ostr.is_open()) return; writeGraph(candidate, ostr); }
27.421569
142
0.613872
[ "vector" ]
bf826cd268a205b34dab4b900bb66d52563d030b
2,244
cpp
C++
scg3/src/ColorCore.cpp
eof1/scg3
b9fac30895b9c2bf2d66250df471cc18267c98a2
[ "Apache-2.0" ]
5
2018-08-20T05:16:53.000Z
2021-05-03T15:43:52.000Z
scg3/src/ColorCore.cpp
eof1/scg3
b9fac30895b9c2bf2d66250df471cc18267c98a2
[ "Apache-2.0" ]
2
2019-03-14T14:27:13.000Z
2019-04-09T08:58:32.000Z
scg3/src/ColorCore.cpp
eof1/scg3
b9fac30895b9c2bf2d66250df471cc18267c98a2
[ "Apache-2.0" ]
9
2016-03-24T10:23:56.000Z
2021-02-06T08:51:01.000Z
/** * \file ColorCore.cpp * * \author Volker Ahlers\n * volker.ahlers@hs-hannover.de */ /* * Copyright 2014-2019 Volker Ahlers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ColorCore.h" #include "RenderState.h" namespace scg { ColorCore::ColorCore() : isColorSet_(false), color_(0.0f), matrix_(1.0f), colorCoreOld_(nullptr) { } ColorCore::~ColorCore() { } ColorCoreSP ColorCore::create() { return std::make_shared<ColorCore>(); } ColorCore* ColorCore::setColor(glm::vec4 color) { if (color.w < -0.001f) { // unset vertex color isColorSet_ = false; } else { // set vertex color color_ = color; isColorSet_ = true; } return this; } ColorCore* ColorCore::setMatrix(glm::mat4 matrix) { matrix_ = matrix; return this; } void ColorCore::render(RenderState* renderState) { // post-multiply current color matrix by local color matrix renderState->colorStack.pushMatrix(); renderState->colorStack.multMatrix(matrix_); // set vertex color (if set) if (isColorSet_) { colorCoreOld_ = renderState->getColor(); renderState->setColor(this); glVertexAttrib4fv(OGLConstants::COLOR.location, glm::value_ptr(color_)); } } void ColorCore::renderPost(RenderState* renderState) { // restore color matrix renderState->colorStack.popMatrix(); // restore vertex color (if set) if (isColorSet_) { renderState->setColor(colorCoreOld_); if (colorCoreOld_) { if (colorCoreOld_->isColorSet_) { glVertexAttrib4fv(OGLConstants::COLOR.location, glm::value_ptr(colorCoreOld_->color_)); } } } } } /* namespace scg */
23.621053
96
0.663993
[ "render" ]
bf8b428b0056485cc29f6136e3d04d38c22293ac
2,434
cpp
C++
Box2D/2d/3 box2d rigid bodies/code/source/main.cpp
patricioHidalgo/Box2D_Sample
558aafdc388d40f753eb37fa56319065b3e8575d
[ "MIT" ]
null
null
null
Box2D/2d/3 box2d rigid bodies/code/source/main.cpp
patricioHidalgo/Box2D_Sample
558aafdc388d40f753eb37fa56319065b3e8575d
[ "MIT" ]
null
null
null
Box2D/2d/3 box2d rigid bodies/code/source/main.cpp
patricioHidalgo/Box2D_Sample
558aafdc388d40f753eb37fa56319065b3e8575d
[ "MIT" ]
null
null
null
//Author: Patricio Hidalgo Sanchez on 2019. //Copyright Creative Commons License. #include <memory> #include <vector> #include <Box2D/Box2D.h> #include <SFML/Window.hpp> #include <SFML/Graphics.hpp> #include "World.hpp" #include "Car.hpp" #include "Ball.hpp" #include "Platform.hpp" #include "Elevator.hpp" #include "Basket.hpp" #include "ContactListener.hpp" #include "Emitter.hpp" using namespace sf; using namespace std; namespace { b2World* create_physics_world (float world_width, float world_height) { // Se crea el mundo físico: b2World* physics_world(new b2World(b2Vec2(0, -100.f))); return physics_world; } } int main () { bool running = true; RenderWindow window(VideoMode(800, 600), "Hidalgo Sanchez, Patricio. Box2D", Style::Titlebar | Style::Close, ContextSettings(32)); window.setVerticalSyncEnabled (true); b2World* physics_world = create_physics_world (800, 600); ContactListener listener; physics_world->SetContactListener(&listener); World world = World(physics_world, &window); Car car = Car(&world, 100, 150); Ball ball = Ball(&world, 100, 160, 10); Basket basket = Basket(&world, 60, 420, 60, 30); Elevator elevator = Elevator(&world, 705, 100, 150, 450, 100, 540); Platform Floor1 = Platform(&world, 75, 110, 200, 0); Platform Floor2 = Platform(&world, 225, 59, 150, -45); Platform Floor3 = Platform(&world, 450, 10, 350, 0); Platform Floor4 = Platform(&world, 560, 450, 120, 0); Platform Floor5 = Platform(&world, 455, 402, 140, 45); Platform Floor6 = Platform(&world, 350, 355, 117, 0); Elevator elevator2 = Elevator(&world, 200, 360, 150, 500, 400, 500); Platform leftBound = Platform(&world, 5, 300, 600, 90); Platform rightBound = Platform(&world, 795, 300, 600, 90); CircleShape c = CircleShape(10); Emitter m = Emitter(&world, 600, 250, c, &running); Clock timer; float delta_time = 0.017f; // ~60 fps do { timer.restart (); // Process window events: Event event; while (window.pollEvent (event)) { if (event.type == Event::Closed) { running = false; } } window.clear(); world.Update(delta_time); world.Render(); window.display (); delta_time = (delta_time + timer.getElapsedTime ().asSeconds ()) * 0.5f; } while (running); return EXIT_SUCCESS; }
22.962264
134
0.64544
[ "render", "vector" ]
bf949ba78da776bcb74620aa4e2ead91657b2cd0
5,725
cpp
C++
src/math/statistics.cpp
Algomorph/LevelSetFusionExperimentsCPP
f56962f0ad5c62e6706f818062782a2e1660afda
[ "Apache-2.0" ]
8
2019-01-07T14:12:21.000Z
2021-01-12T01:48:03.000Z
src/math/statistics.cpp
Algomorph/LevelSetFusionExperimentsCPP
f56962f0ad5c62e6706f818062782a2e1660afda
[ "Apache-2.0" ]
6
2018-12-19T16:43:33.000Z
2019-06-06T19:50:22.000Z
src/math/statistics.cpp
Algomorph/LevelSetFusionExperimentsCPP
f56962f0ad5c62e6706f818062782a2e1660afda
[ "Apache-2.0" ]
2
2019-01-07T14:12:28.000Z
2019-03-06T06:30:24.000Z
/* * statistics.cpp * * Created on: Nov 14, 2018 * Author: Gregory Kramida * Copyright: 2018 Gregory Kramida * * 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. */ //stdlib #include "statistics.tpp" #include <cmath> #include <atomic> #include <limits> //local namespace math { template void locate_max_norm<math::Vector2f>(float& max_norm, math::Vector2i& coordinates, const math::MatrixXv2f& vector_field); template void locate_max_norm<math::Vector3f>(float& max_norm, math::Vector3i& coordinates, const math::Tensor3v3f& vector_field); template void locate_min_norm<math::Vector2f>(float& min_norm, math::Vector2i& coordinates, const math::MatrixXv2f& vector_field); template void locate_min_norm<math::Vector3f>(float& min_norm, math::Vector3i& coordinates, const math::Tensor3v3f& vector_field); template void locate_maximum<float>(float& min_norm, math::Vector3i& coordinates, const math::Tensor3f& vector_field); template void locate_maximum<float>(float& min_norm, math::Vector2i& coordinates, const eig::MatrixXf& vector_field); template float max_norm<math::Vector2f>(const math::MatrixXv2f& vector_field); template float max_norm<math::Vector3f>(const math::Tensor3v3f& vector_field); template float min_norm<math::Vector2f>(const math::MatrixXv2f& vector_field); template float min_norm<math::Vector3f>(const math::Tensor3v3f& vector_field); template float mean<float>(const eig::MatrixXf& field); template float mean<float>(const math::Tensor3f& field); template float std<float>(const eig::MatrixXf& field); template float std<float>(const math::Tensor3f& field); /** * Locates the maximum L2 norm (length) of the vector in the given field. * Identical to @see locate_max_norm with the exception that this version is using a generic traversal function. * @param[out] max_norm length of the longest vector * @param[out] coordinate the location of the longest vector * @param[in] vector_field the field to look at */ void locate_max_norm2(float& max_norm, Vector2i& coordinate, const MatrixXv2f& vector_field) { float max_squared_norm = 0; coordinate = math::Vector2i(0); int column_count = static_cast<int>(vector_field.cols()); auto max_norm_functor = [&] (math::Vector2f element, eig::Index i_element) { float squared_length = math::squared_norm(element); if(squared_length > max_squared_norm) { max_squared_norm = squared_length; div_t division_result = div(static_cast<int>(i_element), column_count); coordinate.x = division_result.quot; coordinate.y = division_result.rem; } }; traversal::traverse_2d_field_i_element_singlethreaded(vector_field, max_norm_functor); max_norm = std::sqrt(max_squared_norm); } /** * Given a 2d vector field, computes the lengths and counts up how many of the vectors are above the provided threshold * @param vector_field - vector field to look at * @param threshold - an arbitrary threshold * @return ratio of the counted vectors to the total number of vectors in the field */ float ratio_of_vector_lengths_above_threshold(const MatrixXv2f& vector_field, float threshold) { float threshold_squared = threshold * threshold; long count_above = 0; long total_count = vector_field.size(); for (eig::Index i_element = 0; i_element < vector_field.size(); i_element++) { float squared_length = math::squared_norm(vector_field(i_element)); if (squared_length > threshold_squared) { count_above++; } } return static_cast<double>(count_above) / static_cast<double>(total_count); } /** * Computes the mean vector length for all vectors in the given field * @param vector_field the field to look at * @return the arithmetic mean vector length */ float mean_vector_length(const MatrixXv2f& vector_field) { long total_count = vector_field.size(); double total_length = 0.0; for (eig::Index i_element = 0; i_element < vector_field.size(); i_element++) { float length = math::length(vector_field(i_element)); total_length += static_cast<double>(length); } return static_cast<float>(total_length / static_cast<double>(total_count)); } /** * Computes the mean vector length and the standard deviation of lengths for vectors in the given field * @param[out] mean the arithmetic mean vector length * @param[out] standard_deviation standard deviation of vector lengths * @param[in] vector_field the field to look at */ void mean_and_std_vector_length(float& mean, float& standard_deviation, const MatrixXv2f& vector_field) { long total_count = vector_field.size(); double total_length = 0.0; for (eig::Index i_element = 0; i_element < vector_field.size(); i_element++) { float length = math::length(vector_field(i_element)); total_length += static_cast<double>(length); } mean = static_cast<float>(total_length / static_cast<double>(total_count)); double total_squared_deviation = 0.0; for (eig::Index i_element = 0; i_element < vector_field.size(); i_element++) { float length = math::length(vector_field(i_element)); float local_deviation = length - mean; total_squared_deviation += local_deviation * local_deviation; } standard_deviation = static_cast<float>(std::sqrt(total_squared_deviation / static_cast<double>(total_count))); } } //namespace math
41.18705
130
0.759127
[ "vector" ]
bcc8b6f4c9f331f55d8bcb1d128c0e1544be0b5c
13,343
cc
C++
src/Radar.cc
robotics-upo/sdformat
30f01b38b5284db2160a566fe8957a00ea707700
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/Radar.cc
robotics-upo/sdformat
30f01b38b5284db2160a566fe8957a00ea707700
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/Radar.cc
robotics-upo/sdformat
30f01b38b5284db2160a566fe8957a00ea707700
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/* * Copyright 2019 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. * */ #include "sdf/Radar.hh" #include "sdf/parser.hh" using namespace sdf; using namespace ignition; /// \brief Private radar data. class sdf::Radar::Implementation { /// \brief Number of rays horizontally per laser sweep public: unsigned int horizontalScanSamples{640}; /// \brief Resolution for horizontal scan public: double horizontalScanResolution{1.0}; /// \brief Minimum angle for horizontal scan public: math::Angle horizontalScanMinAngle{0.0}; /// \brief Maximum angle for horizontal scan public: math::Angle horizontalScanMaxAngle{0.0}; /// \brief Number of rays vertically per laser sweep public: unsigned int verticalScanSamples{1}; /// \brief Resolution for vertical scan public: double verticalScanResolution{1.0}; /// \brief Minimum angle for vertical scan public: math::Angle verticalScanMinAngle{0.0}; /// \brief Maximum angle for vertical scan public: math::Angle verticalScanMaxAngle{0.0}; /// \brief Minimum distance for each ray public: double minRange{0.0}; /// \brief Maximum distance for each ray public: double maxRange{0.0}; /// \brief Linear resolution for each ray public: double rangeResolution{0.0}; /// \brief Noise values for the radar sensor public: Noise radarNoise; /// \brief The SDF element pointer used during load. public: sdf::ElementPtr sdf{nullptr}; /// \brief Number of horizontal measures public: int h_measures{6}; /// \brief Number of vertical measures public: int v_measures{4}; }; ////////////////////////////////////////////////// Radar::Radar() : dataPtr(ignition::utils::MakeImpl<Implementation>()) { } ////////////////////////////////////////////////// /// \brief Load the radar based on an element pointer. This is *not* /// the usual entry point. Typical usage of the SDF DOM is through the Root /// object. /// \param[in] _sdf The SDF Element pointer /// \return Errors, which is a vector of Error objects. Each Error includes /// an error code and message. An empty vector indicates no error. Errors Radar::Load(ElementPtr _sdf) { Errors errors; this->dataPtr->sdf = _sdf; // Check that sdf is a valid pointer if (!_sdf) { errors.push_back({ErrorCode::ELEMENT_MISSING, "Attempting to load a Radar, but the provided SDF " "element is null."}); return errors; } // Check that the provided SDF element is a <radar> element. // This is an error that cannot be recovered, so return an error. if (_sdf->GetName() != "radar" && _sdf->GetName() != "gpu_radar") { errors.push_back({ErrorCode::ELEMENT_INCORRECT_TYPE, "Attempting to load a Radar, but the provided SDF element is " "not a <radar>."}); return errors; } // Load radar sensor properties if (_sdf->HasElement("scan")) { sdf::ElementPtr elem = _sdf->GetElement("scan"); if (elem->HasElement("horizontal")) { sdf::ElementPtr subElem = elem->GetElement("horizontal"); if (subElem->HasElement("samples")) this->dataPtr->horizontalScanSamples = subElem->Get<unsigned int>( "samples"); if (subElem->HasElement("resolution")) this->dataPtr->horizontalScanResolution = subElem->Get<double>( "resolution"); if (subElem->HasElement("min_angle")) this->dataPtr->horizontalScanMinAngle = math::Angle( subElem->Get<double>("min_angle")); if (subElem->HasElement("max_angle")) this->dataPtr->horizontalScanMaxAngle = math::Angle( subElem->Get<double>("max_angle")); } else { errors.push_back({ErrorCode::ELEMENT_MISSING, "A radar scan horizontal element is required, but it is not set."}); return errors; } if (elem->HasElement("vertical")) { sdf::ElementPtr subElem = elem->GetElement("vertical"); if (subElem->HasElement("samples")) this->dataPtr->verticalScanSamples = subElem->Get<unsigned int>( "samples"); if (subElem->HasElement("resolution")) this->dataPtr->verticalScanResolution = subElem->Get<double>( "resolution"); if (subElem->HasElement("min_angle")) this->dataPtr->verticalScanMinAngle = math::Angle(subElem->Get<double>( "min_angle")); if (subElem->HasElement("max_angle")) this->dataPtr->verticalScanMaxAngle = math::Angle(subElem->Get<double>( "max_angle")); } } else { errors.push_back({ErrorCode::ELEMENT_MISSING, "A radar scan element is required, but the scan is not set."}); return errors; } if (_sdf->HasElement("range")) { sdf::ElementPtr elem = _sdf->GetElement("range"); if (elem->HasElement("min")) this->dataPtr->minRange = elem->Get<double>("min"); if (elem->HasElement("max")) this->dataPtr->maxRange = elem->Get<double>("max"); if (elem->HasElement("resolution")) this->dataPtr->rangeResolution = elem->Get<double>("resolution"); } else { errors.push_back({ErrorCode::ELEMENT_MISSING, "A radar range element is required, but the range is not set."}); return errors; } if (_sdf->HasElement("noise")) this->dataPtr->radarNoise.Load(_sdf->GetElement("noise")); return errors; } ////////////////////////////////////////////////// sdf::ElementPtr Radar::Element() const { return this->dataPtr->sdf; } ////////////////////////////////////////////////// unsigned int Radar::HorizontalScanSamples() const { return this->dataPtr->horizontalScanSamples; } ////////////////////////////////////////////////// void Radar::SetHorizontalScanSamples(unsigned int _samples) { this->dataPtr->horizontalScanSamples = _samples; } ////////////////////////////////////////////////// double Radar::HorizontalScanResolution() const { return this->dataPtr->horizontalScanResolution; } ////////////////////////////////////////////////// void Radar::SetHorizontalScanResolution(double _res) { this->dataPtr->horizontalScanResolution = _res; } ////////////////////////////////////////////////// math::Angle Radar::HorizontalScanMinAngle() const { return this->dataPtr->horizontalScanMinAngle; } ////////////////////////////////////////////////// void Radar::SetHorizontalScanMinAngle(const math::Angle &_min) { this->dataPtr->horizontalScanMinAngle = _min; } ////////////////////////////////////////////////// math::Angle Radar::HorizontalScanMaxAngle() const { return this->dataPtr->horizontalScanMaxAngle; } ////////////////////////////////////////////////// void Radar::SetHorizontalScanMaxAngle(const math::Angle &_max) { this->dataPtr->horizontalScanMaxAngle = _max; } ////////////////////////////////////////////////// unsigned int Radar::VerticalScanSamples() const { return this->dataPtr->verticalScanSamples; } ////////////////////////////////////////////////// void Radar::SetVerticalScanSamples(unsigned int _samples) { this->dataPtr->verticalScanSamples = _samples; } ////////////////////////////////////////////////// double Radar::VerticalScanResolution() const { return this->dataPtr->verticalScanResolution; } ////////////////////////////////////////////////// void Radar::SetVerticalScanResolution(double _res) { this->dataPtr->verticalScanResolution = _res; } ////////////////////////////////////////////////// math::Angle Radar::VerticalScanMinAngle() const { return this->dataPtr->verticalScanMinAngle; } ////////////////////////////////////////////////// void Radar::SetVerticalScanMinAngle(const math::Angle &_min) { this->dataPtr->verticalScanMinAngle = _min; } ////////////////////////////////////////////////// math::Angle Radar::VerticalScanMaxAngle() const { return this->dataPtr->verticalScanMaxAngle; } ////////////////////////////////////////////////// void Radar::SetVerticalScanMaxAngle(const math::Angle &_max) { this->dataPtr->verticalScanMaxAngle = _max; } ////////////////////////////////////////////////// double Radar::RangeMin() const { return this->dataPtr->minRange; } ////////////////////////////////////////////////// void Radar::SetRangeMin(double _min) { this->dataPtr->minRange = _min; } ////////////////////////////////////////////////// double Radar::RangeMax() const { return this->dataPtr->maxRange; } ////////////////////////////////////////////////// void Radar::SetRangeMax(double _max) { this->dataPtr->maxRange = _max; } ////////////////////////////////////////////////// double Radar::RangeResolution() const { return this->dataPtr->rangeResolution; } ////////////////////////////////////////////////// void Radar::SetRangeResolution(double _range) { this->dataPtr->rangeResolution = _range; } ////////////////////////////////////////////////// const Noise &Radar::RadarNoise() const { return this->dataPtr->radarNoise; } ////////////////////////////////////////////////// void Radar::SetRadarNoise(const Noise &_noise) { this->dataPtr->radarNoise = _noise; } int Radar::HMeasures() const { return this->dataPtr->h_measures; } void Radar::SetHMeasures(int h_measures) { this->dataPtr->h_measures = h_measures; } int Radar::VMeasures() const { return this->dataPtr->v_measures; } void Radar::SetVMeasures(int v_measures) { this->dataPtr->v_measures = v_measures; } ////////////////////////////////////////////////// bool Radar::operator==(const Radar &_radar) const { if (this->dataPtr->horizontalScanSamples != _radar.HorizontalScanSamples()) return false; if (std::abs(this->dataPtr->horizontalScanResolution - _radar.HorizontalScanResolution()) > 1e-6) return false; if (this->dataPtr->horizontalScanMinAngle != _radar.HorizontalScanMinAngle()) return false; if (this->dataPtr->horizontalScanMaxAngle != _radar.HorizontalScanMaxAngle()) return false; if (this->dataPtr->verticalScanSamples != _radar.VerticalScanSamples()) return false; if (std::abs(this->dataPtr->verticalScanResolution - _radar.VerticalScanResolution()) > 1e-6) return false; if (this->dataPtr->verticalScanMinAngle != _radar.VerticalScanMinAngle()) return false; if (this->dataPtr->verticalScanMaxAngle != _radar.VerticalScanMaxAngle()) return false; if (std::abs(this->dataPtr->minRange - _radar.RangeMin()) > 1e-6) return false; if (std::abs(this->dataPtr->maxRange - _radar.RangeMax()) > 1e-6) return false; if (std::abs(this->dataPtr->rangeResolution - _radar.RangeResolution()) > 1e-6) { return false; } if (this->dataPtr->radarNoise != _radar.RadarNoise()) return false; return true; } ////////////////////////////////////////////////// bool Radar::operator!=(const Radar &_radar) const { return !(*this == _radar); } ///////////////////////////////////////////////// sdf::ElementPtr Radar::ToElement() const { sdf::ElementPtr elem(new sdf::Element); sdf::initFile("radar.sdf", elem); sdf::ElementPtr scanElem = elem->GetElement("scan"); sdf::ElementPtr horElem = scanElem->GetElement("horizontal"); horElem->GetElement("samples")->Set<double>(this->HorizontalScanSamples()); horElem->GetElement("resolution")->Set<double>( this->HorizontalScanResolution()); horElem->GetElement("min_angle")->Set<double>( this->HorizontalScanMinAngle().Radian()); horElem->GetElement("max_angle")->Set<double>( this->HorizontalScanMaxAngle().Radian()); sdf::ElementPtr vertElem = scanElem->GetElement("vertical"); vertElem->GetElement("samples")->Set<double>(this->VerticalScanSamples()); vertElem->GetElement("resolution")->Set<double>( this->VerticalScanResolution()); vertElem->GetElement("min_angle")->Set<double>( this->VerticalScanMinAngle().Radian()); vertElem->GetElement("max_angle")->Set<double>( this->VerticalScanMaxAngle().Radian()); sdf::ElementPtr rangeElem = elem->GetElement("range"); rangeElem->GetElement("min")->Set<double>(this->RangeMin()); rangeElem->GetElement("max")->Set<double>(this->RangeMax()); rangeElem->GetElement("resolution")->Set<double>( this->RangeResolution()); sdf::ElementPtr noiseElem = elem->GetElement("noise"); std::string noiseType; switch (this->dataPtr->radarNoise.Type()) { case sdf::NoiseType::NONE: noiseType = "none"; break; case sdf::NoiseType::GAUSSIAN: noiseType = "gaussian"; break; case sdf::NoiseType::GAUSSIAN_QUANTIZED: noiseType = "gaussian_quantized"; break; default: noiseType = "none"; } // radar does not use noise.sdf description noiseElem->GetElement("type")->Set<std::string>(noiseType); noiseElem->GetElement("mean")->Set<double>(this->dataPtr->radarNoise.Mean()); noiseElem->GetElement("stddev")->Set<double>( this->dataPtr->radarNoise.StdDev()); return elem; }
29.585366
79
0.615829
[ "object", "vector" ]
bccace0ce15f1ce8aa225f3944fd7a37f67449d3
3,082
hpp
C++
AliasTable.hpp
tcantenot/AliasTable
81706488a543ab897e1c548ffa549770d5be5c53
[ "MIT" ]
null
null
null
AliasTable.hpp
tcantenot/AliasTable
81706488a543ab897e1c548ffa549770d5be5c53
[ "MIT" ]
null
null
null
AliasTable.hpp
tcantenot/AliasTable
81706488a543ab897e1c548ffa549770d5be5c53
[ "MIT" ]
null
null
null
#include <queue> #include <vector> template <typename T, typename Compare> using Heap = std::priority_queue<T, std::vector<T>, Compare>; // Build an alias table over the given probability mass function to allow sampling from it in constant time. // https://en.wikipedia.org/wiki/Alias_method // [in] probabilities: Probability mass function (size = n) // [in] n: Number of values // [out] tableProbs: Alias table probabilities (size = n) // [out] tableAliases: Alias table aliases (size = n) template <typename T = float, typename TIndex = unsigned int> void BuildAliasTable(T const * probabilities, TIndex n, T * tableProbs, TIndex * tableAliases) { // Vose's Alias Method // https://www.keithschwarz.com/darts-dice-coins/ // Note: To generate a good alias table (i.e. w/ a smaller probability to perform an alias lookup at runtime), // we are using min and max heaps for the worklists to take from the max of the large worklist and give to the // min of the small worklist. const auto WorklistEntryLess = [&](TIndex lhs, TIndex rhs) { return tableProbs[lhs] < tableProbs[rhs]; }; const auto WorklistEntryGreater = [&](TIndex lhs, TIndex rhs) { return tableProbs[lhs] > tableProbs[rhs]; }; using WorklistMinHeap = Heap<TIndex, decltype(WorklistEntryGreater)>; using WorklistMaxHeap = Heap<TIndex, decltype(WorklistEntryLess)>; WorklistMinHeap small(WorklistEntryGreater); WorklistMaxHeap large(WorklistEntryLess); for(TIndex i = 0; i < n; ++i) { tableAliases[i] = ~TIndex(0); tableProbs[i] = probabilities[i] * n; if(tableProbs[i] < T(1)) small.push(i); else large.push(i); } while(!small.empty() && !large.empty()) { const TIndex s = small.top(); small.pop(); const TIndex l = large.top(); large.pop(); tableAliases[s] = l; tableProbs[l] = (tableProbs[l] + tableProbs[s]) - 1; // More numerically stable than: tableProbs[l] - (TValue(1) - tableProbs[s]) if(tableProbs[l] < T(1)) small.push(l); else large.push(l); } while(!small.empty()) { tableProbs[small.top()] = T(1); small.pop(); } while(!large.empty()) { tableProbs[large.top()] = T(1); large.pop(); } } // Sample the probability mass function represented by the alias table (built with BuildAliasTable) // [in] urand01: Uniform random number in [0, 1) // [in] tableProbs: Alias table probabilities (size = n) // [in] tableAliases: Alias table aliases (size = n) // [in] n: Number of values // Returns the sample index. template <typename T = float, typename TIndex = unsigned int> TIndex SampleAliasTable(T urand01, T const * tableProbs, TIndex const * tableAliases, TIndex n) { const T x = urand01; const T nx = n * x; const TIndex i = static_cast<int>(nx) < n ? static_cast<int>(nx) : n - 1; const T y = nx - i; const T Ui = tableProbs[i]; if(y < Ui) { return i; } else { return tableAliases[i]; } // Alternative version: Marsaglia et. al. 'square histogram' method // Replace computation of y and test if(y < Ui) by // const T Vi = (Ui + i) / n; // if(x < Vi) }
32.442105
131
0.670019
[ "vector" ]
bcd062a688c05d586049160156c6fea4d1051c90
427
cpp
C++
src/Client/Engine/Vignette.cpp
fqhd/BuildBattle
f85ec857aa232313f4678514aa317af73c37de10
[ "MIT" ]
10
2021-08-17T20:55:52.000Z
2022-03-28T00:45:14.000Z
src/Client/Engine/Vignette.cpp
fqhd/BuildBattle
f85ec857aa232313f4678514aa317af73c37de10
[ "MIT" ]
null
null
null
src/Client/Engine/Vignette.cpp
fqhd/BuildBattle
f85ec857aa232313f4678514aa317af73c37de10
[ "MIT" ]
2
2021-07-05T18:49:56.000Z
2021-07-10T22:03:17.000Z
#include "Vignette.hpp" void Vignette::init(){ m_quad.init(); m_shader.load("res/shaders/vignette_vertex_shader.glsl", "res/shaders/vignette_fragment_shader.glsl"); } void Vignette::render(){ m_shader.bind(); glDisable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); m_quad.render(); glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); m_shader.unbind(); } void Vignette::destroy(){ m_shader.destroy(); m_quad.destroy(); }
19.409091
103
0.742389
[ "render" ]
bcd470507c7ea1ecf73e5d883470eefc656fa138
16,139
cpp
C++
src/asiAlgo/auxiliary/asiAlgo_BVHFacets.cpp
yeeeeeeti/3D_feature_extract
6297daa8afaac09aef9b44858e74fb2a95e1e7c5
[ "BSD-3-Clause" ]
null
null
null
src/asiAlgo/auxiliary/asiAlgo_BVHFacets.cpp
yeeeeeeti/3D_feature_extract
6297daa8afaac09aef9b44858e74fb2a95e1e7c5
[ "BSD-3-Clause" ]
null
null
null
src/asiAlgo/auxiliary/asiAlgo_BVHFacets.cpp
yeeeeeeti/3D_feature_extract
6297daa8afaac09aef9b44858e74fb2a95e1e7c5
[ "BSD-3-Clause" ]
null
null
null
//----------------------------------------------------------------------------- // Created on: 21 September 2016 //----------------------------------------------------------------------------- // Copyright (c) 2017, Sergey Slyadnev // 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 copyright holder(s) nor the // names of all 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 AUTHORS 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. //----------------------------------------------------------------------------- // Own include #include <asiAlgo_BVHFacets.h> // Geometry includes #include <asiAlgo_BVHIterator.h> // OCCT includes #include <Bnd_Box.hxx> #include <BRep_Builder.hxx> #include <BRep_Tool.hxx> #include <BRepAdaptor_Surface.hxx> #include <BRepBndLib.hxx> #include <BRepBuilderAPI_MakeEdge.hxx> #include <BVH_BinnedBuilder.hxx> #include <BVH_LinearBuilder.hxx> #include <TopExp.hxx> #include <TopExp_Explorer.hxx> #include <TopoDS.hxx> #include <TopoDS_Compound.hxx> //----------------------------------------------------------------------------- //! Creates the accelerating structure with immediate initialization. //! \param[in] model CAD model to create the accelerating structure for. //! \param[in] builderType type of builder to use. //! \param[in] progress progress notifier. //! \param[in] plotter imperative plotter. asiAlgo_BVHFacets::asiAlgo_BVHFacets(const TopoDS_Shape& model, const BuilderType builderType, ActAPI_ProgressEntry progress, ActAPI_PlotterEntry plotter) : BVH_PrimitiveSet<double, 4> (), m_progress (progress), m_plotter (plotter), m_fBoundingDiag (0.0) { this->init(model, builderType); this->MarkDirty(); } //----------------------------------------------------------------------------- //! Creates the accelerating structure with immediate initialization. //! \param[in] mesh triangulation to create the accelerating structure for. //! \param[in] builderType type of builder to use. //! \param[in] progress progress notifier. //! \param[in] plotter imperative plotter. asiAlgo_BVHFacets::asiAlgo_BVHFacets(const Handle(Poly_Triangulation)& mesh, const BuilderType builderType, ActAPI_ProgressEntry progress, ActAPI_PlotterEntry plotter) : BVH_PrimitiveSet<double, 4> (), m_progress (progress), m_plotter (plotter), m_fBoundingDiag (0.0) { this->init(mesh, builderType); this->MarkDirty(); } //----------------------------------------------------------------------------- //! \return number of stored facets. int asiAlgo_BVHFacets::Size() const { return (int) m_facets.size(); } //----------------------------------------------------------------------------- //! Builds an elementary box for a facet with the given index. //! \param[in] index index of the facet of interest. //! \return AABB for the facet of interest. BVH_Box<double, 4> asiAlgo_BVHFacets::Box(const int index) const { BVH_Box<double, 4> box; const t_facet& facet = m_facets[index]; box.Add(facet.P0); box.Add(facet.P1); box.Add(facet.P2); return box; } //----------------------------------------------------------------------------- //! Calculates center point of a facet with respect to the axis of interest. //! \param[in] index index of the facet of interest. //! \param[in] axis axis of interest. //! \return center parameter along the straight line. double asiAlgo_BVHFacets::Center(const int index, const int axis) const { const t_facet& facet = m_facets[index]; if ( axis == 0 ) return (1.0 / 3.0) * ( facet.P0.x() + facet.P1.x() + facet.P2.x() ); else if ( axis == 1 ) return (1.0 / 3.0) * ( facet.P0.y() + facet.P1.y() + facet.P2.y() ); // The last possibility is "axis == 2" return (1.0 / 3.0) * ( facet.P0.z() + facet.P1.z() + facet.P2.z() ); } //----------------------------------------------------------------------------- //! Swaps two elements for BVH building. //! \param[in] index1 first index. //! \param[in] index2 second index. void asiAlgo_BVHFacets::Swap(const int index1, const int index2) { std::swap(m_facets[index1], m_facets[index2]); } //----------------------------------------------------------------------------- //! Returns vertices for a facet with the given 0-based index. inline void asiAlgo_BVHFacets::GetVertices(const int index, BVH_Vec4d& vertex1, BVH_Vec4d& vertex2, BVH_Vec4d& vertex3) const { const t_facet& facet = m_facets[index]; vertex1 = facet.P0; vertex2 = facet.P1; vertex3 = facet.P2; } //----------------------------------------------------------------------------- //! \return characteristic diagonal of the full model. double asiAlgo_BVHFacets::GetBoundingDiag() const { return m_fBoundingDiag; } //----------------------------------------------------------------------------- //! Dumps the primitive set to the plotter. //! \param[in] IV imperative plotter to dump to. void asiAlgo_BVHFacets::Dump(ActAPI_PlotterEntry IV) { // Access (build) hierarchy of boxes const opencascade::handle<BVH_Tree<double, 4>>& bvh = this->BVH(); // if ( bvh.IsNull() ) { std::cout << "Error: BVH construction failed" << std::endl; return; } // Prepare a topological structure to store BVH primitives in explicit form TopoDS_Compound comp_left, comp_right; BRep_Builder BB; BB.MakeCompound(comp_left); BB.MakeCompound(comp_right); // Loop over the BVH nodes for ( asiAlgo_BVHIterator it(bvh); it.More(); it.Next() ) { const BVH_Vec4i& nodeData = it.Current(); if ( !it.IsLeaf() ) { const BVH_Vec4d& minCorner_Left = bvh->MinPoint( nodeData.y() ); const BVH_Vec4d& maxCorner_Left = bvh->MaxPoint( nodeData.y() ); const BVH_Vec4d& minCorner_Right = bvh->MinPoint( nodeData.z() ); const BVH_Vec4d& maxCorner_Right = bvh->MaxPoint( nodeData.z() ); // Left box { gp_Pnt Pmin( minCorner_Left.x(), minCorner_Left.y(), minCorner_Left.z() ); gp_Pnt Pmax( maxCorner_Left.x(), maxCorner_Left.y(), maxCorner_Left.z() ); const gp_Pnt P2 = gp_Pnt( Pmax.X(), Pmin.Y(), Pmin.Z() ); const gp_Pnt P3 = gp_Pnt( Pmax.X(), Pmax.Y(), Pmin.Z() ); const gp_Pnt P4 = gp_Pnt( Pmin.X(), Pmax.Y(), Pmin.Z() ); const gp_Pnt P5 = gp_Pnt( Pmin.X(), Pmin.Y(), Pmax.Z() ); const gp_Pnt P6 = gp_Pnt( Pmax.X(), Pmin.Y(), Pmax.Z() ); const gp_Pnt P8 = gp_Pnt( Pmin.X(), Pmax.Y(), Pmax.Z() ); if ( Pmin.Distance(P2) > 1.0e-6 ) BB.Add( comp_left, BRepBuilderAPI_MakeEdge(Pmin, P2) ); if ( P2.Distance(P3) > 1.0e-6 ) BB.Add( comp_left, BRepBuilderAPI_MakeEdge(P2, P3) ); if ( P3.Distance(P4) > 1.0e-6 ) BB.Add( comp_left, BRepBuilderAPI_MakeEdge(P3, P4) ); if ( P4.Distance(Pmin) > 1.0e-6 ) BB.Add( comp_left, BRepBuilderAPI_MakeEdge(P4, Pmin) ); if ( P5.Distance(P6) > 1.0e-6 ) BB.Add( comp_left, BRepBuilderAPI_MakeEdge(P5, P6) ); if ( P6.Distance(Pmax) > 1.0e-6 ) BB.Add( comp_left, BRepBuilderAPI_MakeEdge(P6, Pmax) ); if ( Pmax.Distance(P8) > 1.0e-6 ) BB.Add( comp_left, BRepBuilderAPI_MakeEdge(Pmax, P8) ); if ( P8.Distance(P5) > 1.0e-6 ) BB.Add( comp_left, BRepBuilderAPI_MakeEdge(P8, P5) ); if ( P6.Distance(P2) > 1.0e-6 ) BB.Add( comp_left, BRepBuilderAPI_MakeEdge(P6, P2) ); if ( Pmax.Distance(P3) > 1.0e-6 ) BB.Add( comp_left, BRepBuilderAPI_MakeEdge(Pmax, P3) ); if ( P8.Distance(P4) > 1.0e-6 ) BB.Add( comp_left, BRepBuilderAPI_MakeEdge(P8, P4) ); if ( P5.Distance(Pmin) > 1.0e-6 ) BB.Add( comp_left, BRepBuilderAPI_MakeEdge(P5, Pmin) ); } // Right box { gp_Pnt Pmin( minCorner_Right.x(), minCorner_Right.y(), minCorner_Right.z() ); gp_Pnt Pmax( maxCorner_Right.x(), maxCorner_Right.y(), maxCorner_Right.z() ); const gp_Pnt P2 = gp_Pnt( Pmax.X(), Pmin.Y(), Pmin.Z() ); const gp_Pnt P3 = gp_Pnt( Pmax.X(), Pmax.Y(), Pmin.Z() ); const gp_Pnt P4 = gp_Pnt( Pmin.X(), Pmax.Y(), Pmin.Z() ); const gp_Pnt P5 = gp_Pnt( Pmin.X(), Pmin.Y(), Pmax.Z() ); const gp_Pnt P6 = gp_Pnt( Pmax.X(), Pmin.Y(), Pmax.Z() ); const gp_Pnt P8 = gp_Pnt( Pmin.X(), Pmax.Y(), Pmax.Z() ); if ( Pmin.Distance(P2) > 1.0e-6 ) BB.Add( comp_right, BRepBuilderAPI_MakeEdge(Pmin, P2) ); if ( P2.Distance(P3) > 1.0e-6 ) BB.Add( comp_right, BRepBuilderAPI_MakeEdge(P2, P3) ); if ( P3.Distance(P4) > 1.0e-6 ) BB.Add( comp_right, BRepBuilderAPI_MakeEdge(P3, P4) ); if ( P4.Distance(Pmin) > 1.0e-6 ) BB.Add( comp_right, BRepBuilderAPI_MakeEdge(P4, Pmin) ); if ( P5.Distance(P6) > 1.0e-6 ) BB.Add( comp_right, BRepBuilderAPI_MakeEdge(P5, P6) ); if ( P6.Distance(Pmax) > 1.0e-6 ) BB.Add( comp_right, BRepBuilderAPI_MakeEdge(P6, Pmax) ); if ( Pmax.Distance(P8) > 1.0e-6 ) BB.Add( comp_right, BRepBuilderAPI_MakeEdge(Pmax, P8) ); if ( P8.Distance(P5) > 1.0e-6 ) BB.Add( comp_right, BRepBuilderAPI_MakeEdge(P8, P5) ); if ( P6.Distance(P2) > 1.0e-6 ) BB.Add( comp_right, BRepBuilderAPI_MakeEdge(P6, P2) ); if ( Pmax.Distance(P3) > 1.0e-6 ) BB.Add( comp_right, BRepBuilderAPI_MakeEdge(Pmax, P3) ); if ( P8.Distance(P4) > 1.0e-6 ) BB.Add( comp_right, BRepBuilderAPI_MakeEdge(P8, P4) ); if ( P5.Distance(Pmin) > 1.0e-6 ) BB.Add( comp_right, BRepBuilderAPI_MakeEdge(P5, Pmin) ); } } } // Draw BVH IV.ERASE_ALL(); IV.DRAW_SHAPE(comp_left, Color_Yellow, 1.0, true, "BVH Left"); IV.DRAW_SHAPE(comp_right, Color_Green, 1.0, true, "BVH Right"); } //----------------------------------------------------------------------------- //! Initializes the accelerating structure with the given CAD model. //! \param[in] model CAD model to prepare the accelerating structure for. //! \param[in] builderType type of builder to use. //! \return true in case of success, false -- otherwise. bool asiAlgo_BVHFacets::init(const TopoDS_Shape& model, const BuilderType builderType) { if ( model.IsNull() ) return false; // Prepare builder if ( builderType == Builder_Binned ) myBuilder = new BVH_BinnedBuilder<double, 4, 32>(5, 32); else myBuilder = new BVH_LinearBuilder<double, 4>(5, 32); // Explode shape on faces to get face indices TopTools_IndexedMapOfShape faces; TopExp::MapShapes(model, TopAbs_FACE, faces); // Initialize with facets taken from faces for ( int fidx = 1; fidx <= faces.Extent(); ++fidx ) { const TopoDS_Face& face = TopoDS::Face( faces(fidx) ); // if ( !this->addFace(face, fidx) ) return false; } // Calculate bounding diagonal Bnd_Box aabb; BRepBndLib::Add(model, aabb); // m_fBoundingDiag = ( aabb.CornerMax().XYZ() - aabb.CornerMin().XYZ() ).Modulus(); return true; } //----------------------------------------------------------------------------- //! Initializes the accelerating structure with the given CAD model. //! \param[in] model CAD model to prepare the accelerating structure for. //! \param[in] builderType type of builder to use. //! \return true in case of success, false -- otherwise. bool asiAlgo_BVHFacets::init(const Handle(Poly_Triangulation)& mesh, const BuilderType builderType) { // Prepare builder if ( builderType == Builder_Binned ) myBuilder = new BVH_BinnedBuilder<double, 4, 32>(5, 32); else myBuilder = new BVH_LinearBuilder<double, 4>(5, 32); // Initialize with the passed facets if ( !this->addTriangulation(mesh, TopLoc_Location(), -1) ) return false; // Calculate bounding diagonal using fictive face to satisfy OpenCascade's API BRep_Builder BB; TopoDS_Face F; BB.MakeFace(F, mesh); Bnd_Box aabb; BRepBndLib::Add(F, aabb); // m_fBoundingDiag = ( aabb.CornerMax().XYZ() - aabb.CornerMin().XYZ() ).Modulus(); return true; } //----------------------------------------------------------------------------- //! Adds face to the accelerating structure. //! \param[in] face face to add. //! \param[in] face_idx index of the face being added. //! \return true in case of success, false -- otherwise. bool asiAlgo_BVHFacets::addFace(const TopoDS_Face& face, const int face_idx) { TopLoc_Location loc; const Handle(Poly_Triangulation)& tris = BRep_Tool::Triangulation(face, loc); return this->addTriangulation(tris, loc, face_idx); } //----------------------------------------------------------------------------- //! Adds triangulation to the accelerating structure. //! \param[in] triangulation triangulation to add. //! \param[in] loc location to apply. //! \param[in] face_idx index of the corresponding face being. //! \return true in case of success, false -- otherwise. bool asiAlgo_BVHFacets::addTriangulation(const Handle(Poly_Triangulation)& triangulation, const TopLoc_Location& loc, const int face_idx) { if ( triangulation.IsNull() ) return false; for ( int t = 1; t <= triangulation->NbTriangles(); ++t ) { const Poly_Triangle& tri = triangulation->Triangles().Value(t); int n1, n2, n3; tri.Get(n1, n2, n3); gp_Pnt P0 = triangulation->Nodes().Value(n1); P0.Transform(loc); // gp_Pnt P1 = triangulation->Nodes().Value(n2); P1.Transform(loc); // gp_Pnt P2 = triangulation->Nodes().Value(n3); P2.Transform(loc); // Create a new facet t_facet facet(face_idx); // Initialize nodes facet.P0 = BVH_Vec4d(P0.X(), P0.Y(), P0.Z(), 0.0); facet.P1 = BVH_Vec4d(P1.X(), P1.Y(), P1.Z(), 0.0); facet.P2 = BVH_Vec4d(P2.X(), P2.Y(), P2.Z(), 0.0); // Initialize normal gp_Vec V1(P0, P1); V1.Normalize(); gp_Vec V2(P0, P2); V2.Normalize(); facet.N = V1.Crossed(V2); // if ( facet.N.SquareMagnitude() < 1e-8 ) continue; // Skip invalid facet // facet.N.Normalize(); // Store facet in the internal collection m_facets.push_back(facet); } return true; }
36.105145
89
0.580767
[ "cad", "mesh", "geometry", "shape", "model", "transform" ]
bcd6fd74dba610d847f58f314a6dc96222911478
10,195
hpp
C++
openstudiocore/src/runmanager/lib/SSHConnection.hpp
bobzabcik/OpenStudio
858321dc0ad8d572de15858d2ae487b029a8d847
[ "blessing" ]
null
null
null
openstudiocore/src/runmanager/lib/SSHConnection.hpp
bobzabcik/OpenStudio
858321dc0ad8d572de15858d2ae487b029a8d847
[ "blessing" ]
null
null
null
openstudiocore/src/runmanager/lib/SSHConnection.hpp
bobzabcik/OpenStudio
858321dc0ad8d572de15858d2ae487b029a8d847
[ "blessing" ]
null
null
null
#ifndef OPENSTUDIO_RUNMANAGER_SSHCONNECTION_HPP__ #define OPENSTUDIO_RUNMANAGER_SSHCONNECTION_HPP__ #include <string> #include <fstream> #include <utilities/core/Path.hpp> #include <utilities/core/Logger.hpp> #include <QThread> #include <QMutex> #include "RunManagerAPI.hpp" #ifdef RUNMANAGER_HAVE_OPENSSL #include <libssh/libssh.h> #include <libssh/sftp.h> #endif #ifdef min #undef min #endif namespace openstudio { namespace runmanager { namespace detail { /// Thread for executing a remote command and reading the results back from the ssh_session object class ExecThread : public QThread { Q_OBJECT; #ifdef RUNMANAGER_HAVE_OPENSSL public: ExecThread(int id, ssh_session t_session, QMutex *t_mutex, const std::string &t_command, int t_timeout_msecs); virtual ~ExecThread(); protected: void run(); private: REGISTER_LOGGER("openstudio.runmanager.ExecThread"); int m_id; ssh_session m_session; ssh_channel m_channel; QMutex *m_mutex; std::string m_command; int m_timeout_msecs; bool m_error_occurred; #endif signals: void dataRead(int id, QString cmd, QString data); void errDataRead(int id, QString cmd, QString data); void finished(int id, QString cmd); void timeout(int id, QString cmd); }; /// Thread for executing remote file transfer to local and reading the data as it is available class GetFileThread : public QThread { Q_OBJECT; #ifdef RUNMANAGER_HAVE_OPENSSL public: GetFileThread(int id, ssh_session t_session, QMutex *t_mutex, const openstudio::path &t_fromremotepath, const openstudio::path &t_tolocalpath, int t_timeout_msecs); virtual ~GetFileThread(); protected: void run(); private: REGISTER_LOGGER("openstudio.runmanager.GetFileThread"); int m_id; void handle_error(const std::string &desc, ssh_session t_session, sftp_session t_file); ssh_session m_session; sftp_session m_sftp_session; sftp_file m_sftp_file; QMutex *m_mutex; openstudio::path m_fromremote; openstudio::path m_tolocal; int m_timeout_msecs; bool m_error_occurred; std::ofstream m_outfile; #endif signals: void finished(int id, QString fromremotepath, QString tolocalpath); void timeout(int id, QString fromremotepath, QString tolocalpath); }; /// Thread for executing local file transfer to remote and feeding the file data class PutFileThread : public QThread { Q_OBJECT; #ifdef RUNMANAGER_HAVE_OPENSSL public: PutFileThread(int id, ssh_session t_session, QMutex *t_mutex, const openstudio::path &t_fromlocalpath, const openstudio::path &t_toremotepath, int t_timeout_msecs); virtual ~PutFileThread(); protected: void run(); private: REGISTER_LOGGER("openstudio.runmanager.PutFileThread"); int m_id; void handle_error(const std::string &desc, ssh_session t_session, sftp_session t_file); ssh_session m_session; sftp_session m_sftp_session; sftp_file m_sftp_file; QMutex *m_mutex; openstudio::path m_fromlocal; openstudio::path m_toremote; int m_timeout_msecs; bool m_error_occurred; std::ifstream m_infile; #endif signals: void finished(int id, QString fromlocalpath, QString toremotepath); void timeout(int id, QString fromlocalpath, QString toremotepath); }; } /// Credentials object to be used for specifying how to connect to a remote SSH system class RUNMANAGER_API SSHCredentials { public: SSHCredentials(const std::string &host, const std::string &t_username, const std::string &t_password, int t_port=22); SSHCredentials(const std::string &host, const std::string &t_username, const openstudio::path &t_publickey, const openstudio::path &t_privatekey, int t_port = 22); SSHCredentials(const std::string &host, const std::string &t_username, int t_port = 22); SSHCredentials(const std::string &host, int t_port = 22); SSHCredentials(); bool operator==(const SSHCredentials &t_rhs) const; bool operator!=(const SSHCredentials &t_rhs) const { return !(*this == t_rhs); } boost::optional<std::string> host() const; boost::optional<std::string> username() const; boost::optional<std::string> password() const; boost::optional<openstudio::path> publickey() const; boost::optional<openstudio::path> privatekey() const; int port() const; void setHost(const std::string &t_host); void setUsername(const std::string &t_username); void setPassword(const std::string &t_password); void setPublickey(const openstudio::path &t_pubkey); void setPrivatekey(const openstudio::path &t_privkey); void setPort(int t_port); private: boost::optional<std::string> m_host; boost::optional<std::string> m_username; boost::optional<std::string> m_password; boost::optional<openstudio::path> m_publickey; boost::optional<openstudio::path> m_privatekey; int m_port; template<typename T> static bool compareOptionals(const boost::optional<T> &t_lhs, const boost::optional<T> &t_rhs) { if (!t_lhs && !t_rhs) { return true; } if (t_lhs && t_rhs) { return *t_lhs == *t_rhs; } return false; } }; /** * Class for connecting to an SSH server, executing remote commands on it, sending and receiving files * with it. * \todo move this to utilities library? */ class RUNMANAGER_API SSHConnection : public QObject { Q_OBJECT; public: SSHConnection(const SSHCredentials &t_creds, bool t_allow_ui); virtual ~SSHConnection(); /// Returns the credentials used to successfully connect to the server SSHCredentials getCredentials() const; /// execute a command. Only one may be running at a time. void execCommand(int id, const std::string &command, int t_timeout_msecs); /// execute a command out of band. Only one may be running at a time. void execOOBCommand(int id, const std::string &command, int t_timeout_msecs); /// Download a file from the ssh server. Only one may be running at a time. void getFile(int id, const openstudio::path &remotefrom, const openstudio::path &localto, int t_timeout_msecs); /// Upload a file to the ssh server. Only one may be running at a time. void putFile(int id, const openstudio::path &localfrom, const openstudio::path &remoteto, int t_timeout_msecs); /// \returns true if the main execution channel is idle bool idle(); /// \returns true if the outofband execution channel is idle bool oobIdle(); signals: /// Emitted when stdout on main command channel is read void execCommandStandardOut(int id, const std::string &command, const std::string &data); /// Emitted when stderr on main command channel is read void execCommandStandardErr(int id, const std::string &command, const std::string &data); /// Emitted when main command channel exec is completed void execCommandFinished(int id, const std::string &command, bool timedout); /// Emitted when stdout on OOB command channel is read void execOOBCommandStandardOut(int id, const std::string &command, const std::string &data); /// Emitted when stderr on OOB command channel is read void execOOBCommandStandardErr(int id, const std::string &command, const std::string &data); /// Emitted when oob command channel exec is completed void execOOBCommandFinished(int id, const std::string &command, bool timedout); /// Emitted when current get file operation has completed void getFileFinished(int id, const openstudio::path &remotefrom, const openstudio::path &localto, bool timedout); /// Emitted when current put file operation has completed void putFileFinished(int id, const openstudio::path &localfrom, const openstudio::path &remoteto, bool timedout); private slots: //Note: using all QString's for signal parameters to avoid problems with // cross-thread signals // used for reading data from threads void execDataRead(int id, QString command, QString data); void execErrDataRead(int id, QString command, QString data); void execFinished(int id, QString command); void execTimeout(int id, QString command); void execOOBDataRead(int id, QString command, QString data); void execOOBErrDataRead(int id, QString command, QString data); void execOOBFinished(int id, QString command); void execOOBTimeout(int id, QString command); void fileGetFinished(int id, QString remotefrom, QString localto); void fileGetTimeout(int id, QString remotefrom, QString localto); void filePutFinished(int id, QString remotefrom, QString localto); void filePutTimeout(int id, QString remotefrom, QString localto); private: REGISTER_LOGGER("openstudio.runmanager.SSHConnection"); SSHCredentials m_credentials; bool m_command_timedout; bool m_oob_command_timedout; bool m_get_timedout; bool m_put_timedout; #ifdef RUNMANAGER_HAVE_OPENSSL /// deciphers an error and throws an exception static void handle_error(const std::string &t_message, ssh_session t_session); mutable QMutex m_mutex; ssh_session m_session; boost::shared_ptr<detail::ExecThread> m_exec_thread; boost::shared_ptr<detail::GetFileThread> m_get_file_thread; boost::shared_ptr<detail::PutFileThread> m_put_file_thread; boost::shared_ptr<detail::ExecThread> m_oob_exec_thread; #endif }; } } #endif
32.468153
120
0.674252
[ "object" ]
bcd8c7e80d9d2d6ee064b91a33194fc9e8b27500
3,492
cpp
C++
planning_ros_utils/src/ros_utils/mapping_ros_utils.cpp
wuyou33/mpl_ros
4c239292ace1b98f39d35adf74e6d53aa999d63c
[ "Apache-2.0" ]
1
2017-12-17T13:35:56.000Z
2017-12-17T13:35:56.000Z
planning_ros_utils/src/ros_utils/mapping_ros_utils.cpp
wuyou33/mpl_ros
4c239292ace1b98f39d35adf74e6d53aa999d63c
[ "Apache-2.0" ]
null
null
null
planning_ros_utils/src/ros_utils/mapping_ros_utils.cpp
wuyou33/mpl_ros
4c239292ace1b98f39d35adf74e6d53aa999d63c
[ "Apache-2.0" ]
null
null
null
#include <ros_utils/mapping_ros_utils.h> void setMap(std::shared_ptr<MPL::VoxelMapUtil> map_util, const planning_ros_msgs::VoxelMap& msg) { Vec3f ori(msg.origin.x, msg.origin.y, msg.origin.z); Vec3i dim(msg.dim.x, msg.dim.y, msg.dim.z); decimal_t res = msg.info.resolution; std::vector<signed char> map = msg.data; map_util->setMap(ori, dim, map, res); } void getMap(std::shared_ptr<MPL::VoxelMapUtil> map_util, planning_ros_msgs::VoxelMap& map) { Vec3f ori = map_util->getOrigin(); Vec3i dim = map_util->getDim(); decimal_t res = map_util->getRes(); map.origin.x = ori(0); map.origin.y = ori(1); map.origin.z = ori(2); map.dim.x = dim(0); map.dim.y = dim(1); map.dim.z = dim(2); map.info.resolution = res; map.data = map_util->getMap(); } /* void setMap(MPL::SubVoxelMapUtil* map_util, const planning_ros_msgs::VoxelMap& msg) { Vec3f ori(msg.origin.x, msg.origin.y, msg.origin.z); Vec3i dim(msg.dim.x, msg.dim.y, msg.dim.z); decimal_t res = msg.info.resolution; std::vector<signed char> map = msg.data; map_util->setMap(ori, dim, map, res); } void getMap(MPL::SubVoxelMapUtil* map_util, planning_ros_msgs::VoxelMap& map) { Vec3i dim1 = map_util->getDimLow(); Vec3i dim2 = map_util->getDimUp(); Vec3i dim = dim2 - dim1; decimal_t res = map_util->getRes(); Vec3f ori = map_util->intToFloat(dim1); map.origin.x = ori(0); map.origin.y = ori(1); map.origin.z = ori(2); map.dim.x = dim(0); map.dim.y = dim(1); map.dim.z = dim(2); map.info.resolution = res; map.data = map_util->getSubMap(); } void setMap(JPS::VoxelMapUtil* map_util, const planning_ros_msgs::VoxelMap& msg) { Vec3f ori(msg.origin.x, msg.origin.y, msg.origin.z); Vec3i dim(msg.dim.x, msg.dim.y, msg.dim.z); decimal_t res = msg.info.resolution; std::vector<signed char> map = msg.data; map_util->setMap(ori, dim, map, res); } void getMap(JPS::VoxelMapUtil* map_util, planning_ros_msgs::VoxelMap& map) { Vec3f ori = map_util->getOrigin(); Vec3i dim = map_util->getDim(); decimal_t res = map_util->getRes(); map.origin.x = ori(0); map.origin.y = ori(1); map.origin.z = ori(2); map.dim.x = dim(0); map.dim.y = dim(1); map.dim.z = dim(2); map.info.resolution = res; map.data = map_util->getMap(); } void setMap(JPS::SubVoxelMapUtil* map_util, const planning_ros_msgs::VoxelMap& msg) { Vec3f ori(msg.origin.x, msg.origin.y, msg.origin.z); Vec3i dim(msg.dim.x, msg.dim.y, msg.dim.z); decimal_t res = msg.info.resolution; std::vector<signed char> map = msg.data; map_util->setMap(ori, dim, map, res); } void getMap(JPS::SubVoxelMapUtil* map_util, planning_ros_msgs::VoxelMap& map) { Vec3i dim1 = map_util->getDimLow(); Vec3i dim2 = map_util->getDimUp(); Vec3i dim = dim2 - dim1; decimal_t res = map_util->getRes(); Vec3f ori = map_util->intToFloat(dim1); map.origin.x = ori(0); map.origin.y = ori(1); map.origin.z = ori(2); map.dim.x = dim(0); map.dim.y = dim(1); map.dim.z = dim(2); map.info.resolution = res; map.data = map_util->getSubMap(); } void toMPLMapUtil(JPS::VoxelMapUtil* jps_map_util, MPL::VoxelMapUtil* mpl_map_util) { mpl_map_util->setMap(jps_map_util->getOrigin(), jps_map_util->getDim(), jps_map_util->getMap(), jps_map_util->getRes()); } void toJPSMapUtil(MPL::VoxelMapUtil* mpl_map_util, JPS::VoxelMapUtil* jps_map_util) { jps_map_util->setMap(mpl_map_util->getOrigin(), mpl_map_util->getDim(), mpl_map_util->getMap(), mpl_map_util->getRes()); } */
27.936
122
0.679267
[ "vector" ]
bce028e3acce3c858cf15f7a0c269626bdf974bc
720
cpp
C++
src/rules/add_value.cpp
wilkie/apsis
9e6a37ad9dfc8931b25b9429d7e4a770b4e760bf
[ "WTFPL" ]
2
2015-11-05T03:47:29.000Z
2020-01-24T18:48:09.000Z
src/rules/add_value.cpp
wilkie/apsis
9e6a37ad9dfc8931b25b9429d7e4a770b4e760bf
[ "WTFPL" ]
null
null
null
src/rules/add_value.cpp
wilkie/apsis
9e6a37ad9dfc8931b25b9429d7e4a770b4e760bf
[ "WTFPL" ]
null
null
null
#include "apsis/rules/add_value.h" void Apsis::Rules::AddValue::respond(unsigned int event_id, const Apsis::World::Scene&, Apsis::World::Object& object) { static unsigned int amount_id = Apsis::Registry::Property::id("amount"); static unsigned int property_id = Apsis::Registry::Property::id("property"); float amount = (float)object.getForEvent(event_id, amount_id).asDouble(); const char* property = object.getForEvent(event_id, property_id).asCString(); unsigned int value_id = Apsis::Registry::Property::id(property); float value = (float)object.get(value_id).asDouble(); value += amount; object.set(value_id, value); }
40
79
0.658333
[ "object" ]
bce4f5133a6a9075cf8b553d57422b80327f0fa6
478
cpp
C++
cpp/c++11/foreach.cpp
yanrong/book_demo
20cd13f3c3507a11e826ebbf22bd1c7bcb36e06f
[ "Apache-2.0" ]
null
null
null
cpp/c++11/foreach.cpp
yanrong/book_demo
20cd13f3c3507a11e826ebbf22bd1c7bcb36e06f
[ "Apache-2.0" ]
null
null
null
cpp/c++11/foreach.cpp
yanrong/book_demo
20cd13f3c3507a11e826ebbf22bd1c7bcb36e06f
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <vector> #include <map> int main() { std::map<std::string,std::vector<int>>map; std::vector<int> v; v.push_back(1); v.push_back(2); v.push_back(3); map["one"] = v; for(const auto & kvp : map) { std::cout<<kvp.first<<std::endl; for(auto v : kvp.second) { std::cout<<v<<std::endl; } } int arr[]={1,2,3,4,5}; for(int& e : arr) { e=e*e; } for(int& e : arr) { std::cout<<e<<","; } std::cout<<std::endl; return 0; }
13.657143
43
0.550209
[ "vector" ]
bce503324fae26898fd76f5d417097c700712289
14,043
cpp
C++
Chemistry Exploratory Project B.cpp
ShubhamAvasthi/exploratory-project
4503eaef00e1a933c6c993db31d9065269738fe9
[ "MIT" ]
null
null
null
Chemistry Exploratory Project B.cpp
ShubhamAvasthi/exploratory-project
4503eaef00e1a933c6c993db31d9065269738fe9
[ "MIT" ]
null
null
null
Chemistry Exploratory Project B.cpp
ShubhamAvasthi/exploratory-project
4503eaef00e1a933c6c993db31d9065269738fe9
[ "MIT" ]
null
null
null
#include<array> #include<cassert> #include<fstream> #include<iostream> #include<random> #include<thread> #include<vector> #include<windows.h> using namespace std; #define r 127 #define l ((r<<1)+1)//250//720 //195 #define b ((r<<1)+1)//160//160 //45 #define E ' ' #define C 'C' #define O 'O' #define ORIGINAL 15 #define C_col 150 #define O_col 100 #define End_message_space 0 #define max_iter 100000000 #define mf_bin 0.01 #define vis_out 0 ofstream out("out.txt"); HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE); void gotoxy(int y, int x) { COORD coord; coord.X = x; coord.Y = y; SetConsoleCursorPosition(console,coord); } int main() { // Assumptions are made in drawing the circle out.setf(ios::fixed); system("pause"); float yCO=0.0,yO2=1.0; /*do { system("cls"); cout<<"Enter the mole fraction of CO: "; cin>>yCO; cout<<"Enter the mole fraction of O2: "; cin>>yO2; if(yCO+yO2<0||yCO+yO2>1) { cout<<"\nYou entered wrong values of mole fractions. Please enter them again.\n"; system("pause"); } }while(yCO+yO2<=0||yCO+yO2>1);*/ //yCO=0.5;yO2=0.5; while(yCO<=1) { system("cls"); if(vis_out) gotoxy(b+End_message_space,0); cout<<"yCO="<<yCO; array<string,b> grid; int voids=l*b,CO_area=0,O_area=0,CO2_prod=0; gotoxy(0,0); for(int i=0;i<b;i++) { grid[i]=string(l,E); for(int j=0;j<l;j++) { if(((l/2.0)-(j+0.5))*((l/2.0)-(j+0.5))+((b/2.0)-(i+0.5))*((b/2.0)-(i+0.5))>=r*r) { grid[i][j]=O; voids--; O_area++; } if(vis_out) { if(grid[i][j]==O) { SetConsoleTextAttribute(console,O_col); cout<<O; SetConsoleTextAttribute(console,ORIGINAL); } else if(grid[i][j]==E) { cout<<E; } } } if(vis_out) cout<<'\n'; } int cat_sites=voids; //return 0; default_random_engine generator; uniform_real_distribution<double> mf_parameter(0,yCO+yO2); long long it_no=0; long double ACF_O=0,ACF_CO=0; long double theta_s=0; //Time averaged fraction of catalyst sites that are unoccupied. int z=max_iter; while(z--) { if(it_no==max_iter) break; if(mf_parameter(generator)<yCO) // Carbon Monoxide { int x=rand()%l,y=rand()%b; if(grid[y][x]==E) { vector<pair<int,int>> v; if(grid[(y+1)%b][x]==O) v.push_back({(y+1)%b,x}); if(grid[(y-1+b)%b][x]==O) v.push_back({(y-1+b)%b,x}); if(grid[y][(x+1)%l]==O) v.push_back({y,(x+1)%l}); if(grid[y][(x-1+l)%l]==O) v.push_back({y,(x-1+l)%l}); if(v.empty()) { if(vis_out) SetConsoleTextAttribute(console,C_col); grid[y][x]=C; if(vis_out) { gotoxy(y,x); cout<<C; } voids--; CO_area++; if(vis_out) SetConsoleTextAttribute(console,ORIGINAL); } else { int z=rand()%v.size(); if(((l/2.0)-(v[z].second+0.5))*((l/2.0)-(v[z].second+0.5))+((b/2.0)-(v[z].first+0.5))*((b/2.0)-(v[z].first+0.5))<r*r) { grid[v[z].first][v[z].second]=E; voids++; O_area--; } if(vis_out&&(grid[v[z].first][v[z].second]==E)) { gotoxy(v[z].first,v[z].second); SetConsoleTextAttribute(console,ORIGINAL); cout<<grid[v[z].first][v[z].second]; } } } } else //Oxygen { int x=rand()%l,y=rand()%b; bool V=rand()&1; if(grid[y][x]==E&&((V?grid[(y+1)%b][x]:grid[y][(x+1)%l])==E)) { int x2=(V?x:(x+1)%l),y2=(V?(y+1)%b:y); vector<pair<int,int>> v; if(grid[(y+1)%b][x]==C) v.push_back({(y+1)%b,x}); if(grid[(y-1+b)%b][x]==C) v.push_back({(y-1+b)%b,x}); if(grid[y][(x+1)%l]==C) v.push_back({y,(x+1)%l}); if(grid[y][(x-1+l)%l]==C) v.push_back({y,(x-1+l)%l}); if(v.empty()) { if(vis_out) SetConsoleTextAttribute(console,O_col); grid[y][x]=O; if(vis_out) { gotoxy(y,x); cout<<O; } voids--; O_area++; if(vis_out) SetConsoleTextAttribute(console,ORIGINAL); } else { int z=rand()%v.size(); grid[v[z].first][v[z].second]=E; if(vis_out) { gotoxy(v[z].first,v[z].second); cout<<E; } voids++; CO_area--; } v.clear(); if(grid[(y2+1)%b][x2]==C) v.push_back({(y2+1)%b,x2}); if(grid[(y2-1+b)%b][x2]==C) v.push_back({(y2-1+b)%b,x2}); if(grid[y2][(x2+1)%l]==C) v.push_back({y2,(x2+1)%l}); if(grid[y2][(x2-1+l)%l]==C) v.push_back({y2,(x2-1+l)%l}); if(v.empty()) { if(vis_out) SetConsoleTextAttribute(console,O_col); grid[y2][x2]=O; if(vis_out) { gotoxy(y2,x2); cout<<O; } voids--; O_area++; if(vis_out) SetConsoleTextAttribute(console,ORIGINAL); } else { int z=rand()%v.size(); grid[v[z].first][v[z].second]=E; if(vis_out) { gotoxy(v[z].first,v[z].second); cout<<E; } voids++; CO_area--; } } } } //Steady state while(1) { if(it_no==max_iter) break; if(mf_parameter(generator)<yCO) // Carbon Monoxide { int x=rand()%l,y=rand()%b; if(grid[y][x]==E) { vector<pair<int,int>> v; if(grid[(y+1)%b][x]==O) v.push_back({(y+1)%b,x}); if(grid[(y-1+b)%b][x]==O) v.push_back({(y-1+b)%b,x}); if(grid[y][(x+1)%l]==O) v.push_back({y,(x+1)%l}); if(grid[y][(x-1+l)%l]==O) v.push_back({y,(x-1+l)%l}); if(v.empty()) { if(vis_out) SetConsoleTextAttribute(console,C_col); grid[y][x]=C; if(vis_out) { gotoxy(y,x); cout<<C; } voids--; CO_area++; if(vis_out) SetConsoleTextAttribute(console,ORIGINAL); } else { int z=rand()%v.size(); CO2_prod++; if(((l/2.0)-(v[z].second+0.5))*((l/2.0)-(v[z].second+0.5))+((b/2.0)-(v[z].first+0.5))*((b/2.0)-(v[z].first+0.5))<r*r) { grid[v[z].first][v[z].second]=E; voids++; O_area--; } if(vis_out&&(grid[v[z].first][v[z].second]==E)) { gotoxy(v[z].first,v[z].second); SetConsoleTextAttribute(console,ORIGINAL); cout<<grid[v[z].first][v[z].second]; } } } } else //Oxygen { int x=rand()%l,y=rand()%b; bool V=rand()&1; if(grid[y][x]==E&&((V?grid[(y+1)%b][x]:grid[y][(x+1)%l])==E)) { int x2=(V?x:(x+1)%l),y2=(V?(y+1)%b:y); vector<pair<int,int>> v; if(grid[(y+1)%b][x]==C) v.push_back({(y+1)%b,x}); if(grid[(y-1+b)%b][x]==C) v.push_back({(y-1+b)%b,x}); if(grid[y][(x+1)%l]==C) v.push_back({y,(x+1)%l}); if(grid[y][(x-1+l)%l]==C) v.push_back({y,(x-1+l)%l}); if(v.empty()) { if(vis_out) SetConsoleTextAttribute(console,O_col); grid[y][x]=O; if(vis_out) { gotoxy(y,x); cout<<O; } voids--; O_area++; if(vis_out) SetConsoleTextAttribute(console,ORIGINAL); } else { int z=rand()%v.size(); grid[v[z].first][v[z].second]=E; if(vis_out) { gotoxy(v[z].first,v[z].second); cout<<E; } voids++; CO2_prod++; CO_area--; } v.clear(); if(grid[(y2+1)%b][x2]==C) v.push_back({(y2+1)%b,x2}); if(grid[(y2-1+b)%b][x2]==C) v.push_back({(y2-1+b)%b,x2}); if(grid[y2][(x2+1)%l]==C) v.push_back({y2,(x2+1)%l}); if(grid[y2][(x2-1+l)%l]==C) v.push_back({y2,(x2-1+l)%l}); if(v.empty()) { if(vis_out) SetConsoleTextAttribute(console,O_col); grid[y2][x2]=O; if(vis_out) { gotoxy(y2,x2); cout<<O; } voids--; O_area++; if(vis_out) SetConsoleTextAttribute(console,ORIGINAL); } else { int z=rand()%v.size(); grid[v[z].first][v[z].second]=E; if(vis_out) { gotoxy(v[z].first,v[z].second); cout<<E; } voids++; CO2_prod++; CO_area--; } } } ACF_O+=O_area; ACF_CO+=CO_area; theta_s+=voids; //this_thread::sleep_for(1ns); it_no++; } ACF_O/=max_iter; ACF_O/=l*b; ACF_CO/=max_iter; ACF_CO/=l*b; theta_s/=max_iter; theta_s/=cat_sites; if(vis_out) gotoxy(b+End_message_space,0); cout<<"\rSimulation Ended"<<' '<<yCO; //out<<yCO<<' '<<ACF_CO<<' '<<ACF_O<<' '<<(float)CO2_prod/max_iter<<'\n'; out<<yCO<<' '<<yCO*theta_s<<'\n'; //system("pause"); yCO+=mf_bin; yO2-=mf_bin; } }
34.25122
142
0.304778
[ "vector" ]
bcea049a8ca82f19bc0367a2de1e597e9f3bf3b3
20,938
cpp
C++
src/internal/HMStorageHost.cpp
varsameer/NetCHASM
3071241ce0d2cddc077e5e7e1b957677d733ae76
[ "Apache-2.0" ]
13
2019-06-06T01:14:30.000Z
2022-03-03T05:57:51.000Z
src/internal/HMStorageHost.cpp
varsameer/NetCHASM
3071241ce0d2cddc077e5e7e1b957677d733ae76
[ "Apache-2.0" ]
7
2019-07-23T18:31:20.000Z
2021-05-26T12:57:34.000Z
src/internal/HMStorageHost.cpp
varsameer/NetCHASM
3071241ce0d2cddc077e5e7e1b957677d733ae76
[ "Apache-2.0" ]
12
2019-06-27T13:58:03.000Z
2021-12-23T07:43:06.000Z
// Copyright 2019, Oath Inc. // Licensed under the terms of the Apache 2.0 license. See LICENSE file in the root of the distribution for licensing details. #include <string> #include <list> #include "HMStorageHost.h" #include "HMLogBase.h" #include "HMAuxCache.h" #include "HMState.h" using namespace std; void HMStorageHost::initResultsFromBackend(HMDataCheckList& checkList, HMDNSCache& dnsCache, HMAuxCache& auxCache, HMRemoteHostGroupCache& remoteCache, HMRemoteHostCache& remoteHostCache) { (void)remoteCache; set<string> backendNames; set<string> localNames; map<pair<string, HMDNSLookup>,set<HMIPAddress>> dnsMap; map<pair<string, HMDNSLookup>,HMTimeStamp> dnsResTimeMap; HMIPAddress blank(AF_INET); HMIPAddress blankv6(AF_INET6); list<HMCheckHeader> localChecks; vector<HMCheckHeader> getChecks; if(!getHostNames(backendNames)) { HMLog(HM_LOG_ERROR, "Failed to fetch host names from backend"); return; } checkList.getAllChecks(getChecks); for(auto it = getChecks.begin(); it != getChecks.end(); ++it) { localNames.insert(it->m_hostname); localChecks.push_back(*it); } // We have three groups to deal with: // 1 The names in both datasets (check by check update to local and removal from backend) // 2 Names in the backend but not local (delete) // 3 Names in the local but not backend (blank entries needed for IPAddress) set<string> both; for(auto it = backendNames.begin(); it != backendNames.end(); ) { if(localNames.find(*it) != localNames.end()) { both.insert(*it); localNames.erase(*it); it = backendNames.erase(it); continue; } ++it; } // Delete the extra names in the backend for(auto it = backendNames.begin(); it != backendNames.end(); ++it) { removeName(*it); } // Now insert the local checks that are not present in the backend for(auto it = localNames.begin(); it != localNames.end(); ++it) { vector<HMCheckHeader> headers; bool v6, v4 = false; HMCheckHeader checkHeader; for(auto check = localChecks.begin(); check != localChecks.end(); ) { if(*it == check->m_hostname) { // The check does not exist in the backend v4 = (check->m_hostCheck.getDualStack() & HM_DUALSTACK_IPV4_ONLY) ? true : v4; v6 = (check->m_hostCheck.getDualStack() & HM_DUALSTACK_IPV6_ONLY) ? true : v6; checkHeader.m_hostCheck = check->m_hostCheck; checkHeader.m_hostname = check->m_hostname; checkHeader.m_checkParams = check->m_checkParams; checkHeader.m_address = check->m_address; headers.push_back(*check); HMCheckData cd(check->m_hostname, check->m_address, check->m_hostCheck, check->m_checkParams, HMDataCheckResult()); HMAuxInfo empty; HMAuxData ca(check->m_hostname, check->m_address, check->m_hostCheck, check->m_checkParams, empty); if(!storeHostCheckResult(cd)) { HMLog(HM_LOG_ERROR, "Failed to store check entry for %s", check->m_hostname.c_str()); } if(!storeHostAuxInfo(ca)) { HMLog(HM_LOG_ERROR, "Failed to store aux entry for %s", check->m_hostname.c_str()); } check = localChecks.erase(check); continue; } ++check; } // Store the headers if(!storeNameChecks(*it, headers)) { HMLog(HM_LOG_ERROR, "Failed to store headers for %s", it->c_str()); } // Insert blank DNS entry set<HMIPAddress> addresses; uint8_t dualstack = (v4 ? HM_DUALSTACK_IPV4_ONLY : 0) | (v6 ? HM_DUALSTACK_IPV6_ONLY : 0); HMDNSLookup dnsHostCheck(checkHeader.m_hostCheck.getDnsType(), checkHeader.m_hostCheck.getRemoteCheck()); dnsCache.getAddresses(*it, dualstack, dnsHostCheck, addresses); if(addresses.size() == 0) { if(dualstack & HM_DUALSTACK_IPV4_ONLY) { addresses.insert(blank); } if(dualstack & HM_DUALSTACK_IPV6_ONLY) { addresses.insert(blankv6); } } if(!storeDNSResult(*it, addresses)) { HMLog(HM_LOG_ERROR, "Failed to store DNS for %s", it->c_str()); } } // Now we need to deal with the overlap set<HMCheckHeader> filledChecks; for(auto it = both.begin(); it != both.end(); ++it) { vector<HMCheckHeader> checks; if(!getNameChecks(*it, checks)) { HMLog(HM_LOG_ERROR, "Failed to fetch host checks for %s from backend", it->c_str()); continue; } // We need to either copy the results from the backend or remove for(auto check = checks.begin(); check != checks.end(); ++check) { bool found = false; for(auto localCheck = localChecks.begin(); localCheck != localChecks.end(); ++localCheck) { if(localCheck->m_hostname == check->m_hostname && localCheck->m_hostCheck == check->m_hostCheck && localCheck->m_checkParams == check->m_checkParams) { // The check exists in both local and backend // Copy the data from the backend and remove from the localChecks found = true; HMDataCheckResult result; HMAuxInfo auxInfo; if(getHostCheckResult(*check, result)) { checkList.updateCheck(*check, result); } if(getHostAuxInfo(*check, auxInfo)) { auxCache.updateAuxInfo(check->m_hostname, check->m_hostCheck.getCheckInfo(), check->m_address, auxInfo); } HMDNSLookup dnsHostCheck(check->m_hostCheck.getDnsType(), check->m_address.getType() == AF_INET6, check->m_hostCheck.getRemoteCheck()); pair<string, HMDNSLookup> key = make_pair(check->m_hostname, dnsHostCheck); auto res = dnsMap.insert(make_pair(key, set<HMIPAddress>())); res.first->second.insert(check->m_address); if(dnsResTimeMap.find(key) == dnsResTimeMap.end()) { dnsResTimeMap.insert(make_pair(key, result.m_checkTime)); } if(check->m_hostCheck.getFlowType() == HM_FLOW_REMOTE_HOST_TYPE) { remoteHostCache.updateResultTime(check->m_hostname, check->m_hostCheck, result.m_checkTime); } filledChecks.insert(*localCheck); break; } } // Check exists in the backend but not local if(!found) { removeHostCheckResult(*check); removeHostAuxInfo(*check); } } } // Backfill the DNS cache for(auto it = dnsMap.begin(); it != dnsMap.end(); ++it) { HMDNSResult v4Result; HMDNSResult v6Result; auto res = dnsResTimeMap.find(it->first); if (res != dnsResTimeMap.end()) { v4Result.setResultTime(res->second); } res = dnsResTimeMap.find(it->first); if (res != dnsResTimeMap.end()) { v6Result.setResultTime(res->second); } dnsCache.updateReloadDNSEntry(it->first.first, it->second, v4Result, v6Result, res->first.second); } // Fill missing entries in the backend for(auto check = localChecks.begin(); check != localChecks.end(); ++check) { if(filledChecks.find(*check) == filledChecks.end()) { // No backend entry for this vector<HMCheckHeader> headers; getNameChecks(check->m_hostname, headers); headers.push_back(*check); storeNameChecks(check->m_hostname, headers); HMCheckData cd(check->m_hostname, check->m_address, check->m_hostCheck, check->m_checkParams, HMDataCheckResult()); HMAuxInfo empty; HMAuxData ca(check->m_hostname, check->m_address, check->m_hostCheck, check->m_checkParams, empty); if(!storeHostCheckResult(cd)) { HMLog(HM_LOG_ERROR, "Failed to store check entry for %s", check->m_hostname.c_str()); } if(!storeHostAuxInfo(ca)) { HMLog(HM_LOG_ERROR, "Failed to store aux entry for %s", check->m_hostname.c_str()); } set<HMIPAddress> addresses; getDNSResult(check->m_hostname, addresses); bool v4found = false; bool v6found = false; for(auto address = addresses.begin(); address != addresses.end(); ++address) { v4found = (address->getType() == AF_INET) ? true : v4found; v6found = (address->getType() == AF_INET6) ? true : v6found; } uint8_t dualstack = check->m_hostCheck.getDualStack(); if((dualstack & HM_DUALSTACK_IPV4_ONLY) && !v4found) { addresses.insert(blank); } if((dualstack & HM_DUALSTACK_IPV6_ONLY) && !v6found) { addresses.insert(blankv6); } storeDNSResult(check->m_hostname, addresses); } } // Commit the hostNames set<string> hostNames; for(auto it = both.begin(); it != both.end(); ++it) { hostNames.insert(*it); } for(auto it = localNames.begin(); it != localNames.end(); ++it) { hostNames.insert(*it); } storeHostNames(hostNames); } bool HMStorageHost::storeConfigs(HMState& checkState) { // Store the hostnames, the hostchecks and the host group information vector<HMCheckHeader> allChecks; set<string> allHosts; checkState.m_checkList.getAllChecks(allChecks); for(auto it = allChecks.begin(); it != allChecks.end(); ++it) { allHosts.insert(it->m_hostname); } if(!storeHostNames(allHosts)) { return false; } // Now on the second pass, we store all the hostchecks for(auto it = allHosts.begin(); it != allHosts.end(); ++it) { vector<HMCheckHeader> checks; for(auto iit = allChecks.begin(); iit != allChecks.end(); ++iit) { if(iit->m_hostname == *it) { checks.push_back(*iit); } } if(!storeNameChecks(*it, checks)) { return false; } } // Now store the host group info set<string> hostGroupNames; for(auto it = checkState.m_hostGroups.begin(); it != checkState.m_hostGroups.end(); ++it) { hostGroupNames.insert(it->first); if(!storeGroupInfo(it->first, it->second)) { return false; } } return storeHostGroupNames(hostGroupNames); } bool HMStorageHost::getConfigs(HMState& checkState) { set<string> hostNames; string hostGroup = ""; set<HMIPAddress> ip; set<string> hostGroupNames; if(!getHostGroupNames(hostGroupNames)) { return false; } for(auto it = hostGroupNames.begin(); it != hostGroupNames.end(); ++it) { HMDataHostGroup hostGroup(*it); if(!getGroupInfo(*it, hostGroup)) { return false; } checkState.m_hostGroups.insert(make_pair(*it, hostGroup)); checkState.m_checkList.addHostGroup(hostGroup); } if(!getHostNames(hostNames)) { return false; } for(auto it = hostNames.begin(); it != hostNames.end(); ++it) { vector<HMCheckHeader> checks; if(!getNameChecks(*it, checks)) { return false; } for(auto check = checks.begin(); check != checks.end(); ++check) { checkState.m_checkList.insertCheck(hostGroup, check->m_hostname, check->m_hostCheck, check->m_checkParams, ip); } } return true; } bool HMStorageHost::storeCheckResult(const string& hostname, const HMIPAddress& address, const HMDataHostCheck& hostCheck, const HMDataCheckParams& checkParams, const HMDataCheckResult& checkResult) { if(m_readonly) { HMLog(HM_LOG_ERROR, "[STORE] Attempting to store result in read only mode"); return false; } m_checkQueueSpinLock.lock(); m_storeCheckQueue.push(HMCheckData(hostname, address, hostCheck, checkParams, checkResult)); m_checkQueueSpinLock.unlock(); lock_guard<mutex> lk(m_dataReadyMutex); m_dataReadyCond.notify_one(); return true; } bool HMStorageHost::getCheckResult(const string& hostname, const HMIPAddress& address, const HMDataHostCheck& hostCheck, const HMDataCheckParams& checkParams, HMDataCheckResult& checkResult) { HMCheckHeader header(hostname, address, hostCheck, checkParams); return getHostCheckResult(header, checkResult); } bool HMStorageHost::purgeCheckResult(const string& hostname, const HMIPAddress& address, const HMDataHostCheck& hostCheck, const HMDataCheckParams& checkParams) { HMCheckHeader header(hostname, address, hostCheck, checkParams); return removeHostCheckResult(header); } bool HMStorageHost::storeAuxInfo(const string& hostname, const HMIPAddress& address, const HMDataHostCheck& hostCheck, const HMDataCheckParams& checkParams, const HMAuxInfo& auxInfo) { if(m_readonly) { HMLog(HM_LOG_ERROR, "[STORE] Attempting to store aux result in read only mode"); return false; } m_auxQueueSpinLock.lock(); m_storeAuxQueue.push(move(HMAuxData(hostname, address, hostCheck, checkParams, auxInfo))); m_auxQueueSpinLock.unlock(); lock_guard<mutex> lk(m_dataReadyMutex); m_dataReadyCond.notify_one(); return true; } bool HMStorageHost::getAuxInfo(const string& hostname, const HMIPAddress& address, const HMDataHostCheck& hostCheck, const HMDataCheckParams& checkParams, HMAuxInfo& auxInfo) { HMCheckHeader header(hostname, address, hostCheck, checkParams); return getHostAuxInfo(header, auxInfo); } bool HMStorageHost::purgeAuxInfo(const string& hostname, const HMIPAddress& address, const HMDataHostCheck& hostCheck, const HMDataCheckParams& checkParams) { HMCheckHeader header(hostname, address, hostCheck, checkParams); return removeHostAuxInfo(header); } bool HMStorageHost::getDNS(const std::string& hostname, std::set<HMIPAddress>& ips) { return getDNSResult(hostname, ips); } bool HMStorageHost::updateCheckResultCache(HMCheckHeader& header, HMDataCheckResult& result) { (void)header; (void)result; return true; } bool HMStorageHost::updateAuxInfoCache(HMCheckHeader& header, HMAuxInfo& aux) { (void)header; (void)aux; return true; } void HMStorageHost::updateHostGroups(set<string>& hostGroups) { (void)hostGroups; return; } bool HMStorageHost::storeHostGroupCheckResult(const std::string& hostgroupname, std::vector<HMGroupCheckResult>& checkResult) { (void)hostgroupname; (void)checkResult; return true; } bool HMStorageHost::storeHostGroupAuxResult(const std::string& hostgroupname, std::vector<HMGroupAuxResult>& auxResult) { (void)hostgroupname; (void)auxResult; return true; } bool HMStorageHost::getGroupCheckResults(const string& groupName, bool noCache, bool onlyResolved, vector<HMGroupCheckResult>& results) { (void) noCache; (void) onlyResolved; return getGroupCheckResults(groupName, results); } bool HMStorageHost::getGroupCheckResults(const std::string& groupName, std::vector<HMGroupCheckResult>& results) { // assume we have the group info in the group map HMCheckHeader header; HMDataCheckResult result; auto group = m_hostGroupMap->find(groupName); if(group == m_hostGroupMap->end()) { HMLog(HM_LOG_ERROR, "Host group not found during check results lookup"); return false; } group->second.getHostCheck(header.m_hostCheck); group->second.getCheckParameters(header.m_checkParams); // now we need the list of hosts auto hosts = group->second.getHostList(); for(auto it = hosts->begin(); it != hosts->end(); ++it) { set<HMIPAddress> ips; if(!getDNSResult(*it, ips)) { continue; } for(auto ip = ips.begin(); ip != ips.end(); ++ip) { header.m_hostname = *it; header.m_address = *ip; if(getHostCheckResult(header, result)) { results.push_back(HMGroupCheckResult(header.m_hostname, header.m_address, result)); } } } return true; } bool HMStorageHost::getGroupAuxInfo(const string& groupName, bool noCache, bool onlyResolved, vector<HMGroupAuxResult>& results) { (void) noCache; (void) onlyResolved; // assume we have the group info in the group map HMCheckHeader header; HMAuxInfo result; auto group = m_hostGroupMap->find(groupName); if(group == m_hostGroupMap->end()) { HMLog(HM_LOG_ERROR, "Host group not found during check results lookup"); return false; } group->second.getHostCheck(header.m_hostCheck); group->second.getCheckParameters(header.m_checkParams); // now we need the list of hosts auto hosts = group->second.getHostList(); for(auto it = hosts->begin(); it != hosts->end(); ++it) { set<HMIPAddress> ips; if(!getDNSResult(*it, ips)) { continue; } for(auto ip = ips.begin(); ip != ips.end(); ++ip) { header.m_hostname = *it; header.m_address = *ip; if(getHostAuxInfo(header, result)) { results.push_back(HMGroupAuxResult(header.m_hostname, header.m_address, result)); } } } return true; } void HMStorageHost::removeName(const string& hostname) { vector<HMCheckHeader> checks; set<HMIPAddress> addresses; if(!getNameChecks(hostname, checks)) { HMLog(HM_LOG_ERROR, "Failed to fetch host checks for %s from backend", hostname.c_str()); } else { if(!removeNameChecks(hostname, checks)) { HMLog(HM_LOG_ERROR, "Failed to remove host checks for %s from backend", hostname.c_str()); } for(auto check = checks.begin(); check != checks.end(); ++check) { if(!removeHostCheckResult(*check)) { HMLog(HM_LOG_ERROR, "Failed to remove host check %s for %s from backend", check->m_hostCheck.getCheckInfo().c_str(), hostname.c_str()); } if(!removeHostAuxInfo(*check)) { HMLog(HM_LOG_ERROR, "Failed to aux info %s for %s from backend", check->m_hostCheck.getCheckInfo().c_str(), hostname.c_str()); } } } if(!getDNSResult(hostname, addresses)) { HMLog(HM_LOG_ERROR, "Failed to fetch DNS for %s from backend", hostname.c_str()); } if(!removeDNSResult(hostname, addresses)) { HMLog(HM_LOG_ERROR, "Failed to remove DNS for %s from backend", hostname.c_str()); } } bool HMStorageHost::commitHealthCheck() { m_checkQueueSpinLock.lock(); if(m_storeCheckQueue.size() == 0) { m_checkQueueSpinLock.unlock(); return false; } HMCheckData data = m_storeCheckQueue.front(); m_storeCheckQueue.pop(); m_checkQueueSpinLock.unlock(); storeHostCheckResult(data); set<HMIPAddress> addresses; if(getDNSResult(data.m_hostname, addresses)) { addresses.insert(data.m_address); } storeDNSResult(data.m_hostname, addresses); return true; } bool HMStorageHost::commitAuxInfo() { m_auxQueueSpinLock.lock(); if(m_storeAuxQueue.size() == 0) { m_auxQueueSpinLock.unlock(); return false; } HMAuxData data = move(m_storeAuxQueue.front()); m_storeAuxQueue.pop(); m_auxQueueSpinLock.unlock(); storeHostAuxInfo(data); set<HMIPAddress> addresses; if(getDNSResult(data.m_hostname, addresses)) { addresses.insert(data.m_address); } storeDNSResult(data.m_hostname, addresses); return true; }
29.699291
182
0.600583
[ "vector" ]
bcea874d320c15e9dbd8238acbefb325c776e91d
186,320
cpp
C++
src/RInput.cpp
chilingg/Redopera
a898eb269d5d3eba9ba5b14ef9b4209f615f4547
[ "MIT" ]
null
null
null
src/RInput.cpp
chilingg/Redopera
a898eb269d5d3eba9ba5b14ef9b4209f615f4547
[ "MIT" ]
null
null
null
src/RInput.cpp
chilingg/Redopera
a898eb269d5d3eba9ba5b14ef9b4209f615f4547
[ "MIT" ]
null
null
null
#include <RInput.h> #include <RWindow.h> #include <RDebug.h> #include <rsc/RFile.h> using namespace Redopera; RSignal<JoystickPresent> RInput::joyPresented; bool RInput::move_ = false; RPoint2 RInput::wheel_; std::set<Keys> RInput::keyUp_; std::set<Keys> RInput::keyDown_; std::set<Keys> RInput::keyRepeat_; std::set<MouseBtn> RInput::mouseUp_; std::set<MouseBtn> RInput::mouseDown_; std::vector<RInput::Gamepad> RInput::gamepad_; RText RInput::characters_; BtnAct RInput::toButtonAction(int action) { switch(action) { case GLFW_RELEASE: return BtnAct::RELEASE; case GLFW_PRESS: return BtnAct::PRESS; default: throw std::invalid_argument("Invalid value: " + std::to_string(action) + " to Enum ButtonAction!"); } } Keys RInput::toKey(int key) { switch(key) { case GLFW_KEY_UNKNOWN: return Keys::KEY_UNKNOWN; //Printble key case GLFW_KEY_SPACE: return Keys::KEY_SPACE; case GLFW_KEY_APOSTROPHE: return Keys::KEY_APOSTROPHE; case GLFW_KEY_COMMA: return Keys::KEY_COMMA; case GLFW_KEY_MINUS: return Keys::KEY_MINUS; case GLFW_KEY_PERIOD: return Keys::KEY_PERIOD; case GLFW_KEY_SLASH: return Keys::KEY_SLASH; case GLFW_KEY_0: return Keys::KEY_0; case GLFW_KEY_1: return Keys::KEY_1; case GLFW_KEY_2: return Keys::KEY_2; case GLFW_KEY_3: return Keys::KEY_3; case GLFW_KEY_4: return Keys::KEY_4; case GLFW_KEY_5: return Keys::KEY_5; case GLFW_KEY_6: return Keys::KEY_6; case GLFW_KEY_7: return Keys::KEY_7; case GLFW_KEY_8: return Keys::KEY_8; case GLFW_KEY_9: return Keys::KEY_9; case GLFW_KEY_SEMICOLON: return Keys::KEY_SEMICOLON; case GLFW_KEY_EQUAL: return Keys::KEY_EQUAL; case GLFW_KEY_A: return Keys::KEY_A; case GLFW_KEY_B: return Keys::KEY_B; case GLFW_KEY_C: return Keys::KEY_C; case GLFW_KEY_D: return Keys::KEY_D; case GLFW_KEY_E: return Keys::KEY_E; case GLFW_KEY_F: return Keys::KEY_F; case GLFW_KEY_G: return Keys::KEY_G; case GLFW_KEY_H: return Keys::KEY_H; case GLFW_KEY_I: return Keys::KEY_I; case GLFW_KEY_J: return Keys::KEY_J; case GLFW_KEY_K: return Keys::KEY_K; case GLFW_KEY_L: return Keys::KEY_L; case GLFW_KEY_M: return Keys::KEY_M; case GLFW_KEY_N: return Keys::KEY_N; case GLFW_KEY_O: return Keys::KEY_O; case GLFW_KEY_P: return Keys::KEY_P; case GLFW_KEY_Q: return Keys::KEY_Q; case GLFW_KEY_R: return Keys::KEY_R; case GLFW_KEY_S: return Keys::KEY_S; case GLFW_KEY_T: return Keys::KEY_T; case GLFW_KEY_U: return Keys::KEY_U; case GLFW_KEY_V: return Keys::KEY_V; case GLFW_KEY_W: return Keys::KEY_W; case GLFW_KEY_X: return Keys::KEY_X; case GLFW_KEY_Y: return Keys::KEY_Y; case GLFW_KEY_Z: return Keys::KEY_Z; case GLFW_KEY_LEFT_BRACKET: return Keys::KEY_LEFT_BRACKET; case GLFW_KEY_BACKSLASH: return Keys::KEY_BACKSLASH; case GLFW_KEY_RIGHT_BRACKET: return Keys::KEY_RIGHT_BRACKET; case GLFW_KEY_GRAVE_ACCENT: return Keys::KEY_GRAVE_ACCENT; case GLFW_KEY_WORLD_1: return Keys::KEY_WORLD_1; case GLFW_KEY_WORLD_2: return Keys::KEY_WORLD_2; //Function key case GLFW_KEY_ESCAPE: return Keys::KEY_ESCAPE; case GLFW_KEY_ENTER: return Keys::KEY_ENTER; case GLFW_KEY_TAB: return Keys::KEY_TAB; case GLFW_KEY_BACKSPACE: return Keys::KEY_BACKSPACE; case GLFW_KEY_INSERT: return Keys::KEY_INSERT; case GLFW_KEY_DELETE: return Keys::KEY_DELETE; case GLFW_KEY_RIGHT: return Keys::KEY_RIGHT; case GLFW_KEY_LEFT: return Keys::KEY_LEFT; case GLFW_KEY_DOWN: return Keys::KEY_DOWN; case GLFW_KEY_UP: return Keys::KEY_UP; case GLFW_KEY_PAGE_UP: return Keys::KEY_PAGE_UP; case GLFW_KEY_PAGE_DOWN: return Keys::KEY_PAGE_DOWN; case GLFW_KEY_HOME: return Keys::KEY_HOME; case GLFW_KEY_END: return Keys::KEY_END; case GLFW_KEY_CAPS_LOCK: return Keys::KEY_CAPS_LOCK; case GLFW_KEY_SCROLL_LOCK: return Keys::KEY_SCROLL_LOCK; case GLFW_KEY_NUM_LOCK: return Keys::KEY_NUM_LOCK; case GLFW_KEY_PRINT_SCREEN: return Keys::KEY_PRINT_SCREEN; case GLFW_KEY_PAUSE: return Keys::KEY_PAUSE; case GLFW_KEY_F1: return Keys::KEY_F1; case GLFW_KEY_F2: return Keys::KEY_F2; case GLFW_KEY_F3: return Keys::KEY_F3; case GLFW_KEY_F4: return Keys::KEY_F4; case GLFW_KEY_F5: return Keys::KEY_F5; case GLFW_KEY_F6: return Keys::KEY_F6; case GLFW_KEY_F7: return Keys::KEY_F7; case GLFW_KEY_F8: return Keys::KEY_F8; case GLFW_KEY_F9: return Keys::KEY_F9; case GLFW_KEY_F10: return Keys::KEY_F10; case GLFW_KEY_F11: return Keys::KEY_F11; case GLFW_KEY_F12: return Keys::KEY_F12; case GLFW_KEY_F13: return Keys::KEY_F13; case GLFW_KEY_F14: return Keys::KEY_F14; case GLFW_KEY_F15: return Keys::KEY_F15; case GLFW_KEY_F16: return Keys::KEY_F16; case GLFW_KEY_F17: return Keys::KEY_F17; case GLFW_KEY_F18: return Keys::KEY_F18; case GLFW_KEY_F19: return Keys::KEY_F19; case GLFW_KEY_F20: return Keys::KEY_F20; case GLFW_KEY_F21: return Keys::KEY_F21; case GLFW_KEY_F22: return Keys::KEY_F22; case GLFW_KEY_F23: return Keys::KEY_F23; case GLFW_KEY_F24: return Keys::KEY_F24; case GLFW_KEY_F25: return Keys::KEY_F25; case GLFW_KEY_KP_0: return Keys::KEY_KP_0; case GLFW_KEY_KP_1: return Keys::KEY_KP_1; case GLFW_KEY_KP_2: return Keys::KEY_KP_2; case GLFW_KEY_KP_3: return Keys::KEY_KP_3; case GLFW_KEY_KP_4: return Keys::KEY_KP_4; case GLFW_KEY_KP_5: return Keys::KEY_KP_5; case GLFW_KEY_KP_6: return Keys::KEY_KP_6; case GLFW_KEY_KP_7: return Keys::KEY_KP_7; case GLFW_KEY_KP_8: return Keys::KEY_KP_8; case GLFW_KEY_KP_9: return Keys::KEY_KP_9; case GLFW_KEY_KP_DECIMAL: return Keys::KEY_KP_DECIMAL; case GLFW_KEY_KP_DIVIDE: return Keys::KEY_KP_DIVIDE; case GLFW_KEY_KP_MULTIPLY: return Keys::KEY_KP_MULTIPLY; case GLFW_KEY_KP_SUBTRACT: return Keys::KEY_KP_SUBTRACT; case GLFW_KEY_KP_ADD: return Keys::KEY_KP_ADD; case GLFW_KEY_KP_ENTER: return Keys::KEY_KP_ENTER; case GLFW_KEY_KP_EQUAL: return Keys::KEY_KP_EQUAL; case GLFW_KEY_LEFT_SHIFT: return Keys::KEY_LEFT_SHIFT; case GLFW_KEY_LEFT_CONTROL: return Keys::KEY_LEFT_CONTROL; case GLFW_KEY_LEFT_ALT: return Keys::KEY_LEFT_ALT; case GLFW_KEY_LEFT_SUPER: return Keys::KEY_LEFT_SUPER; case GLFW_KEY_RIGHT_SHIFT: return Keys::KEY_RIGHT_SHIFT; case GLFW_KEY_RIGHT_CONTROL: return Keys::KEY_RIGHT_CONTROL; case GLFW_KEY_RIGHT_ALT: return Keys::KEY_RIGHT_ALT; case GLFW_KEY_RIGHT_SUPER: return Keys::KEY_RIGHT_SUPER; case GLFW_KEY_MENU: return Keys::KEY_MENU; default: return Keys::KEY_UNKNOWN; } } MouseBtn RInput::toMouseButtons(int button) { switch(button) { case GLFW_MOUSE_BUTTON_LEFT: return MouseBtn::LEFT; case GLFW_MOUSE_BUTTON_RIGHT: return MouseBtn::RIGHT; case GLFW_MOUSE_BUTTON_MIDDLE: return MouseBtn::MIDDLE; default: throw std::invalid_argument("Invalid value: " + std::to_string(button) + " to Enum MouseButtons!"); } } BtnAct RInput::status(Keys key) { return toButtonAction(glfwGetKey(RWindow::focusWindow()->getHandle(), static_cast<int>(key))); } BtnAct RInput::status(MouseBtn btn) { return toButtonAction(glfwGetMouseButton(RWindow::focusWindow()->getHandle(), static_cast<int>(btn))); } BtnAct RInput::status(GamepadBtn btn, unsigned player) { if (gamepad_.size() <= player) player = 0; return RInput::toButtonAction((gamepad_[player].status.buttons[static_cast<unsigned>(btn)])); } float RInput::status(GamepadAxes axis, unsigned player) { if (gamepad_.size() <= player) player = 0; return gamepad_[player].status.axes[static_cast<unsigned>(axis)]; } bool RInput::press(Keys key) { return keyDown_.count(key); } bool RInput::press(MouseBtn btn) { return mouseDown_.count(btn); } bool RInput::press(GamepadBtn btn, unsigned player) { if (gamepad_.size() <= player) return false; unsigned index = static_cast<unsigned>(btn); return gamepad_[player].status.buttons[index] && !gamepad_[player].preButtons[index]; } bool RInput::release(Keys key) { return keyUp_.count(key); } bool RInput::release(MouseBtn btn) { return mouseUp_.count(btn); } bool RInput::release(GamepadBtn btn, unsigned player) { if (gamepad_.size() <= player) return false; unsigned index = static_cast<unsigned>(btn); return !gamepad_[player].status.buttons[index] && gamepad_[player].preButtons[index]; } bool RInput::repeat(Keys key) { return keyRepeat_.count(key); } bool RInput::cursorMove() { return move_; } RPoint2 RInput::cursorPos() { double x, y; glfwGetCursorPos(RWindow::focusWindow()->getHandle(), &x, &y); RPoint2 pos(x, y); pos -= RWindow::focusWindow()->posOffset(); pos.setY(RWindow::focusWindow()->height() - pos.y()); return pos; } RPoint2 RInput::wheel() { return wheel_; } int RInput::gamepadCount() { return gamepad_.size() - 1; } bool RInput::anyKeyPress() { return !keyDown_.empty(); } bool RInput::anyMouseBtnPress() { return !mouseDown_.empty(); } const RText &RInput::charInput() { return characters_; } bool RInput::updateGamepadMappings(const char *path) { RFile file = RFile::load(path); if (!file.size) rPrError("Failed to load gamepad mappings file: " + std::string(path)); if(glfwUpdateGamepadMappings(reinterpret_cast<char*>(file.data.get())) == GLFW_FALSE) { rPrError("Failed to update gamepad mapping! In path: " + std::string(path) + '\n' + "To https://github.com/gabomdq/SDL_GameControllerDB download gamecontrollerdb.txt file."); rDebug << "Updata to default gameoad mapping is " << (updateGamepadMappings() ? "success." : "failed!"); return false; } else return true; } bool RInput::updateGamepadMappings() { // 加载手柄映射 std::string mappingCode = std::string() + RInput::gamepadMappingCode0 + RInput::gamepadMappingCode1 + RInput::gamepadMappingCode2; return glfwUpdateGamepadMappings(mappingCode.c_str()) == GLFW_TRUE; } void RInput::joystickPresentCallback(int jid, int event) { if(event == GLFW_CONNECTED && glfwJoystickIsGamepad(jid)) { RInput::gamepad_.emplace_back(jid); RInput::joyPresented.emit(JoystickPresent::CONNECTED); } else if(event == GLFW_DISCONNECTED) { auto it = std::find_if(RInput::gamepad_.begin(), RInput::gamepad_.end(), [jid](const Gamepad &g){ return g.jid == jid; }); RInput::gamepad_.erase(it); RInput::joyPresented.emit(JoystickPresent::DISCONNECTED); } } void RInput::updataInput() { move_ = false; wheel_.setPos(0, 0); keyUp_.clear(); mouseUp_.clear(); keyDown_.clear(); mouseDown_.clear(); keyRepeat_.clear(); characters_.clear(); for(auto &player : gamepad_) { std::swap(player.status.buttons, player.preButtons); glfwGetGamepadState(static_cast<int>(player.jid), &player.status); } } void RInput::keyUp(Keys key) { keyUp_.insert(key); } void RInput::keyDown(Keys key) { keyDown_.insert(key); } void RInput::keyRepeat(Keys key) { keyRepeat_.insert(key); } void RInput::mouseUp(MouseBtn btn) { mouseUp_.insert(btn); } void RInput::mouseDown(MouseBtn btn) { mouseDown_.insert(btn); } void RInput::mouseWheel(int x, int y) { wheel_.setPos(x, y); } void RInput::setCursorMove() { move_ = true; } void RInput::charInput(wchar_t c) { characters_ += c; } void RInput::enableGamepad() { gamepad_.emplace_back(0); // add empty gamepad updateGamepadMappings(); // 需手动检测一次手柄连接,检测之前已连接的手柄 for(unsigned i = GLFW_JOYSTICK_1; i <= GLFW_JOYSTICK_LAST; ++i) { if(glfwJoystickIsGamepad(i)) gamepad_.emplace_back(i); } // 手柄连接回调 glfwSetJoystickCallback(joystickPresentCallback); } RInput::Gamepad::Gamepad(int jid): jid(jid) { for(size_t i = 0; i <= GLFW_GAMEPAD_BUTTON_LAST; ++i) { status.buttons[i] = GLFW_RELEASE; preButtons[i] = GLFW_RELEASE; } for(size_t i = 0; i <= GLFW_GAMEPAD_AXIS_LAST; ++i) status.axes[i] = (i == GLFW_GAMEPAD_AXIS_LEFT_TRIGGER || i == GLFW_GAMEPAD_AXIS_RIGHT_TRIGGER) ? -1.f : 0.f; } RInput::Gamepad::Gamepad(const RInput::Gamepad &gamepad): Gamepad(gamepad.jid) { } const char *RInput::gamepadMappingCode0 = "# Game Controller DB for SDL in 2.0.9 format\n" "# Source: https://github.com/gabomdq/SDL_GameControllerDB\n" "# Windows\n" "03000000fa2d00000100000000000000,3DRUDDER,leftx:a0,lefty:a1,rightx:a5,righty:a2,platform:Windows,\n" "03000000c82d00002038000000000000,8bitdo,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b4,y:b3,platform:Windows,\n" "03000000022000000090000000000000,8Bitdo NES30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b4,y:b3,platform:Windows,\n" "03000000203800000900000000000000,8Bitdo NES30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b4,y:b3,platform:Windows,\n" "03000000c82d00000060000000000000,8Bitdo SF30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b4,y:b3,platform:Windows,\n" "03000000c82d00000061000000000000,8Bitdo SF30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b4,y:b3,platform:Windows,\n" "03000000102800000900000000000000,8Bitdo SFC30 GamePad,a:b1,b:b0,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b4,y:b3,platform:Windows,\n" "03000000c82d00003028000000000000,8Bitdo SFC30 GamePad,a:b1,b:b0,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b4,y:b3,platform:Windows,\n" "03000000a00500003232000000000000,8Bitdo Zero GamePad,a:b0,b:b1,back:b10,dpdown:+a2,dpleft:-a0,dpright:+a0,dpup:-a2,leftshoulder:b6,rightshoulder:b7,start:b11,x:b3,y:b4,platform:Windows,\n" "030000008f0e00001200000000000000,Acme GA-02,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b2,y:b3,platform:Windows,\n" "03000000fa190000f0ff000000000000,Acteck AGJ-3200,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,platform:Windows,\n" "03000000341a00003608000000000000,Afterglow PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,\n" "030000006f0e00000263000000000000,Afterglow PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,\n" "030000006f0e00001101000000000000,Afterglow PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,\n" "030000006f0e00001401000000000000,Afterglow PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,\n" "030000006f0e00001402000000000000,Afterglow PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,\n" "030000006f0e00001901000000000000,Afterglow PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,\n" "030000006f0e00001a01000000000000,Afterglow PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,\n" "03000000d62000001d57000000000000,Airflo PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,\n" "03000000d6200000e557000000000000,Batarang,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,\n" "03000000c01100001352000000000000,Battalife Joystick,a:b6,b:b7,back:b2,leftshoulder:b0,leftx:a0,lefty:a1,rightshoulder:b1,start:b3,x:b4,y:b5,platform:Windows,\n" "030000006f0e00003201000000000000,Battlefield 4 PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,\n" "03000000bc2000006012000000000000,Betop 2126F,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,platform:Windows,\n" "03000000bc2000000055000000000000,Betop BFM Gamepad,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b3,y:b4,platform:Windows,\n" "03000000bc2000006312000000000000,Betop Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,platform:Windows,\n" "03000000bc2000006321000000000000,BETOP CONTROLLER,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,platform:Windows,\n" "03000000bc2000006412000000000000,Betop Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,platform:Windows,\n" "03000000c01100000555000000000000,Betop Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,platform:Windows,\n" "03000000c01100000655000000000000,Betop Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,platform:Windows,\n" "03000000790000000700000000000000,Betop Gamepad,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a4,start:b9,x:b3,y:b0,platform:Windows,\n" "03000000808300000300000000000000,Betop Gamepad,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a4,start:b9,x:b3,y:b0,platform:Windows,\n" "030000006b1400000055000000000000,Bigben PS3 Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,platform:Windows,\n" "030000006b1400000103000000000000,Bigben PS3 Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b2,platform:Windows,\n" "0300000066f700000500000000000000,BrutalLegendTest,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b0,y:b3,platform:Windows,\n" "03000000d81d00000b00000000000000,BUFFALO BSGP1601 Series ,a:b5,b:b3,back:b12,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b8,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b9,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b13,x:b4,y:b2,platform:Windows,\n" "03000000e82000006058000000000000,Cideko AK08b,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,platform:Windows,\n" "030000005e0400008e02000000000000,Controller (XBOX 360 For Windows),a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b8,lefttrigger:+a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:-a2,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Windows,\n" "030000005e040000a102000000000000,Controller (Xbox 360 Wireless Receiver for Windows),a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b8,lefttrigger:+a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:-a2,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Windows,\n" "030000005e040000ff02000000000000,Controller (Xbox One For Windows) - Wired,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b8,lefttrigger:+a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:-a2,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Windows,\n" "030000005e040000ea02000000000000,Controller (Xbox One For Windows) - Wireless,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b8,lefttrigger:+a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:-a2,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Windows,\n" "03000000260900008888000000000000,Cyber Gadget GameCube Controller,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b6,righttrigger:a4,rightx:a2,righty:a3~,start:b7,x:b2,y:b3,platform:Windows,\n" "03000000a306000022f6000000000000,Cyborg V.3 Rumble Pad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:+a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:-a3,rightx:a2,righty:a4,start:b9,x:b0,y:b3,platform:Windows,\n" "03000000451300000830000000000000,Defender Game Racer X7,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,platform:Windows,\n" "03000000791d00000103000000000000,Dual Box WII,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b6,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:b5,rightx:a2,righty:a3,start:b9,x:b3,y:b0,platform:Windows,\n" "03000000bd12000002e0000000000000,Dual USB Vibration Joystick,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b9,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b10,righttrigger:b5,rightx:a3,righty:a2,start:b11,x:b3,y:b0,platform:Windows,\n" "030000006f0e00003001000000000000,EA SPORTS PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,\n" "03000000b80500000410000000000000,Elecom Gamepad,a:b2,b:b3,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b1,platform:Windows,\n" "03000000b80500000610000000000000,Elecom Gamepad,a:b2,b:b3,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b1,platform:Windows,\n" "030000008f0e00000f31000000000000,EXEQ,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b2,platform:Windows,\n" "03000000341a00000108000000000000,EXEQ RF USB Gamepad 8206,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b8,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,platform:Windows,\n" "03000000852100000201000000000000,FF-GP1,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,\n" "030000000d0f00008500000000000000,Fighting Commander 2016 PS3,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,\n" "030000000d0f00008400000000000000,Fighting Commander 5,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Windows,\n" "030000000d0f00008700000000000000,Fighting Stick mini 4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,platform:Windows,\n" "030000000d0f00008800000000000000,Fighting Stick mini 4,a:b1,b:b2,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b8,x:b0,y:b3,platform:Windows,\n" "030000000d0f00002700000000000000,FIGHTING STICK V3,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,platform:Windows,\n" "78696e70757403000000000000000000,Fightstick TES,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,lefttrigger:a2,rightshoulder:b5,righttrigger:a5,start:b7,x:b2,y:b3,platform:Windows,\n" "03000000790000000600000000000000,G-Shark GS-GP702,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a4,start:b9,x:b3,y:b0,platform:Windows,\n" "03000000790000002201000000000000,Game Controller for PC,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,platform:Windows,\n" "0300000066f700000100000000000000,Game VIB Joystick,a:b2,b:b3,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b8,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:b7,rightx:a3,righty:a2,start:b11,x:b0,y:b1,platform:Windows,\n" "03000000260900002625000000000000,Gamecube Controller,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b6,lefttrigger:a4,leftx:a0,lefty:a1,righttrigger:a5,rightx:a2,righty:a3,start:b7,x:b2,y:b3,platform:Windows,\n" "030000008f0e00000d31000000000000,GAMEPAD 3 TURBO,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,\n" "03000000280400000140000000000000,GamePad Pro USB,a:b1,b:b2,back:b8,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,platform:Windows,\n" "03000000ac0500003d03000000000000,GameSir,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b3,y:b4,platform:Windows,\n" "03000000ac0500004d04000000000000,GameSir,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b3,y:b4,platform:Windows,\n" "03000000ffff00000000000000000000,GameStop Gamepad,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,platform:Windows,\n" "030000006f0e00000102000000007801,GameStop Xbox 360 Wired Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b8,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Windows,\n" "030000008305000009a0000000000000,Genius,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,platform:Windows,\n" "030000008305000031b0000000000000,Genius Maxfire Blaze 3,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,platform:Windows,\n" "03000000451300000010000000000000,Genius Maxfire Grandias 12,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,platform:Windows,\n" "030000005c1a00003330000000000000,Genius MaxFire Grandias 12V,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b7,leftx:a0,lefty:a1,rightshoulder:b4,rightstick:b11,righttrigger:b5,rightx:a3,righty:a2,start:b9,x:b2,y:b3,platform:Windows,\n" "03000000300f00000b01000000000000,GGE909 Recoil Pad,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b3,y:b0,platform:Windows,\n" "03000000f0250000c283000000000000,Gioteck,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,platform:Windows,\n" "03000000f025000021c1000000000000,Gioteck PS3 Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,platform:Windows,\n" "03000000f0250000c383000000000000,Gioteck VX2 Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,platform:Windows,\n" "03000000f0250000c483000000000000,Gioteck VX2 Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,platform:Windows,\n" "030000007d0400000540000000000000,Gravis Eliminator GamePad Pro,a:b1,b:b2,back:b8,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,platform:Windows,\n" "03000000341a00000302000000000000,Hama Scorpad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,\n" "030000000d0f00004900000000000000,Hatsune Miku Sho Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,\n" "03000000d81400000862000000000000,HitBox Edition Cthulhu+,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b5,lefttrigger:b4,rightshoulder:b7,righttrigger:b6,start:b9,x:b0,y:b3,platform:Windows,\n" "03000000632500002605000000000000,HJD-X,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b3,y:b4,platform:Windows,\n" "030000000d0f00005f00000000000000,Hori Fighting Commander 4 (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,\n" "030000000d0f00005e00000000000000,Hori Fighting Commander 4 (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Windows,\n" "030000000d0f00004000000000000000,Hori Fighting Stick Mini 3,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b5,lefttrigger:b4,rightshoulder:b7,righttrigger:b6,start:b9,x:b0,y:b3,platform:Windows,\n" "030000000d0f00005400000000000000,Hori Pad 3,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,\n" "030000000d0f00000900000000000000,Hori Pad 3 Turbo,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,\n" "030000000d0f00004d00000000000000,Hori Pad A,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,\n" "030000000d0f00009200000000000000,Hori Pokken Tournament DX Pro Pad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,platform:Windows,\n" "030000000d0f0000c100000000000000,Horipad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,\n" "030000000d0f00006e00000000000000,HORIPAD 4 (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,\n" "030000000d0f00006600000000000000,HORIPAD 4 (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Windows,\n" "030000000d0f0000ee00000000000000,HORIPAD mini4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Windows,\n" "03000000250900000017000000000000,HRAP2 on PS/SS/N64 Joypad to USB BOX,a:b2,b:b1,back:b9,leftshoulder:b5,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:b6,start:b8,x:b3,y:b0,platform:Windows,\n" "030000008f0e00001330000000000000,HuiJia SNES Controller,a:b2,b:b1,back:b8,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b6,rightshoulder:b7,start:b9,x:b3,y:b0,platform:Windows,\n" "03000000d81d00000f00000000000000,iBUFFALO BSGP1204 Series,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a2,righty:a3,start:b9,x:b3,y:b0,platform:Windows,\n" "03000000d81d00001000000000000000,iBUFFALO BSGP1204P Series,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a2,righty:a3,start:b9,x:b3,y:b0,platform:Windows,\n" "03000000830500006020000000000000,iBuffalo SNES Controller,a:b1,b:b0,back:b6,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b4,rightshoulder:b5,start:b7,x:b3,y:b2,platform:Windows,\n" "03000000b50700001403000000000000,Impact Black,a:b2,b:b3,back:b8,leftshoulder:b4,leftstick:b10,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b0,y:b1,platform:Windows,\n" "030000006f0e00002401000000000000,INJUSTICE FightStick PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,platform:Windows,\n" "03000000ac0500002c02000000000000,IPEGA,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b8,leftstick:b13,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b9,rightstick:b14,righttrigger:b7,rightx:a3,righty:a4,start:b11,x:b3,y:b4,platform:Windows,\n" "03000000491900000204000000000000,Ipega PG-9023,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b3,y:b4,platform:Windows,\n" "03000000491900000304000000000000,Ipega PG-9087 - Bluetooth Gamepad,+righty:+a5,-righty:-a4,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,start:b11,x:b3,y:b4,platform:Windows,\n" "030000006e0500000a20000000000000,JC-DUX60 ELECOM MMO Gamepad,a:b2,b:b3,back:b17,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b8,leftstick:b14,lefttrigger:b12,leftx:a0,lefty:a1,rightshoulder:b11,rightstick:b15,righttrigger:b13,rightx:a3,righty:a4,start:b20,x:b0,y:b1,platform:Windows,\n" "030000006e0500000520000000000000,JC-P301U,a:b2,b:b3,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b8,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:b7,rightx:a2,righty:a3,start:b11,x:b0,y:b1,platform:Windows,\n" "030000006e0500000320000000000000,JC-U3613M (DInput),a:b2,b:b3,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b8,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:b7,rightx:a2,righty:a3,start:b11,x:b0,y:b1,platform:Windows,\n" "030000006e0500000720000000000000,JC-W01U,a:b2,b:b3,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b1,platform:Windows,\n" "030000007e0500000620000000000000,Joy-Con (L),+leftx:h0.2,+lefty:h0.4,-leftx:h0.8,-lefty:h0.1,a:b0,b:b1,back:b13,leftshoulder:b4,leftstick:b10,rightshoulder:b5,start:b8,x:b2,y:b3,platform:Windows,\n" "030000007e0500000620000001000000,Joy-Con (L),+leftx:h0.2,+lefty:h0.4,-leftx:h0.8,-lefty:h0.1,a:b0,b:b1,back:b13,leftshoulder:b4,leftstick:b10,rightshoulder:b5,start:b8,x:b2,y:b3,platform:Windows,\n" "030000007e0500000720000000000000,Joy-Con (R),+leftx:h0.2,+lefty:h0.4,-leftx:h0.8,-lefty:h0.1,a:b0,b:b1,back:b12,leftshoulder:b4,leftstick:b11,rightshoulder:b5,start:b9,x:b2,y:b3,platform:Windows,\n" "030000007e0500000720000001000000,Joy-Con (R),+leftx:h0.2,+lefty:h0.4,-leftx:h0.8,-lefty:h0.1,a:b0,b:b1,back:b12,leftshoulder:b4,leftstick:b11,rightshoulder:b5,start:b9,x:b2,y:b3,platform:Windows,\n" "03000000bd12000003c0000000000000,JY-P70UR,a:b1,b:b0,back:b5,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b7,leftx:a0,lefty:a1,rightshoulder:b8,rightstick:b11,righttrigger:b9,rightx:a3,righty:a2,start:b4,x:b3,y:b2,platform:Windows,\n" "03000000790000000200000000000000,King PS3 Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a4,start:b9,x:b3,y:b0,platform:Windows,\n" "030000006d040000d1ca000000000000,Logitech ChillStream,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,\n" "030000006d040000d2ca000000000000,Logitech Cordless Precision,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,\n" "030000006d04000011c2000000000000,Logitech Cordless Wingman,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b9,leftstick:b5,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b2,righttrigger:b7,rightx:a3,righty:a4,x:b4,platform:Windows,\n" "030000006d04000016c2000000000000,Logitech Dual Action,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,\n" "030000006d04000018c2000000000000,Logitech F510 Gamepad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,\n" "030000006d04000019c2000000000000,Logitech F710 Gamepad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,\n" "03000000380700006652000000000000,Mad Catz C.T.R.L.R,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a3,righty:a4,start:b9,x:b0,y:b3,platform:Windows,\n" "03000000380700005032000000000000,Mad Catz FightPad PRO (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,\n" "03000000380700005082000000000000,Mad Catz FightPad PRO (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Windows,\n" "03000000380700008433000000000000,Mad Catz FightStick TE S+ (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,\n" "03000000380700008483000000000000,Mad Catz FightStick TE S+ (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Windows,\n" "03000000380700008134000000000000,Mad Catz FightStick TE2+ PS3,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b7,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b4,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,\n" "03000000380700008184000000000000,Mad Catz FightStick TE2+ PS4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b5,leftstick:b10,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b4,rightstick:b11,righttrigger:b7,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Windows,\n" "03000000380700006252000000000000,Mad Catz Micro C.T.R.L.R,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a3,righty:a4,start:b9,x:b0,y:b3,platform:Windows,\n" "03000000380700008034000000000000,Mad Catz TE2 PS3 Fightstick,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,\n" "03000000380700008084000000000000,Mad Catz TE2 PS4 Fightstick,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Windows,\n" "03000000380700008532000000000000,Madcatz Arcade Fightstick TE S PS3,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,\n" "03000000380700003888000000000000,Madcatz Arcade Fightstick TE S+ PS3,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,\n" "03000000380700001888000000000000,MadCatz SFIV FightStick PS3,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b5,lefttrigger:b7,leftx:a0,lefty:a1,rightshoulder:b4,righttrigger:b6,rightx:a2,righty:a3,start:b9,x:b2,y:b3,platform:Windows,\n" "03000000380700008081000000000000,MADCATZ SFV Arcade FightStick Alpha PS4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Windows,\n" "030000002a0600001024000000000000,Matricom,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a3,righty:a4,start:b9,x:b2,y:b3,platform:Windows,\n" "03000000250900000128000000000000,Mayflash Arcade Stick,a:b1,b:b2,back:b8,leftshoulder:b0,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b3,righttrigger:b7,start:b9,x:b5,y:b6,platform:Windows,\n" "03000000790000004418000000000000,Mayflash GameCube Controller,a:b1,b:b2,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:a4,rightx:a5,righty:a2,start:b9,x:b0,y:b3,platform:Windows,\n" "03000000790000004318000000000000,Mayflash GameCube Controller Adapter,a:b1,b:b2,back:b0,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b0,leftshoulder:b4,leftstick:b0,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b0,righttrigger:a4,rightx:a5,righty:a2,start:b9,x:b0,y:b3,platform:Windows,\n" "030000008f0e00001030000000000000,Mayflash USB Adapter for original Sega Saturn controller,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,lefttrigger:b5,rightshoulder:b2,righttrigger:b7,start:b9,x:b3,y:b4,platform:Windows,\n" "0300000025090000e803000000000000,Mayflash Wii Classic Controller,a:b1,b:b0,back:b8,dpdown:b13,dpleft:b12,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b2,platform:Windows,\n" "03000000790000000018000000000000,Mayflash WiiU Pro Game Controller Adapter (DInput),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,\n" "03000000380700006382000000000000,MLG GamePad PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,\n" "03000000efbe0000edfe000000000000,Monect Virtual Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a5,rightx:a3,righty:a4,start:b9,x:b3,y:b0,platform:Windows,\n" "03000000250900006688000000000000,MP-8866 Super Dual Box,a:b2,b:b1,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a2,righty:a3,start:b8,x:b3,y:b0,platform:Windows,\n" "030000001008000001e5000000000000,NEXT SNES Controller,a:b2,b:b1,back:b8,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b4,rightshoulder:b6,start:b9,x:b3,y:b0,platform:Windows,\n" "03000000152000000182000000000000,NGDS,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a3,righty:a4,start:b9,x:b3,y:b0,platform:Windows,\n" "03000000bd12000015d0000000000000,Nintendo Retrolink USB Super SNES Classic Controller,a:b2,b:b1,back:b8,leftshoulder:b4,leftx:a0,lefty:a1,rightshoulder:b5,start:b9,x:b3,y:b0,platform:Windows,\n" "030000007e0500000920000000000000,Nintendo Switch Pro Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,platform:Windows,\n" "030000000d0500000308000000000000,Nostromo N45,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b9,leftshoulder:b4,leftstick:b12,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b10,x:b2,y:b3,platform:Windows,\n" "03000000550900001472000000000000,NVIDIA Controller v01.04,a:b11,b:b10,back:b13,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b7,leftstick:b5,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b4,righttrigger:a5,rightx:a3,righty:a6,start:b3,x:b9,y:b8,platform:Windows,\n" "030000004b120000014d000000000000,NYKO AIRFLO,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:a3,leftstick:a0,lefttrigger:b6,rightshoulder:b5,rightstick:a2,righttrigger:b7,start:b9,x:b2,y:b3,platform:Windows,\n" "03000000782300000a10000000000000,Onlive Wireless Controller,a:b15,b:b14,back:b7,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b5,leftshoulder:b11,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a3,righty:a4,start:b6,x:b13,y:b12,platform:Windows,\n" "03000000d62000006d57000000000000,OPP PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,\n" "030000006b14000001a1000000000000,Orange Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a4,rightx:a5,righty:a2,start:b9,x:b2,y:b3,platform:Windows,\n" "03000000362800000100000000000000,OUYA Game Controller,a:b0,b:b3,dpdown:b9,dpleft:b10,dpright:b11,dpup:b8,guide:b14,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:b13,rightx:a3,righty:a4,x:b1,y:b2,platform:Windows,\n" "03000000120c0000f60e000000000000,P4 Wired Gamepad,a:b1,b:b2,back:b12,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b5,lefttrigger:b7,rightshoulder:b4,righttrigger:b6,start:b9,x:b0,y:b3,platform:Windows,\n" "030000008f0e00000300000000000000,Piranha xtreme,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a3,righty:a2,start:b9,x:b3,y:b0,platform:Windows,\n" "030000004c050000da0c000000000000,PlayStation Classic Controller,a:b2,b:b1,back:b8,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b6,lefttrigger:b4,rightshoulder:b7,righttrigger:b5,start:b9,x:b3,y:b0,platform:Windows,\n" "03000000d62000006dca000000000000,PowerA Pro Ex,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,\n" "03000000d62000009557000000000000,Pro Elite PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,\n" "03000000d62000009f31000000000000,Pro Ex mini PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,\n" "03000000d6200000c757000000000000,Pro Ex mini PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,\n" "03000000632500002306000000000000,PS Controller,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a2,righty:a3,start:b11,x:b3,y:b4,platform:Windows,\n" "03000000e30500009605000000000000,PS to USB convert cable,a:b2,b:b1,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a2,righty:a3,start:b8,x:b3,y:b0,platform:Windows,\n" "03000000100800000100000000000000,PS1 Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a3,righty:a2,start:b9,x:b3,y:b0,platform:Windows,\n" "030000008f0e00007530000000000000,PS1 Controller,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b1,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,\n" "03000000100800000300000000000000,PS2 Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a4,righty:a2,start:b9,x:b3,y:b0,platform:Windows,\n" "03000000250900008888000000000000,PS2 Controller,a:b2,b:b1,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a2,righty:a3,start:b8,x:b3,y:b0,platform:Windows,\n" "03000000666600006706000000000000,PS2 Controller,a:b2,b:b1,back:b8,dpdown:b14,dpleft:b15,dpright:b13,dpup:b12,leftshoulder:b6,leftstick:b9,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b10,righttrigger:b5,rightx:a2,righty:a3,start:b11,x:b3,y:b0,platform:Windows,\n" "030000006b1400000303000000000000,PS2 Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,platform:Windows,\n" "030000009d0d00001330000000000000,PS2 Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,platform:Windows,\n" "03000000250900000500000000000000,PS3 Controller,a:b2,b:b1,back:b9,dpdown:h0.8,dpleft:h0.4,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a2,righty:a3,start:b8,x:b0,y:b3,platform:Windows,\n" "030000004c0500006802000000000000,PS3 Controller,a:b2,b:b1,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b6,leftstick:b10,lefttrigger:a3~,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:a4~,rightx:a2,righty:a5,start:b8,x:b3,y:b0,platform:Windows,\n" "03000000632500007505000000000000,PS3 Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,platform:Windows,\n" "03000000888800000803000000000000,PS3 Controller,a:b2,b:b1,back:b8,dpdown:h0.8,dpleft:h0.4,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b9,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:b7,rightx:a3,righty:a4,start:b11,x:b0,y:b3,platform:Windows,\n" "030000008f0e00001431000000000000,PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,\n" "030000003807000056a8000000000000,PS3 RF pad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,\n" "03000000100000008200000000000000,PS360+ v1.66,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,leftx:h0.4,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,platform:Windows,\n" "030000004c050000a00b000000000000,PS4 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Windows,\n" "030000004c050000c405000000000000,PS4 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Windows,\n" "030000004c050000cc09000000000000,PS4 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Windows,\n" "03000000300f00000011000000000000,QanBa Arcade JoyStick 1008,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,start:b10,x:b0,y:b3,platform:Windows,\n" "03000000300f00001611000000000000,QanBa Arcade JoyStick 4018,a:b1,b:b2,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b9,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b8,x:b0,y:b3,platform:Windows,\n" "03000000222c00000020000000000000,QANBA DRONE ARCADE JOYSTICK,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:a3,rightshoulder:b5,righttrigger:a4,start:b9,x:b0,y:b3,platform:Windows,\n" "03000000300f00001210000000000000,QanBa Joystick Plus,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,rightshoulder:b5,start:b9,x:b2,y:b3,platform:Windows,\n" "03000000341a00000104000000000000,QanBa Joystick Q4RAF,a:b5,b:b6,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b0,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b3,righttrigger:b7,start:b9,x:b1,y:b2,platform:Windows,\n" "03000000222c00000223000000000000,Qanba Obsidian Arcade Joystick PS3 Mode,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,\n" "03000000222c00000023000000000000,Qanba Obsidian Arcade Joystick PS4 Mode,a:b1,b:b2,back:b13,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Windows,\n" "03000000321500000003000000000000,Razer Hydra,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b8,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:a2,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Windows,\n" "03000000321500000204000000000000,Razer Panthera (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,\n" "03000000321500000104000000000000,Razer Panthera (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Windows,\n" "030000000d0f00001100000000000000,REAL ARCADE PRO.3,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,rightshoulder:b5,rightstick:b11,righttrigger:b7,start:b9,x:b0,y:b3,platform:Windows,\n" "030000000d0f00006a00000000000000,Real Arcade Pro.4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Windows,\n" "030000000d0f00006b00000000000000,Real Arcade Pro.4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,\n" "030000000d0f00008a00000000000000,Real Arcade Pro.4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Windows,\n" "030000000d0f00008b00000000000000,Real Arcade Pro.4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,\n" "030000000d0f00007000000000000000,REAL ARCADE PRO.4 VLX,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,rightshoulder:b5,rightstick:b11,righttrigger:b7,start:b9,x:b0,y:b3,platform:Windows,\n" "030000000d0f00002200000000000000,REAL ARCADE Pro.V3,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,\n" "030000000d0f00005b00000000000000,Real Arcade Pro.V4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Windows,\n" "030000000d0f00005c00000000000000,Real Arcade Pro.V4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,\n" "03000000790000001100000000000000,Retrolink SNES Controller,a:b2,b:b1,back:b8,dpdown:+a4,dpleft:-a3,dpright:+a3,dpup:-a4,leftshoulder:b4,rightshoulder:b5,start:b9,x:b3,y:b0,platform:Windows,\n" "0300000000f000000300000000000000,RetroUSB.com RetroPad,a:b1,b:b5,back:b2,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b3,x:b0,y:b4,platform:Windows,\n" "0300000000f00000f100000000000000,RetroUSB.com Super RetroPort,a:b1,b:b5,back:b2,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b3,x:b0,y:b4,platform:Windows,\n" "030000006b140000010d000000000000,Revolution Pro Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Windows,\n" "030000006b140000020d000000000000,Revolution Pro Controller 2(1/2),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Windows,\n" "030000006f0e00001e01000000000000,Rock Candy PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,\n" "030000006f0e00002801000000000000,Rock Candy PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,\n" "030000006f0e00002f01000000000000,Rock Candy PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,\n" "030000004f04000003d0000000000000,run'n'drive,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b7,leftshoulder:a3,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:a4,rightstick:b11,righttrigger:b5,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Windows,\n" "03000000a30600001af5000000000000,Saitek Cyborg,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a3,righty:a4,start:b9,x:b0,y:b3,platform:Windows,\n"; const char *RInput::gamepadMappingCode1 = "03000000a306000023f6000000000000,Saitek Cyborg V.1 Game pad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a4,start:b9,x:b0,y:b3,platform:Windows,\n" "03000000300f00001201000000000000,Saitek Dual Analog Pad,a:b2,b:b3,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b0,y:b1,platform:Windows,\n" "03000000a30600000701000000000000,Saitek P220,a:b2,b:b3,back:b4,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b6,rightshoulder:b7,start:b5,x:b0,y:b1,platform:Windows,\n" "03000000a30600000cff000000000000,Saitek P2500 Force Rumble Pad,a:b2,b:b3,back:b11,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b8,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:b7,rightx:a2,righty:a3,x:b0,y:b1,platform:Windows,\n" "03000000a30600000c04000000000000,Saitek P2900,a:b1,b:b2,back:b12,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b0,y:b3,platform:Windows,\n" "03000000300f00001001000000000000,Saitek P480 Rumble Pad,a:b2,b:b3,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b0,y:b1,platform:Windows,\n" "03000000a30600000b04000000000000,Saitek P990,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b0,y:b3,platform:Windows,\n" "03000000a30600000b04000000010000,Saitek P990 Dual Analog Pad,a:b1,b:b2,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b8,x:b0,y:b3,platform:Windows,\n" "03000000a30600002106000000000000,Saitek PS1000,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a4,start:b9,x:b0,y:b3,platform:Windows,\n" "03000000a306000020f6000000000000,Saitek PS2700,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a4,start:b9,x:b0,y:b3,platform:Windows,\n" "03000000300f00001101000000000000,Saitek Rumble Pad,a:b2,b:b3,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b10,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b0,y:b1,platform:Windows,\n" "0300000000050000289b000000000000,Saturn_Adapter_2.0,a:b1,b:b2,leftshoulder:b6,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:b5,start:b9,x:b0,y:b3,platform:Windows,\n" "030000009b2800000500000000000000,Saturn_Adapter_2.0,a:b1,b:b2,leftshoulder:b6,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:b5,start:b9,x:b0,y:b3,platform:Windows,\n" "030000005e0400008e02000000007801,ShanWan PS3/PC Wired GamePad,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b8,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Windows,\n" "03000000341a00000208000000000000,SL-6555-SBK,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b8,lefttrigger:-a4,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:a4,rightx:a3,righty:a2,start:b7,x:b2,y:b3,platform:Windows,\n" "03000000341a00000908000000000000,SL-6566,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,platform:Windows,\n" "030000008f0e00000800000000000000,SpeedLink Strike FX,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,platform:Windows,\n" "03000000c01100000591000000000000,Speedlink Torid,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,platform:Windows,\n" "03000000110100001914000000000000,SteelSeries,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftstick:b13,lefttrigger:b6,leftx:a0,lefty:a1,rightstick:b14,righttrigger:b7,rightx:a3,righty:a4,start:b11,x:b3,y:b4,platform:Windows,\n" "03000000381000001814000000000000,SteelSeries Stratus XL,a:b0,b:b1,back:b18,dpdown:b13,dpleft:b14,dpright:b15,dpup:b12,guide:b19,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b2,y:b3,platform:Windows,\n" "03000000790000001c18000000000000,STK-7024X,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b3,y:b4,platform:Windows,\n" "03000000ff1100003133000000000000,SVEN X-PAD,a:b2,b:b3,back:b4,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:b9,rightx:a2,righty:a4,start:b5,x:b0,y:b1,platform:Windows,\n" "03000000d620000011a7000000000000,Switch,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,\n" "030000004f04000007d0000000000000,T Mini Wireless,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,\n" "030000004f0400000ab1000000000000,T.16000M,a:b0,b:b1,back:b12,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b11,leftshoulder:b4,lefttrigger:b9,leftx:a0,lefty:a1,rightshoulder:b6,righttrigger:b7,start:b10,x:b2,y:b3,platform:Windows,\n" "03000000fa1900000706000000000000,Team 5,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,platform:Windows,\n" "03000000b50700001203000000000000,Techmobility X6-38V,a:b2,b:b3,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b0,y:b1,platform:Windows,\n" "030000004f04000015b3000000000000,Thrustmaster Dual Analog 4,a:b0,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b1,y:b3,platform:Windows,\n" "030000004f04000023b3000000000000,Thrustmaster Dual Trigger 3-in-1,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Windows,\n" "030000004f04000000b3000000000000,Thrustmaster Firestorm Dual Power,a:b0,b:b2,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b11,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b12,righttrigger:b7,rightx:a2,righty:a3,start:b10,x:b1,y:b3,platform:Windows,\n" "030000004f04000004b3000000000000,Thrustmaster Firestorm Dual Power 3,a:b0,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b1,y:b3,platform:Windows,\n" "03000000666600000488000000000000,TigerGame PS/PS2 Game Controller Adapter,a:b2,b:b1,back:b9,dpdown:b14,dpleft:b15,dpright:b13,dpup:b12,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a2,righty:a3,start:b8,x:b3,y:b0,platform:Windows,\n" "03000000d62000006000000000000000,Tournament PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,\n" "030000005f140000c501000000000000,Trust Gamepad,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,platform:Windows,\n" "03000000b80500000210000000000000,Trust Gamepad,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,platform:Windows,\n" "030000004f04000087b6000000000000,TWCS Throttle,dpdown:b8,dpleft:b9,dpright:b7,dpup:b6,leftstick:b5,lefttrigger:-a5,leftx:a0,lefty:a1,righttrigger:+a5,platform:Windows,\n" "03000000d90400000200000000000000,TwinShock PS2,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a3,righty:a2,start:b9,x:b3,y:b0,platform:Windows,\n" "03000000101c0000171c000000000000,uRage Gamepad,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,platform:Windows,\n" "03000000300f00000701000000000000,USB 4-Axis 12-Button Gamepad,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b3,y:b0,platform:Windows,\n" "03000000341a00002308000000000000,USB gamepad,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,platform:Windows,\n" "030000005509000000b4000000000000,USB gamepad,a:b10,b:b11,back:b5,dpdown:b1,dpleft:b2,dpright:b3,dpup:b0,guide:b14,leftshoulder:b8,leftstick:b6,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b9,rightstick:b7,righttrigger:a5,rightx:a2,righty:a3,start:b4,x:b12,y:b13,platform:Windows,\n" "030000006b1400000203000000000000,USB gamepad,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,platform:Windows,\n" "03000000790000000a00000000000000,USB gamepad,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a4,start:b9,x:b3,y:b0,platform:Windows,\n" "03000000f0250000c183000000000000,USB gamepad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,\n" "03000000ff1100004133000000000000,USB gamepad,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a4,righty:a2,start:b9,x:b3,y:b0,platform:Windows,\n" "03000000632500002305000000000000,USB Vibration Joystick (BM),a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,platform:Windows,\n" "03000000790000001b18000000000000,Venom Arcade Joystick,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,platform:Windows,\n" "030000005e0400000a0b000000000000,Xbox Adaptive Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b8,lefttrigger:+a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:-a2,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Windows,\n" "03000000341a00000608000000000000,Xeox,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,platform:Windows,\n" "03000000450c00002043000000000000,XEOX Gamepad SL-6556-BK,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,platform:Windows,\n" "03000000172700004431000000000000,XiaoMi Game Controller,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b20,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a7,rightx:a2,righty:a5,start:b11,x:b3,y:b4,platform:Windows,\n" "03000000786901006e70000000000000,XInput Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b8,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Windows,\n" "xinput,XInput Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b8,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Windows,\n" "03000000790000004f18000000000000,ZD-T Android,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b3,y:b4,platform:Windows,\n" "# Mac OS X\n" "030000008f0e00000300000009010000,2In1 USB Joystick,+leftx:h0.2,+lefty:h0.4,-leftx:h0.8,-lefty:h0.1,a:b2,b:b1,back:b8,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,platform:Mac OS X,\n" "03000000022000000090000001000000,8Bitdo NES30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a2,righty:a3,start:b11,x:b4,y:b3,platform:Mac OS X,\n" "03000000203800000900000000010000,8Bitdo NES30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a2,righty:a3,start:b11,x:b4,y:b3,platform:Mac OS X,\n" "03000000c82d00000190000001000000,8Bitdo NES30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a2,righty:a3,start:b11,x:b4,y:b3,platform:Mac OS X,\n" "03000000102800000900000000000000,8Bitdo SFC30 GamePad Joystick,a:b1,b:b0,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b4,y:b3,platform:Mac OS X,\n" "03000000a00500003232000008010000,8Bitdo Zero GamePad,a:b0,b:b1,back:b10,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b6,rightshoulder:b7,start:b11,x:b3,y:b4,platform:Mac OS X,\n" "03000000a00500003232000009010000,8Bitdo Zero GamePad,a:b0,b:b1,back:b10,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b6,rightshoulder:b7,start:b11,x:b3,y:b4,platform:Mac OS X,\n" "03000000050b00000045000031000000,ASUS Gamepad,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b7,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b8,righttrigger:a4,rightx:a2,righty:a3,start:b9,x:b2,y:b3,platform:Mac OS X,\n" "030000008305000031b0000000000000,Cideko AK08b,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Mac OS X,\n" "03000000260900008888000088020000,Cyber Gadget GameCube Controller,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b6,righttrigger:a5,rightx:a2,righty:a3~,start:b7,x:b2,y:b3,platform:Mac OS X,\n" "03000000a306000022f6000001030000,Cyborg V.3 Rumble Pad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:+a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:-a3,rightx:a2,righty:a4,start:b9,x:b0,y:b3,platform:Mac OS X,\n" "03000000790000000600000000000000,G-Shark GP-702,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a3,righty:a4,start:b9,x:b3,y:b0,platform:Mac OS X,\n" "03000000ad1b000001f9000000000000,Gamestop BB-070 X360 Controller,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,platform:Mac OS X,\n" "0500000047532047616d657061640000,GameStop Gamepad,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,platform:Mac OS X,\n" "030000006f0e00000102000000000000,GameStop Xbox 360 Wired Controller,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,platform:Mac OS X,\n" "030000007d0400000540000001010000,Gravis Eliminator GamePad Pro,a:b1,b:b2,back:b8,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,platform:Mac OS X,\n" "030000000d0f00005f00000000010000,Hori Fighting Commander 4 (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Mac OS X,\n" "030000000d0f00005e00000000010000,Hori Fighting Commander 4 (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Mac OS X,\n" "030000000d0f00005f00000000000000,HORI Fighting Commander 4 PS3,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Mac OS X,\n" "030000000d0f00005e00000000000000,HORI Fighting Commander 4 PS4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Mac OS X,\n" "030000000d0f00004d00000000000000,HORI Gem Pad 3,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Mac OS X,\n" "030000000d0f00009200000000010000,Hori Pokken Tournament DX Pro Pad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,platform:Mac OS X,\n" "030000000d0f00006e00000000010000,HORIPAD 4 (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Mac OS X,\n" "030000000d0f00006600000000010000,HORIPAD 4 (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Mac OS X,\n" "030000000d0f00006600000000000000,HORIPAD FPS PLUS 4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Mac OS X,\n" "030000000d0f0000ee00000000010000,HORIPAD mini4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Mac OS X,\n" "030000008f0e00001330000011010000,HuiJia SNES Controller,a:b4,b:b2,back:b16,dpdown:+a2,dpleft:-a0,dpright:+a0,dpup:-a2,leftshoulder:b12,rightshoulder:b14,start:b18,x:b6,y:b0,platform:Mac OS X,\n" "03000000830500006020000000010000,iBuffalo SNES Controller,a:b1,b:b0,back:b6,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b4,rightshoulder:b5,start:b7,x:b3,y:b2,platform:Mac OS X,\n" "03000000830500006020000000000000,iBuffalo USB 2-axis 8-button Gamepad,a:b1,b:b0,back:b6,leftshoulder:b4,leftx:a0,lefty:a1,rightshoulder:b5,start:b7,x:b3,y:b2,platform:Mac OS X,\n" "030000007e0500000620000001000000,Joy-Con (L),+leftx:h0.2,+lefty:h0.4,-leftx:h0.8,-lefty:h0.1,a:b0,b:b1,back:b13,leftshoulder:b4,leftstick:b10,rightshoulder:b5,start:b8,x:b2,y:b3,platform:Mac OS X,\n" "030000007e0500000720000001000000,Joy-Con (R),+leftx:h0.2,+lefty:h0.4,-leftx:h0.8,-lefty:h0.1,a:b0,b:b1,back:b12,leftshoulder:b4,leftstick:b11,rightshoulder:b5,start:b9,x:b2,y:b3,platform:Mac OS X,\n" "030000006d04000016c2000000020000,Logitech Dual Action,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Mac OS X,\n" "030000006d04000016c2000000030000,Logitech Dual Action,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Mac OS X,\n" "030000006d04000016c2000014040000,Logitech Dual Action,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Mac OS X,\n" "030000006d04000016c2000000000000,Logitech F310 Gamepad (DInput),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Mac OS X,\n" "030000006d04000018c2000000000000,Logitech F510 Gamepad (DInput),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Mac OS X,\n" "030000006d0400001fc2000000000000,Logitech F710 Gamepad (XInput),a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,platform:Mac OS X,\n" "030000006d04000018c2000000010000,Logitech RumblePad 2 USB,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1~,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3~,start:b9,x:b0,y:b3,platform:Mac OS X,\n" "030000006d04000019c2000000000000,Logitech Wireless Gamepad (DInput),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Mac OS X,\n" "03000000380700005032000000010000,Mad Catz FightPad PRO (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Mac OS X,\n" "03000000380700005082000000010000,Mad Catz FightPad PRO (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Mac OS X,\n" "03000000380700008433000000010000,Mad Catz FightStick TE S+ (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Mac OS X,\n" "03000000380700008483000000010000,Mad Catz FightStick TE S+ (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Mac OS X,\n" "03000000790000004418000000010000,Mayflash GameCube Controller,a:b1,b:b2,dpdown:b14,dpleft:b15,dpright:b13,dpup:b12,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:a4,rightx:a5,righty:a2,start:b9,x:b0,y:b3,platform:Mac OS X,\n" "0300000025090000e803000000000000,Mayflash Wii Classic Controller,a:b1,b:b0,back:b8,dpdown:b13,dpleft:b12,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b2,platform:Mac OS X,\n" "03000000790000000018000000000000,Mayflash WiiU Pro Game Controller Adapter (DInput),a:b4,b:b8,back:b32,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b16,leftstick:b40,lefttrigger:b24,leftx:a0,lefty:a4,rightshoulder:b20,rightstick:b44,righttrigger:b28,rightx:a8,righty:a12,start:b36,x:b0,y:b12,platform:Mac OS X,\n" "03000000d8140000cecf000000000000,MC Cthulhu,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,platform:Mac OS X,\n" "03000000d62000007162000001000000,Moga Pro 2 HID,a:b0,b:b1,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b7,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b8,righttrigger:a4,rightx:a2,righty:a3,start:b6,x:b2,y:b3,platform:Mac OS X,\n" "030000001008000001e5000006010000,NEXT SNES Controller,a:b2,b:b1,back:b8,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b4,rightshoulder:b6,start:b9,x:b3,y:b0,platform:Mac OS X,\n" "030000007e0500000920000000000000,Nintendo Switch Pro Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,platform:Mac OS X,\n" "030000007e0500000920000001000000,Nintendo Switch Pro Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,platform:Mac OS X,\n" "030000008f0e00000300000000000000,Piranha xtreme,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a3,righty:a2,start:b9,x:b3,y:b0,platform:Mac OS X,\n" "03000000d62000006dca000000010000,PowerA Pro Ex,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Mac OS X,\n" "030000004c0500006802000000000000,PS3 Controller,a:b14,b:b13,back:b0,dpdown:b6,dpleft:b7,dpright:b5,dpup:b4,guide:b16,leftshoulder:b10,leftstick:b1,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b11,rightstick:b2,righttrigger:b9,rightx:a2,righty:a3,start:b3,x:b15,y:b12,platform:Mac OS X,\n" "030000004c0500006802000000010000,PS3 Controller,a:b14,b:b13,back:b0,dpdown:b6,dpleft:b7,dpright:b5,dpup:b4,guide:b16,leftshoulder:b10,leftstick:b1,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b11,rightstick:b2,righttrigger:b9,rightx:a2,righty:a3,start:b3,x:b15,y:b12,platform:Mac OS X,\n" "030000004c050000a00b000000010000,PS4 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Mac OS X,\n" "030000004c050000c405000000000000,PS4 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Mac OS X,\n" "030000004c050000c405000000010000,PS4 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Mac OS X,\n" "030000004c050000cc09000000010000,PS4 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Mac OS X,\n" "030000008916000000fd000000000000,Razer Onza TE,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,platform:Mac OS X,\n" "03000000321500000204000000010000,Razer Panthera (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Mac OS X,\n" "03000000321500000104000000010000,Razer Panthera (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Mac OS X,\n" "03000000321500000010000000010000,Razer RAIJU,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Mac OS X,\n" "03000000321500000009000000020000,Razer Serval,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a4,rightx:a2,righty:a3,start:b7,x:b2,y:b3,platform:Mac OS X,\n" "030000003215000000090000163a0000,Razer Serval,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a4,rightx:a2,righty:a3,start:b7,x:b2,y:b3,platform:Mac OS X,\n" "0300000032150000030a000000000000,Razer Wildcat,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,platform:Mac OS X,\n" "03000000790000001100000000000000,Retrolink Classic Controller,a:b2,b:b1,back:b8,leftshoulder:b4,leftx:a3,lefty:a4,rightshoulder:b5,start:b9,x:b3,y:b0,platform:Mac OS X,\n" "03000000790000001100000006010000,Retrolink SNES Controller,a:b2,b:b1,back:b8,dpdown:+a4,dpleft:-a3,dpright:+a3,dpup:-a4,leftshoulder:b4,rightshoulder:b5,start:b9,x:b3,y:b0,platform:Mac OS X,\n" "030000006b140000010d000000010000,Revolution Pro Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Mac OS X,\n" "03000000c6240000fefa000000000000,Rock Candy Gamepad for PS3,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,platform:Mac OS X,\n" "03000000811700007e05000000000000,Sega Saturn,a:b2,b:b4,dpdown:b16,dpleft:b15,dpright:b14,dpup:b17,leftshoulder:b8,lefttrigger:a5,leftx:a0,lefty:a2,rightshoulder:b9,righttrigger:a4,start:b13,x:b0,y:b6,platform:Mac OS X,\n" "03000000b40400000a01000000000000,Sega Saturn USB Gamepad,a:b0,b:b1,back:b5,guide:b2,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b8,x:b3,y:b4,platform:Mac OS X,\n" "030000003512000021ab000000000000,SFC30 Joystick,a:b1,b:b0,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b4,y:b3,platform:Mac OS X,\n" "0300000000f00000f100000000000000,SNES RetroPort,a:b2,b:b3,back:b4,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b5,rightshoulder:b7,start:b6,x:b0,y:b1,platform:Mac OS X,\n" "030000004c050000cc09000000000000,Sony DualShock 4 V2,a:b1,b:b2,back:b13,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Mac OS X,\n" "030000004c050000a00b000000000000,Sony DualShock 4 Wireless Adaptor,a:b1,b:b2,back:b13,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Mac OS X,\n" "030000005e0400008e02000001000000,Steam Virtual Gamepad,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,platform:Mac OS X,\n" "03000000110100002014000000000000,SteelSeries Nimbus,a:b0,b:b1,dpdown:b9,dpleft:b11,dpright:b10,dpup:b8,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b12,x:b2,y:b3,platform:Mac OS X,\n" "03000000110100002014000001000000,SteelSeries Nimbus,a:b0,b:b1,dpdown:b9,dpleft:b11,dpright:b10,dpup:b8,guide:b12,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1~,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3~,x:b2,y:b3,platform:Mac OS X,\n" "03000000381000002014000001000000,SteelSeries Nimbus,a:b0,b:b1,dpdown:b9,dpleft:b11,dpright:b10,dpup:b8,guide:b12,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1~,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3~,x:b2,y:b3,platform:Mac OS X,\n" "03000000110100001714000000000000,SteelSeries Stratus XL,a:b0,b:b1,dpdown:b9,dpleft:b11,dpright:b10,dpup:b8,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1~,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3~,start:b12,x:b2,y:b3,platform:Mac OS X,\n" "03000000110100001714000020010000,SteelSeries Stratus XL,a:b0,b:b1,dpdown:b9,dpleft:b11,dpright:b10,dpup:b8,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1~,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3~,start:b12,x:b2,y:b3,platform:Mac OS X,\n" "030000004f04000015b3000000000000,Thrustmaster Dual Analog 3.2,a:b0,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b1,y:b3,platform:Mac OS X,\n" "030000004f04000000b3000000000000,Thrustmaster Firestorm Dual Power,a:b0,b:b2,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b11,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,righttrigger:b7,rightx:a2,righty:a3,start:b10,x:b1,y:b3,platform:Mac OS X,\n" "03000000bd12000015d0000000000000,Tomee SNES USB Controller,a:b2,b:b1,back:b8,leftshoulder:b4,leftx:a0,lefty:a1,rightshoulder:b5,start:b9,x:b3,y:b0,platform:Mac OS X,\n" "03000000bd12000015d0000000010000,Tomee SNES USB Controller,a:b2,b:b1,back:b8,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b4,rightshoulder:b5,start:b9,x:b3,y:b0,platform:Mac OS X,\n" "03000000100800000100000000000000,Twin USB Joystick,a:b4,b:b2,back:b16,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b12,leftstick:b20,lefttrigger:b8,leftx:a0,lefty:a2,rightshoulder:b14,rightstick:b22,righttrigger:b10,rightx:a6,righty:a4,start:b18,x:b6,y:b0,platform:Mac OS X,\n" "050000005769696d6f74652028303000,Wii Remote,a:b4,b:b5,back:b7,dpdown:b3,dpleft:b0,dpright:b1,dpup:b2,guide:b8,leftshoulder:b11,lefttrigger:b12,leftx:a0,lefty:a1,start:b6,x:b10,y:b9,platform:Mac OS X,\n" "050000005769696d6f74652028313800,Wii U Pro Controller,a:b16,b:b15,back:b7,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b8,leftshoulder:b19,leftstick:b23,lefttrigger:b21,leftx:a0,lefty:a1,rightshoulder:b20,rightstick:b24,righttrigger:b22,rightx:a2,righty:a3,start:b6,x:b18,y:b17,platform:Mac OS X,\n" "030000005e0400008e02000000000000,X360 Controller,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,platform:Mac OS X,\n" "03000000c6240000045d000000000000,Xbox 360 Wired Controller,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,platform:Mac OS X,\n" "030000005e0400000a0b000000000000,Xbox Adaptive Controller,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,platform:Mac OS X,\n" "030000005e040000d102000000000000,Xbox One Wired Controller,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,platform:Mac OS X,\n" "030000005e040000dd02000000000000,Xbox One Wired Controller,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,platform:Mac OS X,\n" "030000005e040000e302000000000000,Xbox One Wired Controller,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,platform:Mac OS X,\n" "030000005e040000e002000000000000,Xbox Wireless Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b8,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Mac OS X,\n" "030000005e040000e002000003090000,Xbox Wireless Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b8,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Mac OS X,\n" "030000005e040000ea02000000000000,Xbox Wireless Controller,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,platform:Mac OS X,\n" "030000005e040000fd02000003090000,Xbox Wireless Controller,a:b0,b:b1,back:b16,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b15,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,platform:Mac OS X,\n" "03000000172700004431000029010000,XiaoMi Game Controller,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b15,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a6,rightx:a2,righty:a5,start:b11,x:b3,y:b4,platform:Mac OS X,\n" "03000000120c0000100e000000010000,ZEROPLUS P4 Gamepad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Mac OS X,\n" "# Linux\n" "05000000c82d00001038000000010000,8Bitdo FC30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a2,righty:a3,start:b11,x:b4,y:b3,platform:Linux,\n" "03000000022000000090000011010000,8Bitdo NES30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a2,righty:a3,start:b11,x:b4,y:b3,platform:Linux,\n" "05000000203800000900000000010000,8Bitdo NES30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a2,righty:a3,start:b11,x:b4,y:b3,platform:Linux,\n" "05000000c82d00002038000000010000,8Bitdo NES30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b4,y:b3,platform:Linux,\n" "03000000c82d00000190000011010000,8Bitdo NES30 Pro 8Bitdo NES30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a5,rightx:a2,righty:a3,start:b11,x:b4,y:b3,platform:Linux,\n" "05000000c82d00000061000000010000,8Bitdo SF30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b4,y:b3,platform:Linux,\n" "05000000102800000900000000010000,8Bitdo SFC30 GamePad,a:b1,b:b0,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b4,y:b3,platform:Linux,\n" "05000000c82d00003028000000010000,8Bitdo SFC30 GamePad,a:b1,b:b0,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b4,y:b3,platform:Linux,\n" "05000000a00500003232000001000000,8Bitdo Zero GamePad,a:b0,b:b1,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b3,y:b4,platform:Linux,\n" "05000000a00500003232000008010000,8Bitdo Zero GamePad,a:b0,b:b1,back:b10,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b6,rightshoulder:b7,start:b11,x:b3,y:b4,platform:Linux,\n" "030000006f0e00001302000000010000,Afterglow,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,\n" "030000006f0e00003901000020060000,Afterglow Controller for Xbox One,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,\n" "030000006f0e00003901000013020000,Afterglow Prismatic Wired Controller 048-007-NA,a:b0,b:b1,x:b2,y:b3,back:b6,guide:b8,start:b7,leftstick:b9,rightstick:b10,leftshoulder:b4,rightshoulder:b5,dpup:h0.1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,leftx:a0,lefty:a1,rightx:a3,righty:a4,lefttrigger:a2,righttrigger:a5,platform:Linux,\n" "030000006f0e00003901000000430000,Afterglow Prismatic Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,\n" "03000000100000008200000011010000,Akishop Customs PS360+ v1.66,a:b1,b:b2,back:b12,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,platform:Linux,\n" "05000000491900000204000021000000,Amazon Fire Game Controller,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,platform:Linux,\n" "05000000050b00000045000031000000,ASUS Gamepad,a:b0,b:b1,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b6,leftshoulder:b4,leftstick:b7,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b8,righttrigger:a4,rightx:a2,righty:a3,start:b10,x:b2,y:b3,platform:Linux,\n" "05000000050b00000045000040000000,ASUS Gamepad,a:b0,b:b1,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b6,leftshoulder:b4,leftstick:b7,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b8,righttrigger:a4,rightx:a2,righty:a3,start:b10,x:b2,y:b3,platform:Linux,\n" "03000000120c00000500000010010000,AxisPad,a:b2,b:b3,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b8,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:b7,rightx:a3,righty:a2,start:b11,x:b0,y:b1,platform:Linux,\n" "03000000666600006706000000010000,boom PSX to PC Converter,a:b2,b:b1,back:b8,dpdown:b14,dpleft:b15,dpright:b13,dpup:b12,leftshoulder:b6,leftstick:b9,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b10,righttrigger:b5,rightx:a2,righty:a3,start:b11,x:b3,y:b0,platform:Linux,\n" "03000000e82000006058000001010000,Cideko AK08b,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,platform:Linux,\n" "03000000260900008888000000010000,Cyber Gadget GameCube Controller,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b6,righttrigger:a5,rightx:a2,righty:a3~,start:b7,x:b2,y:b3,platform:Linux,\n" "03000000a306000022f6000011010000,Cyborg V.3 Rumble Pad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:+a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:-a3,rightx:a2,righty:a4,start:b9,x:b0,y:b3,platform:Linux,\n" "03000000b40400000a01000000010000,CYPRESS USB Gamepad,a:b0,b:b1,back:b5,guide:b2,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b8,x:b3,y:b4,platform:Linux,\n" "03000000790000000600000010010000,DragonRise Inc. Generic USB Joystick,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a3,righty:a4,start:b9,x:b3,y:b0,platform:Linux,\n" "030000006f0e00003001000001010000,EA Sports PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Linux,\n" "03000000341a000005f7000010010000,GameCube {HuiJia USB box},a:b1,b:b2,dpdown:b14,dpleft:b15,dpright:b13,dpup:b12,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:a4,rightx:a5,righty:a2,start:b9,x:b0,y:b3,platform:Linux,\n" "03000000bc2000000055000011010000,GameSir G3w,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,platform:Linux,\n" "0500000047532047616d657061640000,GameStop Gamepad,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,platform:Linux,\n" "030000006f0e00000104000000010000,Gamestop Logic3 Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,\n" "030000008f0e00000800000010010000,Gasia Co. Ltd PS(R) Gamepad,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,platform:Linux,\n" "030000006f0e00001304000000010000,Generic X-Box pad,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:a0,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:a3,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,\n" "03000000f0250000c183000010010000,Goodbetterbest Ltd USB Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Linux,\n" "0300000079000000d418000000010000,GPD Win 2 Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,\n" "030000007d0400000540000000010000,Gravis Eliminator GamePad Pro,a:b1,b:b2,back:b8,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,platform:Linux,\n" "03000000280400000140000000010000,Gravis GamePad Pro USB ,a:b1,b:b2,back:b8,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,platform:Linux,\n" "030000008f0e00000610000000010000,GreenAsia Electronics 4Axes 12Keys GamePad ,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b9,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b10,righttrigger:b5,rightx:a3,righty:a2,start:b11,x:b3,y:b0,platform:Linux,\n" "030000008f0e00001200000010010000,GreenAsia Inc. USB Joystick,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b2,y:b3,platform:Linux,\n" "0500000047532067616d657061640000,GS gamepad,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,platform:Linux,\n" "06000000adde0000efbe000002010000,Hidromancer Game Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,\n" "03000000d81400000862000011010000,HitBox (PS3/PC) Analog Mode,a:b1,b:b2,back:b8,guide:b9,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,start:b12,x:b0,y:b3,platform:Linux,\n" "03000000c9110000f055000011010000,HJC Game GAMEPAD,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,platform:Linux,\n" "030000000d0f00000d00000000010000,hori,a:b0,b:b6,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b3,leftx:b4,lefty:b5,rightshoulder:b7,start:b9,x:b1,y:b2,platform:Linux,\n" "030000000d0f00001000000011010000,HORI CO. LTD. FIGHTING STICK 3,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,platform:Linux,\n" "030000000d0f00006a00000011010000,HORI CO. LTD. Real Arcade Pro.4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Linux,\n" "030000000d0f00006b00000011010000,HORI CO. LTD. Real Arcade Pro.4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Linux,\n" "030000000d0f00002200000011010000,HORI CO. LTD. REAL ARCADE Pro.V3,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,platform:Linux,\n" "030000000d0f00005f00000011010000,Hori Fighting Commander 4 (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Linux,\n" "030000000d0f00005e00000011010000,Hori Fighting Commander 4 (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Linux,\n" "03000000ad1b000001f5000033050000,Hori Pad EX Turbo 2,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,\n" "030000000d0f00009200000011010000,Hori Pokken Tournament DX Pro Pad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,platform:Linux,\n" "030000000d0f00006e00000011010000,HORIPAD 4 (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Linux,\n"; const char *RInput::gamepadMappingCode2 = "030000000d0f00006600000011010000,HORIPAD 4 (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Linux,\n" "030000000d0f0000ee00000011010000,HORIPAD mini4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Linux,\n" "030000000d0f00006700000001010000,HORIPAD ONE,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,\n" "030000008f0e00001330000010010000,HuiJia SNES Controller,a:b2,b:b1,back:b8,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b6,rightshoulder:b7,start:b9,x:b3,y:b0,platform:Linux,\n" "03000000830500006020000010010000,iBuffalo SNES Controller,a:b1,b:b0,back:b6,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b4,rightshoulder:b5,start:b7,x:b3,y:b2,platform:Linux,\n" "050000006964726f69643a636f6e0000,idroid:con,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Linux,\n" "03000000b50700001503000010010000,impact,a:b2,b:b3,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b0,y:b1,platform:Linux,\n" "03000000fd0500000030000000010000,InterAct GoPad I-73000 (Fighting Game Layout),a:b3,b:b4,back:b6,leftx:a0,lefty:a1,rightshoulder:b2,righttrigger:b5,start:b7,x:b0,y:b1,platform:Linux,\n" "0500000049190000020400001b010000,Ipega PG-9069 - Bluetooth Gamepad,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b161,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,platform:Linux,\n" "030000006e0500000320000010010000,JC-U3613M - DirectInput Mode,a:b2,b:b3,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b8,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:b7,rightx:a2,righty:a3,start:b11,x:b0,y:b1,platform:Linux,\n" "03000000300f00001001000010010000,Jess Tech Dual Analog Rumble Pad,a:b2,b:b3,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b0,y:b1,platform:Linux,\n" "03000000300f00000b01000010010000,Jess Tech GGE909 PC Recoil Pad,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b3,y:b0,platform:Linux,\n" "03000000ba2200002010000001010000,Jess Technology USB Game Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b3,y:b0,platform:Linux,\n" "030000007e0500000620000001000000,Joy-Con (L),+leftx:h0.2,+lefty:h0.4,-leftx:h0.8,-lefty:h0.1,a:b0,b:b1,back:b13,leftshoulder:b4,leftstick:b10,rightshoulder:b5,start:b8,x:b2,y:b3,platform:Linux,\n" "050000007e0500000620000001000000,Joy-Con (L),+leftx:h0.2,+lefty:h0.4,-leftx:h0.8,-lefty:h0.1,a:b0,b:b1,back:b13,leftshoulder:b4,leftstick:b10,rightshoulder:b5,start:b8,x:b2,y:b3,platform:Linux,\n" "030000007e0500000720000001000000,Joy-Con (R),+leftx:h0.2,+lefty:h0.4,-leftx:h0.8,-lefty:h0.1,a:b0,b:b1,back:b12,leftshoulder:b4,leftstick:b11,rightshoulder:b5,start:b9,x:b2,y:b3,platform:Linux,\n" "050000007e0500000720000001000000,Joy-Con (R),+leftx:h0.2,+lefty:h0.4,-leftx:h0.8,-lefty:h0.1,a:b0,b:b1,back:b12,leftshoulder:b4,leftstick:b11,rightshoulder:b5,start:b9,x:b2,y:b3,platform:Linux,\n" "030000006f0e00000103000000020000,Logic3 Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,\n" "030000006d04000019c2000010010000,Logitech Cordless RumblePad 2,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Linux,\n" "030000006d04000016c2000010010000,Logitech Dual Action,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Linux,\n" "030000006d04000016c2000011010000,Logitech Dual Action,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Linux,\n" "030000006d0400001dc2000014400000,Logitech F310 Gamepad (XInput),a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,\n" "030000006d0400001ec2000020200000,Logitech F510 Gamepad (XInput),a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,\n" "030000006d04000019c2000011010000,Logitech F710 Gamepad (DInput),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Linux,\n" "030000006d0400001fc2000005030000,Logitech F710 Gamepad (XInput),a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,\n" "030000006d0400000ac2000010010000,Logitech Inc. WingMan RumblePad,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:b2,rightx:a3,righty:a4,x:b3,y:b4,platform:Linux,\n" "030000006d04000015c2000010010000,Logitech Logitech Extreme 3D,a:b0,b:b4,back:b6,guide:b8,leftshoulder:b9,leftstick:h0.8,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:h0.2,start:b7,x:b2,y:b5,platform:Linux,\n" "030000006d04000018c2000010010000,Logitech RumblePad 2,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Linux,\n" "030000006d04000011c2000010010000,Logitech WingMan Cordless RumblePad,a:b0,b:b1,back:b2,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b5,leftshoulder:b6,lefttrigger:b9,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:b10,rightx:a3,righty:a4,start:b8,x:b3,y:b4,platform:Linux,\n" "05000000380700006652000025010000,Mad Catz C.T.R.L.R ,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Linux,\n" "03000000380700005032000011010000,Mad Catz FightPad PRO (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Linux,\n" "03000000380700005082000011010000,Mad Catz FightPad PRO (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Linux,\n" "03000000ad1b00002ef0000090040000,Mad Catz Fightpad SFxT,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,lefttrigger:a2,rightshoulder:b5,righttrigger:a5,start:b7,x:b2,y:b3,platform:Linux,\n" "03000000380700008034000011010000,Mad Catz fightstick (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Linux,\n" "03000000380700008084000011010000,Mad Catz fightstick (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Linux,\n" "03000000380700008433000011010000,Mad Catz FightStick TE S+ (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Linux,\n" "03000000380700008483000011010000,Mad Catz FightStick TE S+ (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Linux,\n" "03000000380700001647000010040000,Mad Catz Wired Xbox 360 Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,\n" "03000000380700003847000090040000,Mad Catz Wired Xbox 360 Controller (SFIV),a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,platform:Linux,\n" "03000000ad1b000016f0000090040000,Mad Catz Xbox 360 Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,\n" "03000000380700001888000010010000,MadCatz PC USB Wired Stick 8818,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Linux,\n" "03000000380700003888000010010000,MadCatz PC USB Wired Stick 8838,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:a0,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Linux,\n" "0300000079000000d218000011010000,MAGIC-NS,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Linux,\n" "03000000120c00000500000000010000,Manta Dualshock 2,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b2,y:b3,platform:Linux,\n" "03000000790000004418000010010000,Mayflash GameCube Controller,a:b1,b:b2,dpdown:b14,dpleft:b15,dpright:b13,dpup:b12,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:a4,rightx:a5,righty:a2,start:b9,x:b0,y:b3,platform:Linux,\n" "03000000790000004318000010010000,Mayflash GameCube Controller Adapter,a:b1,b:b0,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:a4,rightx:a5,righty:a2,start:b9,x:b2,y:b3,platform:Linux,\n" "0300000025090000e803000001010000,Mayflash Wii Classic Controller,a:b1,b:b0,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:a4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:a5,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b2,platform:Linux,\n" "03000000780000000600000010010000,Microntek USB Joystick,a:b2,b:b1,back:b8,leftshoulder:b6,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:b5,start:b9,x:b3,y:b0,platform:Linux,\n" "030000005e0400000e00000000010000,Microsoft SideWinder,a:b0,b:b1,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,rightshoulder:b7,start:b8,x:b3,y:b4,platform:Linux,\n" "030000005e0400008e02000004010000,Microsoft X-Box 360 pad,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,\n" "030000005e0400008e02000062230000,Microsoft X-Box 360 pad,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,\n" "030000005e040000e302000003020000,Microsoft X-Box One Elite pad,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,\n" "030000005e040000d102000001010000,Microsoft X-Box One pad,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,\n" "030000005e040000dd02000003020000,Microsoft X-Box One pad (Firmware 2015),a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,\n" "030000005e040000d102000003020000,Microsoft X-Box One pad v2,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,\n" "030000005e0400008502000000010000,Microsoft X-Box pad (Japan),a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b5,leftstick:b8,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b2,rightstick:b9,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b3,y:b4,platform:Linux,\n" "030000005e0400008902000021010000,Microsoft X-Box pad v2 (US),a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b5,leftstick:b8,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b2,rightstick:b9,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b3,y:b4,platform:Linux,\n" "05000000d6200000e589000001000000,Moga 2 HID,a:b0,b:b1,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b7,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b8,righttrigger:a4,rightx:a2,righty:a3,start:b6,x:b2,y:b3,platform:Linux,\n" "05000000d6200000ad0d000001000000,Moga Pro,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b7,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b8,righttrigger:a4,rightx:a2,righty:a3,start:b6,x:b2,y:b3,platform:Linux,\n" "05000000d62000007162000001000000,Moga Pro 2 HID,a:b0,b:b1,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b7,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b8,righttrigger:a4,rightx:a2,righty:a3,start:b6,x:b2,y:b3,platform:Linux,\n" "03000000250900006688000000010000,MP-8866 Super Dual Box,a:b2,b:b1,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a2,righty:a3,start:b8,x:b3,y:b0,platform:Linux,\n" "030000000d0f00000900000010010000,Natec Genesis P44,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Linux,\n" "030000001008000001e5000010010000,NEXT SNES Controller,a:b2,b:b1,back:b8,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b4,rightshoulder:b6,start:b9,x:b3,y:b0,platform:Linux,\n" "050000007e0500000920000001000000,Nintendo Switch Pro Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,platform:Linux,\n" "050000007e0500003003000001000000,Nintendo Wii Remote Pro Controller,a:b0,b:b1,back:b8,dpdown:b14,dpleft:b15,dpright:b16,dpup:b13,guide:b10,leftshoulder:b4,leftstick:b11,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b12,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b2,platform:Linux,\n" "05000000010000000100000003000000,Nintendo Wiimote,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b11,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b12,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,platform:Linux,\n" "030000000d0500000308000010010000,Nostromo n45 Dual Analog Gamepad,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b9,leftshoulder:b4,leftstick:b12,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b10,x:b2,y:b3,platform:Linux,\n" "03000000550900001072000011010000,NVIDIA Controller,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b13,leftshoulder:b4,leftstick:b8,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:a4,rightx:a2,righty:a3,start:b7,x:b2,y:b3,platform:Linux,\n" "03000000550900001472000011010000,NVIDIA Controller v01.04,a:b0,b:b1,back:b14,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b16,leftshoulder:b4,leftstick:b7,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b8,righttrigger:a4,rightx:a2,righty:a5,start:b6,x:b2,y:b3,platform:Linux,\n" "05000000550900001472000001000000,NVIDIA Controller v01.04,a:b0,b:b1,back:b14,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b16,leftshoulder:b4,leftstick:b7,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b8,righttrigger:a4,rightx:a2,righty:a5,start:b6,x:b2,y:b3,platform:Linux,\n" "03000000451300000830000010010000,NYKO CORE,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Linux,\n" "030000005e0400000202000000010000,Old Xbox pad,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b5,leftstick:b8,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b2,rightstick:b9,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b3,y:b4,platform:Linux,\n" "05000000362800000100000002010000,OUYA Game Controller,a:b0,b:b3,dpdown:b9,dpleft:b10,dpright:b11,dpup:b8,guide:b14,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,x:b1,y:b2,platform:Linux,\n" "05000000362800000100000003010000,OUYA Game Controller,a:b0,b:b3,dpdown:b9,dpleft:b10,dpright:b11,dpup:b8,guide:b14,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,x:b1,y:b2,platform:Linux,\n" "03000000ff1100003133000010010000,PC Game Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,platform:Linux,\n" "030000006f0e00006401000001010000,PDP Battlefield One,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,\n" "030000006f0e0000a802000023020000,PDP Wired Controller for Xbox One,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b11,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b12,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,platform:Linux,\n" "03000000c62400000053000000010000,PowerA,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,\n" "03000000c62400003a54000001010000,PowerA 1428124-01,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,\n" "03000000d62000006dca000011010000,PowerA Pro Ex,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Linux,\n" "03000000ff1100004133000010010000,PS2 Controller,a:b2,b:b1,back:b8,leftshoulder:b6,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:b5,start:b9,x:b3,y:b0,platform:Linux,\n" "03000000341a00003608000011010000,PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Linux,\n" "030000004c0500006802000010010000,PS3 Controller,a:b14,b:b13,back:b0,dpdown:b6,dpleft:b7,dpright:b5,dpup:b4,guide:b16,leftshoulder:b10,leftstick:b1,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b11,rightstick:b2,righttrigger:b9,rightx:a2,righty:a3,start:b3,x:b15,y:b12,platform:Linux,\n" "030000004c0500006802000010810000,PS3 Controller,a:b0,b:b1,back:b8,dpdown:b14,dpleft:b15,dpright:b16,dpup:b13,guide:b10,leftshoulder:b4,leftstick:b11,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b12,righttrigger:a5,rightx:a3,righty:a4,start:b9,x:b3,y:b2,platform:Linux,\n" "030000004c0500006802000011010000,PS3 Controller,a:b14,b:b13,back:b0,dpdown:b6,dpleft:b7,dpright:b5,dpup:b4,guide:b16,leftshoulder:b10,leftstick:b1,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b11,rightstick:b2,righttrigger:b9,rightx:a2,righty:a3,start:b3,x:b15,y:b12,platform:Linux,\n" "030000004c0500006802000011810000,PS3 Controller,a:b0,b:b1,back:b8,dpdown:b14,dpleft:b15,dpright:b16,dpup:b13,guide:b10,leftshoulder:b4,leftstick:b11,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b12,righttrigger:a5,rightx:a3,righty:a4,start:b9,x:b3,y:b2,platform:Linux,\n" "030000006f0e00001402000011010000,PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Linux,\n" "030000008f0e00000300000010010000,PS3 Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,platform:Linux,\n" "050000004c0500006802000000010000,PS3 Controller,a:b14,b:b13,back:b0,dpdown:b6,dpleft:b7,dpright:b5,dpup:b4,guide:b16,leftshoulder:b10,leftstick:b1,lefttrigger:a12,leftx:a0,lefty:a1,rightshoulder:b11,rightstick:b2,righttrigger:a13,rightx:a2,righty:a3,start:b3,x:b15,y:b12,platform:Linux,\n" "050000004c0500006802000000800000,PS3 Controller,a:b0,b:b1,back:b8,dpdown:b14,dpleft:b15,dpright:b16,dpup:b13,guide:b10,leftshoulder:b4,leftstick:b11,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b12,righttrigger:b7,rightx:a3,righty:a4,start:b9,x:b3,y:b2,platform:Linux,\n" "050000004c0500006802000000810000,PS3 Controller,a:b0,b:b1,back:b8,dpdown:b14,dpleft:b15,dpright:b16,dpup:b13,guide:b10,leftshoulder:b4,leftstick:b11,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b12,righttrigger:a5,rightx:a3,righty:a4,start:b9,x:b3,y:b2,platform:Linux,\n" "05000000504c415953544154494f4e00,PS3 Controller,a:b14,b:b13,back:b0,dpdown:b6,dpleft:b7,dpright:b5,dpup:b4,guide:b16,leftshoulder:b10,leftstick:b1,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b11,rightstick:b2,righttrigger:b9,rightx:a2,righty:a3,start:b3,x:b15,y:b12,platform:Linux,\n" "060000004c0500006802000000010000,PS3 Controller,a:b14,b:b13,back:b0,dpdown:b6,dpleft:b7,dpright:b5,dpup:b4,guide:b16,leftshoulder:b10,leftstick:b1,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b11,rightstick:b2,righttrigger:b9,rightx:a2,righty:a3,start:b3,x:b15,y:b12,platform:Linux,\n" "030000004c050000a00b000011010000,PS4 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Linux,\n" "030000004c050000a00b000011810000,PS4 Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b11,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b12,righttrigger:a5,rightx:a3,righty:a4,start:b9,x:b3,y:b2,platform:Linux,\n" "030000004c050000c405000011010000,PS4 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Linux,\n" "030000004c050000c405000011810000,PS4 Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b11,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b12,righttrigger:a5,rightx:a3,righty:a4,start:b9,x:b3,y:b2,platform:Linux,\n" "030000004c050000cc09000000010000,PS4 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Linux,\n" "030000004c050000cc09000011010000,PS4 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Linux,\n" "030000004c050000cc09000011810000,PS4 Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b11,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b12,righttrigger:a5,rightx:a3,righty:a4,start:b9,x:b3,y:b2,platform:Linux,\n" "050000004c050000c405000000010000,PS4 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Linux,\n" "050000004c050000c405000000810000,PS4 Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b11,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b12,righttrigger:a5,rightx:a3,righty:a4,start:b9,x:b3,y:b2,platform:Linux,\n" "050000004c050000cc09000000010000,PS4 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Linux,\n" "050000004c050000cc09000000810000,PS4 Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b11,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b12,righttrigger:a5,rightx:a3,righty:a4,start:b9,x:b3,y:b2,platform:Linux,\n" "050000004c050000cc09000001800000,PS4 Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b11,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b12,righttrigger:a5,rightx:a3,righty:a4,start:b9,x:b3,y:b2,platform:Linux,\n" "03000000300f00001211000011010000,QanBa Arcade JoyStick,a:b2,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b5,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:b6,start:b9,x:b1,y:b3,platform:Linux,\n" "030000009b2800000300000001010000,raphnet.net 4nes4snes v1.5,a:b0,b:b4,back:b2,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b3,x:b1,y:b5,platform:Linux,\n" "030000008916000001fd000024010000,Razer Onza Classic Edition,a:b0,b:b1,back:b6,dpdown:b14,dpleft:b11,dpright:b12,dpup:b13,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,\n" "030000008916000000fd000024010000,Razer Onza Tournament Edition,a:b0,b:b1,back:b6,dpdown:b14,dpleft:b11,dpright:b12,dpup:b13,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,\n" "03000000321500000204000011010000,Razer Panthera (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Linux,\n" "03000000321500000104000011010000,Razer Panthera (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Linux,\n" "03000000321500000010000011010000,Razer RAIJU,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Linux,\n" "030000008916000000fe000024010000,Razer Sabertooth,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,\n" "03000000c6240000045d000024010000,Razer Sabertooth,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,\n" "03000000c6240000045d000025010000,Razer Sabertooth,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,\n" "03000000321500000009000011010000,Razer Serval,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a4,rightx:a2,righty:a3,start:b7,x:b2,y:b3,platform:Linux,\n" "050000003215000000090000163a0000,Razer Serval,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a4,rightx:a2,righty:a3,start:b7,x:b2,y:b3,platform:Linux,\n" "0300000032150000030a000001010000,Razer Wildcat,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,\n" "03000000790000001100000010010000,Retrolink SNES Controller,a:b2,b:b1,back:b8,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b4,rightshoulder:b5,start:b9,x:b3,y:b0,platform:Linux,\n" "0300000000f000000300000000010000,RetroPad,a:b1,b:b5,back:b2,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b3,x:b0,y:b4,platform:Linux,\n" "030000006b140000010d000011010000,Revolution Pro Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Linux,\n" "030000006f0e00001f01000000010000,Rock Candy,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,\n" "030000006f0e00001e01000011010000,Rock Candy PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Linux,\n" "030000006f0e00004601000001010000,Rock Candy Xbox One Controller,a:b0,b:b1,back:b6,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,\n" "03000000a306000023f6000011010000,Saitek Cyborg V.1 Game Pad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a4,start:b9,x:b0,y:b3,platform:Linux,\n" "03000000a30600000cff000010010000,Saitek P2500 Force Rumble Pad,a:b2,b:b3,back:b11,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b8,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:b7,rightx:a3,righty:a2,x:b0,y:b1,platform:Linux,\n" "03000000a30600000c04000011010000,Saitek P2900 Wireless Pad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b9,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a3,righty:a2,start:b12,x:b0,y:b3,platform:Linux,\n" "03000000a30600000901000000010000,Saitek P880,a:b2,b:b3,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b8,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:b7,rightx:a3,righty:a2,x:b0,y:b1,platform:Linux,\n" "03000000a30600000b04000000010000,Saitek P990 Dual Analog Pad,a:b1,b:b2,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b8,x:b0,y:b3,platform:Linux,\n" "03000000a306000018f5000010010000,Saitek PLC Saitek P3200 Rumble Pad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a3,righty:a4,start:b9,x:b0,y:b3,platform:Linux,\n" "03000000c01600008704000011010000,Serial/Keyboard/Mouse/Joystick,a:b12,b:b10,back:b4,dpdown:b2,dpleft:b3,dpright:b1,dpup:b0,leftshoulder:b9,leftstick:b14,lefttrigger:b6,leftx:a1,lefty:a0,rightshoulder:b8,rightstick:b15,righttrigger:b7,rightx:a2,righty:a3,start:b5,x:b13,y:b11,platform:Linux,\n" "03000000f025000021c1000010010000,ShanWan Gioteck PS3 Wired Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,platform:Linux,\n" "03000000632500007505000010010000,SHANWAN PS3/PC Gamepad,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,platform:Linux,\n" "03000000bc2000000055000010010000,ShanWan PS3/PC Wired GamePad,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,platform:Linux,\n" "03000000632500002305000010010000,ShanWan USB Gamepad,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,platform:Linux,\n" "03000000341a00000908000010010000,SL-6566,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,platform:Linux,\n" "03000000250900000500000000010000,Sony PS2 pad with SmartJoy adapter,a:b2,b:b1,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a2,righty:a3,start:b8,x:b3,y:b0,platform:Linux,\n" "030000005e0400008e02000073050000,Speedlink TORID Wireless Gamepad,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,\n" "030000005e0400008e02000020200000,SpeedLink XEOX Pro Analog Gamepad pad,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,\n" "03000000de2800000112000001000000,Steam Controller,a:b0,b:b1,back:b6,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:a3,start:b7,x:b2,y:b3,platform:Linux,\n" "03000000de2800000211000001000000,Steam Controller,a:b0,b:b1,back:b6,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:a3,start:b7,x:b2,y:b3,platform:Linux,\n" "03000000de2800004211000001000000,Steam Controller,a:b0,b:b1,back:b6,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:a3,start:b7,x:b2,y:b3,platform:Linux,\n" "03000000de280000fc11000001000000,Steam Controller,a:b0,b:b1,back:b6,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,\n" "05000000de2800000212000001000000,Steam Controller,a:b0,b:b1,back:b6,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:a3,start:b7,x:b2,y:b3,platform:Linux,\n" "05000000de2800000511000001000000,Steam Controller,a:b0,b:b1,back:b6,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:a3,start:b7,x:b2,y:b3,platform:Linux,\n" "05000000de2800000611000001000000,Steam Controller,a:b0,b:b1,back:b6,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:a3,start:b7,x:b2,y:b3,platform:Linux,\n" "03000000de280000ff11000001000000,Steam Virtual Gamepad,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,\n" "03000000ad1b000038f0000090040000,Street Fighter IV FightStick TE,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,\n" "03000000666600000488000000010000,Super Joy Box 5 Pro,a:b2,b:b1,back:b9,dpdown:b14,dpleft:b15,dpright:b13,dpup:b12,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a2,righty:a3,start:b8,x:b3,y:b0,platform:Linux,\n" "0300000000f00000f100000000010000,Super RetroPort,a:b1,b:b5,back:b2,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b3,x:b0,y:b4,platform:Linux,\n" "030000004f04000020b3000010010000,Thrustmaster 2 in 1 DT,a:b0,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b1,y:b3,platform:Linux,\n" "030000004f04000015b3000010010000,Thrustmaster Dual Analog 4,a:b0,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b1,y:b3,platform:Linux,\n" "030000004f04000023b3000000010000,Thrustmaster Dual Trigger 3-in-1,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Linux,\n" "030000004f04000000b3000010010000,Thrustmaster Firestorm Dual Power,a:b0,b:b2,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b11,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b12,righttrigger:b7,rightx:a2,righty:a3,start:b10,x:b1,y:b3,platform:Linux,\n" "030000004f04000026b3000002040000,Thrustmaster Gamepad GP XID,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,\n" "03000000c6240000025b000002020000,Thrustmaster GPX Gamepad,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,\n" "030000004f04000008d0000000010000,Thrustmaster Run N Drive Wireless,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Linux,\n" "030000004f04000009d0000000010000,Thrustmaster Run N Drive Wireless PS3,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Linux,\n" "030000004f04000012b3000010010000,Thrustmaster vibrating gamepad,a:b0,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b1,y:b3,platform:Linux,\n" "03000000bd12000015d0000010010000,Tomee SNES USB Controller,a:b2,b:b1,back:b8,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b4,rightshoulder:b5,start:b9,x:b3,y:b0,platform:Linux,\n" "03000000d814000007cd000011010000,Toodles 2008 Chimp PC/PS3,a:b0,b:b1,back:b8,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,start:b9,x:b3,y:b2,platform:Linux,\n" "03000000100800000100000010010000,Twin USB PS2 Adapter,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a3,righty:a2,start:b9,x:b3,y:b0,platform:Linux,\n" "03000000100800000300000010010000,USB Gamepad,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a3,righty:a2,start:b9,x:b3,y:b0,platform:Linux,\n" "03000000790000000600000007010000,USB gamepad,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a3,righty:a4,start:b9,x:b3,y:b0,platform:Linux,\n" "03000000790000001100000000010000,USB Gamepad1,a:b2,b:b1,back:b8,dpdown:a0,dpleft:a1,dpright:a2,dpup:a4,start:b9,platform:Linux,\n" "05000000ac0500003232000001000000,VR-BOX,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a3,righty:a2,start:b9,x:b2,y:b3,platform:Linux,\n" "030000005e0400008e02000010010000,X360 Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,\n" "030000005e0400008e02000014010000,X360 Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,\n" "030000005e0400001907000000010000,X360 Wireless Controller,a:b0,b:b1,back:b6,dpdown:b14,dpleft:b11,dpright:b12,dpup:b13,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,\n" "030000005e0400009102000007010000,X360 Wireless Controller,a:b0,b:b1,back:b6,dpdown:b14,dpleft:b11,dpright:b12,dpup:b13,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,\n" "030000005e040000a102000000010000,X360 Wireless Controller,a:b0,b:b1,back:b6,dpdown:b14,dpleft:b11,dpright:b12,dpup:b13,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,\n" "030000005e040000a102000007010000,X360 Wireless Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,\n" "0000000058626f782033363020576900,Xbox 360 Wireless Controller,a:b0,b:b1,back:b14,dpdown:b11,dpleft:b12,dpright:b13,dpup:b10,guide:b7,leftshoulder:b4,leftstick:b8,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:a5,rightx:a3,righty:a4,start:b6,x:b2,y:b3,platform:Linux,\n" "030000005e040000a102000014010000,Xbox 360 Wireless Receiver (XBOX),a:b0,b:b1,back:b6,dpdown:b14,dpleft:b11,dpright:b12,dpup:b13,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,\n" "0000000058626f782047616d65706100,Xbox Gamepad (userspace driver),a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a4,rightx:a2,righty:a3,start:b7,x:b2,y:b3,platform:Linux,\n" "030000005e040000ea02000001030000,Xbox One Wireless Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,\n" "050000005e040000e002000003090000,Xbox One Wireless Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b8,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,\n" "050000005e040000fd02000003090000,Xbox One Wireless Controller,a:b0,b:b1,back:b15,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b16,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,platform:Linux,\n" "03000000450c00002043000010010000,XEOX Gamepad SL-6556-BK,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,platform:Linux,\n" "05000000172700004431000029010000,XiaoMi Game Controller,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b20,leftshoulder:b6,leftstick:b13,lefttrigger:a7,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a6,rightx:a2,righty:a5,start:b11,x:b3,y:b4,platform:Linux,\n" "03000000c0160000e105000001010000,Xin-Mo Xin-Mo Dual Arcade,a:b4,b:b3,back:b6,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b9,leftshoulder:b2,leftx:a0,lefty:a1,rightshoulder:b5,start:b7,x:b1,y:b0,platform:Linux,\n" "xinput,XInput Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,\n" "03000000120c0000100e000011010000,ZEROPLUS P4 Gamepad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Linux,\n" "# Android\n" "05000000bc20000000550000ffff3f00,GameSir G3w,a:b0,b:b1,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b9,leftstick:b7,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a4,rightx:a2,righty:a3,start:b6,x:b2,y:b3,platform:Android,\n" "05000000d6020000e5890000dfff3f00,GPD XD Plus,a:b0,b:b1,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b9,leftstick:b7,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a4,rightx:a2,righty:a5,start:b6,x:b2,y:b3,platform:Android,\n" "64633436313965656664373634323364,Microsoft X-Box 360 pad,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,x:b2,y:b3,platform:Android,\n" "050000007e05000009200000ffff0f00,Nintendo Switch Pro Controller,a:b0,b:b1,back:b15,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b5,leftshoulder:b3,leftstick:b4,lefttrigger:b9,leftx:a0,lefty:a1,rightshoulder:b18,rightstick:b6,righttrigger:b10,rightx:a2,righty:a3,start:b16,x:b17,y:b2,platform:Android,\n" "37336435666338653565313731303834,NVIDIA Controller,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b2,y:b3,platform:Android,\n" "4e564944494120436f72706f72617469,NVIDIA Controller,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b2,y:b3,platform:Android,\n" "61363931656135336130663561616264,NVIDIA Controller,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b2,y:b3,platform:Android,\n" "050000005509000003720000cf7f3f00,NVIDIA Controller v01.01,a:b0,b:b1,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b2,y:b3,platform:Android,\n" "050000005509000010720000ffff3f00,NVIDIA Controller v01.03,a:b0,b:b1,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b2,y:b3,platform:Android,\n" "050000004c05000068020000dfff3f00,PS3 Controller,a:b0,b:b1,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b2,y:b3,platform:Android,\n" "050000004c050000c4050000fffe3f00,PS4 Controller,a:b1,b:b17,back:b15,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b5,leftshoulder:b3,leftstick:b4,lefttrigger:+a3,leftx:a0,lefty:a1,rightshoulder:b18,rightstick:b6,righttrigger:+a4,rightx:a2,righty:a5,start:b16,x:b0,y:b2,platform:Android,\n" "050000004c050000cc090000fffe3f00,PS4 Controller,a:b1,b:b17,back:b15,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b5,leftshoulder:b3,leftstick:b4,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b18,rightstick:b6,righttrigger:a4,rightx:a2,righty:a5,start:b16,x:b0,y:b2,platform:Android,\n" "35643031303033326130316330353564,PS4 Controller,a:b1,b:b17,back:b15,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b5,leftshoulder:b3,leftstick:b4,lefttrigger:+a3,leftx:a0,lefty:a1,rightshoulder:b18,rightstick:b6,righttrigger:+a4,rightx:a2,righty:a5,start:b16,x:b0,y:b2,platform:Android,\n" "050000003215000000090000bf7f3f00,Razer Serval,a:b0,b:b1,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b5,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,x:b2,y:b3,platform:Android,\n" "05000000de2800000511000001000000,Steam Controller,a:b0,b:b1,back:b6,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:a3,start:b7,x:b2,y:b3,platform:Android,\n" "05000000de2800000611000001000000,Steam Controller,a:b0,b:b1,back:b6,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:a3,start:b7,x:b2,y:b3,platform:Android,\n" "5477696e20555342204a6f7973746963,Twin USB Joystick,a:b22,b:b21,back:b28,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b26,leftstick:b30,lefttrigger:b24,leftx:a0,lefty:a1,rightshoulder:b27,rightstick:b31,righttrigger:b25,rightx:a3,righty:a2,start:b29,x:b23,y:b20,platform:Android,\n" "050000005e040000e00200000ffe3f00,Xbox One Wireless Controller,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b3,leftstick:b15,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b18,rightstick:b16,righttrigger:a5,rightx:a3,righty:a4,start:b10,x:b17,y:b2,platform:Android,\n" "050000005e040000fd020000ffff3f00,Xbox One Wireless Controller,a:b0,b:b1,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b9,leftstick:b7,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a4,rightx:a2,righty:a3,start:b6,x:b2,y:b3,platform:Android,\n" "050000005e04000091020000ff073f00,Xbox Wireless Controller,a:b0,b:b1,back:b4,guide:b5,leftshoulder:b9,leftstick:b7,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a3,righty:a4,start:b6,x:b2,y:b3,platform:Android,\n" "34356136633366613530316338376136,Xbox Wireless Controller,a:b0,b:b1,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b3,leftstick:b15,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b18,rightstick:b16,righttrigger:a5,rightx:a3,righty:a4,x:b17,y:b2,platform:Android,\n" "# iOS\n" "05000000ac0500000100000000006d01,*,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b6,leftshoulder:b4,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:a5,rightx:a3,righty:a4,x:b2,y:b3,platform:iOS,\n" "05000000ac0500000200000000006d02,*,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b6,leftshoulder:b4,rightshoulder:b5,x:b2,y:b3,platform:iOS,\n" "4d466947616d65706164010000000000,MFi Extended Gamepad,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:a5,rightx:a3,righty:a4,start:b6,x:b2,y:b3,platform:iOS,\n" "4d466947616d65706164020000000000,MFi Gamepad,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,rightshoulder:b5,start:b6,x:b2,y:b3,platform:iOS,\n" "05000000ac0500000300000000006d03,Remote,a:b0,b:b2,leftx:a0,lefty:a1,platform:iOS,\n" "05000000de2800000511000001000000,Steam Controller,a:b0,b:b1,back:b6,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:a3,start:b7,x:b2,y:b3,platform:iOS,\n" "05000000de2800000611000001000000,Steam Controller,a:b0,b:b1,back:b6,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:a3,start:b7,x:b2,y:b3,platform:iOS,\n";
157.631134
329
0.799345
[ "vector", "3d" ]
4c00e0a72c9189fa168f96a1687439a667076b3e
965
cpp
C++
Gems/GraphModel/Code/Source/Integration/NodePalette/GraphCanvasNodePaletteItems.cpp
cypherdotXd/o3de
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
[ "Apache-2.0", "MIT" ]
11
2021-07-08T09:58:26.000Z
2022-03-17T17:59:26.000Z
Gems/GraphModel/Code/Source/Integration/NodePalette/GraphCanvasNodePaletteItems.cpp
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
29
2021-07-06T19:33:52.000Z
2022-03-22T10:27:49.000Z
Gems/GraphModel/Code/Source/Integration/NodePalette/GraphCanvasNodePaletteItems.cpp
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
4
2021-07-06T19:24:43.000Z
2022-03-31T12:42:27.000Z
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include <GraphModel/Integration/NodePalette/GraphCanvasNodePaletteItems.h> namespace GraphModelIntegration { /// Add common utilities to a specific Node Palette tree. void AddCommonNodePaletteUtilities(GraphCanvas::GraphCanvasTreeItem* rootItem, const GraphCanvas::EditorId& editorId) { GraphCanvas::IconDecoratedNodePaletteTreeItem* utilitiesCategory = rootItem->CreateChildNode<GraphCanvas::IconDecoratedNodePaletteTreeItem>("Utilities", editorId); utilitiesCategory->SetTitlePalette("UtilityNodeTitlePalette"); utilitiesCategory->CreateChildNode<CommentNodePaletteTreeItem>("Comment", editorId); utilitiesCategory->CreateChildNode<NodeGroupNodePaletteTreeItem>("Node Group", editorId); } }
43.863636
171
0.780311
[ "3d" ]
4c0102ba675087b19dffd62db35c3921eee789a3
34,230
cc
C++
src/import_pipeline.cc
mkwork/cquery
fc2af50c27e8d64e985ef90c0a3da73c798c6f56
[ "MIT" ]
null
null
null
src/import_pipeline.cc
mkwork/cquery
fc2af50c27e8d64e985ef90c0a3da73c798c6f56
[ "MIT" ]
null
null
null
src/import_pipeline.cc
mkwork/cquery
fc2af50c27e8d64e985ef90c0a3da73c798c6f56
[ "MIT" ]
null
null
null
#include "import_pipeline.h" #include "cache_manager.h" #include "config.h" #include "diagnostics_engine.h" #include "iindexer.h" #include "import_manager.h" #include "lsp.h" #include "message_handler.h" #include "platform.h" #include "project.h" #include "query_utils.h" #include "queue_manager.h" #include "timer.h" #include "timestamp_manager.h" #include <doctest/doctest.h> #include <loguru.hpp> #include <atomic> #include <chrono> #include <string> #include <vector> namespace { struct Out_Progress : public lsOutMessage<Out_Progress> { struct Params { int indexRequestCount = 0; int doIdMapCount = 0; int loadPreviousIndexCount = 0; int onIdMappedCount = 0; int onIndexedCount = 0; int activeThreads = 0; }; std::string method = "$cquery/progress"; Params params; }; MAKE_REFLECT_STRUCT(Out_Progress::Params, indexRequestCount, doIdMapCount, loadPreviousIndexCount, onIdMappedCount, onIndexedCount, activeThreads); MAKE_REFLECT_STRUCT(Out_Progress, jsonrpc, method, params); // Instead of processing messages forever, we only process upto // |kIterationSize| messages of a type at one time. While the import time // likely stays the same, this should reduce overall queue lengths which means // the user gets a usable index faster. struct IterationLoop { const int kIterationSize = 100; int count = 0; bool Next() { return count++ < kIterationSize; } void Reset() { count = 0; } }; struct IModificationTimestampFetcher { virtual ~IModificationTimestampFetcher() = default; virtual optional<int64_t> GetModificationTime(const std::string& path) = 0; }; struct RealModificationTimestampFetcher : IModificationTimestampFetcher { ~RealModificationTimestampFetcher() override = default; // IModificationTimestamp: optional<int64_t> GetModificationTime(const std::string& path) override { return GetLastModificationTime(path); } }; struct FakeModificationTimestampFetcher : IModificationTimestampFetcher { std::unordered_map<std::string, optional<int64_t>> entries; ~FakeModificationTimestampFetcher() override = default; // IModificationTimestamp: optional<int64_t> GetModificationTime(const std::string& path) override { auto it = entries.find(path); assert(it != entries.end()); return it->second; } }; long long GetCurrentTimeInMilliseconds() { auto time_since_epoch = Timer::Clock::now().time_since_epoch(); long long elapsed_milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(time_since_epoch) .count(); return elapsed_milliseconds; } struct ActiveThread { ActiveThread(Config* config, ImportPipelineStatus* status) : config_(config), status_(status) { if (config_->progressReportFrequencyMs < 0) return; ++status_->num_active_threads; } ~ActiveThread() { if (config_->progressReportFrequencyMs < 0) return; --status_->num_active_threads; EmitProgress(); } // Send indexing progress to client if reporting is enabled. void EmitProgress() { auto* queue = QueueManager::instance(); Out_Progress out; out.params.indexRequestCount = queue->index_request.Size(); out.params.doIdMapCount = queue->do_id_map.Size(); out.params.loadPreviousIndexCount = queue->load_previous_index.Size(); out.params.onIdMappedCount = queue->on_id_mapped.Size(); out.params.onIndexedCount = queue->on_indexed.Size(); out.params.activeThreads = status_->num_active_threads; // Ignore this progress update if the last update was too recent. if (config_->progressReportFrequencyMs != 0) { // Make sure we output a status update if queue lengths are zero. bool all_zero = out.params.indexRequestCount == 0 && out.params.doIdMapCount == 0 && out.params.loadPreviousIndexCount == 0 && out.params.onIdMappedCount == 0 && out.params.onIndexedCount == 0 && out.params.activeThreads == 0; if (!all_zero && GetCurrentTimeInMilliseconds() < status_->next_progress_output) return; status_->next_progress_output = GetCurrentTimeInMilliseconds() + config_->progressReportFrequencyMs; } QueueManager::WriteStdout(kMethodType_Unknown, out); } Config* config_; ImportPipelineStatus* status_; }; enum class ShouldParse { Yes, No, NoSuchFile }; // Checks if |path| needs to be reparsed. This will modify cached state // such that calling this function twice with the same path may return true // the first time but will return false the second. // // |from|: The file which generated the parse request for this file. ShouldParse FileNeedsParse( bool is_interactive, TimestampManager* timestamp_manager, IModificationTimestampFetcher* modification_timestamp_fetcher, ImportManager* import_manager, const std::shared_ptr<ICacheManager>& cache_manager, IndexFile* opt_previous_index, const std::string& path, const std::vector<std::string>& args, const optional<std::string>& from) { auto unwrap_opt = [](const optional<std::string>& opt) -> std::string { if (opt) return " (via " + *opt + ")"; return ""; }; // If the file is a dependency but another file as already imported it, // don't bother. if (!is_interactive && from && !import_manager->TryMarkDependencyImported(path)) { return ShouldParse::No; } optional<int64_t> modification_timestamp = modification_timestamp_fetcher->GetModificationTime(path); // Cannot find file. if (!modification_timestamp) return ShouldParse::NoSuchFile; optional<int64_t> last_cached_modification = timestamp_manager->GetLastCachedModificationTime(cache_manager.get(), path); // File has been changed. if (!last_cached_modification || modification_timestamp != *last_cached_modification) { LOG_S(INFO) << "Timestamp has changed for " << path << unwrap_opt(from); return ShouldParse::Yes; } // Command-line arguments changed. auto is_file = [](const std::string& arg) { return EndsWithAny(arg, {".h", ".c", ".cc", ".cpp", ".hpp", ".m", ".mm"}); }; if (opt_previous_index) { auto& prev_args = opt_previous_index->args; bool same = prev_args.size() == args.size(); for (size_t i = 0; i < args.size() && same; ++i) { same = prev_args[i] == args[i] || (is_file(prev_args[i]) && is_file(args[i])); } if (!same) { LOG_S(INFO) << "Arguments have changed for " << path << unwrap_opt(from); return ShouldParse::Yes; } } // File has not changed, do not parse it. return ShouldParse::No; }; enum CacheLoadResult { Parse, DoNotParse }; CacheLoadResult TryLoadFromCache( FileConsumerSharedState* file_consumer_shared, TimestampManager* timestamp_manager, IModificationTimestampFetcher* modification_timestamp_fetcher, ImportManager* import_manager, const std::shared_ptr<ICacheManager>& cache_manager, bool is_interactive, const Project::Entry& entry, const std::string& path_to_index) { // Always run this block, even if we are interactive, so we can check // dependencies and reset files in |file_consumer_shared|. IndexFile* previous_index = cache_manager->TryLoad(path_to_index); if (!previous_index) return CacheLoadResult::Parse; // If none of the dependencies have changed and the index is not // interactive (ie, requested by a file save), skip parsing and just load // from cache. // Check timestamps and update |file_consumer_shared|. ShouldParse path_state = FileNeedsParse( is_interactive, timestamp_manager, modification_timestamp_fetcher, import_manager, cache_manager, previous_index, path_to_index, entry.args, nullopt); if (path_state == ShouldParse::Yes) file_consumer_shared->Reset(path_to_index); // Target file does not exist on disk, do not emit any indexes. // TODO: Dependencies should be reassigned to other files. We can do this by // updating the "primary_file" if it doesn't exist. Might not actually be a // problem in practice. if (path_state == ShouldParse::NoSuchFile) return CacheLoadResult::DoNotParse; bool needs_reparse = is_interactive || path_state == ShouldParse::Yes; for (const std::string& dependency : previous_index->dependencies) { assert(!dependency.empty()); if (FileNeedsParse(is_interactive, timestamp_manager, modification_timestamp_fetcher, import_manager, cache_manager, previous_index, dependency, entry.args, previous_index->path) == ShouldParse::Yes) { needs_reparse = true; // Do not break here, as we need to update |file_consumer_shared| for // every dependency that needs to be reparsed. file_consumer_shared->Reset(dependency); } } // FIXME: should we still load from cache? if (needs_reparse) return CacheLoadResult::Parse; // No timestamps changed - load directly from cache. LOG_S(INFO) << "Skipping parse; no timestamp change for " << path_to_index; // TODO/FIXME: real perf PerformanceImportFile perf; std::vector<Index_DoIdMap> result; result.push_back(Index_DoIdMap(cache_manager->TakeOrLoad(path_to_index), cache_manager, perf, is_interactive, false /*write_to_disk*/)); for (const std::string& dependency : previous_index->dependencies) { // Only load a dependency if it is not already loaded. // // This is important for perf in large projects where there are lots of // dependencies shared between many files. if (!file_consumer_shared->Mark(dependency)) continue; LOG_S(INFO) << "Emitting index result for " << dependency << " (via " << previous_index->path << ")"; std::unique_ptr<IndexFile> dependency_index = cache_manager->TryTakeOrLoad(dependency); // |dependency_index| may be null if there is no cache for it but // another file has already started importing it. if (!dependency_index) continue; result.push_back(Index_DoIdMap(std::move(dependency_index), cache_manager, perf, is_interactive, false /*write_to_disk*/)); } QueueManager::instance()->do_id_map.EnqueueAll(std::move(result)); return CacheLoadResult::DoNotParse; } std::vector<FileContents> PreloadFileContents( const std::shared_ptr<ICacheManager>& cache_manager, const Project::Entry& entry, const std::string& entry_contents, const std::string& path_to_index) { // Load file contents for all dependencies into memory. If the dependencies // for the file changed we may not end up using all of the files we // preloaded. If a new dependency was added the indexer will grab the file // contents as soon as possible. // // We do this to minimize the race between indexing a file and capturing the // file contents. // // TODO: We might be able to optimize perf by only copying for files in // working_files. We can pass that same set of files to the indexer as // well. We then default to a fast file-copy if not in working set. // index->file_contents comes from cache, so we need to check if that cache is // still valid. if so, we can use it, otherwise we need to load from disk. auto get_latest_content = [](const std::string& path, int64_t cached_time, const std::string& cached) -> std::string { optional<int64_t> mod_time = GetLastModificationTime(path); if (!mod_time) return ""; if (*mod_time == cached_time) return cached; optional<std::string> fresh_content = ReadContent(path); if (!fresh_content) { LOG_S(ERROR) << "Failed to load content for " << path; return ""; } return *fresh_content; }; std::vector<FileContents> file_contents; file_contents.push_back(FileContents(entry.filename, entry_contents)); cache_manager->IterateLoadedCaches([&](IndexFile* index) { if (index->path == entry.filename) return; file_contents.push_back(FileContents( index->path, get_latest_content(index->path, index->last_modification_time, index->file_contents))); }); return file_contents; } void ParseFile(Config* config, DiagnosticsEngine* diag_engine, WorkingFiles* working_files, FileConsumerSharedState* file_consumer_shared, TimestampManager* timestamp_manager, IModificationTimestampFetcher* modification_timestamp_fetcher, ImportManager* import_manager, IIndexer* indexer, const Index_Request& request, const Project::Entry& entry) { // If the file is inferred, we may not actually be able to parse that file // directly (ie, a header file, which are not listed in the project). If this // file is inferred, then try to use the file which originally imported it. std::string path_to_index = entry.filename; if (entry.is_inferred) { IndexFile* entry_cache = request.cache_manager->TryLoad(entry.filename); if (entry_cache) path_to_index = entry_cache->import_file; } // Try to load the file from cache. if (TryLoadFromCache(file_consumer_shared, timestamp_manager, modification_timestamp_fetcher, import_manager, request.cache_manager, request.is_interactive, entry, path_to_index) == CacheLoadResult::DoNotParse) { return; } LOG_S(INFO) << "Parsing " << path_to_index; std::vector<FileContents> file_contents = PreloadFileContents( request.cache_manager, entry, request.contents, path_to_index); std::vector<Index_DoIdMap> result; PerformanceImportFile perf; auto indexes = indexer->Index(config, file_consumer_shared, path_to_index, entry.args, file_contents, &perf); if (!indexes) { if (config->index.enabled && !std::holds_alternative<std::monostate>(request.id)) { Out_Error out; out.id = request.id; out.error.code = lsErrorCodes::InternalError; out.error.message = "Failed to index " + path_to_index; QueueManager::WriteStdout(kMethodType_Unknown, out); } return; } for (std::unique_ptr<IndexFile>& new_index : *indexes) { Timer time; // Only emit diagnostics for non-interactive sessions, which makes it easier // to identify indexing problems. For interactive sessions, diagnostics are // handled by code completion. if (!request.is_interactive) diag_engine->Publish(working_files, new_index->path, new_index->diagnostics_); // When main thread does IdMap request it will request the previous index if // needed. LOG_S(INFO) << "Emitting index result for " << new_index->path; result.push_back(Index_DoIdMap(std::move(new_index), request.cache_manager, perf, request.is_interactive, true /*write_to_disk*/)); } QueueManager::instance()->do_id_map.EnqueueAll(std::move(result), request.is_interactive); } bool IndexMain_DoParse( Config* config, DiagnosticsEngine* diag_engine, WorkingFiles* working_files, FileConsumerSharedState* file_consumer_shared, TimestampManager* timestamp_manager, IModificationTimestampFetcher* modification_timestamp_fetcher, ImportManager* import_manager, IIndexer* indexer) { auto* queue = QueueManager::instance(); optional<Index_Request> request = queue->index_request.TryPopFront(); if (!request) return false; Project::Entry entry; entry.filename = request->path; entry.args = request->args; ParseFile(config, diag_engine, working_files, file_consumer_shared, timestamp_manager, modification_timestamp_fetcher, import_manager, indexer, request.value(), entry); return true; } bool IndexMain_DoCreateIndexUpdate(TimestampManager* timestamp_manager) { auto* queue = QueueManager::instance(); bool did_work = false; IterationLoop loop; while (loop.Next()) { optional<Index_OnIdMapped> response = queue->on_id_mapped.TryPopFront(); if (!response) return did_work; did_work = true; Timer time; IdMap* previous_id_map = nullptr; IndexFile* previous_index = nullptr; if (response->previous) { previous_id_map = response->previous->ids.get(); previous_index = response->previous->file.get(); } // Build delta update. IndexUpdate update = IndexUpdate::CreateDelta(previous_id_map, response->current->ids.get(), previous_index, response->current->file.get()); response->perf.index_make_delta = time.ElapsedMicrosecondsAndReset(); LOG_S(INFO) << "Built index update for " << response->current->file->path << " (is_delta=" << !!response->previous << ")"; // Write current index to disk if requested. if (response->write_to_disk) { LOG_S(INFO) << "Writing cached index to disk for " << response->current->file->path; time.Reset(); response->cache_manager->WriteToCache(*response->current->file); response->perf.index_save_to_disk = time.ElapsedMicrosecondsAndReset(); timestamp_manager->UpdateCachedModificationTime( response->current->file->path, response->current->file->last_modification_time); } #if false #define PRINT_SECTION(name) \ if (response->perf.name) { \ total += response->perf.name; \ output << " " << #name << ": " << FormatMicroseconds(response->perf.name); \ } std::stringstream output; long long total = 0; output << "[perf]"; PRINT_SECTION(index_parse); PRINT_SECTION(index_build); PRINT_SECTION(index_save_to_disk); PRINT_SECTION(index_load_cached); PRINT_SECTION(querydb_id_map); PRINT_SECTION(index_make_delta); output << "\n total: " << FormatMicroseconds(total); output << " path: " << response->current_index->path; LOG_S(INFO) << output.rdbuf(); #undef PRINT_SECTION if (response->is_interactive) LOG_S(INFO) << "Applying IndexUpdate" << std::endl << update.ToString(); #endif Index_OnIndexed reply(std::move(update), response->perf); queue->on_indexed.PushBack(std::move(reply), response->is_interactive); } return did_work; } bool IndexMain_LoadPreviousIndex() { auto* queue = QueueManager::instance(); optional<Index_DoIdMap> response = queue->load_previous_index.TryPopFront(); if (!response) return false; response->previous = response->cache_manager->TryTakeOrLoad(response->current->path); LOG_IF_S(ERROR, !response->previous) << "Unable to load previous index for already imported index " << response->current->path; queue->do_id_map.PushBack(std::move(*response)); return true; } bool IndexMergeIndexUpdates() { auto* queue = QueueManager::instance(); optional<Index_OnIndexed> root = queue->on_indexed.TryPopBack(); if (!root) return false; bool did_merge = false; IterationLoop loop; while (loop.Next()) { optional<Index_OnIndexed> to_join = queue->on_indexed.TryPopBack(); if (!to_join) break; did_merge = true; // Timer time; root->update.Merge(std::move(to_join->update)); // time.ResetAndPrint("Joined querydb updates for files: " + // StringJoinMap(root->update.files_def_update, //[](const QueryFile::DefUpdate& update) { // return update.path; //})); } queue->on_indexed.PushFront(std::move(*root)); return did_merge; } } // namespace ImportPipelineStatus::ImportPipelineStatus() : num_active_threads(0), next_progress_output(0) {} // Index a file using an already-parsed translation unit from code completion. // Since most of the time for indexing a file comes from parsing, we can do // real-time indexing. // TODO: add option to disable this. void IndexWithTuFromCodeCompletion( Config* config, FileConsumerSharedState* file_consumer_shared, ClangTranslationUnit* tu, const std::vector<CXUnsavedFile>& file_contents, const std::string& path, const std::vector<std::string>& args) { file_consumer_shared->Reset(path); PerformanceImportFile perf; ClangIndex index; auto indexes = ParseWithTu(config, file_consumer_shared, &perf, tu, &index, path, args, file_contents); if (!indexes) return; std::vector<Index_DoIdMap> result; for (std::unique_ptr<IndexFile>& new_index : *indexes) { Timer time; std::shared_ptr<ICacheManager> cache_manager; assert(false && "FIXME cache_manager"); // When main thread does IdMap request it will request the previous index if // needed. LOG_S(INFO) << "Emitting index result for " << new_index->path; result.push_back(Index_DoIdMap(std::move(new_index), cache_manager, perf, true /*is_interactive*/, true /*write_to_disk*/)); } LOG_IF_S(WARNING, result.size() > 1) << "Code completion index update generated more than one index"; QueueManager::instance()->do_id_map.EnqueueAll(std::move(result)); } void Indexer_Main(Config* config, DiagnosticsEngine* diag_engine, FileConsumerSharedState* file_consumer_shared, TimestampManager* timestamp_manager, ImportManager* import_manager, ImportPipelineStatus* status, Project* project, WorkingFiles* working_files, MultiQueueWaiter* waiter) { RealModificationTimestampFetcher modification_timestamp_fetcher; auto* queue = QueueManager::instance(); // Build one index per-indexer, as building the index acquires a global lock. auto indexer = IIndexer::MakeClangIndexer(); while (true) { bool did_work = false; { ActiveThread active_thread(config, status); // TODO: process all off IndexMain_DoIndex before calling // IndexMain_DoCreateIndexUpdate for better icache behavior. We need to // have some threads spinning on both though otherwise memory usage will // get bad. // We need to make sure to run both IndexMain_DoParse and // IndexMain_DoCreateIndexUpdate so we don't starve querydb from doing any // work. Running both also lets the user query the partially constructed // index. did_work = IndexMain_DoParse(config, diag_engine, working_files, file_consumer_shared, timestamp_manager, &modification_timestamp_fetcher, import_manager, indexer.get()) || did_work; did_work = IndexMain_DoCreateIndexUpdate(timestamp_manager) || did_work; did_work = IndexMain_LoadPreviousIndex() || did_work; // Nothing to index and no index updates to create, so join some already // created index updates to reduce work on querydb thread. if (!did_work) did_work = IndexMergeIndexUpdates() || did_work; } // We didn't do any work, so wait for a notification. if (!did_work) { waiter->Wait(&queue->on_indexed, &queue->index_request, &queue->on_id_mapped, &queue->load_previous_index); } } } namespace { void QueryDb_DoIdMap(QueueManager* queue, QueryDatabase* db, ImportManager* import_manager, Index_DoIdMap* request) { assert(request->current); // If the request does not have previous state and we have already imported // it, load the previous state from disk and rerun IdMap logic later. Do not // do this if we have already attempted in the past. if (!request->load_previous && !request->previous && db->usr_to_file.find(NormalizedPath(request->current->path)) != db->usr_to_file.end()) { assert(!request->load_previous); request->load_previous = true; queue->load_previous_index.PushBack(std::move(*request)); return; } // Check if the file is already being imported into querydb. If it is, drop // the request. // // Note, we must do this *after* we have checked for the previous index, // otherwise we will never actually generate the IdMap. if (!import_manager->StartQueryDbImport(request->current->path)) { LOG_S(INFO) << "Dropping index as it is already being imported for " << request->current->path; return; } Index_OnIdMapped response(request->cache_manager, request->perf, request->is_interactive, request->write_to_disk); Timer time; auto make_map = [db](std::unique_ptr<IndexFile> file) -> std::unique_ptr<Index_OnIdMapped::File> { if (!file) return nullptr; auto id_map = std::make_unique<IdMap>(db, file->id_cache); return std::make_unique<Index_OnIdMapped::File>(std::move(file), std::move(id_map)); }; response.current = make_map(std::move(request->current)); response.previous = make_map(std::move(request->previous)); response.perf.querydb_id_map = time.ElapsedMicrosecondsAndReset(); queue->on_id_mapped.PushBack(std::move(response)); } void QueryDb_OnIndexed(QueueManager* queue, QueryDatabase* db, ImportManager* import_manager, ImportPipelineStatus* status, SemanticHighlightSymbolCache* semantic_cache, WorkingFiles* working_files, Index_OnIndexed* response) { Timer time; db->ApplyIndexUpdate(&response->update); time.ResetAndPrint("Applying index update for " + StringJoinMap(response->update.files_def_update, [](const QueryFile::DefUpdate& value) { return value.value.path; })); // Update indexed content, inactive lines, and semantic highlighting. for (auto& updated_file : response->update.files_def_update) { WorkingFile* working_file = working_files->GetFileByFilename(updated_file.value.path); if (working_file) { // Update indexed content. working_file->SetIndexContent(updated_file.file_content); // Inactive lines. EmitInactiveLines(working_file, updated_file.value.inactive_regions); // Semantic highlighting. QueryFileId file_id = db->usr_to_file[NormalizedPath(working_file->filename)]; QueryFile* file = &db->files[file_id.id]; EmitSemanticHighlighting(db, semantic_cache, working_file, file); } // Mark the files as being done in querydb stage after we apply the index // update. import_manager->DoneQueryDbImport(updated_file.value.path); } } } // namespace bool QueryDb_ImportMain(Config* config, QueryDatabase* db, ImportManager* import_manager, ImportPipelineStatus* status, SemanticHighlightSymbolCache* semantic_cache, WorkingFiles* working_files) { auto* queue = QueueManager::instance(); ActiveThread active_thread(config, status); bool did_work = false; IterationLoop loop; while (loop.Next()) { optional<Index_DoIdMap> request = queue->do_id_map.TryPopFront(); if (!request) break; did_work = true; QueryDb_DoIdMap(queue, db, import_manager, &*request); } loop.Reset(); while (loop.Next()) { optional<Index_OnIndexed> response = queue->on_indexed.TryPopFront(); if (!response) break; did_work = true; QueryDb_OnIndexed(queue, db, import_manager, status, semantic_cache, working_files, &*response); } return did_work; } TEST_SUITE("ImportPipeline") { struct Fixture { Fixture() { QueueManager::Init(&querydb_waiter, &indexer_waiter, &stdout_waiter); queue = QueueManager::instance(); cache_manager = ICacheManager::MakeFake({}); indexer = IIndexer::MakeTestIndexer({}); diag_engine.Init(&config); } bool PumpOnce() { return IndexMain_DoParse(&config, &diag_engine, &working_files, &file_consumer_shared, &timestamp_manager, &modification_timestamp_fetcher, &import_manager, indexer.get()); } void MakeRequest(const std::string& path, const std::vector<std::string>& args = {}, bool is_interactive = false, const std::string& contents = "void foo();") { queue->index_request.PushBack( Index_Request(path, args, is_interactive, contents, cache_manager)); } MultiQueueWaiter querydb_waiter; MultiQueueWaiter indexer_waiter; MultiQueueWaiter stdout_waiter; QueueManager* queue = nullptr; Config config; DiagnosticsEngine diag_engine; WorkingFiles working_files; FileConsumerSharedState file_consumer_shared; TimestampManager timestamp_manager; FakeModificationTimestampFetcher modification_timestamp_fetcher; ImportManager import_manager; std::shared_ptr<ICacheManager> cache_manager; std::unique_ptr<IIndexer> indexer; }; TEST_CASE_FIXTURE(Fixture, "FileNeedsParse") { auto check = [&](const std::string& file, bool is_dependency = false, bool is_interactive = false, const std::vector<std::string>& old_args = {}, const std::vector<std::string>& new_args = {}) { std::unique_ptr<IndexFile> opt_previous_index; if (!old_args.empty()) { opt_previous_index = std::make_unique<IndexFile>("---.cc", "<empty>"); opt_previous_index->args = old_args; } optional<std::string> from; if (is_dependency) from = std::string("---.cc"); return FileNeedsParse(is_interactive /*is_interactive*/, &timestamp_manager, &modification_timestamp_fetcher, &import_manager, cache_manager, opt_previous_index.get(), file, new_args, from); }; // A file with no timestamp is not imported, since this implies the file no // longer exists on disk. modification_timestamp_fetcher.entries["bar.h"] = nullopt; REQUIRE(check("bar.h", false /*is_dependency*/) == ShouldParse::NoSuchFile); // A dependency is only imported once. modification_timestamp_fetcher.entries["foo.h"] = 5; REQUIRE(check("foo.h", true /*is_dependency*/) == ShouldParse::Yes); REQUIRE(check("foo.h", true /*is_dependency*/) == ShouldParse::No); // An interactive dependency is imported. REQUIRE(check("foo.h", true /*is_dependency*/) == ShouldParse::No); REQUIRE(check("foo.h", true /*is_dependency*/, true /*is_interactive*/) == ShouldParse::Yes); // A file whose timestamp has not changed is not imported. When the // timestamp changes (either forward or backward) it is reimported. auto check_timestamp_change = [&](int64_t timestamp) { modification_timestamp_fetcher.entries["aa.cc"] = timestamp; REQUIRE(check("aa.cc") == ShouldParse::Yes); REQUIRE(check("aa.cc") == ShouldParse::Yes); REQUIRE(check("aa.cc") == ShouldParse::Yes); timestamp_manager.UpdateCachedModificationTime("aa.cc", timestamp); REQUIRE(check("aa.cc") == ShouldParse::No); }; check_timestamp_change(5); check_timestamp_change(6); check_timestamp_change(5); check_timestamp_change(4); // Argument change implies reimport, even if timestamp has not changed. timestamp_manager.UpdateCachedModificationTime("aa.cc", 5); modification_timestamp_fetcher.entries["aa.cc"] = 5; REQUIRE(check("aa.cc", false /*is_dependency*/, false /*is_interactive*/, {"b"} /*old_args*/, {"b", "a"} /*new_args*/) == ShouldParse::Yes); } // FIXME: validate other state like timestamp_manager, etc. // FIXME: add more interesting tests that are not the happy path // FIXME: test // - IndexMain_DoCreateIndexUpdate // - IndexMain_LoadPreviousIndex // - QueryDb_ImportMain TEST_CASE_FIXTURE(Fixture, "index request with zero results") { indexer = IIndexer::MakeTestIndexer({IIndexer::TestEntry{"foo.cc", 0}}); MakeRequest("foo.cc"); REQUIRE(queue->index_request.Size() == 1); REQUIRE(queue->do_id_map.Size() == 0); PumpOnce(); REQUIRE(queue->index_request.Size() == 0); REQUIRE(queue->do_id_map.Size() == 0); REQUIRE(file_consumer_shared.used_files.empty()); } TEST_CASE_FIXTURE(Fixture, "one index request") { indexer = IIndexer::MakeTestIndexer({IIndexer::TestEntry{"foo.cc", 100}}); MakeRequest("foo.cc"); REQUIRE(queue->index_request.Size() == 1); REQUIRE(queue->do_id_map.Size() == 0); PumpOnce(); REQUIRE(queue->index_request.Size() == 0); REQUIRE(queue->do_id_map.Size() == 100); REQUIRE(file_consumer_shared.used_files.empty()); } TEST_CASE_FIXTURE(Fixture, "multiple index requests") { indexer = IIndexer::MakeTestIndexer( {IIndexer::TestEntry{"foo.cc", 100}, IIndexer::TestEntry{"bar.cc", 5}}); MakeRequest("foo.cc"); MakeRequest("bar.cc"); REQUIRE(queue->index_request.Size() == 2); REQUIRE(queue->do_id_map.Size() == 0); while (PumpOnce()) { } REQUIRE(queue->index_request.Size() == 0); REQUIRE(queue->do_id_map.Size() == 105); REQUIRE(file_consumer_shared.used_files.empty()); } }
36.376196
82
0.661116
[ "vector" ]
4c0748af032d651da22be18a09a9e772ea4d887c
20,057
cpp
C++
shared/ClanLib-2.0/Sources/Core/Math/outline_triangulator_generic.cpp
iProgramMC/proton
1c383134b44a22cebab8e8db1afb17afd59dd543
[ "XFree86-1.1" ]
47
2018-07-30T12:05:15.000Z
2022-03-31T04:12:03.000Z
shared/ClanLib-2.0/Sources/Core/Math/outline_triangulator_generic.cpp
iProgramMC/proton
1c383134b44a22cebab8e8db1afb17afd59dd543
[ "XFree86-1.1" ]
11
2019-03-31T13:05:10.000Z
2021-11-03T11:37:18.000Z
shared/ClanLib-2.0/Sources/Core/Math/outline_triangulator_generic.cpp
iProgramMC/proton
1c383134b44a22cebab8e8db1afb17afd59dd543
[ "XFree86-1.1" ]
16
2019-07-09T07:59:00.000Z
2022-02-25T15:49:06.000Z
/* ** ClanLib SDK ** Copyright (c) 1997-2010 The ClanLib Team ** ** This software is provided 'as-is', without any express or implied ** warranty. In no event will the authors be held liable for any damages ** arising from the use of this software. ** ** Permission is granted to anyone to use this software for any purpose, ** including commercial applications, and to alter it and redistribute it ** freely, subject to the following restrictions: ** ** 1. The origin of this software must not be misrepresented; you must not ** claim that you wrote the original software. If you use this software ** in a product, an acknowledgment in the product documentation would be ** appreciated but is not required. ** 2. Altered source versions must be plainly marked as such, and must not be ** misrepresented as being the original software. ** 3. This notice may not be removed or altered from any source distribution. ** ** Note: Some of the libraries ClanLib may link to may have additional ** requirements or restrictions. ** ** File Author(s): ** ** Magnus Norddahl */ #include "Core/precomp.h" #include "outline_triangulator_generic.h" #include "API/Core/Math/delauney_triangulator.h" #include "API/Core/Math/line_math.h" #include <list> #include <algorithm> ///////////////////////////////////////////////////////////////////////////// // CL_OutlineTriangulator_Generic construction: CL_OutlineTriangulator_Generic::CL_OutlineTriangulator_Generic() { } CL_OutlineTriangulator_Generic::~CL_OutlineTriangulator_Generic() { } ///////////////////////////////////////////////////////////////////////////// // CL_OutlineTriangulator_Generic attributes: ///////////////////////////////////////////////////////////////////////////// // CL_OutlineTriangulator_Generic operations: void CL_OutlineTriangulator_Generic::triangulate() { // Order vertices: std::vector<CL_OutlineTriangulator_Vertex *> vertices; create_ordered_vertex_list(vertices); // 1. Create initial triangulation: CL_DelauneyTriangulator delauney; std::vector<CL_OutlineTriangulator_Vertex *>::size_type index_vertices, num_vertices; num_vertices = vertices.size(); for (index_vertices = 0; index_vertices < num_vertices; index_vertices++) { vertices[index_vertices]->num_triangles = 0; vertices[index_vertices]->extra = 0; vertices[index_vertices]->triangles = 0; delauney.add_vertex( vertices[index_vertices]->x, vertices[index_vertices]->y, vertices[index_vertices]); } delauney.generate(); // 2. Link triangles to vertices: const std::vector<CL_DelauneyTriangulator_Triangle> &triangles = delauney.get_triangles(); std::vector<CL_DelauneyTriangulator_Triangle>::size_type index_triangles, num_triangles; num_triangles = triangles.size(); for (index_triangles = 0; index_triangles < num_triangles; index_triangles++) { CL_OutlineTriangulator_Vertex *data_A = (CL_OutlineTriangulator_Vertex *) triangles[index_triangles].vertex_A->data; CL_OutlineTriangulator_Vertex *data_B = (CL_OutlineTriangulator_Vertex *) triangles[index_triangles].vertex_B->data; CL_OutlineTriangulator_Vertex *data_C = (CL_OutlineTriangulator_Vertex *) triangles[index_triangles].vertex_C->data; data_A->num_triangles++; data_B->num_triangles++; data_C->num_triangles++; } CL_DelauneyTriangulator_Triangle const **links = new CL_DelauneyTriangulator_Triangle const *[num_triangles]; int pos = 0; for (index_vertices = 0; index_vertices < num_vertices; index_vertices++) { vertices[index_vertices]->data = links+pos; pos += vertices[index_vertices]->num_triangles; vertices[index_vertices]->num_triangles = 0; } for (index_triangles = 0; index_triangles < num_triangles; index_triangles++) { CL_OutlineTriangulator_Vertex *data_A = (CL_OutlineTriangulator_Vertex *) triangles[index_triangles].vertex_A->data; CL_OutlineTriangulator_Vertex *data_B = (CL_OutlineTriangulator_Vertex *) triangles[index_triangles].vertex_B->data; CL_OutlineTriangulator_Vertex *data_C = (CL_OutlineTriangulator_Vertex *) triangles[index_triangles].vertex_C->data; data_A->triangles[data_A->num_triangles++] = &triangles[index_triangles]; data_B->triangles[data_B->num_triangles++] = &triangles[index_triangles]; data_C->triangles[data_C->num_triangles++] = &triangles[index_triangles]; } // 3. Walk contours. Check if any triangles intersect with each line segment. // 3a. Add each triangle's point that intersect to vertex buffer. // 3b. Divide vertices into two lists, one for left and one for right side of line segment. // 3c. Delauney triangulate each point list. // 3d. Update links to include new triangles. // 3e. Add the resulting triangles to triangles list. std::list<CL_DelauneyTriangulator_Triangle const *> final_triangles; for (index_triangles = 0; index_triangles < num_triangles; index_triangles++) final_triangles.push_back(&triangles[index_triangles]); std::vector<CL_DelauneyTriangulator_Triangle const **> added_links; std::vector<CL_DelauneyTriangulator> extra_triangulations; std::vector<CL_OutlineTriangulator_Polygon>::size_type index_polygons, num_polygons; num_polygons = polygons.size(); for (index_polygons = 0; index_polygons < num_polygons; index_polygons++) { CL_OutlineTriangulator_Polygon &cur_poly = polygons[index_polygons]; std::vector<CL_OutlineTriangulator_Contour>::size_type index_contours, num_contours; num_contours = cur_poly.contours.size(); for (index_contours = 0; index_contours < num_contours; index_contours++) { CL_OutlineTriangulator_Contour &cur_contour = cur_poly.contours[index_contours]; std::vector<CL_OutlineTriangulator_Vertex>::size_type index_vertices, num_vertices; num_vertices = cur_contour.vertices.size(); for (index_vertices = 1; index_vertices < num_vertices; index_vertices++) { CL_OutlineTriangulator_Vertex *vertex_1 = &cur_contour.vertices[index_vertices-1]; CL_OutlineTriangulator_Vertex *vertex_2 = &cur_contour.vertices[index_vertices]; CL_OutlineTriangulator_Collision collision = find_colliding_triangles(vertex_1, vertex_2); if (collision.triangles.empty()) continue; std::vector<CL_OutlineTriangulator_Vertex *>::size_type index_points, num_points; // Triangulate left and right sides: CL_DelauneyTriangulator delauney_first; num_points = collision.first.size(); for (index_points = 0; index_points < num_points; index_points++) { delauney.add_vertex( collision.first[index_points]->x, collision.first[index_points]->y, collision.first[index_points]); } delauney_first.generate(); CL_DelauneyTriangulator delauney_second; num_points = collision.second.size(); for (index_points = 0; index_points < num_points; index_points++) { delauney.add_vertex( collision.second[index_points]->x, collision.second[index_points]->y, collision.second[index_points]); } delauney_second.generate(); extra_triangulations.push_back(delauney_first); extra_triangulations.push_back(delauney_second); // Remove old triangles: std::vector<CL_DelauneyTriangulator_Triangle *>::size_type index_old_triangles, size_old_triangles; size_old_triangles = collision.triangles.size(); for (index_old_triangles = 0; index_old_triangles < size_old_triangles; index_old_triangles++) { remove_triangle(collision.triangles[index_old_triangles]); final_triangles.remove(collision.triangles[index_old_triangles]); } // Add new triangles: CL_DelauneyTriangulator_Triangle const **new_links = add_triangles(delauney_first, delauney_second); added_links.push_back(new_links); const std::vector<CL_DelauneyTriangulator_Triangle> &triangles1 = delauney_first.get_triangles(); const std::vector<CL_DelauneyTriangulator_Triangle> &triangles2 = delauney_second.get_triangles(); std::vector<CL_DelauneyTriangulator_Triangle>::size_type index_triangles, num_triangles1, num_triangles2; num_triangles1 = triangles1.size(); num_triangles2 = triangles2.size(); for (index_triangles = 0; index_triangles < num_triangles1; index_triangles++) final_triangles.push_back(&triangles1[index_triangles]); for (index_triangles = 0; index_triangles < num_triangles2; index_triangles++) final_triangles.push_back(&triangles2[index_triangles]); } } } // 4. Remove outside and hole triangles. // 5. Clean up: delete[] links; std::vector<CL_DelauneyTriangulator_Triangle const **>::size_type index_added_links, size_added_links; size_added_links = added_links.size(); for (index_added_links = 0; index_added_links < size_added_links; index_added_links++) { delete[] added_links[index_added_links]; } // 6. Generate final list: } CL_DelauneyTriangulator_Triangle const **CL_OutlineTriangulator_Generic::add_triangles( CL_DelauneyTriangulator &d1, CL_DelauneyTriangulator &d2) { const std::vector<CL_DelauneyTriangulator_Triangle> &triangles1 = d1.get_triangles(); const std::vector<CL_DelauneyTriangulator_Triangle> &triangles2 = d2.get_triangles(); std::vector<CL_DelauneyTriangulator_Triangle>::size_type index_triangles, num_triangles1, num_triangles2; num_triangles1 = triangles1.size(); for (index_triangles = 0; index_triangles < num_triangles1; index_triangles++) { CL_OutlineTriangulator_Vertex *data_A = (CL_OutlineTriangulator_Vertex *) triangles1[index_triangles].vertex_A->data; CL_OutlineTriangulator_Vertex *data_B = (CL_OutlineTriangulator_Vertex *) triangles1[index_triangles].vertex_B->data; CL_OutlineTriangulator_Vertex *data_C = (CL_OutlineTriangulator_Vertex *) triangles1[index_triangles].vertex_C->data; data_A->extra++; data_B->extra++; data_C->extra++; } num_triangles2 = triangles2.size(); for (index_triangles = 0; index_triangles < num_triangles2; index_triangles++) { CL_OutlineTriangulator_Vertex *data_A = (CL_OutlineTriangulator_Vertex *) triangles2[index_triangles].vertex_A->data; CL_OutlineTriangulator_Vertex *data_B = (CL_OutlineTriangulator_Vertex *) triangles2[index_triangles].vertex_B->data; CL_OutlineTriangulator_Vertex *data_C = (CL_OutlineTriangulator_Vertex *) triangles2[index_triangles].vertex_C->data; data_A->extra++; data_B->extra++; data_C->extra++; } const std::vector<CL_DelauneyTriangulator_Vertex> &vertices1 = d1.get_vertices(); const std::vector<CL_DelauneyTriangulator_Vertex> &vertices2 = d2.get_vertices(); std::vector<CL_DelauneyTriangulator_Vertex *>::size_type index_vertices, num_vertices1, num_vertices2; num_vertices1 = d1.get_vertices().size(); num_vertices2 = d2.get_vertices().size(); int links_needed = 0; for (index_vertices = 0; index_vertices < num_vertices1; index_vertices++) { CL_OutlineTriangulator_Vertex *v = (CL_OutlineTriangulator_Vertex *) vertices1[index_vertices].data; links_needed += v->num_triangles + v->extra; } for (index_vertices = 0; index_vertices < num_vertices2; index_vertices++) { CL_OutlineTriangulator_Vertex *v = (CL_OutlineTriangulator_Vertex *) vertices2[index_vertices].data; links_needed += v->num_triangles + v->extra; } CL_DelauneyTriangulator_Triangle const **links = new CL_DelauneyTriangulator_Triangle const *[links_needed]; int pos = 0; for (index_vertices = 0; index_vertices < num_vertices1; index_vertices++) { CL_OutlineTriangulator_Vertex *v = (CL_OutlineTriangulator_Vertex *) vertices1[index_vertices].data; if (v->extra == 0) continue; for (int i=0; i<v->num_triangles; i++) links[pos+i] = v->triangles[i]; v->data = links+pos; pos += v->num_triangles + v->extra; v->extra = 0; } for (index_vertices = 0; index_vertices < num_vertices2; index_vertices++) { CL_OutlineTriangulator_Vertex *v = (CL_OutlineTriangulator_Vertex *) vertices2[index_vertices].data; if (v->extra == 0) continue; for (int i=0; i<v->num_triangles; i++) links[pos+i] = v->triangles[i]; v->data = links+pos; pos += v->num_triangles + v->extra; v->extra = 0; } for (index_triangles = 0; index_triangles < num_triangles1; index_triangles++) { CL_OutlineTriangulator_Vertex *data_A = (CL_OutlineTriangulator_Vertex *) triangles1[index_triangles].vertex_A->data; CL_OutlineTriangulator_Vertex *data_B = (CL_OutlineTriangulator_Vertex *) triangles1[index_triangles].vertex_B->data; CL_OutlineTriangulator_Vertex *data_C = (CL_OutlineTriangulator_Vertex *) triangles1[index_triangles].vertex_C->data; data_A->triangles[data_A->num_triangles++] = &triangles1[index_triangles]; data_B->triangles[data_B->num_triangles++] = &triangles1[index_triangles]; data_C->triangles[data_C->num_triangles++] = &triangles1[index_triangles]; } for (index_triangles = 0; index_triangles < num_triangles2; index_triangles++) { CL_OutlineTriangulator_Vertex *data_A = (CL_OutlineTriangulator_Vertex *) triangles2[index_triangles].vertex_A->data; CL_OutlineTriangulator_Vertex *data_B = (CL_OutlineTriangulator_Vertex *) triangles2[index_triangles].vertex_B->data; CL_OutlineTriangulator_Vertex *data_C = (CL_OutlineTriangulator_Vertex *) triangles2[index_triangles].vertex_C->data; data_A->triangles[data_A->num_triangles++] = &triangles2[index_triangles]; data_B->triangles[data_B->num_triangles++] = &triangles2[index_triangles]; data_C->triangles[data_C->num_triangles++] = &triangles2[index_triangles]; } return links; } CL_OutlineTriangulator_Collision CL_OutlineTriangulator_Generic::find_colliding_triangles( CL_OutlineTriangulator_Vertex *v1, CL_OutlineTriangulator_Vertex *v2) { CL_OutlineTriangulator_Collision collision; for (int index_triangles = 0; index_triangles < v1->num_triangles; index_triangles++) { CL_OutlineTriangulator_Vertex *vA = (CL_OutlineTriangulator_Vertex *) v1->triangles[index_triangles]->vertex_A->data; CL_OutlineTriangulator_Vertex *vB = (CL_OutlineTriangulator_Vertex *) v1->triangles[index_triangles]->vertex_B->data; CL_OutlineTriangulator_Vertex *vC = (CL_OutlineTriangulator_Vertex *) v1->triangles[index_triangles]->vertex_C->data; // If an edge is same line as the constrained line, there can be no colliding triangles: if ( (v1 == vA && v2 == vB) || (v1 == vB && v2 == vA) || (v1 == vB && v2 == vC) || (v1 == vC && v2 == vB) || (v1 == vC && v2 == vA) || (v1 == vA && v2 == vC)) return collision; bool intersectsA, intersectsB, intersectsC; if (v1 == vA || v1 == vB || v2 == vA || v2 == vB) intersectsA = false; else intersectsA = intersects( v1->x, v1->y, v2->x, v2->y, v1->triangles[index_triangles]->vertex_A->x, v1->triangles[index_triangles]->vertex_A->y, v1->triangles[index_triangles]->vertex_B->x, v1->triangles[index_triangles]->vertex_B->y); if (v1 == vB || v1 == vC || v2 == vB || v2 == vC) intersectsB = false; else intersectsB = intersects( v1->x, v1->y, v2->x, v2->y, v1->triangles[index_triangles]->vertex_B->x, v1->triangles[index_triangles]->vertex_B->y, v1->triangles[index_triangles]->vertex_C->x, v1->triangles[index_triangles]->vertex_C->y); if (v1 == vC || v1 == vA || v2 == vC || v2 == vA) intersectsC = false; else intersectsC = intersects( v1->x, v1->y, v2->x, v2->y, v1->triangles[index_triangles]->vertex_C->x, v1->triangles[index_triangles]->vertex_C->y, v1->triangles[index_triangles]->vertex_A->x, v1->triangles[index_triangles]->vertex_A->y); if (intersectsA == false && intersectsB == false && intersectsC == false) continue; // Collision. Add all points to the correct side of the intersected line: collision.triangles.push_back(v1->triangles[index_triangles]); if (vA == v1 || vA == v2) { collision.first.push_back(vA); collision.second.push_back(vA); } else if (CL_LineMath::point_right_of_line(vA->x, vA->y, v1->x, v1->y, v2->x, v2->y)) { collision.second.push_back(vA); } else { collision.first.push_back(vA); } if (vB == v1 || vB == v2) { collision.first.push_back(vB); collision.second.push_back(vB); } else if (CL_LineMath::point_right_of_line(vB->x, vB->y, v1->x, v1->y, v2->x, v2->y)) { collision.second.push_back(vB); } else { collision.first.push_back(vB); } if (vC == v1 || vC == v2) { collision.first.push_back(vC); collision.second.push_back(vC); } else if (CL_LineMath::point_right_of_line(vC->x, vC->y, v1->x, v1->y, v2->x, v2->y)) { collision.second.push_back(vC); } else { collision.first.push_back(vC); } } return collision; } void CL_OutlineTriangulator_Generic::remove_triangle(CL_DelauneyTriangulator_Triangle const *t) { for (int vertex = 0; vertex < 3; vertex++) { CL_OutlineTriangulator_Vertex *data = 0; switch (vertex) { case 0: data = (CL_OutlineTriangulator_Vertex *) t->vertex_A->data; break; case 1: data = (CL_OutlineTriangulator_Vertex *) t->vertex_B->data; break; case 2: data = (CL_OutlineTriangulator_Vertex *) t->vertex_C->data; break; } for (int index = 0; index < data->num_triangles; index++) { if (data->triangles[index] == t) { for (int index2 = index; index2 < data->num_triangles-1; index2++) { data->triangles[index2] = data->triangles[index2+1]; } index--; data->num_triangles--; } } } } struct CL_CompareVertices { bool operator()(CL_OutlineTriangulator_Vertex *a, CL_OutlineTriangulator_Vertex *b) const { if (a->x == b->x) return a->y < b->y; return a->x < b->x; } }; void CL_OutlineTriangulator_Generic::create_ordered_vertex_list(std::vector<CL_OutlineTriangulator_Vertex *> &vertices) { std::vector<CL_OutlineTriangulator_Polygon>::size_type index_polygons, num_polygons; num_polygons = polygons.size(); for (index_polygons = 0; index_polygons < num_polygons; index_polygons++) { CL_OutlineTriangulator_Polygon &cur_poly = polygons[index_polygons]; std::vector<CL_OutlineTriangulator_Contour>::size_type index_contours, num_contours; num_contours = cur_poly.contours.size(); for (index_contours = 0; index_contours < num_contours; index_contours++) { CL_OutlineTriangulator_Contour &cur_contour = cur_poly.contours[index_contours]; std::vector<CL_OutlineTriangulator_Vertex>::size_type index_vertices, num_vertices; num_vertices = cur_contour.vertices.size(); for (index_vertices = 0; index_vertices < num_vertices; index_vertices++) { vertices.push_back(&cur_contour.vertices[index_vertices]); } } } // Sort list: std::sort(vertices.begin(), vertices.end(), CL_CompareVertices()); // Remove duplicates: std::vector<CL_OutlineTriangulator_Vertex *>::iterator it = vertices.begin(); if (it == vertices.end()) return; float last_x = (*it)->x; float last_y = (*it)->y; ++it; while (it != vertices.end()) { if (last_x == (*it)->x && last_y == (*it)->y) { it = vertices.erase(it); } else { last_x = (*it)->x; last_y = (*it)->y; ++it; } } } bool CL_OutlineTriangulator_Generic::intersects( float Ax, float Ay, float Bx, float By, float Cx, float Cy, float Dx, float Dy) { float denominator = ((Bx-Ax)*(Dy-Cy)-(By-Ay)*(Dx-Cx)); if( denominator == 0 ) // parallell { return false; } float r = ((Ay-Cy)*(Dx-Cx)-(Ax-Cx)*(Dy-Cy)) / denominator; float s = ((Ay-Cy)*(Bx-Ax)-(Ax-Cx)*(By-Ay)) / denominator; if( (s > 0.0 && s < 1.0) && (r > 0.0 && r < 1.0) ) return true; return false; } ///////////////////////////////////////////////////////////////////////////// // CL_OutlineTriangulator_Generic implementation:
37.073937
120
0.70539
[ "vector", "3d" ]
4c0bd4da1b9c2e6e0958958a05cf0fe63de3a5c2
4,838
cpp
C++
TravellingSalesman/Tour.cpp
SebastianTroy/salesman
cf9154080d5018fe1d38d60bcd7cee7b4ab8a4fb
[ "MIT" ]
null
null
null
TravellingSalesman/Tour.cpp
SebastianTroy/salesman
cf9154080d5018fe1d38d60bcd7cee7b4ab8a4fb
[ "MIT" ]
null
null
null
TravellingSalesman/Tour.cpp
SebastianTroy/salesman
cf9154080d5018fe1d38d60bcd7cee7b4ab8a4fb
[ "MIT" ]
null
null
null
#include "Tour.h" #include <QLine> Tour::Tour(QRect area, QObject* parent) : QObject(parent) , currentArea_(area) { } void Tour::AddStop(QPointF stop) { tour_.push_back(stop); emit onTourUpdated(); } void Tour::AddRandomStops(unsigned count) { for (unsigned i = 0; i < count; ++i) { AddStop(QPointF(RandomNumber(0, currentArea_.width()), RandomNumber(0, currentArea_.height()))); } } void Tour::SetLooped(bool looped) { looped_ = looped; emit onTourUpdated(); } void Tour::SetTour(std::vector<QPointF>&& newTour) { tour_ = std::move(newTour); } void Tour::ScaleTo(QRect area) { double xScale = static_cast<double>(area.width()) / currentArea_.width(); double yScale = static_cast<double>(area.height()) / currentArea_.height(); for (QPointF& stop : tour_) { stop.rx() *= xScale; stop.ry() *= yScale; } currentArea_ = area; } void Tour::Shuffle() { std::random_shuffle(std::begin(tour_), std::end(tour_)); emit onTourUpdated(); } void Tour::MoveStopUnder(QLineF translation, int radius) { for (QPointF& stop : tour_) { if (GetDistance(stop, translation.p1()) <= radius) { stop += (translation.p2() - translation.p1()); emit onTourUpdated(); return; } } } void Tour::RemoveStopsUnder(QPointF location, int radius) { std::erase_if(tour_, [&](QPointF stop) { return GetDistance(stop, location) <= radius; }); emit onTourUpdated(); } void Tour::CullStopsOutOfBounds() { std::erase_if(tour_, [&](QPointF stop) { return !currentArea_.contains(stop.toPoint()); }); emit onTourUpdated(); } void Tour::Clear() { tour_.clear(); emit onTourUpdated(); } void Tour::RandomiseStopLocation() { if (tour_.size() > 1) { const auto& [ indexA, indexB ] = RandomUniqueTourIndices();{} QPointF copy = tour_[indexA]; auto iter = std::begin(tour_); std::advance(iter, indexA); tour_.erase(iter); iter = std::begin(tour_); std::advance(iter, indexB); tour_.insert(iter, copy); } } void Tour::RandomiseStopsLocations() { if (tour_.size() > 1) { unsigned count = RandomNumber(1, tour_.size()); for (unsigned i = 0; i < count; ++i) { RandomiseStopLocation(); } } } void Tour::ReverseSection() { if (tour_.size() > 1) { auto [ start, end ] = RandomUniqueTourIndices();{} if (start > end) { std::swap(start, end); } while (end - start > 0) { std::swap(tour_[start], tour_[end]); ++start; --end; } } } void Tour::MoveSection() { if (tour_.size() > 1) { auto [ start, end ] = RandomUniqueTourIndices();{} if (start > end) { std::swap(start, end); } std::vector<QPointF> section; std::copy(std::cbegin(tour_) + start, std::cbegin(tour_) + end, std::back_inserter(section)); tour_.erase(std::begin(tour_) + start, std::begin(tour_) + end); std::move(std::cbegin(section), std::cend(section), std::back_inserter(tour_)); } } void Tour::SwapStops() { if (tour_.size() > 1) { const auto& [ indexA, indexB ] = RandomUniqueTourIndices();{} QPointF& a = tour_[indexA]; QPointF& b = tour_[indexB]; std::swap(a, b); } } std::vector<QPointF> Tour::GetTour() const { return tour_; } double Tour::GetDistance() const { double distance = 0; QPointF lastStop = tour_.empty() ? QPointF() : tour_.front(); ForEachStop([&](const QPointF& stop) { distance += GetDistance(lastStop, stop); lastStop = stop; }); if (looped_ && tour_.size() >= 2) { distance += GetDistance(tour_.front(), tour_.back()); } return distance; } bool Tour::IsLooped() const { return looped_; } void Tour::ForEachStop(const std::function<void (const QPointF&)>& action) const { for (const auto& stop : tour_) { std::invoke(action, stop); } } double Tour::GetDistance(const QPointF& a, const QPointF& b) const { return std::sqrt(std::pow(a.x() - b.x(), 2) + std::pow(a.y() - b.y(), 2)); } int Tour::RandomTourIndex() const { return RandomNumber(0, tour_.size() - 1); } std::pair<int, int> Tour::RandomUniqueTourIndices() const { return RandomUniqueNumbers(0, tour_.size() - 1); } int Tour::RandomNumber(int min, int max) { std::uniform_int_distribution<int> distribution(min, max); return distribution(entropy_); } std::pair<int, int> Tour::RandomUniqueNumbers(int min, int max) { size_t a = RandomNumber(min, max); size_t b = RandomNumber(min, max); while (a == b) { b = RandomNumber(min, max); } return std::make_pair(a, b); }
22.607477
104
0.58764
[ "vector" ]
4c0e14d6c5b47b0d5e0afca357e1d638e57b28aa
9,466
cpp
C++
catkin_ws/src/o2ac_examples/src/grasp_example.cpp
mitdo/o2ac-ur
74c82a54a693bf6a3fc995ff63e7c91ac1fda6fd
[ "MIT" ]
32
2021-09-02T12:29:47.000Z
2022-03-30T21:44:10.000Z
catkin_ws/src/o2ac_examples/src/grasp_example.cpp
kroglice/o2ac-ur
f684f21fd280a22ec061dc5d503801f6fefb2422
[ "MIT" ]
4
2021-09-22T00:51:14.000Z
2022-01-30T11:54:19.000Z
catkin_ws/src/o2ac_examples/src/grasp_example.cpp
kroglice/o2ac-ur
f684f21fd280a22ec061dc5d503801f6fefb2422
[ "MIT" ]
7
2021-11-02T12:26:09.000Z
2022-02-01T01:45:22.000Z
#include "o2ac_helper_functions.h" #include "ros/ros.h" #include <moveit/move_group_interface/move_group_interface.h> #include <moveit/planning_scene_interface/planning_scene_interface.h> #include <tf/transform_listener.h> // Includes the TF conversions #include <moveit_msgs/Grasp.h> // This example spawns an object in the scene and tries to pick and place it. // Based on: // http://docs.ros.org/kinetic/api/moveit_tutorials/html/doc/planning_scene_ros_api/planning_scene_ros_api_tutorial.html // http://docs.ros.org/kinetic/api/moveit_tutorials/html/doc/pick_place/pick_place_tutorial.html // ################################################################ void openGripper(trajectory_msgs::JointTrajectory &posture) { /* Add the knuckle joint of the robotiq gripper. */ posture.joint_names.resize(1); posture.joint_names[0] = "a_bot_robotiq_85_left_knuckle_joint"; /* Set it to some open position, whatever this unit is supposed to be. */ posture.points.resize(1); posture.points[0].positions.resize(1); posture.points[0].positions[0] = 0.04; posture.points[0].time_from_start = ros::Duration(0.5); } void closedGripper(trajectory_msgs::JointTrajectory &posture) { /* Add the knuckle joint of the robotiq gripper. */ posture.joint_names.resize(1); posture.joint_names[0] = "a_bot_robotiq_85_left_knuckle_joint"; /* Set to closed. */ posture.points.resize(1); posture.points[0].positions.resize(1); posture.points[0].positions[0] = 0.5; posture.points[0].time_from_start = ros::Duration(0.5); } void pick(moveit::planning_interface::MoveGroupInterface &move_group) { // Create a vector of grasps to be attempted. // This can test multiple grasps supplied by a grasp generator. std::vector<moveit_msgs::Grasp> grasps; grasps.resize(20); // Setting grasp pose // ++++++++++++++++++++++ // This is the pose of the parent link of the robot's end effector. // The orientation is not tested yet, but hopefully looks down. grasps[0].grasp_pose.header.frame_id = "set2_bin2_4"; grasps[0].grasp_pose.pose.orientation = tf::createQuaternionMsgFromRollPitchYaw(0, M_PI / 12, M_PI); grasps[0].grasp_pose.pose.position.x = -0.01; grasps[0].grasp_pose.pose.position.y = 0.0; grasps[0].grasp_pose.pose.position.z = 0.1; // Setting pre-grasp approach // ++++++++++++++++++++++++++ /* Defined with respect to frame_id */ grasps[0].pre_grasp_approach.direction.header.frame_id = "set2_bin2_4"; /* Direction is set as negative x axis */ grasps[0].pre_grasp_approach.direction.vector.x = -1.0; grasps[0].pre_grasp_approach.min_distance = 0.095; grasps[0].pre_grasp_approach.desired_distance = 0.115; // Setting post-grasp retreat // ++++++++++++++++++++++++++ /* Defined with respect to frame_id */ grasps[0].post_grasp_retreat.direction.header.frame_id = "set2_bin2_4"; /* Direction is set as positive z axis */ grasps[0].post_grasp_retreat.direction.vector.z = 1.0; grasps[0].post_grasp_retreat.min_distance = 0.1; grasps[0].post_grasp_retreat.desired_distance = 0.25; // Fill the Grasp msg with the eef posture before grasp // +++++++++++++++++++++++++++++++++++ openGripper(grasps[0].pre_grasp_posture); // Fill the Grasp msg with the eef posture during grasp // +++++++++++++++++++++++++++++++++++ closedGripper(grasps[0].grasp_posture); for (int i = 1; i < 20; i++) { grasps[i] = grasps[0]; // Alternative: // grasps[i].grasp_pose.pose.orientation = // tf::createQuaternionMsgFromRollPitchYaw(0, M_PI/8 + rand()*M_PI/12, // M_PI); grasps[i].grasp_pose.pose.position.x = // grasps[i].grasp_pose.pose.position.x + rand()*.02; // grasps[i].grasp_pose.pose.position.y = // grasps[i].grasp_pose.pose.position.y; // grasps[i].grasp_pose.pose.position.z = // grasps[i].grasp_pose.pose.position.z + rand()*.02; } // Set support surface move_group.setSupportSurfaceName("set2_bin2_4"); // TODO: This might have to // be an object in the // planning scene, not the // robot definition // Call pick to pick up the object using the grasps given move_group.pick("object", grasps); } void place(moveit::planning_interface::MoveGroupInterface &group) { std::vector<moveit_msgs::PlaceLocation> place_location; place_location.resize(20); // Setting place location pose // +++++++++++++++++++++++++++ place_location[0].place_pose.header.frame_id = "set3_tray_2"; place_location[0].place_pose.pose.orientation = tf::createQuaternionMsgFromRollPitchYaw(M_PI / 2, 0.0, -M_PI / 2); rotatePoseByRPY(0.0, 0.0, M_PI / 2.0, place_location[0].place_pose.pose); /* This pose refers to the center of the object. */ place_location[0].place_pose.pose.position.x = 0; place_location[0].place_pose.pose.position.y = 0; place_location[0].place_pose.pose.position.z = 0.05; // Setting pre-place approach // ++++++++++++++++++++++++++ /* Defined with respect to frame_id */ place_location[0].pre_place_approach.direction.header.frame_id = "set3_tray_2"; /* Direction is set as negative z axis */ place_location[0].pre_place_approach.direction.vector.z = -1.0; place_location[0].pre_place_approach.min_distance = 0.095; place_location[0].pre_place_approach.desired_distance = 0.115; // Setting post-grasp retreat // ++++++++++++++++++++++++++ /* Defined with respect to frame_id */ place_location[0].post_place_retreat.direction.header.frame_id = "set3_tray_2"; /* Direction is set as z axis */ place_location[0].post_place_retreat.direction.vector.z = 1.0; place_location[0].post_place_retreat.min_distance = 0.1; place_location[0].post_place_retreat.desired_distance = 0.25; // Setting posture of eef after placing object // +++++++++++++++++++++++++++++++++++++++++++ /* Similar to the pick case */ openGripper(place_location[0].post_place_posture); for (int i = 1; i < 20; i++) { place_location[i] = place_location[0]; } // Set support surface group.setSupportSurfaceName("set3_tray_2"); // Call place to place the object using the place locations given. group.place("object", place_location); } void addCollisionObjects(moveit::planning_interface::PlanningSceneInterface &planning_scene_interface, bool already_published_object) { if (!already_published_object) { // Creating Environment // ^^^^^^^^^^^^^^^^^^^^ // Create vector to hold a collision object. std::vector<moveit_msgs::CollisionObject> collision_objects; collision_objects.resize(1); // Define the object that we will be manipulating collision_objects[0].header.frame_id = "set2_bin2_4"; collision_objects[0].id = "object"; /* Define the primitive and its dimensions. */ collision_objects[0].primitives.resize(1); collision_objects[0].primitives[0].type = collision_objects[0].primitives[0].BOX; collision_objects[0].primitives[0].dimensions.resize(3); collision_objects[0].primitives[0].dimensions[0] = 0.02; collision_objects[0].primitives[0].dimensions[1] = 0.02; collision_objects[0].primitives[0].dimensions[2] = 0.1; /* Define the pose of the object. */ collision_objects[0].primitive_poses.resize(1); collision_objects[0].primitive_poses[0].position.x = 0; collision_objects[0].primitive_poses[0].position.y = 0; collision_objects[0].primitive_poses[0].position.z = 0.06; collision_objects[0].operation = collision_objects[0].ADD; planning_scene_interface.applyCollisionObjects(collision_objects); } } // ################################################################ int main(int argc, char **argv) { // Initialize ROS ros::init(argc, argv, "CommandRobotMoveit"); ros::NodeHandle nh("~"); // ROS spinner. ros::AsyncSpinner spinner(1); spinner.start(); tf::TransformListener tflistener; std::string movegroup_name, ee_link; bool already_published_object; nh.param<std::string>("move_group", movegroup_name, "a_bot"); nh.param<std::string>("ee_link", ee_link, "a_bot_gripper_tip_link"); nh.param<bool>("already_published_object", already_published_object, false); // Dynamic parameter to choose the rate at which this node should run double ros_rate; nh.param("ros_rate", ros_rate, 0.2); // 0.2 Hz = 5 seconds ros::Rate *loop_rate_ = new ros::Rate(ros_rate); std::string bin_header; // Create MoveGroup moveit::planning_interface::MoveGroupInterface group_a(movegroup_name); moveit::planning_interface::MoveGroupInterface::Plan myplan; // Configure planner group_a.setPlannerId("RRTConnectkConfigDefault"); group_a.setEndEffectorLink(ee_link); moveit::planning_interface::MoveItErrorCode success_plan = moveit_msgs::MoveItErrorCodes::FAILURE, motion_done = moveit_msgs::MoveItErrorCodes::FAILURE; moveit::planning_interface::PlanningSceneInterface planning_scene_interface; group_a.setPlanningTime(45.0); addCollisionObjects(planning_scene_interface, already_published_object); ROS_INFO("Attempting to pick the object."); // Wait a bit for ROS things to initialize ros::WallDuration(1.0).sleep(); pick(group_a); ROS_INFO("Attempting to place the object."); ros::WallDuration(1.0).sleep(); place(group_a); ros::waitForShutdown(); return 0; };
38.016064
120
0.681809
[ "object", "vector" ]
4c0e5359f7cb957ad510383dd5f45dcce6c7efbe
813
cpp
C++
test/cuda_creations_test.cpp
vineelpratap/gtn-1
56a6359dbf5cc2a3855893d57166141703b592d9
[ "MIT" ]
75
2021-06-03T00:37:34.000Z
2022-03-27T08:07:15.000Z
test/cuda_creations_test.cpp
vineelpratap/gtn-1
56a6359dbf5cc2a3855893d57166141703b592d9
[ "MIT" ]
12
2021-08-21T13:23:24.000Z
2022-03-01T02:23:16.000Z
test/cuda_creations_test.cpp
vineelpratap/gtn-1
56a6359dbf5cc2a3855893d57166141703b592d9
[ "MIT" ]
8
2021-06-03T02:29:36.000Z
2022-03-12T00:40:14.000Z
#include "catch.hpp" #include "gtn/graph.h" #include "gtn/creations.h" #include "gtn/utils.h" using namespace gtn; TEST_CASE("test cuda scalar creation", "[cuda creations]") { float weight = static_cast<float>(rand()); auto g = scalarGraph(weight, Device::CUDA).cpu(); CHECK(g.numArcs() == 1); CHECK(g.label(0) == epsilon); CHECK(g.numNodes() == 2); CHECK(g.item() == weight); CHECK(g.calcGrad() == true); CHECK(equal(g, scalarGraph(weight))); } TEST_CASE("test cuda linear creation", "[cuda creations]") { std::vector<int> nodeSizes = {0, 1, 5}; std::vector<int> arcSizes = {0, 1, 5, 10}; for (auto N : nodeSizes) { for (auto M : arcSizes) { auto gDev = linearGraph(M, N, Device::CUDA).cpu(); auto gHost = linearGraph(M, N); CHECK(equal(gDev, gHost)); } } }
26.225806
60
0.621156
[ "vector" ]
4c14d4c3333a02dae29dd54b89dedd0f655b35a2
24,463
cpp
C++
Plugins/org.mitk.gui.qt.igt.app.hummelprotocolmeasurements/src/internal/QmitkIGTTrackingSemiAutomaticMeasurementView.cpp
zhaomengxiao/MITK
a09fd849a4328276806008bfa92487f83a9e2437
[ "BSD-3-Clause" ]
1
2022-03-03T12:03:32.000Z
2022-03-03T12:03:32.000Z
Plugins/org.mitk.gui.qt.igt.app.hummelprotocolmeasurements/src/internal/QmitkIGTTrackingSemiAutomaticMeasurementView.cpp
zhaomengxiao/MITK
a09fd849a4328276806008bfa92487f83a9e2437
[ "BSD-3-Clause" ]
1
2021-12-22T10:19:02.000Z
2021-12-22T10:19:02.000Z
Plugins/org.mitk.gui.qt.igt.app.hummelprotocolmeasurements/src/internal/QmitkIGTTrackingSemiAutomaticMeasurementView.cpp
zhaomengxiao/MITK_lancet
a09fd849a4328276806008bfa92487f83a9e2437
[ "BSD-3-Clause" ]
1
2020-11-27T09:41:18.000Z
2020-11-27T09:41:18.000Z
/*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ // Blueberry #include <berryISelectionService.h> #include <berryIWorkbenchWindow.h> // Qmitk #include "QmitkIGTTrackingSemiAutomaticMeasurementView.h" // Qt #include <QMessageBox> #include <qfiledialog.h> #include <qevent.h> #include <QCheckBox> // MITK #include <mitkNavigationToolStorageDeserializer.h> #include <mitkTrackingDeviceSourceConfigurator.h> #include <mitkLog.h> #include "mitkHummelProtocolEvaluation.h" // POCO #include <Poco/File.h> #include <Poco/Path.h> const std::string QmitkIGTTrackingSemiAutomaticMeasurementView::VIEW_ID = "org.mitk.views.igttrackingsemiautomaticmeasurement"; QmitkIGTTrackingSemiAutomaticMeasurementView::QmitkIGTTrackingSemiAutomaticMeasurementView() : QmitkFunctionality() , m_Controls(nullptr) , m_MultiWidget(nullptr) { m_NextFile = 0; m_FilenameVector = std::vector<std::string>(); m_Timer = new QTimer(this); m_logging = false; m_referenceValid = true; m_tracking = false; m_EvaluationFilter = mitk::NavigationDataEvaluationFilter::New(); } QmitkIGTTrackingSemiAutomaticMeasurementView::~QmitkIGTTrackingSemiAutomaticMeasurementView() { } void QmitkIGTTrackingSemiAutomaticMeasurementView::CreateResults() { QString LogFileName = m_Controls->m_OutputPath->text() + "_results.log"; mitk::LoggingBackend::Unregister(); mitk::LoggingBackend::SetLogFile(LogFileName.toStdString().c_str()); mitk::LoggingBackend::Register(); double RMSmean = 0; for (std::size_t i = 0; i < m_RMSValues.size(); ++i) { MITK_INFO << "RMS at " << this->m_FilenameVector.at(i) << ": " << m_RMSValues.at(i); RMSmean += m_RMSValues.at(i); } RMSmean /= m_RMSValues.size(); MITK_INFO << "RMS mean over " << m_RMSValues.size() << " values: " << RMSmean; mitk::DataNode::Pointer newNode = mitk::DataNode::New(); newNode->SetName("Tracking Results"); newNode->SetData(this->m_MeanPoints); this->GetDataStorage()->Add(newNode); std::vector<mitk::HummelProtocolEvaluation::HummelProtocolDistanceError> results5cmDistances; if (m_Controls->m_mediumVolume->isChecked()) mitk::HummelProtocolEvaluation::Evaluate5cmDistances(m_MeanPoints, mitk::HummelProtocolEvaluation::medium, results5cmDistances); else if (m_Controls->m_smallVolume->isChecked()) mitk::HummelProtocolEvaluation::Evaluate5cmDistances(m_MeanPoints, mitk::HummelProtocolEvaluation::small, results5cmDistances); else if (m_Controls->m_standardVolume->isChecked()) mitk::HummelProtocolEvaluation::Evaluate5cmDistances(m_MeanPoints, mitk::HummelProtocolEvaluation::standard, results5cmDistances); } void QmitkIGTTrackingSemiAutomaticMeasurementView::CreateQtPartControl(QWidget *parent) { // build up qt view, unless already done if (!m_Controls) { // create GUI widgets from the Qt Designer's .ui file m_Controls = new Ui::QmitkIGTTrackingSemiAutomaticMeasurementViewControls; m_Controls->setupUi(parent); //buttons connect(m_Controls->m_LoadMeasurementToolStorage, SIGNAL(clicked()), this, SLOT(OnLoadMeasurementStorage())); connect(m_Controls->m_LoadReferenceToolStorage, SIGNAL(clicked()), this, SLOT(OnLoadReferenceStorage())); connect(m_Controls->m_StartTracking, SIGNAL(clicked()), this, SLOT(OnStartTracking())); connect(m_Controls->m_LoadList, SIGNAL(clicked()), this, SLOT(OnMeasurementLoadFile())); connect(m_Controls->m_StartNextMeasurement, SIGNAL(clicked()), this, SLOT(StartNextMeasurement())); connect(m_Controls->m_ReapeatLastMeasurement, SIGNAL(clicked()), this, SLOT(RepeatLastMeasurement())); connect(m_Controls->m_SetReference, SIGNAL(clicked()), this, SLOT(OnSetReference())); connect(m_Controls->m_UseReferenceTrackingSystem, SIGNAL(toggled(bool)), this, SLOT(OnUseReferenceToggled(bool))); connect(m_Controls->m_CreateResults, SIGNAL(clicked()), this, SLOT(CreateResults())); //event filter qApp->installEventFilter(this); //timers connect(m_Timer, SIGNAL(timeout()), this, SLOT(UpdateTimer())); } //initialize some view m_Controls->m_StopTracking->setEnabled(false); } void QmitkIGTTrackingSemiAutomaticMeasurementView::MultiWidgetAvailable(QmitkAbstractMultiWidget &multiWidget) { m_MultiWidget = dynamic_cast<QmitkStdMultiWidget*>(&multiWidget); } void QmitkIGTTrackingSemiAutomaticMeasurementView::MultiWidgetNotAvailable() { m_MultiWidget = nullptr; } void QmitkIGTTrackingSemiAutomaticMeasurementView::OnUseReferenceToggled(bool state) { if (state) { m_Controls->m_ReferenceBox->setEnabled(true); m_Controls->m_SetReference->setEnabled(true); } else { m_Controls->m_ReferenceBox->setEnabled(false); m_Controls->m_SetReference->setEnabled(false); } } mitk::NavigationToolStorage::Pointer QmitkIGTTrackingSemiAutomaticMeasurementView::ReadStorage(std::string file) { mitk::NavigationToolStorage::Pointer returnValue; //initialize tool storage returnValue = mitk::NavigationToolStorage::New(); //read tool storage from disk mitk::NavigationToolStorageDeserializer::Pointer myDeserializer = mitk::NavigationToolStorageDeserializer::New(GetDataStorage()); returnValue = myDeserializer->Deserialize(file); if (returnValue.IsNull()) { QMessageBox msgBox; msgBox.setText(myDeserializer->GetErrorMessage().c_str()); msgBox.exec(); returnValue = nullptr; } return returnValue; } void QmitkIGTTrackingSemiAutomaticMeasurementView::OnSetReference() { //initialize reference m_ReferenceStartPositions = std::vector<mitk::Point3D>(); m_ReferenceTrackingDeviceSource->Update(); QString Label = "Positions At Start: "; for (unsigned int i = 0; i < m_ReferenceTrackingDeviceSource->GetNumberOfOutputs(); ++i) { mitk::Point3D position = m_ReferenceTrackingDeviceSource->GetOutput(i)->GetPosition(); Label = Label + "Tool" + QString::number(i) + ":[" + QString::number(position[0]) + ":" + QString::number(position[1]) + ":" + QString::number(position[1]) + "] "; m_ReferenceStartPositions.push_back(position); } m_Controls->m_ReferencePosAtStart->setText(Label); } void QmitkIGTTrackingSemiAutomaticMeasurementView::OnLoadMeasurementStorage() { //read in filename QString filename = QFileDialog::getOpenFileName(nullptr, tr("Open Toolfile"), "/", tr("All Files (*.*)")); if (filename.isNull()) return; m_MeasurementStorage = ReadStorage(filename.toStdString()); //update label Poco::Path myPath = Poco::Path(filename.toStdString()); //use this to seperate filename from path QString toolLabel = QString("Tool Storage: ") + QString::number(m_MeasurementStorage->GetToolCount()) + " Tools from " + myPath.getFileName().c_str(); m_Controls->m_MeasurementToolStorageLabel->setText(toolLabel); //update status widget m_Controls->m_ToolStatusWidget->RemoveStatusLabels(); m_Controls->m_ToolStatusWidget->PreShowTools(m_MeasurementStorage); } void QmitkIGTTrackingSemiAutomaticMeasurementView::OnLoadReferenceStorage() { //read in filename static QString oldFile; if (oldFile.isNull()) oldFile = "/"; QString filename = QFileDialog::getOpenFileName(nullptr, tr("Open Toolfile"), oldFile, tr("All Files (*.*)")); if (filename.isNull()) return; oldFile = filename; m_ReferenceStorage = ReadStorage(filename.toStdString()); //update label Poco::Path myPath = Poco::Path(filename.toStdString()); //use this to seperate filename from path QString toolLabel = QString("Tool Storage: ") + QString::number(m_ReferenceStorage->GetToolCount()) + " Tools from " + myPath.getFileName().c_str(); m_Controls->m_ReferenceToolStorageLabel->setText(toolLabel); } void QmitkIGTTrackingSemiAutomaticMeasurementView::OnStartTracking() { //check if everything is ready to start tracking if (m_MeasurementStorage.IsNull()) { MessageBox("Error: No measurement tools loaded yet!"); return; } else if (m_ReferenceStorage.IsNull() && m_Controls->m_UseReferenceTrackingSystem->isChecked()) { MessageBox("Error: No refernce tools loaded yet!"); return; } else if (m_MeasurementStorage->GetToolCount() == 0) { MessageBox("Error: No way to track without tools!"); return; } else if (m_Controls->m_UseReferenceTrackingSystem->isChecked() && (m_ReferenceStorage->GetToolCount() == 0)) { MessageBox("Error: No way to track without tools!"); return; } //build the first IGT pipeline (MEASUREMENT) mitk::TrackingDeviceSourceConfigurator::Pointer myTrackingDeviceSourceFactory1 = mitk::TrackingDeviceSourceConfigurator::New(this->m_MeasurementStorage, this->m_Controls->m_MeasurementTrackingDeviceConfigurationWidget->GetTrackingDevice()); m_MeasurementTrackingDeviceSource = myTrackingDeviceSourceFactory1->CreateTrackingDeviceSource(this->m_MeasurementToolVisualizationFilter); if (m_MeasurementTrackingDeviceSource.IsNull()) { MessageBox(myTrackingDeviceSourceFactory1->GetErrorMessage()); return; } //connect the tool visualization widget for (unsigned int i = 0; i < m_MeasurementTrackingDeviceSource->GetNumberOfOutputs(); ++i) { m_Controls->m_ToolStatusWidget->AddNavigationData(m_MeasurementTrackingDeviceSource->GetOutput(i)); m_EvaluationFilter->SetInput(i, m_MeasurementTrackingDeviceSource->GetOutput(i)); } m_Controls->m_ToolStatusWidget->ShowStatusLabels(); m_Controls->m_ToolStatusWidget->SetShowPositions(true); m_Controls->m_ToolStatusWidget->SetShowQuaternions(true); //build the second IGT pipeline (REFERENCE) if (m_Controls->m_UseReferenceTrackingSystem->isChecked()) { mitk::TrackingDeviceSourceConfigurator::Pointer myTrackingDeviceSourceFactory2 = mitk::TrackingDeviceSourceConfigurator::New(this->m_ReferenceStorage, this->m_Controls->m_ReferenceDeviceConfigurationWidget->GetTrackingDevice()); m_ReferenceTrackingDeviceSource = myTrackingDeviceSourceFactory2->CreateTrackingDeviceSource(); if (m_ReferenceTrackingDeviceSource.IsNull()) { MessageBox(myTrackingDeviceSourceFactory2->GetErrorMessage()); return; } } //initialize tracking try { m_MeasurementTrackingDeviceSource->Connect(); m_MeasurementTrackingDeviceSource->StartTracking(); if (m_Controls->m_UseReferenceTrackingSystem->isChecked()) { m_ReferenceTrackingDeviceSource->Connect(); m_ReferenceTrackingDeviceSource->StartTracking(); } } catch (...) { MessageBox("Error while starting the tracking device!"); return; } //set reference if (m_Controls->m_UseReferenceTrackingSystem->isChecked()) OnSetReference(); //start timer m_Timer->start(1000 / (m_Controls->m_SamplingRate->value())); m_Controls->m_StartTracking->setEnabled(false); m_Controls->m_StartTracking->setEnabled(true); m_tracking = true; } void QmitkIGTTrackingSemiAutomaticMeasurementView::OnStopTracking() { if (this->m_logging) FinishMeasurement(); m_MeasurementTrackingDeviceSource->Disconnect(); m_MeasurementTrackingDeviceSource->StopTracking(); if (m_Controls->m_UseReferenceTrackingSystem->isChecked()) { m_ReferenceTrackingDeviceSource->Disconnect(); m_ReferenceTrackingDeviceSource->StopTracking(); } m_Timer->stop(); m_Controls->m_StartTracking->setEnabled(true); m_Controls->m_StartTracking->setEnabled(false); m_tracking = false; } void QmitkIGTTrackingSemiAutomaticMeasurementView::OnMeasurementLoadFile() { m_FilenameVector = std::vector<std::string>(); m_FilenameVector.clear(); m_NextFile = 0; //read in filename QString filename = QFileDialog::getOpenFileName(nullptr, tr("Open Measurement Filename List"), "/", tr("All Files (*.*)")); if (filename.isNull()) return; //define own locale std::locale C("C"); setlocale(LC_ALL, "C"); //read file std::ifstream file; file.open(filename.toStdString().c_str(), std::ios::in); if (file.good()) { //read out file file.seekg(0L, std::ios::beg); // move to begin of file while (!file.eof()) { std::string buffer; std::getline(file, buffer); // read out file line by line if (buffer.size() > 0) m_FilenameVector.push_back(buffer); } } //fill list at GUI m_Controls->m_MeasurementList->clear(); for (unsigned int i = 0; i < m_FilenameVector.size(); i++) { new QListWidgetItem(tr(m_FilenameVector.at(i).c_str()), m_Controls->m_MeasurementList); } //update label next measurement std::stringstream label; label << "Next Measurement: " << m_FilenameVector.at(0); m_Controls->m_NextMeasurement->setText(label.str().c_str()); //reset results files m_MeanPoints = mitk::PointSet::New(); m_RMSValues = std::vector<double>(); m_EvaluationFilter = mitk::NavigationDataEvaluationFilter::New(); if (m_MeasurementToolVisualizationFilter.IsNotNull()) m_EvaluationFilter->SetInput(0, m_MeasurementToolVisualizationFilter->GetOutput(0)); } void QmitkIGTTrackingSemiAutomaticMeasurementView::UpdateTimer() { if (m_EvaluationFilter.IsNotNull() && m_logging) m_EvaluationFilter->Update(); else m_MeasurementToolVisualizationFilter->Update(); m_Controls->m_ToolStatusWidget->Refresh(); //update reference if (m_Controls->m_UseReferenceTrackingSystem->isChecked()) { m_ReferenceTrackingDeviceSource->Update(); QString Label = "Current Positions: "; bool distanceThresholdExceeded = false; for (unsigned int i = 0; i < m_ReferenceTrackingDeviceSource->GetNumberOfOutputs(); ++i) { mitk::Point3D position = m_ReferenceTrackingDeviceSource->GetOutput(i)->GetPosition(); Label = Label + "Tool" + QString::number(i) + ":[" + QString::number(position[0]) + ":" + QString::number(position[1]) + ":" + QString::number(position[1]) + "] "; if (position.EuclideanDistanceTo(m_ReferenceStartPositions.at(i)) > m_Controls->m_ReferenceThreshold->value()) distanceThresholdExceeded = true; } m_Controls->m_ReferenceCurrentPos->setText(Label); if (distanceThresholdExceeded) { m_Controls->m_ReferenceOK->setText("<html><body style=\" font-family:\'MS Shell Dlg 2\'; font-size:28pt; font-weight:400; font-style:normal;\">NOT OK!</body></html>"); m_referenceValid = false; } else { m_Controls->m_ReferenceOK->setText("<html><body style=\" font-family:\'MS Shell Dlg 2\'; font-size:28pt; font-weight:400; font-style:normal;\">OK</body></html>"); m_referenceValid = true; } } //update logging if (m_logging) { //check for missing objects if (m_MeasurementLoggingFilterXML.IsNull() || m_MeasurementLoggingFilterCSV.IsNull() ) { return; } //log/measure m_MeasurementLoggingFilterXML->Update(); m_MeasurementLoggingFilterCSV->Update(); if (m_Controls->m_UseReferenceTrackingSystem->isChecked() && m_ReferenceLoggingFilterXML.IsNotNull() && m_ReferenceLoggingFilterCSV.IsNotNull()) { m_ReferenceLoggingFilterXML->Update(); m_ReferenceLoggingFilterCSV->Update(); } m_loggedFrames++; LogAdditionalCSVFile(); //check if all frames are logged ... if yes finish the measurement if (m_loggedFrames > m_Controls->m_SamplesPerMeasurement->value()) { FinishMeasurement(); } //update logging label QString loggingLabel = "Collected Samples: " + QString::number(m_loggedFrames); m_Controls->m_CollectedSamples->setText(loggingLabel); } } void QmitkIGTTrackingSemiAutomaticMeasurementView::StartNextMeasurement() { if (this->m_NextFile >= static_cast<int>(m_FilenameVector.size())) { MessageBox("Last Measurement reached!"); return; } m_loggedFrames = 0; m_logging = true; //check if directory exists, if not create one Poco::File myPath(std::string(m_Controls->m_OutputPath->text().toUtf8()).c_str()); if (!myPath.exists()) myPath.createDirectory(); QString LogFileName = m_Controls->m_OutputPath->text() + QString(m_FilenameVector.at(m_NextFile).c_str()) + ".log"; mitk::LoggingBackend::Unregister(); mitk::LoggingBackend::SetLogFile(LogFileName.toStdString().c_str()); mitk::LoggingBackend::Register(); //initialize logging filters m_MeasurementLoggingFilterXML = mitk::NavigationDataRecorderDeprecated::New(); m_MeasurementLoggingFilterXML->SetRecordingMode(mitk::NavigationDataRecorderDeprecated::NormalFile); m_MeasurementLoggingFilterCSV = mitk::NavigationDataRecorderDeprecated::New(); m_MeasurementLoggingFilterCSV->SetRecordingMode(mitk::NavigationDataRecorderDeprecated::NormalFile); m_MeasurementLoggingFilterXML->SetOutputFormat(mitk::NavigationDataRecorderDeprecated::xml); m_MeasurementLoggingFilterCSV->SetOutputFormat(mitk::NavigationDataRecorderDeprecated::csv); QString MeasurementFilenameXML = m_Controls->m_OutputPath->text() + QString(m_FilenameVector.at(m_NextFile).c_str()) + ".xml"; QString MeasurementFilenameCSV = m_Controls->m_OutputPath->text() + QString(m_FilenameVector.at(m_NextFile).c_str()) + ".csv"; m_MeasurementLoggingFilterXML->SetFileName(MeasurementFilenameXML.toStdString()); m_MeasurementLoggingFilterCSV->SetFileName(MeasurementFilenameCSV.toStdString()); m_MeasurementLoggingFilterXML->SetRecordCountLimit(m_Controls->m_SamplesPerMeasurement->value()); m_MeasurementLoggingFilterCSV->SetRecordCountLimit(m_Controls->m_SamplesPerMeasurement->value()); if (m_Controls->m_UseReferenceTrackingSystem->isChecked()) { m_ReferenceLoggingFilterXML = mitk::NavigationDataRecorderDeprecated::New(); m_ReferenceLoggingFilterXML->SetRecordingMode(mitk::NavigationDataRecorderDeprecated::NormalFile); m_ReferenceLoggingFilterCSV = mitk::NavigationDataRecorderDeprecated::New(); m_ReferenceLoggingFilterCSV->SetRecordingMode(mitk::NavigationDataRecorderDeprecated::NormalFile); m_ReferenceLoggingFilterXML->SetOutputFormat(mitk::NavigationDataRecorderDeprecated::xml); m_ReferenceLoggingFilterCSV->SetOutputFormat(mitk::NavigationDataRecorderDeprecated::csv); QString ReferenceFilenameXML = m_Controls->m_OutputPath->text() + "Reference_" + QString(m_FilenameVector.at(m_NextFile).c_str()) + ".xml"; QString ReferenceFilenameCSV = m_Controls->m_OutputPath->text() + "Reference_" + QString(m_FilenameVector.at(m_NextFile).c_str()) + ".csv"; m_ReferenceLoggingFilterXML->SetFileName(ReferenceFilenameXML.toStdString()); m_ReferenceLoggingFilterCSV->SetFileName(ReferenceFilenameCSV.toStdString()); m_ReferenceLoggingFilterXML->SetRecordCountLimit(m_Controls->m_SamplesPerMeasurement->value()); m_ReferenceLoggingFilterCSV->SetRecordCountLimit(m_Controls->m_SamplesPerMeasurement->value()); } //start additional csv logging StartLoggingAdditionalCSVFile(m_FilenameVector.at(m_NextFile)); //connect filter for (unsigned int i = 0; i < m_MeasurementToolVisualizationFilter->GetNumberOfOutputs(); ++i) { m_MeasurementLoggingFilterXML->AddNavigationData(m_MeasurementToolVisualizationFilter->GetOutput(i)); m_MeasurementLoggingFilterCSV->AddNavigationData(m_MeasurementToolVisualizationFilter->GetOutput(i)); } if (m_Controls->m_UseReferenceTrackingSystem->isChecked()) for (unsigned int i = 0; i < m_ReferenceTrackingDeviceSource->GetNumberOfOutputs(); ++i) { m_ReferenceLoggingFilterXML->AddNavigationData(m_ReferenceTrackingDeviceSource->GetOutput(i)); m_ReferenceLoggingFilterCSV->AddNavigationData(m_ReferenceTrackingDeviceSource->GetOutput(i)); } //start filter m_MeasurementLoggingFilterXML->StartRecording(); m_MeasurementLoggingFilterCSV->StartRecording(); if (m_Controls->m_UseReferenceTrackingSystem->isChecked()) { m_ReferenceLoggingFilterXML->StartRecording(); m_ReferenceLoggingFilterCSV->StartRecording(); } //disable all buttons DisableAllButtons(); //update label next measurement std::stringstream label; if ((m_NextFile + 1) >= static_cast<int>(m_FilenameVector.size())) label << "Next Measurement: <none>"; else label << "Next Measurement: " << m_FilenameVector.at(m_NextFile + 1); m_Controls->m_NextMeasurement->setText(label.str().c_str()); //update label last measurement std::stringstream label2; label2 << "Last Measurement: " << m_FilenameVector.at(m_NextFile); m_Controls->m_LastMeasurement->setText(label2.str().c_str()); m_NextFile++; } void QmitkIGTTrackingSemiAutomaticMeasurementView::RepeatLastMeasurement() { m_NextFile--; StartNextMeasurement(); } void QmitkIGTTrackingSemiAutomaticMeasurementView::MessageBox(std::string s) { QMessageBox msgBox; msgBox.setText(s.c_str()); msgBox.exec(); } void QmitkIGTTrackingSemiAutomaticMeasurementView::DisableAllButtons() { m_Controls->m_LoadList->setEnabled(false); m_Controls->m_StartNextMeasurement->setEnabled(false); m_Controls->m_ReapeatLastMeasurement->setEnabled(false); m_Controls->m_SamplingRate->setEnabled(false); m_Controls->m_SamplesPerMeasurement->setEnabled(false); m_Controls->m_ReferenceThreshold->setEnabled(false); } void QmitkIGTTrackingSemiAutomaticMeasurementView::EnableAllButtons() { m_Controls->m_LoadList->setEnabled(true); m_Controls->m_StartNextMeasurement->setEnabled(true); m_Controls->m_ReapeatLastMeasurement->setEnabled(true); m_Controls->m_SamplingRate->setEnabled(true); m_Controls->m_SamplesPerMeasurement->setEnabled(true); m_Controls->m_ReferenceThreshold->setEnabled(true); } void QmitkIGTTrackingSemiAutomaticMeasurementView::FinishMeasurement() { m_logging = false; m_MeasurementLoggingFilterXML->StopRecording(); m_MeasurementLoggingFilterCSV->StopRecording(); if (m_Controls->m_UseReferenceTrackingSystem->isChecked()) { m_ReferenceLoggingFilterXML->StopRecording(); m_ReferenceLoggingFilterCSV->StopRecording(); } StopLoggingAdditionalCSVFile(); int id = m_NextFile - 1; mitk::Point3D positionMean = m_EvaluationFilter->GetPositionMean(0); MITK_INFO << "Evaluated " << m_EvaluationFilter->GetNumberOfAnalysedNavigationData(0) << " samples."; double rms = m_EvaluationFilter->GetPositionErrorRMS(0); MITK_INFO << "RMS: " << rms; MITK_INFO << "Position Mean: " << positionMean; m_MeanPoints->SetPoint(id, positionMean); if (static_cast<int>(m_RMSValues.size()) <= id) m_RMSValues.push_back(rms); else m_RMSValues[id] = rms; m_EvaluationFilter->ResetStatistic(); EnableAllButtons(); } void QmitkIGTTrackingSemiAutomaticMeasurementView::StartLoggingAdditionalCSVFile(std::string filePostfix) { //write logfile header QString header = "Nr;MITK_Time;Valid_Reference;"; QString tool = QString("MeasureTool_") + QString(m_MeasurementTrackingDeviceSource->GetOutput(0)->GetName()); header = header + tool + "[x];" + tool + "[y];" + tool + "[z];" + tool + "[qx];" + tool + "[qy];" + tool + "[qz];" + tool + "[qr]\n"; //open logfile and write header m_logFileCSV.open(std::string(m_Controls->m_OutputPath->text().toUtf8()).append("/LogFileCombined").append(filePostfix.c_str()).append(".csv").c_str(), std::ios::out); m_logFileCSV << header.toStdString().c_str(); } void QmitkIGTTrackingSemiAutomaticMeasurementView::LogAdditionalCSVFile() { mitk::Point3D pos = m_MeasurementTrackingDeviceSource->GetOutput(0)->GetPosition(); mitk::Quaternion rot = m_MeasurementTrackingDeviceSource->GetOutput(0)->GetOrientation(); std::string valid = ""; if (m_referenceValid) valid = "true"; else valid = "false"; std::stringstream timestamp; timestamp << m_MeasurementTrackingDeviceSource->GetOutput(0)->GetTimeStamp(); QString dataSet = QString::number(m_loggedFrames) + ";" + QString(timestamp.str().c_str()) + ";" + QString(valid.c_str()) + ";" + QString::number(pos[0]) + ";" + QString::number(pos[1]) + ";" + QString::number(pos[2]) + ";" + QString::number(rot.x()) + ";" + QString::number(rot.y()) + ";" + QString::number(rot.z()) + ";" + QString::number(rot.r()) + "\n"; m_logFileCSV << dataSet.toStdString(); } void QmitkIGTTrackingSemiAutomaticMeasurementView::StopLoggingAdditionalCSVFile() { m_logFileCSV.close(); } bool QmitkIGTTrackingSemiAutomaticMeasurementView::eventFilter(QObject *, QEvent *ev) { if (ev->type() == QEvent::KeyPress) { QKeyEvent *k = (QKeyEvent *)ev; bool down = k->key() == 16777239; if (down && m_tracking && !m_logging) StartNextMeasurement(); } return false; }
39.520194
359
0.74676
[ "vector" ]
4c17b44b3b29166ad55a07422513f0b2e6a24b1a
7,808
hpp
C++
src/BugReports.hpp
hcoffey1/hippocrates
103b01e73064f0baf5ad230a630b630f2102158c
[ "MIT" ]
3
2021-10-17T00:34:54.000Z
2022-02-03T15:32:04.000Z
src/BugReports.hpp
hcoffey1/hippocrates
103b01e73064f0baf5ad230a630b630f2102158c
[ "MIT" ]
1
2022-03-14T20:36:52.000Z
2022-03-22T15:52:34.000Z
src/BugReports.hpp
hcoffey1/hippocrates
103b01e73064f0baf5ad230a630b630f2102158c
[ "MIT" ]
3
2021-09-13T02:17:19.000Z
2021-10-17T00:35:12.000Z
#pragma once /** * Bug reports contain two things: */ #include <cstdint> #include <list> #include <string> #include <unordered_map> #include <vector> #include "llvm/IR/Module.h" #include "llvm/IR/Instruction.h" #include "llvm/IR/Function.h" #include "llvm/IR/DebugInfoMetadata.h" #include "yaml-cpp/yaml.h" namespace pmfix { /** * Just a wrapper for virtual address information. */ struct AddressInfo { uint64_t address; uint64_t length; AddressInfo() : address(0), length(0) {} // Helpers -- both inclusive. uint64_t start(void) const { return address; } uint64_t end(void) const { return address + length - 1llu; } // Methods for checking overlap with others/cache lines. bool isSingleCacheLine(void) const; bool overlaps(const AddressInfo &other) const; // Returns true if this fully encompasses other. bool contains(const AddressInfo &other) const; bool canAdd(const AddressInfo &other) const; // These are equal if the cache lines equal bool operator==(const AddressInfo &other) const; void operator+=(const AddressInfo &other); std::string str() const { std::stringstream buffer; buffer << "<AddressInfo: addr=" << address << " len=" << length << ">"; return buffer.str(); } }; /** * Just a wrapper for source code location information. */ struct LocationInfo { std::string function; std::string file; // -1 represents unknown int64_t line = -1; // Returns just the file name, trims directory information. std::string getFilename(void) const; struct Hash { // We only want to hash the last part of the file to avoid // hash issues when the directories differ. uint64_t operator()(const LocationInfo &li) const { return std::hash<std::string>{}(li.function) ^ std::hash<std::string>{}(li.getFilename()) ^ std::hash<int64_t>{}(li.line); } }; bool operator==(const LocationInfo &other) const; bool operator!=(const LocationInfo &li) const { return !(*this == li); } bool valid(void) const {return line > 0;} std::string str() const; }; /** * Location for a fix to generate. * * This should philosophically be a range of instructions within a single basic * block. */ struct FixLoc { llvm::Instruction *first; llvm::Instruction *last; LocationInfo dbgLoc; struct Hash { uint64_t operator()(const FixLoc &fl) const; }; struct Compare { /** * Return a < b. */ bool operator()(const FixLoc &a, const FixLoc &b) const; }; FixLoc() : first(nullptr), last(nullptr) {} FixLoc(llvm::Instruction *i) : first(i), last(i) {} FixLoc(llvm::Instruction *f, llvm::Instruction *l) : first(f), last(l) {} FixLoc(llvm::Instruction *f, llvm::Instruction *l, LocationInfo li) : first(f), last(l), dbgLoc(li) {} bool isValid() const; bool isSingleInst() const { return first == last; } bool operator==(const FixLoc &other) const { return first == other.first && last == other.last; } std::list<llvm::Instruction*> insts() const; static const FixLoc &NullLoc(); std::string str() const; }; /** * Creates a map of source code location -> LLVM IR location. Then allows lookups * so that bugs can be mapped from trace info (which are at source level) to * somewhere in the IR so we can start fixing bugs. * * Sometimes, there are multiple locations that map to the same line of source * code---not just multiple assembly instructions, but multiple locations. The * solution I think is just apply fixes to both locations. The instructions * should be identical. */ class BugLocationMapper { private: llvm::Module &m_; std::unordered_map<LocationInfo, std::list<llvm::Instruction*>, LocationInfo::Hash> locMap_; std::unordered_map<LocationInfo, std::list<FixLoc>, LocationInfo::Hash> fixLocMap_; void insertMapping(llvm::Instruction *i); void createMappings(llvm::Module &m); static std::unique_ptr<BugLocationMapper> instance; BugLocationMapper(llvm::Module &m) : m_(m) { createMappings(m); } BugLocationMapper(const BugLocationMapper &) = delete; public: static BugLocationMapper &getInstance(llvm::Module &m); const std::list<FixLoc> &operator[](const LocationInfo &li) const { return fixLocMap_.at(li); } bool contains(const LocationInfo &li) const { return fixLocMap_.count(li); } const std::list<llvm::Instruction*> &insts(const LocationInfo &li) const { return locMap_.at(li); } bool instsContains(const LocationInfo &li) const { return fixLocMap_.count(li); } llvm::Module &module() const { return m_; } }; struct TraceEvent { /** * The type of event, i.e. the kind of operation. */ enum Type { INVALID = -1, STORE = 0, FLUSH, FENCE, ASSERT_PERSISTED, ASSERT_ORDERED, REQUIRED_FLUSH }; /** * Which bug finder the source came from. */ enum Source { UNKNOWN = -1, PMTEST = 0, GENERIC = 1 }; static Type getType(std::string typeString); // Event data. Source source; Type type; uint64_t timestamp; std::vector<AddressInfo> addresses; LocationInfo location; bool isBug; std::vector<LocationInfo> callstack; // Debug std::string typeString; // Helper bool isOperation(void) const { return type == STORE || type == FLUSH || type == FENCE; } bool isAssertion(void) const { return type == ASSERT_PERSISTED || type == ASSERT_ORDERED || type == REQUIRED_FLUSH; } static bool callStacksEqual(const TraceEvent &a, const TraceEvent &b); std::string str() const; /** * Get the values of the PM pointers associated with the events. */ std::list<llvm::Value*> pmValues(const BugLocationMapper &mapper) const; }; class TraceInfo { private: friend class TraceInfoBuilder; // Trace data. // -- indices where bugs live std::list<int> bugs_; // -- the actual events std::vector<TraceEvent> events_; // -- the source of the trace TraceEvent::Source source_; // Metadata. For stuff like which fix generator to use. YAML::Node meta_; // Don't want direct construction of this class. TraceInfo() {} void addEvent(TraceEvent &&event); TraceInfo(YAML::Node m); public: const TraceEvent &operator[](int i) const { return events_[i]; } TraceEvent &operator[](int i) { return events_[i]; } const std::list<int> &bugs() const { return bugs_; } const std::vector<TraceEvent> &events() const { return events_; } size_t size() const { return events_.size(); } bool empty() const { return events_.empty(); } std::string str() const; template<typename T> T getMetadata(const char *key) const { return meta_[key].as<T>(); } TraceEvent::Source getSource() const { return source_; } }; /** * Ian: my thought on using this builder style is that it will de-clutter * the TraceInfo class. */ class TraceInfoBuilder { private: YAML::Node doc_; BugLocationMapper &mapper_; /** * Convert the YAML node into a proper trace event. */ void processEvent(TraceInfo &ti, YAML::Node event); /** * Fixes up slight naming differences in trace event stack traces. */ void resolveLocations(TraceEvent &te); public: TraceInfoBuilder(llvm::Module &m, YAML::Node document) : mapper_(BugLocationMapper::getInstance(m)), doc_(document) {}; TraceInfo build(void); }; }
25.940199
81
0.632813
[ "vector" ]
4c1875cd4f5d707bd20cceac80f463e1c4a501e7
4,174
cpp
C++
src/smartRandom.cpp
hiddewie/Hartenjagen
b7acd871dddeecaa633a73153f599a4a1925b7e4
[ "MIT" ]
null
null
null
src/smartRandom.cpp
hiddewie/Hartenjagen
b7acd871dddeecaa633a73153f599a4a1925b7e4
[ "MIT" ]
null
null
null
src/smartRandom.cpp
hiddewie/Hartenjagen
b7acd871dddeecaa633a73153f599a4a1925b7e4
[ "MIT" ]
null
null
null
#include <string> #include <vector> #include <iostream> #include <algorithm> #include "hearts.h" using namespace std; SmartRandom::SmartRandom(int id, int round) : IPlayer(id, round) { this->heartsBroken = false; } int SmartRandom::getLowestRankIndex(bool heartsBroken) { int highestCardRank = 1000, lowestCardIndex = 0; Card currentCard; for (unsigned int i = 0; i < hand.size(); i++) { currentCard = hand.at(i); if (currentCard.getCardRank() < highestCardRank && (heartsBroken || currentCard.getCardSuit() != HEARTS)) { highestCardRank = currentCard.getCardRank(); lowestCardIndex = i; } } return lowestCardIndex; } int SmartRandom::getHighestRankIndex(bool heartsBroken) { int highestCardRank = 0, highestCardIndex = 0; Card currentCard; for (unsigned int i = 0; i < hand.size(); i++) { currentCard = hand.at(i); if (currentCard.getCardRank() > highestCardRank && (heartsBroken || currentCard.getCardSuit() != HEARTS)) { highestCardRank = currentCard.getCardRank(); highestCardIndex = i; } } return highestCardIndex; } int SmartRandom::getIndex(Card c) { for (unsigned int i = 0; i < hand.size(); i++) { if (c == hand.at(i)) { return i; } } throw Error("Card " + c.getName() + " not in hand."); } vector<int> SmartRandom::passCards() { int highestPoints[] = { 0, 0, 0 }; int highestCardsIndidces[] = { 0, 0, 0 }; Card currentCard; for (unsigned int i = 0; i < hand.size(); i++) { currentCard = hand.at(i); if (currentCard.getCardRank() >= highestPoints[0]) { highestPoints[2] = highestPoints[1]; highestPoints[1] = highestPoints[0]; highestPoints[0] = currentCard.getCardRank(); highestCardsIndidces[2] = highestCardsIndidces[1]; highestCardsIndidces[1] = highestCardsIndidces[0]; highestCardsIndidces[0] = i; } else if (currentCard.getCardRank() >= highestPoints[1]) { highestPoints[2] = highestPoints[1]; highestPoints[1] = currentCard.getCardRank(); highestCardsIndidces[2] = highestCardsIndidces[1]; highestCardsIndidces[1] = i; } else if (currentCard.getCardRank() >= highestPoints[2]) { highestPoints[2] = currentCard.getCardRank(); highestCardsIndidces[2] = i; } } vector<int> ret; for (int i = 0; i < 3; i++) { ret.push_back(highestCardsIndidces[i]); } return ret; } int SmartRandom::decide(const Trick& trick) { Card::sortCardsDescending(hand); for (int i = 0; i < 4; i++) { sortedHand[i].clear(); } for (unsigned int i = 0; i < hand.size(); i++) { sortedHand[hand.at(i).getCardSuit()].push_back(hand.at(i)); } for (int i = 0; i < 4; i++) { Card::sortCardsDescending(sortedHand[i]); } int cardsPlayed = trick.playedCards.size(); if (cardsPlayed == 0) { // first player if (hand.size() == 13) { // first trick, first player for (unsigned int i = 0; i < hand.size(); i++) { Card clubs2 = Card(CLUBS, TWO); if (clubs2 == this->hand.at(i)) { return i; } } } else { // first player, not first trick int i = hand.size() - 1; while (i > 0 && (!heartsBroken && hand.at(i).getCardSuit() == HEARTS)) { i--; } return i; } } else { // second, third or last player int firstSuit = trick.playedCards.at(0).card.getCardSuit(); if (sortedHand[firstSuit].size() > 0) { // match suit for (int i = (int) sortedHand[firstSuit].size() - 1; i>= 0; i--) { if (sortedHand[firstSuit].at(i).getCardRank() < trick.playedCards.at(0).card.getCardRank()) { return i; } } return getIndex(sortedHand[firstSuit].at(0)); } else { // cannot match suit if (heartsBroken && sortedHand[HEARTS].size() > 0) { return getIndex(sortedHand[HEARTS].at(0)); } else { int i = hand.size() - 1; while (i > 0 && hand.at(i).getCardSuit() == HEARTS) { i --; } return i; } } } throw Error("SmartRandom error!"); } void SmartRandom::endOfTrick(const Trick& trick) { if (!heartsBroken) { for (int i = 0; i < 4; i++) { if (trick.playedCards.at(i).card.getCardSuit() == HEARTS) { heartsBroken = true; } } } }
28.986111
110
0.615956
[ "vector" ]
4c18d98b43d877c66da1b351a233dea0a1d76463
8,093
hpp
C++
src/mge/core/parameter.hpp
mge-engine/mge
e7a6253f99dd640a655d9a80b94118d35c7d8139
[ "MIT" ]
null
null
null
src/mge/core/parameter.hpp
mge-engine/mge
e7a6253f99dd640a655d9a80b94118d35c7d8139
[ "MIT" ]
91
2019-03-09T11:31:29.000Z
2022-02-27T13:06:06.000Z
src/mge/core/parameter.hpp
mge-engine/mge
e7a6253f99dd640a655d9a80b94118d35c7d8139
[ "MIT" ]
null
null
null
// mge - Modern Game Engine // Copyright (c) 2021 by Alexander Schroeder // All rights reserved. #pragma once #include "boost/boost_lexical_cast.hpp" #include "mge/core/dllexport.hpp" #include "mge/core/make_string_view.hpp" #include <any> #include <functional> #include <mutex> #include <sstream> #include <string_view> namespace mge { /** * @brief Configuration parameter. * Implements the interface to describe, read and write a parameter. */ class MGECORE_EXPORT basic_parameter { public: using change_callback = std::function<void()>; /** * @brief Construct a parameter. * * @param section parameter section * @param name parameter name * @param description parameter description */ basic_parameter(std::string_view section, std::string_view name, std::string_view description); virtual ~basic_parameter(); /** * @brief Parameter section. * * @return parameter section name */ std::string_view section() const noexcept; /** * @brief Parameter name. * * @return parameter name */ std::string_view name() const noexcept; /** * @brief Parameter description. * * @return parameter description text */ std::string_view description() const noexcept; /** * @brief Check whether parameter is set. * * @return @c true if the parameter is set in * configuration */ virtual bool has_value() const = 0; /** * @brief Unset or clears a parameter. */ virtual void reset(); /** * @brief Sets parameter from string * * @param value parameter string value */ virtual void from_string(std::string_view value) = 0; /** * @brief Retrieves parameter as string. * * @return parameter value */ virtual std::string to_string() const = 0; /** * @brief Call to notify a change. * If a change listener is registered, call that. */ void notify_change(); /** * @brief Return current change handler. * * @return change handler */ change_callback change_handler() const; /** * @brief Set the change handler. * * @param handler new change handler */ void set_change_handler(const change_callback& handler); private: std::string_view m_section; std::string_view m_name; std::string_view m_description; mutable std::mutex m_change_lock; change_callback m_change_callback; }; /** * @brief Typed parameter. * * @tparam T parameter type */ template <typename T> class parameter : public basic_parameter { public: /** * @brief Construct a new parameter. * * @tparam SECTION_N length of section literal * @tparam NAME_N length of name literal * @tparam DESCRIPTION_N length of description literal * @param section parameter section * @param name parameter name * @param description parameter description */ template <size_t SECTION_N, size_t NAME_N, size_t DESCRIPTION_N> parameter(const char (&section)[SECTION_N], const char (&name)[NAME_N], const char (&description)[DESCRIPTION_N]) : basic_parameter(make_string_view(section), make_string_view(name), make_string_view(description)) {} /** * @brief Construct a new parameter. * * @tparam SECTION_N length of section literal * @tparam NAME_N length of name literal * @tparam DESCRIPTION_N length of description literal * @param section parameter section * @param name parameter name * @param description parameter description * @param default_value */ template <size_t SECTION_N, size_t NAME_N, size_t DESCRIPTION_N> parameter(const char (&section)[SECTION_N], const char (&name)[NAME_N], const char (&description)[DESCRIPTION_N], const T& default_value) : basic_parameter(make_string_view(section), make_string_view(name), make_string_view(description)) , m_default_value(default_value) {} /** * @brief Construct a new parameter object * * @param section parameter section * @param name parameter name * @param description parameter description */ parameter(std::string_view section, std::string_view name, std::string_view description) : basic_parameter(section, name, description) {} virtual ~parameter() = default; bool has_value() const override { return m_value.has_value() || m_default_value.has_value(); } /** * @brief Retrieve typed value. * * @return stored value */ typename T get() const { if (m_value.has_value()) { return std::any_cast<T>(m_value); } else { return std::any_cast<T>(m_default_value); } } /** * @brief Retrieve typed value, checking default. * * @param default_value default value * @return config value or default value if not set */ typename T get(const T& default_value) const { if (has_value()) { return get(); } else { return default_value; } } void from_string(std::string_view value) override { T val = boost::lexical_cast<T>(value); m_value = val; } std::string to_string() const override { std::stringstream ss; ss << get(); return ss.str(); } void reset() override { m_value.reset(); } private: std::any m_value; const std::any m_default_value; }; /** * @def MGE_DEFINE_PARAMETER * @brief Define a parameter. * @param TYPE parameter type * @param SECTION parameter section * @param NAME parameter name * @param DESCRIPTION parameter description */ #define MGE_DEFINE_PARAMETER(TYPE, SECTION, NAME, DESCRIPTION) \ ::mge::parameter<TYPE> p_##SECTION##_##NAME(#SECTION, #NAME, DESCRIPTION); /** * @def MGE_DEFINE_PARAMETER_WITH_DEFAULT * @brief Define a parameter. * @param TYPE parameter type * @param SECTION parameter section * @param NAME parameter name * @param DESCRIPTION parameter description * @param DEFAULT */ #define MGE_DEFINE_PARAMETER_WITH_DEFAULT(TYPE, \ SECTION, \ NAME, \ DESCRIPTION, \ DEFAULT) \ ::mge::parameter<TYPE> p_##SECTION##_##NAME(#SECTION, \ #NAME, \ DESCRIPTION, \ DEFAULT); /** * @def MGE_PARAMETER * @brief Access a parameter. * @param SECTION parameter section * @param NAME parameter name */ #define MGE_PARAMETER(SECTION, NAME) p_##SECTION##_##NAME } // namespace mge
30.539623
80
0.522427
[ "object" ]
4c18ef1a2d85f3ce3c7badd1d62e05b1a10d9fc1
1,637
hpp
C++
native-library/src/util_classes/transport.hpp
AVSystem/Anjay-java
c8f8c5e0ac5a086db4ca183155eed07374fc6585
[ "Apache-2.0" ]
4
2021-03-03T11:27:57.000Z
2022-03-29T03:42:47.000Z
native-library/src/util_classes/transport.hpp
AVSystem/Anjay-java
c8f8c5e0ac5a086db4ca183155eed07374fc6585
[ "Apache-2.0" ]
null
null
null
native-library/src/util_classes/transport.hpp
AVSystem/Anjay-java
c8f8c5e0ac5a086db4ca183155eed07374fc6585
[ "Apache-2.0" ]
3
2020-11-04T13:13:24.000Z
2021-12-06T08:03:48.000Z
/* * Copyright 2020-2021 AVSystem <avsystem@avsystem.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <anjay/core.h> #include "../jni_wrapper.hpp" #include "./exception.hpp" namespace utils { struct Transport { static constexpr auto Name() { return "com/avsystem/anjay/Anjay$Transport"; } static jni::Local<jni::Object<Transport>> New(jni::JNIEnv &env, anjay_socket_transport_t transport) { auto native_transport_class = jni::Class<Transport>::Find(env); auto get_enum_instance = [&](const char *name) { return native_transport_class.Get( env, native_transport_class .GetStaticField<jni::Object<Transport>>(env, name)); }; switch (transport) { case ANJAY_SOCKET_TRANSPORT_UDP: return get_enum_instance("UDP"); case ANJAY_SOCKET_TRANSPORT_TCP: return get_enum_instance("TCP"); default: avs_throw(IllegalArgumentException(env, "Unsupported transport")); } } }; } // namespace utils
30.886792
80
0.658522
[ "object" ]
4c2534e3bc7566ce57c400cbab1221c799ed969f
6,575
cpp
C++
src/command/object/commandObject.cpp
Galfurian/RadMud
1362cb0ee1b7a17386e57a98e29dd8baeea75af3
[ "MIT" ]
18
2016-05-26T18:11:31.000Z
2022-02-10T20:00:52.000Z
src/command/object/commandObject.cpp
Galfurian/RadMud
1362cb0ee1b7a17386e57a98e29dd8baeea75af3
[ "MIT" ]
null
null
null
src/command/object/commandObject.cpp
Galfurian/RadMud
1362cb0ee1b7a17386e57a98e29dd8baeea75af3
[ "MIT" ]
2
2016-06-30T15:20:01.000Z
2020-08-27T18:28:33.000Z
/// @file commandObject.cpp /// @author Enrico Fraccaroli /// @date Aug 23 2014 /// @copyright /// Copyright (c) 2016 Enrico Fraccaroli <enrico.fraccaroli@gmail.com> /// 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 "commandObject.hpp" #include "commandObjectLightSource.hpp" #include "commandObjectManagement.hpp" #include "commandObjectContainer.hpp" #include "commandObjectCharacter.hpp" #include "commandObjectProcess.hpp" #include "commandObjectLiquids.hpp" #include "commandObjectShop.hpp" #include "mud.hpp" void LoadObjectCommands() { // //////////////////////////////////////////////////////////////////////// // COMMAND MANAGEMENT Mud::instance().addCommand(std::make_shared<Command>( DoTake, "take", "(item|all) [(container)]", "Take something from the ground or from a container.", false, true, false)); Mud::instance().addCommand(std::make_shared<Command>( DoDrop, "drop", "(item|all)", "Drop an object.", false, true, false)); Mud::instance().addCommand(std::make_shared<Command>( DoPut, "put", "(something) (container)", "Put something inside a container.", false, true, false)); Mud::instance().addCommand(std::make_shared<Command>( DoGive, "give", "(item|all) (someone)", "Give an object to someone.", false, false, false)); // //////////////////////////////////////////////////////////////////////// // COMMAND LIQUIDS Mud::instance().addCommand(std::make_shared<Command>( DoDrink, "drink", "(liquid container)", "Drink from a container of liquids.", false, false, false)); Mud::instance().addCommand(std::make_shared<Command>( DoFill, "fill", "(liquid container) (source of liquid)", "Fill a container of liquids from a source of liquid.", false, false, false)); Mud::instance().addCommand(std::make_shared<Command>( DoPour, "pour", "(liquid container) [liquid container]", "Pour the content of the container into another one or on the ground.", false, false, false)); // //////////////////////////////////////////////////////////////////////// // COMMAND CONTAINER Mud::instance().addCommand(std::make_shared<Command>( DoOrganize, "organize", "(name|weight) [(container)]", "Order the desired container or if no target is passed, the room.", false, false, false)); Mud::instance().addCommand(std::make_shared<Command>( DoOpen, "open", "(container)|(direction)", "Open a door in a given direction or a container.", false, true, false)); Mud::instance().addCommand(std::make_shared<Command>( DoClose, "close", "(container)|(direction)", "Close a door in a given direction or a container.", false, true, false)); // //////////////////////////////////////////////////////////////////////// // COMMAND CHARACTER Mud::instance().addCommand(std::make_shared<Command>( DoEquipments, "equipments", "", "List all the items you are wearing.", false, true, false)); Mud::instance().addCommand(std::make_shared<Command>( DoWield, "wield", "(item)", "Wield a weapon, a shield or maybe a tool.", false, true, false)); Mud::instance().addCommand(std::make_shared<Command>( DoWear, "wear", "(item)", "Puts on a piece of equipment.", false, false, false)); Mud::instance().addCommand(std::make_shared<Command>( DoRemove, "remove", "(item)", "Remove a worn or wielded item.", false, true, false)); Mud::instance().addCommand(std::make_shared<Command>( DoInventory, "inventory", "", "Show character's inventory.", false, true, false)); // //////////////////////////////////////////////////////////////////////// // COMMAND SHOP Mud::instance().addCommand(std::make_shared<Command>( DoDeposit, "deposit", "(coin) (shop)", "Deposit a coin inside a shop.", false, false, false)); Mud::instance().addCommand(std::make_shared<Command>( DoSell, "sell", "(item) (shop)", "Sell an item to a shop keeper.", false, false, false)); Mud::instance().addCommand(std::make_shared<Command>( DoBuy, "buy", "(item) (shop)", "Allows to buy an item from a shop.", false, false, false)); Mud::instance().addCommand(std::make_shared<Command>( DoBalance, "balance", "", "Shows the character's balance.", false, false, false)); // //////////////////////////////////////////////////////////////////////// // COMMAND LIGHT SOURCE Mud::instance().addCommand(std::make_shared<Command>( DoTurn, "turn", "(item)", "Allows to turn on and off an actionable item.", false, true, false)); Mud::instance().addCommand(std::make_shared<Command>( DoKindle, "kindle", "(item) (ignition source)", "Allows to kindle a fire.", false, true, false)); Mud::instance().addCommand(std::make_shared<Command>( DoRefill, "refill", "(light source) (fuel)", "Allows to refill a light source.", false, true, false)); // //////////////////////////////////////////////////////////////////////// // COMMAND LIGHT PROCESS Mud::instance().addCommand(std::make_shared<Command>( DoDismember, "dismember", "(corpse)", "Allows to dismember a corpse.", false, true, false)); }
44.425676
79
0.589354
[ "object" ]
4c387f430de9532a9b607876b27efd02cf83e966
3,680
cpp
C++
jf.cpp
tveerman/jf
6086c4e077446abd770577eb231b034b97391862
[ "MIT" ]
null
null
null
jf.cpp
tveerman/jf
6086c4e077446abd770577eb231b034b97391862
[ "MIT" ]
null
null
null
jf.cpp
tveerman/jf
6086c4e077446abd770577eb231b034b97391862
[ "MIT" ]
null
null
null
/* jf - JSON formatter version 0.1 https://github.com/tveerman/jf.git Licensed under the MIT License <http://opensource.org/licenses/MIT>. SPDX-License-Identifier: MIT Copyright (c) 2022 Thomas Veerman 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 "json.hpp" #include <cstdlib> #include <filesystem> #include <fstream> #include <iostream> #include <sys/stat.h> #include <vector> static void usage() { std::cout << "jf [-h] [-i n] [file]" << std::endl << "\t-h\tShows this help message." << std::endl << "\t-i\tNumber of spaces to indent. Default is 2. Use -1 for no indentation at all." << std::endl << "\tfile\tPath to file to indent. When no path is provided the data is read " "from stdin." << std::endl; exit(1); } static bool get_data(std::string const &path, nlohmann::json &j) { if (path.empty()) { std::cin >> j; return true; } if (std::filesystem::exists(path)) { std::ifstream ifs(path); if (ifs.good()) { ifs >> j; } else { std::cerr << "Could not read from file" << std::endl; return false; } } else { std::cerr << "File does not exist" << std::endl; return false; } return true; } int main(int argc, char *argv[]) { bool i_flag = false; long long indentation = 2; std::string path; for (int i = 1; i < argc; i++) { std::string arg = argv[i]; if (i_flag) { indentation = strtoll(argv[i], NULL, 10); i_flag = false; continue; } if (arg == "-i") { i_flag = true; } else if (arg == "--help" || arg == "-h") { usage(); } else if (path.empty()) { path = arg; } else { usage(); } } if (indentation < -1 || indentation > 8) { indentation = 2; } nlohmann::json j; if (!get_data(path, j)) { return 1; } try { std::cout << j.dump(indentation) << std::endl; return 0; } catch (nlohmann::json::exception &e) { std::cerr << "Failed to parse json: " << e.what() << std::endl; return 1; } }
30.92437
98
0.527989
[ "vector" ]
4c38adc5c99b4d442084600a82d3c98a6f92c02e
18,115
cpp
C++
src/public/src/ysgebl/src/kernelutil/ysshellext_patchutil.cpp
rothberg-cmu/rothberg-run
a42df5ca9fae97de77753864f60d05295d77b59f
[ "MIT" ]
1
2019-08-10T00:24:09.000Z
2019-08-10T00:24:09.000Z
src/public/src/ysgebl/src/kernelutil/ysshellext_patchutil.cpp
rothberg-cmu/rothberg-run
a42df5ca9fae97de77753864f60d05295d77b59f
[ "MIT" ]
null
null
null
src/public/src/ysgebl/src/kernelutil/ysshellext_patchutil.cpp
rothberg-cmu/rothberg-run
a42df5ca9fae97de77753864f60d05295d77b59f
[ "MIT" ]
2
2019-05-01T03:11:10.000Z
2019-05-01T03:30:35.000Z
/* //////////////////////////////////////////////////////////// File Name: ysshellext_patchutil.cpp Copyright (c) 2017 Soji Yamakawa. All rights reserved. http://www.ysflight.com Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //////////////////////////////////////////////////////////// */ #include "ysshellext_patchutil.h" #include "ysshellext_localop.h" #include "ysshellext_geomcalc.h" #include "ysshellext_orientationutil.h" YsShellExt_PatchBetweenTwoConstEdge::YsShellExt_PatchBetweenTwoConstEdge() { shl.EnableSearch(); } YsShellExt_PatchBetweenTwoConstEdge::~YsShellExt_PatchBetweenTwoConstEdge() { } void YsShellExt_PatchBetweenTwoConstEdge::CleanUp(void) { shl.CleanUp(); patchVtKeyToSrcVtHd.CleanUp(); patchVtKeyToSeqId.CleanUp(); seqCeHd[0]=NULL; seqCeHd[1]=NULL; rawVtHdSeq[0].CleanUp(); rawVtHdSeq[1].CleanUp(); vtHdSeq[0].CleanUp(); vtHdSeq[1].CleanUp(); totalLen[0]=0.0; totalLen[1]=0.0; } YSRESULT YsShellExt_PatchBetweenTwoConstEdge::SetVertexSequence(const YsShell &srcShl, YSSIZE_T nVt0,const YsShellVertexHandle vtHdArray0[],YSBOOL isLoop0, YSSIZE_T nVt1,const YsShellVertexHandle vtHdArray1[],YSBOOL isLoop1) { return SetVertexSequence(srcShl, YsConstArrayMask<YsShell::VertexHandle>(nVt0,vtHdArray0),YsArray<YsVec3>(),isLoop0, YsConstArrayMask<YsShell::VertexHandle>(nVt1,vtHdArray1),YsArray<YsVec3>(),isLoop1); } YSRESULT YsShellExt_PatchBetweenTwoConstEdge::SetVertexSequence(const YsShell &srcShl, const YsConstArrayMask <YsShell::VertexHandle> &vtHdArray0,const YsConstArrayMask <YsVec3> &vtPosArray0,YSBOOL isLoop0, const YsConstArrayMask <YsShell::VertexHandle> &vtHdArray1,const YsConstArrayMask <YsVec3> &vtPosArray1,YSBOOL isLoop1) { auto nVt0=vtHdArray0.size(); auto nVt1=vtHdArray1.size(); if((YSTRUE!=isLoop0 && 2>nVt0) || (YSTRUE==isLoop0 && 3>nVt0) || (YSTRUE!=isLoop1 && 2>nVt1) || (YSTRUE==isLoop1 && 3>nVt1)) { return YSERR; } YsArray <YsShellVertexHandle> newVtHdArray[2]; newVtHdArray[0].Set(nVt0,vtHdArray0); newVtHdArray[1].Set(nVt1,vtHdArray1); shl.CleanUp(); isLoop[0]=isLoop0; isLoop[1]=isLoop1; { YsHashTable <YsShell::VertexHandle> srcVtKeyToNewVtHd; for(int seq=0; seq<2; ++seq) { const auto nVt=newVtHdArray[seq].size(); const auto vtHdArray=newVtHdArray[seq].data(); const auto vtPosArray=(0==seq ? vtPosArray0 : vtPosArray1); for(YSSIZE_T idx=0; idx<nVt; ++idx) { YsShell::VertexHandle vtHd=nullptr; if(nullptr!=vtHdArray[idx] && YSOK==srcVtKeyToNewVtHd.FindElement(vtHd,srcShl.GetSearchKey(vtHdArray[idx])) && nullptr!=vtHd) { } else { if(nullptr!=vtHdArray[idx]) { vtHd=shl.AddVertex(srcShl.GetVertexPosition(vtHdArray[idx])); patchVtKeyToSrcVtHd.AddElement(shl.GetSearchKey(vtHd),vtHdArray[idx]); srcVtKeyToNewVtHd.AddElement(srcShl.GetSearchKey(vtHdArray[idx]),vtHd); } else { vtHd=shl.AddVertex(vtPosArray[idx]); } } int registeredSeqId=-1; if(YSOK==patchVtKeyToSeqId.FindElement(registeredSeqId,shl.GetSearchKey(vtHd)) && registeredSeqId!=seq) { patchVtKeyToSeqId.UpdateElement(shl.GetSearchKey(vtHd),-1); } else { patchVtKeyToSeqId.UpdateElement(shl.GetSearchKey(vtHd),seq); } rawVtHdSeq[seq].Append(vtHd); } } } if(YSOK==YsExtractNonSharedPart<YsShell::VertexHandle>(rawVtHdSeq[0],rawVtHdSeq[1],rawVtHdSeq[0],isLoop[0],rawVtHdSeq[1],isLoop[1])) { isLoop[0]=YSFALSE; isLoop[1]=YSFALSE; } // Did I assign patchVtKeyToSeqId right? >> for(int seq=0; seq<2; ++seq) { printf("Sequence %d\n",seq); for(auto vtHd : rawVtHdSeq[seq]) { int registeredSeqId=-1; patchVtKeyToSeqId.FindElement(registeredSeqId,shl.GetSearchKey(vtHd)); printf("%d\n",registeredSeqId); } } // Did I assign patchVtKeyToSeqId right? << for(int seq=0; seq<2; ++seq) { totalLen[seq]=0.0; for(YSSIZE_T idx=1; idx<rawVtHdSeq[seq].size(); ++idx) { totalLen[seq]+=shl.GetEdgeLength(rawVtHdSeq[seq][idx-1],rawVtHdSeq[seq][idx]); } if(YSTRUE==isLoop[seq] && 3<=rawVtHdSeq[seq].GetN()) { totalLen[seq]+=shl.GetEdgeLength(rawVtHdSeq[seq][0],rawVtHdSeq[seq].Last()); } vtHdSeq[seq]=rawVtHdSeq[seq]; seqCeHd[seq]=shl.AddConstEdge(rawVtHdSeq[seq],isLoop[seq]); } return YSOK; } YSRESULT YsShellExt_PatchBetweenTwoConstEdge::UpdateVertexSequence(int seqIdx,const YsShell &srcShl,const YsConstArrayMask <YsShell::VertexHandle> &srcVtHdArray) { YsArray <YsShell::VertexHandle> vtHdStock=srcVtHdArray; for(auto vtHd : vtHdSeq[seqIdx]) { YsShell::VertexHandle srcVtHd=nullptr; if(YSOK!=patchVtKeyToSrcVtHd.FindElement(srcVtHd,shl.GetSearchKey(vtHd))) { YSSIZE_T nearestIdx=-1; double nearDist=0.0; for(YSSIZE_T idx=0; idx<vtHdStock.size(); ++idx) { auto canVtHd=vtHdStock[idx]; auto dist=(shl.GetVertexPosition(vtHd)-srcShl.GetVertexPosition(canVtHd)).GetSquareLength(); if(0>nearestIdx || dist<nearDist) { nearDist=dist; nearestIdx=idx; } } if(0<=nearestIdx) { patchVtKeyToSrcVtHd.UpdateElement(shl.GetSearchKey(vtHd),vtHdStock[nearestIdx]); vtHdStock.DeleteBySwapping(nearestIdx); } } } return YSOK; } void YsShellExt_PatchBetweenTwoConstEdge::CalculateParameter(void) { for(int seq=0; seq<2; ++seq) { paramArray[seq].Set(vtHdSeq[seq].GetN(),NULL); if(YSTRUE==isLoop[seq]) { paramArray[seq].Increment(); } paramArray[seq][0]=0.0; paramArray[seq].Last()=1.0; double lSum=0.0; int last=(YSTRUE==isLoop[seq] ? 1 : 0); for(YSSIZE_T idx=1; idx<vtHdSeq[seq].GetN()-1+last; ++idx) { lSum+=shl.GetEdgeLength(vtHdSeq[seq][idx-1],vtHdSeq[seq].GetCyclic(idx)); paramArray[seq][idx]=lSum/totalLen[seq]; } printf("Sequence %d\n",seq); for(auto t : paramArray[seq]) { printf("%lf\n",t); } } } void YsShellExt_PatchBetweenTwoConstEdge::MakeInitialGuess(void) { YSSIZE_T index[2]={0,0}; int last[2]= { (YSTRUE==isLoop[0] ? 1 : 0), (YSTRUE==isLoop[1] ? 1 : 0), }; while(index[0]<paramArray[0].GetN()-1 || index[1]<paramArray[1].GetN()-1) { int nextMove=-1; if(index[0]>=paramArray[0].GetN()-1) { nextMove=1; } else if(index[1]>=paramArray[1].GetN()-1) { nextMove=0; } else if(paramArray[0][index[0]]<paramArray[1][index[1]]) { nextMove=0; } else { nextMove=1; } YsShellVertexHandle triVtHd[3]= { vtHdSeq[0].GetCyclic(index[0]), vtHdSeq[1].GetCyclic(index[1]), vtHdSeq[nextMove].GetCyclic(index[nextMove]+1) }; if(triVtHd[0]!=triVtHd[1] && triVtHd[1]!=triVtHd[2] && triVtHd[0]!=triVtHd[2]) { shl.AddPolygon(3,triVtHd); } ++index[nextMove]; } } void YsShellExt_PatchBetweenTwoConstEdge::MinimizeDihedralAngleSum(void) { YsArray <YsStaticArray <YsShellVertexHandle,2> > allEdge; YsShellEdgeEnumHandle edHd=NULL; while(YSOK==shl.MoveToNextEdge(edHd)) { YsShellVertexHandle edVtHd[2]; shl.GetEdge(edVtHd,edHd); if(0==shl.GetNumConstEdgeUsingEdgePiece(edVtHd)) { allEdge.Increment(); allEdge.Last()[0]=edVtHd[0]; allEdge.Last()[1]=edVtHd[1]; } } for(;;) { YSBOOL improvement=YSFALSE; for(auto &edVtHd : allEdge) { YsShell_SwapInfo swapInfo; if(YSOK==swapInfo.MakeInfo((const YsShell &)shl,edVtHd)) { if(0<shl.GetNumPolygonUsingEdge(swapInfo.newDiagonal[0],swapInfo.newDiagonal[1])) { continue; } int seqId[2]; if(YSOK!=patchVtKeyToSeqId.FindElement(seqId[0],shl.GetSearchKey(swapInfo.newDiagonal[0])) || YSOK!=patchVtKeyToSeqId.FindElement(seqId[1],shl.GetSearchKey(swapInfo.newDiagonal[1])) || seqId[0]==seqId[1] || seqId[0]<0 || // seqId[?] will be negative if the vertex is used from multiple sequences. seqId[1]<0) { continue; } const double oldDhaTotal=YsShellExt_CalculateTotalDihedralAngleAroundEdge(shl,swapInfo.orgDiagonal); YsArray <YsShellVertexHandle,4> oldTriVtHd[2]; shl.GetPolygon(oldTriVtHd[0],swapInfo.triPlHd[0]); shl.GetPolygon(oldTriVtHd[1],swapInfo.triPlHd[1]); shl.SetPolygonVertex(swapInfo.triPlHd[0],3,swapInfo.newTriVtHd[0]); shl.SetPolygonVertex(swapInfo.triPlHd[1],3,swapInfo.newTriVtHd[1]); const double newDhaTotal=YsShellExt_CalculateTotalDihedralAngleAroundEdge(shl,swapInfo.newDiagonal); if(newDhaTotal<oldDhaTotal-YsTolerance) { improvement=YSTRUE; edVtHd[0]=swapInfo.newDiagonal[0]; edVtHd[1]=swapInfo.newDiagonal[1]; } else { shl.SetPolygonVertex(swapInfo.triPlHd[0],oldTriVtHd[0]); shl.SetPolygonVertex(swapInfo.triPlHd[1],oldTriVtHd[1]); } } } if(YSTRUE!=improvement) { break; } } } void YsShellExt_PatchBetweenTwoConstEdge::MergeTriFormQuad(void) { // Greedy method YsArray <YsShell::Edge> edgeArray; YsArray <double> maxDotArray; YsShellEdgeEnumHandle edHd=NULL; while(YSOK==shl.MoveToNextEdge(edHd)) { auto edge=shl.GetEdge(edHd); YsShell_MergeInfo mergeInfo; auto edPlHd=shl.FindPolygonFromEdgePiece(edge); if(2==edPlHd.GetN() && YSOK==mergeInfo.MakeInfo(shl.Conv(),edPlHd)) { auto quadVtHd=mergeInfo.GetNewPolygon(); if(4==quadVtHd.GetN()) { int seqId[2]; if(YSOK!=patchVtKeyToSeqId.FindElement(seqId[0],shl.GetSearchKey(quadVtHd[0])) || YSOK!=patchVtKeyToSeqId.FindElement(seqId[1],shl.GetSearchKey(quadVtHd[2])) || seqId[0]==seqId[1] || seqId[0]<0 || // seqId[?] will be negative if the vertex is used from multiple sequences. seqId[1]<0) { continue; } if(YSOK!=patchVtKeyToSeqId.FindElement(seqId[0],shl.GetSearchKey(quadVtHd[1])) || YSOK!=patchVtKeyToSeqId.FindElement(seqId[1],shl.GetSearchKey(quadVtHd[3])) || seqId[0]==seqId[1] || seqId[0]<0 || // seqId[?] will be negative if the vertex is used from multiple sequences. seqId[1]<0) { continue; } // 2017/04/20 Quad-quality was checked by the shape quality. However, for this purpose, I think // plane-ness should be used. YsVec3 n[4]; for(int i=0; i<4; ++i) { YsVec3 v1=shl.GetVertexPosition(quadVtHd.GetCyclic(i+1))-shl.GetVertexPosition(quadVtHd[i]); YsVec3 v2=shl.GetVertexPosition(quadVtHd.GetCyclic(i+2))-shl.GetVertexPosition(quadVtHd.GetCyclic(i+1)); n[i]=YsUnitVector(v1^v2); } double minDot=0.0; for(int i=0; i<4; ++i) { for(int j=i+1; j<4; ++j) { YsMakeSmaller(minDot,fabs(n[i]*n[j])); } } edgeArray.Add(edge); maxDotArray.Add(-minDot); } } NEXTEDGE: ; } YsSimpleMergeSort<double,YsShell::Edge>(maxDotArray.GetN(),maxDotArray,edgeArray); for(auto edge : edgeArray) { YsShell_MergeInfo mergeInfo; auto edPlHd=shl.FindPolygonFromEdgePiece(edge); if(2==edPlHd.GetN() && YSOK==mergeInfo.MakeInfo(shl.Conv(),edPlHd)) { auto quadVtHd=mergeInfo.GetNewPolygon(); if(4==quadVtHd.GetN()) { shl.SetPolygonVertex(edPlHd[0],quadVtHd); shl.DeletePolygon(edPlHd[1]); } } } } YsArray <YsShell::VertexHandle> YsShellExt_PatchBetweenTwoConstEdge::GetVertexSequence(int seq) const { YsArray <YsShell::VertexHandle> vtHdArray; for(auto vtHd : vtHdSeq[seq]) { YsShell::VertexHandle srcVtHd=nullptr; patchVtKeyToSrcVtHd.FindElement(srcVtHd,shl.GetSearchKey(vtHd)); vtHdArray.push_back(srcVtHd); } return vtHdArray; } //////////////////////////////////////////////////////////// void YsShellExt_MultiPatchSequence::CleanUp(void) { for(auto &patch : patchUtil) { patch.CleanUp(); } patchUtil.CleanUp(); } const YsConstArrayMask<YsShellExt_PatchBetweenTwoConstEdge> YsShellExt_MultiPatchSequence::GetPatchSequence(void) const { YsConstArrayMask <YsShellExt_PatchBetweenTwoConstEdge> mask=patchUtil; return mask; } YSRESULT YsShellExt_MultiPatchSequence::SetUpFromConstEdge(const YsShellExt &srcShl,const YsConstArrayMask<YsShellExt::ConstEdgeHandle> &ceHdArray) { if(2>ceHdArray.size()) { return YSERR; } patchUtil.Set(ceHdArray.GetN()-1,NULL); for(YSSIZE_T idx=0; idx<ceHdArray.GetN()-1; ++idx) { YsArray <YsShellVertexHandle> ceVtHd[2]; YSBOOL isLoop[2]; srcShl.GetConstEdge(ceVtHd[0],isLoop[0],ceHdArray[idx]); srcShl.GetConstEdge(ceVtHd[1],isLoop[1],ceHdArray[idx+1]); patchUtil[idx].CleanUp(); if(YSOK!=patchUtil[idx].SetVertexSequence(srcShl.Conv(),ceVtHd,isLoop)) { return YSERR; } patchUtil[idx].CalculateParameter(); patchUtil[idx].MakeInitialGuess(); patchUtil[idx].MinimizeDihedralAngleSum(); } CalculateNormal(); return YSOK; } YSRESULT YsShellExt_MultiPatchSequence::SetUpFromPolygon(const YsShellExt &srcShl,const YsConstArrayMask<YsShell::PolygonHandle> &inPlHd) { if(2>inPlHd.size()) { return YSERR; } patchUtil.Set(inPlHd.GetN()-1,NULL); for(YSSIZE_T idx=0; idx<inPlHd.GetN()-1; ++idx) { YsArray <YsShellVertexHandle> plVtHd[2]; const YSBOOL isLoop[2]={YSTRUE,YSTRUE}; srcShl.GetPolygon(plVtHd[0],inPlHd[idx]); srcShl.GetPolygon(plVtHd[1],inPlHd[idx+1]); patchUtil[idx].CleanUp(); if(YSOK!=patchUtil[idx].SetVertexSequence(srcShl.Conv(),plVtHd,isLoop)) { return YSERR; } patchUtil[idx].CalculateParameter(); patchUtil[idx].MakeInitialGuess(); patchUtil[idx].MinimizeDihedralAngleSum(); } CalculateNormal(); return YSOK; } YSRESULT YsShellExt_MultiPatchSequence::SetUpFromFirstLastCrossSectionAndPathBetween( const YsShellExt &srcShl, const YsConstArrayMask <YsShell::VertexHandle> &seg0In, const YsConstArrayMask <YsShell::VertexHandle> &seg1In, const YsConstArrayMask <YsShell::VertexHandle> &pathIn) { YsArray <YsShell::VertexHandle> seg[2]= { seg0In,seg1In }; YsArray <YsShell::VertexHandle> path=pathIn; if(YSTRUE==seg[0].IsIncluded(path.front()) && YSTRUE==seg[1].IsIncluded(path.back())) { path.pop_back(); } if(YSTRUE==seg[0].IsIncluded(path.back()) && YSTRUE==seg[1].IsIncluded(path.front())) { path.Invert(); path.pop_back(); } else if(YSTRUE==seg[0].IsIncluded(path.front()) && YSTRUE!=seg[1].IsIncluded(path.back())) { // In this case, nothing to do. } else if(YSTRUE==seg[0].IsIncluded(path.back()) && YSTRUE!=seg[1].IsIncluded(path.front())) { path.Invert(); } const YsVec3 axsVtPos[2]= { srcShl.GetVertexPosition(seg[0].front()), srcShl.GetVertexPosition(seg[0].back()) }; auto xAxs=YsUnitVector(axsVtPos[1]-axsVtPos[0]); YsVec3 origin; YsVec3 yAxs; double L0; YsGetNearestPointOnLine3(origin,axsVtPos[0],axsVtPos[1],srcShl.GetVertexPosition(path[0])); yAxs=srcShl.GetVertexPosition(path[0])-origin; L0=yAxs.GetLength(); yAxs/=L0; YSSIZE_T indexOfPathInSeg=-1; for(YSSIZE_T i=0; i<seg[0].size(); ++i) { if(seg[0][i]==path[0]) { indexOfPathInSeg=i; break; } } if(0>=indexOfPathInSeg) { return YSERR; } YsArray <YsShell::VertexHandle> prevSeg=seg[0]; YsArray <YsVec3> prevSegPos; patchUtil.resize(path.size()); for(YSSIZE_T i=0; i<path.size(); ++i) { YsArray <YsShell::VertexHandle> nextSeg; YsArray <YsVec3> nextSegPos; if(i==path.size()-1) { nextSeg=seg[1]; } else { YsVec3 nextYAxs=srcShl.GetVertexPosition(path[i+1])-origin; double L=nextYAxs.GetLength(); nextYAxs/=L; double yScale=L/L0; nextSeg.resize(seg[0].size()); nextSegPos.resize(seg[0].size()); for(YSSIZE_T idx=0; idx<seg[0].size(); ++idx) { auto v=srcShl.GetVertexPosition(seg[0][idx]); double x=(v-origin)*xAxs; double y=(v-origin)*yAxs; nextSeg[idx]=nullptr; nextSegPos[idx]=origin+x*xAxs+y*nextYAxs*yScale; } nextSeg[0]=seg[0].front(); nextSeg[indexOfPathInSeg]=path[i+1]; nextSeg.back()=seg[0].back(); } patchUtil[i].SetVertexSequence(srcShl.Conv(),prevSeg,prevSegPos,YSFALSE,nextSeg,nextSegPos,YSFALSE); patchUtil[i].CalculateParameter(); patchUtil[i].MakeInitialGuess(); patchUtil[i].MinimizeDihedralAngleSum(); prevSeg=nextSeg; prevSegPos=nextSegPos; } CalculateNormal(); return YSOK; } void YsShellExt_MultiPatchSequence::CalculateNormal(void) { for(auto &patch : patchUtil) { YsShellExt_OrientationUtil orientationUtil; orientationUtil.CleanUp(); orientationUtil.FixOrientationOfClosedSolid(patch.shl); auto plHdNeedFip=orientationUtil.GetPolygonNeedFlip(); for(auto plHd : plHdNeedFip) { YsArray <YsShellVertexHandle,4> plVtHd; patch.shl.GetPolygon(plVtHd,plHd); plVtHd.Invert(); patch.shl.SetPolygonVertex(plHd,plVtHd); } orientationUtil.RecalculateNormalFromCurrentOrientation((const YsShell &)patch.shl); auto plNomPairNeedNormalReset=orientationUtil.GetPolygonNormalPair(); for(auto plNomPair : plNomPairNeedNormalReset) { patch.shl.SetPolygonNormal(plNomPair.plHd,plNomPair.nom); } } } void YsShellExt_MultiPatchSequence::Invert(void) { for(auto &patch : patchUtil) { YsShellExt_OrientationUtil::InvertPolygonAll(patch.shl); } } void YsShellExt_MultiPatchSequence::MergeTriFormQuad(void) { for(auto &patch : patchUtil) { patch.MergeTriFormQuad(); } }
27.281627
161
0.700193
[ "shape" ]
4c3ac301a09f4cfbbca60785ec4dfc325e6f7565
2,039
cpp
C++
Stacks/EvaluateReversePolishNotation150.cpp
devangi2000/Data-Structures-Algorithms-Handbook
ce0f00de89af5da7f986e65089402dc6908a09b5
[ "MIT" ]
38
2021-10-14T09:36:53.000Z
2022-01-27T02:36:19.000Z
Stacks/EvaluateReversePolishNotation150.cpp
devangi2000/Data-Structures-Algorithms-Handbook
ce0f00de89af5da7f986e65089402dc6908a09b5
[ "MIT" ]
null
null
null
Stacks/EvaluateReversePolishNotation150.cpp
devangi2000/Data-Structures-Algorithms-Handbook
ce0f00de89af5da7f986e65089402dc6908a09b5
[ "MIT" ]
4
2021-12-06T15:47:12.000Z
2022-02-04T04:25:00.000Z
// Evaluate the value of an arithmetic expression in Reverse Polish Notation. // Valid operators are +, -, *, and /. Each operand may be an integer or another expression. // Note that division between two integers should truncate toward zero. // It is guaranteed that the given RPN expression is always valid. That means the expression would always evaluate to a result, and there will not be any division by zero operation. // Example 1: // Input: tokens = ["2","1","+","3","*"] // Output: 9 // Explanation: ((2 + 1) * 3) = 9 // Example 2: // Input: tokens = ["4","13","5","/","+"] // Output: 6 // Explanation: (4 + (13 / 5)) = 6 // Example 3: // Input: tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"] // Output: 22 // Explanation: ((10 * (6 / ((9 + 3) * -11))) + 17) + 5 // = ((10 * (6 / (12 * -11))) + 17) + 5 // = ((10 * (6 / -132)) + 17) + 5 // = ((10 * 0) + 17) + 5 // = (0 + 17) + 5 // = 17 + 5 // = 22 // Constraints: // 1 <= tokens.length <= 104 // tokens[i] is either an operator: "+", "-", "*", or "/", or an integer in the range [-200, 200]. class Solution { public: int evalRPN(vector<string>& tokens) { stack<int> st; for(int i = 0; i < tokens.size(); i++){ if(tokens[i].size() > 1 or isdigit(tokens[i][0])){ st.push(stoi(tokens[i])); } else{ int x = st.top(); st.pop(); int y = st.top(); st.pop(); switch(tokens[i][0]){ case '+': st.push(x + y); break; case '-': st.push(y - x); break; case '*': st.push(x * y); break; case '/': st.push(y / x); break; } } } return st.top(); } };
29.128571
182
0.413438
[ "vector" ]
4c43f06cd807d6e0afe1127107071abd7a0b3c76
1,337
cpp
C++
450_set/Matrix/0044.cpp
Sahil1515/coding
2bd2a2257c8cac5a5c00b37e79bbb68a24e186d4
[ "RSA-MD" ]
null
null
null
450_set/Matrix/0044.cpp
Sahil1515/coding
2bd2a2257c8cac5a5c00b37e79bbb68a24e186d4
[ "RSA-MD" ]
null
null
null
450_set/Matrix/0044.cpp
Sahil1515/coding
2bd2a2257c8cac5a5c00b37e79bbb68a24e186d4
[ "RSA-MD" ]
null
null
null
// } Driver Code Ends class Solution { public: void rotateby90(vector<vector<int> >& matrix, int n) { // code here for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if(i<j) { swap(matrix[i][j],matrix[j][i]); } } } for(int i=0;i<n;i++) {https://media.geeksforgeeks.org/img-practice/check-square-1596781127.svg int j=0,k=n-1; while(j<k){ int temp=matrix[j][i]; matrix[j][i]=matrix[k][i]; matrix[k][i]=temp; j++; k--; } } } }; // { Driver Code Starts. int main() { int t; cin>>t; while(t--) { int n; cin>>n; vector<vector<int> > matrix(n); for(int i=0; i<n; i++) { matrix[i].assign(n, 0); for( int j=0; j<n; j++) { cin>>matrix[i][j]; } } Solution ob; ob.rotateby90(matrix, n); for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) cout<<matrix[i][j]<<" "; cout<<endl; } return 0; } // } Driver Code Ends
20.890625
81
0.347794
[ "vector" ]
4c44b3634733d6c074224429a9758b51c7d004ea
2,549
hpp
C++
src/grids.hpp
keijak/hikidashi-cpp
63d01dfa1587fa56fd7f4e50712f7c10d8168520
[ "Apache-2.0" ]
null
null
null
src/grids.hpp
keijak/hikidashi-cpp
63d01dfa1587fa56fd7f4e50712f7c10d8168520
[ "Apache-2.0" ]
null
null
null
src/grids.hpp
keijak/hikidashi-cpp
63d01dfa1587fa56fd7f4e50712f7c10d8168520
[ "Apache-2.0" ]
null
null
null
#include <bits/stdc++.h> auto make_neighbors(int H, int W) { static const int dx[4] = {1, 0, -1, 0}; static const int dy[4] = {0, 1, 0, -1}; auto inside = [&](int i, int j) { return 0 <= i and i < H and 0 <= j and j < W; }; auto neighbors = [&](int x, int y) { std::vector<std::pair<int, int>> ret; ret.reserve(4); for (int d = 0; d < 4; ++d) { const int nx = x + dx[d]; const int ny = y + dy[d]; if (not inside(nx, ny)) continue; ret.emplace_back(nx, ny); } return ret; }; return std::pair{inside, neighbors}; } template <typename V> void transpose(std::vector<V> &grid) { const int h = grid.size(); if (h == 0) return; const int w = grid[0].size(); if (w == 0) return; std::vector<V> tmp(w, V(h, grid[0][0])); for (int i = 0; i < h; ++i) { for (int j = 0; j < w; ++j) { tmp[j][i] = grid[i][j]; } } std::swap(grid, tmp); } template <typename V> void transpose(std::vector<V> &grid, int &H, int &W) { transpose(grid); std::swap(H, W); } template <typename V> void rotate90(std::vector<V> &grid) { const int h = grid.size(); if (h == 0) return; const int w = grid[0].size(); if (w == 0) return; std::vector<V> tmp(w, V(h, grid[0][0])); for (int i = 0; i < h; ++i) { for (int j = 0; j < w; ++j) { tmp[w - 1 - j][i] = grid[i][j]; } } std::swap(grid, tmp); } template <typename V> void rotate90(std::vector<V> &grid, int &H, int &W) { rotate90(grid); std::swap(H, W); } template <typename V> void rotate180(std::vector<V> &grid) { const int h = grid.size(); if (h == 0) return; const int w = grid[0].size(); if (w == 0) return; auto tmp = grid; for (int i = 0; i < h; ++i) { for (int j = 0; j < w; ++j) { tmp[h - 1 - i][w - 1 - j] = grid[i][j]; } } std::swap(grid, tmp); } // Swaps i-th column and (W-1-i)-th column. template <typename V> void flip_horizontally(std::vector<V> &grid) { const int h = grid.size(); if (h == 0) return; const int w = grid[0].size(); if (w == 0) return; for (int i = 0; i < h; ++i) { for (int j = 0;; ++j) { const int r = w - 1 - j; if (r <= j) break; std::swap(grid[i][j], grid[i][r]); } } } // Swaps i-th row and (H-1-i)-th row. template <typename V> void flip_vertically(std::vector<V> &grid) { const int h = grid.size(); if (h == 0) return; const int w = grid[0].size(); if (w == 0) return; for (int i = 0;; ++i) { const int r = h - 1 - i; if (r <= i) break; std::swap(grid[i], grid[r]); } }
23.82243
54
0.515104
[ "vector" ]
4c4a8aaa1fc86af6caaba463d490917a7ea489d9
2,837
hpp
C++
include/caffe/layers/fm_layer.hpp
Lanselott/FM_caffe
f87df8c5b1b2252fce6b9bab4cccf120d96774e5
[ "MIT" ]
null
null
null
include/caffe/layers/fm_layer.hpp
Lanselott/FM_caffe
f87df8c5b1b2252fce6b9bab4cccf120d96774e5
[ "MIT" ]
null
null
null
include/caffe/layers/fm_layer.hpp
Lanselott/FM_caffe
f87df8c5b1b2252fce6b9bab4cccf120d96774e5
[ "MIT" ]
null
null
null
#ifndef CAFFE_FM_LAYER_HPP_ #define CAFFE_FM_LAYER_HPP_ #include <vector> #include "caffe/blob.hpp" #include "caffe/layer.hpp" #include "caffe/proto/caffe.pb.h" #include "caffe/util/im2col.hpp" namespace caffe { /** * @brief Also known as a "fully-connected" layer, computes an inner product * with a set of learned weights, and (optionally) adds biases. * * TODO(dox): thorough documentation for Forward, Backward, and proto params. */ template <typename Dtype> class FmLayer : public Layer<Dtype> { public: explicit FmLayer(const LayerParameter &param) : Layer<Dtype>(param) {} virtual void LayerSetUp(const vector<Blob<Dtype> *> &bottom, const vector<Blob<Dtype> *> &top); virtual void Reshape(const vector<Blob<Dtype> *> &bottom, const vector<Blob<Dtype> *> &top); virtual inline const char *type() const { return "Fm"; } virtual inline int ExactNumBottomBlobs() const { return 1; } virtual inline int ExactNumTopBlobs() const { return 1; } protected: /* inline void conv_im2col_cpu(const Dtype *data, Dtype *col_buff, int *all_zero_mask = NULL) { im2col_nd_cpu(data, num_spatial_axes_, conv_input_shape_.cpu_data(), col_buffer_shape_.data(), kernel_shape_.cpu_data(), pad_.cpu_data(), stride_.cpu_data(), dilation_.cpu_data(), col_buff); } */ virtual void Forward_cpu(const vector<Blob<Dtype> *> &bottom, const vector<Blob<Dtype> *> &top); virtual void Forward_gpu(const vector<Blob<Dtype> *> &bottom, const vector<Blob<Dtype> *> &top); virtual void Backward_cpu(const vector<Blob<Dtype> *> &top, const vector<bool> &propagate_down, const vector<Blob<Dtype> *> &bottom); virtual void Backward_gpu(const vector<Blob<Dtype> *> &top, const vector<bool> &propagate_down, const vector<Blob<Dtype> *> &bottom); int M_; int K_; int N_; int conv_out_spatial_dim_; int col_offset_; bool csr_init; bool bias_term_; vector<int> col_buffer_shape_; Blob<Dtype> col_buffer_; Blob<Dtype> bias_multiplier_; Blob<Dtype> v_vector_; bool transpose_; ///< if true, assume transposed weights int k_value; bool do_sparse; Blob<int> col_buf_mask_; Blob<int> row_buf_mask_; vector<int> left_columns_; //the number of left columns of weight matrix for each group vector<int> left_rows_; Blob<Dtype> squeezed_weight_buffer_; Blob<Dtype> nz_weight_values_;//nonzero elements Blob<int> nz_weight_indices_;//index of nonzero Blob<int> nz_weight_index_pointers_;//pointer(index) of indices }; } // namespace caffe #endif // CAFFE_INNER_PRODUCT_LAYER_HPP_
34.180723
103
0.656327
[ "vector" ]
4c4c424805066694eebb2362d90947ffb0538d95
1,370
cpp
C++
game_files/game_objects/tt.cpp
sakumo7/zpr
7b9cdbec1ff8d8179a96bb6e1e88f54ee84d138e
[ "MIT" ]
null
null
null
game_files/game_objects/tt.cpp
sakumo7/zpr
7b9cdbec1ff8d8179a96bb6e1e88f54ee84d138e
[ "MIT" ]
null
null
null
game_files/game_objects/tt.cpp
sakumo7/zpr
7b9cdbec1ff8d8179a96bb6e1e88f54ee84d138e
[ "MIT" ]
null
null
null
#include "../game_order/game_order.hpp" #include "building.hpp" #include <cstdio> #include <iostream> #include <vector> #include <memory> #include "../game_order/order_decoder.hpp" #include "game_object_factory.hpp" #include "game_object.hpp" #include "map_point.hpp" using namespace std; int main(){ Resources r(500); Building building(12); shared_ptr<Player> player = make_shared<Player>("player"); player->resources_=r; player->ships_.push_back(make_shared<Ship>(12,13)); player->ships_.push_back(make_shared<Ship>(32,123)); player->buildings_.push_back(make_shared<Building>(12)); player->id_=3; shared_ptr<Player> player2 = make_shared<Player>("player2"); Resources r2(300); player2->resources_=r2; player2->ships_.push_back(make_shared<Ship>(1,3)); player2->ships_.push_back(make_shared<Ship>(322,1213)); player2->buildings_.push_back(make_shared<Building>(12)); player2->buildings_.push_back(make_shared<Building>(124)); player2->buildings_.push_back(make_shared<Building>(112)); player2->id_=2; GameState game_state; game_state.players_.push_back(player); game_state.players_.push_back(player2); cout<<endl; GameState game_state2; game_state2.loadFromString(game_state.toString()); if((game_state.toString()).compare(game_state2.toString())){ }else cout<<"zapisywanie do string i odczytywanie poprawne"; return 0; }
25.37037
62
0.754015
[ "vector" ]
4c4c4c2803396ba63d399157f03c3a4cea1e3009
7,439
cpp
C++
src/main/core/engine/scene/GameObject.cpp
Kelan0/PlanetRenderer-2.0
55bebcdadb253cb3dd9165d0d4161966ac90ea95
[ "MIT" ]
2
2020-10-29T01:45:38.000Z
2021-07-21T08:19:36.000Z
src/main/core/engine/scene/GameObject.cpp
Kelan0/PlanetRenderer-2.0
55bebcdadb253cb3dd9165d0d4161966ac90ea95
[ "MIT" ]
null
null
null
src/main/core/engine/scene/GameObject.cpp
Kelan0/PlanetRenderer-2.0
55bebcdadb253cb3dd9165d0d4161966ac90ea95
[ "MIT" ]
4
2019-10-08T23:24:10.000Z
2021-03-02T16:05:28.000Z
#include "GameObject.h" #include "core/application/Application.h" #include "core/engine/scene/GameComponent.h" #include "core/engine/scene/SceneGraph.h" bool isValidId(std::string id); GameObject::GameObject(Transformation transformation) { this->setTransformation(transformation); this->parent = NULL; this->sceneTreeDepth = 0; } GameObject::GameObject(GameObject* parent, std::string name, Transformation transformation) { this->setTransformation(transformation); this->parent = NULL; this->sceneTreeDepth = 0; if (parent != NULL) { parent->addChild(name, this); } else { this->parent = NULL; this->sceneTreeDepth = 0; } } GameObject::~GameObject() { if (this->parent != NULL) { this->parent->removeChild(this); } for (auto it = this->children.begin(); it != this->children.end(); it++) { delete it->second; } for (auto it = this->components.begin(); it != this->components.end(); it++) { delete it->second; } } void GameObject::setParent(GameObject* _parent, std::string _id) { if (this->parent != NULL) { if (!this->parent->removeChild(this)) { logWarn("New parent was set directly, but this GameObject was not found in its old parent. The parent was not notified of its removal."); } } // TODO: check for circular branches. this->parent = _parent; this->name = _id; this->updateSceneTree(); } void GameObject::updateSceneTree() { if (this->parent != NULL) { this->sceneTreeDepth = this->parent->getSceneTreeDepth() + 1; } else { this->sceneTreeDepth = 0; } for (auto it = this->children.begin(); it != this->children.end(); it++) { if (it->second != NULL) { it->second->updateSceneTree(); } } } bool GameObject::isValidId(std::string id) { return id.size() > 0; } void GameObject::render(SceneGraph* sceneGraph, double partialTicks, double dt) { sceneGraph->pushTransformationState(this->getTransformation()); for (auto it = this->components.begin(); it != this->components.end(); it++) { if (it->second != NULL) { it->second->render(sceneGraph, partialTicks, dt); } } for (auto it = this->children.begin(); it != this->children.end(); it++) { if (it->second != NULL) { it->second->render(sceneGraph, partialTicks, dt); } } sceneGraph->popTransformationState(); } void GameObject::update(SceneGraph* sceneGraph, double dt) { sceneGraph->pushTransformationState(this->getTransformation()); for (auto it = this->components.begin(); it != this->components.end(); it++) { if (it->second != NULL) { it->second->update(sceneGraph, dt); } } for (auto it = this->children.begin(); it != this->children.end(); it++) { if (it->second != NULL) { it->second->update(sceneGraph, dt); } } sceneGraph->popTransformationState(); } std::string GameObject::getName() { return this->name; } std::vector<std::string> GameObject::getChildNames() { std::vector<std::string> names; names.reserve(this->children.size()); for (auto it = this->children.begin(); it != this->children.end(); it++) { names.push_back(it->first); } return names; } int32 GameObject::getChildCount() { return this->children.size(); } GameObject* GameObject::getParent() { return this->parent; } GameObject* GameObject::getRoot() { if (this->parent != NULL) { return this->parent->getRoot(); } else { return this; } } GameObject* GameObject::findClosestAncestor(std::string id) { if (this->parent != NULL) { std::vector<std::string> names = this->parent->getChildNames(); for (auto it = names.begin(); it != names.end(); it++) { if (*it == id) { return this->parent->getChild(*it); } } } return NULL; } GameObject* GameObject::findClosestDescendent(std::string id) { // TODO: BFS/DFS option //or (auto it = children.begin(); it != children.end(); it++) { // if (it->first == id) { // return it->second; // } // return NULL; } int32 GameObject::getSceneTreeDepth() { return this->sceneTreeDepth; } bool GameObject::hasChild(std::string id) { if (this->isValidId(id)) { auto it = this->children.find(id); return it != this->children.end() && it->second != NULL; } return false; } GameObject* GameObject::getChild(std::string id) { if (this->isValidId(id)) { auto it = this->children.find(id); if (it != this->children.end()) { return it->second; } } return NULL; } GameObject* GameObject::addChild(std::string id, GameObject* object) { GameObject* replaced = NULL; if (this->isValidId(id)) { auto it = this->children.find(id); if (it != this->children.end()) { replaced = it->second; } if (object == NULL) { this->children.erase(it); } else { this->children[id] = object; object->setParent(this, id); } } return replaced; } GameObject* GameObject::removeChild(std::string id) { auto it = this->children.find(id); GameObject* removed = NULL; if (it != this->children.end()) { removed = it->second; this->children.erase(it); if (removed != NULL) { removed->setParent(NULL, ""); } } return removed; } bool GameObject::removeChild(GameObject* object) { for (auto it = this->children.begin(); it != this->children.end(); it++) { GameObject* removed = it->second; if (removed == object) { this->children.erase(it); if (removed != NULL) { removed->setParent(NULL, ""); } return true; } } return false; } bool GameObject::hasComponent(std::string id) { if (this->isValidId(id)) { auto it = this->components.find(id); return it != this->components.end() && it->second != NULL; } return false; } GameComponent* GameObject::getComponent(std::string id) { if (this->isValidId(id)) { auto it = this->components.find(id); if (it != this->components.end()) { return it->second; } } return NULL; } GameComponent* GameObject::addComponent(std::string id, GameComponent* component) { GameComponent* replaced = NULL; if (this->isValidId(id)) { auto it = this->components.find(id); if (it != this->components.end()) { replaced = it->second; } if (component == NULL) { this->components.erase(it); } else { this->components[id] = component; component->parent = this; } } return replaced; } GameComponent* GameObject::removeComponent(std::string id) { auto it = this->components.find(id); GameComponent* removed = NULL; if (it != this->components.end()) { removed = it->second; this->components.erase(it); if (removed != NULL) { removed->parent = NULL; } } return removed; } bool GameObject::removeComponent(GameComponent* component) { for (auto it = this->components.begin(); it != this->components.end(); it++) { GameComponent* removed = it->second; if (removed == component) { this->components.erase(it); if (removed != NULL) { removed->parent = NULL; } return true; } } return false; } void GameObject::setTransformation(Transformation transformation) { this->transformation = transformation; } Transformation& GameObject::getTransformation() { return this->transformation; } Transformation GameObject::getGlobalTransformation() { // This is potentially slow to calculate for big scene trees... this should be cached when possible. Transformation transform(this->getTransformation()); if (parent != NULL) { Transformation p = parent->getGlobalTransformation(); transform.translate(p.getTranslation()); transform.rotate(p.getOrientation()); transform.scale(p.getScale()); } return transform; }
21.688047
155
0.659363
[ "render", "object", "vector", "transform" ]
4c5db0f0e0854db04840be7742680befcde3f9dc
377
hpp
C++
CCP4M_Old/include/CommonFuncs.hpp
Electrux/CCPP-Code
3c5e5b866cf050c11bced9651b112eb31dd2465d
[ "BSD-3-Clause" ]
6
2019-08-29T23:31:17.000Z
2021-11-14T20:35:47.000Z
CCP4M_Old/include/CommonFuncs.hpp
Electrux/CCPP-Code
3c5e5b866cf050c11bced9651b112eb31dd2465d
[ "BSD-3-Clause" ]
null
null
null
CCP4M_Old/include/CommonFuncs.hpp
Electrux/CCPP-Code
3c5e5b866cf050c11bced9651b112eb31dd2465d
[ "BSD-3-Clause" ]
1
2019-09-01T12:22:58.000Z
2019-09-01T12:22:58.000Z
#ifndef COMMONFUNCS_HPP #define COMMONFUNCS_HPP #include <string> #include <vector> std::vector< std::string > ToVector( int argc, char ** argv ); std::vector< std::string > DelimStringToVector( std::string str, char delim = ',' ); std::string GetStringBetweenQuotes( std::string & str ); std::string GetStringTillLastSlash( std::string & str ); #endif //COMMONFUNCS_HPP
23.5625
84
0.724138
[ "vector" ]
4c6264b5f3c5542704482de4a44db59b738b2442
2,921
cc
C++
driver/kernel/windows/kernel_registers_windows.cc
ghollingworth/libedgetpu
d37e668cd9ef0e657b9e4e413df53f370532e87e
[ "Apache-2.0" ]
99
2020-06-09T05:52:44.000Z
2022-03-08T06:06:55.000Z
driver/kernel/windows/kernel_registers_windows.cc
ghollingworth/libedgetpu
d37e668cd9ef0e657b9e4e413df53f370532e87e
[ "Apache-2.0" ]
35
2020-06-09T15:00:26.000Z
2022-03-15T10:22:32.000Z
driver/kernel/windows/kernel_registers_windows.cc
ghollingworth/libedgetpu
d37e668cd9ef0e657b9e4e413df53f370532e87e
[ "Apache-2.0" ]
23
2020-06-09T14:50:54.000Z
2022-03-15T11:18:16.000Z
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "driver/kernel/windows/kernel_registers_windows.h" #include <fcntl.h> #include <io.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include "driver/kernel/gasket_ioctl.h" #include "driver/registers/registers.h" #include "port/errors.h" #include "port/integral_types.h" #include "port/status.h" #include "port/status_macros.h" #include "port/statusor.h" #include "port/std_mutex_lock.h" #include "port/stringprintf.h" namespace platforms { namespace darwinn { namespace driver { KernelRegistersWindows::KernelRegistersWindows( const std::string& device_path, const std::vector<MmapRegion>& mmap_region, bool read_only) : KernelRegisters(device_path, mmap_region, read_only) {} KernelRegistersWindows::KernelRegistersWindows(const std::string& device_path, uint64 mmap_offset, uint64 mmap_size, bool read_only) : KernelRegisters(device_path, mmap_offset, mmap_size, read_only) {} KernelRegistersWindows::~KernelRegistersWindows() { UnmapAllRegions(); } StatusOr<uint64*> KernelRegistersWindows::MapRegion( FileDescriptor fd, const MappedRegisterRegion& region, bool read_only) { gasket_address_map_ioctl ioctl = {0, region.offset, region.size, 0, 0, nullptr}; bool res; res = DeviceIoControl(fd, GASKET_IOCTL_MAP_HDW_VIEW, &ioctl, sizeof(ioctl), &ioctl, sizeof(ioctl), NULL, NULL); if (!res) { return InternalError(StringPrintf( "KernelRegisters::MapRegion failed! gle=%d", GetLastError())); } return static_cast<uint64*>(ioctl.virtaddr); } Status KernelRegistersWindows::UnmapRegion(FileDescriptor fd, const MappedRegisterRegion& region) { gasket_address_map_ioctl ioctl = {0, region.offset, region.size, 0, 0, region.registers}; bool res; res = DeviceIoControl(fd, GASKET_IOCTL_UNMAP_HDW_VIEW, &ioctl, sizeof(ioctl), &ioctl, sizeof(ioctl), NULL, NULL); if (!res) { FailedPreconditionError(StringPrintf( "KernelRegisters::UnmapRegion failed! gle=%d", GetLastError())); } return OkStatus(); } } // namespace driver } // namespace darwinn } // namespace platforms
34.77381
80
0.682643
[ "vector" ]
4c66825b8bd15e90abd6689fb9051efdd83b32a2
1,912
cc
C++
vcs/src/model/RegisterDeviceRequest.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
vcs/src/model/RegisterDeviceRequest.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
vcs/src/model/RegisterDeviceRequest.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/vcs/model/RegisterDeviceRequest.h> using AlibabaCloud::Vcs::Model::RegisterDeviceRequest; RegisterDeviceRequest::RegisterDeviceRequest() : RpcServiceRequest("vcs", "2020-05-15", "RegisterDevice") { setMethod(HttpRequest::Method::Post); } RegisterDeviceRequest::~RegisterDeviceRequest() {} std::string RegisterDeviceRequest::getDeviceTimeStamp()const { return deviceTimeStamp_; } void RegisterDeviceRequest::setDeviceTimeStamp(const std::string& deviceTimeStamp) { deviceTimeStamp_ = deviceTimeStamp; setBodyParameter("DeviceTimeStamp", deviceTimeStamp); } std::string RegisterDeviceRequest::getDeviceSn()const { return deviceSn_; } void RegisterDeviceRequest::setDeviceSn(const std::string& deviceSn) { deviceSn_ = deviceSn; setBodyParameter("DeviceSn", deviceSn); } std::string RegisterDeviceRequest::getDeviceId()const { return deviceId_; } void RegisterDeviceRequest::setDeviceId(const std::string& deviceId) { deviceId_ = deviceId; setBodyParameter("DeviceId", deviceId); } std::string RegisterDeviceRequest::getServerId()const { return serverId_; } void RegisterDeviceRequest::setServerId(const std::string& serverId) { serverId_ = serverId; setBodyParameter("ServerId", serverId); }
25.837838
83
0.753661
[ "model" ]
4c68d9614a470ebbc85017c683d002b0ba37a526
7,779
cpp
C++
Source/modules/webcl/WebCLEvent.cpp
crosswalk-project/blink-crosswalk
16d1b69626699e9ca703e0c24c829e96d07fcd3e
[ "BSD-3-Clause" ]
18
2015-04-16T09:57:11.000Z
2020-12-09T15:58:55.000Z
Source/modules/webcl/WebCLEvent.cpp
crosswalk-project/blink-crosswalk
16d1b69626699e9ca703e0c24c829e96d07fcd3e
[ "BSD-3-Clause" ]
58
2015-01-02T14:37:31.000Z
2015-11-30T04:58:51.000Z
Source/modules/webcl/WebCLEvent.cpp
crosswalk-project/blink-crosswalk
16d1b69626699e9ca703e0c24c829e96d07fcd3e
[ "BSD-3-Clause" ]
35
2015-01-14T00:10:29.000Z
2022-01-20T10:28:15.000Z
// Copyright (C) 2011 Samsung Electronics Corporation. All rights reserved. // Copyright (C) 2015 Intel Corporation All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "config.h" #if ENABLE(WEBCL) #include "bindings/modules/v8/V8WebCLCommandQueue.h" #include "bindings/modules/v8/V8WebCLContext.h" #include "core/webcl/WebCLException.h" #include "modules/webcl/WebCL.h" #include "modules/webcl/WebCLEvent.h" #include "modules/webcl/WebCLOpenCL.h" #include "platform/ThreadSafeFunctional.h" #include "public/platform/Platform.h" #include "public/platform/WebTraceLocation.h" namespace blink { // The holder of WebCLEvent. class WebCLEventHolder { public: WeakPtr<WebCLObject> event; cl_int type; cl_event event2; cl_int type2; }; WebCLEvent::~WebCLEvent() { release(); ASSERT(!m_clEvent); } PassRefPtr<WebCLEvent> WebCLEvent::create() { return adoptRef(new WebCLEvent(0)); } ScriptValue WebCLEvent::getInfo(ScriptState* scriptState, unsigned paramName, ExceptionState& es) { v8::Handle<v8::Object> creationContext = scriptState->context()->Global(); v8::Isolate* isolate = scriptState->isolate(); if (isReleased()) { es.throwWebCLException(WebCLException::INVALID_EVENT, WebCLException::invalidEventMessage); return ScriptValue(scriptState, v8::Null(isolate)); } cl_int err = CL_SUCCESS; cl_int intUnits = 0; cl_command_type commandType = 0; switch(paramName) { case CL_EVENT_COMMAND_EXECUTION_STATUS: err = clGetEventInfo(m_clEvent, CL_EVENT_COMMAND_EXECUTION_STATUS, sizeof(cl_int), &intUnits, nullptr); if (err == CL_SUCCESS) return ScriptValue(scriptState, v8::Integer::New(isolate, static_cast<int>(intUnits))); break; case CL_EVENT_COMMAND_TYPE: err = clGetEventInfo(m_clEvent, CL_EVENT_COMMAND_TYPE, sizeof(cl_command_type), &commandType, nullptr); if (err == CL_SUCCESS) return ScriptValue(scriptState, v8::Integer::NewFromUnsigned(isolate, static_cast<unsigned>(commandType))); break; case CL_EVENT_CONTEXT: ASSERT(!isUserEvent()); return ScriptValue(scriptState, toV8(context(), creationContext, isolate)); case CL_EVENT_COMMAND_QUEUE: ASSERT(m_commandQueue); ASSERT(!isUserEvent()); return ScriptValue(scriptState, toV8(m_commandQueue, creationContext, isolate)); default: es.throwWebCLException(WebCLException::INVALID_VALUE, WebCLException::invalidValueMessage); return ScriptValue(scriptState, v8::Null(isolate)); } WebCLException::throwException(err, es); return ScriptValue(scriptState, v8::Null(isolate)); } int WebCLEvent::getStatus() { cl_int intUnits = 0; cl_int err = clGetEventInfo(m_clEvent, CL_EVENT_COMMAND_EXECUTION_STATUS, sizeof(cl_int), &intUnits, nullptr); if (err == CL_SUCCESS) return static_cast<int>(intUnits); return CL_INVALID_VALUE; } unsigned WebCLEvent::getProfilingInfo(int paramName, ExceptionState& es) { if (isReleased()) { es.throwWebCLException(WebCLException::INVALID_EVENT, WebCLException::invalidEventMessage); return 0; } int status = getStatus(); unsigned properties = m_commandQueue ? m_commandQueue->getProperties() : 0; if (isUserEvent() || status != CL_COMPLETE || !(properties & CL_QUEUE_PROFILING_ENABLE)) { es.throwWebCLException(WebCLException::PROFILING_INFO_NOT_AVAILABLE, WebCLException::profilingInfoNotAvailableMessage); return 0; } cl_int err = CL_SUCCESS; cl_ulong ulongUnits = 0; switch(paramName) { case CL_PROFILING_COMMAND_QUEUED: err = clGetEventProfilingInfo(m_clEvent, CL_PROFILING_COMMAND_QUEUED, sizeof(cl_ulong), &ulongUnits, nullptr); if (err == CL_SUCCESS) return static_cast<unsigned long long>(ulongUnits); break; case CL_PROFILING_COMMAND_SUBMIT: err = clGetEventProfilingInfo(m_clEvent, CL_PROFILING_COMMAND_SUBMIT, sizeof(cl_ulong), &ulongUnits, nullptr); if (err == CL_SUCCESS) return static_cast<unsigned long long>(ulongUnits); break; case CL_PROFILING_COMMAND_START: err = clGetEventProfilingInfo(m_clEvent, CL_PROFILING_COMMAND_START, sizeof(cl_ulong), &ulongUnits, nullptr); if (err == CL_SUCCESS) return static_cast<unsigned long long>(ulongUnits); break; case CL_PROFILING_COMMAND_END: err = clGetEventProfilingInfo(m_clEvent, CL_PROFILING_COMMAND_END, sizeof(cl_ulong), &ulongUnits, nullptr); if (err == CL_SUCCESS) return static_cast<unsigned long long>(ulongUnits); break; default: es.throwWebCLException(WebCLException::INVALID_VALUE, WebCLException::invalidValueMessage); return 0; } WebCLException::throwException(err, es); return 0; } void WebCLEvent::setCallback(unsigned commandExecCallbackType, WebCLCallback* callback, ExceptionState& es) { if (isReleased()) { es.throwWebCLException(WebCLException::INVALID_EVENT, WebCLException::invalidEventMessage); return; } if (commandExecCallbackType != CL_COMPLETE) { es.throwWebCLException(WebCLException::INVALID_VALUE, WebCLException::invalidValueMessage); return; } ASSERT(callback); if (m_callbacks.size()) { m_callbacks.append(adoptRef(callback)); return; } m_callbacks.clear(); m_callbacks.append(adoptRef(callback)); WebCLEventHolder* holder = new WebCLEventHolder; holder->event = createWeakPtr(); holder->type = commandExecCallbackType; cl_int err = clSetEventCallback(m_clEvent, commandExecCallbackType, &callbackProxy, holder); if (err != CL_SUCCESS) WebCLException::throwException(err, es); } void WebCLEvent::release() { if (isReleased()) return; cl_int err = clReleaseEvent(m_clEvent); if (err != CL_SUCCESS) ASSERT_NOT_REACHED(); m_clEvent = 0; // Release un-triggered callbacks. m_callbacks.clear(); } bool WebCLEvent::setAssociatedCommandQueue(WebCLCommandQueue* commandQueue) { if (m_commandQueue) return false; m_commandQueue = commandQueue; setContext(m_commandQueue->context()); return true; } WebCLEvent::WebCLEvent(cl_event clEvent) : WebCLObject() , m_commandQueue(nullptr) , m_clEvent(clEvent) { } void WebCLEvent::callbackProxy(cl_event event, cl_int type, void* userData) { OwnPtr<WebCLEventHolder> holder = adoptPtr(static_cast<WebCLEventHolder*>(userData)); holder->event2 = event; holder->type2 = type; if (!isMainThread()) { Platform::current()->mainThread()->postTask(FROM_HERE, threadSafeBind(&WebCLEvent::callbackProxyOnMainThread, holder.release())); return; } callbackProxyOnMainThread(holder.release()); } void WebCLEvent::callbackProxyOnMainThread(PassOwnPtr<WebCLEventHolder> holder) { ASSERT(isMainThread()); RefPtr<WebCLEvent> webEvent(static_cast<WebCLEvent*>(holder->event.get())); #ifndef NDEBUG cl_event event = holder->event2; #endif cl_int type = holder->type2; if (!webEvent) return; // Ignore the callback if the WebCLEvent is released or OpenCL event is abnormally terminated. if (webEvent->isReleased() || type != holder->type) { webEvent->m_callbacks.clear(); return; } ASSERT(event == webEvent->getEvent()); Vector<RefPtr<WebCLCallback>> callbacks = webEvent->m_callbacks; ASSERT(callbacks.size()); for (auto callback : callbacks) callback->handleEvent(); webEvent->m_callbacks.clear(); } } // namespace blink #endif // ENABLE(WEBCL)
32.4125
137
0.704589
[ "object", "vector" ]
4c6b4b734469d2902d5ae896b1be507829e94728
1,256
cpp
C++
testing/interpolation/DummyTransformation.cpp
MIC-DKFZ/RTTB
8b772501fd3fffcb67233a9307661b03dff72785
[ "BSD-3-Clause" ]
18
2018-04-19T12:57:32.000Z
2022-03-12T17:43:02.000Z
testing/interpolation/DummyTransformation.cpp
MIC-DKFZ/RTTB
8b772501fd3fffcb67233a9307661b03dff72785
[ "BSD-3-Clause" ]
null
null
null
testing/interpolation/DummyTransformation.cpp
MIC-DKFZ/RTTB
8b772501fd3fffcb67233a9307661b03dff72785
[ "BSD-3-Clause" ]
7
2018-06-24T21:09:56.000Z
2021-09-09T09:30:49.000Z
// ----------------------------------------------------------------------- // RTToolbox - DKFZ radiotherapy quantitative evaluation library // // Copyright (c) German Cancer Research Center (DKFZ), // Software development for Integrated Diagnostics and Therapy (SIDT). // ALL RIGHTS RESERVED. // See rttbCopyright.txt or // http://www.dkfz.de/en/sidt/projects/rttb/copyright.html [^] // // This software is distributed WITHOUT ANY WARRANTY; without even // the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the above copyright notices for more information. // //------------------------------------------------------------------------ #include "DummyTransformation.h" namespace rttb { namespace testing { bool DummyTransformation::transformInverse(const WorldCoordinate3D& worldCoordinateTarget, WorldCoordinate3D& worldCoordinateMoving) const { worldCoordinateMoving = worldCoordinateTarget; return true; } bool DummyTransformation::transform(const WorldCoordinate3D& worldCoordinateMoving, WorldCoordinate3D& worldCoordinateTarget) const { worldCoordinateTarget = worldCoordinateMoving; return true; } } }
33.945946
93
0.636943
[ "transform" ]
4c725ad09bc110666ee2577d8514e1547d2903dd
2,181
cpp
C++
common/src/fonts.cpp
jasbok/libshimmer
794b0e27ee8492f46202efebd24dab32a7c5c1da
[ "MIT" ]
null
null
null
common/src/fonts.cpp
jasbok/libshimmer
794b0e27ee8492f46202efebd24dab32a7c5c1da
[ "MIT" ]
null
null
null
common/src/fonts.cpp
jasbok/libshimmer
794b0e27ee8492f46202efebd24dab32a7c5c1da
[ "MIT" ]
null
null
null
#include "fonts.h" #include "freetype.h" namespace common::fonts { spec::spec( const std::string& id, const std::string& path, unsigned int size, std::vector<range_uint> unicodes ) : _id ( id ), _path ( path ), _size ( size ), _unicodes ( unicodes ) {} spec& spec::path ( const std::string& path ) { _path = path; return *this; } std::string spec::path() const { return _path; } spec& spec::id ( const std::string& id ) { _id = id; return *this; } std::string spec::id() const { return _id; } spec& spec::size ( unsigned int size ) { _size = size; return *this; } unsigned int spec::size() const { return _size; } spec& spec::unicodes ( const unicode_ranges& unicodes ) { _unicodes = unicodes; return *this; } spec::unicode_ranges spec::unicodes() const { return _unicodes; } glyph_pack _convert_to_glyphs ( const freetype& ft, const spec::unicode_ranges& unicodes ) { glyph_pack pack; for ( auto range : unicodes ) { for ( unsigned int c = range.start; c < range.end; c++ ) { try { auto glyph = ft.unicode ( static_cast<wchar_t>( c ) ); auto dims = glyph.meta.dims; if ( glyph.meta.dims.area() > 0 ) { pack.metas.push_back ( std::move ( glyph.meta ) ); pack.bitmaps.push_back ( std::move ( glyph.bitmap ) ); } } catch ( const std::exception& ) {} } } return pack; } glyph_pack load ( const std::vector<spec>& fonts, unsigned int dpi ) { freetype ft; glyph_pack pack; for ( const auto& font : fonts ) { ft.load ( font.path(), font.size(), dpi ); auto data = _convert_to_glyphs ( ft, font.unicodes() ); std::move ( data.bitmaps.begin(), data.bitmaps.end(), back_inserter ( pack.bitmaps ) ); std::move ( data.metas.begin(), data.metas.end(), back_inserter ( pack.metas ) ); } return pack; } }
20.383178
74
0.523155
[ "vector" ]
dbd04008f68fbf0c2899814d933d3518816095d0
5,285
cc
C++
patchpanel/datapath_fuzzer.cc
ascii33/platform2
b78891020724e9ff26b11ca89c2a53f949e99748
[ "BSD-3-Clause" ]
null
null
null
patchpanel/datapath_fuzzer.cc
ascii33/platform2
b78891020724e9ff26b11ca89c2a53f949e99748
[ "BSD-3-Clause" ]
null
null
null
patchpanel/datapath_fuzzer.cc
ascii33/platform2
b78891020724e9ff26b11ca89c2a53f949e99748
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2019 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <net/if.h> #include <string.h> #include <sys/ioctl.h> #include <memory> #include <string> #include <vector> #include <base/at_exit.h> #include <base/bind.h> #include <base/callback_helpers.h> #include <base/logging.h> #include <fuzzer/FuzzedDataProvider.h> #include "patchpanel/datapath.h" #include "patchpanel/firewall.h" #include "patchpanel/minijailed_process_runner.h" #include "patchpanel/multicast_forwarder.h" #include "patchpanel/net_util.h" #include "patchpanel/subnet.h" #include "patchpanel/system.h" namespace patchpanel { namespace { // Always succeeds class FakeProcessRunner : public MinijailedProcessRunner { public: FakeProcessRunner() = default; FakeProcessRunner(const FakeProcessRunner&) = delete; FakeProcessRunner& operator=(const FakeProcessRunner&) = delete; ~FakeProcessRunner() = default; int Run(const std::vector<std::string>& argv, bool log_failures) override { return 0; } int RunSync(const std::vector<std::string>& argv, bool log_failures, std::string* output) override { return 0; } }; // Always succeeds class NoopSystem : public System { public: NoopSystem() = default; NoopSystem(const NoopSystem&) = delete; NoopSystem& operator=(const NoopSystem&) = delete; virtual ~NoopSystem() = default; int Ioctl(int fd, ioctl_req_t request, const char* argp) override { return 0; } }; class Environment { public: Environment() { logging::SetMinLogLevel(logging::LOGGING_FATAL); // <- DISABLE LOGGING. } base::AtExitManager at_exit; }; extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { static Environment env; FuzzedDataProvider provider(data, size); uint32_t pid = provider.ConsumeIntegral<uint32_t>(); std::string netns_name = provider.ConsumeRandomLengthString(10); std::string ifname = provider.ConsumeRandomLengthString(IFNAMSIZ - 1); std::string ifname2 = provider.ConsumeRandomLengthString(IFNAMSIZ - 1); std::string ifname3 = provider.ConsumeRandomLengthString(IFNAMSIZ - 1); std::string bridge = provider.ConsumeRandomLengthString(IFNAMSIZ - 1); uint32_t addr = provider.ConsumeIntegral<uint32_t>(); std::string addr_str = IPv4AddressToString(addr); uint32_t prefix_len = provider.ConsumeIntegralInRange<uint32_t>(0, 31); SubnetAddress subnet_addr(provider.ConsumeIntegral<int32_t>(), prefix_len, base::DoNothing()); MacAddress mac; std::vector<uint8_t> mac_addr_bytes = provider.ConsumeBytes<uint8_t>(mac.size()); std::copy(mac_addr_bytes.begin(), mac_addr_bytes.end(), mac.begin()); struct in6_addr ipv6_addr; memset(&ipv6_addr, 0, sizeof(ipv6_addr)); std::vector<uint8_t> ipv6_addr_bytes = provider.ConsumeBytes<uint8_t>(sizeof(ipv6_addr.s6_addr)); std::copy(ipv6_addr_bytes.begin(), ipv6_addr_bytes.end(), ipv6_addr.s6_addr); std::string ipv6_addr_str = IPv6AddressToString(ipv6_addr); bool route_on_vpn = provider.ConsumeBool(); ConnectedNamespace nsinfo = {}; nsinfo.pid = pid; nsinfo.netns_name = netns_name; nsinfo.source = TrafficSource::USER; nsinfo.outbound_ifname = ifname; nsinfo.route_on_vpn = route_on_vpn; nsinfo.host_ifname = ifname2; nsinfo.peer_ifname = ifname3; nsinfo.peer_subnet = std::make_unique<Subnet>(addr, prefix_len, base::DoNothing()); nsinfo.peer_mac_addr = mac; auto runner = new FakeProcessRunner(); auto firewall = new Firewall(); NoopSystem system; Datapath datapath(runner, firewall, &system); datapath.Start(); datapath.Stop(); datapath.NetnsAttachName(netns_name, pid); datapath.NetnsDeleteName(netns_name); datapath.AddBridge(ifname, addr, prefix_len); datapath.RemoveBridge(ifname); datapath.AddToBridge(ifname, ifname2); datapath.StartRoutingDevice(ifname, ifname2, addr, TrafficSource::UNKNOWN, route_on_vpn); datapath.StopRoutingDevice(ifname, ifname2, addr, TrafficSource::UNKNOWN, route_on_vpn); datapath.StartRoutingNamespace(nsinfo); datapath.StopRoutingNamespace(nsinfo); datapath.ConnectVethPair(pid, netns_name, ifname, ifname2, mac, addr, prefix_len, provider.ConsumeBool()); datapath.RemoveInterface(ifname); datapath.AddTAP(ifname, &mac, &subnet_addr, ""); datapath.RemoveTAP(ifname); datapath.AddIPv4Route(provider.ConsumeIntegral<uint32_t>(), provider.ConsumeIntegral<uint32_t>(), provider.ConsumeIntegral<uint32_t>()); datapath.StartConnectionPinning(ifname); datapath.StopConnectionPinning(ifname); datapath.StartVpnRouting(ifname); datapath.StopVpnRouting(ifname); datapath.MaskInterfaceFlags(ifname, provider.ConsumeIntegral<uint16_t>(), provider.ConsumeIntegral<uint16_t>()); datapath.AddIPv6HostRoute(ifname, ipv6_addr_str, prefix_len); datapath.RemoveIPv6HostRoute(ifname, ipv6_addr_str, prefix_len); datapath.AddIPv6Address(ifname, ipv6_addr_str); datapath.RemoveIPv6Address(ifname, ipv6_addr_str); return 0; } } // namespace } // namespace patchpanel
35
79
0.727342
[ "vector" ]
dbd94f94053b0326ff52ec8684a5363c147fad17
3,681
cpp
C++
engine/src/core/blshaderprogram.cpp
comaralex/Chess2k17
0c90ad1ec6416d4881932ca6588551d76ae3b8ac
[ "BSD-2-Clause" ]
1
2020-07-23T11:58:12.000Z
2020-07-23T11:58:12.000Z
engine/src/core/blshaderprogram.cpp
comaralex/Chess2k17
0c90ad1ec6416d4881932ca6588551d76ae3b8ac
[ "BSD-2-Clause" ]
null
null
null
engine/src/core/blshaderprogram.cpp
comaralex/Chess2k17
0c90ad1ec6416d4881932ca6588551d76ae3b8ac
[ "BSD-2-Clause" ]
1
2020-07-24T14:39:47.000Z
2020-07-24T14:39:47.000Z
#include "blshaderprogram.h" #include <bllogger.h> #include <blconstants.h> namespace black { ShaderProgram::ShaderProgram() : QOpenGLShaderProgram(), m_vertex(), m_fragment() { } ShaderProgram::ShaderProgram(std::shared_ptr<Shader> vertex, std::shared_ptr<Shader> fragment) : ShaderProgram() { create(vertex, fragment); } ShaderProgram::~ShaderProgram() { m_fragment.reset(); m_vertex.reset(); } void ShaderProgram::create(std::shared_ptr<Shader> vertex, std::shared_ptr<Shader> fragment) { m_vertex.reset(); m_vertex = vertex; m_fragment.reset(); m_fragment = fragment; this->addShader(vertex->shader()); this->addShader(fragment->shader()); if ( !this->link() ) { Logger::getInstance() << this->log() << std::endl; // TODO: exceptions! throw "Failed to link shaders"; } } bool ShaderProgram::link() { this->bindLocations(); return QOpenGLShaderProgram::link(); } void ShaderProgram::setModelMatrix(const QMatrix4x4 &model) { if ( !supportModelMatrix() ) { return; } this->setUniformValue("mModel", model); } void ShaderProgram::setCamera(const std::shared_ptr<Camera> camera) { if ( !supportCamera() ) { return; } setUniformValue("mView", camera->view()); setUniformValue("mPerspective", camera->perspective()); if ( !supportCameraPosition() ) { return; } this->setUniformValue("cameraPos", camera->position()); } void ShaderProgram::setLight(const std::shared_ptr<Light> light) { if ( !supportLight() ) { return; } this->setUniformValue("lightPosition", light->position()); this->setUniformValue("light.ambient", light->ambient()); this->setUniformValue("light.diffuse", light->diffuse()); this->setUniformValue("light.spectacular", light->spectacular()); } //void ShaderProgram::setTerrain(const std::shared_ptr<Terrain> &terrain) //{ // if ( !supportTerrain() ) { // return; // } // // Terrain textures setted here // // And height mapp and so on //} void ShaderProgram::setMaterial(const std::shared_ptr<Material> material) { if ( !supportMaterials() ) { return; } this->setUniformValue("material.ambient", material->ambient()); this->setUniformValue("material.diffuse", material->diffuse()); this->setUniformValue("material.spectacular", material->spectacular()); this->setUniformValue("material.shineFactor", material->shineFactor()); } void ShaderProgram::enableTextures() { if ( !this->supportTextures() ) { return; } this->setUniformValue("enableTextures", true); } void ShaderProgram::disableTextures() { if ( !this->supportTextures() ) { return; } this->setUniformValue("enableTextures", false); } bool ShaderProgram::bind() { bool res = QOpenGLShaderProgram::bind(); defaultUniforms(); return res; } std::string ShaderProgram::log() const { return QOpenGLShaderProgram::log().toStdString(); } /* * Strictly coded attribute locations. Why not? */ void ShaderProgram::bindLocations() { this->bindAttributeLocation("vPosition", Constants::VERTEX_ATTR_POSITION); this->bindAttributeLocation("vNormal", Constants::VERTEX_ATTR_NORMAL); this->bindAttributeLocation("vTexCoords", Constants::VERTEX_ATTR_TEXCOORDS); } void ShaderProgram::defaultUniforms() { this->enableTextures(); } std::shared_ptr<Shader> ShaderProgram::fragment() const { return m_fragment; } std::shared_ptr<Shader> ShaderProgram::vertex() const { return m_vertex; } } // end of black namespace
21.781065
80
0.657973
[ "model" ]
dbdbaab91149c7feeaa7c2ab6e161b35529edab4
4,955
hpp
C++
catkin_ws/src/srrg2_slam_interfaces/srrg2_slam_interfaces/src/srrg2_slam_interfaces/trackers/tracker_slice_processor_estimation_buffer.hpp
laaners/progetto-labiagi_pick_e_delivery
3453bfbc1dd7562c78ba06c0f79b069b0a952c0e
[ "MIT" ]
null
null
null
catkin_ws/src/srrg2_slam_interfaces/srrg2_slam_interfaces/src/srrg2_slam_interfaces/trackers/tracker_slice_processor_estimation_buffer.hpp
laaners/progetto-labiagi_pick_e_delivery
3453bfbc1dd7562c78ba06c0f79b069b0a952c0e
[ "MIT" ]
null
null
null
catkin_ws/src/srrg2_slam_interfaces/srrg2_slam_interfaces/src/srrg2_slam_interfaces/trackers/tracker_slice_processor_estimation_buffer.hpp
laaners/progetto-labiagi_pick_e_delivery
3453bfbc1dd7562c78ba06c0f79b069b0a952c0e
[ "MIT" ]
null
null
null
#pragma once #include "tracker_slice_processor_prior.h" namespace srrg2_slam_interfaces { //! buffered tracker pose estimation as prior slice for e.g. fancy motion modelling template <typename EstimateType_, typename FixedMeasurementType_> class TrackerSliceProcessorEstimationBuffer_ : public TrackerSliceProcessorPrior_<EstimateType_, FixedMeasurementType_> { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW using EstimateType = EstimateType_; using FixedMeasurementType = FixedMeasurementType_; using MovingType = FixedMeasurementType; using ThisType = TrackerSliceProcessorEstimationBuffer_<EstimateType, FixedMeasurementType>; using BaseType = TrackerSliceProcessorPrior_<EstimateType, FixedMeasurementType>; template <typename T> friend class MultiTrackerBase_; protected: // void setRobotInLocalMap(const EstimateType& estimate_) override { // BaseType::setRobotInLocalMap(estimate_); // } void setScene(srrg2_core::PropertyContainerBase* scene_) override { BaseType::addSceneProperty(scene_); // ds if not relocalized (otherwise the new coordinate frame origin will be already set) if (!_relocalized) { // ds the tracker moved into a new local map (i.e. in which it's pose == identity) // ds to keep the motion model sane we have to shift it into the new local map _robot_in_local_map_updated = ThisType::_robot_in_local_map; _scene_changed = true; } } void setClosure(const srrg2_core::CorrespondenceVector& correspondences_, const EstimateType& fixed_in_moving_, const EstimateType& robot_in_moving_local_map_) override { // ds the tracker moved into an older local map with a shifted pose (loop closure offset) // ds to keep the motion model sane we have to shift it into the local map + relocalization _robot_in_local_map_updated = ThisType::_robot_in_local_map * robot_in_moving_local_map_.inverse(); // std::cerr << "_robot_in_local_map: \n" << ThisType::_robot_in_local_map.matrix() << // std::endl; std::cerr << "robot_in_moving_local_map_: \n" // << robot_in_moving_local_map_.matrix() << std::endl; // std::cerr << "_robot_in_local_map_updated: \n" // << _robot_in_local_map_updated.matrix() << std::endl; _relocalized = true; } void setRawData(srrg2_core::BaseSensorMessagePtr measurement_, TrackerReportRecord& report_record_) override { // ds no actual measurement to process - just configure the adaptor assert(ThisType::param_adaptor.value()); ThisType::addMeasurementProperty(); ThisType::param_adaptor->setMeas(&(ThisType::_measurement_slice)); } void merge() override { BaseType::merge(); // ds if we have a tracker estimate adaptor std::shared_ptr<RawDataPreprocessorTrackerEstimate_<FixedMeasurementType>> tracker_estimate_adaptor = std::dynamic_pointer_cast<RawDataPreprocessorTrackerEstimate_<FixedMeasurementType>>( ThisType::param_adaptor.value()); if (tracker_estimate_adaptor) { if (_scene_changed || _relocalized) { // ds provide adaptor with tracker pose instead of a measurement // ds with re-centering after re-population (estimate reset) tracker_estimate_adaptor->setCoordinateFrameOrigin(_robot_in_local_map_updated); _scene_changed = false; _relocalized = false; } // ds set refined pose estimate that can be used in the next compute tracker_estimate_adaptor->setRobotInLocalMap(ThisType::_robot_in_local_map); } } bool isSceneSliceEmpty() const override { // ds this slice does not have an actual scene, but a transform instead // ds it is assumed to be not "empty" if the scene is set return (ThisType::_scene_slice != nullptr); } // ds scene change (into another/new local map) bool _scene_changed = false; EstimateType _robot_in_local_map_updated; // ds relocalization event, we keep the latest estimate to compute the local map transform bool _relocalized = false; }; using TrackerSliceProcessorEstimationBuffer2D = TrackerSliceProcessorEstimationBuffer_<srrg2_core::Isometry2f, srrg2_core::StdDequeEigenIsometry2f>; using TrackerSliceProcessorEstimationBuffer3D = TrackerSliceProcessorEstimationBuffer_<srrg2_core::Isometry3f, srrg2_core::StdDequeEigenIsometry3f>; using TrackerSliceProcessorEstimationBuffer2DPtr = std::shared_ptr<TrackerSliceProcessorEstimationBuffer2D>; using TrackerSliceProcessorEstimationBuffer3DPtr = std::shared_ptr<TrackerSliceProcessorEstimationBuffer3D>; } // namespace srrg2_slam_interfaces
45.87963
97
0.703532
[ "model", "transform" ]
dbe135fe7fa1637d4c17fc39dceb90857c10dc84
6,913
cpp
C++
wallet/api/v6_3/v6_3_api_handle.cpp
arjundashrath/beam
93957ce8d0a58edcb112653a732083caeb9b3971
[ "Apache-2.0" ]
null
null
null
wallet/api/v6_3/v6_3_api_handle.cpp
arjundashrath/beam
93957ce8d0a58edcb112653a732083caeb9b3971
[ "Apache-2.0" ]
null
null
null
wallet/api/v6_3/v6_3_api_handle.cpp
arjundashrath/beam
93957ce8d0a58edcb112653a732083caeb9b3971
[ "Apache-2.0" ]
null
null
null
// Copyright 2018 The Beam Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "v6_3_api.h" #include "version.h" namespace beam::wallet { void V63Api::onHandleIPFSAdd(const JsonRpcId &id, IPFSAdd&& req) { #ifdef BEAM_IPFS_SUPPORT auto ipfs = getIPFS(); ipfs->AnyThread_add(std::move(req.data), req.pin, req.timeout, [this, id, pin = req.pin, wguard = _weakSelf](std::string&& hash) { auto guard = wguard.lock(); if (!guard) { LOG_WARNING() << "API destroyed before IPFS response received."; return; } IPFSAdd::Response response = {hash, pin}; doResponse(id, response); }, [this, id, wguard = _weakSelf] (std::string&& err) { auto guard = wguard.lock(); if (!guard) { LOG_WARNING() << "API destroyed before IPFS response received."; return; } sendError(id, ApiError::IPFSError, err); } ); #else sendError(id, ApiError::NotSupported); #endif } void V63Api::onHandleIPFSHash(const JsonRpcId &id, IPFSHash&& req) { #ifdef BEAM_IPFS_SUPPORT auto ipfs = getIPFS(); ipfs->AnyThread_hash(std::move(req.data), req.timeout, [this, id, wguard = _weakSelf](std::string&& hash) { auto guard = wguard.lock(); if (!guard) { LOG_WARNING() << "API destroyed before IPFS response received."; return; } IPFSHash::Response response = {hash}; doResponse(id, response); }, [this, id, wguard = _weakSelf] (std::string&& err) { auto guard = wguard.lock(); if (!guard) { LOG_WARNING() << "API destroyed before IPFS response received."; return; } sendError(id, ApiError::IPFSError, err); } ); #else sendError(id, ApiError::NotSupported); #endif } void V63Api::onHandleIPFSGet(const JsonRpcId &id, IPFSGet&& req) { #ifdef BEAM_IPFS_SUPPORT auto ipfs = getIPFS(); ipfs->AnyThread_get(req.hash, req.timeout, [this, id, hash = req.hash, wguard = _weakSelf](std::vector<uint8_t>&& data) { auto guard = wguard.lock(); if (!guard) { LOG_WARNING() << "API destroyed before IPFS response received."; return; } IPFSGet::Response response = {hash, std::move(data)}; doResponse(id, response); }, [this, id, wguard = _weakSelf] (std::string&& err) { auto guard = wguard.lock(); if (!guard) { LOG_WARNING() << "API destroyed before IPFS response received."; return; } sendError(id, ApiError::IPFSError, err); } ); #else sendError(id, ApiError::NotSupported); #endif } void V63Api::onHandleIPFSPin(const JsonRpcId &id, IPFSPin&& req) { #ifdef BEAM_IPFS_SUPPORT auto ipfs = getIPFS(); ipfs->AnyThread_pin(req.hash, req.timeout, [this, id, hash = req.hash, wguard = _weakSelf]() { auto guard = wguard.lock(); if (!guard) { LOG_WARNING() << "API destroyed before IPFS response received."; return; } IPFSPin::Response response = {hash}; doResponse(id, response); }, [this, id, wguard = _weakSelf] (std::string&& err) { auto guard = wguard.lock(); if (!guard) { LOG_WARNING() << "API destroyed before IPFS response received."; return; } sendError(id, ApiError::IPFSError, err); } ); #else sendError(id, ApiError::NotSupported); #endif } void V63Api::onHandleIPFSUnpin(const JsonRpcId &id, IPFSUnpin&& req) { #ifdef BEAM_IPFS_SUPPORT auto ipfs = getIPFS(); ipfs->AnyThread_unpin(req.hash, [this, id, hash = req.hash, wguard = _weakSelf]() { auto guard = wguard.lock(); if (!guard) { LOG_WARNING() << "API destroyed before IPFS response received."; return; } IPFSUnpin::Response response = {hash}; doResponse(id, response); }, [this, id, wguard = _weakSelf] (std::string&& err) { auto guard = wguard.lock(); if (!guard) { LOG_WARNING() << "API destroyed before IPFS response received."; return; } sendError(id, ApiError::IPFSError, err); } ); #else sendError(id, ApiError::NotSupported); #endif } void V63Api::onHandleIPFSGc(const JsonRpcId &id, IPFSGc&& req) { #ifdef BEAM_IPFS_SUPPORT auto ipfs = getIPFS(); ipfs->AnyThread_gc(req.timeout, [this, id, wguard = _weakSelf]() { auto guard = wguard.lock(); if (!guard) { LOG_WARNING() << "API destroyed before IPFS response received."; return; } IPFSGc::Response response; doResponse(id, response); }, [this, id, wguard = _weakSelf] (std::string&& err) { auto guard = wguard.lock(); if (!guard) { LOG_WARNING() << "API destroyed before IPFS response received."; return; } sendError(id, ApiError::IPFSError, err); } ); #else sendError(id, ApiError::NotSupported); #endif } }
33.235577
86
0.482424
[ "vector" ]
dbef5c463925972ac3045b378e73500aa301fbc0
18,478
cpp
C++
src/demo/vxm_timing_demo.cpp
KIwabuchi/gbtl
62c6b1e3262f3623359e793edb5ec4fa7bb471f0
[ "Unlicense" ]
112
2016-04-26T05:54:30.000Z
2022-03-27T05:56:16.000Z
src/demo/vxm_timing_demo.cpp
KIwabuchi/gbtl
62c6b1e3262f3623359e793edb5ec4fa7bb471f0
[ "Unlicense" ]
21
2016-03-22T19:06:46.000Z
2021-10-07T15:40:18.000Z
src/demo/vxm_timing_demo.cpp
KIwabuchi/gbtl
62c6b1e3262f3623359e793edb5ec4fa7bb471f0
[ "Unlicense" ]
22
2016-04-26T05:54:35.000Z
2021-12-21T03:33:20.000Z
/* * GraphBLAS Template Library (GBTL), Version 3.0 * * Copyright 2020 Carnegie Mellon University, Battelle Memorial Institute, and * Authors. * * THIS MATERIAL WAS PREPARED AS AN ACCOUNT OF WORK SPONSORED BY AN AGENCY OF * THE UNITED STATES GOVERNMENT. NEITHER THE UNITED STATES GOVERNMENT NOR THE * UNITED STATES DEPARTMENT OF ENERGY, NOR THE UNITED STATES DEPARTMENT OF * DEFENSE, NOR CARNEGIE MELLON UNIVERSITY, NOR BATTELLE, NOR ANY OF THEIR * EMPLOYEES, NOR ANY JURISDICTION OR ORGANIZATION THAT HAS COOPERATED IN THE * DEVELOPMENT OF THESE MATERIALS, MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR * ASSUMES ANY LEGAL LIABILITY OR RESPONSIBILITY FOR THE ACCURACY, COMPLETENESS, * OR USEFULNESS OR ANY INFORMATION, APPARATUS, PRODUCT, SOFTWARE, OR PROCESS * DISCLOSED, OR REPRESENTS THAT ITS USE WOULD NOT INFRINGE PRIVATELY OWNED * RIGHTS. * * Released under a BSD-style license, please see LICENSE file or contact * permission@sei.cmu.edu for full terms. * * [DISTRIBUTION STATEMENT A] This material has been approved for public release * and unlimited distribution. Please see Copyright notice for non-US * Government use and distribution. * * DM20-0442 */ #include <iostream> #include <fstream> #include <chrono> #include <random> #define GRAPHBLAS_DEBUG 1 #include <graphblas/graphblas.hpp> #include "Timer.hpp" using namespace grb; //**************************************************************************** IndexType read_edge_list(std::string const &pathname, IndexArrayType &row_indices, IndexArrayType &col_indices) { std::ifstream infile(pathname); IndexType max_id = 0; uint64_t num_rows = 0; uint64_t src, dst; while (infile) { infile >> src >> dst; //std::cout << "Read: " << src << ", " << dst << std::endl; max_id = std::max(max_id, src); max_id = std::max(max_id, dst); //if (src > max_id) max_id = src; //if (dst > max_id) max_id = dst; row_indices.push_back(src); col_indices.push_back(dst); ++num_rows; } std::cout << "Read " << num_rows << " rows." << std::endl; std::cout << "#Nodes = " << (max_id + 1) << std::endl; return (max_id + 1); } //**************************************************************************** int main(int argc, char **argv) { if (argc < 2) { std::cerr << "ERROR: too few arguments." << std::endl; std::cerr << "Usage: " << argv[0] << " <edge list file>" << std::endl; exit(1); } // Read the edgelist and create the tuple arrays std::string pathname(argv[1]); IndexArrayType iA, jA, iu; IndexType const NUM_NODES(read_edge_list(pathname, iA, jA)); using T = int32_t; using MatType = Matrix<T>; using VecType = Vector<T>; using BoolVecType = Vector<bool>; std::vector<T> v(iA.size(), 1); std::vector<bool> bv(iA.size(), true); MatType A(NUM_NODES, NUM_NODES); MatType AT(NUM_NODES, NUM_NODES); VecType u(NUM_NODES); VecType w(NUM_NODES); VecType w1(NUM_NODES); BoolVecType M(NUM_NODES); A.build(iA.begin(), jA.begin(), v.begin(), iA.size()); transpose(AT, NoMask(), NoAccumulate(), A); std::default_random_engine generator; std::uniform_real_distribution<double> distribution; for (IndexType iu = 0; iu < NUM_NODES; ++iu) { if (distribution(generator) < 0.15) M.setElement(iu, true); if (distribution(generator) < 0.1) u.setElement(iu, 1); } std::cout << "Running algorithm(s)... M.nvals = " << M.nvals() << std::endl; std::cout << "u.nvals = " << u.nvals() << std::endl; T count(0); Timer<std::chrono::steady_clock, std::chrono::microseconds> my_timer; // warm up vxm(w, NoMask(), NoAccumulate(), ArithmeticSemiring<double>(), u, A); //===================================================== // Perform matrix vector multiplies //===================================================== //=================== // u'*A //=================== std::cout << "IMPLEMENTATION: u'*A" << std::endl; w.clear(); my_timer.start(); vxm(w, NoMask(), NoAccumulate(), ArithmeticSemiring<double>(), u, AT); my_timer.stop(); reduce(count, NoAccumulate(), PlusMonoid<int32_t>(), w); std::cout << "w' := u'+.*A : " << my_timer.elapsed() << " usec, w.nvals = " << w.nvals() << " reduce = " << count << std::endl; my_timer.start(); vxm(w, NoMask(), Plus<double>(), ArithmeticSemiring<double>(), u, AT); my_timer.stop(); reduce(count, NoAccumulate(), PlusMonoid<int32_t>(), w); std::cout << "w' := w' + u'+.*A : " << my_timer.elapsed() << " usec, w.nvals = " << w.nvals() << " reduce = " << count << std::endl; my_timer.start(); vxm(w, M, NoAccumulate(), ArithmeticSemiring<double>(), u, AT); my_timer.stop(); reduce(count, NoAccumulate(), PlusMonoid<int32_t>(), w); std::cout << "w'<m',merge> := u'+.*A : " << my_timer.elapsed() << " usec, w.nvals = " << w.nvals() << " reduce = " << count << std::endl; my_timer.start(); vxm(w, M, NoAccumulate(), ArithmeticSemiring<double>(), u, AT, REPLACE); my_timer.stop(); reduce(count, NoAccumulate(), PlusMonoid<int32_t>(), w); std::cout << "w'<m',replace> := u'+.*A : " << my_timer.elapsed() << " usec, w.nvals = " << w.nvals() << " reduce = " << count << std::endl; my_timer.start(); vxm(w, M, Plus<double>(), ArithmeticSemiring<double>(), u, AT); my_timer.stop(); reduce(count, NoAccumulate(), PlusMonoid<int32_t>(), w); std::cout << "w'<m',merge> := w' + u'+.*A : " << my_timer.elapsed() << " usec, w.nvals = " << w.nvals() << " reduce = " << count << std::endl; my_timer.start(); vxm(w, M, Plus<double>(), ArithmeticSemiring<double>(), u, AT, REPLACE); my_timer.stop(); reduce(count, NoAccumulate(), PlusMonoid<int32_t>(), w); std::cout << "w'<m',replace> := w' + u'+.*A : " << my_timer.elapsed() << " usec, w.nvals = " << w.nvals() << " reduce = " << count << std::endl; my_timer.start(); vxm(w, complement(M), NoAccumulate(), ArithmeticSemiring<double>(), u, AT); my_timer.stop(); reduce(count, NoAccumulate(), PlusMonoid<int32_t>(), w); std::cout << "w'<!m',merge> := u'+.*A : " << my_timer.elapsed() << " usec, w.nvals = " << w.nvals() << " reduce = " << count << std::endl; my_timer.start(); vxm(w, complement(M), NoAccumulate(), ArithmeticSemiring<double>(), u, AT, REPLACE); my_timer.stop(); reduce(count, NoAccumulate(), PlusMonoid<int32_t>(), w); std::cout << "w'<!m',replace> := u'+.*A : " << my_timer.elapsed() << " usec, w.nvals = " << w.nvals() << " reduce = " << count << std::endl; my_timer.start(); vxm(w, complement(M), Plus<double>(), ArithmeticSemiring<double>(), u, AT); my_timer.stop(); reduce(count, NoAccumulate(), PlusMonoid<int32_t>(), w); std::cout << "w'<!m',merge> := w' + u'+.*A : " << my_timer.elapsed() << " usec, w.nvals = " << w.nvals() << " reduce = " << count << std::endl; my_timer.start(); vxm(w, complement(M), Plus<double>(), ArithmeticSemiring<double>(), u, AT, REPLACE); my_timer.stop(); reduce(count, NoAccumulate(), PlusMonoid<int32_t>(), w); std::cout << "w'<!m',replace> := w' + u'+.*A: " << my_timer.elapsed() << " usec, w.nvals = " << w.nvals() << " reduce = " << count << std::endl; //---- my_timer.start(); vxm(w, structure(M), NoAccumulate(), ArithmeticSemiring<double>(), u, AT); my_timer.stop(); reduce(count, NoAccumulate(), PlusMonoid<int32_t>(), w); std::cout << "w'<s(m'),merge> := u'+.*A : " << my_timer.elapsed() << " usec, w.nvals = " << w.nvals() << " reduce = " << count << std::endl; my_timer.start(); vxm(w, structure(M), NoAccumulate(), ArithmeticSemiring<double>(), u, AT, REPLACE); my_timer.stop(); reduce(count, NoAccumulate(), PlusMonoid<int32_t>(), w); std::cout << "w'<s(m'),replace> := u'+.*A : " << my_timer.elapsed() << " usec, w.nvals = " << w.nvals() << " reduce = " << count << std::endl; my_timer.start(); vxm(w, structure(M), Plus<double>(), ArithmeticSemiring<double>(), u, AT); my_timer.stop(); reduce(count, NoAccumulate(), PlusMonoid<int32_t>(), w); std::cout << "w'<s(m'),merge> := w' + u'+.*A : " << my_timer.elapsed() << " usec, w.nvals = " << w.nvals() << " reduce = " << count << std::endl; my_timer.start(); vxm(w, structure(M), Plus<double>(), ArithmeticSemiring<double>(), u, AT, REPLACE); my_timer.stop(); reduce(count, NoAccumulate(), PlusMonoid<int32_t>(), w); std::cout << "w'<s(m'),replace> := w' + u'+.*A : " << my_timer.elapsed() << " usec, w.nvals = " << w.nvals() << " reduce = " << count << std::endl; my_timer.start(); vxm(w, complement(structure(M)), NoAccumulate(), ArithmeticSemiring<double>(), u, AT); my_timer.stop(); reduce(count, NoAccumulate(), PlusMonoid<int32_t>(), w); std::cout << "w'<!s(m'),merge> := u'+.*A : " << my_timer.elapsed() << " usec, w.nvals = " << w.nvals() << " reduce = " << count << std::endl; my_timer.start(); vxm(w, complement(structure(M)), NoAccumulate(), ArithmeticSemiring<double>(), u, AT, REPLACE); my_timer.stop(); reduce(count, NoAccumulate(), PlusMonoid<int32_t>(), w); std::cout << "w'<!s(m'),replace> := u'+.*A : " << my_timer.elapsed() << " usec, w.nvals = " << w.nvals() << " reduce = " << count << std::endl; my_timer.start(); vxm(w, complement(structure(M)), Plus<double>(), ArithmeticSemiring<double>(), u, AT); my_timer.stop(); reduce(count, NoAccumulate(), PlusMonoid<int32_t>(), w); std::cout << "w'<!s(m'),merge> := w' + u'+.*A : " << my_timer.elapsed() << " usec, w.nvals = " << w.nvals() << " reduce = " << count << std::endl; my_timer.start(); vxm(w, complement(structure(M)), Plus<double>(), ArithmeticSemiring<double>(), u, AT, REPLACE); my_timer.stop(); reduce(count, NoAccumulate(), PlusMonoid<int32_t>(), w); std::cout << "w'<!s(m'),replace> := w' + u'+.*A: " << my_timer.elapsed() << " usec, w.nvals = " << w.nvals() << " reduce = " << count << std::endl; //=================== // u'*A' //=================== std::cout << "IMPLEMENTATION: u'*A'" << std::endl; w1.clear(); my_timer.start(); vxm(w1, NoMask(), NoAccumulate(), ArithmeticSemiring<double>(), u, transpose(A)); my_timer.stop(); reduce(count, NoAccumulate(), PlusMonoid<int32_t>(), w1); std::cout << "w' := u'+.*A' : " << my_timer.elapsed() << " usec, w1.nvals = " << w1.nvals() << " reduce = " << count << std::endl; my_timer.start(); vxm(w1, NoMask(), Plus<double>(), ArithmeticSemiring<double>(), u, transpose(A)); my_timer.stop(); reduce(count, NoAccumulate(), PlusMonoid<int32_t>(), w1); std::cout << "w' := w' + u'+.*A' : " << my_timer.elapsed() << " usec, w1.nvals = " << w1.nvals() << " reduce = " << count << std::endl; my_timer.start(); vxm(w1, M, NoAccumulate(), ArithmeticSemiring<double>(), u, transpose(A)); my_timer.stop(); reduce(count, NoAccumulate(), PlusMonoid<int32_t>(), w1); std::cout << "w'<m',merge> := u'+.*A' : " << my_timer.elapsed() << " usec, w1.nvals = " << w1.nvals() << " reduce = " << count << std::endl; my_timer.start(); vxm(w1, M, NoAccumulate(), ArithmeticSemiring<double>(), u, transpose(A), REPLACE); my_timer.stop(); reduce(count, NoAccumulate(), PlusMonoid<int32_t>(), w1); std::cout << "w'<m',replace> := u'+.*A : " << my_timer.elapsed() << " usec, w1.nvals = " << w1.nvals() << " reduce = " << count << std::endl; my_timer.start(); vxm(w1, M, Plus<double>(), ArithmeticSemiring<double>(), u, transpose(A)); my_timer.stop(); reduce(count, NoAccumulate(), PlusMonoid<int32_t>(), w1); std::cout << "w'<m',merge> := w' + u'+.*A' : " << my_timer.elapsed() << " usec, w1.nvals = " << w1.nvals() << " reduce = " << count << std::endl; my_timer.start(); vxm(w1, M, Plus<double>(), ArithmeticSemiring<double>(), u, transpose(A), REPLACE); my_timer.stop(); reduce(count, NoAccumulate(), PlusMonoid<int32_t>(), w1); std::cout << "w'<m',replace> := w' + u'+.*A' : " << my_timer.elapsed() << " usec, w1.nvals = " << w1.nvals() << " reduce = " << count << std::endl; my_timer.start(); vxm(w1, complement(M), NoAccumulate(), ArithmeticSemiring<double>(), u, transpose(A)); my_timer.stop(); reduce(count, NoAccumulate(), PlusMonoid<int32_t>(), w1); std::cout << "w'<!m',merge> := u'+.*A' : " << my_timer.elapsed() << " usec, w1.nvals = " << w1.nvals() << " reduce = " << count << std::endl; my_timer.start(); vxm(w1, complement(M), NoAccumulate(), ArithmeticSemiring<double>(), u, transpose(A), REPLACE); my_timer.stop(); reduce(count, NoAccumulate(), PlusMonoid<int32_t>(), w1); std::cout << "w'<!m',replace> := u'+.*A' : " << my_timer.elapsed() << " usec, w1.nvals = " << w1.nvals() << " reduce = " << count << std::endl; my_timer.start(); vxm(w1, complement(M), Plus<double>(), ArithmeticSemiring<double>(), u, transpose(A)); my_timer.stop(); reduce(count, NoAccumulate(), PlusMonoid<int32_t>(), w1); std::cout << "w'<!m',merge> := w' + u'+.*A' : " << my_timer.elapsed() << " usec, w1.nvals = " << w1.nvals() << " reduce = " << count << std::endl; my_timer.start(); vxm(w1, complement(M), Plus<double>(), ArithmeticSemiring<double>(), u, transpose(A), REPLACE); my_timer.stop(); reduce(count, NoAccumulate(), PlusMonoid<int32_t>(), w1); std::cout << "w'<!m',replace> := w' + u'+.*A': " << my_timer.elapsed() << " usec, w1.nvals = " << w1.nvals() << " reduce = " << count << std::endl; //----- my_timer.start(); vxm(w1, structure(M), NoAccumulate(), ArithmeticSemiring<double>(), u, transpose(A)); my_timer.stop(); reduce(count, NoAccumulate(), PlusMonoid<int32_t>(), w1); std::cout << "w'<s(m'),merge> := u'+.*A' : " << my_timer.elapsed() << " usec, w1.nvals = " << w1.nvals() << " reduce = " << count << std::endl; my_timer.start(); vxm(w1, structure(M), NoAccumulate(), ArithmeticSemiring<double>(), u, transpose(A), REPLACE); my_timer.stop(); reduce(count, NoAccumulate(), PlusMonoid<int32_t>(), w1); std::cout << "w'<s(m'),replace> := u'+.*A' : " << my_timer.elapsed() << " usec, w1.nvals = " << w1.nvals() << " reduce = " << count << std::endl; my_timer.start(); vxm(w1, structure(M), Plus<double>(), ArithmeticSemiring<double>(), u, transpose(A)); my_timer.stop(); reduce(count, NoAccumulate(), PlusMonoid<int32_t>(), w1); std::cout << "w'<s(m'),merge> := w' + u'+.*A' : " << my_timer.elapsed() << " usec, w1.nvals = " << w1.nvals() << " reduce = " << count << std::endl; my_timer.start(); vxm(w1, structure(M), Plus<double>(), ArithmeticSemiring<double>(), u, transpose(A), REPLACE); my_timer.stop(); reduce(count, NoAccumulate(), PlusMonoid<int32_t>(), w1); std::cout << "w'<s(m'),replace> := w' + u'+.*A' : " << my_timer.elapsed() << " usec, w1.nvals = " << w1.nvals() << " reduce = " << count << std::endl; my_timer.start(); vxm(w1, complement(structure(M)), NoAccumulate(), ArithmeticSemiring<double>(), u, transpose(A)); my_timer.stop(); reduce(count, NoAccumulate(), PlusMonoid<int32_t>(), w1); std::cout << "w'<!s(m'),merge> := u'+.*A' : " << my_timer.elapsed() << " usec, w1.nvals = " << w1.nvals() << " reduce = " << count << std::endl; my_timer.start(); vxm(w1, complement(structure(M)), NoAccumulate(), ArithmeticSemiring<double>(), u, transpose(A), REPLACE); my_timer.stop(); reduce(count, NoAccumulate(), PlusMonoid<int32_t>(), w1); std::cout << "w'<!s(m'),replace> := u'+.*A' : " << my_timer.elapsed() << " usec, w1.nvals = " << w1.nvals() << " reduce = " << count << std::endl; my_timer.start(); vxm(w1, complement(structure(M)), Plus<double>(), ArithmeticSemiring<double>(), u, transpose(A)); my_timer.stop(); reduce(count, NoAccumulate(), PlusMonoid<int32_t>(), w1); std::cout << "w'<!s(m'),merge> := w' + u'+.*A' : " << my_timer.elapsed() << " usec, w1.nvals = " << w1.nvals() << " reduce = " << count << std::endl; my_timer.start(); vxm(w1, complement(structure(M)), Plus<double>(), ArithmeticSemiring<double>(), u, transpose(A), REPLACE); my_timer.stop(); reduce(count, NoAccumulate(), PlusMonoid<int32_t>(), w1); std::cout << "w'<!s(m'),replace> := w' + u'+.*A': " << my_timer.elapsed() << " usec, w1.nvals = " << w1.nvals() << " reduce = " << count << std::endl; bool passed = (w == w1); std::cout << "Results " << (passed ? "PASSED" : "FAILED") << std::endl; return 0; }
36.662698
80
0.514612
[ "vector" ]
dbf0a2dc9439ec2d66d49ae76af6d24be228e78f
10,958
cpp
C++
SharedCode/scenes/SplayFingersScene.cpp
jing-interactive/digital_art_2014
736ce10ea3fa92b415c57fa5a1a41a64e6d98622
[ "MIT" ]
1
2019-10-10T12:23:21.000Z
2019-10-10T12:23:21.000Z
SharedCode/scenes/SplayFingersScene.cpp
jing-interactive/digital_art_2014
736ce10ea3fa92b415c57fa5a1a41a64e6d98622
[ "MIT" ]
null
null
null
SharedCode/scenes/SplayFingersScene.cpp
jing-interactive/digital_art_2014
736ce10ea3fa92b415c57fa5a1a41a64e6d98622
[ "MIT" ]
3
2019-05-02T11:20:41.000Z
2021-07-26T16:38:38.000Z
#pragma once #include "SplayFingersScene.h" SplayFingersScene::SplayFingersScene(ofxPuppet* puppet, HandWithFingertipsSkeleton* handWithFingertipsSkeleton, HandWithFingertipsSkeleton* immutableHandWithFingertipsSkeleton) { Scene::Scene(); Scene::setup("Splay Fingers", "Splay Fingers (Hand With Fingertips)", puppet, (Skeleton*)handWithFingertipsSkeleton, (Skeleton*)immutableHandWithFingertipsSkeleton); this->maxPalmAngleLeft = 60; this->maxPalmAngleRight = -60; this->maxBaseAngleLeft = 20; this->maxBaseAngleRight = -20; this->maxAngle = 50; this->averageAngleOffset = 0; this->effectStrength = 1.0; this->insertionFracRunningAvg = 0.5; this->angularSpreadRunningAvg = 60.0; } //================================================================= void SplayFingersScene::setupGui() { SplayFingersScene::initializeGui(); this->gui->addSlider("Max Angle", 0, 90, &maxAngle); this->gui->addSpacer(); this->gui->addSlider("Effect Strength", 0, 3, &effectStrength); this->gui->addSpacer(); this->gui->autoSizeToFitWidgets(); } //================================================================= void SplayFingersScene::setupMouseGui() { SplayFingersScene::initializeMouseGui(); vector<string> mouseOptions; mouseOptions.push_back("Palm Position"); mouseOptions.push_back("Palm Rotation"); mouseOptions.push_back("Finger Base Rotation"); this->mouseRadio = this->mouseGui->addRadio("Mouse Control Options", mouseOptions); this->mouseRadio->getToggles()[0]->setValue(true); this->mouseGui->addSpacer(); this->mouseGui->autoSizeToFitWidgets(); } //================================================================= void SplayFingersScene::update() { HandWithFingertipsSkeleton* handWithFingertipsSkeleton = (HandWithFingertipsSkeleton*)this->skeleton; int palm = HandWithFingertipsSkeleton::PALM; ofVec2f palmPos = handWithFingertipsSkeleton->getPositionAbsolute(palm); // get range of finger splay: the maximum difference in angle between the thumb and pinky. // The angular spread seems to range from ~30-90 degrees. // pinky: ofVec2f pinkyPt0 = handWithFingertipsSkeleton->getPositionAbsolute(HandWithFingertipsSkeleton::PINKY_BASE); ofVec2f pinkyPt1 = handWithFingertipsSkeleton->getPositionAbsolute(HandWithFingertipsSkeleton::PINKY_MID); ofVec2f pinkyDir = pinkyPt1 - pinkyPt0; // thumb: ofVec2f thumbPt1 = handWithFingertipsSkeleton->getPositionAbsolute(HandWithFingertipsSkeleton::THUMB_MID); ofVec2f thumbPt2 = handWithFingertipsSkeleton->getPositionAbsolute(HandWithFingertipsSkeleton::THUMB_TOP); ofVec2f thumbDir = thumbPt2 - thumbPt1; float pinkyAngle = RAD_TO_DEG * atan2f ( pinkyDir.y, pinkyDir.x ); float thumbAngle = RAD_TO_DEG * atan2f ( thumbDir.y, thumbDir.x ); float angularSpread = (180.0 - abs(pinkyAngle)) + (180.0 - abs(thumbAngle)); angularSpreadRunningAvg = 0.95*angularSpreadRunningAvg + 0.05*angularSpread; // printf ("angularSpreadRunningAvg = %f \n", angularSpreadRunningAvg); if (true) { int tip[] = {HandWithFingertipsSkeleton::PINKY_TIP, HandWithFingertipsSkeleton::RING_TIP, HandWithFingertipsSkeleton::MIDDLE_TIP, HandWithFingertipsSkeleton::INDEX_TIP, HandWithFingertipsSkeleton::THUMB_TIP}; int top[] = {HandWithFingertipsSkeleton::PINKY_TOP, HandWithFingertipsSkeleton::RING_TOP, HandWithFingertipsSkeleton::MIDDLE_TOP, HandWithFingertipsSkeleton::INDEX_TOP, HandWithFingertipsSkeleton::THUMB_TOP}; int mid[] = {HandWithFingertipsSkeleton::PINKY_MID, HandWithFingertipsSkeleton::RING_MID, HandWithFingertipsSkeleton::MIDDLE_MID, HandWithFingertipsSkeleton::INDEX_MID, HandWithFingertipsSkeleton::THUMB_MID}; int base[] = { HandWithFingertipsSkeleton::PINKY_BASE, HandWithFingertipsSkeleton::RING_BASE, HandWithFingertipsSkeleton::MIDDLE_BASE, HandWithFingertipsSkeleton::INDEX_BASE, HandWithFingertipsSkeleton::THUMB_BASE}; // have the agnel offset based on a running average, for stability float angleOffset = ofMap (palmPos.x, 256,440, 1,0); angleOffset = ofClamp (angleOffset, 0,1); angleOffset = maxAngle * powf (angleOffset, 0.75); averageAngleOffset = 0.94*averageAngleOffset + 0.06* angleOffset; float insertionFrac = ofMap (palmPos.x, 256,440, 1,0); insertionFrac = ofClamp (insertionFrac, 0,1); insertionFrac = powf (insertionFrac, 1.0); // nullop insertionFracRunningAvg = 0.95*insertionFracRunningAvg + 0.05*insertionFrac; // 0...1 int fingerCount = 5; for (int i=0; i < fingerCount; i++) { int joints[] = {base[i], mid[i], top[i], tip[i]}; float angleOffsetToUse = averageAngleOffset; ofVec2f basePos = handWithFingertipsSkeleton->getPositionAbsolute(joints[0]); bool bDoThumb = (fingerCount > 4); if (bDoThumb && (i == 4)){ basePos = handWithFingertipsSkeleton->getPositionAbsolute(joints[1]); } ofVec2f positions[] = { handWithFingertipsSkeleton->getPositionAbsolute(joints[0]), handWithFingertipsSkeleton->getPositionAbsolute(joints[1]), handWithFingertipsSkeleton->getPositionAbsolute(joints[2]), handWithFingertipsSkeleton->getPositionAbsolute(joints[3])}; float lengths[] = { positions[0].distance(positions[1]), positions[1].distance(positions[2]), positions[2].distance(positions[3])}; ofVec2f dir = positions[1] - positions[0]; if (bDoThumb && (i == 4)){ dir = positions[2] - positions[1]; } dir.normalize(); float dx = dir.x; float dy = dir.y; float fingerOrientationDegrees = RAD_TO_DEG * atan2f(dy,dx); float newFingerOrientationDegrees = fingerOrientationDegrees; if (fingerOrientationDegrees > 0){ // ~135 (at extreme)...180 float amountToExaggerate = 180 - fingerOrientationDegrees; amountToExaggerate *= (1.0 + effectStrength);//*insertionFracRunningAvg); newFingerOrientationDegrees = 180 - amountToExaggerate; } else { // ~ -135 (at extreme)...-180 float amountToExaggerate = fingerOrientationDegrees - (-180); amountToExaggerate *= (1.0 + effectStrength);//*insertionFracRunningAvg); newFingerOrientationDegrees = -180 + amountToExaggerate; } angleOffsetToUse = newFingerOrientationDegrees - fingerOrientationDegrees; if (bDoThumb && (i == 4)){ angleOffsetToUse *= 0.75; // just a little less so for the thumb, please....looks better } int fingerPartCount = 3; for (int j=0; j<fingerPartCount; j++) { dir = dir.getRotated (angleOffsetToUse); dir.normalize(); dir = dir * lengths[j]; ofVec2f parent = handWithFingertipsSkeleton->getPositionAbsolute(joints[j]); handWithFingertipsSkeleton->setPosition(joints[j+1], parent, true, false); handWithFingertipsSkeleton->setPosition(joints[j+1], dir, false, false); } } } } //================================================================= void SplayFingersScene::updateMouse(float mx, float my) { ofVec2f mouse(mx, my); HandWithFingertipsSkeleton* handWithFingertipsSkeleton = (HandWithFingertipsSkeleton*)this->skeleton; HandWithFingertipsSkeleton* immutableHandWithFingertipsSkeleton = (HandWithFingertipsSkeleton*)this->immutableSkeleton; ofVec2f xAxis(1, 0); const int fingerCount = 5; int wrist = HandWithFingertipsSkeleton::WRIST; int palm = HandWithFingertipsSkeleton::PALM; int base[] = {HandWithFingertipsSkeleton::THUMB_BASE, HandWithFingertipsSkeleton::INDEX_BASE, HandWithFingertipsSkeleton::MIDDLE_BASE, HandWithFingertipsSkeleton::RING_BASE, HandWithFingertipsSkeleton::PINKY_BASE}; int mid[] = {HandWithFingertipsSkeleton::THUMB_MID, HandWithFingertipsSkeleton::INDEX_MID, HandWithFingertipsSkeleton::MIDDLE_MID, HandWithFingertipsSkeleton::RING_MID, HandWithFingertipsSkeleton::PINKY_MID}; int top[] = {HandWithFingertipsSkeleton::THUMB_TIP, HandWithFingertipsSkeleton::INDEX_TIP, HandWithFingertipsSkeleton::MIDDLE_TIP, HandWithFingertipsSkeleton::RING_TIP, HandWithFingertipsSkeleton::PINKY_TIP}; ofVec2f origWristPos = puppet->getOriginalMesh().getVertex(handWithFingertipsSkeleton->getControlIndex(wrist)); ofVec2f origPalmPos = puppet->getOriginalMesh().getVertex(handWithFingertipsSkeleton->getControlIndex(palm)); ofVec2f origBasePos[fingerCount]; ofVec2f origMidPos[fingerCount]; ofVec2f origTopPos[fingerCount]; for (int i=0; i < fingerCount; i++) { origBasePos[i] = puppet->getOriginalMesh().getVertex(handWithFingertipsSkeleton->getControlIndex(base[i])); origMidPos[i] = puppet->getOriginalMesh().getVertex(handWithFingertipsSkeleton->getControlIndex(mid[i])); origTopPos[i] = puppet->getOriginalMesh().getVertex(handWithFingertipsSkeleton->getControlIndex(top[i])); } ofVec2f origPalmDir; ofVec2f origFingerDir; float curRot; float newRot; float correction = 0; float baseCorrection[] = {26.75, -3, 1.75, 7.75, 9.75}; float midCorrection[] = {6.75, 2, -1.5, -1.75, -3.5}; switch(getSelection(mouseRadio)) { case 0: // palm position handWithFingertipsSkeleton->setPosition(HandWithFingertipsSkeleton::PALM, mouse, true); immutableHandWithFingertipsSkeleton->setPosition(HandWithFingertipsSkeleton::PALM, mouse, true); break; case 1: // palm rotation origPalmDir = origPalmPos - origWristPos; curRot = origPalmDir.angle(xAxis); newRot; if (mx <= 384) { newRot = ofMap(mx, 0, 384, -(curRot+correction+maxPalmAngleLeft), -(curRot+correction)); } else { newRot = ofMap(mx, 384, 768, -(curRot+correction), -(curRot+correction+maxPalmAngleRight)); } handWithFingertipsSkeleton->setRotation(palm, newRot, true, false); immutableHandWithFingertipsSkeleton->setRotation(palm, newRot, true, false); break; case 2: // finger base rotation for (int i=0; i < fingerCount; i++) { origFingerDir = origBasePos[i] - origPalmPos; curRot = origFingerDir.angle(xAxis); if (mx <= 384) { newRot = ofMap(mx, 0, 384, -(curRot+baseCorrection[i]+maxBaseAngleLeft), -(curRot+baseCorrection[i])); } else { newRot = ofMap(mx, 384, 768, -(curRot+baseCorrection[i]), -(curRot+baseCorrection[i]+maxBaseAngleRight)); } handWithFingertipsSkeleton->setRotation(base[i], newRot, true, false); immutableHandWithFingertipsSkeleton->setRotation(base[i], newRot, true, false); } break; } } void SplayFingersScene::draw() { //ofSetColor(255); //ofLine(0, splayAxis, ofGetWidth(),splayAxis); }
43.484127
215
0.685618
[ "vector" ]
dbfa2f8ec4640339b879fe4f557fbebc1989aee6
27,072
cc
C++
src/core/web_app_manager.cc
webosose/wam
5d3eb5d50a176fb82c1fa5564655277181c9235a
[ "Apache-2.0" ]
12
2018-03-22T18:51:21.000Z
2020-07-18T03:57:53.000Z
src/core/web_app_manager.cc
webosose/wam
5d3eb5d50a176fb82c1fa5564655277181c9235a
[ "Apache-2.0" ]
24
2018-10-30T10:33:03.000Z
2020-06-02T19:59:29.000Z
src/core/web_app_manager.cc
webosose/wam
5d3eb5d50a176fb82c1fa5564655277181c9235a
[ "Apache-2.0" ]
17
2018-03-22T18:51:24.000Z
2021-11-19T13:03:43.000Z
// Copyright (c) 2008-2021 LG Electronics, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // SPDX-License-Identifier: Apache-2.0 #include "web_app_manager.h" #include <unistd.h> #include <algorithm> #include <sstream> #include <string> #include <json/value.h> #include "webos/application_installation_handler.h" #include "webos/public/runtime.h" #include "application_description.h" #include "base_check.h" #include "device_info.h" #include "log_manager.h" #include "network_status_manager.h" #include "platform_module_factory.h" #include "service_sender.h" #include "util/url.h" #include "utils.h" #include "web_app_base.h" #include "web_app_factory_manager_impl.h" #include "web_app_manager_config.h" #include "web_app_manager_service.h" #include "web_app_manager_tracer.h" #include "web_page_base.h" #include "web_process_manager.h" #include "window_types.h" static const int kContinuousReloadingLimit = 3; WebAppManager* WebAppManager::Instance() { // not a leak -- static variable initializations are only ever done once static WebAppManager* instance = new WebAppManager(); return instance; } WebAppManager::WebAppManager() : deleting_pages_(false), network_status_manager_(new NetworkStatusManager()), suspend_delay_(0), max_custom_suspend_delay_(0), is_accessibility_enabled_(false) {} WebAppManager::~WebAppManager() { if (device_info_) device_info_->Terminate(); } void WebAppManager::NotifyMemoryPressure( webos::WebViewBase::MemoryPressureLevel level) { std::list<const WebAppBase*> app_list = RunningApps(); for (auto it = app_list.begin(); it != app_list.end(); ++it) { const WebAppBase* app = *it; // Skip memory pressure handling on preloaded apps if chromium pressure is // critical (when system is on low or critical) because they will be killed // anyway if (app->IsActivated() && (!app->Page()->IsPreload() || level != webos::WebViewBase::MEMORY_PRESSURE_CRITICAL)) app->Page()->NotifyMemoryPressure(level); else { LOG_DEBUG( "Skipping memory pressure handler for" " instanceId(%s) appId(%s) isActivated(%d) isPreload(%d) Level(%d)", app->InstanceId().c_str(), app->AppId().c_str(), app->IsActivated(), app->Page()->IsPreload(), level); } } } void WebAppManager::SetPlatformModules( std::unique_ptr<PlatformModuleFactory> factory) { web_app_manager_config_ = factory->GetWebAppManagerConfig(); service_sender_ = factory->GetServiceSender(); web_process_manager_ = factory->GetWebProcessManager(); device_info_ = factory->GetDeviceInfo(); device_info_->Initialize(); LoadEnvironmentVariable(); } void WebAppManager::SetWebAppFactory( std::unique_ptr<WebAppFactoryManager> factory) { web_app_factory_ = std::move(factory); } bool WebAppManager::Run() { LoadEnvironmentVariable(); return true; } void WebAppManager::Quit() {} WebAppFactoryManager* WebAppManager::GetWebAppFactory() { return web_app_factory_ ? web_app_factory_.get() : WebAppFactoryManagerImpl::Instance(); } void WebAppManager::LoadEnvironmentVariable() { suspend_delay_ = web_app_manager_config_->GetSuspendDelayTime(); max_custom_suspend_delay_ = web_app_manager_config_->GetMaxCustomSuspendDelayTime(); web_app_manager_config_->PostInitConfiguration(); } void WebAppManager::SetUiSize(int width, int height) { if (device_info_) { device_info_->SetDisplayWidth(width); device_info_->SetDisplayHeight(height); } } int WebAppManager::CurrentUiWidth() { int width = 0; if (device_info_) device_info_->GetDisplayWidth(width); return width; } int WebAppManager::CurrentUiHeight() { int height = 0; if (device_info_) device_info_->GetDisplayHeight(height); return height; } bool WebAppManager::GetSystemLanguage(std::string& value) { if (!device_info_) return false; return device_info_->GetSystemLanguage(value); } bool WebAppManager::GetDeviceInfo(const std::string& name, std::string& value) { if (!device_info_) return false; return device_info_->GetDeviceInfo(name, value); } void WebAppManager::OnRelaunchApp(const std::string& instance_id, const std::string& app_id, const std::string& args, const std::string& launching_app_id) { WebAppBase* app = FindAppByInstanceId(instance_id); if (!app) { LOG_WARNING(MSGID_APP_RELAUNCH, 0, "Failed to relaunch due to no running app"); return; } if (app->AppId() != app_id) { LOG_WARNING(MSGID_APP_RELAUNCH, 0, "Failed to relaunch due to no running app named %s", app_id.c_str()); } // Do not relaunch when preload args is setted // luna-send -n 1 luna://com.webos.applicationManager/launch '{"id":<AppId> // "preload":<PreloadState> }' Json::Value json = util::StringToJson(args); if (!json.isObject()) { LOG_WARNING(MSGID_APP_RELAUNCH, 0, "Failed to parse json args: '%s'", args.c_str()); return; } // if this app is KeepAlive and window.close() was once and relaunch now no // matter preloaded, fastswitching, launch by launch API need to clear the // flag if it needs if (app->KeepAlive() && app->ClosePageRequested()) app->SetClosePageRequested(false); if (!json["preload"].isString() && !json["launchedHidden"].asBool()) { app->Relaunch(args.c_str(), launching_app_id.c_str()); } else { LOG_INFO(MSGID_WAM_DEBUG, 3, PMLOGKS("APP_ID", app->AppId().c_str()), PMLOGKS("INSTANCE_ID", instance_id.c_str()), PMLOGKFV("PID", "%d", app->Page()->GetWebProcessPID()), "Relaunch with preload option, ignore"); } } bool WebAppManager::PurgeSurfacePool(uint32_t pid) { return true; // Deprecated (2016-04-01) } bool WebAppManager::IsDiscardCodeCacheRequired() { return false; // Deprecated (2016-04-01) } bool WebAppManager::SetInspectorEnable(const std::string& app_id) { // 1. find appId from then running App List, for (AppList::const_iterator it = app_list_.begin(); it != app_list_.end(); ++it) { WebAppBase* app = (*it); if (app_id == app->Page()->AppId()) { LOG_DEBUG("[%s] setInspectorEnable", app_id.c_str()); app->Page()->SetInspectorEnable(); return true; } } return false; } void WebAppManager::DiscardCodeCache(uint32_t pid) { // Deprecated (2016-04-01) } void WebAppManager::OnShutdownEvent() { #if defined(TARGET_DESKTOP) for (AppList::const_iterator it = app_list_.begin(); it != app_list_.end(); ++it) { delete (*it); } // Palm::WebGlobal::garbageCollectNow(); #endif return; } bool WebAppManager::OnKillApp(const std::string& app_id, const std::string& instance_id, bool force) { WebAppBase* app = FindAppByInstanceId(instance_id); if (app == nullptr || (app->AppId() != app_id)) { LOG_INFO(MSGID_KILL_APP, 2, PMLOGKS("APP_ID", app_id.c_str()), PMLOGKS("INSTANCE_ID", instance_id.c_str()), "App doesn't exist; return"); return false; } if (force) ForceCloseAppInternal(app); else CloseAppInternal(app); return true; } bool WebAppManager::OnPauseApp(const std::string& instance_id) { if (WebAppBase* app = FindAppByInstanceId(instance_id)) { // although, name of the handler-function as well as the code it // contains are not consistent, according to the "pauseApp" Luna API // design, a "paused" application shall be just hidden by WAM app->HideWindow(); return true; } LOG_INFO(MSGID_PAUSE_APP, 1, PMLOGKS("INSTANCE_ID", instance_id.c_str()), "Application not found."); return false; } std::list<const WebAppBase*> WebAppManager::RunningApps() { std::list<const WebAppBase*> apps; for (AppList::const_iterator it = app_list_.begin(); it != app_list_.end(); ++it) { apps.push_back(*it); } return apps; } std::list<const WebAppBase*> WebAppManager::RunningApps(uint32_t pid) { std::list<const WebAppBase*> apps; for (AppList::const_iterator it = app_list_.begin(); it != app_list_.end(); ++it) { WebAppBase* app = (*it); if (app->Page()->GetWebProcessPID() == pid) apps.push_back(app); } return apps; } WebAppBase* WebAppManager::OnLaunchUrl( const std::string& url, const std::string& win_type, std::shared_ptr<ApplicationDescription> app_desc, const std::string& instance_id, const std::string& args, const std::string& launching_app_id, int& err_code, std::string& err_msg) { WebAppFactoryManager* factory = GetWebAppFactory(); WebAppBase* app = factory->CreateWebApp(win_type.c_str(), app_desc, app_desc->SubType().c_str()); if (!app) { err_code = kErrCodeLaunchappUnsupportedType; err_msg = kErrUnsupportedType; return nullptr; } WebPageBase* page = factory->CreateWebPage(win_type.c_str(), wam::Url(url.c_str()), app_desc, app_desc->SubType().c_str(), args.c_str()); // set use launching time optimization true while app loading. page->SetUseLaunchOptimization(true); if (win_type == kWtFloating || win_type == kWtCard) page->SetEnableBackgroundRun(app_desc->IsEnableBackgroundRun()); app->SetAppDescription(app_desc); app->SetAppProperties(args); app->SetInstanceId(instance_id); app->SetLaunchingAppId(launching_app_id); if (web_app_manager_config_->IsCheckLaunchTimeEnabled()) app->StartLaunchTimer(); app->Attach(page); app->SetPreloadState(args); page->Load(); WebPageAdded(page); app_list_.push_back(app); if (app_version_.find(app_desc->Id()) != app_version_.end()) { if (app_version_[app_desc->Id()] != app_desc->Version()) { app->SetNeedReload(true); app_version_[app_desc->Id()] = app_desc->Version(); } } else { app_version_[app_desc->Id()] = app_desc->Version(); } LOG_INFO(MSGID_START_LAUNCHURL, 3, PMLOGKS("APP_ID", app->AppId().c_str()), PMLOGKS("INSTANCE_ID", app->InstanceId().c_str()), PMLOGKFV("PID", "%d", app->Page()->GetWebProcessPID()), ""); return app; } void WebAppManager::ForceCloseAppInternal(WebAppBase* app) { app->SetKeepAlive(false); CloseAppInternal(app); } void WebAppManager::RemoveClosingAppList(const std::string& instance_id) { while (closing_app_list_.find(instance_id) != closing_app_list_.end()) { closing_app_list_.erase(instance_id); } } void WebAppManager::CloseAppInternal(WebAppBase* app, bool ignore_clean_resource) { WebPageBase* page = app->Page(); UTIL_ASSERT(page); if (page->IsClosing()) { LOG_INFO(MSGID_CLOSE_APP_INTERNAL, 3, PMLOGKS("APP_ID", app->AppId().c_str()), PMLOGKS("INSTANCE_ID", app->InstanceId().c_str()), PMLOGKFV("PID", "%d", app->Page()->GetWebProcessPID()), "In Closing; return"); } LOG_INFO(MSGID_CLOSE_APP_INTERNAL, 3, PMLOGKS("APP_ID", app->AppId().c_str()), PMLOGKS("INSTANCE_ID", app->InstanceId().c_str()), PMLOGKFV("PID", "%d", app->Page()->GetWebProcessPID()), ""); if (app->KeepAlive() && app->HideWindow()) return; std::string type = app->GetAppDescription()->DefaultWindowType(); AppDeleted(app); WebPageRemoved(app->Page()); RemoveWebAppFromWebProcessInfoMap(app->AppId()); PostRunningAppList(); last_crashed_app_ids_ = std::unordered_map<std::string, int>(); // Set m_isClosing flag first, this flag will be checked in web page // suspending page->SetClosing(true); app->DeleteSurfaceGroup(); // Do suspend WebPage if (type == "overlay") app->Hide(true); else app->OnStageDeactivated(); if (ignore_clean_resource) delete app; else { closing_app_list_.emplace(app->InstanceId(), app); if (page->IsRegisteredCloseCallback()) { LOG_INFO(MSGID_CLOSE_APP_INTERNAL, 3, PMLOGKS("APP_ID", app->AppId().c_str()), PMLOGKS("INSTANCE_ID", app->InstanceId().c_str()), PMLOGKFV("PID", "%d", app->Page()->GetWebProcessPID()), "CloseCallback; execute"); app->ExecuteCloseCallback(); } else { LOG_INFO(MSGID_CLOSE_APP_INTERNAL, 3, PMLOGKS("APP_ID", app->AppId().c_str()), PMLOGKS("INSTANCE_ID", app->InstanceId().c_str()), PMLOGKFV("PID", "%d", app->Page()->GetWebProcessPID()), "NO CloseCallback; load about:blank"); app->DispatchUnload(); } } } bool WebAppManager::CloseAllApps(uint32_t pid) { AppList running_apps; for (AppList::iterator it = app_list_.begin(); it != app_list_.end(); ++it) { WebAppBase* app = (*it); if (!pid) running_apps.insert(running_apps.end(), app); else if (web_process_manager_->GetWebProcessPID(app) == pid) running_apps.insert(running_apps.end(), app); } AppList::iterator it = running_apps.begin(); while (it != running_apps.end()) { WebAppBase* app = (*it); ForceCloseAppInternal(app); // closeAppInternal will cause the app pointed to to become invalid, // so remove it from the list so we don't act upon it after that it = running_apps.erase(it); } return running_apps.empty(); } void WebAppManager::WebPageAdded(WebPageBase* page) { std::string app_id = page->AppId(); auto found = find_if(app_page_map_.begin(), app_page_map_.end(), [&](const auto& item) { return (item.first == app_id) && (item.second == page); }); if (found == app_page_map_.end()) { app_page_map_.emplace(app_id, page); } } void WebAppManager::WebPageRemoved(WebPageBase* page) { if (!deleting_pages_) { // Remove from list of pending delete pages PageList::iterator iter = std::find(pages_to_delete_list_.begin(), pages_to_delete_list_.end(), page); if (iter != pages_to_delete_list_.end()) { pages_to_delete_list_.erase(iter); } } auto range = app_page_map_.equal_range(page->AppId()); auto it = range.first; while (it != range.second) { if (it->second == page) { it = app_page_map_.erase(it); } else { it++; } } } void WebAppManager::RemoveWebAppFromWebProcessInfoMap( const std::string& appId) { // Deprecated (2016-04-01) } WebAppBase* WebAppManager::FindAppById(const std::string& app_id) { for (AppList::iterator it = app_list_.begin(); it != app_list_.end(); ++it) { WebAppBase* app = (*it); if (app->Page() && app->AppId() == app_id) return app; } return 0; } std::list<WebAppBase*> WebAppManager::FindAppsById(const std::string& appId) { std::list<WebAppBase*> apps; for (AppList::iterator it = app_list_.begin(); it != app_list_.end(); ++it) { WebAppBase* app = (*it); if (app->Page() && app->AppId() == appId) apps.push_back(app); } return apps; } WebAppBase* WebAppManager::FindAppByInstanceId(const std::string& instance_id) { for (AppList::iterator it = app_list_.begin(); it != app_list_.end(); ++it) { WebAppBase* app = (*it); if (app->Page() && (app->InstanceId() == instance_id)) return app; } return 0; } void WebAppManager::AppDeleted(WebAppBase* app) { if (!app) return; std::string app_id; if (app->Page()) app_id = app->AppId(); app_list_.remove(app); if (!app_id.empty()) shell_page_map_.erase(app_id); } void WebAppManager::SetSystemLanguage(const std::string& language) { if (!device_info_) return; device_info_->SetSystemLanguage(language); for (AppList::const_iterator it = app_list_.begin(); it != app_list_.end(); ++it) { WebAppBase* app = (*it); app->SetPreferredLanguages(language); } LOG_DEBUG("New system language: %s", language.c_str()); } void WebAppManager::SetDeviceInfo(const std::string& name, const std::string& value) { if (!device_info_) return; std::string old_value; if (device_info_->GetDeviceInfo(name, old_value) && (old_value == value)) return; device_info_->SetDeviceInfo(name, value); BroadcastWebAppMessage(WebAppMessageType::kDeviceInfoChanged, name); LOG_DEBUG("SetDeviceInfo %s; %s to %s", name.c_str(), old_value.c_str(), value.c_str()); } void WebAppManager::BroadcastWebAppMessage(WebAppMessageType type, const std::string& message) { for (AppList::const_iterator it = app_list_.begin(); it != app_list_.end(); ++it) { WebAppBase* app = (*it); app->HandleWebAppMessage(type, message); } } bool WebAppManager::ProcessCrashed(const std::string& app_id, const std::string& instance_id) { WebAppBase* app = FindAppByInstanceId(instance_id); if (!app) return false; if (app->IsWindowed()) { if (app->IsActivated()) { last_crashed_app_ids_[app->AppId()]++; int reloading_limit = app->IsNormal() ? kContinuousReloadingLimit - 1 : kContinuousReloadingLimit; if (last_crashed_app_ids_[app->AppId()] >= reloading_limit) { LOG_INFO(MSGID_WEBPROC_CRASH, 4, PMLOGKS("APP_ID", app_id.c_str()), PMLOGKS("INSTANCE_ID", instance_id.c_str()), PMLOGKS("InForeground", "true"), PMLOGKS("Reloading limit", "Close app"), ""); CloseAppInternal(app, true); } else { LOG_INFO(MSGID_WEBPROC_CRASH, 4, PMLOGKS("APP_ID", app_id.c_str()), PMLOGKS("INSTANCE_ID", instance_id.c_str()), PMLOGKS("InForeground", "true"), PMLOGKS("Reloading limit", "OK; Reload default page"), ""); app->Page()->ReloadDefaultPage(); } } else if (app->IsMinimized()) { LOG_INFO(MSGID_WEBPROC_CRASH, 3, PMLOGKS("APP_ID", app_id.c_str()), PMLOGKS("INSTANCE_ID", instance_id.c_str()), PMLOGKS("InBackground", "Will be Reloaded in Relaunch"), ""); app->SetCrashState(true); } } return true; } const std::string WebAppManager::WindowTypeFromString(const std::string& str) { if (str == "overlay") return kWtOverlay; if (str == "popup") return kWtPopup; if (str == "minimal") return kWtMinimal; if (str == "floating") return kWtFloating; if (str == "system_ui") return kWtSystemUi; return kWtCard; } void WebAppManager::SetForceCloseApp(const std::string& app_id, const std::string& instance_id) { WebAppBase* app = FindAppByInstanceId(instance_id); if (!app) return; if (app->IsWindowed()) { if (app->KeepAlive() && app->GetHiddenWindow()) { ForceCloseAppInternal(app); LOG_INFO(MSGID_FORCE_CLOSE_KEEP_ALIVE_APP, 2, PMLOGKS("APP_ID", app_id.c_str()), PMLOGKS("INSTANCE_ID", instance_id.c_str()), ""); return; } } app->SetForceClose(); } void WebAppManager::RequestKillWebProcess(uint32_t pid) { // Deprecated (2016-0401) } void WebAppManager::DeleteStorageData(const std::string& identifier) { web_process_manager_->DeleteStorageData( IdentifierForSecurityOrigin(identifier)); } void WebAppManager::KillCustomPluginProcess(const std::string& base_path) { // Deprecated (2016-04-01) } /** * Launch an application (webApps only, not native). * * @param appId The application ID to launch. * @param params The call parameters. * @param the ID of the application performing the launch (can be NULL). * @param errMsg The error message (will be empty if this call was successful). * * @todo: this should now be moved private and be protected...leaving it for now * as to not break stuff and make things slightly faster for intra-sysmgr * mainloop launches */ std::string WebAppManager::Launch(const std::string& app_desc_string, const std::string& params, const std::string& launching_app_id, int& err_code, std::string& err_msg) { std::shared_ptr<ApplicationDescription> desc( ApplicationDescription::FromJsonString(app_desc_string.c_str())); if (!desc) return std::string(); std::string url = desc->EntryPoint(); std::string win_type = WindowTypeFromString(desc->DefaultWindowType()); err_msg.erase(); // Set displayAffinity (multi display support) Json::Value json = util::StringToJson(params); if (!json.isObject()) { LOG_WARNING(MSGID_APP_LAUNCH, 0, "Failed to parse params: '%s'", params.c_str()); return std::string(); } Json::Value affinity = json["displayAffinity"]; if (affinity.isInt()) desc->SetDisplayAffinity(affinity.asInt()); std::string instance_id = json["instanceId"].asString(); // Check if app is already running if (IsRunningApp(instance_id)) { OnRelaunchApp(instance_id, desc->Id().c_str(), params.c_str(), launching_app_id.c_str()); } else { // Run as a normal app if (!OnLaunchUrl(url, win_type, desc, instance_id, params, launching_app_id, err_code, err_msg)) { return std::string(); } } return instance_id; } bool WebAppManager::IsRunningApp(const std::string& id) { std::list<const WebAppBase*> running = RunningApps(); for (auto it = running.begin(); it != running.end(); ++it) if ((*it)->InstanceId() == id) return true; return false; } std::vector<ApplicationInfo> WebAppManager::List(bool include_system_apps) { std::vector<ApplicationInfo> list; std::list<const WebAppBase*> running = RunningApps(); for (auto it = running.begin(); it != running.end(); ++it) { const WebAppBase* web_app_base = *it; if (web_app_base->AppId().size() || (!web_app_base->AppId().size() && include_system_apps)) { uint32_t pid = web_process_manager_->GetWebProcessPID(web_app_base); list.push_back(ApplicationInfo(web_app_base->InstanceId(), web_app_base->AppId(), pid)); } } return list; } Json::Value WebAppManager::GetWebProcessProfiling() { return web_process_manager_->GetWebProcessProfiling(); } void WebAppManager::CloseApp(const std::string& app_id) { if (service_sender_) service_sender_->CloseApp(app_id); } void WebAppManager::PostRunningAppList() { if (!service_sender_) return; std::vector<ApplicationInfo> apps = List(true); service_sender_->PostlistRunningApps(apps); } void WebAppManager::PostWebProcessCreated(const std::string& app_id, const std::string& instance_id, uint32_t pid) { if (!service_sender_) return; PostRunningAppList(); if (!web_app_manager_config_->IsPostWebProcessCreatedDisabled()) service_sender_->PostWebProcessCreated(app_id, instance_id, pid); } uint32_t WebAppManager::GetWebProcessId(const std::string& app_id, const std::string& instance_id) { uint32_t pid = 0; WebAppBase* app = FindAppByInstanceId(instance_id); if (app && app->AppId() == app_id && web_process_manager_) pid = web_process_manager_->GetWebProcessPID(app); return pid; } std::string WebAppManager::GenerateInstanceId() { static int next_process_id = 1000; std::ostringstream stream; stream << (next_process_id++); return stream.str(); } void WebAppManager::SetAccessibilityEnabled(bool enabled) { if (is_accessibility_enabled_ == enabled) return; for (auto it = app_list_.begin(); it != app_list_.end(); ++it) { // set audion guidance on/off on settings app if ((*it)->Page()) (*it)->Page()->SetAudioGuidanceOn(enabled); (*it)->SetUseAccessibility(enabled); } is_accessibility_enabled_ = enabled; } void WebAppManager::SendEventToAllAppsAndAllFrames( const std::string& jsscript) { for (auto it = app_list_.begin(); it != app_list_.end(); ++it) { WebAppBase* app = (*it); if (app->Page()) { LOG_DEBUG("[%s] send event with %s", app->AppId().c_str(), jsscript.c_str()); // to send all subFrame, use this function instead of // evaluateJavaScriptInAllFrames() app->Page()->EvaluateJavaScriptInAllFrames(jsscript); } } } void WebAppManager::ServiceCall(const std::string& url, const std::string& payload, const std::string& appId) { if (service_sender_) service_sender_->ServiceCall(url, payload, appId); } void WebAppManager::UpdateNetworkStatus(const Json::Value& object) { NetworkStatus status; status.FromJsonObject(object); webos::Runtime::GetInstance()->SetNetworkConnected( status.IsInternetConnectionAvailable()); network_status_manager_->UpdateNetworkStatus(status); } bool WebAppManager::IsEnyoApp(const std::string& appId) { WebAppBase* app = FindAppById(appId); if (app && !app->GetAppDescription()->EnyoVersion().empty()) return true; return false; } void WebAppManager::ClearBrowsingData(const int remove_browsing_data_mask) { web_process_manager_->ClearBrowsingData(remove_browsing_data_mask); } int WebAppManager::MaskForBrowsingDataType(const char* type) { return web_process_manager_->MaskForBrowsingDataType(type); } void WebAppManager::AppInstalled(const std::string& app_id) { LOG_INFO(MSGID_WAM_DEBUG, 0, "App installed; id=%s", app_id.c_str()); auto p = webos::ApplicationInstallationHandler::GetInstance(); if (p) p->OnAppInstalled(app_id); } void WebAppManager::AppRemoved(const std::string& app_id) { LOG_INFO(MSGID_WAM_DEBUG, 0, "App removed; id=%s", app_id.c_str()); auto p = webos::ApplicationInstallationHandler::GetInstance(); if (p) p->OnAppRemoved(app_id); } std::string WebAppManager::IdentifierForSecurityOrigin( const std::string& identifier) { std::string lowcase_identifier = identifier; std::transform(lowcase_identifier.begin(), lowcase_identifier.end(), lowcase_identifier.begin(), tolower); if (lowcase_identifier != identifier) { LOG_WARNING(MSGID_APPID_HAS_UPPERCASE, 0, "Application id should not contain capital letters"); } return (lowcase_identifier + webos::WebViewBase::kSecurityOriginPostfix); }
31.045872
80
0.656767
[ "object", "vector", "transform" ]
e0129af44faa2098301e541e21650152a1bdd056
3,362
cpp
C++
src/tiertwo/netfulfilledman.cpp
BITRUBCOIN-Project/BITRUBCOIN
0a0f9f21bfb15c3c9ed91f7f88e3b955a2d842d1
[ "MIT" ]
null
null
null
src/tiertwo/netfulfilledman.cpp
BITRUBCOIN-Project/BITRUBCOIN
0a0f9f21bfb15c3c9ed91f7f88e3b955a2d842d1
[ "MIT" ]
null
null
null
src/tiertwo/netfulfilledman.cpp
BITRUBCOIN-Project/BITRUBCOIN
0a0f9f21bfb15c3c9ed91f7f88e3b955a2d842d1
[ "MIT" ]
null
null
null
// Copyright (c) 2014-2020 The Dash Core developers // Copyright (c) 2022 The BITRUBCOIN Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or https://www.opensource.org/licenses/mit-license.php. #include "tiertwo/netfulfilledman.h" #include "chainparams.h" #include "netaddress.h" #include "shutdown.h" #include "utiltime.h" CNetFulfilledRequestManager g_netfulfilledman(DEFAULT_ITEMS_FILTER_SIZE); CNetFulfilledRequestManager::CNetFulfilledRequestManager(unsigned int _itemsFilterSize) { itemsFilterSize = _itemsFilterSize; if (itemsFilterSize != 0) { itemsFilter = std::make_unique<CBloomFilter>(itemsFilterSize, 0.001, 0, BLOOM_UPDATE_ALL); } } void CNetFulfilledRequestManager::AddFulfilledRequest(const CService& addr, const std::string& strRequest) { LOCK(cs_mapFulfilledRequests); mapFulfilledRequests[addr][strRequest] = GetTime() + Params().FulfilledRequestExpireTime(); } bool CNetFulfilledRequestManager::HasFulfilledRequest(const CService& addr, const std::string& strRequest) const { LOCK(cs_mapFulfilledRequests); auto it = mapFulfilledRequests.find(addr); if (it != mapFulfilledRequests.end()) { auto itReq = it->second.find(strRequest); if (itReq != it->second.end()) { return itReq->second > GetTime(); } } return false; } static std::vector<unsigned char> convertElement(const CService& addr, const uint256& itemHash) { CDataStream stream(SER_NETWORK, PROTOCOL_VERSION); stream << addr.GetAddrBytes(); stream << itemHash; return {stream.begin(), stream.end()}; } void CNetFulfilledRequestManager::AddItemRequest(const CService& addr, const uint256& itemHash) { LOCK(cs_mapFulfilledRequests); assert(itemsFilter); itemsFilter->insert(convertElement(addr, itemHash)); itemsFilterCount++; } bool CNetFulfilledRequestManager::HasItemRequest(const CService& addr, const uint256& itemHash) const { LOCK(cs_mapFulfilledRequests); assert(itemsFilter); return itemsFilter->contains(convertElement(addr, itemHash)); } void CNetFulfilledRequestManager::CheckAndRemove() { LOCK(cs_mapFulfilledRequests); int64_t now = GetTime(); for (auto it = mapFulfilledRequests.begin(); it != mapFulfilledRequests.end();) { for (auto it_entry = it->second.begin(); it_entry != it->second.end();) { if (now > it_entry->second) { it_entry = it->second.erase(it_entry); } else { it_entry++; } } if (it->second.empty()) { it = mapFulfilledRequests.erase(it); } else { it++; } } if (now > lastFilterCleanup || itemsFilterCount >= itemsFilterSize) { itemsFilter->clear(); itemsFilterCount = 0; lastFilterCleanup = now + filterCleanupTime; } } void CNetFulfilledRequestManager::Clear() { LOCK(cs_mapFulfilledRequests); mapFulfilledRequests.clear(); } std::string CNetFulfilledRequestManager::ToString() const { LOCK(cs_mapFulfilledRequests); std::ostringstream info; info << "Nodes with fulfilled requests: " << (int)mapFulfilledRequests.size(); return info.str(); } void CNetFulfilledRequestManager::DoMaintenance() { if (ShutdownRequested()) return; CheckAndRemove(); }
30.844037
112
0.694825
[ "vector" ]
e012d513f668f0ddb11bfaca08b6ddcb5fbf3f4f
1,629
cpp
C++
Siv3D/src/ThirdParty/lunasvg/svggeometryelement.cpp
nokotan/siv6
7df183550a6c0160ba918d6ad24c3ae48231e26b
[ "MIT" ]
1
2020-05-16T14:13:04.000Z
2020-05-16T14:13:04.000Z
Siv3D/src/ThirdParty/lunasvg/svggeometryelement.cpp
nokotan/siv6
7df183550a6c0160ba918d6ad24c3ae48231e26b
[ "MIT" ]
null
null
null
Siv3D/src/ThirdParty/lunasvg/svggeometryelement.cpp
nokotan/siv6
7df183550a6c0160ba918d6ad24c3ae48231e26b
[ "MIT" ]
null
null
null
#include "svggeometryelement.h" #include "paint.h" #include "strokedata.h" namespace lunasvg { SVGGeometryElement::SVGGeometryElement(ElementID elementId, SVGDocument* document) : SVGGraphicsElement(elementId, document) { } void SVGGeometryElement::render(RenderContext& context) const { if(style().isDisplayNone()) { context.skipElement(); return; } SVGGraphicsElement::render(context); RenderState& state = context.state(); if(state.style.isHidden()) return; state.bbox = makeBoundingBox(state); if(state.style.hasStroke()) { double strokeWidth = state.style.strokeWidth(state); state.bbox.x -= strokeWidth * 0.5; state.bbox.y -= strokeWidth * 0.5; state.bbox.width += strokeWidth; state.bbox.height += strokeWidth; } if(context.mode() == RenderModeBounding) return; Path path = makePath(state); if(context.mode() == RenderModeDisplay) { StrokeData strokeData = state.style.strokeData(state); Paint fillPaint = state.style.fillPaint(state); Paint strokePaint = state.style.strokePaint(state); WindRule fillRule = state.style.fillRule(); fillPaint.setOpacity(state.style.fillOpacity() * state.style.opacity()); strokePaint.setOpacity(state.style.strokeOpacity() * state.style.opacity()); state.canvas.draw(path, state.matrix, fillRule, fillPaint, strokePaint, strokeData); } else { state.canvas.draw(path, state.matrix, state.style.clipRule(), KRgbBlack, Paint(), StrokeData()); } } } // namespace lunasvg
28.086207
104
0.661756
[ "render" ]
e0150d471fef102355bc524ed3d76dcd00175d1e
965
hpp
C++
agency/coordinate/detail/shape/make_shape.hpp
nerikhman/agency
966ac59101f2fc3561a86b11874fbe8de361d0e4
[ "BSD-3-Clause" ]
129
2016-08-18T23:24:15.000Z
2022-03-25T12:06:05.000Z
agency/coordinate/detail/shape/make_shape.hpp
nerikhman/agency
966ac59101f2fc3561a86b11874fbe8de361d0e4
[ "BSD-3-Clause" ]
86
2016-08-19T03:43:33.000Z
2020-07-20T14:27:41.000Z
agency/coordinate/detail/shape/make_shape.hpp
nerikhman/agency
966ac59101f2fc3561a86b11874fbe8de361d0e4
[ "BSD-3-Clause" ]
23
2016-08-18T23:52:13.000Z
2022-02-28T16:28:20.000Z
#pragma once #include <agency/detail/config.hpp> #include <utility> #include <array> namespace agency { namespace detail { template<class Shape> struct make_shape_impl { template<class... Args> __AGENCY_ANNOTATION static Shape make(Args&&... args) { return Shape{std::forward<Args>(args)...}; } }; // specialization for std::array, which requires the weird doubly-nested brace syntax template<class T, size_t n> struct make_shape_impl<std::array<T,n>> { template<class... Args> __AGENCY_ANNOTATION static std::array<T,n> make(Args&&... args) { return std::array<T,n>{{std::forward<Args>(args)...}}; } }; // make_shape makes a Shape from a list of elements // XXX should probably require that the number of Args... matches shape_size template<class Shape, class... Args> __AGENCY_ANNOTATION Shape make_shape(Args&&... args) { return make_shape_impl<Shape>::make(std::forward<Args>(args)...); } } // end detail } // end agency
19.3
85
0.699482
[ "shape" ]
e01bdf2948d2d3381eb3db19a45975b4cf78385c
957
cpp
C++
FirstInterCommunication/src/Window.cpp
droplet92/FIC
db8bcc2503f7001dc6af5474b59ef9129f995f91
[ "MIT" ]
null
null
null
FirstInterCommunication/src/Window.cpp
droplet92/FIC
db8bcc2503f7001dc6af5474b59ef9129f995f91
[ "MIT" ]
null
null
null
FirstInterCommunication/src/Window.cpp
droplet92/FIC
db8bcc2503f7001dc6af5474b59ef9129f995f91
[ "MIT" ]
null
null
null
#include "Window.h" #include <SFML/Graphics.hpp> #include <string> #include "GameObject.h" namespace FIC { constexpr unsigned int windowWidth = 1920; constexpr unsigned int windowHeight = 1080; const sf::VideoMode Window::windowVideoMode = { windowWidth, windowHeight }; const std::string Window::windowTitle = "FIC"; struct Window::Impl { sf::RenderWindow window{ windowVideoMode, windowTitle, sf::Style::Fullscreen }; }; Window::Window() : pImpl(new Impl) { } Window::~Window() = default; bool Window::isOpen() const { return pImpl->window.isOpen(); } void Window::draw(const GameObject& object) const { pImpl->window.draw(object); } void Window::clear() const { pImpl->window.clear(sf::Color::Blue); } void Window::display() const { pImpl->window.display(); } bool Window::pollEvent(sf::Event& event) { return pImpl->window.pollEvent(event); } void Window::close() const { pImpl->window.close(); } }
17.722222
81
0.685475
[ "object" ]
e01ca590af1051ab704fb860cfdd2825b27b00d4
3,853
cpp
C++
ext_modules/_maix_camera/_camera_pybind.cpp
znstj/MaixPy3
f672b2049b668a5a72ad249933cf9a009760799e
[ "MIT" ]
null
null
null
ext_modules/_maix_camera/_camera_pybind.cpp
znstj/MaixPy3
f672b2049b668a5a72ad249933cf9a009760799e
[ "MIT" ]
null
null
null
ext_modules/_maix_camera/_camera_pybind.cpp
znstj/MaixPy3
f672b2049b668a5a72ad249933cf9a009760799e
[ "MIT" ]
null
null
null
#include "_maix_camera.h" using namespace std; namespace py = pybind11; class _Camera_pybind11 { private: public: string version = "0.2"; string name = "_maix_Camera"; _Camera_pybind11() { } ~_Camera_pybind11() { cout << "_maix_Camera exit!" << endl; } string _maix_Camera_help() { return "MaixPy3 Camera\n"; } }; PYBIND11_MODULE(_maix_camera, m) { m.doc() = "This is MaixPy3 Camera\n"; pybind11::class_<_Camera_pybind11>(m, "_maix_camera") .def(pybind11::init()) .def_readonly("_VERSION_", &_Camera_pybind11::version) .def_readonly("_NAME_", &_Camera_pybind11::name) .def("help", &_Camera_pybind11::_maix_Camera_help, R"pbdoc(read()\n\nRead image(rgb888) bytes data from device.\n)pbdoc") .doc() = "_maix_Camera"; pybind11::class_<_camera>(m, "Camera") .def(py::init<int, int, int, int, int>(), py::arg("w") = 240, py::arg("h") = 240, py::arg("dev_id") = 0, py::arg("m") = 0, py::arg("f") = 0) .def_readwrite("width", &_camera::width) .def_readwrite("height", &_camera::height) .def("read", &_camera::read) .def("close", &_camera::close, R"pbdoc(close()\n\nClose Camera device.\n)pbdoc") .def("__enter__", &_camera::__enter__) .def("__exit__", &_camera::__exit__) .doc() = "Camera(width, height,device_id) -> Camera object.\n"; } void v_close(_camera *tp) { #ifdef VirtualCamera cout << "virtual_camera close!" << endl; #else // VirtualCamera if (NULL != tp->cam) { libmaix_cam_destroy(&tp->cam); } libmaix_image_module_deinit(); libmaix_camera_module_deinit(); #endif //VirtualCamera else } void v_init(_camera *tp) { #ifdef VirtualCamera cout << "virtual_camera init success!" << endl; #else // VirtualCamera libmaix_camera_module_init(); libmaix_image_module_init(); tp->rgb_img = NULL; tp->cam = libmaix_cam_create(tp->dev_id, tp->width, tp->height, tp->m, tp->f); if (NULL != tp->cam) { int ret = tp->cam->start_capture(tp->cam); if (0 == ret) { return; } else { PyErr_SetString(PyExc_RuntimeError, "cam start capture err!"); throw py::error_already_set(); } } else { PyErr_SetString(PyExc_RuntimeError, "libmaix_cam_create err!"); throw py::error_already_set(); } v_close(tp); #endif // VirtualCamera } _camera::_camera(int w, int h, int dev_id, int m, int f) { this->width = w; this->height = h; this->dev_id = dev_id; this->m = m; this->f = f; v_init(this); } _camera::~_camera() { v_close(this); } // "read()\n\nRead image(rgb888) bytes data from device.\n" pybind11::list _camera::read() { py::list return_val; #ifdef VirtualCamera return_val.append(0); return_val.append(py::none()); #else int ret = LIBMAIX_ERR_NONE; for (size_t i = 0; i < 5; i++) { ret = this->cam->capture_image(this->cam, &this->rgb_img); // not ready, sleep to release CPU if (ret == LIBMAIX_ERR_NOT_READY) { usleep(25 * 1000); continue; } break; } /* Copy data to bytearray and return */ if (NULL != this->rgb_img) { return_val.append(true); py::bytes tmp((char *)this->rgb_img->data, this->rgb_img->width * this->rgb_img->height * 3); return_val.append(tmp); } else { return_val.append(false); return_val.append(py::none()); } #endif // VirtualCamera return return_val; } void _camera::close() { v_close(this); } void _camera::__enter__() { //do nothing... } void _camera::__exit__() { v_close(this); } // string v831_camera::str() // { // return string(__FILE__); // }
23.071856
148
0.586815
[ "object" ]
e0382db9a3a6575cbebf0d83c78539f562f6c3cf
1,114
hpp
C++
Includes/Programs/Calculator.hpp
utilForever/Calculator
9a97e476721e862cd3909c3d25457d9b6e1fef65
[ "MIT" ]
54
2015-11-05T01:51:08.000Z
2018-09-06T11:11:22.000Z
Includes/Programs/Calculator.hpp
utilForever/CubbyCalc
9a97e476721e862cd3909c3d25457d9b6e1fef65
[ "MIT" ]
7
2018-12-07T14:50:14.000Z
2021-08-10T05:33:18.000Z
Includes/Programs/Calculator.hpp
utilForever/Calculator
9a97e476721e862cd3909c3d25457d9b6e1fef65
[ "MIT" ]
19
2016-04-07T07:57:54.000Z
2018-09-05T10:54:10.000Z
#ifndef CUBBYCALC_CALCULATOR_HPP #define CUBBYCALC_CALCULATOR_HPP #include <Expressions/Expression.hpp> #include <Expressions/ExpressionMaker.hpp> #include <Variables/VariableTable.hpp> #include <vector> class Calculator { private: Calculator(const Calculator&); Calculator& operator=(const Calculator&); ExpressionMaker m_expMaker; VariableTable m_varTable; static const std::string m_validCommand; static const std::string m_numberedCommand; Expression m_currentExpression; char m_command; size_t m_expressionNumber; int m_expressionNR; std::vector<Expression> m_oldExpressions; void PrintHelp(); void GetCommand(); bool ValidCommand(); void ExecuteCommand(); void PrintExpression(std::ostream&) const; void EvaluateAndPrintExpression(std::ostream&) const; void PrintPostfix(std::ostream&) const; void PrintInfix(std::ostream&) const; void PrintTree(std::ostream&) const; void SetCurrentExpression(); void ReadExpression(std::istream&); std::vector<std::string> SplitExpression(const std::string&, const std::string&); public: Calculator(); ~Calculator(); void Run(); }; #endif
23.702128
82
0.779174
[ "vector" ]
e0393eda67d3a6ea4e6957037d6de8f3e9395793
53,478
cpp
C++
SURVIVORSrc/src/simulator/SV_Simulator.cpp
aquaskyline/LinkedReadsSimulator
9ad7e54651be49305ae1a9287e9a66515d7c5057
[ "MIT" ]
42
2016-12-21T19:57:55.000Z
2021-11-23T22:04:42.000Z
SURVIVORSrc/src/simulator/SV_Simulator.cpp
aquaskyline/LinkedReadsSimulator
9ad7e54651be49305ae1a9287e9a66515d7c5057
[ "MIT" ]
34
2017-01-09T01:40:23.000Z
2021-03-16T15:50:59.000Z
SURVIVORSrc/src/simulator/SV_Simulator.cpp
aquaskyline/LinkedReadsSimulator
9ad7e54651be49305ae1a9287e9a66515d7c5057
[ "MIT" ]
13
2017-01-03T21:44:49.000Z
2021-07-16T13:21:55.000Z
/* * SV_Simulator.cpp * * Created on: Jan 30, 2016 * Author: fsedlaze */ #include "SV_Simulator.h" bool is_valid(char base) { return (((base == 'A' || base == 'C') || (base == 'R' || base == 'X')) || ((base == 'T' || base == 'G') || (base == 'N' || base == 'M'))); } void check_genome(std::map<std::string, std::string> &genome, std::string msg) { std::cout << msg << " Genome checking:" << std::endl; for (std::map<std::string, std::string>::iterator i = genome.begin(); i != genome.end(); i++) { for (size_t j = 1; j < (*i).second.size() + 1; j++) { if (!is_valid((*i).second[j - 1])) { std::cout << "err! " << (*i).second[j - 1] << std::endl; } } } } int parse_value(char* buffer, size_t buffer_size) { //required for parameter! int count = 0; for (size_t i = 1; i < buffer_size && buffer[i] != '\n' && buffer[i] != '\0'; i++) { if (count == 1) { return atoi(&buffer[i]); } if (buffer[i] == ' ') { count++; } } return -1; } void simulate(std::map<std::string, std::string> genome, std::vector<struct_var> svs, std::string output_prefix) { std::cout << "apply SV" << std::endl; } parameter parse_param(std::string filename) { parameter tmp; size_t buffer_size = 200000; char*buffer = new char[buffer_size]; std::ifstream myfile; myfile.open(filename.c_str(), std::ifstream::in); if (!myfile.good()) { std::cout << "Annotation Parser: could not open file: " << filename.c_str() << std::endl; exit(0); } myfile.getline(buffer, buffer_size); myfile.getline(buffer, buffer_size); tmp.dup_max = parse_value(buffer, buffer_size); myfile.getline(buffer, buffer_size); tmp.dup_min = parse_value(buffer, buffer_size); myfile.getline(buffer, buffer_size); tmp.dup_num = parse_value(buffer, buffer_size); myfile.getline(buffer, buffer_size); tmp.indel_min = parse_value(buffer, buffer_size); myfile.getline(buffer, buffer_size); tmp.indel_max = parse_value(buffer, buffer_size); myfile.getline(buffer, buffer_size); tmp.indel_num = parse_value(buffer, buffer_size); myfile.getline(buffer, buffer_size); tmp.translocations_min = parse_value(buffer, buffer_size); myfile.getline(buffer, buffer_size); tmp.translocations_max = parse_value(buffer, buffer_size); myfile.getline(buffer, buffer_size); tmp.translocations_num = parse_value(buffer, buffer_size); myfile.getline(buffer, buffer_size); tmp.inv_min = parse_value(buffer, buffer_size); myfile.getline(buffer, buffer_size); tmp.inv_max = parse_value(buffer, buffer_size); myfile.getline(buffer, buffer_size); tmp.inv_num = parse_value(buffer, buffer_size); myfile.getline(buffer, buffer_size); tmp.inv_del_num = 0; if (!myfile.eof()) { tmp.inv_del_min = parse_value(buffer, buffer_size); myfile.getline(buffer, buffer_size); tmp.inv_del_max = parse_value(buffer, buffer_size); myfile.getline(buffer, buffer_size); tmp.inv_del_num = parse_value(buffer, buffer_size); myfile.getline(buffer, buffer_size); } tmp.inv_dup_num = 0; if (!myfile.eof()) { tmp.inv_dup_min = parse_value(buffer, buffer_size); myfile.getline(buffer, buffer_size); tmp.inv_dup_max = parse_value(buffer, buffer_size); myfile.getline(buffer, buffer_size); tmp.inv_dup_num = parse_value(buffer, buffer_size); myfile.getline(buffer, buffer_size); } tmp.intrachr_num = 0; if (!myfile.eof()) { tmp.intrachr_min = parse_value(buffer, buffer_size); myfile.getline(buffer, buffer_size); tmp.intrachr_max = parse_value(buffer, buffer_size); myfile.getline(buffer, buffer_size); tmp.intrachr_num = parse_value(buffer, buffer_size); //std::cout<<"NUM: "<<tmp.intrachr_num<<std::endl; } myfile.close(); return tmp; } std::map<std::string, std::string> read_fasta(std::string ref_file, int min_length) { std::string buffer; std::ifstream myfile; myfile.open(ref_file.c_str(), std::ifstream::in); if (!myfile.good()) { std::cout << "Annotation Parser: could not open file: " << ref_file.c_str() << std::endl; exit(0); } getline(myfile,buffer); std::map<std::string, std::string> genome; std::string seq; std::string name; while (!myfile.eof()) { if (buffer[0] == '>') { if (seq.size() > min_length) { genome[name] = seq; } name.clear(); seq.clear(); for (size_t i = 1; i < buffer.size() && buffer[i] != '\n' && buffer[i] != '\0' && buffer[i] != ' '; i++) { name += (buffer[i]); } } else { for (size_t i = 0; i < buffer.size() && buffer[i] != '\n' && buffer[i] != '\0'; i++) { seq += toupper(buffer[i]); } } getline(myfile,buffer); } for (size_t i = 0; i < buffer.size() && buffer[i] != '\n' && buffer[i] != '\0'; i++) { seq += toupper(buffer[i]); } myfile.close(); if (seq.size() > min_length) { genome[name] = seq; } seq.clear(); name.clear(); std::cout << "# Chrs passed size threshold:" << genome.size() << std::endl; return genome; } void sort_svs(std::vector<struct_var> svs) { std::map<std::string, std::vector<struct_var> > svs_tmp; for (size_t i = 0; i < svs.size(); i++) { svs_tmp[svs[i].pos.chr].push_back(svs[i]); //sort by chr: } for (std::map<std::string, std::vector<struct_var> >::iterator i = svs_tmp.begin(); i != svs_tmp.end(); i++) { std::vector<struct_var> tmp; if (!(*i).second.empty()) { tmp.push_back((*i).second[0]); for (size_t j = 0; j < (*i).second.size(); i++) { std::cout << (*i).second[j].pos.chr.c_str() << " " << (*i).second[j].pos.start << std::endl; size_t t = 0; while (tmp[t].pos.start < (*i).second[j].pos.start) { t++; } tmp.insert(tmp.begin() + t, (*i).second[j]); } } for (size_t j = 0; j < tmp.size(); j++) { std::cout << tmp[j].pos.chr.c_str() << " " << tmp[j].pos.start << std::endl; } } } float percent_N(std::string seq) { double n = 0; double size = (double) seq.size(); for (size_t i = 0; i < seq.size(); i++) { if (seq[i] == 'N') { n++; } } // std::cout<<"Percent: "<<n/size << " "<<n <<" " <<size<<std::endl; return n / size; } position get_pos(std::map<std::string, std::string> genome, int min_pos, int max_pos) { //std::cout<<max_pos<<std::endl; position tmp; std::string seq = "N"; //std::cout<<percent_N(seq)<<std::endl; //std::cout<<"Start:"<<std::endl; for (size_t i = 0; i < 100 && percent_N(seq) > 0.05; i++) { std::map<std::string, std::string>::iterator chr = genome.begin(); int id = rand() % genome.size(); //chose rand chr. int count = 0; while (chr != genome.end() && id != count) { //fast forward count++; chr++; } //std::cout<<"Place1"<<std::endl; tmp.chr = (*chr).first; //std::cout<<"Place1.1"<<std::endl; tmp.start = rand() % (((*chr).second.size() - max_pos)); //choose random start pos within chr length //std::cout<<"Place1.2"<<std::endl; if (max_pos == -1) { //insertion, translocation: //std::cout<<"Place1.3"<<std::endl; tmp.stop = max_pos; //std::cout<<"Place1.4"<<std::endl; } else { //std::cout<<"Place1.5"<<std::endl; tmp.stop = tmp.start + min_pos + (rand() % (max_pos - min_pos)); // choose stop location //std::cout<<"Place1.6"<<std::endl; } //std::cout<<"Place2"<<std::endl; int num = 0; while ((*chr).second.size() < tmp.stop && num < 100) { //choose chr,start, stop such that the mutation fits. Allow max 50 iterations! tmp.start = rand() % (((*chr).second.size() - max_pos)); //choose random start pos within chr length tmp.stop = tmp.start + min_pos + (rand() % (max_pos - min_pos)); // choose stop location num++; } //std::cout<<"Place3"<<std::endl; if (num == 100) { std::cerr << "Simulations are hindered by the two small chr size. " << std::endl; tmp.stop = -2; } if (max_pos != -1) { seq = (*chr).second.substr(tmp.start, tmp.stop - tmp.start); } //std::cout<<(*chr).first<<" "<<tmp.start<<" "<<tmp.stop<<std::endl; } //std::cout<<"end:"<<std::endl; return tmp; } bool is_overlapping(position curr, std::vector<struct_var> svs) { for (size_t i = 0; i < svs.size(); i++) { if (strcmp(svs[i].pos.chr.c_str(), curr.chr.c_str()) == 0) { if (svs[i].pos.stop >= curr.start && svs[i].pos.start <= curr.stop) { return true; } } } return false; } position choose_pos(std::map<std::string, std::string> genome, int min, int max, std::vector<struct_var>& svs) { position pos = get_pos(genome, min, max); int num = 0; while (is_overlapping(pos, svs) && num < 100) { pos = get_pos(genome, min, max); num++; } if (num == 100) { std::cerr << "Terminate program as it could not find a non overlapping region" << std::endl; exit(0); } return pos; } std::vector<struct_var> generate_mutations(std::string parameter_file, std::map<std::string, std::string> genome) { parameter par = parse_param(parameter_file); std::vector<struct_var> svs; //duplications struct_var mut; for (int i = 0; i < par.dup_num; i++) { mut.type = 0; //get_start location; mut.pos = choose_pos(genome, par.dup_min, par.dup_max, svs); //get_opposit location svs.push_back(mut); } //indels for (int i = 0; i < par.indel_num; i++) { //std::cout << "indel" << std::endl; if (rand() % 100 <= 50) { mut.type = 1; //insertion } else { mut.type = 4; //deletion } mut.pos = choose_pos(genome, par.indel_min, par.indel_max, svs); mut.target = mut.pos; svs.push_back(mut); } //inv for (int i = 0; i < par.inv_num; i++) { // std::cout << "inv" << std::endl; mut.type = 2; mut.pos = choose_pos(genome, par.inv_min, par.inv_max, svs); mut.target = mut.pos; mut.target.start = mut.pos.stop; mut.target.stop = mut.pos.start; svs.push_back(mut); } //tra inter std::cout << par.intrachr_num << std::endl; for (int i = 0; i < par.intrachr_num; i++) { mut.type = 6; mut.pos = choose_pos(genome, par.translocations_min, par.translocations_max, svs); //std::cout<<i<<": "<<mut.pos.chr<<" "<<mut.pos.start<<" size: "<<mut.pos.stop-mut.pos.start<<std::endl; mut.target = choose_pos(genome, mut.pos.stop - mut.pos.start, (mut.pos.stop - mut.pos.start) + 1, svs); //TRA has to be of the same size! while (strcmp(mut.target.chr.c_str(), mut.pos.chr.c_str()) != 0) { mut.target = choose_pos(genome, mut.pos.stop - mut.pos.start, (mut.pos.stop - mut.pos.start) + 1, svs); } //I need to be sure about the same lenght of the tra!: int size1 = mut.pos.stop - mut.pos.start; int size2 = mut.target.stop - mut.target.start; mut.pos.stop = mut.pos.start + std::min(size1, size2); mut.target.stop = mut.target.start + std::min(size1, size2); svs.push_back(mut); } //tra for (int i = 0; i < par.translocations_num; i++) { // std::cout << "tra" << std::endl; mut.type = 3; mut.pos = choose_pos(genome, par.translocations_min, par.translocations_max, svs); //std::cout<<"size: "<<mut.pos.stop-mut.pos.start<<std::endl; mut.target = choose_pos(genome, mut.pos.stop - mut.pos.start, (mut.pos.stop - mut.pos.start) + 1, svs); //TRA has to be of the same size! while (strcmp(mut.target.chr.c_str(), mut.pos.chr.c_str()) == 0) { mut.target = choose_pos(genome, mut.pos.stop - mut.pos.start, (mut.pos.stop - mut.pos.start) + 1, svs); } //I need to be sure about the same lenght of the tra!: int size1 = mut.pos.stop - mut.pos.start; int size2 = mut.target.stop - mut.target.start; mut.pos.stop = mut.pos.start + std::min(size1, size2); mut.target.stop = mut.target.start + std::min(size1, size2); svs.push_back(mut); } //complex inv_del for (int i = 0; i < par.inv_del_num; i++) { //1. sim: mut.type = 2; mut.pos = choose_pos(genome, par.inv_del_min, par.inv_del_max, svs); //2. determin size of del: int len = (mut.pos.stop - mut.pos.start) / 10; //dels are ~20% ofthe size! mut.pos.start += len; mut.pos.stop -= len; mut.target = mut.pos; mut.target.start = mut.pos.stop; mut.target.stop = mut.pos.start; svs.push_back(mut); struct_var del; //the del infront: del.type = 4; del.pos.chr = mut.pos.chr; del.pos.stop = mut.pos.start; del.pos.start = del.pos.stop - len; del.target = del.pos; svs.push_back(del); //the del behind: del.pos.start = mut.pos.stop; del.pos.stop = del.pos.start + len; del.target = del.pos; svs.push_back(del); } //inv dup for (int i = 0; i < par.inv_dup_num; i++) { mut.type = 5; //get_start location; mut.pos = choose_pos(genome, par.inv_dup_min, par.inv_dup_max, svs); //get_opposit location svs.push_back(mut); } // sort_svs(svs); return svs; } std::vector<struct_var> generate_mutations_ref(std::string parameter_file, std::map<std::string, std::string> genome) { parameter par = parse_param(parameter_file); std::vector<struct_var> svs; //duplications struct_var mut; //indels for (int i = 0; i < par.indel_num; i++) { //std::cout << "indel" << std::endl; if (rand() % 100 <= 50) { mut.type = 1; //insertion } else { mut.type = 4; //deletion } mut.pos = choose_pos(genome, par.indel_min, par.indel_max, svs); mut.target = mut.pos; svs.push_back(mut); } //inv for (int i = 0; i < par.inv_num; i++) { // std::cout << "inv" << std::endl; mut.type = 2; mut.pos = choose_pos(genome, par.inv_min, par.inv_max, svs); mut.target = mut.pos; mut.target.start = mut.pos.stop; mut.target.stop = mut.pos.start; svs.push_back(mut); } //tra for (int i = 0; i < par.translocations_num; i++) { // std::cout << "tra" << std::endl; mut.type = 3; mut.pos = choose_pos(genome, par.translocations_min, par.translocations_max, svs); //std::cout<<"size: "<<mut.pos.stop-mut.pos.start<<std::endl; mut.target = choose_pos(genome, mut.pos.stop - mut.pos.start, (mut.pos.stop - mut.pos.start) + 1, svs); //TRA has to be of the same size! while (strcmp(mut.target.chr.c_str(), mut.pos.chr.c_str()) == 0) { mut.target = choose_pos(genome, mut.pos.stop - mut.pos.start, (mut.pos.stop - mut.pos.start) + 1, svs); } //I need to be sure about the same lenght of the tra!: int size1 = mut.pos.stop - mut.pos.start; int size2 = mut.target.stop - mut.target.start; mut.pos.stop = mut.pos.start + std::min(size1, size2); mut.target.stop = mut.target.start + std::min(size1, size2); svs.push_back(mut); } return svs; } void store_sorted(std::vector<struct_var> &svs, struct_var tmp) { std::vector<struct_var>::iterator i = svs.begin(); while (i != svs.end() && strcmp(tmp.target.chr.c_str(), (*i).target.chr.c_str()) >= 0 && tmp.target.start > (*i).target.start) { i++; } svs.insert(i, tmp); } void store_ins(std::vector<insertions> & ins, insertions tmp) { std::vector<insertions>::iterator i = ins.begin(); while (i != ins.end() && tmp.target.start > (*i).target.start) { i++; } ins.insert(i, tmp); } char complement(char nuc) { switch (nuc) { case 'A': return 'T'; break; case 'C': return 'G'; break; case 'G': return 'C'; break; case 'T': return 'A'; break; default: return nuc; break; } return nuc; } void invert(std::string &seq) { std::string tmp; for (std::string::reverse_iterator i = seq.rbegin(); i != seq.rend(); i++) { tmp += complement((*i)); } seq.clear(); seq = tmp; } std::string rand_seq(int length) { std::string tmp; //tmp.resize((size_t) length); for (int i = 0; i < length; i++) { switch (rand() % 4) { case 0: tmp += 'A'; break; case 1: tmp += 'C'; break; case 2: tmp += 'G'; break; case 3: tmp += 'T'; break; } } return tmp; } void apply_mutations(std::map<std::string, std::string> &genome, std::vector<struct_var>& svs) { srand(time(NULL)); std::vector<insertions> ins; insertions in; std::string seq1; std::string seq2; int pos; std::vector<struct_var> new_svs; //Thanks to the invdup we need this. //all mutations that do not change the coordinates are later applied. //all others are directly applied (e.g. INV, TRA) for (size_t i = 0; i < svs.size(); i++) { std::string tmp; switch (svs[i].type) { case 0: //duplication svs[i].seq = genome[svs[i].pos.chr].substr(svs[i].pos.start, (svs[i].pos.stop - svs[i].pos.start)); in.seq = svs[i].seq; in.target = svs[i].pos; //check store_ins(ins, in); break; case 1: //insertion: svs[i].seq = rand_seq(svs[i].target.stop - svs[i].target.start); in.seq = svs[i].seq; in.target = svs[i].target; store_ins(ins, in); break; case 2: //inversion tmp = genome[svs[i].pos.chr].substr(svs[i].pos.start, (svs[i].pos.stop - svs[i].pos.start)); //std::cout<<"INV: "<<tmp.size()<<std::endl; invert(tmp); genome[svs[i].pos.chr].erase(svs[i].pos.start, tmp.size()); genome[svs[i].pos.chr].insert(svs[i].pos.start, tmp); break; case 3: //translocations seq1 = genome[svs[i].pos.chr].substr(svs[i].pos.start, (svs[i].pos.stop - svs[i].pos.start)); seq2 = genome[svs[i].target.chr].substr(svs[i].target.start, (svs[i].target.stop - svs[i].target.start)); // std::cout<<"TRA: "<<seq1.size()<<" "<<seq2.size()<<std::endl; pos = 0; for (int j = svs[i].target.start; j < svs[i].target.stop; j++) { genome[svs[i].target.chr][j] = seq1[pos]; pos++; } pos = 0; for (int j = svs[i].pos.start; j < svs[i].pos.stop; j++) { genome[svs[i].pos.chr][j] = seq2[pos]; pos++; } break; case 4: //deletion: //just mark those regions //std::cout<<"DEL: "<<svs[i].pos.chr<<" "<<svs[i].pos.start <<" "<<svs[i].pos.stop<<" g: "<< genome[svs[i].pos.chr].size()<<std::endl; // std::cout << "size: " << genome[svs[i].pos.chr].size() << " " << svs[i].pos.start << " " << (svs[i].pos.stop - svs[i].pos.start) << std::endl; for (size_t j = svs[i].pos.start; j < svs[i].pos.stop; j++) { genome[svs[i].pos.chr][j] = 'X'; } break; case 5: //invduplication first a duplication and then an inversion svs[i].seq = genome[svs[i].pos.chr].substr(svs[i].pos.start, (svs[i].pos.stop - svs[i].pos.start)); in.seq = svs[i].seq; invert(in.seq); in.target = svs[i].pos; //check store_ins(ins, in); svs[i].type=0;//dup new_svs.push_back(svs[i]); svs[i].type=2;//inv break; case 6: //inter tra: svs[i].seq = genome[svs[i].pos.chr].substr(svs[i].pos.start, (svs[i].pos.stop - svs[i].pos.start)); // = genome[svs[i].target.chr].substr(svs[i].target.start, (svs[i].target.stop - svs[i].target.start)); // std::cout<<"TRA: "<<seq1.size()<<" "<<seq2.size()<<std::endl; in.seq = svs[i].seq; in.target = svs[i].target; store_ins(ins, in); pos = 0; for (int j = svs[i].pos.start; j < svs[i].pos.stop; j++) { genome[svs[i].pos.chr][j] = 'X'; pos++; } break; default: break; } } for (std::vector<insertions>::reverse_iterator i = ins.rbegin(); i != ins.rend(); i++) { genome[(*i).target.chr].insert((*i).target.start, (*i).seq); } for(size_t i =0;i<new_svs.size();i++){ svs.push_back(new_svs[i]); } } void apply_mutations_ref(std::map<std::string, std::string> &genome, std::vector<struct_var> &svs) { std::cout << "apply mut ref!" << std::endl; srand(time(NULL)); std::vector<insertions> ins; insertions in; std::string seq1; std::string seq2; int pos; //all mutations that do not change the coordinates are later applied. //all others are directly applied (e.g. INV, TRA) //for (size_t i = 0; i < svs.size(); i++) { std::vector<struct_var> tmp_svs; for (size_t i = 0; i < svs.size(); i++) { store_sorted(tmp_svs, svs[i]); } svs = tmp_svs; //iterator for (std::vector<struct_var>::reverse_iterator i = svs.rbegin(); i != svs.rend(); i++) { if ((*i).type == 4) { //insertions: (simulated deletions) move always further away..??? (*i).type = 1; } else if ((*i).type == 1) { (*i).type = 4; } } for (std::vector<struct_var>::iterator i = svs.begin(); i != svs.end(); i++) { std::cout << (*i).pos.start << " " << (*i).type << std::endl; std::string tmp; switch ((*i).type) { case 1: genome[(*i).pos.chr].erase((*i).pos.start, (*i).pos.stop - (*i).pos.start); break; case 2: //inversion tmp = genome[(*i).pos.chr].substr((*i).pos.start, ((*i).pos.stop - (*i).pos.start)); //std::cout<<"INV: "<<tmp.size()<<std::endl; invert(tmp); genome[(*i).pos.chr].erase((*i).pos.start, tmp.size()); genome[(*i).pos.chr].insert((*i).pos.start, tmp); break; case 3: //translocations seq1 = genome[(*i).pos.chr].substr((*i).pos.start, ((*i).pos.stop - (*i).pos.start)); seq2 = genome[(*i).target.chr].substr((*i).target.start, ((*i).target.stop - (*i).target.start)); // std::cout<<"TRA: "<<seq1.size()<<" "<<seq2.size()<<std::endl; pos = 0; for (int j = (*i).target.start; j < (*i).target.stop; j++) { genome[(*i).target.chr][j] = seq1[pos]; pos++; } pos = 0; for (int j = (*i).pos.start; j < (*i).pos.stop; j++) { genome[(*i).pos.chr][j] = seq2[pos]; pos++; } break; case 4: //deletions: (simulated insertions) (*i).seq = rand_seq((*i).target.stop - (*i).target.start); in.seq = (*i).seq; in.target = (*i).target; genome[in.target.chr].insert(in.target.start, in.seq); break; default: break; } } } void write_fasta(std::string output_prefix, std::map<std::string, std::string> genome) { std::string out = output_prefix; out += ".fasta"; FILE *file2; file2 = fopen(out.c_str(), "w"); if (file2 == NULL) { std::cout << "Error in printing: The file or path that you set " << output_prefix.c_str() << " is not valid. It can be that there is no disc space available." << std::endl; exit(0); } for (std::map<std::string, std::string>::iterator i = genome.begin(); i != genome.end(); i++) { fprintf(file2, "%c", '>'); fprintf(file2, "%s", (*i).first.c_str()); fprintf(file2, "%c", '\n'); int len = 0; for (size_t j = 1; j < (*i).second.size() + 1; j++) { if (!is_valid((*i).second[j - 1])) { std::cout << "err! " << (*i).second[j - 1] << std::endl; } if ((*i).second[j - 1] != 'X') { fprintf(file2, "%c", (*i).second[j - 1]); len++; } if (len % 100 == 0) { fprintf(file2, "%c", '\n'); } } if (len % 100 != 0) { fprintf(file2, "%c", '\n'); } } //std::cout << std::endl; fclose(file2); } void write_sv(std::string output_prefix, std::vector<struct_var> svs) { std::string out = output_prefix; out += ".bed"; FILE *file2; file2 = fopen(out.c_str(), "w"); if (file2 == NULL) { std::cout << "Error in printing: The file or path that you set " << out.c_str() << " is not valid. It can be that there is no disc space available." << std::endl; exit(0); } out = output_prefix; out += ".insertions.fa"; FILE *file; file = fopen(out.c_str(), "w"); if (file == NULL) { std::cout << "Error in printing: The file or path that you set " << out.c_str() << " is not valid. It can be that there is no disc space available." << std::endl; exit(0); } for (size_t i = 0; i < svs.size(); i++) { if (svs[i].type == 1) { //write inserted sequeces to fasta file! fprintf(file, "%c", '>'); fprintf(file, "%s", svs[i].pos.chr.c_str()); fprintf(file, "%c", '_'); fprintf(file, "%i", svs[i].pos.start); fprintf(file, "%c", '\n'); fprintf(file, "%s", svs[i].seq.c_str()); fprintf(file, "%c", '\n'); } //write pseudo bed: if (svs[i].type == 3 || svs[i].type == 6) { fprintf(file2, "%s", svs[i].pos.chr.c_str()); fprintf(file2, "%c", '\t'); fprintf(file2, "%i", svs[i].pos.start); fprintf(file2, "%c", '\t'); fprintf(file2, "%s", svs[i].target.chr.c_str()); fprintf(file2, "%c", '\t'); fprintf(file2, "%i", svs[i].target.start); fprintf(file2, "%c", '\t'); if (svs[i].type == 3) { fprintf(file2, "%s", "TRA\n"); } else { fprintf(file2, "%s", "INTRATRA\n"); } fprintf(file2, "%s", svs[i].pos.chr.c_str()); fprintf(file2, "%c", '\t'); fprintf(file2, "%i", svs[i].pos.stop); fprintf(file2, "%c", '\t'); fprintf(file2, "%s", svs[i].target.chr.c_str()); fprintf(file2, "%c", '\t'); fprintf(file2, "%i", svs[i].target.stop); fprintf(file2, "%c", '\t'); } else { fprintf(file2, "%s", svs[i].pos.chr.c_str()); fprintf(file2, "%c", '\t'); fprintf(file2, "%i", svs[i].pos.start); fprintf(file2, "%c", '\t'); fprintf(file2, "%s", svs[i].pos.chr.c_str()); fprintf(file2, "%c", '\t'); fprintf(file2, "%i", svs[i].pos.stop); fprintf(file2, "%c", '\t'); } switch (svs[i].type) { case 0: fprintf(file2, "%s", "DUP"); break; case 1: fprintf(file2, "%s", "INS"); break; case 2: fprintf(file2, "%s", "INV"); break; case 3: fprintf(file2, "%s", "TRA"); break; case 4: fprintf(file2, "%s", "DEL"); break; case 5: fprintf(file2, "%s", "INVDUP"); break; case 6: fprintf(file2, "%s", "INTRATRA"); break; default: break; } fprintf(file2, "%c", '\n'); } fclose(file); fclose(file2); } void simulate_SV(std::string ref_file, std::string parameter_file, bool coordinates, std::string output_prefix) { //read in list of SVs over vcf? //apply vcf to genome? srand(time(NULL)); parameter par = parse_param(parameter_file); int min_chr_len = std::max(std::max(par.dup_max, par.indel_max), std::max(par.inv_max, par.translocations_max)); std::map<std::string, std::string> genome = read_fasta(ref_file, min_chr_len); check_genome(genome, "First:"); std::cout << "generate SV" << std::endl; std::vector<struct_var> svs; if (coordinates) { //simulate reads svs = generate_mutations(parameter_file, genome); check_genome(genome, "Sec:"); apply_mutations(genome, svs); //problem: We need two different coordinates. Simulate once for one and then for the other??? } else { svs = generate_mutations_ref(parameter_file, genome); check_genome(genome, "Sec:"); apply_mutations_ref(genome, svs); //problem: We need two different coordinates. Simulate once for one and then for the other??? } check_genome(genome, "Last:"); std::cout << "write genome" << std::endl; write_fasta(output_prefix, genome); std::cout << "write SV" << std::endl; write_sv(output_prefix, svs); } void generate_parameter_file(std::string parameter_file) { FILE *file2; file2 = fopen(parameter_file.c_str(), "w"); if (file2 == NULL) { std::cerr << "Error in printing: The file or path that you set " << parameter_file.c_str() << " is not valid. It can be that there is no disc space available." << std::endl; exit(0); } fprintf(file2, "%s", "PARAMETER FILE: DO JUST MODIFY THE VALUES AND KEEP THE SPACES!\n"); fprintf(file2, "%s", "DUPLICATION_minimum_length: 100\n"); fprintf(file2, "%s", "DUPLICATION_maximum_length: 10000\n"); fprintf(file2, "%s", "DUPLICATION_number: 3\n"); fprintf(file2, "%s", "INDEL_minimum_length: 20\n"); fprintf(file2, "%s", "INDEL_maximum_length: 500\n"); fprintf(file2, "%s", "INDEL_number: 1\n"); fprintf(file2, "%s", "TRANSLOCATION_minimum_length: 1000\n"); fprintf(file2, "%s", "TRANSLOCATION_maximum_length: 3000\n"); fprintf(file2, "%s", "TRANSLOCATION_number: 2\n"); fprintf(file2, "%s", "INVERSION_minimum_length: 600\n"); fprintf(file2, "%s", "INVERSION_maximum_length: 800\n"); fprintf(file2, "%s", "INVERSION_number: 4\n"); fprintf(file2, "%s", "INV_del_minimum_length: 600\n"); fprintf(file2, "%s", "INV_del_maximum_length: 800\n"); fprintf(file2, "%s", "INV_del_number: 2\n"); fprintf(file2, "%s", "INV_dup_minimum_length: 600\n"); fprintf(file2, "%s", "INV_dup_maximum_length: 800\n"); fprintf(file2, "%s", "INV_dup_number: 2\n"); fprintf(file2, "%s", "INTRA_TRANS_minimum_length: 600\n"); fprintf(file2, "%s", "INTRA_TRANS_maximum_length: 800\n"); fprintf(file2, "%s", "INTRA_TRANS_number: 2\n"); fclose(file2); } /*******************************************************************/ void store_ins(std::vector<insertions_diploid> & ins, insertions_diploid tmp) { //change input type std::vector<insertions_diploid>::iterator i = ins.begin(); while (i != ins.end() && tmp.target.start > (*i).target.start) { i++; } ins.insert(i, tmp); } bool is_overlapping_diploid(position curr, std::vector<struct_var_diploid> svs) { //change input type for (size_t i = 0; i < svs.size(); i++) { if (strcmp(svs[i].pos.chr.c_str(), curr.chr.c_str()) == 0) { if (svs[i].pos.stop >= curr.start && svs[i].pos.start <= curr.stop) { return true; } } } return false; } position choose_pos_diploid(std::map<std::string, std::string> genome, int min, int max, std::vector<struct_var_diploid>& svs) { //change input type position pos = get_pos(genome, min, max); int num = 0; while (is_overlapping_diploid(pos, svs) && num < 100) { pos = get_pos(genome, min, max); num++; } if (num == 100) { std::cerr << "Terminate program as it could not find a non overlapping region" << std::endl; exit(0); } return pos; } void apply_SNP(std::map<std::string, std::string>& genomeA,std::map<std::string, std::string> &genomeB, int bases_per_snp, FILE *file2A, FILE *file2B, FILE *file2AB) { //NEW //iterate thru chromosomes and apply SNPs FILE *tmpFile; for (std::map<std::string, std::string>::iterator i = genomeA.begin(); i != genomeA.end(); i++) { std::string &strA = (*i).second; std::string chrname = (*i).first; std::string &strB = genomeB[chrname]; for (size_t j = 1; j < strA.size() + 1; j++) { if ((!is_valid(strA[j - 1])) || (!is_valid(strB[j - 1])) || (strA[j - 1] != strB[j - 1])) { std::cout << "err! " << strA[j - 1] << strB[j - 1] << std::endl; } if (rand() % bases_per_snp == 0) { //introduce mutation here char snp; while ((snp = rand_seq(1)[0]) == strA[j - 1]){ continue; } int choice = rand() % 3; if (choice == 0) { //modify A only strA[j - 1] = snp; tmpFile = file2A; } else if (choice == 1) { //modify B only strB[j - 1] = snp; tmpFile = file2B; } else { //homozygous choice == 2 strA[j - 1] = snp; strB[j - 1] = snp; tmpFile = file2AB; } //std::cout << "snp " << strA[j - 1] << strB[j - 1] << std::endl; fprintf(tmpFile, "%s", chrname.c_str()); fprintf(tmpFile, "%c", '\t'); fprintf(tmpFile, "%zu", j); fprintf(tmpFile, "%c", '\t'); fprintf(tmpFile, "%s", chrname.c_str()); fprintf(tmpFile, "%c", '\t'); fprintf(tmpFile, "%zu", (j+1) ); fprintf(tmpFile, "%c", '\t'); fprintf(tmpFile, "%s", "SNP\n"); } } } } int determine_haplotype(int* num_a, int* num_b, int limit) { //NEW int hap; if (*num_a == limit) { //if only B needs more events hap = 1; *num_b = *num_b + 1; } else if (*num_b == limit) { //if only A needs more events hap = 0; *num_a = *num_a + 1; } else { //event has opportunity to be homozygous if (rand() % 3 == 0) { //both with 1/3 chance hap = 2; *num_a = *num_a + 1; *num_b = *num_b + 1; } else if (rand() % 2 == 0) { //B only with 1/3 chance hap = 1; *num_b = *num_b + 1; } else { //A only with 1/3 chance hap = 0; *num_a = *num_a + 1; } } //std::cout << *num_a << *num_b << std::endl; return hap; } std::vector<struct_var_diploid> generate_mutations_diploid(std::string parameter_file, std::map<std::string, std::string> genome) { //EDITED parameter par = parse_param(parameter_file); std::vector<struct_var_diploid> svs; //variables for throughout function struct_var_diploid mut; int num_a = 0; int num_b = 0; std::cout << "generate_mutations_diploid function" << std::endl; //duplications while (num_a < par.dup_num or num_b < par.dup_num) { mut.type = 0; //get_start location; mut.pos = choose_pos_diploid(genome, par.dup_min, par.dup_max, svs); //std::cout << "chose position duplication" << std::endl; //get_opposit location //determine haplotype mut.haplotype=determine_haplotype(&num_a,&num_b,par.dup_num); //std::cout << "got haplotype duplication" << std::endl; svs.push_back(mut); //std::cout << num_a << num_b << std::endl; } num_a = 0; num_b = 0; //indels while (num_a < par.indel_num or num_b < par.indel_num) { //std::cout << "indel" << std::endl; if (rand() % 100 <= 50) { mut.type = 1; //insertion } else { mut.type = 4; //deletion } mut.pos = choose_pos_diploid(genome, par.indel_min, par.indel_max, svs); mut.target = mut.pos; mut.haplotype=determine_haplotype(&num_a,&num_b,par.indel_num); svs.push_back(mut); } num_a = 0; num_b = 0; //inv while (num_a < par.inv_num or num_b < par.inv_num) { //std::cout << "inv" << std::endl; mut.type = 2; mut.pos = choose_pos_diploid(genome, par.inv_min, par.inv_max, svs); mut.target = mut.pos; mut.target.start = mut.pos.stop; mut.target.stop = mut.pos.start; mut.haplotype=determine_haplotype(&num_a,&num_b,par.inv_num); svs.push_back(mut); } num_a = 0; num_b = 0; //tra inter //std::cout << par.intrachr_num << std::endl; while (num_a < par.intrachr_num or num_b < par.intrachr_num) { mut.type = 6; mut.pos = choose_pos_diploid(genome, par.translocations_min, par.translocations_max, svs); //std::cout<<num_a<<": "<<mut.pos.chr<<" "<<mut.pos.start<<" size: "<<mut.pos.stop-mut.pos.start<<std::endl; mut.target = choose_pos_diploid(genome, mut.pos.stop - mut.pos.start, (mut.pos.stop - mut.pos.start) + 1, svs); //TRA has to be of the same size! while (strcmp(mut.target.chr.c_str(), mut.pos.chr.c_str()) != 0) { mut.target = choose_pos_diploid(genome, mut.pos.stop - mut.pos.start, (mut.pos.stop - mut.pos.start) + 1, svs); } //I need to be sure about the same lenght of the tra!: int size1 = mut.pos.stop - mut.pos.start; int size2 = mut.target.stop - mut.target.start; mut.pos.stop = mut.pos.start + std::min(size1, size2); mut.target.stop = mut.target.start + std::min(size1, size2); mut.haplotype=determine_haplotype(&num_a,&num_b,par.intrachr_num); svs.push_back(mut); } num_a = 0; num_b = 0; //tra while (num_a < par.translocations_num or num_b < par.translocations_num) { //std::cout << "tra" << std::endl; mut.type = 3; mut.pos = choose_pos_diploid(genome, par.translocations_min, par.translocations_max, svs); //std::cout<<"size: "<<mut.pos.stop-mut.pos.start<<std::endl; mut.target = choose_pos_diploid(genome, mut.pos.stop - mut.pos.start, (mut.pos.stop - mut.pos.start) + 1, svs); //TRA has to be of the same size! while (strcmp(mut.target.chr.c_str(), mut.pos.chr.c_str()) == 0) { mut.target = choose_pos_diploid(genome, mut.pos.stop - mut.pos.start, (mut.pos.stop - mut.pos.start) + 1, svs); } //I need to be sure about the same lenght of the tra!: int size1 = mut.pos.stop - mut.pos.start; int size2 = mut.target.stop - mut.target.start; mut.pos.stop = mut.pos.start + std::min(size1, size2); mut.target.stop = mut.target.start + std::min(size1, size2); mut.haplotype=determine_haplotype(&num_a,&num_b,par.translocations_num); svs.push_back(mut); } num_a = 0; num_b = 0; //complex inv_del while (num_a < par.inv_del_num or num_b < par.inv_del_num) { //1. sim: mut.type = 2; mut.pos = choose_pos_diploid(genome, par.inv_del_min, par.inv_del_max, svs); //2. determin size of del: int len = (mut.pos.stop - mut.pos.start) / 10; //dels are ~20% ofthe size! mut.pos.start += len; mut.pos.stop -= len; mut.target = mut.pos; mut.target.start = mut.pos.stop; mut.target.stop = mut.pos.start; mut.haplotype=determine_haplotype(&num_a,&num_b,par.inv_del_num); svs.push_back(mut); struct_var_diploid del; del.haplotype = mut.haplotype; //the del infront: del.type = 4; del.pos.chr = mut.pos.chr; del.pos.stop = mut.pos.start; del.pos.start = del.pos.stop - len; del.target = del.pos; svs.push_back(del); //the del behind: del.pos.start = mut.pos.stop; del.pos.stop = del.pos.start + len; del.target = del.pos; svs.push_back(del); } num_a = 0; num_b = 0; //inv dup for (int i = 0; i < par.inv_dup_num; i++) { mut.type = 5; //get_start location; mut.pos = choose_pos_diploid(genome, par.inv_dup_min, par.inv_dup_max, svs); //get_opposit location mut.haplotype=determine_haplotype(&num_a,&num_b,par.inv_dup_num); svs.push_back(mut); } // sort_svs(svs); return svs; } void write_fasta_diploid(std::string output_prefix, std::map<std::string, std::string> genomeA,std::map<std::string, std::string> genomeB) { //EDITED std::string outA = output_prefix; std::string outB = output_prefix; outA += "A.fasta"; outB += "B.fasta"; FILE *file2A; FILE *file2B; file2A = fopen(outA.c_str(), "w"); file2B = fopen(outB.c_str(), "w"); if (file2A == NULL || file2B == NULL) { std::cout << "Error in printing: The file or path that you set " << output_prefix.c_str() << " is not valid. It can be that there is no disc space available." << std::endl; exit(0); } for (std::map<std::string, std::string>::iterator i = genomeA.begin(); i != genomeA.end(); i++) { fprintf(file2A, "%c", '>'); fprintf(file2A, "%s", (*i).first.c_str()); fprintf(file2A, "%c", '\n'); fprintf(file2B, "%c", '>'); fprintf(file2B, "%s", (*i).first.c_str()); fprintf(file2B, "%c", '\n'); std::string strA = (*i).second; std::string strB = genomeB[(*i).first]; int len = 0; for (size_t j = 1; j < strA.size() + 1; j++) { if (!is_valid(strA[j - 1])) { std::cout << "err! " << strA[j - 1] << std::endl; } if (strA[j - 1] != 'X') { fprintf(file2A, "%c", strA[j - 1]); len++; } if (len % 100 == 0) { fprintf(file2A, "%c", '\n'); } } if (len % 100 != 0) { fprintf(file2A, "%c", '\n'); } len = 0; for (size_t j = 1; j < strB.size() + 1; j++) { if (!is_valid(strB[j - 1])) { std::cout << "err! " << strB[j - 1] << std::endl; } if (strB[j - 1] != 'X') { fprintf(file2B, "%c", strB[j - 1]); len++; } if (len % 100 == 0) { fprintf(file2B, "%c", '\n'); } } if (len % 100 != 0) { fprintf(file2B, "%c", '\n'); } } //std::cout << std::endl; fclose(file2A); fclose(file2B); } void apply_mutations_diploid(std::map<std::string, std::string>& genomeA, std::map<std::string, std::string>& genomeB, std::vector<struct_var_diploid>& svs) { //EDITED srand(time(NULL)); std::vector<insertions_diploid> ins; insertions_diploid in; std::string seq1; std::string seq2; int pos; std::vector<struct_var_diploid> new_svs; //Thanks to the invdup we need this. //all mutations that do not change the coordinates are later applied. //all others are directly applied (e.g. INV, TRA) for (size_t i = 0; i < svs.size(); i++) { std::string tmp; switch (svs[i].type) { case 0: //duplication //separate homozygous for each genome b/c of SNPs if (svs[i].haplotype == 0 or svs[i].haplotype == 2) { //implement on A svs[i].seq = genomeA[svs[i].pos.chr].substr(svs[i].pos.start, (svs[i].pos.stop - svs[i].pos.start)); in.haplotype = 0; in.seq = svs[i].seq; in.target = svs[i].pos; //check store_ins(ins, in); } if (svs[i].haplotype == 1 or svs[i].haplotype == 2) { //implement on B svs[i].seq = genomeB[svs[i].pos.chr].substr(svs[i].pos.start, (svs[i].pos.stop - svs[i].pos.start)); in.haplotype = 1; in.seq = svs[i].seq; in.target = svs[i].pos; //check store_ins(ins, in); } break; case 1: //insertion: svs[i].seq = rand_seq(svs[i].target.stop - svs[i].target.start); in.haplotype = svs[i].haplotype; in.seq = svs[i].seq; in.target = svs[i].target; store_ins(ins, in); break; case 2: //inversion //std::cout<<"INV: "<<tmp.size()<<std::endl; //separate homozygous for each genome b/c of SNPs if (svs[i].haplotype == 0 or svs[i].haplotype == 2) { //implement on A tmp = genomeA[svs[i].pos.chr].substr(svs[i].pos.start, (svs[i].pos.stop - svs[i].pos.start)); invert(tmp); genomeA[svs[i].pos.chr].erase(svs[i].pos.start, tmp.size()); genomeA[svs[i].pos.chr].insert(svs[i].pos.start, tmp); } if (svs[i].haplotype == 1 or svs[i].haplotype == 2) { //implement on B tmp = genomeB[svs[i].pos.chr].substr(svs[i].pos.start, (svs[i].pos.stop - svs[i].pos.start)); invert(tmp); genomeB[svs[i].pos.chr].erase(svs[i].pos.start, tmp.size()); genomeB[svs[i].pos.chr].insert(svs[i].pos.start, tmp); } break; case 3: //translocations // std::cout<<"TRA: "<<seq1.size()<<" "<<seq2.size()<<std::endl; //separate homozygous for each genome b/c of SNPs if (svs[i].haplotype == 0 or svs[i].haplotype == 2) { //implement on A seq1 = genomeA[svs[i].pos.chr].substr(svs[i].pos.start, (svs[i].pos.stop - svs[i].pos.start)); seq2 = genomeA[svs[i].target.chr].substr(svs[i].target.start, (svs[i].target.stop - svs[i].target.start)); pos = 0; for (int j = svs[i].target.start; j < svs[i].target.stop; j++) { genomeA[svs[i].target.chr][j] = seq1[pos]; pos++; } pos = 0; for (int j = svs[i].pos.start; j < svs[i].pos.stop; j++) { genomeA[svs[i].pos.chr][j] = seq2[pos]; pos++; } } if (svs[i].haplotype == 1 or svs[i].haplotype == 2) { //implement on B seq1 = genomeA[svs[i].pos.chr].substr(svs[i].pos.start, (svs[i].pos.stop - svs[i].pos.start)); seq2 = genomeA[svs[i].target.chr].substr(svs[i].target.start, (svs[i].target.stop - svs[i].target.start)); pos = 0; for (int j = svs[i].target.start; j < svs[i].target.stop; j++) { genomeB[svs[i].target.chr][j] = seq1[pos]; pos++; } pos = 0; for (int j = svs[i].pos.start; j < svs[i].pos.stop; j++) { genomeB[svs[i].pos.chr][j] = seq2[pos]; pos++; } } break; case 4: //deletion: //just mark those regions //std::cout<<"DEL: "<<svs[i].pos.chr<<" "<<svs[i].pos.start <<" "<<svs[i].pos.stop<<" g: "<< genome[svs[i].pos.chr].size()<<std::endl; // std::cout << "size: " << genome[svs[i].pos.chr].size() << " " << svs[i].pos.start << " " << (svs[i].pos.stop - svs[i].pos.start) << std::endl; if (svs[i].haplotype == 0 or svs[i].haplotype == 2) { //implement on A for (size_t j = svs[i].pos.start; j < svs[i].pos.stop; j++) { genomeA[svs[i].pos.chr][j] = 'X'; } } if (svs[i].haplotype == 1 or svs[i].haplotype == 2) { //implement on B for (size_t j = svs[i].pos.start; j < svs[i].pos.stop; j++) { genomeB[svs[i].pos.chr][j] = 'X'; } } break; case 5: //invduplication first a duplication and then an inversion //separate homozygous for each genome b/c of SNPs if (svs[i].haplotype == 0 or svs[i].haplotype == 2) { //implement on A svs[i].seq = genomeA[svs[i].pos.chr].substr(svs[i].pos.start, (svs[i].pos.stop - svs[i].pos.start)); in.haplotype = 0; in.seq = svs[i].seq; invert(in.seq); in.target = svs[i].pos; //check store_ins(ins, in); } if (svs[i].haplotype == 1 or svs[i].haplotype == 2) { //implement on B svs[i].seq = genomeB[svs[i].pos.chr].substr(svs[i].pos.start, (svs[i].pos.stop - svs[i].pos.start)); in.haplotype = 1; in.seq = svs[i].seq; invert(in.seq); in.target = svs[i].pos; //check store_ins(ins, in); } //haplotype for svs[i] is set appropriately svs[i].type=0;//dup new_svs.push_back(svs[i]); svs[i].type=2;//inv break; case 6: //inter tra: // std::cout<<"TRA: "<<seq1.size()<<" "<<seq2.size()<<std::endl; //separate homozygous insertions for each genome b/c of SNPs if (svs[i].haplotype == 0 or svs[i].haplotype == 2) { //implement on A svs[i].seq = genomeA[svs[i].pos.chr].substr(svs[i].pos.start, (svs[i].pos.stop - svs[i].pos.start)); in.haplotype = 0; in.seq = svs[i].seq; in.target = svs[i].target; store_ins(ins, in); pos = 0; for (int j = svs[i].pos.start; j < svs[i].pos.stop; j++) { genomeA[svs[i].pos.chr][j] = 'X'; pos++; } } if (svs[i].haplotype == 1 or svs[i].haplotype == 2) { //implement on B svs[i].seq = genomeB[svs[i].pos.chr].substr(svs[i].pos.start, (svs[i].pos.stop - svs[i].pos.start)); in.haplotype = 1; in.seq = svs[i].seq; in.target = svs[i].target; store_ins(ins, in); pos = 0; for (int j = svs[i].pos.start; j < svs[i].pos.stop; j++) { genomeB[svs[i].pos.chr][j] = 'X'; pos++; } } break; default: break; } } for (std::vector<insertions_diploid>::reverse_iterator i = ins.rbegin(); i != ins.rend(); i++) { if ((*i).haplotype == 0 or (*i).haplotype == 2) { //implement on A genomeA[(*i).target.chr].insert((*i).target.start, (*i).seq); } if ((*i).haplotype == 1 or (*i).haplotype == 2) { //implement on B genomeB[(*i).target.chr].insert((*i).target.start, (*i).seq); } } for(size_t i =0;i<new_svs.size();i++){ svs.push_back(new_svs[i]); //have correct haplotypes already } } void write_sv_diploid(std::string output_prefix, std::vector<struct_var_diploid> svs, FILE *file2A, FILE *file2B, FILE *file2AB) { //EDITED std::string outA = output_prefix; std::string outB = output_prefix; std::string outAB = output_prefix; outA += ".hetA.insertions.fa"; outB += ".hetB.insertions.fa"; outAB += ".homAB.insertions.fa"; FILE *fileA; FILE *fileB; FILE *fileAB; fileA = fopen(outA.c_str(), "w"); fileB = fopen(outB.c_str(), "w"); fileAB = fopen(outAB.c_str(), "w"); if (fileA == NULL || fileB == NULL || fileAB == NULL) { std::cout << "Error in printing: The file or path that you set " << outA.c_str() << " is not valid. It can be that there is no disc space available." << std::endl; exit(0); } FILE *tmpFile; for (size_t i = 0; i < svs.size(); i++) { if (svs[i].haplotype == 0) { //appropriate insertion file tmpFile = fileA; } else if (svs[i].haplotype == 1) { tmpFile = fileB; } else { tmpFile = fileAB; } if (svs[i].type == 1) { //write inserted sequeces to fasta file! fprintf(tmpFile, "%c", '>'); fprintf(tmpFile, "%s", svs[i].pos.chr.c_str()); fprintf(tmpFile, "%c", '_'); fprintf(tmpFile, "%i", svs[i].pos.start); fprintf(tmpFile, "%c", '\n'); fprintf(tmpFile, "%s", svs[i].seq.c_str()); fprintf(tmpFile, "%c", '\n'); } if (svs[i].haplotype == 0) { //appropriate bed file tmpFile = file2A; } else if (svs[i].haplotype == 1) { tmpFile = file2B; } else { tmpFile = file2AB; } //write pseudo bed: if (svs[i].type == 3 || svs[i].type == 6) { fprintf(tmpFile, "%s", svs[i].pos.chr.c_str()); fprintf(tmpFile, "%c", '\t'); fprintf(tmpFile, "%i", svs[i].pos.start); fprintf(tmpFile, "%c", '\t'); fprintf(tmpFile, "%s", svs[i].target.chr.c_str()); fprintf(tmpFile, "%c", '\t'); fprintf(tmpFile, "%i", svs[i].target.start); fprintf(tmpFile, "%c", '\t'); if (svs[i].type == 3) { fprintf(tmpFile, "%s", "TRA\n"); } else { fprintf(tmpFile, "%s", "INTRATRA\n"); } fprintf(tmpFile, "%s", svs[i].pos.chr.c_str()); fprintf(tmpFile, "%c", '\t'); fprintf(tmpFile, "%i", svs[i].pos.stop); fprintf(tmpFile, "%c", '\t'); fprintf(tmpFile, "%s", svs[i].target.chr.c_str()); fprintf(tmpFile, "%c", '\t'); fprintf(tmpFile, "%i", svs[i].target.stop); fprintf(tmpFile, "%c", '\t'); } else { fprintf(tmpFile, "%s", svs[i].pos.chr.c_str()); fprintf(tmpFile, "%c", '\t'); fprintf(tmpFile, "%i", svs[i].pos.start); fprintf(tmpFile, "%c", '\t'); fprintf(tmpFile, "%s", svs[i].pos.chr.c_str()); fprintf(tmpFile, "%c", '\t'); fprintf(tmpFile, "%i", svs[i].pos.stop); fprintf(tmpFile, "%c", '\t'); } switch (svs[i].type) { case 0: fprintf(tmpFile, "%s", "DUP"); break; case 1: fprintf(tmpFile, "%s", "INS"); break; case 2: fprintf(tmpFile, "%s", "INV"); break; case 3: fprintf(tmpFile, "%s", "TRA"); break; case 4: fprintf(tmpFile, "%s", "DEL"); break; case 5: fprintf(tmpFile, "%s", "INVDUP"); break; case 6: fprintf(tmpFile, "%s", "INTRATRA"); break; default: break; } fprintf(tmpFile, "%c", '\n'); } fclose(fileA); fclose(file2A); fclose(fileB); fclose(file2B); fclose(fileAB); fclose(file2AB); } void simulate_SV_diploid(std::string ref_file, std::string parameter_file, bool coordinates, std::string output_prefix, int bases_per_snp) { //EDITED //read in list of SVs over vcf? //apply vcf to genome? srand(time(NULL)); parameter par = parse_param(parameter_file); int min_chr_len = std::max(std::max(par.dup_max, par.indel_max), std::max(par.inv_max, par.translocations_max)); //Create two copies of the reference, A and B std::map<std::string, std::string> genomeA = read_fasta(ref_file, min_chr_len); std::map<std::string, std::string> genomeB = read_fasta(ref_file, min_chr_len); //create bed files std::string outA = output_prefix; std::string outB = output_prefix; std::string outAB = output_prefix; outA += ".hetA.bed"; outB += ".hetB.bed"; outAB += ".homAB.bed"; FILE *file2A; FILE *file2B; FILE *file2AB; file2A = fopen(outA.c_str(), "w"); file2B = fopen(outB.c_str(), "w"); file2AB = fopen(outAB.c_str(), "w"); if (file2A == NULL || file2B == NULL || file2AB == NULL) { std::cout << "Error in printing: The file or path that you set " << outA.c_str() << " is not valid. It can be that there is no disc space available." << std::endl; exit(0); } apply_SNP(genomeA,genomeB,bases_per_snp,file2A,file2B,file2AB); check_genome(genomeA, "First:"); check_genome(genomeB, "First:"); std::cout << "generate SV" << std::endl; std::vector<struct_var_diploid> svs; //struct_var_diploid has flags for whether it's in copy A and in copy B if (coordinates || !coordinates) { //simulate reads svs = generate_mutations_diploid(parameter_file, genomeA); //which genome doesn't matter, just chooses coordinates check_genome(genomeA, "Sec:"); check_genome(genomeB, "Sec:"); apply_mutations_diploid(genomeA, genomeB, svs); } //else { //ignore this case //svs = generate_mutations_ref(parameter_file, genome); //check_genome(genome, "Sec:"); //apply_mutations_ref(genome, svs); //problem: We need two different coordinates. Simulate once for one and then for the other??? //} check_genome(genomeA, "Last, A:"); check_genome(genomeB, "Last, B:"); std::cout << "write genome" << std::endl; write_fasta_diploid(output_prefix, genomeA,genomeB); std::cout << "write SV" << std::endl; write_sv_diploid(output_prefix, svs,file2A,file2B,file2AB); }
34.524209
177
0.568383
[ "vector" ]
e047a5828a266070ad7fb9f7853eb7492046b4f3
1,747
hpp
C++
include/guidance/suppress_mode_handler.hpp
AugustoQueiroz/pedalavel-backend
c7fa405ff6f6823bdc9d4bb857eddc7197be1f4f
[ "BSD-2-Clause" ]
null
null
null
include/guidance/suppress_mode_handler.hpp
AugustoQueiroz/pedalavel-backend
c7fa405ff6f6823bdc9d4bb857eddc7197be1f4f
[ "BSD-2-Clause" ]
null
null
null
include/guidance/suppress_mode_handler.hpp
AugustoQueiroz/pedalavel-backend
c7fa405ff6f6823bdc9d4bb857eddc7197be1f4f
[ "BSD-2-Clause" ]
1
2019-09-23T22:49:07.000Z
2019-09-23T22:49:07.000Z
#ifndef OSRM_GUIDANCE_SUPPRESS_MODE_HANDLER_HPP_ #define OSRM_GUIDANCE_SUPPRESS_MODE_HANDLER_HPP_ #include "guidance/intersection.hpp" #include "guidance/intersection_handler.hpp" #include "util/node_based_graph.hpp" namespace osrm { namespace guidance { // Suppresses instructions for certain modes. // Think: ferry route. This handler suppresses all instructions while on the ferry route. // We don't want to announce "Turn Right", "Turn Left" while on ferries, as one example. class SuppressModeHandler final : public IntersectionHandler { public: SuppressModeHandler(const util::NodeBasedDynamicGraph &node_based_graph, const extractor::EdgeBasedNodeDataContainer &node_data_container, const std::vector<util::Coordinate> &coordinates, const extractor::CompressedEdgeContainer &compressed_geometries, const extractor::RestrictionMap &node_restriction_map, const std::unordered_set<NodeID> &barrier_nodes, const extractor::TurnLanesIndexedArray &turn_lanes_data, const util::NameTable &name_table, const extractor::SuffixTable &street_name_suffix_table); ~SuppressModeHandler() override final = default; bool canProcess(const NodeID nid, const EdgeID via_eid, const Intersection &intersection) const override final; Intersection operator()(const NodeID nid, const EdgeID via_eid, Intersection intersection) const override final; }; } // namespace guidance } // namespace osrm #endif /* OSRM_GUIDANCE_SUPPRESS_MODE_HANDLER_HPP_ */
39.704545
89
0.680023
[ "vector" ]
e04851c556172b193885cb026af1b665a3e4e578
14,685
cpp
C++
wdbecmbd/CrdWdbeVec/QryWdbeVecList.cpp
mpsitech/wdbe-WhizniumDBE
27360ce6569dc55098a248b8a0a4b7e3913a6ce6
[ "MIT" ]
4
2020-10-27T14:33:25.000Z
2021-08-07T20:55:42.000Z
wdbecmbd/CrdWdbeVec/QryWdbeVecList.cpp
mpsitech/wdbe-WhizniumDBE
27360ce6569dc55098a248b8a0a4b7e3913a6ce6
[ "MIT" ]
null
null
null
wdbecmbd/CrdWdbeVec/QryWdbeVecList.cpp
mpsitech/wdbe-WhizniumDBE
27360ce6569dc55098a248b8a0a4b7e3913a6ce6
[ "MIT" ]
null
null
null
/** * \file QryWdbeVecList.cpp * job handler for job QryWdbeVecList (implementation) * \copyright (C) 2016-2020 MPSI Technologies GmbH * \author Alexander Wirthmueller (auto-generation) * \date created: 28 Nov 2020 */ // IP header --- ABOVE #ifdef WDBECMBD #include <Wdbecmbd.h> #else #include <Wdbed.h> #endif #include "QryWdbeVecList.h" #include "QryWdbeVecList_blks.cpp" using namespace std; using namespace Sbecore; using namespace Xmlio; // IP ns.cust --- INSERT /****************************************************************************** class QryWdbeVecList ******************************************************************************/ QryWdbeVecList::QryWdbeVecList( XchgWdbe* xchg , DbsWdbe* dbswdbe , const ubigint jrefSup , const uint ixWdbeVLocale ) : JobWdbe(xchg, VecWdbeVJob::QRYWDBEVECLIST, jrefSup, ixWdbeVLocale) { jref = xchg->addJob(dbswdbe, this, jrefSup); // IP constructor.cust1 --- INSERT xchg->addStmgr(jref, Stub::VecVNonetype::SHORT); ixWdbeVQrystate = VecWdbeVQrystate::OOD; // IP constructor.cust2 --- INSERT rerun(dbswdbe); xchg->addClstn(VecWdbeVCall::CALLWDBEVECMOD, jref, Clstn::VecVJobmask::ALL, 0, false, Arg(), 0, Clstn::VecVJactype::LOCK); xchg->addClstn(VecWdbeVCall::CALLWDBESTUBCHG, jref, Clstn::VecVJobmask::SELF, 0, false, Arg(), 0, Clstn::VecVJactype::LOCK); // IP constructor.cust3 --- INSERT // IP constructor.spec3 --- INSERT }; QryWdbeVecList::~QryWdbeVecList() { // IP destructor.spec --- INSERT // IP destructor.cust --- INSERT xchg->removeJobByJref(jref); }; // IP cust --- INSERT void QryWdbeVecList::refreshJnum() { ubigint preRefSel = xchg->getRefPreset(VecWdbeVPreset::PREWDBEREFSEL, jref); stgiac.jnum = getJnumByRef(preRefSel); if (preRefSel == 0) xchg->removeClstns(VecWdbeVCall::CALLWDBEVECUPD_REFEQ, jref); else xchg->addRefClstn(VecWdbeVCall::CALLWDBEVECUPD_REFEQ, jref, Clstn::VecVJobmask::ALL, 0, true, preRefSel); }; void QryWdbeVecList::rerun( DbsWdbe* dbswdbe , const bool call ) { string sqlstr; vector<ubigint> cnts; uint cnt, cntsum; vector<ubigint> lims; vector<ubigint> ofss; uint preIxPre = xchg->getIxPreset(VecWdbeVPreset::PREWDBEIXPRE, jref); uint preIxOrd = xchg->getIxPreset(VecWdbeVPreset::PREWDBEIXORD, jref); ubigint preRefUnt = xchg->getRefPreset(VecWdbeVPreset::PREWDBEREFUNT, jref); ubigint preRefVer = xchg->getRefPreset(VecWdbeVPreset::PREWDBEREFVER, jref); string preSrf = xchg->getSrefPreset(VecWdbeVPreset::PREWDBEVECLIST_SRF, jref); uint preTyp = xchg->getIxPreset(VecWdbeVPreset::PREWDBEVECLIST_TYP, jref); uint preHkt = xchg->getIxPreset(VecWdbeVPreset::PREWDBEVECLIST_HKT, jref); ubigint preHku = xchg->getRefPreset(VecWdbeVPreset::PREWDBEVECLIST_HKU, jref); dbswdbe->tblwdbeqselect->removeRstByJref(jref); dbswdbe->tblwdbeqveclist->removeRstByJref(jref); cntsum = 0; if (preIxPre == VecWdbeVPreset::PREWDBEREFUNT) { sqlstr = "SELECT COUNT(TblWdbeMVector.ref)"; sqlstr += " FROM TblWdbeMVector"; sqlstr += " WHERE TblWdbeMVector.hkIxVTbl = " + to_string(VecWdbeVMVectorHkTbl::UNT); sqlstr += " AND TblWdbeMVector.hkUref = " + to_string(preRefUnt) + ""; rerun_filtSQL(sqlstr, preSrf, preTyp, preHkt, preHku, false); dbswdbe->loadUintBySQL(sqlstr, cnt); cnts.push_back(cnt); lims.push_back(0); ofss.push_back(0); cntsum += cnt; } else if (preIxPre == VecWdbeVPreset::PREWDBEREFVER) { sqlstr = "SELECT COUNT(TblWdbeMVector.ref)"; sqlstr += " FROM TblWdbeMVector, TblWdbeMUnit"; sqlstr += " WHERE TblWdbeMVector.hkIxVTbl = " + to_string(VecWdbeVMVectorHkTbl::UNT); sqlstr += " AND TblWdbeMVector.hkUref = TblWdbeMUnit.ref"; sqlstr += " AND TblWdbeMUnit.refIxVTbl = " + to_string(VecWdbeVMUnitRefTbl::VER); sqlstr += " AND TblWdbeMUnit.refUref = " + to_string(preRefVer) + ""; rerun_filtSQL(sqlstr, preSrf, preTyp, preHkt, preHku, false); dbswdbe->loadUintBySQL(sqlstr, cnt); cnts.push_back(cnt); lims.push_back(0); ofss.push_back(0); cntsum += cnt; sqlstr = "SELECT COUNT(TblWdbeMVector.ref)"; sqlstr += " FROM TblWdbeMVector, TblWdbeMSystem"; sqlstr += " WHERE TblWdbeMVector.hkIxVTbl = " + to_string(VecWdbeVMVectorHkTbl::SYS); sqlstr += " AND TblWdbeMVector.hkUref = TblWdbeMSystem.ref"; sqlstr += " AND TblWdbeMSystem.refWdbeMVersion = " + to_string(preRefVer) + ""; rerun_filtSQL(sqlstr, preSrf, preTyp, preHkt, preHku, false); dbswdbe->loadUintBySQL(sqlstr, cnt); cnts.push_back(cnt); lims.push_back(0); ofss.push_back(0); cntsum += cnt; } else { sqlstr = "SELECT COUNT(TblWdbeMVector.ref)"; sqlstr += " FROM TblWdbeMVector"; rerun_filtSQL(sqlstr, preSrf, preTyp, preHkt, preHku, true); dbswdbe->loadUintBySQL(sqlstr, cnt); cnts.push_back(cnt); lims.push_back(0); ofss.push_back(0); cntsum += cnt; }; statshr.ntot = 0; statshr.nload = 0; if (stgiac.jnumFirstload > cntsum) { if (cntsum >= stgiac.nload) stgiac.jnumFirstload = cntsum-stgiac.nload+1; else stgiac.jnumFirstload = 1; }; for (unsigned int i = 0; i < cnts.size(); i++) { if (statshr.nload < stgiac.nload) { if ((statshr.ntot+cnts[i]) >= stgiac.jnumFirstload) { if (statshr.ntot >= stgiac.jnumFirstload) { ofss[i] = 0; } else { ofss[i] = stgiac.jnumFirstload-statshr.ntot-1; }; if ((statshr.nload+cnts[i]-ofss[i]) > stgiac.nload) lims[i] = stgiac.nload-statshr.nload; else lims[i] = cnts[i]-ofss[i]; }; }; statshr.ntot += cnts[i]; statshr.nload += lims[i]; }; if (preIxPre == VecWdbeVPreset::PREWDBEREFUNT) { rerun_baseSQL(sqlstr); sqlstr += " FROM TblWdbeMVector"; sqlstr += " WHERE TblWdbeMVector.hkIxVTbl = " + to_string(VecWdbeVMVectorHkTbl::UNT); sqlstr += " AND TblWdbeMVector.hkUref = " + to_string(preRefUnt) + ""; rerun_filtSQL(sqlstr, preSrf, preTyp, preHkt, preHku, false); rerun_orderSQL(sqlstr, preIxOrd); sqlstr += " LIMIT " + to_string(lims[0]) + " OFFSET " + to_string(ofss[0]); dbswdbe->executeQuery(sqlstr); } else if (preIxPre == VecWdbeVPreset::PREWDBEREFVER) { rerun_baseSQL(sqlstr); sqlstr += " FROM TblWdbeMVector, TblWdbeMUnit"; sqlstr += " WHERE TblWdbeMVector.hkIxVTbl = " + to_string(VecWdbeVMVectorHkTbl::UNT); sqlstr += " AND TblWdbeMVector.hkUref = TblWdbeMUnit.ref"; sqlstr += " AND TblWdbeMUnit.refIxVTbl = " + to_string(VecWdbeVMUnitRefTbl::VER); sqlstr += " AND TblWdbeMUnit.refUref = " + to_string(preRefVer) + ""; rerun_filtSQL(sqlstr, preSrf, preTyp, preHkt, preHku, false); rerun_orderSQL(sqlstr, preIxOrd); sqlstr += " LIMIT " + to_string(lims[0]) + " OFFSET " + to_string(ofss[0]); dbswdbe->executeQuery(sqlstr); rerun_baseSQL(sqlstr); sqlstr += " FROM TblWdbeMVector, TblWdbeMSystem"; sqlstr += " WHERE TblWdbeMVector.hkIxVTbl = " + to_string(VecWdbeVMVectorHkTbl::SYS); sqlstr += " AND TblWdbeMVector.hkUref = TblWdbeMSystem.ref"; sqlstr += " AND TblWdbeMSystem.refWdbeMVersion = " + to_string(preRefVer) + ""; rerun_filtSQL(sqlstr, preSrf, preTyp, preHkt, preHku, false); rerun_orderSQL(sqlstr, preIxOrd); sqlstr += " LIMIT " + to_string(lims[1]) + " OFFSET " + to_string(ofss[1]); dbswdbe->executeQuery(sqlstr); } else { rerun_baseSQL(sqlstr); sqlstr += " FROM TblWdbeMVector"; rerun_filtSQL(sqlstr, preSrf, preTyp, preHkt, preHku, true); rerun_orderSQL(sqlstr, preIxOrd); sqlstr += " LIMIT " + to_string(lims[0]) + " OFFSET " + to_string(ofss[0]); dbswdbe->executeQuery(sqlstr); }; sqlstr = "UPDATE TblWdbeQVecList SET jnum = qref WHERE jref = " + to_string(jref); dbswdbe->executeQuery(sqlstr); ixWdbeVQrystate = VecWdbeVQrystate::UTD; statshr.jnumFirstload = stgiac.jnumFirstload; fetch(dbswdbe); if (call) xchg->triggerCall(dbswdbe, VecWdbeVCall::CALLWDBESTATCHG, jref); }; void QryWdbeVecList::rerun_baseSQL( string& sqlstr ) { sqlstr = "INSERT INTO TblWdbeQVecList(jref, jnum, ref, sref, ixVBasetype, hkIxVTbl, hkUref)"; sqlstr += " SELECT " + to_string(jref) + ", 0, TblWdbeMVector.ref, TblWdbeMVector.sref, TblWdbeMVector.ixVBasetype, TblWdbeMVector.hkIxVTbl, TblWdbeMVector.hkUref"; }; void QryWdbeVecList::rerun_filtSQL( string& sqlstr , const string& preSrf , const uint preTyp , const uint preHkt , const ubigint preHku , const bool addwhere ) { bool first = addwhere; if (preSrf.length() > 0) { rerun_filtSQL_append(sqlstr, first); sqlstr += "TblWdbeMVector.sref = '" + preSrf + "'"; }; if (preTyp != 0) { rerun_filtSQL_append(sqlstr, first); sqlstr += "TblWdbeMVector.ixVBasetype = " + to_string(preTyp) + ""; }; if (preHkt != 0) { rerun_filtSQL_append(sqlstr, first); sqlstr += "TblWdbeMVector.hkIxVTbl = " + to_string(preHkt) + ""; }; if (preHku != 0) { rerun_filtSQL_append(sqlstr, first); sqlstr += "TblWdbeMVector.hkUref = " + to_string(preHku) + ""; }; }; void QryWdbeVecList::rerun_filtSQL_append( string& sqlstr , bool& first ) { if (first) { sqlstr += " WHERE "; first = false; } else sqlstr += " AND "; }; void QryWdbeVecList::rerun_orderSQL( string& sqlstr , const uint preIxOrd ) { if (preIxOrd == VecVOrd::HKU) sqlstr += " ORDER BY TblWdbeMVector.hkUref ASC"; else if (preIxOrd == VecVOrd::HKT) sqlstr += " ORDER BY TblWdbeMVector.hkIxVTbl ASC"; else if (preIxOrd == VecVOrd::SRF) sqlstr += " ORDER BY TblWdbeMVector.sref ASC"; else if (preIxOrd == VecVOrd::TYP) sqlstr += " ORDER BY TblWdbeMVector.ixVBasetype ASC"; }; void QryWdbeVecList::fetch( DbsWdbe* dbswdbe ) { string sqlstr; StmgrWdbe* stmgr = NULL; Stcch* stcch = NULL; WdbeQVecList* rec = NULL; dbswdbe->tblwdbeqveclist->loadRstByJref(jref, false, rst); statshr.nload = rst.nodes.size(); stmgr = xchg->getStmgrByJref(jref); if (stmgr) { stmgr->begin(); stcch = stmgr->stcch; stcch->clear(); for (unsigned int i = 0; i < rst.nodes.size(); i++) { rec = rst.nodes[i]; rec->jnum = statshr.jnumFirstload + i; rec->srefIxVBasetype = VecWdbeVMVectorBasetype::getSref(rec->ixVBasetype); rec->titIxVBasetype = VecWdbeVMVectorBasetype::getTitle(rec->ixVBasetype, ixWdbeVLocale); rec->srefHkIxVTbl = VecWdbeVMVectorHkTbl::getSref(rec->hkIxVTbl); rec->titHkIxVTbl = VecWdbeVMVectorHkTbl::getTitle(rec->hkIxVTbl, ixWdbeVLocale); if (rec->hkIxVTbl == VecWdbeVMVectorHkTbl::CTR) { rec->stubHkUref = StubWdbe::getStubCtrStd(dbswdbe, rec->hkUref, ixWdbeVLocale, Stub::VecVNonetype::SHORT, stcch); } else if (rec->hkIxVTbl == VecWdbeVMVectorHkTbl::SYS) { rec->stubHkUref = StubWdbe::getStubSysStd(dbswdbe, rec->hkUref, ixWdbeVLocale, Stub::VecVNonetype::SHORT, stcch); } else if (rec->hkIxVTbl == VecWdbeVMVectorHkTbl::UNT) { rec->stubHkUref = StubWdbe::getStubUntStd(dbswdbe, rec->hkUref, ixWdbeVLocale, Stub::VecVNonetype::SHORT, stcch); } else rec->stubHkUref = "-"; }; stmgr->commit(); stmgr->unlockAccess("QryWdbeVecList", "fetch"); }; refreshJnum(); }; uint QryWdbeVecList::getJnumByRef( const ubigint ref ) { uint retval = 0; WdbeQVecList* rec = NULL; for (unsigned int i = 0; i < rst.nodes.size(); i++) { rec = rst.nodes[i]; if (rec->ref == ref) { retval = rec->jnum; break; }; }; return retval; }; ubigint QryWdbeVecList::getRefByJnum( const uint jnum ) { uint ref = 0; WdbeQVecList* rec = getRecByJnum(jnum); if (rec) ref = rec->ref; return ref; }; WdbeQVecList* QryWdbeVecList::getRecByJnum( const uint jnum ) { WdbeQVecList* rec = NULL; for (unsigned int i = 0; i < rst.nodes.size(); i++) { rec = rst.nodes[i]; if (rec->jnum == jnum) break; }; if (rec) if (rec->jnum != jnum) rec = NULL; return rec; }; void QryWdbeVecList::handleRequest( DbsWdbe* dbswdbe , ReqWdbe* req ) { if (req->ixVBasetype == ReqWdbe::VecVBasetype::CMD) { reqCmd = req; if (req->cmd == "cmdset") { cout << "\trerun" << endl; cout << "\tshow" << endl; } else if (req->cmd == "rerun") { req->retain = handleRerun(dbswdbe); } else if (req->cmd == "show") { req->retain = handleShow(dbswdbe); } else { cout << "\tinvalid command!" << endl; }; if (!req->retain) reqCmd = NULL; }; }; bool QryWdbeVecList::handleRerun( DbsWdbe* dbswdbe ) { bool retval = false; string input; cout << "\tjnumFirstload (" << stgiac.jnumFirstload << "): "; cin >> input; stgiac.jnumFirstload = atol(input.c_str()); cout << "\tnload (" << stgiac.nload << "): "; cin >> input; stgiac.nload = atol(input.c_str()); rerun(dbswdbe); return retval; }; bool QryWdbeVecList::handleShow( DbsWdbe* dbswdbe ) { bool retval = false; WdbeQVecList* rec = NULL; // header row cout << "\tqref"; cout << "\tjref"; cout << "\tjnum"; cout << "\tref"; cout << "\tsref"; cout << "\tixVBasetype"; cout << "\tsrefIxVBasetype"; cout << "\ttitIxVBasetype"; cout << "\thkIxVTbl"; cout << "\tsrefHkIxVTbl"; cout << "\ttitHkIxVTbl"; cout << "\thkUref"; cout << "\tstubHkUref"; cout << endl; // record rows for (unsigned int i = 0; i < rst.nodes.size(); i++) { rec = rst.nodes[i]; cout << "\t" << rec->qref; cout << "\t" << rec->jref; cout << "\t" << rec->jnum; cout << "\t" << rec->ref; cout << "\t" << rec->sref; cout << "\t" << rec->ixVBasetype; cout << "\t" << rec->srefIxVBasetype; cout << "\t" << rec->titIxVBasetype; cout << "\t" << rec->hkIxVTbl; cout << "\t" << rec->srefHkIxVTbl; cout << "\t" << rec->titHkIxVTbl; cout << "\t" << rec->hkUref; cout << "\t" << rec->stubHkUref; cout << endl; }; return retval; }; void QryWdbeVecList::handleCall( DbsWdbe* dbswdbe , Call* call ) { if (call->ixVCall == VecWdbeVCall::CALLWDBEVECUPD_REFEQ) { call->abort = handleCallWdbeVecUpd_refEq(dbswdbe, call->jref); } else if (call->ixVCall == VecWdbeVCall::CALLWDBEVECMOD) { call->abort = handleCallWdbeVecMod(dbswdbe, call->jref); } else if ((call->ixVCall == VecWdbeVCall::CALLWDBESTUBCHG) && (call->jref == jref)) { call->abort = handleCallWdbeStubChgFromSelf(dbswdbe); }; }; bool QryWdbeVecList::handleCallWdbeVecUpd_refEq( DbsWdbe* dbswdbe , const ubigint jrefTrig ) { bool retval = false; if (ixWdbeVQrystate != VecWdbeVQrystate::OOD) { ixWdbeVQrystate = VecWdbeVQrystate::OOD; xchg->triggerCall(dbswdbe, VecWdbeVCall::CALLWDBESTATCHG, jref); }; return retval; }; bool QryWdbeVecList::handleCallWdbeVecMod( DbsWdbe* dbswdbe , const ubigint jrefTrig ) { bool retval = false; if ((ixWdbeVQrystate == VecWdbeVQrystate::UTD) || (ixWdbeVQrystate == VecWdbeVQrystate::SLM)) { ixWdbeVQrystate = VecWdbeVQrystate::MNR; xchg->triggerCall(dbswdbe, VecWdbeVCall::CALLWDBESTATCHG, jref); }; return retval; }; bool QryWdbeVecList::handleCallWdbeStubChgFromSelf( DbsWdbe* dbswdbe ) { bool retval = false; // IP handleCallWdbeStubChgFromSelf --- INSERT return retval; };
29.252988
165
0.675043
[ "vector" ]
e049cf17cf8cf12e0a8c6d937672b7dc78fe1efa
797
cpp
C++
test/unit/math/mix/fun/cumulative_sum_test.cpp
LaudateCorpus1/math
990a66b3cccd27a5fd48626360bb91093a48278b
[ "BSD-3-Clause" ]
null
null
null
test/unit/math/mix/fun/cumulative_sum_test.cpp
LaudateCorpus1/math
990a66b3cccd27a5fd48626360bb91093a48278b
[ "BSD-3-Clause" ]
null
null
null
test/unit/math/mix/fun/cumulative_sum_test.cpp
LaudateCorpus1/math
990a66b3cccd27a5fd48626360bb91093a48278b
[ "BSD-3-Clause" ]
null
null
null
#include <test/unit/math/test_ad.hpp> #include <vector> void expect_cumulative_sum(std::vector<double>& x) { auto f = [](const auto& y) { return stan::math::cumulative_sum(y); }; Eigen::VectorXd v = Eigen::Map<Eigen::VectorXd>(x.data(), x.size()); Eigen::RowVectorXd rv = Eigen::Map<Eigen::RowVectorXd>(x.data(), x.size()); stan::test::expect_ad(f, x); stan::test::expect_ad(f, v); stan::test::expect_ad_matvar(f, v); stan::test::expect_ad(f, rv); stan::test::expect_ad_matvar(f, rv); } TEST(MathMixMatFun, cumulativeSum) { std::vector<double> a; expect_cumulative_sum(a); std::vector<double> b{1.7}; expect_cumulative_sum(b); std::vector<double> c{5.9, -1.2}; expect_cumulative_sum(c); std::vector<double> d{5.9, -1.2, 192.13456}; expect_cumulative_sum(d); }
28.464286
77
0.671267
[ "vector" ]
e04c36e6520ec2f74c0cef842f6f5b3daa4a8536
3,132
cc
C++
src/tool/pps/pps_driver.cc
SoftReaper/Mesa-Renoir-deb
8d1de1f66058d62b41fe55d36522efea2bdf996d
[ "MIT" ]
null
null
null
src/tool/pps/pps_driver.cc
SoftReaper/Mesa-Renoir-deb
8d1de1f66058d62b41fe55d36522efea2bdf996d
[ "MIT" ]
null
null
null
src/tool/pps/pps_driver.cc
SoftReaper/Mesa-Renoir-deb
8d1de1f66058d62b41fe55d36522efea2bdf996d
[ "MIT" ]
null
null
null
/* * Copyright © 2019-2020 Collabora, Ltd. * Author: Antonio Caggiano <antonio.caggiano@collabora.com> * Author: Rohan Garg <rohan.garg@collabora.com> * Author: Robert Beckett <bob.beckett@collabora.com> * Author: Corentin Noël <corentin.noel@collabora.com> * * SPDX-License-Identifier: MIT */ #include "pps_driver.h" #include <iterator> #include <sstream> #ifdef PPS_FREEDRENO #include "freedreno/ds/fd_pps_driver.h" #endif // PPS_FREEDRENO #ifdef PPS_INTEL #include "intel/ds/intel_pps_driver.h" #endif // PPS_INTEL #ifdef PPS_PANFROST #include "panfrost/ds/pan_pps_driver.h" #endif // PPS_PANFROST #include "pps.h" #include "pps_algorithm.h" namespace pps { std::unordered_map<std::string, std::unique_ptr<Driver>> create_supported_drivers() { std::unordered_map<std::string, std::unique_ptr<Driver>> map; #ifdef PPS_FREEDRENO map.emplace("msm", std::make_unique<FreedrenoDriver>()); #endif // PPS_FREEDRENO #ifdef PPS_INTEL map.emplace("i915", std::make_unique<IntelDriver>()); #endif // PPS_INTEL #ifdef PPS_PANFROST map.emplace("panfrost", std::make_unique<PanfrostDriver>()); #endif // PPS_PANFROST return map; } const std::unordered_map<std::string, std::unique_ptr<Driver>> &Driver::get_supported_drivers() { static auto map = create_supported_drivers(); return map; } const std::vector<std::string> Driver::supported_device_names() { std::vector<std::string> supported_device_names; for (auto &entry : get_supported_drivers()) { supported_device_names.emplace_back(entry.first); } return supported_device_names; } Driver *Driver::get_driver(DrmDevice &&drm_device) { auto &supported_drivers = get_supported_drivers(); auto it = supported_drivers.find(drm_device.name); if (it == std::end(supported_drivers)) { PERFETTO_FATAL("Failed to find a driver for DRM device %s", drm_device.name.c_str()); } Driver *driver = it->second.get(); driver->drm_device = std::move(drm_device); return driver; } std::string Driver::default_driver_name() { auto supported_devices = Driver::supported_device_names(); auto devices = DrmDevice::create_all(); for (auto &device : devices) { if (CONTAINS(supported_devices, device.name)) { PPS_LOG_IMPORTANT("Driver selected: %s", device.name.c_str()); return device.name; } } PPS_LOG_FATAL("Failed to find any driver"); } std::string Driver::find_driver_name(const char *requested) { auto supported_devices = Driver::supported_device_names(); auto devices = DrmDevice::create_all(); for (auto &device : devices) { if (device.name == requested) { PPS_LOG_IMPORTANT("Driver selected: %s", device.name.c_str()); return device.name; } } std::ostringstream drivers_os; std::copy(supported_devices.begin(), supported_devices.end() - 1, std::ostream_iterator<std::string>(drivers_os, ", ")); drivers_os << supported_devices.back(); PPS_LOG_ERROR( "Device '%s' not found (supported drivers: %s)", requested, drivers_os.str().c_str()); return default_driver_name(); } } // namespace pps
26.319328
95
0.704981
[ "vector" ]
e04e3ac4e36762c08a0709078c7b8fba8fc0ddf5
1,425
cpp
C++
C++/Cpp-Templates-Second-Edition/chapters/src/chapter6.cpp
danpeczek/tech-cookbook
c22f499147524dfd58a253bdb9d4ab89e0004475
[ "MIT" ]
1
2020-11-06T18:42:05.000Z
2020-11-06T18:42:05.000Z
C++/Cpp-Templates-Second-Edition/chapters/src/chapter6.cpp
danpeczek/tech-cookbook
c22f499147524dfd58a253bdb9d4ab89e0004475
[ "MIT" ]
45
2020-11-03T10:46:52.000Z
2022-03-14T21:08:21.000Z
C++/Cpp-Templates-Second-Edition/chapters/src/chapter6.cpp
danpeczek/tech-cookbook
c22f499147524dfd58a253bdb9d4ab89e0004475
[ "MIT" ]
null
null
null
#include "chapters/chapter6.hpp" #include <iostream> #include <string> #include <basics/move.hpp> #include <basics/specialMemTempl.hpp> #include <common/common_prints.hpp> namespace chapters { namespace { void perfectForwarding() { common::printTitle("Perfect forwarding"); basics::X v; basics::X const c; basics::f(v); basics::f(c); basics::f(basics::X()); basics::f(std::move(v)); common::emptyLine(); } void specialMemberFunctionTemplates() { common::printTitle("Special Member Function Templates"); std::string s = "s meaning name"; basics::Person p1(s); basics::Person p2("tmp"); basics::Person p3(p1); basics::Person p4(std::move(p1)); common::emptyLine(); basics::Person2 p21(s); basics::Person2 p22("tmp"); const basics::Person2 p23("ctmp"); basics::Person2 p24(p23); /* The following approaches will not work, due to fact that predefined template is better than implemented copy and move constructor. This will not be the case if passed Person object will be const. */ // basics::Person2 p25(p21); // basics::Person2 p26(std::move(21)); common::emptyLine(); basics::Person3 p31(s); basics::Person3 p32("tmp"); basics::Person3 p33(p31); basics::Person3 p34(std::move(p31)); common::emptyLine(); } } // namespace void runChapter6() { common::printTitle("C++ Templates Chapter 6"); perfectForwarding(); specialMemberFunctionTemplates(); } }
23.75
111
0.689825
[ "object" ]
e055b4c6c6109942d29fac3bda63127cba12b59c
2,688
cpp
C++
_source/_engine/_render/scene.cpp
hywei/toy_raytracer
323fdd818f06a88b7823d9174a99912bbc06367d
[ "MIT" ]
null
null
null
_source/_engine/_render/scene.cpp
hywei/toy_raytracer
323fdd818f06a88b7823d9174a99912bbc06367d
[ "MIT" ]
null
null
null
_source/_engine/_render/scene.cpp
hywei/toy_raytracer
323fdd818f06a88b7823d9174a99912bbc06367d
[ "MIT" ]
null
null
null
#include <cassert> #include "_render/scene.h" #include "_render/material.h" #include "_foundation/math/intersect.h" namespace raytracer { Scene::Scene() {} Scene::~Scene() { for (auto geo : geometries_) delete(geo); for (auto shape : shapes_) delete(shape); for (auto material : materials_) delete(material); } void Scene::addSphere(const Vec3& pos, float radius, const Material* material) { SphereGeometry* sphere_geometry = new SphereGeometry(radius); RTShape* shape = new RTShape(sphere_geometry, pos); shape->setMaterial(material); geometries_.emplace_back(sphere_geometry); shapes_.emplace_back(shape); } void Scene::addPlane(const Vec3& norm, float d, const Material* material) { PlaneGeometry* plane_geometry = new PlaneGeometry(norm, d); RTShape* shape = new RTShape(plane_geometry, Vec3(0.f, 0.f, 0.f)); shape->setMaterial(material); geometries_.emplace_back(plane_geometry); shapes_.emplace_back(shape); } void Scene::addBox(const Vec3& pos, const Vec3& half_extents, const Material* material) { BoxGeometry* box_geometry = new BoxGeometry(half_extents); RTShape* shape = new RTShape(box_geometry, pos); shape->setMaterial(material); geometries_.emplace_back(box_geometry); shapes_.emplace_back(shape); } const Material* Scene::addLambertianMaterial(const Vec3& albedo) { LambertianMaterial* material = new LambertianMaterial(albedo); materials_.emplace_back(static_cast<Material*>(material)); return material; } const Material* Scene::addMetalMaterial(const Vec3& albedo) { MetalMaterial* material = new MetalMaterial(albedo); materials_.emplace_back(static_cast<Material*>(material)); return material; } const Material* Scene::addDielectricMaterial(const float ref_idx) { DielectricMaterial* material = new DielectricMaterial(ref_idx); materials_.emplace_back(static_cast<Material*>(material)); return material; } bool Scene::raycast(const Ray& ray, HitInfo& out_hit) const { out_hit.frac = std::numeric_limits<float>::max(); bool has_hit = false; for (auto shape : shapes_) { HitInfo hit; if (intersect::ray_shape(ray, *shape, hit)) { assert(hit.frac > 0.f); if (hit.frac < out_hit.frac) { out_hit = hit; } has_hit = true; } } return has_hit; } }
29.538462
91
0.61942
[ "shape" ]
e05949915518dfc501f8d9f1b24358e040aa9552
3,329
cpp
C++
src/Packet.cpp
qingchen1984/LibNet
8c164fe8009ca40af062f1d3851bae51d0f83ade
[ "MIT" ]
11
2015-05-13T15:21:35.000Z
2022-02-28T09:39:45.000Z
src/Packet.cpp
qingchen1984/LibNet
8c164fe8009ca40af062f1d3851bae51d0f83ade
[ "MIT" ]
1
2015-04-29T15:34:19.000Z
2015-05-05T12:26:36.000Z
src/Packet.cpp
AlexMog/LibNet
8c164fe8009ca40af062f1d3851bae51d0f83ade
[ "MIT" ]
5
2015-05-29T14:33:08.000Z
2018-10-20T14:28:50.000Z
// // Packet.cpp for LibNet in /home/alexmog/projets/LibNet/src // // Made by Moghrabi Alexandre // Login <alexandre.moghrabi@epitech.eu> // // Started on Tue Nov 18 09:52:30 2014 Moghrabi Alexandre // Last update Tue May 5 13:53:13 2015 Moghrabi Alexandre // #include <iostream> #include "mognetwork/Packet.hh" namespace mognetwork { Packet::Packet() : m_readerPos(0), m_dataPack(NULL) { m_data = new std::vector<char>; } Packet::Packet(std::vector<char>* data) : m_readerPos(0), m_dataPack(NULL) { m_data = data; } Packet::Packet(TcpSocket::ReadedDatas* data) : m_readerPos(0) { m_dataPack = data; m_data = &m_dataPack->datas; } Packet::~Packet() { if (m_dataPack != NULL) delete m_dataPack; else if (m_data != NULL) delete m_data; } Packet& Packet::operator>>(uint32_t& data) { if (verifySize(sizeof(data))) { data = ntohl(*reinterpret_cast<const uint32_t*>(&((*m_data)[m_readerPos]))); m_readerPos += sizeof(data); } return (*this); } Packet& Packet::operator>>(uint16_t& data) { if (verifySize(sizeof(data))) { data = ntohs(*reinterpret_cast<const uint16_t*>(&((*m_data)[m_readerPos]))); m_readerPos += sizeof(data); } return *this; } Packet& Packet::operator<<(uint32_t data) { uint32_t write = htonl(data); push(&write, sizeof(write)); return (*this); } Packet& Packet::operator<<(uint16_t data) { uint16_t write = htons(data); push(&write, sizeof(write)); return *this; } Packet& Packet::operator>>(char* data) { int32_t size = 0; *this >> size; if (size > 0 && verifySize(size)) { memcpy(data, &((*m_data)[m_readerPos]), size); data[size] = '\0'; m_readerPos += size; } return (*this); } Packet& Packet::operator>>(std::string& data) { int32_t size = 0; *this >> size; if (size > 0 && verifySize(size)) { char *buffer = new char[size + 1]; memcpy(buffer, &((*m_data)[m_readerPos]), size); buffer[size] = '\0'; m_readerPos += size; data.append(buffer); delete buffer; } return (*this); } Packet& Packet::operator<<(const std::string& data) { int32_t size = data.size(); *this << size; push(data.c_str(), size); return (*this); } Packet& Packet::operator<<(const char* data) { int32_t size = strlen(data) * sizeof(char); *this << size; push(data, size); return (*this); } void Packet::push(const void* data, unsigned int size) { unsigned int actualSize; if (data && size > 0) { actualSize = m_data->size(); m_data->resize(actualSize + size); memcpy(&((*m_data)[actualSize]), data, size); } } void Packet::clear() { if (m_data != NULL) m_data->clear(); m_readerPos = 0; } void Packet::reinitialize(TcpSocket::ReadedDatas* data) { m_readerPos = 0; if (m_dataPack != NULL) delete m_dataPack; else if (m_data != NULL) delete m_data; m_dataPack = data; m_data = &m_dataPack->datas; } void Packet::reinitialize(std::vector<char>* data) { m_readerPos = 0; if (m_dataPack != NULL) delete m_dataPack; else if (m_data != NULL) delete m_data; m_dataPack = NULL; m_data = data; } } // namespace mognetwork
20.549383
77
0.599579
[ "vector" ]
e05e46897d08705f65130266cd433cabaf7d9d88
2,152
cpp
C++
source/houcor/test/hou/cor/test_std_string.cpp
DavideCorradiDev/houzi-game-engine
d704aa9c5b024300578aafe410b7299c4af4fcec
[ "MIT" ]
2
2018-04-12T20:59:20.000Z
2018-07-26T16:04:07.000Z
source/houcor/test/hou/cor/test_std_string.cpp
DavideCorradiDev/houzi-game-engine
d704aa9c5b024300578aafe410b7299c4af4fcec
[ "MIT" ]
null
null
null
source/houcor/test/hou/cor/test_std_string.cpp
DavideCorradiDev/houzi-game-engine
d704aa9c5b024300578aafe410b7299c4af4fcec
[ "MIT" ]
null
null
null
// Houzi Game Engine // Copyright (c) 2018 Davide Corradi // Licensed under the MIT license. #include "hou/test.hpp" #include "hou/cor/std_string.hpp" using namespace hou; using namespace testing; namespace { class test_std_string : public Test {}; } TEST_F(test_std_string, format_string) { std::string str = u8"This is a %s string with number: %d"; std::string formatted_string_ref = u8"This is a nice string with number: 2"; std::string formatted_string = format_string(str, u8"nice", 2); EXPECT_EQ(formatted_string_ref, formatted_string); } TEST_F(test_std_string, replace_all) { std::string s_in = u8"This is a blue blueprint of a blueblue blues"; std::string s_out = replace_all(s_in, "blue", "red"); EXPECT_EQ(u8"This is a red redprint of a redred reds", s_out); } TEST_F(test_std_string, format_regex) { std::string s_in = u8".^$*+?()[{\\|"; std::string s_out = escape_regex(s_in); EXPECT_EQ(u8"\\.\\^\\$\\*\\+\\?\\(\\)\\[\\{\\\\\\|", s_out); } TEST_F(test_std_string, bool_to_string) { EXPECT_EQ("true", to_string(true)); EXPECT_EQ("false", to_string(false)); } TEST_F(test_std_string, split_string) { std::string s = "This ;; is a, string; delimited; by ;semicolons"; std::vector<std::string> items_semicolon; std::vector<std::string> items_semicolon_ref { "This ", "", " is a, string", " delimited", " by ", "semicolons", }; split_string(s, ';', std::back_inserter(items_semicolon)); EXPECT_EQ(items_semicolon_ref, items_semicolon); std::vector<std::string> items_comma; std::vector<std::string> items_comma_ref { "This ;; is a", " string; delimited; by ;semicolons", }; split_string(s, ',', std::back_inserter(items_comma)); EXPECT_EQ(items_comma_ref, items_comma); } TEST_F(test_std_string, split_string_output) { std::string s = "a b c d"; std::vector<std::string> chars(4, std::string()); auto it = split_string(s, ' ', chars.begin()); EXPECT_EQ(chars.end(), it); } TEST_F(test_std_string, to_string) { EXPECT_EQ("46", to_string(46)); EXPECT_EQ("34.56", to_string(34.56f)); EXPECT_EQ("a", to_string('a')); }
20.301887
78
0.666822
[ "vector" ]
e0631942c463e7b042146e102ecfe9b38ec223c5
1,779
cpp
C++
data/transcoder_evaluation_gfg/cpp/MAXIMUM_SUBARRAY_SUM_ARRAY_CREATED_REPEATED_CONCATENATION.cpp
mxl1n/CodeGen
e5101dd5c5e9c3720c70c80f78b18f13e118335a
[ "MIT" ]
241
2021-07-20T08:35:20.000Z
2022-03-31T02:39:08.000Z
data/transcoder_evaluation_gfg/cpp/MAXIMUM_SUBARRAY_SUM_ARRAY_CREATED_REPEATED_CONCATENATION.cpp
mxl1n/CodeGen
e5101dd5c5e9c3720c70c80f78b18f13e118335a
[ "MIT" ]
49
2021-07-22T23:18:42.000Z
2022-03-24T09:15:26.000Z
data/transcoder_evaluation_gfg/cpp/MAXIMUM_SUBARRAY_SUM_ARRAY_CREATED_REPEATED_CONCATENATION.cpp
mxl1n/CodeGen
e5101dd5c5e9c3720c70c80f78b18f13e118335a
[ "MIT" ]
71
2021-07-21T05:17:52.000Z
2022-03-29T23:49:28.000Z
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // #include <iostream> #include <cstdlib> #include <string> #include <vector> #include <fstream> #include <iomanip> #include <bits/stdc++.h> using namespace std; int f_gold ( int a [ ], int n, int k ) { int max_so_far = INT_MIN, max_ending_here = 0; for ( int i = 0; i < n * k; i ++ ) { max_ending_here = max_ending_here + a [ i % n ]; if ( max_so_far < max_ending_here ) max_so_far = max_ending_here; if ( max_ending_here < 0 ) max_ending_here = 0; } return max_so_far; } //TOFILL int main() { int n_success = 0; vector<vector<int>> param0 {{5,6,12,20,23,28,33,37,47,51,53,56,63,65,65,68,69,76,76,78,83},{68,10,52,-44,34,-4,-34,2,50,-60,50,94,-98,-98,-44,-36,-4,-62,-2,-92,-70,-48,-78,-10,94},{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},{71,59,21,82,73,29,30,25,21,10,85,22,60,43,49,20,34,39,69,6,44,27,50,33,57,29,65,18,68,56,50,28},{-84,-74,-74,-56,-54,-48,-48,-46,-42,-34,-32,-30,-18,-16,-16,6,12,20,24,26,30,32,34,42,42,42,44,46,46,50,50,62,72,78,90},{0,1,1,1,1,1,1,1,1,0,1,1,0,0,1,1,0,1,1,1,0,1,1,0,0,0,1,1,1,0},{3,7,11,11,26,60,68,71,77,91,95},{28,48,-86,-52,6,4,30,18,-32,60,-2,16,-88,-36},{1},{76}}; vector<int> param1 {18,22,34,23,17,16,8,8,0,0}; vector<int> param2 {20,22,29,30,23,25,10,11,0,0}; for(int i = 0; i < param0.size(); ++i) { if(f_filled(&param0[i].front(),param1[i],param2[i]) == f_gold(&param0[i].front(),param1[i],param2[i])) { n_success+=1; } } cout << "#Results:" << " " << n_success << ", " << param0.size(); return 0; }
39.533333
634
0.586847
[ "vector" ]
e0641121bed187bc9224ffe5fab0ea04ac7315ae
16,563
cpp
C++
src/Base/pybind11/PyQWidget.cpp
roto5296/choreonoid
ffe12df8db71e32aea18833afb80dffc42c373d0
[ "MIT" ]
66
2020-03-11T14:06:01.000Z
2022-03-23T23:18:27.000Z
src/Base/pybind11/PyQWidget.cpp
roto5296/choreonoid
ffe12df8db71e32aea18833afb80dffc42c373d0
[ "MIT" ]
12
2020-07-23T06:13:11.000Z
2022-01-13T14:25:01.000Z
src/Base/pybind11/PyQWidget.cpp
roto5296/choreonoid
ffe12df8db71e32aea18833afb80dffc42c373d0
[ "MIT" ]
18
2020-07-17T15:57:54.000Z
2022-03-29T13:18:59.000Z
#include "PyQObjectHolder.h" #include "PyQString.h" #include "PyQtSignal.h" #include <QWidget> #include <QLayout> #include <QBackingStore> #include <QGraphicsEffect> #include <QGraphicsProxyWidget> #include <QPainter> #include <QBitmap> #include <QStyle> #include <QAction> #include <QLocale> #include <vector> using namespace std; namespace py = pybind11; namespace cnoid { void exportPyQWidget(py::module m) { py::class_<QWidget, PyQObjectHolder<QWidget>, QObject> qWidget(m, "QWidget"); py::enum_<QWidget::RenderFlag>(qWidget, "RenderFlag") .value("DrawWindowBackground", QWidget::DrawWindowBackground) .value("DrawChildren", QWidget::DrawChildren) .value("IgnoreMask", QWidget::IgnoreMask) .export_values(); py::class_<QFlags<QWidget::RenderFlag>>(qWidget, "RenderFlags") .def(py::init<>()) .def(py::init<QWidget::RenderFlag>()) .def(py::init( [](const std::vector<QWidget::RenderFlag>& flags){ int vflags = 0; for(auto& flag : flags){ vflags |= flag; } return std::unique_ptr<QFlags<QWidget::RenderFlag>>(new QFlags<QWidget::RenderFlag>(vflags)); })) ; py::implicitly_convertible<QWidget::RenderFlag, QFlags<QWidget::RenderFlag>>(); py::implicitly_convertible<QFlags<QWidget::RenderFlag>, QWidget::RenderFlag>(); qWidget .def("acceptDrops", &QWidget::acceptDrops) .def("accessibleDescription", &QWidget::accessibleDescription) .def("accessibleName", &QWidget::accessibleName) .def("actions", [](QWidget& self){ auto srcActions = self.actions(); vector<QAction*> actions; actions.reserve(srcActions.count()); for(auto& action : srcActions){ actions.push_back(action); } return actions; }) .def("activateWindow", &QWidget::activateWindow) .def("addAction", &QWidget::addAction) .def("addActions", [](QWidget& self, const vector<QAction*>& actions){ QList<QAction*> qactions; for(auto& action : actions){ qactions.append(action); } self.addActions(qactions); }) .def("adjustSize", &QWidget::adjustSize) .def("autoFillBackground", &QWidget::autoFillBackground) .def("backgroundRole", &QWidget::backgroundRole) .def("backingStore", &QWidget::backingStore) .def("baseSize", &QWidget::baseSize) .def("childAt", (QWidget*(QWidget::*)(int,int)const) &QWidget::childAt) .def("childAt", (QWidget*(QWidget::*)(const QPoint&)const) &QWidget::childAt) .def("childrenRect", &QWidget::childrenRect) .def("childrenRegion", &QWidget::childrenRegion) .def("clearFocus", &QWidget::clearFocus) .def("clearMask", &QWidget::clearMask) .def("contentsMargins", &QWidget::contentsMargins) .def("contentsRect", &QWidget::contentsRect) .def("contextMenuPolicy", &QWidget::contextMenuPolicy) .def("cursor", &QWidget::cursor) .def("effectiveWinId", &QWidget::effectiveWinId) .def("ensurePolished", &QWidget::ensurePolished) .def("focusPolicy", &QWidget::focusPolicy) .def("focusProxy", &QWidget::focusProxy) .def("focusWidget", &QWidget::focusWidget) .def("font", &QWidget::font) .def("fontInfo", &QWidget::fontInfo) .def("fontMetrics", &QWidget::fontMetrics) .def("foregroundRole", &QWidget::foregroundRole) .def("frameGeometry", &QWidget::frameGeometry) .def("frameSize", &QWidget::frameSize) .def("geometry", &QWidget::geometry) //.def("getContentsMargins" &QWidget::getContentsMargins) .def("grab", &QWidget::grab, py::arg("rectangle") = QRect(QPoint(0, 0), QSize(-1, -1))) .def("grabGesture", &QWidget::grabGesture, py::arg("gesture"), py::arg("flags") = Qt::GestureFlags()) .def("grabKeyboard", &QWidget::grabKeyboard) .def("grabMouse", (void(QWidget::*)()) &QWidget::grabMouse) .def("grabMouse", (void(QWidget::*)(const QCursor&)) &QWidget::grabMouse) .def("grabShortcut", &QWidget::grabShortcut, py::arg("key"), py::arg("context") = Qt::WindowShortcut) .def("graphicsEffect", &QWidget::graphicsEffect) .def("graphicsProxyWidget", &QWidget::graphicsProxyWidget) //.def("hasEditFocus", &QWidget::hasEditFocus) .def("hasFocus", &QWidget::hasFocus) .def("hasHeightForWidth", &QWidget::hasHeightForWidth) .def("hasMouseTracking", &QWidget::hasMouseTracking) //.def("hasTabletTracking", &QWidget::hasTabletTracking) // Not supported by Qt 5.5 .def("height", &QWidget::height) .def("heightForWidth", &QWidget::heightForWidth) .def("inputMethodHints", &QWidget::inputMethodHints) .def("inputMethodQuery", &QWidget::inputMethodQuery) .def("insertAction", &QWidget::insertAction) .def("insertActions", &QWidget::insertActions) .def("isActiveWindow", &QWidget::isActiveWindow) .def("isAncestorOf", &QWidget::isAncestorOf) .def("isEnabled", &QWidget::isEnabled) .def("isEnabledTo", &QWidget::isEnabledTo) .def("isFullScreen", &QWidget::isFullScreen) .def("isHidden", &QWidget::isHidden) .def("isMaximized", &QWidget::isMaximized) .def("isMinimized", &QWidget::isMinimized) .def("isModal", &QWidget::isModal) .def("isVisible", &QWidget::isVisible) .def("isVisibleTo", &QWidget::isVisibleTo) .def("isWindow", &QWidget::isWindow) .def("isWindowModified", &QWidget::isWindowModified) .def("layout", &QWidget::layout) .def("layoutDirection", &QWidget::layoutDirection) .def("locale", &QWidget::locale) .def("mapFrom", &QWidget::mapFrom) .def("mapFromGlobal", &QWidget::mapFromGlobal) .def("mapFromParent", &QWidget::mapFromParent) .def("mapTo", &QWidget::mapTo) .def("mapToGlobal", &QWidget::mapToGlobal) .def("mapToParent", &QWidget::mapToParent) .def("mask", &QWidget::mask) .def("maximumHeight", &QWidget::maximumHeight) .def("maximumSize", &QWidget::maximumSize) .def("maximumWidth", &QWidget::maximumWidth) .def("minimumHeight", &QWidget::minimumHeight) .def("minimumSize", &QWidget::minimumSize) .def("minimumSizeHint", &QWidget::minimumSizeHint) .def("minimumWidth", &QWidget::minimumWidth) .def("move", (void(QWidget::*)(const QPoint&)) &QWidget::move) .def("move", (void(QWidget::*)(int,int)) &QWidget::move) .def("nativeParentWidget", &QWidget::nativeParentWidget) .def("nextInFocusChain", &QWidget::nextInFocusChain) .def("normalGeometry", &QWidget::normalGeometry) .def("overrideWindowFlags", &QWidget::overrideWindowFlags) .def("palette", &QWidget::palette) .def("parentWidget", &QWidget::parentWidget) .def("pos", &QWidget::pos) .def("previousInFocusChain", &QWidget::previousInFocusChain) .def("rect", &QWidget::rect) .def("releaseKeyboard", &QWidget::releaseKeyboard) .def("releaseMouse", &QWidget::releaseMouse) .def("releaseShortcut", &QWidget::releaseShortcut) .def("removeAction", &QWidget::removeAction) .def("render", (void(QWidget::*)(QPaintDevice*, const QPoint&, const QRegion&, QWidget::RenderFlags)) &QWidget::render, py::arg("target"), py::arg("targetOffset") = QPoint(), py::arg("sourceRegion") = QRegion(), py::arg("renderFlags") = QWidget::RenderFlags(QWidget::DrawWindowBackground | QWidget::DrawChildren)) .def("render", (void(QWidget::*)(QPainter*painter, const QPoint&, const QRegion&, QWidget::RenderFlags)) &QWidget::render, py::arg("painter"), py::arg("targetOffset") = QPoint(), py::arg("sourceRegion") = QRegion(), py::arg("renderFlags") = QWidget::RenderFlags(QWidget::DrawWindowBackground | QWidget::DrawChildren)) .def("repaint", (void(QWidget::*)(int,int,int,int)) &QWidget::repaint) .def("repaint", (void(QWidget::*)(const QRect&)) &QWidget::repaint) .def("repaint", (void(QWidget::*)(const QRegion&)) &QWidget::repaint) .def("resize", (void(QWidget::*)(const QSize&)) &QWidget::resize) .def("resize", (void(QWidget::*)(int, int)) &QWidget::resize) .def("restoreGeometry", &QWidget::restoreGeometry) .def("saveGeometry", &QWidget::saveGeometry) .def("scroll", (void(QWidget::*)(int, int)) &QWidget::scroll) .def("scroll", (void(QWidget::*)(int, int, const QRect&)) &QWidget::scroll) .def("setAcceptDrops", &QWidget::setAcceptDrops) .def("setAccessibleDescription", &QWidget::setAccessibleDescription) .def("setAccessibleName", &QWidget::setAccessibleName) .def("setAttribute", &QWidget::setAttribute) .def("setAutoFillBackground", &QWidget::setAutoFillBackground) .def("setBackgroundRole", &QWidget::setBackgroundRole) .def("setBaseSize", (void(QWidget::*)(const QSize&)) &QWidget::setBaseSize) .def("setBaseSize", (void(QWidget::*)(int,int)) &QWidget::setBaseSize) .def("setContentsMargins",(void(QWidget::*)(int, int, int, int)) &QWidget::setContentsMargins) .def("setContentsMargins", (void(QWidget::*)(const QMargins&)) &QWidget::setContentsMargins) .def("setContextMenuPolicy", &QWidget::setContextMenuPolicy) .def("setCursor", &QWidget::setCursor) //.def("setEditFocus", &QWidget::setEditFocus) .def("setFixedHeight", &QWidget::setFixedHeight) .def("setFixedSize", (void(QWidget::*)(const QSize&)) &QWidget::setFixedSize) .def("setFixedSize", (void(QWidget::*)(int, int)) &QWidget::setFixedSize) .def("setFixedWidth", &QWidget::setFixedWidth) .def("setFocus", (void(QWidget::*)(Qt::FocusReason)) &QWidget::setFocus) .def("setFocusPolicy", &QWidget::setFocusPolicy) .def("setFocusProxy", &QWidget::setFocusProxy) .def("setFont", &QWidget::setFont) .def("setForegroundRole", &QWidget::setForegroundRole) .def("setGeometry", (void(QWidget::*)(const QRect&)) &QWidget::setGeometry) .def("setGeometry", (void(QWidget::*)(int, int, int, int)) &QWidget::setGeometry) .def("setGraphicsEffect", &QWidget::setGraphicsEffect) .def("setInputMethodHints", &QWidget::setInputMethodHints) .def("setLayout", &QWidget::setLayout) .def("setLayoutDirection", &QWidget::setLayoutDirection) .def("setLocale", &QWidget::setLocale) .def("setMask", (void(QWidget::*)(const QBitmap&)) &QWidget::setMask) .def("setMask", (void(QWidget::*)(const QRegion&)) &QWidget::setMask) .def("setMaximumHeight", &QWidget::setMaximumHeight) .def("setMaximumSize", (void(QWidget::*)(const QSize&)) &QWidget::setMaximumSize) .def("setMaximumSize", (void(QWidget::*)(int, int)) &QWidget::setMaximumSize) .def("setMaximumWidth", &QWidget::setMaximumWidth) .def("setMinimumHeight", &QWidget::setMinimumHeight) .def("setMinimumSize", (void(QWidget::*)(const QSize&)) &QWidget::setMinimumSize) .def("setMinimumSize", (void(QWidget::*)(int, int)) &QWidget::setMinimumSize) .def("setMinimumWidth", &QWidget::setMinimumWidth) .def("setMouseTracking", &QWidget::setMouseTracking) .def("setPalette", &QWidget::setPalette) .def("setParent", (void (QWidget::*)(QWidget* parent)) &QWidget::setParent) .def("setParent", (void (QWidget::*)(QWidget* parent, Qt::WindowFlags)) &QWidget::setParent) .def("setShortcutAutoRepeat", &QWidget::setShortcutAutoRepeat, py::arg("id"), py::arg("enable") = true) .def("setShortcutEnabled", &QWidget::setShortcutEnabled, py::arg("id"), py::arg("enable") = true) .def("setSizeIncrement", (void(QWidget::*)(const QSize&)) &QWidget::setSizeIncrement) .def("setSizeIncrement", (void(QWidget::*)(int,int)) &QWidget::setSizeIncrement) .def("setSizePolicy", (void(QWidget::*)(QSizePolicy)) &QWidget::setSizePolicy) .def("setSizePolicy", (void(QWidget::*)(QSizePolicy::Policy, QSizePolicy::Policy)) &QWidget::setSizePolicy) .def("setStatusTip", &QWidget::setStatusTip) .def("setStyle", &QWidget::setStyle) //.def("setTabletTracking", &QWidget::setTabletTracking) // Not supported by Qt 5.5 .def("setToolTip", &QWidget::setToolTip) .def("setToolTipDuration", &QWidget::setToolTipDuration) .def("setUpdatesEnabled", &QWidget::setUpdatesEnabled) .def("setWhatsThis", &QWidget::setWhatsThis) .def("setWindowFilePath", &QWidget::setWindowFilePath) //.def("setWindowFlag", &QWidget::setWindowFlag, py::arg("flag"), py::arg("on") = true) // Introduced in Qt 5.9 .def("setWindowFlags", &QWidget::setWindowFlags) .def("setWindowIcon", &QWidget::setWindowIcon) .def("setWindowModality", &QWidget::setWindowModality) .def("setWindowOpacity", &QWidget::setWindowOpacity) .def("setWindowRole", &QWidget::setWindowRole) .def("setWindowState", &QWidget::setWindowState) //.def("setupUi", &QWidget::setupUi) .def("size", &QWidget::size) .def("sizeHint", &QWidget::sizeHint) .def("sizeIncrement", &QWidget::sizeIncrement) .def("sizePolicy", &QWidget::sizePolicy) .def("stackUnder", &QWidget::stackUnder) .def("statusTip", &QWidget::statusTip) .def("style", &QWidget::style) .def("styleSheet", &QWidget::styleSheet) .def("testAttribute", &QWidget::testAttribute) .def("toolTip", &QWidget::toolTip) .def("toolTipDuration", &QWidget::toolTipDuration) .def("underMouse", &QWidget::underMouse) .def("ungrabGesture", &QWidget::ungrabGesture) .def("unsetCursor", &QWidget::unsetCursor) .def("unsetLayoutDirection", &QWidget::unsetLayoutDirection) .def("unsetLocale", &QWidget::unsetLocale) .def("update", (void(QWidget::*)(int, int, int, int)) &QWidget::update) .def("update", (void(QWidget::*)(const QRect&)) &QWidget::update) .def("update", (void(QWidget::*)(const QRegion&)) &QWidget::update) .def("update", (void(QWidget::*)()) &QWidget::update) .def("updateGeometry", &QWidget::updateGeometry) .def("updatesEnabled", &QWidget::updatesEnabled) .def("visibleRegion", &QWidget::visibleRegion) .def("whatsThis", &QWidget::whatsThis) .def("width", &QWidget::width) .def("winId", &QWidget::winId) .def("window", &QWidget::window) .def("windowFilePath", &QWidget::windowFilePath) .def("windowFlags", &QWidget::windowFlags) .def("windowHandle", &QWidget::windowHandle) .def("windowIcon", &QWidget::windowIcon) .def("windowModality", &QWidget::windowModality) .def("windowOpacity", &QWidget::windowOpacity) .def("windowRole", &QWidget::windowRole) .def("windowState", &QWidget::windowState) .def("windowTitle", &QWidget::windowTitle) .def("windowType", &QWidget::windowType) .def("x", &QWidget::x) .def("y", &QWidget::y) // Public slots .def("close", &QWidget::close) .def("hide", &QWidget::hide) .def("lower", &QWidget::lower) .def("raise", &QWidget::raise) .def("repaint", (void (QWidget::*)()) &QWidget::repaint) .def("setDisabled", &QWidget::setDisabled) .def("setEnabled", &QWidget::setEnabled) .def("setFocus", (void (QWidget::*)()) &QWidget::setFocus) .def("setHidden", &QWidget::setHidden) .def("setStyleSheet", &QWidget::setStyleSheet) .def("setVisible", &QWidget::setVisible) .def("setWindowModified", &QWidget::setWindowModified) .def("setWindowTitle", &QWidget::setWindowTitle) .def("show", &QWidget::show) .def("showFullScreen", &QWidget::showFullScreen) .def("showMaximized", &QWidget::showMaximized) .def("showMinimized", &QWidget::showMinimized) .def("showNormal", &QWidget::showNormal) .def("update", (void (QWidget::*)()) &QWidget::update) ; } }
53.775974
130
0.623619
[ "geometry", "render", "vector" ]
e06477ab1a95eb7c8fa75c82757830abc0d3de94
576
cpp
C++
C++/StackV/main.cpp
iamsuryakant/100-days-of-code
eaf4863d98dc273f03a989fe87d010d201d91516
[ "MIT" ]
1
2020-07-04T12:45:50.000Z
2020-07-04T12:45:50.000Z
C++/StackV/main.cpp
iamsuryakant/100-days-of-code
eaf4863d98dc273f03a989fe87d010d201d91516
[ "MIT" ]
1
2020-08-08T02:23:46.000Z
2020-08-08T02:47:56.000Z
C++/StackV/main.cpp
iamsuryakant/100-days-of-code
eaf4863d98dc273f03a989fe87d010d201d91516
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; struct MyStack{ vector<int> v; void push(int x){ v.push_back(x); } int pop(){ int res=v.back(); v.pop_back(); return res; } int peek(){ return v.back(); } int size(){ return v.size(); } bool isEmpty(){ return v.empty(); } }; int main() { MyStack s; s.push(5); s.push(10); s.push(20); cout<<s.pop()<<endl; cout<<s.size()<<endl; cout<<s.peek()<<endl; cout<<s.isEmpty()<<endl; return 0; }
13.395349
28
0.467014
[ "vector" ]
e06aea4af23ca778d27d0a9fd4f25ee4ca332e55
3,933
cpp
C++
mirp_bin/mirp_create_reference.cpp
multiplemonomials/MIRP
ca4d36c0d5fd8ef42cb7bca4f09667f6e11f61c8
[ "BSD-3-Clause" ]
24
2017-07-05T19:40:31.000Z
2021-03-06T23:50:10.000Z
mirp_bin/mirp_create_reference.cpp
multiplemonomials/MIRP
ca4d36c0d5fd8ef42cb7bca4f09667f6e11f61c8
[ "BSD-3-Clause" ]
6
2017-09-22T18:06:47.000Z
2021-11-16T03:39:33.000Z
mirp_bin/mirp_create_reference.cpp
multiplemonomials/MIRP
ca4d36c0d5fd8ef42cb7bca4f09667f6e11f61c8
[ "BSD-3-Clause" ]
1
2021-02-27T02:04:06.000Z
2021-02-27T02:04:06.000Z
/*! \file * * \brief mirp_create_reference main function */ #include "mirp_bin/cmdline.hpp" #include "mirp_bin/test_common.hpp" #include "mirp_bin/ref_integral.hpp" #include <mirp/kernels/all.h> #include <sstream> #include <iostream> #include <stdexcept> using namespace mirp; static void print_help(void) { std::cout << "\n" << "mirp_create_reference - Create a reference data file for use with other programs\n" << "\n" << "\n" << "Required arguments:\n" << " --basis Path to a basis set file (usually ends in .bas)\n" << " --geometry Path to an XYZ file(usually ends in .xyz)\n" << " --outfile Output file (usually ends in .dat). Existing data will\n" << " be overwritten\n" << " --integral The type of integral to compute. Possibilities are:\n" << " gtoeri\n" << "\n" << "\n" << "Optional arguments:\n" << " --am Comma-separated list of AM classes to calculate.\n" << " The AM should be represented by their letters.\n" << " (for example, for ERI: --am ssss,psps,dddd)\n" << "\n" << "\n" << "Other arguments:\n" << " -h, --help Display this help screen\n" << "\n"; } /*! \brief Main function */ int main(int argc, char ** argv) { std::string basfile, xyzfile, outfile; std::string integral; std::vector<std::vector<int>> amlist; try { auto cmdline = convert_cmdline(argc, argv); if(cmdline.size() == 0 || cmdline_get_switch(cmdline, "-h") || cmdline_get_switch(cmdline, "--help")) { print_help(); return 0; } basfile = cmdline_get_arg_str(cmdline, "--basis"); xyzfile = cmdline_get_arg_str(cmdline, "--geometry"); outfile = cmdline_get_arg_str(cmdline, "--outfile"); integral = cmdline_get_arg_str(cmdline, "--integral"); if(cmdline_has_arg(cmdline, "--am")) { std::string amlist_str = cmdline_get_arg_str(cmdline, "--am"); std::vector<std::string> amlist_split = split(amlist_str, ','); for(const auto & s : amlist_split) { std::vector<int> am_ntet; for(char c : s) am_ntet.push_back(amchar_to_int(c)); amlist.push_back(std::move(am_ntet)); } } if(cmdline.size() != 0) { std::stringstream ss; ss << "Unknown command line arguments:\n"; for(const auto & it : cmdline) ss << " " << it << "\n"; throw std::runtime_error(ss.str()); } } catch(std::exception & ex) { std::cout << "\nError parsing command line: " << ex.what() << "\n\n"; std::cout << "Run \"mirp_create_reference -h\" for help\n\n"; return 1; } // Create a header from the command line std::string header("# Reference values for the "); header += integral; header += " integral generated with:\n"; header += "# "; for(int i = 0; i < argc; i++) header += " " + std::string(argv[i]); header += "\n#\n"; try { if(integral == "gtoeri") { integral4_create_reference(xyzfile, basfile, outfile, header, amlist, mirp_gtoeri_exact); } else { std::cout << "Integral \"" << integral << "\" is not valid\n"; return 3; } } catch(std::exception & ex) { std::cout << "Error while running tests: " << ex.what() << "\n"; return 1; } return 0; }
30.726563
109
0.489448
[ "geometry", "vector" ]
e07238d17f9ecbfaa9c4861ae66bc6dcee626329
8,115
cpp
C++
ogldev-source/tutorial46/tutorial46.cpp
maodougansidui/ucsb_cmpsc180
2a207838ce269c27fa0f9a601b5633e4327a6e3b
[ "MIT" ]
null
null
null
ogldev-source/tutorial46/tutorial46.cpp
maodougansidui/ucsb_cmpsc180
2a207838ce269c27fa0f9a601b5633e4327a6e3b
[ "MIT" ]
null
null
null
ogldev-source/tutorial46/tutorial46.cpp
maodougansidui/ucsb_cmpsc180
2a207838ce269c27fa0f9a601b5633e4327a6e3b
[ "MIT" ]
null
null
null
/* Copyright 2015 Etay Meiri This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Tutorial 46 - Screen Space Ambient Occlusion With Depth Reconstruction */ #include <math.h> #include <GL/glew.h> #include <string> #ifndef WIN32 #include <sys/time.h> #include <unistd.h> #endif #include <sys/types.h> #include "ogldev_app.h" #include "ogldev_util.h" #include "ogldev_pipeline.h" #include "ogldev_camera.h" #include "ssao_technique.h" #include "geom_pass_tech.h" #include "blur_tech.h" #include "lighting_technique.h" #include "ogldev_backend.h" #include "ogldev_camera.h" #include "mesh.h" #include "ogldev_io_buffer.h" #define WINDOW_WIDTH 1280 #define WINDOW_HEIGHT 1024 class Tutorial46 : public ICallbacks, public OgldevApp { public: Tutorial46() { m_pGameCamera = NULL; m_persProjInfo.FOV = 60.0f; m_persProjInfo.Height = WINDOW_HEIGHT; m_persProjInfo.Width = WINDOW_WIDTH; m_persProjInfo.zNear = 1.0f; m_persProjInfo.zFar = 5000.0f; m_pipeline.SetPerspectiveProj(m_persProjInfo); m_directionalLight.Color = Vector3f(1.0f, 1.0f, 1.0f); m_directionalLight.AmbientIntensity = 0.3f; m_directionalLight.DiffuseIntensity = 1.0f; m_directionalLight.Direction = Vector3f(1.0f, 0.0, 0.0); m_shaderType = 0; } ~Tutorial46() { SAFE_DELETE(m_pGameCamera); } bool Init() { // Vector3f Pos(0.0f, 23.0f, -5.0f); // Vector3f Target(-1.0f, 0.0f, 0.1f); Vector3f Pos(0.0f, 24.0f, -38.0f); Vector3f Target(0.0f, -0.5f, 1.0f); Vector3f Up(0.0, 1.0f, 0.0f); m_pGameCamera = new Camera(WINDOW_WIDTH, WINDOW_HEIGHT, Pos, Target, Up); if (!m_geomPassTech.Init()) { OGLDEV_ERROR0("Error initializing the geometry pass technique\n"); return false; } if (!m_SSAOTech.Init()) { OGLDEV_ERROR0("Error initializing the SSAO technique\n"); return false; } m_SSAOTech.Enable(); m_SSAOTech.SetSampleRadius(1.5f); Matrix4f PersProjTrans; PersProjTrans.InitPersProjTransform(m_persProjInfo); m_SSAOTech.SetProjMatrix(PersProjTrans); float AspectRatio = m_persProjInfo.Width / m_persProjInfo.Height; m_SSAOTech.SetAspectRatio(AspectRatio); float TanHalfFOV = tanf(ToRadian(m_persProjInfo.FOV / 2.0f)); m_SSAOTech.SetTanHalfFOV(TanHalfFOV); if (!m_lightingTech.Init()) { OGLDEV_ERROR0("Error initializing the lighting technique\n"); return false; } m_lightingTech.Enable(); m_lightingTech.SetDirectionalLight(m_directionalLight); m_lightingTech.SetScreenSize(WINDOW_WIDTH, WINDOW_HEIGHT); m_lightingTech.SetShaderType(0); if (!m_blurTech.Init()) { OGLDEV_ERROR0("Error initializing the blur technique\n"); return false; } //if (!m_mesh.LoadMesh("../Content/crytek_sponza/sponza.obj")) { if (!m_mesh.LoadMesh("../Content/jeep.obj")) { return false; } m_mesh.GetOrientation().m_scale = Vector3f(0.05f); m_mesh.GetOrientation().m_pos = Vector3f(0.0f, 0.0f, 0.0f); m_mesh.GetOrientation().m_rotation = Vector3f(0.0f, 180.0f, 0.0f); if (!m_quad.LoadMesh("../Content/quad.obj")) { return false; } if (!m_depthBuffer.Init(WINDOW_WIDTH, WINDOW_HEIGHT, true, GL_NONE)) { return false; } if (!m_aoBuffer.Init(WINDOW_WIDTH, WINDOW_HEIGHT, false, GL_R32F)) { return false; } if (!m_blurBuffer.Init(WINDOW_WIDTH, WINDOW_HEIGHT, false, GL_R32F)) { return false; } #ifndef WIN32 if (!m_fontRenderer.InitFontRenderer()) { return false; } #endif return true; } void Run() { OgldevBackendRun(this); } virtual void RenderSceneCB() { m_pGameCamera->OnRender(); m_pipeline.SetCamera(*m_pGameCamera); GeometryPass(); SSAOPass(); BlurPass(); LightingPass(); RenderFPS(); CalcFPS(); OgldevBackendSwapBuffers(); } void GeometryPass() { m_geomPassTech.Enable(); m_depthBuffer.BindForWriting(); glClear(GL_DEPTH_BUFFER_BIT); m_pipeline.Orient(m_mesh.GetOrientation()); m_geomPassTech.SetWVP(m_pipeline.GetWVPTrans()); m_mesh.Render(); } void SSAOPass() { m_SSAOTech.Enable(); m_SSAOTech.BindDepthBuffer(m_depthBuffer); m_aoBuffer.BindForWriting(); glClear(GL_COLOR_BUFFER_BIT); m_quad.Render(); } void BlurPass() { m_blurTech.Enable(); m_blurTech.BindInputBuffer(m_aoBuffer); m_blurBuffer.BindForWriting(); glClear(GL_COLOR_BUFFER_BIT); m_quad.Render(); } void LightingPass() { m_lightingTech.Enable(); m_lightingTech.SetShaderType(m_shaderType); m_lightingTech.BindAOBuffer(m_blurBuffer); glBindFramebuffer(GL_FRAMEBUFFER, 0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); m_pipeline.Orient(m_mesh.GetOrientation()); m_lightingTech.SetWVP(m_pipeline.GetWVPTrans()); m_lightingTech.SetWorldMatrix(m_pipeline.GetWorldTrans()); m_mesh.Render(); } virtual void KeyboardCB(OGLDEV_KEY OgldevKey, OGLDEV_KEY_STATE State) { switch (OgldevKey) { case OGLDEV_KEY_ESCAPE: case OGLDEV_KEY_q: OgldevBackendLeaveMainLoop(); break; case OGLDEV_KEY_A: m_shaderType++; m_shaderType = m_shaderType % 3; break; default: m_pGameCamera->OnKeyboard(OgldevKey); } } virtual void PassiveMouseCB(int x, int y) { m_pGameCamera->OnMouse(x, y); } private: SSAOTechnique m_SSAOTech; GeomPassTech m_geomPassTech; LightingTechnique m_lightingTech; BlurTech m_blurTech; Camera* m_pGameCamera; Mesh m_mesh; Mesh m_quad; PersProjInfo m_persProjInfo; Pipeline m_pipeline; IOBuffer m_depthBuffer; IOBuffer m_aoBuffer; IOBuffer m_blurBuffer; DirectionalLight m_directionalLight; int m_shaderType; }; int main(int argc, char** argv) { // Magick::InitializeMagick(*argv); OgldevBackendInit(OGLDEV_BACKEND_TYPE_GLFW, argc, argv, true, false); if (!OgldevBackendCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, false, "Tutorial 45")) { OgldevBackendTerminate(); return 1; } SRANDOM; Tutorial46* pApp = new Tutorial46(); if (!pApp->Init()) { delete pApp; OgldevBackendTerminate(); return 1; } pApp->Run(); delete pApp; OgldevBackendTerminate(); return 0; }
26.177419
88
0.587307
[ "mesh", "geometry", "render" ]
2fdfb925a25ba1af67c0f5c6ba6991d06cf29964
8,748
cpp
C++
3rdparty/wxWidgets/src/msw/fontenum.cpp
mikiec84/winsparkle
e73db4ddb3be830b36b58e2f90f4bee6a0c684b7
[ "MIT" ]
2
2015-01-10T09:15:16.000Z
2018-01-03T21:21:46.000Z
3rdparty/wxWidgets/src/msw/fontenum.cpp
mikiec84/winsparkle
e73db4ddb3be830b36b58e2f90f4bee6a0c684b7
[ "MIT" ]
null
null
null
3rdparty/wxWidgets/src/msw/fontenum.cpp
mikiec84/winsparkle
e73db4ddb3be830b36b58e2f90f4bee6a0c684b7
[ "MIT" ]
1
2019-01-20T12:55:33.000Z
2019-01-20T12:55:33.000Z
/////////////////////////////////////////////////////////////////////////////// // Name: src/msw/fontenum.cpp // Purpose: wxFontEnumerator class for Windows // Author: Julian Smart // Modified by: Vadim Zeitlin to add support for font encodings // Created: 04/01/98 // RCS-ID: $Id: fontenum.cpp 58757 2009-02-08 11:45:59Z VZ $ // Copyright: (c) Julian Smart // Licence: wxWindows licence /////////////////////////////////////////////////////////////////////////////// // ============================================================================ // declarations // ============================================================================ // ---------------------------------------------------------------------------- // headers // ---------------------------------------------------------------------------- // For compilers that support precompilation, includes "wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #if wxUSE_FONTENUM #ifndef WX_PRECOMP #include "wx/gdicmn.h" #include "wx/font.h" #include "wx/encinfo.h" #include "wx/dynarray.h" #endif #include "wx/msw/private.h" #include "wx/fontutil.h" #include "wx/fontenum.h" #include "wx/fontmap.h" // ---------------------------------------------------------------------------- // private classes // ---------------------------------------------------------------------------- // the helper class which calls ::EnumFontFamilies() and whose OnFont() is // called from the callback passed to this function and, in its turn, calls the // appropariate wxFontEnumerator method class wxFontEnumeratorHelper { public: wxFontEnumeratorHelper(wxFontEnumerator *fontEnum); // control what exactly are we enumerating // we enumerate fonts with given enocding bool SetEncoding(wxFontEncoding encoding); // we enumerate fixed-width fonts void SetFixedOnly(bool fixedOnly) { m_fixedOnly = fixedOnly; } // we enumerate the encodings available in this family void SetFamily(const wxString& family); // call to start enumeration void DoEnumerate(); // called by our font enumeration proc bool OnFont(const LPLOGFONT lf, const LPTEXTMETRIC tm) const; private: // the object we forward calls to OnFont() to wxFontEnumerator *m_fontEnum; // if != -1, enum only fonts which have this encoding int m_charset; // if not empty, enum only the fonts with this facename wxString m_facename; // if not empty, enum only the fonts in this family wxString m_family; // if true, enum only fixed fonts bool m_fixedOnly; // if true, we enumerate the encodings, not fonts bool m_enumEncodings; // the list of charsets we already found while enumerating charsets wxArrayInt m_charsets; // the list of facenames we already found while enumerating facenames wxArrayString m_facenames; wxDECLARE_NO_COPY_CLASS(wxFontEnumeratorHelper); }; // ---------------------------------------------------------------------------- // private functions // ---------------------------------------------------------------------------- #ifndef __WXMICROWIN__ int CALLBACK wxFontEnumeratorProc(LPLOGFONT lplf, LPTEXTMETRIC lptm, DWORD dwStyle, LPARAM lParam); #endif // ============================================================================ // implementation // ============================================================================ // ---------------------------------------------------------------------------- // wxFontEnumeratorHelper // ---------------------------------------------------------------------------- wxFontEnumeratorHelper::wxFontEnumeratorHelper(wxFontEnumerator *fontEnum) { m_fontEnum = fontEnum; m_charset = DEFAULT_CHARSET; m_fixedOnly = false; m_enumEncodings = false; } void wxFontEnumeratorHelper::SetFamily(const wxString& family) { m_enumEncodings = true; m_family = family; } bool wxFontEnumeratorHelper::SetEncoding(wxFontEncoding encoding) { if ( encoding != wxFONTENCODING_SYSTEM ) { wxNativeEncodingInfo info; if ( !wxGetNativeFontEncoding(encoding, &info) ) { #if wxUSE_FONTMAP if ( !wxFontMapper::Get()->GetAltForEncoding(encoding, &info) ) #endif // wxUSE_FONTMAP { // no such encodings at all return false; } } m_charset = info.charset; m_facename = info.facename; } return true; } #if defined(__GNUWIN32__) && !defined(__CYGWIN10__) && !wxCHECK_W32API_VERSION( 1, 1 ) && !wxUSE_NORLANDER_HEADERS #define wxFONTENUMPROC int(*)(ENUMLOGFONTEX *, NEWTEXTMETRICEX*, int, LPARAM) #else #define wxFONTENUMPROC FONTENUMPROC #endif void wxFontEnumeratorHelper::DoEnumerate() { #ifndef __WXMICROWIN__ HDC hDC = ::GetDC(NULL); #ifdef __WXWINCE__ ::EnumFontFamilies(hDC, m_facename.empty() ? NULL : m_facename.wx_str(), (wxFONTENUMPROC)wxFontEnumeratorProc, (LPARAM)this) ; #else // __WIN32__ LOGFONT lf; lf.lfCharSet = (BYTE)m_charset; wxStrlcpy(lf.lfFaceName, m_facename.c_str(), WXSIZEOF(lf.lfFaceName)); lf.lfPitchAndFamily = 0; ::EnumFontFamiliesEx(hDC, &lf, (wxFONTENUMPROC)wxFontEnumeratorProc, (LPARAM)this, 0 /* reserved */) ; #endif // Win32/CE ::ReleaseDC(NULL, hDC); #endif } bool wxFontEnumeratorHelper::OnFont(const LPLOGFONT lf, const LPTEXTMETRIC tm) const { if ( m_enumEncodings ) { // is this a new charset? int cs = lf->lfCharSet; if ( m_charsets.Index(cs) == wxNOT_FOUND ) { wxConstCast(this, wxFontEnumeratorHelper)->m_charsets.Add(cs); wxFontEncoding enc = wxGetFontEncFromCharSet(cs); return m_fontEnum->OnFontEncoding(lf->lfFaceName, wxFontMapper::GetEncodingName(enc)); } else { // continue enumeration return true; } } if ( m_fixedOnly ) { // check that it's a fixed pitch font (there is *no* error here, the // flag name is misleading!) if ( tm->tmPitchAndFamily & TMPF_FIXED_PITCH ) { // not a fixed pitch font return true; } } if ( m_charset != DEFAULT_CHARSET ) { // check that we have the right encoding if ( lf->lfCharSet != m_charset ) { return true; } } else // enumerating fonts in all charsets { // we can get the same facename twice or more in this case because it // may exist in several charsets but we only want to return one copy of // it (note that this can't happen for m_charset != DEFAULT_CHARSET) if ( m_facenames.Index(lf->lfFaceName) != wxNOT_FOUND ) { // continue enumeration return true; } wxConstCast(this, wxFontEnumeratorHelper)-> m_facenames.Add(lf->lfFaceName); } return m_fontEnum->OnFacename(lf->lfFaceName); } // ---------------------------------------------------------------------------- // wxFontEnumerator // ---------------------------------------------------------------------------- bool wxFontEnumerator::EnumerateFacenames(wxFontEncoding encoding, bool fixedWidthOnly) { wxFontEnumeratorHelper fe(this); if ( fe.SetEncoding(encoding) ) { fe.SetFixedOnly(fixedWidthOnly); fe.DoEnumerate(); } // else: no such fonts, unknown encoding return true; } bool wxFontEnumerator::EnumerateEncodings(const wxString& family) { wxFontEnumeratorHelper fe(this); fe.SetFamily(family); fe.DoEnumerate(); return true; } // ---------------------------------------------------------------------------- // Windows callbacks // ---------------------------------------------------------------------------- #ifndef __WXMICROWIN__ int CALLBACK wxFontEnumeratorProc(LPLOGFONT lplf, LPTEXTMETRIC lptm, DWORD WXUNUSED(dwStyle), LPARAM lParam) { // we used to process TrueType fonts only, but there doesn't seem to be any // reasons to restrict ourselves to them here #if 0 // Get rid of any fonts that we don't want... if ( dwStyle != TRUETYPE_FONTTYPE ) { // continue enumeration return TRUE; } #endif // 0 wxFontEnumeratorHelper *fontEnum = (wxFontEnumeratorHelper *)lParam; return fontEnum->OnFont(lplf, lptm); } #endif #endif // wxUSE_FONTENUM
29.856655
114
0.536351
[ "object" ]
2fec197de5a3f2d985312bb1cede19a666283a9a
32,802
cpp
C++
tst/unit/geometry/test_geometry.cpp
lanl/phoebus
c570f42882c1c9e01e3bfe4b00b22e15a7a9992b
[ "BSD-3-Clause" ]
3
2022-03-24T22:09:12.000Z
2022-03-29T23:16:21.000Z
tst/unit/geometry/test_geometry.cpp
lanl/phoebus
c570f42882c1c9e01e3bfe4b00b22e15a7a9992b
[ "BSD-3-Clause" ]
8
2022-03-15T20:49:43.000Z
2022-03-29T17:45:04.000Z
tst/unit/geometry/test_geometry.cpp
lanl/phoebus
c570f42882c1c9e01e3bfe4b00b22e15a7a9992b
[ "BSD-3-Clause" ]
null
null
null
// © 2021. Triad National Security, LLC. All rights reserved. This // program was produced under U.S. Government contract // 89233218CNA000001 for Los Alamos National Laboratory (LANL), which // is operated by Triad National Security, LLC for the U.S. // Department of Energy/National Nuclear Security Administration. All // rights in the program are reserved by Triad National Security, LLC, // and the U.S. Department of Energy/National Nuclear Security // Administration. The Government is granted for itself and others // acting on its behalf a nonexclusive, paid-up, irrevocable worldwide // license in this material to reproduce, prepare derivative works, // distribute copies to the public, perform publicly and display // publicly, and to permit others to do so. // stdlib includes #include <cmath> // external includes #include "catch2/catch.hpp" #include <Kokkos_Core.hpp> // parthenon includes #include <coordinates/coordinates.hpp> #include <defs.hpp> #include <kokkos_abstraction.hpp> #include <parameter_input.hpp> // phoebus includes #include "geometry/geometry_utils.hpp" #include "phoebus_utils/cell_locations.hpp" #include "phoebus_utils/linear_algebra.hpp" #include "phoebus_utils/robust.hpp" // coordinate system includes #include <geometry/analytic_system.hpp> #include <geometry/boyer_lindquist.hpp> #include <geometry/cached_system.hpp> #include <geometry/flrw.hpp> #include <geometry/fmks.hpp> #include <geometry/geometry_defaults.hpp> #include <geometry/mckinney_gammie_ryan.hpp> #include <geometry/minkowski.hpp> #include <geometry/modified_system.hpp> #include <geometry/spherical_kerr_schild.hpp> #include <geometry/spherical_minkowski.hpp> using namespace Geometry; using parthenon::Coordinates_t; using parthenon::ParameterInput; using parthenon::ParArray1D; using parthenon::Real; using parthenon::RegionSize; using robust::ratio; constexpr int NTRIALS = 100; constexpr int NG = 2; constexpr int NX = 32 + 2 * NG; constexpr Real EPS = 1e-5; KOKKOS_INLINE_FUNCTION Real GetDifference(Real a, Real b) { return 2 * ratio(std::abs(b - a), std::abs(b) + std::abs(a)); } TEST_CASE("Minkowski Coordinates", "[geometry]") { GIVEN("A Cartesian Minkowski coordinate system") { Analytic<Minkowski, IndexerMeshBlock> system; THEN("The coordinate system can be called on device") { int n_wrong = 100; // > 0 Kokkos::parallel_reduce( "get n wrong", NTRIALS, KOKKOS_LAMBDA(const int i, int &update) { // lapse Real alpha = system.Lapse(0, 0, 0, 0); if (alpha != 1.) update += 1; // shift Real beta[NDSPACE]; system.ContravariantShift(CellLocation::Corn, 0, 0, 0, beta); for (int l = 0; l < NDSPACE; ++l) { if (beta[l] != 0.0) update += 1; } // metric Real gamma[NDSPACE][NDSPACE]; system.Metric(CellLocation::Face1, 0, 0, 0, gamma); for (int l = 0; l < NDSPACE; l++) { for (int m = 0; m < NDSPACE; m++) { if (l == m && gamma[l][m] != 1.) update += 1; if (l != m && gamma[l][m] != 0.) update += 1; } } // inverse metric system.MetricInverse(CellLocation::Cent, 0, 0, 0, gamma); for (int l = 0; l < NDSPACE; l++) { for (int m = 0; m < NDSPACE; m++) { if (l == m && gamma[l][m] != 1.) update += 1; if (l != m && gamma[l][m] != 0.) update += 1; } } // metric determinants for (int k = 0; k < NX; ++k) { for (int j = 0; j < NX; ++j) { for (int ii = 0; ii < NX; ++ii) { Real dgamma = system.DetGamma(CellLocation::Face2, k, j, ii); if (dgamma != 1.0) update += 1; Real dg = system.DetG(CellLocation::Face3, k, j, ii); if (dg != 1.0) update += 1; } } } // connection coefficient Real Gamma[NDFULL][NDFULL][NDFULL]; system.ConnectionCoefficient(0, 0, 0, 0, Gamma); for (int l = 0; l < NDFULL; ++l) { for (int m = 0; m < NDFULL; ++m) { for (int n = 0; n < NDFULL; ++n) { if (Gamma[l][m][n] != 0.0) update += 1; } } } // grad g // g_{nu l, mu} Real dg[NDFULL][NDFULL][NDFULL]; system.MetricDerivative(0, 0, 0, 0, dg); for (int nu = 0; nu < NDFULL; ++nu) { for (int l = 0; l < NDFULL; ++l) { for (int mu = 0; mu < NDFULL; ++mu) { if (dg[nu][l][mu] != 0.0) update += 1; } } } // grad ln(alpha) Real grada[NDFULL]; system.GradLnAlpha(CellLocation::Corn, 0, 0, 0, grada); for (int mu = 0; mu < NDFULL; ++mu) { if (grada[mu] != 0.0) update += 1; } }, n_wrong); REQUIRE(n_wrong == 0); } } GIVEN("A ParArray1D of Coordinates_ts") { ParArray1D<Coordinates_t> coords("coords view", NTRIALS); auto coords_h = Kokkos::create_mirror_view(coords); for (int i = 0; i < NTRIALS; ++i) { coords_h(i) = Coordinates_t(); // or something more complicated } Kokkos::deep_copy(coords, coords_h); THEN("We can create a Minkowski coordinate system using this") { Real time = 3.0; IndexerMesh indexer(coords); Analytic<Minkowski, IndexerMesh> system(time, indexer); AND_THEN("The coordinate system can be called on device") { int n_wrong = 100; // > 0 Kokkos::parallel_reduce( "get n wrong", NTRIALS, KOKKOS_LAMBDA(const int b, int &update) { // Indexer Real X1, X2, X3; indexer.GetX(CellLocation::Cent, b, 0, 0, 0, X1, X2, X3); // shift Real beta[NDSPACE]; system.ContravariantShift(CellLocation::Corn, b, 0, 0, 0, beta); for (int l = 0; l < NDSPACE; ++l) { if (beta[l] != 0.0) update += 1; } // metric Real gamma[NDSPACE][NDSPACE]; system.Metric(CellLocation::Face1, b, 0, 0, 0, gamma); for (int l = 1; l < NDSPACE; l++) { for (int m = 1; m < NDSPACE; m++) { if (l == m && gamma[l][m] != 1.) { update += 1; } if (l != m && gamma[l][m] != 0.) { update += 1; } } } Real g[NDFULL][NDFULL]; system.SpacetimeMetric(CellLocation::Face1, b, 0, 0, 0, g); for (int mu = 0; mu < NDFULL; ++mu) { for (int nu = 0; nu < NDFULL; ++nu) { Real comp = g[mu][nu]; if (mu == nu && mu == 0 && comp != -1.) update += 1; if (mu == nu && mu != 0 && comp != 1.) update += 1; if (mu != nu && comp != 0.) update += 1; } } // metric determinants for (int k = 0; k < NX; ++k) { for (int j = 0; j < NX; ++j) { for (int ii = 0; ii < NX; ++ii) { Real dgamma = system.DetGamma(CellLocation::Face2, b, k, j, ii); if (dgamma != 1.0) update += 1; Real dg = system.DetG(CellLocation::Face3, b, k, j, ii); if (dg != 1.0) update += 1; } } } // grad ln(alpha) Real grada[NDFULL]; system.GradLnAlpha(CellLocation::Corn, b, 0, 0, 0, grada); for (int mu = 0; mu < NDFULL; ++mu) { if (grada[mu] != 0.0) update += 1; } }, n_wrong); REQUIRE(n_wrong == 0); } } } } TEST_CASE("FLRW Coordinates", "[geometry]") { GIVEN("A coords object") { Coordinates_t coords; WHEN("We create an FLRW object") { Real t = 1.0; Real a0 = 1; Real dadt = 1; Real x, y, z; x = y = z = 0; IndexerMeshBlock indexer(coords); Analytic<FLRW, IndexerMeshBlock> system(t, indexer, a0, dadt); THEN("The coordinate system can be called on device") { int n_wrong = 100; Kokkos::parallel_reduce( "get n wrong", NTRIALS, KOKKOS_LAMBDA(const int i, int &update) { // lapse Real alpha = system.Lapse(t, x, y, z); if (alpha != 1) update += 1; // shift Real beta[NDSPACE]; system.ContravariantShift(t, x, y, z, beta); SPACELOOP(m) { if (beta[m] != 0) { update += 1; } } // metric Real gamma[NDSPACE][NDSPACE]; system.Metric(t, x, y, z, gamma); SPACELOOP2(i, j) { if ((i != j) && gamma[i][j] != 0) update += 1; if ((i == j) && GetDifference(gamma[i][j], 4) > EPS) update += 1; } // Inverse metric system.MetricInverse(t, x, y, z, gamma); SPACELOOP2(i, j) { if ((i != j) && gamma[i][j] != 0) update += 1; if ((i == j) && GetDifference(gamma[i][j], 1. / 4.) > EPS) update += 1; } }, n_wrong); REQUIRE(n_wrong == 0); } } } } TEST_CASE("Spherical Minkowski Coordinates", "[geometry]") { GIVEN("A coords object") { Coordinates_t coords; WHEN("We create a Spherical Minkowski object") { IndexerMeshBlock indexer(coords); Analytic<SphericalMinkowski, IndexerMeshBlock> system(indexer); THEN("The coordinate system can be called on device") { int n_wrong = 100; Kokkos::parallel_reduce( "get n wrong", NTRIALS, KOKKOS_LAMBDA(const int i, int &update) { Real r, th, ph; // lapse Real alpha = system.Lapse(0, 1, M_PI / 2., 0); if (alpha != 1) update += 1; // shift Real beta[NDSPACE]; system.ContravariantShift(0, 3, 3 * M_PI / 4., M_PI / 2., beta); SPACELOOP(m) { if (beta[m] != 0) { update += 1; } } // metric Real gamma[NDSPACE][NDSPACE]; r = 5; th = 3 * M_PI / 4; ph = 3 * M_PI / 4; system.Metric(0, r, th, ph, gamma); if (gamma[0][0] != 1) update += 1; if (GetDifference(gamma[1][1], r * r) > EPS) update += 1; if (GetDifference(gamma[2][2], std::pow(r * std::sin(th), 2)) > EPS) update += 1; if (gamma[0][1] != 0) update += 1; if (gamma[0][2] != 0) update += 1; if (gamma[1][2] != 0) update += 1; // Inverse metric system.MetricInverse(0, r, th, ph, gamma); if (GetDifference(gamma[1][1], 1 / (r * r)) > EPS) update += 1; if (GetDifference(gamma[2][2], std::pow(r * std::sin(th), -2)) > EPS) update += 1; // Connection Coefficient Real Gamma[NDFULL][NDFULL][NDFULL]; system.ConnectionCoefficient(0, r, th, ph, Gamma); SPACETIMELOOP2(mu, nu) { if (Gamma[0][mu][nu] != 0) update += 1; } if (GetDifference(Gamma[1][2][2], -r) > EPS) update += 1; if (GetDifference(Gamma[1][3][3], -r * std::sin(th) * std::sin(th)) > EPS) update += 1; if (GetDifference(Gamma[2][1][2], r) > EPS) update += 1; if (GetDifference(Gamma[2][3][3], -r * r * std::cos(th) * std::sin(th)) > EPS) update += 1; if (GetDifference(Gamma[3][2][3], r * r * std::cos(th) * std::sin(th)) > EPS) update += 1; if (GetDifference(Gamma[3][1][3], r * std::sin(th) * std::sin(th)) > EPS) update += 1; }, n_wrong); REQUIRE(n_wrong == 0); } } } } // Strategy for more complex metrics: Evaluate at equator as a // consistency check between code implementation and mathematica // BL is horrible, and not currently super important, so these tests // won't be complete TEST_CASE("Boyer-Lindquist Coordinates", "[geometry]") { GIVEN("A coords object") { Coordinates_t coords; WHEN("We create a Boyer-Lindquist object") { constexpr Real a = 0.9; IndexerMeshBlock indexer(coords); Analytic<BoyerLindquist, IndexerMeshBlock> system(indexer, a); THEN("The coordinate system can be called on device") { int n_wrong = 100; Kokkos::parallel_reduce( "get n wrong", NTRIALS, KOKKOS_LAMBDA(const int i, int &update) { constexpr Real r = 10; constexpr Real th = M_PI / 2; constexpr Real ph = 0; // Lapse Real alpha = system.Lapse(0, r, th, ph); if (GetDifference(alpha, std::sqrt(r / (r - 2))) > EPS) update += 1; // Shift Real beta[NDSPACE]; system.ContravariantShift(0, r, th, ph, beta); if (beta[0] != 0) update += 1; if (beta[1] != 0) update += 1; if (GetDifference(beta[2], -2 * a / (r - 2)) > EPS) update += 1; // metric Real gamma[NDSPACE][NDSPACE]; system.Metric(0, r, th, ph, gamma); if (GetDifference(gamma[2][2], (r - 2) / (r * (a * a + (r - 2) * r))) > EPS) update += 1; // Inverse metric Real g[NDFULL][NDFULL]; system.SpacetimeMetricInverse(0, r, th, ph, g); if (GetDifference(g[3][3], a * a * (1 + (2 / r)) + r * r) > EPS) update += 1; // Gradient Real dg[NDFULL][NDFULL][NDFULL]; system.MetricDerivative(0, r, th, ph, dg); if (GetDifference(dg[2][2][1], -2 / (r * r * r)) > EPS) { update += 1; } // connection coefficent Real connection[NDFULL][NDFULL][NDFULL]; system.ConnectionCoefficient(0, r, th, ph, connection); if (GetDifference(connection[1][1][1], (r - a * a) / (r * r * r)) > EPS) { update += 1; } }, n_wrong); REQUIRE(n_wrong == 0); } } } } TEST_CASE("Spherical Kerr-Schild Coordinates", "[geometry]") { GIVEN("A coords object") { Coordinates_t coords; WHEN("We create a Kerr-Schild object") { constexpr Real a = 0.9; IndexerMeshBlock indexer(coords); Analytic<SphericalKerrSchild, IndexerMeshBlock> system(indexer, a); THEN("The coordinate system can be called on device") { int n_wrong = 100; Kokkos::parallel_reduce( "get n wrong", NTRIALS, KOKKOS_LAMBDA(const int i, int &update) { constexpr Real r = 6; constexpr Real th = M_PI / 2; constexpr Real ph = 3 * M_PI / 2; // Lapse Real alpha = system.Lapse(1, r, th, ph); if (GetDifference(alpha, std::sqrt(r / (r + 2))) > EPS) update += 1; // metric determinant Real gamdet = system.DetGamma(-3, r, th, ph); if (GetDifference(gamdet, std::sqrt(r * r * r * (2 + r))) > EPS) update += 1; Real gdet = system.DetG(-5, r, th, ph); if (GetDifference(gdet, r * r) > EPS) update += 1; // Shift Real beta[NDSPACE]; system.ContravariantShift(2, r, th, ph, beta); if (GetDifference(beta[0], 2 / (2 + r)) > EPS) update += 1; if (beta[1] != 0 || beta[2] != 0) update += 1; // metric Real gamma[NDSPACE][NDSPACE]; system.Metric(3, r, th, ph, gamma); if (gamma[0][1] != 0 || gamma[1][0] != 0 || gamma[1][2] != 0 || gamma[2][1] != 0) update += 1; if (GetDifference(gamma[0][0], (2 + r) / r) > EPS) { printf("%g %g\n", gamma[0][0], (2 + r) / r); update += 1; } if (GetDifference(gamma[1][1], r * r) > EPS) update += 1; if (GetDifference(gamma[2][2], r * r + ((a * a * (2 + r)) / r)) > EPS) update += 1; if (GetDifference(gamma[0][2], -a * (r + 2) / r) > EPS) update += 1; // Inverse metric system.MetricInverse(4, r, th, ph, gamma); if (gamma[0][1] != 0 || gamma[1][0] != 0 || gamma[1][2] != 0 || gamma[2][1] != 0) update += 1; if (GetDifference(gamma[0][0], ((a * a) / (r * r)) + (r / (2 + r))) > EPS) update += 1; if (GetDifference(gamma[1][1], (1 / (r * r))) > EPS) update += 1; if (GetDifference(gamma[2][2], (1 / (r * r))) > EPS) update += 1; if (GetDifference(gamma[2][0], a / (r * r)) > EPS) update += 1; if (GetDifference(gamma[0][2], a / (r * r)) > EPS) update += 1; // Metric Derivative Real dg[NDFULL][NDFULL][NDFULL]; system.MetricDerivative(11, r, th, ph, dg); SPACETIMELOOP2(mu, nu) { if (dg[mu][nu][0] != 0) update += 1; } for (int mu = 0; mu < 2; ++mu) { for (int nu = 0; nu < 2; ++nu) { if (GetDifference(dg[mu][nu][1], -2 / (r * r)) > EPS) update += 1; } } if (GetDifference(dg[2][2][1], 2 * r) > EPS) update += 1; if (GetDifference(dg[3][3][1], 2 * r - (2 * a * a / (r * r))) > EPS) update += 1; if (GetDifference(dg[0][3][1], 2 * a / (r * r)) > EPS) update += 1; if (GetDifference(dg[3][0][1], 2 * a / (r * r)) > EPS) update += 1; if (GetDifference(dg[1][3][1], 2 * a / (r * r)) > EPS) update += 1; if (GetDifference(dg[3][1][1], 2 * a / (r * r)) > EPS) update += 1; if (dg[0][2][1] != 0 || dg[2][0][1] != 0 || dg[1][2][1] != 0 || dg[2][1][1] != 0 || dg[2][3][1] != 0 || dg[3][2][1] != 0) update += 1; SPACETIMELOOP2(mu, nu) { if (std::abs(dg[mu][nu][2]) > EPS) update += 1; if (dg[mu][nu][3] != 0) update += 1; } // Christoffel connection Real Gamma[NDFULL][NDFULL][NDFULL]; system.ConnectionCoefficient(10, r, th, ph, Gamma); if (std::abs(Gamma[0][0][0]) > EPS || std::abs(Gamma[0][0][2]) > EPS || std::abs(Gamma[0][0][3]) > EPS || std::abs(Gamma[0][1][2]) > EPS || std::abs(Gamma[0][2][0]) > EPS || std::abs(Gamma[0][2][1]) > EPS || std::abs(Gamma[0][2][2]) > EPS || std::abs(Gamma[0][2][3]) > EPS || std::abs(Gamma[0][3][0]) > EPS || std::abs(Gamma[0][3][2]) > EPS || std::abs(Gamma[0][3][3]) > EPS) update += 1; if (GetDifference(Gamma[0][0][1], -1 / (r * r)) > EPS) update += 1; if (GetDifference(Gamma[0][1][0], -1 / (r * r)) > EPS) update += 1; if (GetDifference(Gamma[0][1][1], -2 / (r * r)) > EPS) update += 1; if (GetDifference(Gamma[0][3][1], a / (r * r)) > EPS) update += 1; if (GetDifference(Gamma[0][1][3], a / (r * r)) > EPS) update += 1; if (std::abs(Gamma[1][0][1]) > EPS || std::abs(Gamma[1][1][0]) > EPS || std::abs(Gamma[1][0][2]) > EPS || std::abs(Gamma[1][2][0]) > EPS || std::abs(Gamma[1][1][2]) > EPS || std::abs(Gamma[1][2][1]) > EPS || std::abs(Gamma[1][1][3]) > EPS || std::abs(Gamma[1][3][1]) > EPS || std::abs(Gamma[1][2][3]) > EPS || std::abs(Gamma[1][3][2]) > EPS) update += 1; if (GetDifference(Gamma[1][0][0], 1 / (r * r)) > EPS) update += 1; if (GetDifference(Gamma[1][1][1], -1 / (r * r)) > EPS) update += 1; if (GetDifference(Gamma[1][2][2], -r) > EPS) update += 1; if (GetDifference(Gamma[1][3][3], ((a * a) / (r * r)) - r) > EPS) update += 1; if (GetDifference(Gamma[1][0][3], -a / (r * r)) > EPS) update += 1; if (GetDifference(Gamma[1][3][0], -a / (r * r)) > EPS) update += 1; for (int mu = 0; mu < NDFULL; ++mu) { for (int nu = 0; nu < NDFULL; ++nu) { if (!((mu == 1 && nu == 2) || (mu == 2 && nu == 1)) && std::abs(Gamma[2][mu][nu]) > EPS) update += 1; } } if (GetDifference(Gamma[2][2][1], r) > EPS) update += 1; if (GetDifference(Gamma[2][1][2], r) > EPS) update += 1; if (std::abs(Gamma[3][0][0]) > EPS || std::abs(Gamma[3][0][2]) > EPS || std::abs(Gamma[3][2][0]) > EPS || std::abs(Gamma[3][0][3]) > EPS || std::abs(Gamma[3][3][0]) > EPS || std::abs(Gamma[3][1][2]) > EPS || std::abs(Gamma[3][2][1]) > EPS || std::abs(Gamma[3][2][2]) > EPS || std::abs(Gamma[3][2][3]) > EPS || std::abs(Gamma[3][3][2]) > EPS || std::abs(Gamma[3][3][3]) > EPS) update += 1; if (GetDifference(Gamma[3][0][1], a / (r * r)) > EPS) update += 1; if (GetDifference(Gamma[3][1][0], a / (r * r)) > EPS) update += 1; if (GetDifference(Gamma[3][1][1], 2 * a / (r * r)) > EPS) update += 1; if (GetDifference(Gamma[3][1][3], r - ((a * a) / (r * r))) > EPS) update += 1; if (GetDifference(Gamma[3][3][1], r - ((a * a) / (r * r))) > EPS) update += 1; // gradlnalpha Real da[NDFULL]; system.GradLnAlpha(2021, r, th, ph, da); if (std::abs(da[0]) > EPS || std::abs(da[2]) > EPS || std::abs(da[3]) > EPS) update += 1; if (GetDifference(da[1], 1 / (2 * r + r * r)) > EPS) update += 1; }, n_wrong); REQUIRE(n_wrong == 0); } } } } TEST_CASE("McKinneyGammieRyan", "[geometry]") { GIVEN("The parameters for a modifier") { constexpr bool derefine_poles = true; constexpr Real hslope = 0.3; constexpr Real poly_xt = 0.82; constexpr Real poly_alpha = 14.0; constexpr Real mks_smooth = 0.5; constexpr Real x0 = -0.4409148982097008; WHEN("We create a modifier object") { McKinneyGammieRyan transformation(derefine_poles, hslope, poly_xt, poly_alpha, x0, mks_smooth); THEN("The modifier can be called on device") { int n_wrong = 100; Kokkos::parallel_reduce( "get n wrong", NTRIALS, KOKKOS_LAMBDA(const int i, int &update) { // locations chosen from a nubhlight sim constexpr Real X[] = {0, 1.1324898310315077, 0.2638888888888889, 3.2724923474893677}; Real C[NDSPACE]; Real Jcov[NDSPACE][NDSPACE]; Real Jcon[NDSPACE][NDSPACE]; transformation(X[1], X[2], X[3], C, Jcov, Jcon); // r if (GetDifference(C[0], 3.1033737650977384) > EPS) update += 1; // theta if (GetDifference(C[1], 1.1937404314936582) > EPS) update += 1; // phi if (GetDifference(C[2], 3.2724923474893677) > EPS) update += 1; // Jcov if (std::abs(Jcov[0][1] > EPS)) update += 1; if (std::abs(Jcov[0][2] > EPS)) update += 1; if (std::abs(Jcov[1][2] > EPS)) update += 1; if (std::abs(Jcov[2][0] > EPS)) update += 1; if (std::abs(Jcov[2][1] > EPS)) update += 1; if (GetDifference(Jcov[2][2], 1) > EPS) update += 1; if (GetDifference(Jcov[0][0], 3.10337377) > EPS) update += 1; if (GetDifference(Jcov[1][0], -0.00802045) > EPS) update += 1; if (GetDifference(Jcov[1][1], 2.29713534) > EPS) update += 1; // Jcon if (std::abs(Jcon[0][1] > EPS)) update += 1; if (std::abs(Jcon[0][2] > EPS)) update += 1; if (std::abs(Jcon[1][2] > EPS)) update += 1; if (std::abs(Jcon[2][0] > EPS)) update += 1; if (std::abs(Jcon[2][1] > EPS)) update += 1; if (GetDifference(Jcon[2][2], 1) > EPS) update += 1; if (GetDifference(Jcon[0][0], 0.32222996) > EPS) update += 1; if (GetDifference(Jcon[1][0], 0.00112507) > EPS) update += 1; if (GetDifference(Jcon[1][1], 0.43532481) > EPS) update += 1; }, n_wrong); REQUIRE(n_wrong == 0); } } } } TEST_CASE("Modified Kerr-Schild", "[geometry]") { GIVEN("A coords object and a modifier object") { constexpr Real a = 0.8; // Taken from a nubhlight run constexpr bool derefine_poles = true; constexpr Real hslope = 0.3; constexpr Real poly_xt = 0.82; constexpr Real poly_alpha = 14.0; constexpr Real mks_smooth = 0.5; constexpr Real x0 = -0.4409148982097008; constexpr Real dxfd = 1e-10; Coordinates_t coords; IndexerMeshBlock indexer(coords); McKinneyGammieRyan transformation(derefine_poles, hslope, poly_xt, poly_alpha, x0, mks_smooth); WHEN("We create an FMKS object") { FMKSMeshBlock system(indexer, dxfd, transformation, a); THEN("The coordinate system can be called on device") { int n_wrong = 100; Kokkos::parallel_reduce( "get n wrong", NTRIALS, KOKKOS_LAMBDA(const int i, int &update) { // locations chosen from a nubhlight sim constexpr Real X[] = {0, 1.1324898310315077, 0.2638888888888889, 3.2724923474893677}; // lapse Real alpha = system.Lapse(X[0], X[1], X[2], X[3]); if (GetDifference(alpha, 0.7811769941965497) > EPS) update += 1; // metric determinant Real gdet = system.DetG(X[0], X[1], X[2], X[3]); if (GetDifference(gdet, 64.40965903079623) > EPS) update += 1; // Spacetime metric Real g[NDFULL][NDFULL]; system.SpacetimeMetric(X[0], X[1], X[2], X[3], g); if (GetDifference(g[0][0], -0.3612937485396168) > EPS) update += 1; if (GetDifference(g[0][1], 1.9821442243860723) > EPS) update += 1; if (GetDifference(g[1][0], 1.9821442243860723) > EPS) update += 1; if (std::abs(g[0][2]) > EPS) update += 1; if (std::abs(g[2][0]) > EPS) update += 1; if (GetDifference(g[1][1], 15.78288823) > EPS) update += 1; if (GetDifference(g[1][2], -0.17903916) > EPS) update += 1; if (GetDifference(g[2][1], -0.17903916) > EPS) update += 1; if (GetDifference(g[1][3], -3.51690001) > EPS) update += 1; if (GetDifference(g[3][1], -3.51690001) > EPS) update += 1; if (GetDifference(g[2][2], 51.27859056) > EPS) update += 1; if (std::abs(g[2][3]) > EPS || std::abs(g[3][2]) > EPS) update += 1; if (GetDifference(g[3][3], 9.18405881) > EPS) update += 1; // Inverse metric Real ginv[NDFULL][NDFULL]; system.SpacetimeMetricInverse(X[0], X[1], X[2], X[3], ginv); if (GetDifference(ginv[0][0], -1.63870625e+00) > EPS) update += 1; if (GetDifference(ginv[0][1], 2.05810289e-01) > EPS) update += 1; if (GetDifference(ginv[1][0], 2.05810289e-01) > EPS) update += 1; if (std::abs(ginv[0][3]) > EPS || std::abs(ginv[3][0]) > EPS) update += 1; if (GetDifference(ginv[1][1], 4.34252153e-02) > EPS) update += 1; if (GetDifference(ginv[1][2], 0.00015161910494636605) > EPS) { printf("Bad ginv[1][2] %g %g\n", ginv[1][2], 0.00015161910494636605); update += 1; } if (GetDifference(ginv[2][1], 0.00015161910494636605) > EPS) update += 1; if (GetDifference(ginv[1][3], 2.65272964e-02) > EPS) update += 1; if (GetDifference(ginv[3][1], 2.65272964e-02) > EPS) update += 1; if (GetDifference(ginv[2][2], 1.95018454e-02) > EPS) update += 1; if (GetDifference(ginv[3][3], 1.19042557e-01) > EPS) update += 1; // Do the metric and inverse metric match? Real delta[NDFULL][NDFULL]; LinearAlgebra::SetZero(delta, NDFULL, NDFULL); SPACETIMELOOP3(mu, nu, sigma) { delta[mu][nu] += ginv[mu][sigma] * g[sigma][nu]; } SPACETIMELOOP2(mu, nu) { if (mu == nu) { if (GetDifference(delta[mu][nu], 1) > 1e-10) { printf("bad delta %d %d %g\n", mu, nu, delta[mu][nu]); update += 1; } } else if (std::abs(delta[mu][nu]) > 1e-10) { printf("bad delta %d %d %g\n", mu, nu, delta[mu][nu]); update += 1; } } // Connection Real Gamma[NDFULL][NDFULL][NDFULL]; Real Gamma_lo[NDFULL][NDFULL][NDFULL]; system.ConnectionCoefficient(X[0], X[1], X[2], X[3], Gamma_lo); SPACETIMELOOP3(sigma, mu, nu) { Gamma[sigma][mu][nu] = 0; SPACETIMELOOP(rho) { Gamma[sigma][mu][nu] += ginv[sigma][rho] * Gamma_lo[rho][mu][nu]; } } constexpr Real Gamma_nubhlight[NDFULL][NDFULL][NDFULL] = { {{6.45525676e-02, 5.14097064e-01, -3.30779101e-02, -4.46414555e-02}, {5.14097064e-01, 2.56904200e+00, -0.06613399, -3.55524840e-01}, {-3.30779101e-02, -0.06613399, -1.04594396e+01, 2.28750940e-02}, {-4.46414555e-02, -3.55524840e-01, 2.28750940e-02, -1.68257280e+00}}, {{1.36203547e-02, -5.87986418e-02, -2.03004280e-13, -9.41918320e-03}, {-5.87986418e-02, 5.04209748e-01, -4.40835235e-02, 2.61511601e-01}, {-2.03004280e-13, -4.40835235e-02, -2.20690336e+00, -1.18727250e-12}, {-9.41918320e-03, 2.61511601e-01, -1.18727250e-12, -3.55016683e-01}}, {{-5.97507320e-04, -2.20716631e-03, -7.08797170e-16, 8.24885520e-03}, {-2.20716631e-03, -9.62764242e-03, 1.13318725e+00, 6.46865963e-02}, {-7.08797170e-16, 1.13318725e+00, -3.33103600e+00, -4.14512175e-15}, {8.24885520e-03, 6.46865963e-02, -4.14512175e-15, -1.69890236e-01}}, {{8.32030847e-03, 2.59880304e-02, -4.78314158e-02, -5.75392575e-03}, {2.59880304e-02, 8.27752972e-02, -3.76137106e-01, 9.69923918e-01}, {-4.78314158e-02, -3.76137106e-01, -1.34813792e+00, 9.42750263e-01}, {-5.75392575e-03, 9.69923918e-01, 9.42750263e-01, -2.16870146e-01}}}; SPACETIMELOOP3(sigma, mu, nu) { if (std::abs(Gamma_nubhlight[sigma][mu][nu]) > 0.1) { if (GetDifference(Gamma[sigma][mu][nu], Gamma_nubhlight[sigma][mu][nu]) > 0.1) { printf("%d %d %d: %g %g\n", sigma, mu, nu, Gamma[sigma][mu][nu], Gamma_nubhlight[sigma][mu][nu]); update += 1; } } else { if (std::abs(Gamma[sigma][mu][nu]) > 0.1) { printf("%d %d %d: %g %g\n", sigma, mu, nu, Gamma[sigma][mu][nu], Gamma_nubhlight[sigma][mu][nu]); update += 1; } } } }, n_wrong); REQUIRE(n_wrong == 0); } } } }
44.872777
90
0.470642
[ "geometry", "object" ]
2ffede30e8768c6cffb16f75b21cebf61bd25d6c
3,692
cc
C++
chrome/browser/ui/views/hung_renderer_view_browsertest.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/ui/views/hung_renderer_view_browsertest.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/ui/views/hung_renderer_view_browsertest.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/hung_renderer_view.h" #include <string> #include "base/bind_helpers.h" #include "chrome/browser/platform_util.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_commands.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/tab_dialogs.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/browser/ui/test/test_browser_dialog.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_delegate.h" #include "content/public/test/browser_test_utils.h" // Interactive UI tests for the hung renderer (aka page unresponsive) dialog. class HungRendererDialogViewBrowserTest : public DialogBrowserTest { public: HungRendererDialogViewBrowserTest() {} // Normally the dialog only shows multiple WebContents when they're all part // of the same process, but that's hard to achieve in a test. void AddWebContents(HungRendererDialogView* dialog, content::WebContents* web_contents) { HungPagesTableModel* model = dialog->hung_pages_table_model_.get(); model->tab_observers_.push_back( std::make_unique<HungPagesTableModel::WebContentsObserverImpl>( model, web_contents)); if (model->observer_) model->observer_->OnModelChanged(); dialog->UpdateLabels(); } // DialogBrowserTest: void ShowUi(const std::string& name) override { auto* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); HungRendererDialogView::Show(web_contents, web_contents->GetRenderViewHost()->GetWidget(), base::DoNothing::Repeatedly()); if (name == "MultiplePages") { auto* web_contents2 = chrome::DuplicateTabAt(browser(), 0); AddWebContents(HungRendererDialogView::GetInstance(), web_contents2); } } private: DISALLOW_COPY_AND_ASSIGN(HungRendererDialogViewBrowserTest); }; // TODO(tapted): The framework sometimes doesn't pick up the spawned dialog and // the ASSERT_EQ in TestBrowserUi::ShowAndVerifyUi() fails. This seems to only // happen on the bots. So these tests are disabled for now. IN_PROC_BROWSER_TEST_F(HungRendererDialogViewBrowserTest, DISABLED_InvokeUi_Default) { ShowAndVerifyUi(); } IN_PROC_BROWSER_TEST_F(HungRendererDialogViewBrowserTest, DISABLED_InvokeUi_MultiplePages) { ShowAndVerifyUi(); } // This is a regression test for https://crbug.com/855369. IN_PROC_BROWSER_TEST_F(HungRendererDialogViewBrowserTest, InactiveWindow) { // Simulate creation of the dialog, without initializing or showing it yet. // This is what happens when HungRendererDialogView::ShowForWebContents // returns early if the frame or the dialog are not active. HungRendererDialogView::Create(browser()->window()->GetNativeWindow()); EXPECT_TRUE(HungRendererDialogView::GetInstance()); // Simulate the renderer becoming responsive again. content::WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); content::RenderWidgetHost* render_widget_host = web_contents->GetRenderWidgetHostView()->GetRenderWidgetHost(); content::WebContentsDelegate* web_contents_delegate = browser(); web_contents_delegate->RendererResponsive(web_contents, render_widget_host); }
41.954545
80
0.749187
[ "model" ]
6405a749a596d0b6e430d009019c0f9b35e7552b
3,497
cpp
C++
training/POJ/3686.cpp
voleking/ICPC
fc2cf408fa2607ad29b01eb00a1a212e6d0860a5
[ "MIT" ]
68
2017-10-08T04:44:23.000Z
2019-08-06T20:15:02.000Z
training/POJ/3686.cpp
voleking/ICPC
fc2cf408fa2607ad29b01eb00a1a212e6d0860a5
[ "MIT" ]
null
null
null
training/POJ/3686.cpp
voleking/ICPC
fc2cf408fa2607ad29b01eb00a1a212e6d0860a5
[ "MIT" ]
18
2017-05-31T02:52:23.000Z
2019-07-05T09:18:34.000Z
// written at 16:21 on 22 Jan 2017 #include <cctype> #include <cfloat> #include <climits> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <string> #include <sstream> #include <algorithm> #include <complex> #include <deque> #include <list> #include <map> #include <queue> #include <set> #include <stack> #include <vector> #include <utility> #include <bitset> #define IOS std::ios::sync_with_stdio(false); std::cin.tie(nullptr); std::cout.tie(nullptr); // #define __DEBUG__ #ifdef __DEBUG__ #define DEBUG(...) printf(__VA_ARGS__) #else #define DEBUG(...) #endif #define filename "" #define setfile() freopen(filename".in", "r", stdin); freopen(filename".ans", "w", stdout); #define resetfile() freopen("/dev/tty", "r", stdin); freopen("/dev/tty", "w", stdout); system("more " filename".ans"); #define rep(i, j, k) for (int i = j; i < k; ++i) #define irep(i, j, k) for (int i = j - 1; i >= k; --i) using namespace std; template <typename T> inline T sqr(T a) { return a * a;}; typedef long long ll; typedef unsigned long long ull; typedef long double ld; typedef pair<int, int > Pii; const double pi = acos(-1.0); const int INF = INT_MAX; const ll LLINF = LLONG_MAX; const int MAX_V = 3e3 + 10; struct edge { int to, cap, cost, rev; }; vector<edge> G[MAX_V]; int V, prevv[MAX_V], preve[MAX_V], h[MAX_V], dist[MAX_V]; int t, N, M, z; void add_edge(int from, int to, int cap, int cost) { // cout << from << "->" << to << " " << cap << " " << cost << endl; G[from].push_back((edge){to, cap, cost, (int)G[to].size()}); G[to].push_back((edge){from, 0, -cost, (int)G[from].size() - 1}); } int min_cost_flow(int s, int t, int f) { int res = 0; memset(h, 0, sizeof h); while (f > 0) { priority_queue<Pii, vector<Pii>, greater<Pii> > que; fill(dist, dist + V, INF / 3); dist[s] = 0; que.push(Pii(0, s)); while (!que.empty()) { Pii p = que.top(); que.pop(); int v = p.second; if (dist[v] < p.first) continue; rep(i, 0, G[v].size()) { edge &e = G[v][i]; if (e.cap > 0 && dist[e.to] > dist[v] + e.cost + h[v] - h[e.to]) { dist[e.to] = dist[v] + e.cost + h[v] - h[e.to]; prevv[e.to] = v; preve[e.to] = i; que.push(Pii(dist[e.to], e.to)); } } } if (dist[t] == INF / 3) return -1; rep(v, 0, V) h[v] += dist[v]; int d = f; for (int v = t; v != s; v = prevv[v]) d = min(d, G[prevv[v]][preve[v]].cap); f -= d; res += h[t] * d; for (int v = t; v != s; v = prevv[v]) { edge &e = G[prevv[v]][preve[v]]; e.cap -= d; G[v][e.rev].cap += d; } } return res; } int main(int argc, char const *argv[]) { // 0 ~ N - 1 toy // N ~ 2N - 1 fact1 // ... // MN ~ (M + 1)N - 1 factM scanf("%d", &t); while (t--) { scanf("%d%d", &N, &M); int s = (M + 1) * N, t = s + 1; V = t + 1; rep(i, 0, V) G[i].clear(); rep(i, 0, N) add_edge(s, i, 1, 0); rep(i, N, (M + 1) * N) add_edge(i, t, 1, 0); rep(i, 0, N) rep(j, 0, M) { scanf("%d", &z); rep(k, 0, N) add_edge(i, (j + 1) * N + k, 1, (k + 1) * z); } printf("%.6f\n", (double)min_cost_flow(s, t, N) / N); } return 0; }
28.900826
118
0.495854
[ "vector" ]
640707b9f739c3f4c47475aea0bb7d872074d98e
2,808
cpp
C++
example/GTest.cpp
Ambrou/GUnit
cd39485f0821d319357a5a72471c40606c9cb2c8
[ "BSL-1.0" ]
189
2017-01-06T19:50:24.000Z
2022-03-29T06:19:02.000Z
example/GTest.cpp
Ambrou/GUnit
cd39485f0821d319357a5a72471c40606c9cb2c8
[ "BSL-1.0" ]
46
2017-04-23T17:17:44.000Z
2022-03-18T10:18:30.000Z
example/GTest.cpp
Ambrou/GUnit
cd39485f0821d319357a5a72471c40606c9cb2c8
[ "BSL-1.0" ]
46
2017-01-02T12:02:45.000Z
2022-02-27T10:03:14.000Z
// // Copyright (c) 2016-2017 Kris Jusiak (kris at jusiak dot net) // // 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) // #include "GUnit/GTest.h" #include "GUnit/GMake.h" struct interface { virtual ~interface() = default; virtual void foo(int) const = 0; virtual void bar(int, const std::string&) const = 0; }; class example { public: example(int data, interface& i) : data(data), i(i) {} void update() { i.foo(42); i.bar(1, "str"); } auto get_data() const { return data; } private: int data = {}; interface& i; }; class example_no_data { public: explicit example_no_data(interface& i) : i(i) {} void update() { i.foo(42); i.bar(1, "str"); } private: interface& i; }; //////////////////////////////////////////////////////////////////////////////// GTEST("Simple Test", "[True/False should be True/False]") { EXPECT_TRUE(true); EXPECT_FALSE(false); } GTEST("Vector test") { std::vector<int> sut{}; EXPECT_TRUE(sut.empty()); SHOULD("increase the size after a push back") { sut.push_back(42); EXPECT_EQ(1u, sut.size()); } SHOULD("increase the size after a emplace back") { sut.emplace_back(42); EXPECT_EQ(1u, sut.size()); } DISABLED_SHOULD("disabled should") {} SHOULD("do nothing") {} } class VectorTest : public testing::Test { protected: void SetUp() override { sut.push_back(42); } std::vector<int> sut; }; GTEST(VectorTest, "[Using Test]") { EXPECT_EQ(1u, sut.size()); // from VectorTest::SetUp sut.push_back(77); // SetUp SHOULD("increase the size after a emplace back") { EXPECT_EQ(2u, sut.size()); sut.push_back(21); EXPECT_EQ(3u, sut.size()); } } GTEST(example) { // SetUp - will be run for each SHOULD section and it will create sut and // mocks if possible using namespace testing; std::tie(sut, mocks) = make<SUT, StrictGMock>(42); SHOULD("make simple example") { EXPECT_EQ(42, sut->get_data()); EXPECT_CALL(mock<interface>(), (foo)(42)).Times(1); EXPECT_CALL(mock<interface>(), (bar)(_, "str")); sut->update(); } SHOULD("override example") { std::tie(sut, mocks) = make<SUT, NaggyGMock>(77); EXPECT_EQ(77, sut->get_data()); EXPECT_CALL(mock<interface>(), (foo)(42)).Times(1); EXPECT_CALL(mock<interface>(), (bar)(_, "str")); sut->update(); } // TearDown } GTEST(example_no_data) { // SetUp - will be run for each SHOULD section and it will create sut and // mocks if possible using namespace testing; SHOULD("make simple example") { EXPECT_CALL(mock<interface>(), (foo)(42)).Times(1); EXPECT_CALL(mock<interface>(), (bar)(_, "str")); sut->update(); } // TearDown }
21.6
80
0.612892
[ "vector" ]
640727529ba758e4b0b54d146375297c1adc7c74
568
hpp
C++
include/main_menu_scene.hpp
BokorBence/Jack-O-Lector
dde9a10be4b89ea1634b7945a99de7ea41862051
[ "MIT" ]
null
null
null
include/main_menu_scene.hpp
BokorBence/Jack-O-Lector
dde9a10be4b89ea1634b7945a99de7ea41862051
[ "MIT" ]
11
2021-09-30T14:25:02.000Z
2021-12-07T12:04:23.000Z
include/main_menu_scene.hpp
BokorBence/Jack-O-Lector
dde9a10be4b89ea1634b7945a99de7ea41862051
[ "MIT" ]
1
2021-10-03T13:23:39.000Z
2021-10-03T13:23:39.000Z
#pragma once #include "scene.hpp" #include "button.hpp" #include "SDL_image.h" #include "SDL.h" #include <vector> #include <string> class Main_menu_scene : public Scene { public: std::string title; Button* level_select; Button* quit; SDL_Surface* background; SDL_Surface* menu_title; SDL_Texture* background_tex; SDL_Texture* menu_title_tex; SDL_Rect title_rect; std::string background_path; Main_menu_scene(SDL_Renderer*, int*, Scene*); void draw_scene() override; void handle_events(const SDL_Event &) override; private: int* quitflag; Scene* next; };
21.037037
48
0.758803
[ "vector" ]
6412c90d004502f2717f0b8c93ea25c5f06d6567
831
cpp
C++
src/io/github/technicalnotes/programming/basics/12-function.cpp
chiragbhatia94/programming-cpp
efd6aa901deacf416a3ab599e6599845a8111eac
[ "MIT" ]
null
null
null
src/io/github/technicalnotes/programming/basics/12-function.cpp
chiragbhatia94/programming-cpp
efd6aa901deacf416a3ab599e6599845a8111eac
[ "MIT" ]
null
null
null
src/io/github/technicalnotes/programming/basics/12-function.cpp
chiragbhatia94/programming-cpp
efd6aa901deacf416a3ab599e6599845a8111eac
[ "MIT" ]
null
null
null
#include "bits/stdc++.h" // brings all the standard c++ functions // #include <iostream> // #include <string> // #include <vector> // #include <numeric> // #include <functional> using namespace std; // FUNCTION DECLARATION double addNumbers(double num1, double num2); int addN(int a, int n); // END FUNCTION DECLARATION int main() { cout << addNumbers(12, 12); std::function<int(int)> fib = [&fib](int n) { return (n < 2) ? n : fib(n - 1) + fib(n - 2); }; cout << endl << fib(8) << endl; function<int(int)> add2 = bind(addN, placeholders::_1, 2); cout << "5 + 2 = " << add2(5); return 0; } // FUNCTIONS double addNumbers(double num1, double num2) { return num1 + num2; } int addN(int a, int n) { return a + n; } // END FUNCTIONS
19.785714
66
0.561974
[ "vector" ]