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
5dda64e18a7fe9bfc8c8bd46d0577c4fb57a3cc9
1,199
cpp
C++
cpp/Problem-12.cpp
shivamacs/solve-project-euler
296ecc9098417c413366e01d4aa125b9acac31b1
[ "MIT" ]
null
null
null
cpp/Problem-12.cpp
shivamacs/solve-project-euler
296ecc9098417c413366e01d4aa125b9acac31b1
[ "MIT" ]
null
null
null
cpp/Problem-12.cpp
shivamacs/solve-project-euler
296ecc9098417c413366e01d4aa125b9acac31b1
[ "MIT" ]
null
null
null
/* The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... Let us list the factors of the first seven triangle numbers: 1: 1 3: 1,3 6: 1,2,3,6 10: 1,2,5,10 15: 1,3,5,15 21: 1,3,7,21 28: 1,2,4,7,14,28 We can see that 28 is the first triangle number to have over five divisors. What is the value of the first triangle number to have over five hundred divisors? */ #include <bits/stdc++.h> using namespace std; int main() { vector<int> divisors; long triangleNum = 0; int n = 1; while (divisors.size() <= 501) { divisors.clear(); triangleNum += n; for (int i=1;i<=sqrt(triangleNum);i++) { if (triangleNum%i == 0) { if (triangleNum/i == i) divisors.push_back(i); else { divisors.push_back(i); divisors.push_back(triangleNum/i); } } } if (divisors.size() > 500) cout<<triangleNum<<endl; n++; } }
25.510638
147
0.53628
[ "vector" ]
5ddaa0d44a36f4e33771a556cb951d53d24e2e20
4,400
cpp
C++
src/video/drivers/pango_video.cpp
hyhyhy666/Pangolin
27abebdd1aa004a0ffb0b96b52319a816fd89574
[ "MIT" ]
25
2016-06-16T13:21:05.000Z
2021-01-05T12:03:02.000Z
src/video/drivers/pango_video.cpp
hyhyhy666/Pangolin
27abebdd1aa004a0ffb0b96b52319a816fd89574
[ "MIT" ]
1
2022-02-27T07:12:34.000Z
2022-02-27T07:12:34.000Z
src/video/drivers/pango_video.cpp
hyhyhy666/Pangolin
27abebdd1aa004a0ffb0b96b52319a816fd89574
[ "MIT" ]
23
2016-06-17T01:49:13.000Z
2022-01-24T13:59:31.000Z
/* This file is part of the Pangolin Project. * http://github.com/stevenlovegrove/Pangolin * * Copyright (c) 2014 Steven Lovegrove * * 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 <pangolin/video/drivers/pango_video.h> #include <pangolin/compat/bind.h> namespace pangolin { const std::string pango_video_type = "raw_video"; PangoVideo::PangoVideo(const std::string& filename, bool realtime) : reader(filename, realtime), frame_id(-1) { src_id = FindSource(); if(src_id == -1) { throw pangolin::VideoException("No appropriate video streams found in log."); } } PangoVideo::~PangoVideo() { } size_t PangoVideo::SizeBytes() const { return size_bytes; } const std::vector<StreamInfo>& PangoVideo::Streams() const { return streams; } void PangoVideo::Start() { } void PangoVideo::Stop() { } bool PangoVideo::GrabNext( unsigned char* image, bool /*wait*/ ) { if(reader.ReadToSourcePacketAndLock(src_id)) { // read this frames actual data reader.Read((char*)image, size_bytes); reader.ReleaseSourcePacketLock(src_id); ++frame_id; return true; }else{ return false; } } bool PangoVideo::GrabNewest( unsigned char* image, bool wait ) { return GrabNext(image, wait); } const json::value& PangoVideo::DeviceProperties() const { if(src_id >=0) { return reader.Sources()[src_id].info["device"]; }else{ throw std::runtime_error("Not initialised"); } } const json::value& PangoVideo::FrameProperties() const { if(src_id >=0) { return reader.Sources()[src_id].meta; }else{ throw std::runtime_error("Not initialised"); } } int PangoVideo::GetCurrentFrameId() const { return frame_id; } int PangoVideo::GetTotalFrames() const { return std::numeric_limits<int>::max()-1; } int PangoVideo::Seek(int /*frameid*/) { // TODO: Implement seek return -1; } int PangoVideo::FindSource() { for(PacketStreamSourceId src_id=0; src_id < reader.Sources().size(); ++src_id) { const PacketStreamSource& src = reader.Sources()[src_id]; try { if( !src.driver.compare(pango_video_type) ) { // Read sources header size_bytes = 0; device_properties = src.info["device"]; const json::value& json_streams = src.info["streams"]; const size_t num_streams = json_streams.size(); for(size_t i=0; i<num_streams; ++i) { const json::value& json_stream = json_streams[i]; StreamInfo si( VideoFormatFromString( json_stream["encoding"].get<std::string>() ), json_stream["width"].get<int64_t>(), json_stream["height"].get<int64_t>(), json_stream["pitch"].get<int64_t>(), (unsigned char*)0 + json_stream["offset"].get<int64_t>() ); size_bytes += si.SizeBytes(); streams.push_back(si); } return src_id; } }catch(...) { pango_print_info("Unable to parse PacketStream Source. File version incompatible.\n"); } } return -1; } }
26.829268
98
0.624773
[ "vector" ]
5ddbbe00387ec309e851eb250c469e55f50520f7
1,521
hpp
C++
cmake/external/coremltools/mlmodel/src/NeuralNetworkBuffer.hpp
fushwLZU/onnxruntime_test
7ee82dde9150dc0d3014c06a82eabdecb989f2f3
[ "MIT" ]
3
2018-10-02T17:23:01.000Z
2020-08-15T04:47:07.000Z
mlmodel/src/NeuralNetworkBuffer.hpp
holzschu/coremltools
5ece9069a1487d5083f00f56afe07832d88e3dfa
[ "BSD-3-Clause" ]
75
2020-11-24T05:37:45.000Z
2022-02-25T15:14:23.000Z
mlmodel/src/NeuralNetworkBuffer.hpp
holzschu/coremltools
5ece9069a1487d5083f00f56afe07832d88e3dfa
[ "BSD-3-Clause" ]
1
2021-05-07T15:38:20.000Z
2021-05-07T15:38:20.000Z
// // NeuralNetworkBuffer.hpp // CoreML // // Created by Bhushan Sonawane on 11/8/19. // Copyright © 2019 Apple Inc. All rights reserved. // #pragma once #include <fstream> #include <string> #include <vector> namespace NNBuffer { enum class BufferMode { Write=0, Append, Read }; // // NeuralNetworkBuffer - Network parameter read-write management to file // Current management policy // Each parameter is written to binary file in following order. // [Length of data (size_t), Data type of data (size_t), data (length of data * size of data type)] // class NeuralNetworkBuffer { public: // Must be constructed with file path to store parameters NeuralNetworkBuffer(const std::string& bufferFilePath, BufferMode mode=BufferMode::Write); ~NeuralNetworkBuffer(); NeuralNetworkBuffer(const NeuralNetworkBuffer&) = delete; NeuralNetworkBuffer(NeuralNetworkBuffer&&) = delete; NeuralNetworkBuffer& operator=(const NeuralNetworkBuffer&) = delete; NeuralNetworkBuffer& operator=(NeuralNetworkBuffer&&) = delete; // Stores given buffer and returns offset in buffer file template<class T> uint64_t AddBuffer(const std::vector<T>& buffer); // Reads buffer from given offset and stores in vector // passed by reference. // Note that, this routine resizes the given vector. template<class T> void GetBuffer(uint64_t offset, std::vector<T>& buffer); private: std::string bufferFilePath; std::fstream bufferStream; }; } // namespace NNBuffer
27.160714
99
0.720579
[ "vector" ]
5dedde5e3d075781fc38ed5defa9d5a519a011a1
4,934
hh
C++
sniper/common/misc/FSBAllocator.hh
kleberkruger/donuts
99a7c5885fcb6d252a47a4cb74ca714f8ba12ca6
[ "MIT" ]
1
2021-04-22T05:27:08.000Z
2021-04-22T05:27:08.000Z
sniper/common/misc/FSBAllocator.hh
kleberkruger/donuts
99a7c5885fcb6d252a47a4cb74ca714f8ba12ca6
[ "MIT" ]
null
null
null
sniper/common/misc/FSBAllocator.hh
kleberkruger/donuts
99a7c5885fcb6d252a47a4cb74ca714f8ba12ca6
[ "MIT" ]
1
2021-10-04T13:53:51.000Z
2021-10-04T13:53:51.000Z
/*=========================================================================== This library is released under the MIT license. See FSBAllocator.html for further information and documentation. Copyright (c) 2008-2011 Juha Nieminen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. =============================================================================*/ #ifndef INCLUDE_FSBALLOCATOR_HH #define INCLUDE_FSBALLOCATOR_HH #include "log.h" #include <new> #include <vector> #include <typeinfo> #include <cxxabi.h> class UnspecifiedType { }; template<unsigned ElemSize, unsigned MaxElem = 0, typename TypeToAlloc = UnspecifiedType> class FSBAllocator_ElemAllocator { typedef std::size_t Data_t; static const Data_t BlockElements = 512; static const Data_t DSize = sizeof(Data_t); static const Data_t ElemSizeInDSize = (ElemSize + (DSize-1)) / DSize; static const Data_t UnitSizeInDSize = ElemSizeInDSize + 1; static const Data_t BlockSize = BlockElements*UnitSizeInDSize; class MemBlock { Data_t* block; Data_t firstFreeUnitIndex, allocatedElementsAmount, endIndex; public: MemBlock(): block(new Data_t[BlockSize]), firstFreeUnitIndex(Data_t(-1)), allocatedElementsAmount(0) {} bool isFull() const { return allocatedElementsAmount == BlockElements; } void clear() { firstFreeUnitIndex = Data_t(-1); } void* allocate(Data_t vectorIndex) { if(firstFreeUnitIndex == Data_t(-1)) { if(allocatedElementsAmount == 0) { endIndex = 0; } Data_t* retval = block + endIndex; endIndex += UnitSizeInDSize; retval[ElemSizeInDSize] = vectorIndex; ++allocatedElementsAmount; return retval; } else { Data_t* retval = block + firstFreeUnitIndex; firstFreeUnitIndex = *retval; ++allocatedElementsAmount; return retval; } } void deallocate(Data_t* ptr) { *ptr = firstFreeUnitIndex; firstFreeUnitIndex = ptr - block; if(--allocatedElementsAmount == 0) clear(); } }; struct BlocksVector { std::vector<MemBlock> data; BlocksVector() { data.reserve(1024); } ~BlocksVector() { for(std::size_t i = 0; i < data.size(); ++i) data[i].clear(); } }; BlocksVector blocksVector; std::vector<Data_t> blocksWithFree; public: void* allocate() { if(blocksWithFree.empty()) { blocksWithFree.push_back(blocksVector.data.size()); blocksVector.data.push_back(MemBlock()); if (MaxElem) { int status; char *nameoftype = abi::__cxa_demangle(typeid(TypeToAlloc).name(), 0, 0, &status); LOG_ASSERT_ERROR(blocksVector.data.size() * BlockElements <= MaxElem, "Maximum number of blocks exceeded for allocator of %d-sized objects of %s", ElemSize, nameoftype); free(nameoftype); } } const Data_t index = blocksWithFree.back(); MemBlock& block = blocksVector.data[index]; void* retval = block.allocate(index); if(block.isFull()) blocksWithFree.pop_back(); return retval; } void deallocate(void* ptr) { if(!ptr) return; Data_t* unitPtr = (Data_t*)ptr; const Data_t blockIndex = unitPtr[ElemSizeInDSize]; MemBlock& block = blocksVector.data[blockIndex]; if(block.isFull()) blocksWithFree.push_back(blockIndex); block.deallocate(unitPtr); } }; #endif
29.90303
184
0.599311
[ "vector" ]
5df88074d2f7d51c3e243c598bef2ba91b2a2d75
3,048
cpp
C++
data/dailyCodingProblem292.cpp
vidit1999/daily_coding_problem
b90319cb4ddce11149f54010ba36c4bd6fa0a787
[ "MIT" ]
2
2020-09-04T20:56:23.000Z
2021-06-11T07:42:26.000Z
data/dailyCodingProblem728.cpp
vidit1999/daily_coding_problem
b90319cb4ddce11149f54010ba36c4bd6fa0a787
[ "MIT" ]
null
null
null
data/dailyCodingProblem728.cpp
vidit1999/daily_coding_problem
b90319cb4ddce11149f54010ba36c4bd6fa0a787
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; /* A teacher must divide a class of students into two teams to play dodgeball. Unfortunately, not all the kids get along, and several refuse to be put on the same team as that of their enemies. Given an adjacency list of students and their enemies, write an algorithm that finds a satisfactory pair of teams, or returns False if none exists. For example, given the following enemy graph you should return the teams {0, 1, 4, 5} and {2, 3}. students = { 0: [3], 1: [2], 2: [1, 4], 3: [0, 4, 5], 4: [2, 3], 5: [3] } On the other hand, given the input below, you should return False. students = { 0: [3], 1: [2], 2: [1, 3, 4], 3: [0, 2, 4, 5], 4: [2, 3], 5: [3] } */ bool checkSafeSet( int student, unordered_set<int>& uset, vector<unordered_set<int>>& students ){ for(auto it : students[student]){ if(uset.find(it) != uset.end()){ return false; } } return true; } bool friendlyTeamsHelper( int student, unordered_set<int>& first_team, unordered_set<int>& second_team, pair<unordered_set<int>, unordered_set<int>>& ans, vector<unordered_set<int>>& students ){ if(student == students.size()){ ans = {first_team, second_team}; return true; } // check if first team is safe if(checkSafeSet(student, first_team, students)){ // insert into teams accordingly first_team.insert(student); for(int i : students[student]){ second_team.insert(i); } if(friendlyTeamsHelper(student+1, first_team, second_team, ans, students)){ return true; } // not work then backtrack first_team.erase(student); for(int i : students[student]){ second_team.erase(i); } } // check if second team is safe if(checkSafeSet(student, second_team, students)){ // insert into teams accordingly second_team.insert(student); for(int i : students[student]){ first_team.insert(i); } if(friendlyTeamsHelper(student+1, first_team, second_team, ans, students)){ return true; } // not work then backtrack second_team.erase(student); for(int i : students[student]){ first_team.erase(i); } } return false; } pair<unordered_set<int>, unordered_set<int>> friendlyTeams( vector<unordered_set<int>>& students ){ unordered_set<int> first_team, second_team; pair<unordered_set<int>, unordered_set<int>> ans; friendlyTeamsHelper(0, first_team, second_team, ans, students); return ans; } void testFunc(vector<vector<unordered_set<int>>> v){ for(auto students : v){ auto ans = friendlyTeams(students); if(ans.first.empty() && ans.second.empty()){ cout << "No team possible."; } else{ cout << "First Team : "; for(int i : ans.first){ cout << i << " "; } cout << "\nSecond Team : "; for(int i : ans.second){ cout << i << " "; } } cout << "\n\n"; } } // main function int main(){ testFunc({ { {3}, {2}, {1, 3, 4}, {0, 2, 4, 5}, {2, 3}, {3} }, { {3}, {2}, {1, 4}, {0, 4, 5}, {2, 3}, {3}, } }); return 0; }
18.814815
77
0.631562
[ "vector" ]
5df96c5b9d1837e693a767f1f0faf29a1ae30d39
7,421
cpp
C++
src/phyx-1.01/src/main_revcomp.cpp
jlanga/smsk_selection
08070c6d4a6fbd9320265e1e698c95ba80f81123
[ "MIT" ]
4
2021-07-18T05:20:20.000Z
2022-01-03T10:22:33.000Z
src/phyx-1.01/src/main_revcomp.cpp
jlanga/smsk_selection
08070c6d4a6fbd9320265e1e698c95ba80f81123
[ "MIT" ]
1
2017-08-21T07:26:13.000Z
2018-11-08T13:59:48.000Z
src/phyx-1.01/src/main_revcomp.cpp
jlanga/smsk_orthofinder
08070c6d4a6fbd9320265e1e698c95ba80f81123
[ "MIT" ]
2
2021-07-18T05:20:26.000Z
2022-03-31T18:23:31.000Z
#include <algorithm> #include <iostream> #include <fstream> #include <string> #include <vector> #include <cstring> #include <time.h> #include <stdlib.h> #include <getopt.h> using namespace std; #include "seq_reader.h" #include "sequence.h" #include "seq_utils.h" #include "utils.h" #include "log.h" #include "edlib.h" void print_help() { cout << "Reverse complement sequences from nexus, phylip, or fastq to fasta." << endl; cout << "Can read from stdin or file, but output is fasta." << endl; cout << endl; cout << "Usage: pxrevcomp [OPTION]... [FILE]..."<<endl; cout << endl; cout << " -s, --seqf=FILE input sequence file, stdin otherwise"<<endl; cout << " -i, --ids=IDS a comma sep list of ids to flip (NO SPACES!)" << endl; cout << " -g, --guess EXPERIMENTAL: guess whether there are seqs that need to be " << endl; cout << " rev comp. uses edlib library on first seq" << endl; cout << " -p, --pguess EXPERIMENTAL: progressively guess " << endl; cout << " -m, --sguess EXPERIMENTAL: sampled guess " << endl; cout << " -o, --outf=FILE output sequence file, stout otherwise"<<endl; cout << " -h, --help display this help and exit"<<endl; cout << " -V, --version display version and exit"<<endl; cout << endl; cout << "Report bugs to: <https://github.com/FePhyFoFum/phyx/issues>" <<endl; cout << "phyx home page: <https://github.com/FePhyFoFum/phyx>"<<endl; } string versionline("pxrevcomp 0.11\nCopyright (C) 2017 FePhyFoFum\nLicense GPLv3\nwritten by Stephen A. Smith (blackrim)"); static struct option const long_options[] = { {"seqf", required_argument, NULL, 's'}, {"ids", required_argument, NULL, 'i'}, {"guess", no_argument, NULL, 'g'}, {"pguess", no_argument, NULL, 'p'}, {"sguess", no_argument, NULL, 'm'}, {"outf", required_argument, NULL, 'o'}, {"help", no_argument, NULL, 'h'}, {"version", no_argument, NULL, 'V'}, {NULL, 0, NULL, 0} }; bool reverse_it_or_not(vector<Sequence> & seqs, Sequence comp_seq){ int best_distance = 10000000; int best_dis_rev = 100000000; string comp = comp_seq.get_sequence(); string revcomp = comp_seq.reverse_complement(); for (unsigned int i=0;i<seqs.size();i++){ EdlibAlignResult result = edlibAlign(comp.c_str(), comp.length(), seqs[i].get_sequence().c_str(), seqs[i].get_sequence().length(), edlibNewAlignConfig(best_distance, EDLIB_MODE_HW, EDLIB_TASK_DISTANCE)); if (result.editDistance < 0) continue; if (result.editDistance < best_distance) best_distance = result.editDistance; edlibFreeAlignResult(result); } for (unsigned int i=0;i<seqs.size();i++){ EdlibAlignResult result = edlibAlign(revcomp.c_str(), revcomp.length(), seqs[i].get_sequence().c_str(), seqs[i].get_sequence().length(), edlibNewAlignConfig(best_distance, EDLIB_MODE_HW, EDLIB_TASK_DISTANCE)); if (result.editDistance < 0) continue; if (result.editDistance < best_dis_rev) best_dis_rev = result.editDistance; edlibFreeAlignResult(result); } if (best_dis_rev < best_distance) return true; return false; } int main(int argc, char * argv[]) { srand (time(NULL)); log_call(argc, argv); bool fileset = false; bool outfileset = false; bool idsset = false; vector<string> ids; bool guess = false; bool pguess = false; bool sguess = false; double sguess_samplenum = 0.2; // 10% of them will be used for revcomp char * seqf = NULL; char * outf = NULL; char * idssc = NULL; while (1) { int oi = -1; int c = getopt_long(argc, argv, "s:i:o:mgphV", long_options, &oi); if (c == -1) { break; } switch(c) { case 's': fileset = true; seqf = strdup(optarg); check_file_exists(seqf); break; case 'i': idsset = true; idssc = strdup(optarg); break; case 'g': guess = true; break; case 'p': guess = true; pguess = true; break; case 'm': guess = true; sguess = true; break; case 'o': outfileset = true; outf = strdup(optarg); break; case 'h': print_help(); exit(0); case 'V': cout << versionline << endl; exit(0); default: print_error(argv[0], (char)c); exit(0); } } if (fileset && outfileset) { check_inout_streams_identical(seqf, outf); } if (idsset == true){ vector<string> tokens2; tokenize(idssc, tokens2, ","); for (unsigned int j=0; j < tokens2.size(); j++) { trim_spaces(tokens2[j]); ids.push_back(tokens2[j]); } } istream * pios = NULL; ostream * poos = NULL; ifstream * fstr = NULL; ofstream * ofstr = NULL; if (fileset == true) { fstr = new ifstream(seqf); pios = fstr; } else { pios = &cin; if (check_for_input_to_stream() == false) { print_help(); exit(1); } } if (outfileset == true) { ofstr = new ofstream(outf); poos = ofstr; } else { poos = &cout; } Sequence seq; string retstring; int ft = test_seq_filetype_stream(*pios,retstring); if (guess == false){ while (read_next_seq_from_stream(*pios,ft,retstring,seq)) { if(idsset == false || count(ids.begin(),ids.end(),seq.get_id())==1){ seq.perm_reverse_complement(); } (*poos) << seq.get_fasta(); } if (ft == 2) { if(idsset == false || count(ids.begin(),ids.end(),seq.get_id())==1){ seq.perm_reverse_complement(); } (*poos) << seq.get_fasta(); } }else{ bool first = true; vector<Sequence> done; //for pguess while (read_next_seq_from_stream(*pios,ft,retstring,seq)) { if (first == true){ done.push_back(seq); (*poos) << seq.get_fasta(); first = false; }else{ if (reverse_it_or_not(done, seq)){ seq.perm_reverse_complement(); } (*poos) << seq.get_fasta(); if(pguess){ done.push_back(seq); }else if(sguess){ double r = ((double) rand() / (RAND_MAX)); if (r < sguess_samplenum){ done.push_back(seq); } } } } if (ft == 2) { if (reverse_it_or_not(done, seq)){ seq.perm_reverse_complement(); } (*poos) << seq.get_fasta(); } } if (fileset) { fstr->close(); delete pios; } if (outfileset) { ofstr->close(); delete poos; } return EXIT_SUCCESS; }
31.578723
123
0.518798
[ "vector" ]
5dfdb35644c0475c74da120eb5d7271207c2be58
3,930
cpp
C++
Shoot/src/Button.cpp
franticsoftware/starports
d723404b20383949874868c251c60cfa06120fde
[ "MIT" ]
5
2016-11-13T08:13:57.000Z
2019-03-31T10:22:38.000Z
Shoot/src/Button.cpp
franticsoftware/starports
d723404b20383949874868c251c60cfa06120fde
[ "MIT" ]
null
null
null
Shoot/src/Button.cpp
franticsoftware/starports
d723404b20383949874868c251c60cfa06120fde
[ "MIT" ]
1
2016-12-23T11:25:35.000Z
2016-12-23T11:25:35.000Z
/* Amine Rehioui Created: September 3rd 2013 */ #include "Shoot.h" #include "Button.h" #include "Sprite.h" #include "InputManager.h" #include "EventManager.h" #include "LayoutComponent.h" namespace shoot { DEFINE_OBJECT(Button); //! Constructor Button::Button() : m_bPressed(false) // properties , m_bCheckBox(false) , m_bChecked(true) , m_bCustomBBox(false) , m_UIEnabled(true) { } //! serializes the entity to/from a PropertyStream void Button::Serialize(PropertyStream& stream) { super::Serialize(stream); stream.Serialize("UIEnabled", &m_UIEnabled); stream.Serialize("Command", &m_Command); stream.Serialize("CheckBox", &m_bCheckBox); stream.Serialize("CustomBBox", &m_bCustomBBox); } //! called during the initialization of the entity void Button::Init() { super::Init(); m_Icon = static_cast<Sprite*>(GetChildByName("Icon")); // Init bounding box if(!m_bCustomBBox) { if(Entity2D* pBG = static_cast<Entity2D*>(GetChildByName("BG"))) m_BoundingBox = pBG->GetBoundingBox() + pBG->GetPosition(); else if(m_Icon.IsValid()) m_BoundingBox = m_Icon->GetBoundingBox() + m_Icon->GetPosition(); } } //! called during the update of the entity void Button::Update() { if (!m_bVisible) return; if(InputManager::Instance()->IsTouchJustPressed(this)) { m_vOriginalPosition = m_vPosition; if (IsTouched()) { if (m_UIEnabled) SetPressed(true); InputManager::Instance()->RequestTouchFocus(this); } } else if (InputManager::Instance()->IsTouchPressed(this)) { if(m_bPressed && !IsTouched()) SetPressed(false); } else if (InputManager::Instance()->IsTouchJustReleased(this)) { if(!m_bPressed) return; if(m_bCheckBox) SetChecked(!m_bChecked); SetPressed(false); SendUIEvent(); } } //! returns true if the button is touched bool Button::IsTouched() const { if(auto layout = GetComponent<LayoutComponent>()) { auto _this = const_cast<Button*>(this); auto touchPos = InputManager::Instance()->GetRawTouchState().vPosition; auto transform = layout->Align(_this, m_vOriginalPosition); auto invTransform = Matrix44::Identity; transform.GetInverse(invTransform); auto invTouchPos = invTransform.TransformVect(Vector3::Create(touchPos, 0.0f)); return GetBoundingBox().Contains(invTouchPos.XY); } Matrix44 transformation = Matrix44::Identity; transformation.Translate(-Vector3::Create(m_vCenter.X, m_vCenter.Y, 0.0f)); transformation.Scale(Vector3::Create(m_vScale.X, m_vScale.Y, 1.0f)); transformation.Rotate(Vector3::Create(0.0f, 0.0f, m_fRotation*Math::DegToRadFactor)); transformation.Translate(Vector3::Create(m_vOriginalPosition.X, m_vOriginalPosition.Y, 0.0f)); if(Entity2D* p2DEntity = GetAncestor<Entity2D>()) transformation *= p2DEntity->GetWorldTransform(); Matrix44 inverse; if(transformation.GetInverse(inverse)) { Vector2 vTouchPos = InputManager::Instance()->GetTouchState().vPosition; Vector3 invTouchPos3D = inverse.TransformVect(Vector3::Create(vTouchPos.X, vTouchPos.Y, 0.0f)); Vector2 vInvTouchPos = Vector2::Create(invTouchPos3D.X, invTouchPos3D.Y); return GetBoundingBox().Contains(vInvTouchPos); } return false; } //! sends the UI event void Button::SendUIEvent() { UIEvent* pEvent = snew UIEvent(); pEvent->m_Sender = this; pEvent->m_Command = m_Command; pEvent->m_bChecked = m_bChecked; EventManager::Instance()->SendEvent(pEvent); } //! changes pressed status void Button::SetPressed(bool bPressed) { if(bPressed) m_vPosition = m_vOriginalPosition + Vector2::Create(5.0f, 5.0f); else m_vPosition = m_vOriginalPosition; m_bLocalTransformationMatrixDirty = true; m_bPressed = bPressed; } //! sets checked status void Button::SetChecked(bool bChecked) { if(m_Icon.IsValid()) m_Icon->SetCurrentFrame(bChecked ? 0 : 1); m_bChecked = bChecked; } }
24.5625
98
0.707379
[ "transform" ]
b908936491207f437bd2c436a7bdbd03fac217b5
794
hpp
C++
include/RED4ext/Scripting/Natives/Generated/game/ReplicatedShotData.hpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
42
2020-12-25T08:33:00.000Z
2022-03-22T14:47:07.000Z
include/RED4ext/Scripting/Natives/Generated/game/ReplicatedShotData.hpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
38
2020-12-28T22:36:06.000Z
2022-02-16T11:25:47.000Z
include/RED4ext/Scripting/Natives/Generated/game/ReplicatedShotData.hpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
20
2020-12-28T22:17:38.000Z
2022-03-22T17:19:01.000Z
#pragma once // This file is generated from the Game's Reflection data #include <cstdint> #include <RED4ext/Common.hpp> #include <RED4ext/Handle.hpp> #include <RED4ext/NativeTypes.hpp> #include <RED4ext/Scripting/Natives/Generated/Vector3.hpp> #include <RED4ext/Scripting/Natives/Generated/net/Time.hpp> namespace RED4ext { namespace game { struct Object; } namespace game { struct ReplicatedShotData { static constexpr const char* NAME = "gameReplicatedShotData"; static constexpr const char* ALIAS = NAME; net::Time timeStamp; // 00 TweakDBID attackId; // 08 WeakHandle<game::Object> target; // 10 Vector3 targetLocalOffset; // 20 uint8_t unk2C[0x30 - 0x2C]; // 2C }; RED4EXT_ASSERT_SIZE(ReplicatedShotData, 0x30); } // namespace game } // namespace RED4ext
25.612903
65
0.736776
[ "object" ]
b90fae9f1ec1eb0193cf88c9f7c140c04ac71931
34,892
cpp
C++
water/src/water/water.cpp
Ludophonic/JigLib
541ec63b345ccf01e58cce49eb2f73c21eaf6aa6
[ "Zlib" ]
10
2016-06-01T12:54:45.000Z
2021-09-07T17:34:37.000Z
water/src/water/water.cpp
Ludophonic/JigLib
541ec63b345ccf01e58cce49eb2f73c21eaf6aa6
[ "Zlib" ]
null
null
null
water/src/water/water.cpp
Ludophonic/JigLib
541ec63b345ccf01e58cce49eb2f73c21eaf6aa6
[ "Zlib" ]
4
2017-05-03T14:03:03.000Z
2021-01-04T04:31:15.000Z
//============================================================== // Copyright (C) 2004 Danny Chapman // danny@rowlhouse.freeserve.co.uk //-------------------------------------------------------------- // /// @file water.cpp // // Simulation of a liquid (typically water) in a container that also // contains a buoyant object. Implementation is based on // "Particle-Based Fluid Simulation for Interactive Applications" by // Matthias Muller et al., but with some modifications. // // Written around Dec 2004 // //============================================================== #include "water.hpp" #include "spatialgrid.hpp" #include "shapes.hpp" #include "graphics.hpp" #include "jiglib.hpp" #include <cmath> #include <cstdio> #include <cstdlib> // for RAND_MAX using namespace std; using namespace JigLib; tConfigFile * gConfigFile = 0; // window size int gWindowW; int gWindowH; // render individual particles or a filled in grid bool gRenderParticles; int gNRenderSamplesX; int gNRenderSamplesY; tScalar gRenderDensityMin; tScalar gRenderDensityMax; // x ranges from 0 to domainX tScalar gDomainX; // y ranges from 0 to domainY tScalar gDomainY; // width of the container - leave some space for movement tScalar gContainerWidth; tScalar gContainerHeight; // position of the bottom left hand corner of the container. tScalar gContainerX; tScalar gContainerY; // initial height of the fluid surface tScalar gInitialFluidHeight; // gravity - acceleration tVector2 gGravity; // fluid density - this is kg/m2 (since 2D) tScalar gDensity0; // number of moving particles int gNParticles; // gViscosity tScalar gViscosity; // relationship of pressure to density when using eq of state // P = gGasK((density/gDensity0)^2 - 1) tScalar gGasK; // integration gTimeStep - for simplicity (especially when using // verlet etc) this will be constant so doesn't need to be passed // around, at least within this file tScalar gTimeStep; // scale physics time tScalar gTimeScale; // radius of influence of each particle tScalar gParticleRadius; // mass of each particle - gets initialised at startup tScalar gParticleMass; // slight hack for the boundary - apply force proportional to this // when within gBoundaryForceScaleDist of the (lower?) boundary tScalar gBoundaryForceScale; tScalar gBoundaryForceScaleDist; // for the kernels tScalar gKernelH; tScalar gKernelH9; tScalar gKernelH6; tScalar gKernelH4; tScalar gKernelH3; tScalar gKernelH2; // normalising factors for the kernels tScalar gWPoly6Scale = 0.0f; tScalar gWSpikyScale = 0.0f; tScalar gWViscosityScale = 0.0f; tScalar gWLucyScale = 0.0f; // The array of gNParticles particles tParticle * gParticles = 0; // use a grid to speed up the integrals since we only need to use // nearby particles tSpatialGrid * gSpatialGrid = 0; // create an object on startup? bool gCreateObject; ::tRectangle * gRectangle = 0; // ratio of object density to the liquid tScalar gObjectDensityFrac; // bit hacky - extra force stopping objects getting "welded" tScalar gObjectBoundaryScale; // Extra buoyancy because of non-realistic pressure tScalar gObjectBuoyancyScale; // for user interaction - when the user clicks, record the mouse // position so we can track it afterwards enum tInteractionMode { INTERACTION_NONE, INTERACTION_BOX, INTERACTION_CONTAINER, INTERACTION_FOUNTAIN }; tInteractionMode gInteractionMode = INTERACTION_NONE; tVector2 gOldMousePos(0.0f, 0.0f); //============================================================== // A bunch of Kernels follow - not all of them get used but it's nice // to have a menu to choose from :) //============================================================== //============================================================== // WPoly6 //============================================================== inline tScalar WPoly6(const tVector2 & r) { tScalar r2 = r.GetLengthSq(); if (r2 > gKernelH2) return 0.0f; tScalar a = gKernelH2 - r2; return gWPoly6Scale * a * a * a; } //============================================================== // WPoly6Grad //============================================================== inline tVector2 WPoly6Grad(const tVector2 & r) { tScalar r2 = r.GetLengthSq(); if (r2 > gKernelH2) return tVector2(0.0f, 0.0f); const tScalar f = -6.0f * gWPoly6Scale; tScalar a = gKernelH2 - r2; tScalar b = f * a * a; return tVector2(b * r.x, b * r.y); } //============================================================== // WSpiky //============================================================== inline tScalar WSpiky(const tVector2 & R) { tScalar r2 = R.GetLengthSq(); if (r2 > gKernelH2) return 0.0f; tScalar a = gKernelH - Sqrt(r2); return gWSpikyScale * a * a * a; } //============================================================== // WSpikyGrad //============================================================== inline tVector2 WSpikyGrad(const tVector2 & R) { tScalar r2 = R.GetLengthSq(); if (r2 > gKernelH2) return tVector2(0.0f, 0.0f); static const tScalar minR2 = 1.0E-12; if (r2 < minR2) r2 = minR2; tScalar r = Sqrt(r2); tScalar a = -3.0f * gWSpikyScale * (gKernelH - r) * (gKernelH - r) / r; return tVector2(a * R.x, a * R.y); } //============================================================== // WViscosity //============================================================== inline tScalar WViscosity(const tVector2 & R) { tScalar r2 = R.GetLengthSq(); if (r2 > gKernelH2) return 0.0f; static const tScalar minR2 = 1.0E-12; if (r2 < minR2) r2 = minR2; tScalar r = Sqrt(r2); tScalar r3 = r * r * r; return gWViscosityScale * ( ( (-r3 / (2.0f * gKernelH3)) + (r2 / gKernelH2) + gKernelH / (2.0f * r)) - 1.0f); } //======================================================== // WViscosityLap //======================================================== inline tScalar WViscosityLap(const tVector2 & R) { tScalar r2 = R.GetLengthSq(); if (r2 > gKernelH2) return 0.0f; tScalar r = Sqrt(r2); return gWViscosityScale * (6.0f / gKernelH3) * (gKernelH - r); } //============================================================== // WLucy // My cat's called Lucy //============================================================== inline tScalar WLucy(const tVector2 & R) { tScalar r2 = R.GetLengthSq(); if (r2 > gKernelH2) return 0.0f; tScalar r = Sqrt(r2); tScalar a = (1.0f + 3.0f * r / gKernelH) * Cube(1 - r / gKernelH); return gWLucyScale * a; } //============================================================== // WLucyGrad // If you're feeling lazy: // http://www.calc101.com/webMathematica/derivatives.jsp // with // (1 + 3 * ((x^2 + y^2)^0.5)/H) * ((1 - ((x^2 + y^2)^0.5)/H)^3) //============================================================== inline tVector2 WLucyGrad(const tVector2 & R) { tScalar r2 = R.GetLengthSq(); if (r2 > gKernelH2) return tVector2(0.0f, 0.0f); tScalar r = Sqrt(r2); tScalar a = -12.0f * (gKernelH2 - 2.0f * r * gKernelH + r2) / gKernelH4; return tVector2(a * R.x, a * R.y); } //============================================================== // CalculatePressure //============================================================== inline tScalar CalculatePressure(tScalar density) { return gGasK * (Cube(density/gDensity0) - 1.0f); } //============================================================== // CalculateNewParticles //============================================================== void CalculateNewParticles() { tVector2 force; for (int i = 0 ; i < gNParticles ; ++i) { AddVector2(force, gParticles[i].mBodyForce, gParticles[i].mPressureForce, gParticles[i].mViscosityForce); // use verlet to integrate tScalar damping = 0.01f; // 0-1 tVector2 tmp = gParticles[i].mR; gParticles[i].mR += (1.0f - damping) * (gParticles[i].mR - gParticles[i].mOldR) + (gTimeStep * gTimeStep / gParticleMass) * force; gParticles[i].mOldR = tmp; // cache velocity as it's useful gParticles[i].mV = (gParticles[i].mR - gParticles[i].mOldR) / gTimeStep; } } //============================================================== // AddBoundaryForce // adds to the force var passed in //============================================================== inline void AddBoundaryForce(const tVector2 & pos, tVector2 & force, tScalar dist, tScalar scale) { tScalar delta = pos.y - gContainerY; if (delta < 0.0f) delta = 0.0f; if (delta < dist) force.y += scale * (1.0f - Sq(delta/dist)); } //============================================================== // AddBoundaryForce // slightly hacky, but just do this on the lower boundary to stop // particles bunching up there. Could easily generalise this //============================================================== void AddBoundaryForces() { for (int i = 0 ; i < gNParticles ; ++i) { AddBoundaryForce(gParticles[i].mR, gParticles[i].mBodyForce, gBoundaryForceScaleDist, gBoundaryForceScale); } } //============================================================== // ImposeBoundaryConditions //============================================================== void ImposeBoundaryConditions() { // velocity scaling when colliding with walls tVector2 normal; for (int i = gNParticles ; i-- != 0 ; ) { if (gParticles[i].mR.x < gContainerX) { gParticles[i].mR.x = gContainerX; } else if (gParticles[i].mR.x > gContainerX + gContainerWidth) { gParticles[i].mR.x = gContainerX + gContainerWidth; } if (gParticles[i].mR.y < gContainerY) { gParticles[i].mR.y = gContainerY; } else if (gParticles[i].mR.y > gContainerY + gContainerHeight) { gParticles[i].mR.y = gContainerY + gContainerHeight; } if (gRectangle) { if (gRectangle->MovePointOutOfObject(gParticles[i].mR, normal)) { // do nothing extra } } } } #ifdef CALC_NORMAL_FIELD //============================================================== // CalculateNormalField //============================================================== void CalculateNormalField() { int i; tSpatialGridIterator gridIter; for (i = gNParticles ; i-- != 0 ; ) { gParticles[i].mCs = 0.0f; for (tParticle * particle = gridIter.FindFirst(gParticles[i].mR, *gSpatialGrid) ; particle != 0 ; particle = gridIter.GetNext(*gSpatialGrid)) { if (particle->mDensity > 0.0f) { gParticles[i].mCs += gParticleMass * WPoly6(gParticles[i].mR - particle->mR) / particle->mDensity; } } } // now n = grad(Cs) for (i = gNParticles ; i-- != 0 ; ) { gParticles[i].mN.Set(0.0f, 0.0f); for (tParticle * particle = gridIter.FindFirst(gParticles[i].mR, *gSpatialGrid) ; particle != 0 ; particle = gridIter.GetNext(*gSpatialGrid)) { if (particle->mDensity > 0.0f) { gParticles[i].mN += (gParticleMass * particle->mCs / particle->mDensity) * WPoly6Grad(gParticles[i].mR - particle->mR); } } } } #endif //============================================================== // CheckKernel //============================================================== void NormaliseKernels() { int n = 1000; tScalar xmin = -1.0f * gKernelH; tScalar ymin = xmin; tScalar xmax = -xmin; tScalar ymax = xmax; tScalar dx = (xmax - xmin) / (n - 1); tScalar dy = (ymax - ymin) / (n - 1); tScalar dA = dx * dy; tScalar totalPoly6 = 0.0f; tScalar totalSpiky = 0.0f; tScalar totalViscosity = 0.0f; tScalar totalLucy = 0.0f; gWPoly6Scale = 1.0f; gWSpikyScale = 1.0f; gWViscosityScale = 1.0f; gWLucyScale = 1.0f; for (int i = 0 ; i < n ; ++i) { for (int j = 0 ; j < n ; ++j) { tVector2 r(xmin + i * dx, ymin + j * dy); totalPoly6 += WPoly6(r) * dA; totalSpiky += WSpiky(r) * dA; totalViscosity += WViscosity(r) * dA; totalLucy += WLucy(r) * dA; } } gWPoly6Scale = 1.0f / totalPoly6; gWSpikyScale = 1.0f / totalSpiky; gWViscosityScale = 1.0f / totalViscosity; gWLucyScale = 1.0f / totalLucy; } //======================================================== // tResolver //======================================================== class tResolver : public tPenetrationResolver { bool ResolvePenetration(tShapeParticle & particle); }; //======================================================== // ResolvePenetration //======================================================== bool tResolver::ResolvePenetration(tShapeParticle & particle) { bool moved = false; if (particle.mPos.x < gContainerX) { particle.mPos.x = gContainerX; moved = true; } else if (particle.mPos.x > gContainerX + gContainerWidth) { particle.mPos.x = gContainerX + gContainerWidth; moved = true; } if (particle.mPos.y < gContainerY) { particle.mPos.y = gContainerY; moved = true; } else if (particle.mPos.y > gContainerY + gContainerHeight) { particle.mPos.y = gContainerY + gContainerHeight; moved = true; } return moved; } //======================================================== // SetObjectForces //======================================================== void SetObjectForces() { if (!gRectangle) return; int nObjectParticles; int iObjectParticle; tShapeParticle * objectParticles = gRectangle->GetParticles(nObjectParticles); for (iObjectParticle = nObjectParticles ; iObjectParticle-- != 0 ; ) { // do gravity etc tVector2 bodyForce = gGravity / objectParticles[iObjectParticle].mInvMass; objectParticles[iObjectParticle].mForce = bodyForce; } for (iObjectParticle = nObjectParticles ; iObjectParticle-- != 0 ; ) { // assume that the points are in order for traversing the // object. We sample each edge at intervals of gParticleRadius, // get the force at each sample (pressure is force/distance) which // must be perpendicular to the object edge, and distribute it // between the particles at the end of the line, according to the // position. int iStart = iObjectParticle; int iEnd = (iStart + 1) % nObjectParticles; tShapeParticle & particleStart = objectParticles[iStart]; tShapeParticle & particleEnd = objectParticles[iEnd]; tVector2 edgeDelta = particleEnd.mPos - particleStart.mPos; tScalar edgeLen = (edgeDelta).GetLength(); tVector2 edgeDir = edgeDelta / edgeLen; tVector2 edgeNormal(edgeDir.y, -edgeDir.x); // points out of the object int nSamples = 1 + (int) (edgeLen / gParticleRadius); tScalar sampleLen = edgeLen / nSamples; tSpatialGridIterator gridIter; for (int iSample = nSamples ; iSample-- != 0 ; ) { // samples are at the mid positions of the edge element tScalar fracStart = 1.0f - (0.5f + iSample)/nSamples; tScalar fracEnd = 1.0f - fracStart; tVector2 samplePos = fracStart * particleStart.mPos + fracEnd * particleEnd.mPos; tVector2 localPressureForce(0.0f, 0.0f); // evaluate the fluid pressure here - derived from the local density tScalar localDensity = 0.0f; tVector2 pressureGradient(0.0f, 0.0f); for (tParticle * particle = gridIter.FindFirst(samplePos, *gSpatialGrid) ; particle != 0 ; particle = gridIter.GetNext(*gSpatialGrid)) { tVector2 r = samplePos - particle->mR; if (r.GetLengthSq() < gKernelH2) { localDensity += gParticleMass * WSpiky(r); if (particle->mDensity > 0.0f) pressureGradient -= WPoly6Grad(r) * (gParticleMass * particle->mP / particle->mDensity); } } // don't bother with viscosity // now we've calculated the density use it to decide whether or // not to add the hacky boundary force if ( (0 == iSample) && (localDensity > 0.5f * gDensity0) ) { AddBoundaryForce(objectParticles[iStart].mPos, objectParticles[iStart].mForce, 2 * gBoundaryForceScaleDist, -gObjectBoundaryScale * gGravity.y / objectParticles[iStart].mInvMass); } // the factor in here is a horrible hack because the ideal-gas // approx doesn't really give a good pressure gradient... etc localPressureForce = gObjectBuoyancyScale * sampleLen * edgeNormal * (Dot(pressureGradient, edgeNormal)); objectParticles[iStart].mForce += fracStart * localPressureForce; objectParticles[iEnd].mForce += fracEnd * localPressureForce; } } } //======================================================== // IntegrateObjects //======================================================== void IntegrateObjects() { if (!gRectangle) return; if (INTERACTION_BOX != gInteractionMode) { SetObjectForces(); gRectangle->Integrate(gTimeStep); } tResolver resolver; gRectangle->ResolveConstraints(4, resolver); } //============================================================== // CalculatePressureAndDensities //============================================================== void CalculatePressureAndDensities() { tVector2 r; tSpatialGridIterator gridIter; for (int i = gNParticles ; i-- != 0 ; ) { gParticles[i].mDensity = 0.0f; for (tParticle * particle = gridIter.FindFirst(gParticles[i].mR, *gSpatialGrid); particle != 0 ; particle = gridIter.GetNext(*gSpatialGrid)) { SubVector2(r, gParticles[i].mR, particle->mR); gParticles[i].mDensity += gParticleMass * WPoly6(r); } gParticles[i].mP = CalculatePressure(gParticles[i].mDensity); } } //============================================================== // CalculateForces // The forces between particles are symmetric so only calculate // them once per pair //============================================================== void CalculateForces() { tVector2 tmp; tVector2 r; int i; for (i = gNParticles ; i-- != 0 ; ) { ScaleVector2(gParticles[i].mBodyForce, gGravity, gParticleMass); gParticles[i].mPressureForce.Set(0.0f, 0.0f); gParticles[i].mViscosityForce.Set(0.0f, 0.0f); } tSpatialGridIterator gridIter; for (i = gNParticles ; i-- != 0 ; ) { for (tParticle * particle = gridIter.FindFirst(gParticles[i].mR, *gSpatialGrid) ; particle != 0 ; particle = gridIter.GetNext(*gSpatialGrid)) { // only do each pair once if (particle > &gParticles[i]) continue; if (particle->mDensity > SCALAR_TINY) { // pressure SubVector2(r, gParticles[i].mR, particle->mR); if (r.GetLengthSq() < gKernelH2) { ScaleVector2(tmp, WSpikyGrad(r), gParticleMass * (gParticles[i].mP + particle->mP) / (2.0f * particle->mDensity)); gParticles[i].mPressureForce -= tmp; particle->mPressureForce += tmp; // viscosity ScaleVector2(tmp, particle->mV - gParticles[i].mV, gViscosity * gParticleMass * WViscosityLap(r) / particle->mDensity); gParticles[i].mViscosityForce += tmp; particle->mViscosityForce -= tmp; } } } } AddBoundaryForces(); } //============================================================== // PreventParticleCohabitation //============================================================== void PreventParticleCohabitation() { tScalar minDist = 0.5f * gParticleRadius; tScalar minDist2 = Sq(minDist); tScalar resolveFrac = 0.1f; tVector2 delta; tSpatialGridIterator gridIter; for (int i = gNParticles ; i-- != 0 ; ) { for (tParticle * particle = gridIter.FindFirst(gParticles[i].mR, *gSpatialGrid) ; particle != 0 ; particle = gridIter.GetNext(*gSpatialGrid)) { // only need to check each pair once if (particle > &gParticles[i]) continue; SubVector2(delta, particle->mR, gParticles[i].mR); tScalar deltaLenSq = delta.GetLengthSq(); if (deltaLenSq > minDist2) continue; if (deltaLenSq > SCALAR_TINY) { tScalar deltaLen = Sqrt(deltaLenSq); tScalar diff = resolveFrac * 0.5f * (deltaLen - minDist) / deltaLen; delta *= diff; gParticles[i].mR += delta; gParticles[i].mOldR += delta; particle->mR -= delta; particle->mOldR -= delta; } else { gParticles[i].mR.x += 0.5f * resolveFrac * minDist; gParticles[i].mOldR.x += 0.5f * resolveFrac * minDist; particle->mR.x -= 0.5f * resolveFrac * minDist; particle->mOldR.x -= 0.5f * resolveFrac * minDist; } } } } //============================================================== // DoFountain //============================================================== void DoFountain() { static int fountainParticle = 0; tVector2 vel(2.0f, 2.0f); int w = glutGet(GLUT_WINDOW_WIDTH); int h = glutGet(GLUT_WINDOW_HEIGHT); tVector2 pos = (gDomainX / gWindowW) * gOldMousePos; tScalar frac = 0.05f; pos += frac * tVector2(RangedRandom(0.0f, gDomainX), RangedRandom(0.0f, gDomainY)); gParticles[fountainParticle].mR = pos; gParticles[fountainParticle].mOldR = pos - gTimeStep * vel; gParticles[fountainParticle].mV = vel; fountainParticle = (fountainParticle + 1) % gNParticles; } //============================================================== // Integrate //============================================================== void Integrate() { if (gInteractionMode == INTERACTION_FOUNTAIN) DoFountain(); CalculatePressureAndDensities(); CalculateForces(); CalculateNewParticles(); ImposeBoundaryConditions(); PreventParticleCohabitation(); gSpatialGrid->PopulateGrid(gParticles, gNParticles); #ifdef CALC_NORMAL_FIELD CalculateNormalField(); #endif // and the objects IntegrateObjects(); } //============================================================== // Initialise //============================================================== void Initialise() { NormaliseKernels(); gParticles = new tParticle[gNParticles]; gSpatialGrid = new tSpatialGrid( tVector2(-gContainerWidth, -gContainerHeight), tVector2(gDomainX + gContainerWidth, gDomainY + gContainerHeight), gKernelH); int i; for (i = 0 ; i < gNParticles ; ++i) { gParticles[i].mR.Set( gContainerX + RangedRandom(0.0f, gContainerWidth), gContainerY + RangedRandom(0.0f, gInitialFluidHeight)); gParticles[i].mOldR = gParticles[i].mR; gParticles[i].mV.Set(0.0f, 0.0f); gParticles[i].mDensity = gDensity0; gParticles[i].mP = CalculatePressure(gDensity0); gParticles[i].mPressureForce.Set(0.0f, 0.0f); gParticles[i].mViscosityForce.Set(0.0f, 0.0f); gParticles[i].mBodyForce.Set(0.0f, 0.0f); #ifdef CALC_NORMAL_FIELD gParticles[i].mCs = 0.0f; gParticles[i].mN.Set(0.0f, 0.0f); #endif gParticles[i].mNext = 0; } gSpatialGrid->PopulateGrid(gParticles, gNParticles); if (gCreateObject) { tScalar widthFrac = 0.4f; tScalar heightFrac = 0.2f; gRectangle = new ::tRectangle(widthFrac * gContainerWidth, heightFrac * gContainerHeight, gObjectDensityFrac * gDensity0); gRectangle->SetCoGPosition( tVector2(gContainerX + 0.5f * gContainerWidth, gContainerY + gContainerHeight - heightFrac * gContainerHeight)); gRectangle->SetParticleForces(gGravity); } } //============================================================== // DrawContainer //============================================================== void DrawContainer() { GLCOLOR3(1.0f,1.0f, 1.0f); glBegin(GL_QUADS); GLVERTEX2(gContainerX, gContainerY + gContainerHeight); GLVERTEX2(gContainerX, gContainerY); GLVERTEX2(gContainerX + gContainerWidth, gContainerY); GLVERTEX2(gContainerX + gContainerWidth, gContainerY + gContainerHeight); GLVERTEX2(gContainerX, gContainerY + gContainerHeight); glEnd(); } //======================================================== // DrawQuad //======================================================== inline void DrawQuad(const tVector2 & min, const tVector2 & max) { GLVERTEX2(min.x, min.y); GLVERTEX2(max.x, min.y); GLVERTEX2(max.x, max.y); GLVERTEX2(min.x, max.y); } //============================================================== // DrawVoid //============================================================== void DrawVoid() { GLCOLOR3(0.5f,0.5f, 0.5f); glBegin(GL_QUADS); DrawQuad(tVector2(0.0f, 0.0f), tVector2(gDomainX, gContainerY)); DrawQuad(tVector2(0.0f, gContainerY + gContainerHeight), tVector2(gDomainX, gDomainY)); DrawQuad(tVector2(0.0f, 0.0f), tVector2(gContainerX, gDomainY)); DrawQuad(tVector2(gContainerX + gContainerWidth, 0.0f), tVector2(gDomainX, gDomainY)); glEnd(); } //============================================================== // DrawGridWater // sets up a grid to render between the water particles... //============================================================== void DrawGridWater() { glColor3f(0.0f,0.0f, 1.0f); // number points int nx = gNRenderSamplesX; int ny = gNRenderSamplesY; tScalar dx = gContainerWidth / (nx - 1); tScalar dy = gContainerHeight / (ny - 1); static tArray2D<tScalar> densities(nx, ny); densities.Resize(nx, ny); tSpatialGridIterator gridIter; tVector2 r; for (int ix = nx ; ix-- != 0 ; ) { for (int iy = ny ; iy-- != 0 ; ) { r.Set(gContainerX + ix * dx, gContainerY + iy * dy); // now evaluate the density at this point tScalar d = 0.0f; for (tParticle * particle = gridIter.FindFirst(r, *gSpatialGrid) ; particle != 0 ; particle = gridIter.GetNext(*gSpatialGrid)) { d += gParticleMass * WPoly6(r - particle->mR); } densities(ix, iy) = d; } } tScalar min = gRenderDensityMin; tScalar max = gRenderDensityMax; glBegin(GL_QUADS); int i, j; tScalar grey; for (i = nx-1 ; i-- != 0 ; ) { for (j = ny-1 ; j-- != 0 ; ) { tScalar x = gContainerX + i * dx; tScalar y = gContainerY + j * dy; grey = (densities(i, j) - min) / (max - min); GLCOLOR3(0, 0, grey); GLVERTEX2(x, y); grey = (densities(i+1, j) - min) / (max - min); GLCOLOR3(0, 0, grey); GLVERTEX2(x + dx, y); grey = (densities(i+1, j+1) - min) / (max - min); GLCOLOR3(0, 0, grey); GLVERTEX2(x + dx, y + dy); grey = (densities(i, j+1) - min) / (max - min); GLCOLOR3(0, 0, grey); GLVERTEX2(x, y + dy); } } glEnd(); } //============================================================== // DrawWater //============================================================== void DrawWater() { if (gRenderParticles) { int i; GLCOLOR3(0.0f,0.0f, 1.0f); glPointSize(6); glEnable(GL_POINT_SMOOTH); glBegin(GL_POINTS); for (i = gNParticles ; i-- != 0 ; ) { GLVERTEX2(gParticles[i].mR.x, gParticles[i].mR.y); } glEnd(); } else { DrawGridWater(); } } //======================================================== // DrawObjects //======================================================== void DrawObjects() { if (gRectangle) gRectangle->Draw(); } //============================================================== // Display //============================================================== void Display() { static int lastTime = glutGet(GLUT_ELAPSED_TIME); int thisTime = glutGet(GLUT_ELAPSED_TIME); tScalar dt = (thisTime - lastTime) * 0.001f; dt *= gTimeScale; static tScalar residual = 0.0f; if (dt > 0.2f) { dt = 0.2f; residual = 0.0f; TRACE("can't keep up \n"); } int nLoops = (int) ((dt + residual)/ gTimeStep); if (nLoops > 0) { residual = dt - (nLoops * gTimeStep); for (int iLoop = 0 ; iLoop < nLoops ; ++iLoop) { Integrate(); } lastTime = thisTime; } // count FPS { static int lastTimeForFPS = thisTime; static int counter = 0; if (thisTime - lastTimeForFPS > 5000) { TRACE("FPS = %5.2f\n", counter / 5.0f); counter = 0; lastTimeForFPS = thisTime; } else { ++counter; } } glClear(GL_COLOR_BUFFER_BIT ); DrawContainer(); DrawWater(); DrawObjects(); DrawVoid(); glutSwapBuffers(); } //============================================================== // Idle //============================================================== void Idle() { Display(); } //======================================================== // ApplyImpulse //======================================================== void ApplyImpulse(const tVector2 & deltaVel) { for (int i = gNParticles ; i-- != 0 ; ) { gParticles[i].mV += deltaVel; gParticles[i].mOldR -= deltaVel * gTimeStep; } } //============================================================== // MoveContainer //============================================================== void MoveContainer(const tVector2 & dR) { gContainerX += dR.x; gContainerY += dR.y; } //============================================================== // MoveBox //============================================================== void MoveBox(const tVector2 & dR) { if (gRectangle) gRectangle->Move(dR); } //============================================================== // Keyboard //============================================================== void Keyboard( unsigned char key, int x, int y ) { switch (key) { case 'q': case 27: exit(0); break; case 'a': ApplyImpulse(tVector2(-1.0f, 0.0f)); break; case 'd': ApplyImpulse(tVector2(1.0f, 0.0f)); break; case 's': ApplyImpulse(tVector2(0.0f, -1.0f)); break; case 'w': ApplyImpulse(tVector2(0.0f, 1.0f)); break; default: break; } } //============================================================== // Mouse //============================================================== void Mouse(int button, int state, int x, int y) { if (GLUT_UP == state) { gInteractionMode = INTERACTION_NONE; return; } int h = glutGet(GLUT_WINDOW_HEIGHT); gOldMousePos.Set(x, h-y); if (GLUT_LEFT_BUTTON == button) gInteractionMode = INTERACTION_CONTAINER; else if (GLUT_RIGHT_BUTTON == button) gInteractionMode = INTERACTION_BOX; else if (GLUT_MIDDLE_BUTTON == button) gInteractionMode = INTERACTION_FOUNTAIN; } //============================================================== // MouseMotion //============================================================== void MouseMotion(int x, int y) { int h = glutGet(GLUT_WINDOW_HEIGHT); tVector2 newPos(x, h-y); tVector2 delta = (gDomainX / gWindowW) * (newPos - gOldMousePos); if (INTERACTION_CONTAINER == gInteractionMode) { MoveContainer(delta); } else if (INTERACTION_BOX == gInteractionMode) { MoveBox(delta); } gOldMousePos = newPos; } //============================================================== // ReadConfig //============================================================== void ReadConfig() { #define GET(val) gConfigFile->GetValue(#val, val) Assert(gConfigFile); // defaults gWindowW = 640; gWindowH = 480; gRenderParticles = false; gNRenderSamplesX = 64; gNRenderSamplesY = 48; gRenderDensityMin = 500.0f; gRenderDensityMax = 800.0f; gDomainX = 2.0f; tScalar gContainerWidthFrac = 0.8f; tScalar gContainerHeightFrac = 0.5f; tScalar gInitialFluidHeightFrac = 0.9f; gGravity.Set(0.0f, -10.0f); gDensity0 = 1000.0f; gNParticles = 200; gViscosity = 0.05f; gGasK = 10.0f; gTimeStep = 1.0f / 100.0f; gTimeScale = 1.0f; tScalar kernelScale = 5.0f; gBoundaryForceScale = 0.0f; gBoundaryForceScaleDist = 0.1f; gCreateObject = true; gObjectDensityFrac = 0.5f; gObjectBoundaryScale = 20.0f; gObjectBuoyancyScale = 6.0f; GET(gWindowW); GET(gWindowH); GET(gRenderParticles); GET(gNRenderSamplesX); GET(gNRenderSamplesY); GET(gRenderDensityMin); GET(gRenderDensityMax); GET(gDomainX); GET(gContainerWidthFrac); GET(gContainerHeightFrac); GET(gInitialFluidHeightFrac); gConfigFile->GetValue("gGravityX", gGravity.x); gConfigFile->GetValue("gGravityY", gGravity.y); GET(gDensity0); GET(gNParticles); GET(gViscosity); GET(gGasK); GET(gTimeStep); GET(gTimeScale); GET(kernelScale); GET(gBoundaryForceScale); GET(gBoundaryForceScaleDist); GET(gCreateObject); GET(gObjectDensityFrac); GET(gObjectBoundaryScale); GET(gObjectBuoyancyScale); gDomainY = gDomainX * gWindowH / gWindowW; gContainerWidth = gContainerWidthFrac * gDomainX; gContainerHeight = gContainerHeightFrac * gDomainX; gContainerX = 0.5f * gDomainX - 0.5f * gContainerWidth; gContainerY = 0.1f * gDomainY; gInitialFluidHeight = gInitialFluidHeightFrac * gContainerHeight; gParticleRadius = Sqrt(gContainerWidth * gInitialFluidHeight / (4.0f * gNParticles)); tScalar volume = gContainerWidth * gInitialFluidHeight; gParticleMass = volume * gDensity0 / gNParticles; gKernelH = kernelScale * gParticleRadius; gKernelH9 = pow(gKernelH, 9.0f); gKernelH6 = pow(gKernelH, 6.0f); gKernelH4 = pow(gKernelH, 4.0f); gKernelH3 = pow(gKernelH, 3.0f); gKernelH2 = pow(gKernelH, 2.0f); } //============================================================== // main //============================================================== int main(int argc, char* argv[]) { // GLUT routines glutInit(&argc, argv); TRACE("Water simulation by Danny Chapman Dec 2004\n"); string configFileName("water.cfg"); bool configFileOk; if (argc > 1) configFileName = string(argv[1]); gConfigFile = new tConfigFile(configFileName, configFileOk); if (!configFileOk) TRACE("Warning: Unable to open main config file: %s\n", configFileName.c_str()); ReadConfig(); glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE); glutInitWindowSize( gWindowW, gWindowH ); // Open a window glutCreateWindow( "Water - Danny Chapman Dec 2004" ); glClearColor( 0.0,0.0,0.0,1 ); // set the projection so that we draw things in world space, not // screen space gluOrtho2D(0.0f, gDomainX, 0.0f, gDomainY); glutDisplayFunc(&Display); glutIdleFunc(&Idle); glutKeyboardFunc(&Keyboard); glutMouseFunc(&Mouse); glutMotionFunc(&MouseMotion); // my code Initialise(); glutMainLoop(); delete gConfigFile; return 1; };
28.788779
91
0.543391
[ "render", "object" ]
b913101a72e0d71d9bbdb0fe2e8a666a1e8390fe
3,930
cpp
C++
spoj/gss3.cpp
dotslash/algProg
5618c5741553776bcb28959b2838500be8b2c3b6
[ "MIT" ]
null
null
null
spoj/gss3.cpp
dotslash/algProg
5618c5741553776bcb28959b2838500be8b2c3b6
[ "MIT" ]
null
null
null
spoj/gss3.cpp
dotslash/algProg
5618c5741553776bcb28959b2838500be8b2c3b6
[ "MIT" ]
null
null
null
#include <cstdio> #include <cassert> #include <cstring> #include <climits> #include <cmath> #include <iostream> #include <algorithm> #include <vector> #define pb push_back #define long long long #define nl(x) scanf("%lld",&x) #define ni(x) scanf("%d",&x) #define pii pair<int,int> #define val1 first #define val2 second #define msb(x) 31-__builtin_clz (x) #define setbits(x) __builtin_popcount(x) using namespace std; //segtree code taken from http://letuskode.blogspot.in/2013/01/segtrees.html //segtree code begins //merge,fields pf node,createleaf functions should be modified based on the scenario int n; struct node{ int preFix,sufFix,best,segSum; bool id; void split(node& l, node& r){} void merge(node& a, node& b) { id = a.id && b.id; if(a.id){ segSum = b.segSum; preFix = b.preFix; sufFix = b.sufFix; best = b.best; } else if(b.id){ segSum = a.segSum; preFix = a.preFix; sufFix = a.sufFix; best = a.best; } else{ segSum = a.segSum + b.segSum; preFix = max(a.segSum+b.preFix,a.preFix); sufFix = max(a.sufFix+b.segSum,b.sufFix); best = max(a.sufFix+b.preFix, max(a.best,b.best)); id = a.id && b.id; } } }; node* tree; node createleaf(int x){ node n; n.preFix = x; n.sufFix = x; n.best = x; n.segSum = x; return n; } node getIden(){ node n; n.id = true; return n; } void update_single_node(node& n, int new_val){ n.preFix =new_val; n.sufFix =new_val; n.best = new_val; n.segSum =new_val; } void init(int* values,int sz){ n = msb(sz)+1; if(setbits(sz)==1) n--; tree = new node[1<<(n+1)]; //bottom level for (int i = 0; i < sz; i += 1){ tree[i+(1<<n)] = createleaf(values[i]); } for (int i = (1<<n)+sz; i < (1<<(n+1)); i += 1){ tree[i] =createleaf(0); } for (int i = (1<<n)-1; i > 0; i --) { tree[i].merge(tree[2*i],tree[2*i+1]); } } node range_query(int root, int left_most_leaf, int right_most_leaf, int u, int v) { //query the interval [u,v), ie, {x:u<=x<v} //the interval [left_most_leaf,right_most_leaf) is //the set of all leaves descending from "root" if(u<=left_most_leaf && right_most_leaf<=v) return tree[root]; int mid = (left_most_leaf+right_most_leaf)/2, left_child = root*2, right_child = left_child+1; tree[root].split(tree[left_child], tree[right_child]); node l=getIden(), r=getIden(); //getIden() is an element such that merge(x,getIden()) = merge(getIden(),x) = x for all x if(u < mid) l = range_query(left_child, left_most_leaf, mid, u, v); if(v > mid) r = range_query(right_child, mid, right_most_leaf, u, v); tree[root].merge(tree[left_child],tree[right_child]); node n; n.merge(l,r); return n; } void range_update(int root, int left_most_leaf, int right_most_leaf, int u, int v, int new_val) { if(u<=left_most_leaf && right_most_leaf<=v) return update_single_node(tree[root], new_val); int mid = (left_most_leaf+right_most_leaf)/2, left_child = root*2, right_child = left_child+1; tree[root].split(tree[left_child], tree[right_child]); if(u < mid) range_update(left_child, left_most_leaf, mid, u, v, new_val); if(v > mid) range_update(right_child, mid, right_most_leaf, u, v, new_val); tree[root].merge(tree[left_child], tree[right_child]); } void update(int pos, int new_val){ return range_update(1,1<<n,1<<(n+1),pos+(1<<n),pos+1+(1<<n),new_val); } //segtree ends int main (){ int x; ni(x); int arr[x]; for (int i = 0; i < x; i += 1) { ni(arr[i]); } init(arr,x); int t; ni(t); int type,l,r; for (int i = 0; i < t; i += 1){ ni(type); ni(l); ni(r); l--; if(type){ printf("%d\n",range_query(1,1<<n,1<<(n+1),l+(1<<n),r+(1<<n)).best); } else{ update(l,r); } } }
25.519481
95
0.596438
[ "vector" ]
2c6c977465d53064dc37d0f9b5fab4bb469e6a52
1,059
cpp
C++
data/dailyCodingProblem244.cpp
vidit1999/daily_coding_problem
b90319cb4ddce11149f54010ba36c4bd6fa0a787
[ "MIT" ]
2
2020-09-04T20:56:23.000Z
2021-06-11T07:42:26.000Z
data/dailyCodingProblem244.cpp
vidit1999/daily_coding_problem
b90319cb4ddce11149f54010ba36c4bd6fa0a787
[ "MIT" ]
null
null
null
data/dailyCodingProblem244.cpp
vidit1999/daily_coding_problem
b90319cb4ddce11149f54010ba36c4bd6fa0a787
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; /* The Sieve of Eratosthenes is an algorithm used to generate all prime numbers smaller than N. The method is to take increasingly larger prime numbers, and mark their multiples as composite. For example, to find all primes less than 100, we would first mark [4, 6, 8, ...] (multiples of two), then [6, 9, 12, ...] (multiples of three), and so on. Once we have done this for all primes less than N, the unmarked numbers that remain will be prime. Implement this algorithm. Bonus: Create a generator that produces primes indefinitely (that is, without taking N as an input). */ vector<int> primesLessThanN(int n){ bool *arr = new bool[n](); arr[0] = true, arr[1] = true; for(int i=2; i<n; i++){ if(arr[i] == false){ for(int j=2; i*j<n; j++){ arr[i*j] = true; } } } vector<int> ans; for(int i=0; i<n; i++){ if(arr[i] == false) ans.push_back(i); } delete [] arr; return ans; } // main function int main(){ for(int i : primesLessThanN(100)) cout << i << "\n"; return 0; }
23.021739
98
0.653447
[ "vector" ]
2c7048e10614ab4e051e7222dbe59eb2f013817f
30,748
cpp
C++
Temp/StagingArea/Data/il2cppOutput/UnityEngine.PhysicsModule.cpp
Sunderer325/DigitalOxygenTest
26ae3e725fe6ecba49cf52739890a9a559ce61ce
[ "MIT" ]
1
2021-06-30T23:24:16.000Z
2021-06-30T23:24:16.000Z
Temp/StagingArea/Data/il2cppOutput/UnityEngine.PhysicsModule.cpp
Sunderer325/ThereIsAHundredOfThem
26ae3e725fe6ecba49cf52739890a9a559ce61ce
[ "MIT" ]
null
null
null
Temp/StagingArea/Data/il2cppOutput/UnityEngine.PhysicsModule.cpp
Sunderer325/ThereIsAHundredOfThem
26ae3e725fe6ecba49cf52739890a9a559ce61ce
[ "MIT" ]
null
null
null
#include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <cstring> #include <string.h> #include <stdio.h> #include <cmath> #include <limits> #include <assert.h> #include <stdint.h> #include "codegen/il2cpp-codegen.h" #include "il2cpp-object-internals.h" // System.String struct String_t; // System.Void struct Void_t22962CB4C05B1D89B55A6E1139F0E87A90987017; // UnityEngine.Collider struct Collider_t0FEEB36760860AD21B3B1F0509C365B393EC4BDF; // UnityEngine.Object struct Object_tAE11E5E46CD5C37C9F3E8950C00CD8B45666A2D0; IL2CPP_EXTERN_C RuntimeClass* Collider_t0FEEB36760860AD21B3B1F0509C365B393EC4BDF_il2cpp_TypeInfo_var; IL2CPP_EXTERN_C RuntimeClass* Object_tAE11E5E46CD5C37C9F3E8950C00CD8B45666A2D0_il2cpp_TypeInfo_var; IL2CPP_EXTERN_C const uint32_t RaycastHit_get_collider_mE70B84C4312B567344F60992A6067855F2C3A7A9_MetadataUsageId; IL2CPP_EXTERN_C_BEGIN IL2CPP_EXTERN_C_END #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // <Module> struct U3CModuleU3E_t1ABA099244C4281E9C7E9402BE77B2165BA664F6 { public: public: }; // System.Object struct Il2CppArrayBounds; // System.Array // System.ValueType struct ValueType_t4D0C27076F7C36E76190FB3328E232BCB1CD1FFF : public RuntimeObject { public: public: }; // Native definition for P/Invoke marshalling of System.ValueType struct ValueType_t4D0C27076F7C36E76190FB3328E232BCB1CD1FFF_marshaled_pinvoke { }; // Native definition for COM marshalling of System.ValueType struct ValueType_t4D0C27076F7C36E76190FB3328E232BCB1CD1FFF_marshaled_com { }; // UnityEngine.Physics struct Physics_t795152566290B75B831BBCB079E5F82B1BAA93B2 : public RuntimeObject { public: public: }; // System.Int32 struct Int32_t585191389E07734F19F3156FF88FB3EF4800D102 { public: // System.Int32 System.Int32::m_value int32_t ___m_value_0; public: inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(Int32_t585191389E07734F19F3156FF88FB3EF4800D102, ___m_value_0)); } inline int32_t get_m_value_0() const { return ___m_value_0; } inline int32_t* get_address_of_m_value_0() { return &___m_value_0; } inline void set_m_value_0(int32_t value) { ___m_value_0 = value; } }; // System.IntPtr struct IntPtr_t { public: // System.Void* System.IntPtr::m_value void* ___m_value_0; public: inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(IntPtr_t, ___m_value_0)); } inline void* get_m_value_0() const { return ___m_value_0; } inline void** get_address_of_m_value_0() { return &___m_value_0; } inline void set_m_value_0(void* value) { ___m_value_0 = value; } }; struct IntPtr_t_StaticFields { public: // System.IntPtr System.IntPtr::Zero intptr_t ___Zero_1; public: inline static int32_t get_offset_of_Zero_1() { return static_cast<int32_t>(offsetof(IntPtr_t_StaticFields, ___Zero_1)); } inline intptr_t get_Zero_1() const { return ___Zero_1; } inline intptr_t* get_address_of_Zero_1() { return &___Zero_1; } inline void set_Zero_1(intptr_t value) { ___Zero_1 = value; } }; // System.Single struct Single_tDDDA9169C4E4E308AC6D7A824F9B28DC82204AE1 { public: // System.Single System.Single::m_value float ___m_value_0; public: inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(Single_tDDDA9169C4E4E308AC6D7A824F9B28DC82204AE1, ___m_value_0)); } inline float get_m_value_0() const { return ___m_value_0; } inline float* get_address_of_m_value_0() { return &___m_value_0; } inline void set_m_value_0(float value) { ___m_value_0 = value; } }; // UnityEngine.Vector2 struct Vector2_tA85D2DD88578276CA8A8796756458277E72D073D { public: // System.Single UnityEngine.Vector2::x float ___x_0; // System.Single UnityEngine.Vector2::y float ___y_1; public: inline static int32_t get_offset_of_x_0() { return static_cast<int32_t>(offsetof(Vector2_tA85D2DD88578276CA8A8796756458277E72D073D, ___x_0)); } inline float get_x_0() const { return ___x_0; } inline float* get_address_of_x_0() { return &___x_0; } inline void set_x_0(float value) { ___x_0 = value; } inline static int32_t get_offset_of_y_1() { return static_cast<int32_t>(offsetof(Vector2_tA85D2DD88578276CA8A8796756458277E72D073D, ___y_1)); } inline float get_y_1() const { return ___y_1; } inline float* get_address_of_y_1() { return &___y_1; } inline void set_y_1(float value) { ___y_1 = value; } }; struct Vector2_tA85D2DD88578276CA8A8796756458277E72D073D_StaticFields { public: // UnityEngine.Vector2 UnityEngine.Vector2::zeroVector Vector2_tA85D2DD88578276CA8A8796756458277E72D073D ___zeroVector_2; // UnityEngine.Vector2 UnityEngine.Vector2::oneVector Vector2_tA85D2DD88578276CA8A8796756458277E72D073D ___oneVector_3; // UnityEngine.Vector2 UnityEngine.Vector2::upVector Vector2_tA85D2DD88578276CA8A8796756458277E72D073D ___upVector_4; // UnityEngine.Vector2 UnityEngine.Vector2::downVector Vector2_tA85D2DD88578276CA8A8796756458277E72D073D ___downVector_5; // UnityEngine.Vector2 UnityEngine.Vector2::leftVector Vector2_tA85D2DD88578276CA8A8796756458277E72D073D ___leftVector_6; // UnityEngine.Vector2 UnityEngine.Vector2::rightVector Vector2_tA85D2DD88578276CA8A8796756458277E72D073D ___rightVector_7; // UnityEngine.Vector2 UnityEngine.Vector2::positiveInfinityVector Vector2_tA85D2DD88578276CA8A8796756458277E72D073D ___positiveInfinityVector_8; // UnityEngine.Vector2 UnityEngine.Vector2::negativeInfinityVector Vector2_tA85D2DD88578276CA8A8796756458277E72D073D ___negativeInfinityVector_9; public: inline static int32_t get_offset_of_zeroVector_2() { return static_cast<int32_t>(offsetof(Vector2_tA85D2DD88578276CA8A8796756458277E72D073D_StaticFields, ___zeroVector_2)); } inline Vector2_tA85D2DD88578276CA8A8796756458277E72D073D get_zeroVector_2() const { return ___zeroVector_2; } inline Vector2_tA85D2DD88578276CA8A8796756458277E72D073D * get_address_of_zeroVector_2() { return &___zeroVector_2; } inline void set_zeroVector_2(Vector2_tA85D2DD88578276CA8A8796756458277E72D073D value) { ___zeroVector_2 = value; } inline static int32_t get_offset_of_oneVector_3() { return static_cast<int32_t>(offsetof(Vector2_tA85D2DD88578276CA8A8796756458277E72D073D_StaticFields, ___oneVector_3)); } inline Vector2_tA85D2DD88578276CA8A8796756458277E72D073D get_oneVector_3() const { return ___oneVector_3; } inline Vector2_tA85D2DD88578276CA8A8796756458277E72D073D * get_address_of_oneVector_3() { return &___oneVector_3; } inline void set_oneVector_3(Vector2_tA85D2DD88578276CA8A8796756458277E72D073D value) { ___oneVector_3 = value; } inline static int32_t get_offset_of_upVector_4() { return static_cast<int32_t>(offsetof(Vector2_tA85D2DD88578276CA8A8796756458277E72D073D_StaticFields, ___upVector_4)); } inline Vector2_tA85D2DD88578276CA8A8796756458277E72D073D get_upVector_4() const { return ___upVector_4; } inline Vector2_tA85D2DD88578276CA8A8796756458277E72D073D * get_address_of_upVector_4() { return &___upVector_4; } inline void set_upVector_4(Vector2_tA85D2DD88578276CA8A8796756458277E72D073D value) { ___upVector_4 = value; } inline static int32_t get_offset_of_downVector_5() { return static_cast<int32_t>(offsetof(Vector2_tA85D2DD88578276CA8A8796756458277E72D073D_StaticFields, ___downVector_5)); } inline Vector2_tA85D2DD88578276CA8A8796756458277E72D073D get_downVector_5() const { return ___downVector_5; } inline Vector2_tA85D2DD88578276CA8A8796756458277E72D073D * get_address_of_downVector_5() { return &___downVector_5; } inline void set_downVector_5(Vector2_tA85D2DD88578276CA8A8796756458277E72D073D value) { ___downVector_5 = value; } inline static int32_t get_offset_of_leftVector_6() { return static_cast<int32_t>(offsetof(Vector2_tA85D2DD88578276CA8A8796756458277E72D073D_StaticFields, ___leftVector_6)); } inline Vector2_tA85D2DD88578276CA8A8796756458277E72D073D get_leftVector_6() const { return ___leftVector_6; } inline Vector2_tA85D2DD88578276CA8A8796756458277E72D073D * get_address_of_leftVector_6() { return &___leftVector_6; } inline void set_leftVector_6(Vector2_tA85D2DD88578276CA8A8796756458277E72D073D value) { ___leftVector_6 = value; } inline static int32_t get_offset_of_rightVector_7() { return static_cast<int32_t>(offsetof(Vector2_tA85D2DD88578276CA8A8796756458277E72D073D_StaticFields, ___rightVector_7)); } inline Vector2_tA85D2DD88578276CA8A8796756458277E72D073D get_rightVector_7() const { return ___rightVector_7; } inline Vector2_tA85D2DD88578276CA8A8796756458277E72D073D * get_address_of_rightVector_7() { return &___rightVector_7; } inline void set_rightVector_7(Vector2_tA85D2DD88578276CA8A8796756458277E72D073D value) { ___rightVector_7 = value; } inline static int32_t get_offset_of_positiveInfinityVector_8() { return static_cast<int32_t>(offsetof(Vector2_tA85D2DD88578276CA8A8796756458277E72D073D_StaticFields, ___positiveInfinityVector_8)); } inline Vector2_tA85D2DD88578276CA8A8796756458277E72D073D get_positiveInfinityVector_8() const { return ___positiveInfinityVector_8; } inline Vector2_tA85D2DD88578276CA8A8796756458277E72D073D * get_address_of_positiveInfinityVector_8() { return &___positiveInfinityVector_8; } inline void set_positiveInfinityVector_8(Vector2_tA85D2DD88578276CA8A8796756458277E72D073D value) { ___positiveInfinityVector_8 = value; } inline static int32_t get_offset_of_negativeInfinityVector_9() { return static_cast<int32_t>(offsetof(Vector2_tA85D2DD88578276CA8A8796756458277E72D073D_StaticFields, ___negativeInfinityVector_9)); } inline Vector2_tA85D2DD88578276CA8A8796756458277E72D073D get_negativeInfinityVector_9() const { return ___negativeInfinityVector_9; } inline Vector2_tA85D2DD88578276CA8A8796756458277E72D073D * get_address_of_negativeInfinityVector_9() { return &___negativeInfinityVector_9; } inline void set_negativeInfinityVector_9(Vector2_tA85D2DD88578276CA8A8796756458277E72D073D value) { ___negativeInfinityVector_9 = value; } }; // UnityEngine.Vector3 struct Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 { public: // System.Single UnityEngine.Vector3::x float ___x_2; // System.Single UnityEngine.Vector3::y float ___y_3; // System.Single UnityEngine.Vector3::z float ___z_4; public: inline static int32_t get_offset_of_x_2() { return static_cast<int32_t>(offsetof(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720, ___x_2)); } inline float get_x_2() const { return ___x_2; } inline float* get_address_of_x_2() { return &___x_2; } inline void set_x_2(float value) { ___x_2 = value; } inline static int32_t get_offset_of_y_3() { return static_cast<int32_t>(offsetof(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720, ___y_3)); } inline float get_y_3() const { return ___y_3; } inline float* get_address_of_y_3() { return &___y_3; } inline void set_y_3(float value) { ___y_3 = value; } inline static int32_t get_offset_of_z_4() { return static_cast<int32_t>(offsetof(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720, ___z_4)); } inline float get_z_4() const { return ___z_4; } inline float* get_address_of_z_4() { return &___z_4; } inline void set_z_4(float value) { ___z_4 = value; } }; struct Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720_StaticFields { public: // UnityEngine.Vector3 UnityEngine.Vector3::zeroVector Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___zeroVector_5; // UnityEngine.Vector3 UnityEngine.Vector3::oneVector Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___oneVector_6; // UnityEngine.Vector3 UnityEngine.Vector3::upVector Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___upVector_7; // UnityEngine.Vector3 UnityEngine.Vector3::downVector Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___downVector_8; // UnityEngine.Vector3 UnityEngine.Vector3::leftVector Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___leftVector_9; // UnityEngine.Vector3 UnityEngine.Vector3::rightVector Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___rightVector_10; // UnityEngine.Vector3 UnityEngine.Vector3::forwardVector Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___forwardVector_11; // UnityEngine.Vector3 UnityEngine.Vector3::backVector Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___backVector_12; // UnityEngine.Vector3 UnityEngine.Vector3::positiveInfinityVector Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___positiveInfinityVector_13; // UnityEngine.Vector3 UnityEngine.Vector3::negativeInfinityVector Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___negativeInfinityVector_14; public: inline static int32_t get_offset_of_zeroVector_5() { return static_cast<int32_t>(offsetof(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720_StaticFields, ___zeroVector_5)); } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 get_zeroVector_5() const { return ___zeroVector_5; } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 * get_address_of_zeroVector_5() { return &___zeroVector_5; } inline void set_zeroVector_5(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 value) { ___zeroVector_5 = value; } inline static int32_t get_offset_of_oneVector_6() { return static_cast<int32_t>(offsetof(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720_StaticFields, ___oneVector_6)); } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 get_oneVector_6() const { return ___oneVector_6; } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 * get_address_of_oneVector_6() { return &___oneVector_6; } inline void set_oneVector_6(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 value) { ___oneVector_6 = value; } inline static int32_t get_offset_of_upVector_7() { return static_cast<int32_t>(offsetof(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720_StaticFields, ___upVector_7)); } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 get_upVector_7() const { return ___upVector_7; } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 * get_address_of_upVector_7() { return &___upVector_7; } inline void set_upVector_7(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 value) { ___upVector_7 = value; } inline static int32_t get_offset_of_downVector_8() { return static_cast<int32_t>(offsetof(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720_StaticFields, ___downVector_8)); } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 get_downVector_8() const { return ___downVector_8; } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 * get_address_of_downVector_8() { return &___downVector_8; } inline void set_downVector_8(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 value) { ___downVector_8 = value; } inline static int32_t get_offset_of_leftVector_9() { return static_cast<int32_t>(offsetof(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720_StaticFields, ___leftVector_9)); } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 get_leftVector_9() const { return ___leftVector_9; } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 * get_address_of_leftVector_9() { return &___leftVector_9; } inline void set_leftVector_9(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 value) { ___leftVector_9 = value; } inline static int32_t get_offset_of_rightVector_10() { return static_cast<int32_t>(offsetof(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720_StaticFields, ___rightVector_10)); } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 get_rightVector_10() const { return ___rightVector_10; } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 * get_address_of_rightVector_10() { return &___rightVector_10; } inline void set_rightVector_10(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 value) { ___rightVector_10 = value; } inline static int32_t get_offset_of_forwardVector_11() { return static_cast<int32_t>(offsetof(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720_StaticFields, ___forwardVector_11)); } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 get_forwardVector_11() const { return ___forwardVector_11; } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 * get_address_of_forwardVector_11() { return &___forwardVector_11; } inline void set_forwardVector_11(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 value) { ___forwardVector_11 = value; } inline static int32_t get_offset_of_backVector_12() { return static_cast<int32_t>(offsetof(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720_StaticFields, ___backVector_12)); } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 get_backVector_12() const { return ___backVector_12; } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 * get_address_of_backVector_12() { return &___backVector_12; } inline void set_backVector_12(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 value) { ___backVector_12 = value; } inline static int32_t get_offset_of_positiveInfinityVector_13() { return static_cast<int32_t>(offsetof(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720_StaticFields, ___positiveInfinityVector_13)); } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 get_positiveInfinityVector_13() const { return ___positiveInfinityVector_13; } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 * get_address_of_positiveInfinityVector_13() { return &___positiveInfinityVector_13; } inline void set_positiveInfinityVector_13(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 value) { ___positiveInfinityVector_13 = value; } inline static int32_t get_offset_of_negativeInfinityVector_14() { return static_cast<int32_t>(offsetof(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720_StaticFields, ___negativeInfinityVector_14)); } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 get_negativeInfinityVector_14() const { return ___negativeInfinityVector_14; } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 * get_address_of_negativeInfinityVector_14() { return &___negativeInfinityVector_14; } inline void set_negativeInfinityVector_14(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 value) { ___negativeInfinityVector_14 = value; } }; // UnityEngine.Object struct Object_tAE11E5E46CD5C37C9F3E8950C00CD8B45666A2D0 : public RuntimeObject { public: // System.IntPtr UnityEngine.Object::m_CachedPtr intptr_t ___m_CachedPtr_0; public: inline static int32_t get_offset_of_m_CachedPtr_0() { return static_cast<int32_t>(offsetof(Object_tAE11E5E46CD5C37C9F3E8950C00CD8B45666A2D0, ___m_CachedPtr_0)); } inline intptr_t get_m_CachedPtr_0() const { return ___m_CachedPtr_0; } inline intptr_t* get_address_of_m_CachedPtr_0() { return &___m_CachedPtr_0; } inline void set_m_CachedPtr_0(intptr_t value) { ___m_CachedPtr_0 = value; } }; struct Object_tAE11E5E46CD5C37C9F3E8950C00CD8B45666A2D0_StaticFields { public: // System.Int32 UnityEngine.Object::OffsetOfInstanceIDInCPlusPlusObject int32_t ___OffsetOfInstanceIDInCPlusPlusObject_1; public: inline static int32_t get_offset_of_OffsetOfInstanceIDInCPlusPlusObject_1() { return static_cast<int32_t>(offsetof(Object_tAE11E5E46CD5C37C9F3E8950C00CD8B45666A2D0_StaticFields, ___OffsetOfInstanceIDInCPlusPlusObject_1)); } inline int32_t get_OffsetOfInstanceIDInCPlusPlusObject_1() const { return ___OffsetOfInstanceIDInCPlusPlusObject_1; } inline int32_t* get_address_of_OffsetOfInstanceIDInCPlusPlusObject_1() { return &___OffsetOfInstanceIDInCPlusPlusObject_1; } inline void set_OffsetOfInstanceIDInCPlusPlusObject_1(int32_t value) { ___OffsetOfInstanceIDInCPlusPlusObject_1 = value; } }; // Native definition for P/Invoke marshalling of UnityEngine.Object struct Object_tAE11E5E46CD5C37C9F3E8950C00CD8B45666A2D0_marshaled_pinvoke { intptr_t ___m_CachedPtr_0; }; // Native definition for COM marshalling of UnityEngine.Object struct Object_tAE11E5E46CD5C37C9F3E8950C00CD8B45666A2D0_marshaled_com { intptr_t ___m_CachedPtr_0; }; // UnityEngine.RaycastHit struct RaycastHit_t19695F18F9265FE5425062BBA6A4D330480538C3 { public: // UnityEngine.Vector3 UnityEngine.RaycastHit::m_Point Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___m_Point_0; // UnityEngine.Vector3 UnityEngine.RaycastHit::m_Normal Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___m_Normal_1; // System.UInt32 UnityEngine.RaycastHit::m_FaceID uint32_t ___m_FaceID_2; // System.Single UnityEngine.RaycastHit::m_Distance float ___m_Distance_3; // UnityEngine.Vector2 UnityEngine.RaycastHit::m_UV Vector2_tA85D2DD88578276CA8A8796756458277E72D073D ___m_UV_4; // System.Int32 UnityEngine.RaycastHit::m_Collider int32_t ___m_Collider_5; public: inline static int32_t get_offset_of_m_Point_0() { return static_cast<int32_t>(offsetof(RaycastHit_t19695F18F9265FE5425062BBA6A4D330480538C3, ___m_Point_0)); } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 get_m_Point_0() const { return ___m_Point_0; } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 * get_address_of_m_Point_0() { return &___m_Point_0; } inline void set_m_Point_0(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 value) { ___m_Point_0 = value; } inline static int32_t get_offset_of_m_Normal_1() { return static_cast<int32_t>(offsetof(RaycastHit_t19695F18F9265FE5425062BBA6A4D330480538C3, ___m_Normal_1)); } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 get_m_Normal_1() const { return ___m_Normal_1; } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 * get_address_of_m_Normal_1() { return &___m_Normal_1; } inline void set_m_Normal_1(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 value) { ___m_Normal_1 = value; } inline static int32_t get_offset_of_m_FaceID_2() { return static_cast<int32_t>(offsetof(RaycastHit_t19695F18F9265FE5425062BBA6A4D330480538C3, ___m_FaceID_2)); } inline uint32_t get_m_FaceID_2() const { return ___m_FaceID_2; } inline uint32_t* get_address_of_m_FaceID_2() { return &___m_FaceID_2; } inline void set_m_FaceID_2(uint32_t value) { ___m_FaceID_2 = value; } inline static int32_t get_offset_of_m_Distance_3() { return static_cast<int32_t>(offsetof(RaycastHit_t19695F18F9265FE5425062BBA6A4D330480538C3, ___m_Distance_3)); } inline float get_m_Distance_3() const { return ___m_Distance_3; } inline float* get_address_of_m_Distance_3() { return &___m_Distance_3; } inline void set_m_Distance_3(float value) { ___m_Distance_3 = value; } inline static int32_t get_offset_of_m_UV_4() { return static_cast<int32_t>(offsetof(RaycastHit_t19695F18F9265FE5425062BBA6A4D330480538C3, ___m_UV_4)); } inline Vector2_tA85D2DD88578276CA8A8796756458277E72D073D get_m_UV_4() const { return ___m_UV_4; } inline Vector2_tA85D2DD88578276CA8A8796756458277E72D073D * get_address_of_m_UV_4() { return &___m_UV_4; } inline void set_m_UV_4(Vector2_tA85D2DD88578276CA8A8796756458277E72D073D value) { ___m_UV_4 = value; } inline static int32_t get_offset_of_m_Collider_5() { return static_cast<int32_t>(offsetof(RaycastHit_t19695F18F9265FE5425062BBA6A4D330480538C3, ___m_Collider_5)); } inline int32_t get_m_Collider_5() const { return ___m_Collider_5; } inline int32_t* get_address_of_m_Collider_5() { return &___m_Collider_5; } inline void set_m_Collider_5(int32_t value) { ___m_Collider_5 = value; } }; // UnityEngine.Component struct Component_t05064EF382ABCAF4B8C94F8A350EA85184C26621 : public Object_tAE11E5E46CD5C37C9F3E8950C00CD8B45666A2D0 { public: public: }; // UnityEngine.Collider struct Collider_t0FEEB36760860AD21B3B1F0509C365B393EC4BDF : public Component_t05064EF382ABCAF4B8C94F8A350EA85184C26621 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif // UnityEngine.Object UnityEngine.Object::FindObjectFromInstanceID(System.Int32) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Object_tAE11E5E46CD5C37C9F3E8950C00CD8B45666A2D0 * Object_FindObjectFromInstanceID_m7594ED98F525AAE38FEC80052729ECAF3E821350 (int32_t ___instanceID0, const RuntimeMethod* method); // UnityEngine.Collider UnityEngine.RaycastHit::get_collider() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Collider_t0FEEB36760860AD21B3B1F0509C365B393EC4BDF * RaycastHit_get_collider_mE70B84C4312B567344F60992A6067855F2C3A7A9 (RaycastHit_t19695F18F9265FE5425062BBA6A4D330480538C3 * __this, const RuntimeMethod* method); // UnityEngine.Vector3 UnityEngine.RaycastHit::get_point() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 RaycastHit_get_point_m0E564B2A72C7A744B889AE9D596F3EFA55059001 (RaycastHit_t19695F18F9265FE5425062BBA6A4D330480538C3 * __this, const RuntimeMethod* method); // UnityEngine.Vector3 UnityEngine.RaycastHit::get_normal() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 RaycastHit_get_normal_mF736A6D09D98D63AB7E5BF10F38AEBFC177A1D94 (RaycastHit_t19695F18F9265FE5425062BBA6A4D330480538C3 * __this, const RuntimeMethod* method); // System.Single UnityEngine.RaycastHit::get_distance() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float RaycastHit_get_distance_m1CBA60855C35F29BBC348D374BBC76386A243543 (RaycastHit_t19695F18F9265FE5425062BBA6A4D330480538C3 * __this, const RuntimeMethod* method); #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Collider UnityEngine.RaycastHit::get_collider() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Collider_t0FEEB36760860AD21B3B1F0509C365B393EC4BDF * RaycastHit_get_collider_mE70B84C4312B567344F60992A6067855F2C3A7A9 (RaycastHit_t19695F18F9265FE5425062BBA6A4D330480538C3 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (RaycastHit_get_collider_mE70B84C4312B567344F60992A6067855F2C3A7A9_MetadataUsageId); s_Il2CppMethodInitialized = true; } Collider_t0FEEB36760860AD21B3B1F0509C365B393EC4BDF * V_0 = NULL; { int32_t L_0 = __this->get_m_Collider_5(); IL2CPP_RUNTIME_CLASS_INIT(Object_tAE11E5E46CD5C37C9F3E8950C00CD8B45666A2D0_il2cpp_TypeInfo_var); Object_tAE11E5E46CD5C37C9F3E8950C00CD8B45666A2D0 * L_1 = Object_FindObjectFromInstanceID_m7594ED98F525AAE38FEC80052729ECAF3E821350(L_0, /*hidden argument*/NULL); V_0 = ((Collider_t0FEEB36760860AD21B3B1F0509C365B393EC4BDF *)IsInstClass((RuntimeObject*)L_1, Collider_t0FEEB36760860AD21B3B1F0509C365B393EC4BDF_il2cpp_TypeInfo_var)); goto IL_0014; } IL_0014: { Collider_t0FEEB36760860AD21B3B1F0509C365B393EC4BDF * L_2 = V_0; return L_2; } } IL2CPP_EXTERN_C Collider_t0FEEB36760860AD21B3B1F0509C365B393EC4BDF * RaycastHit_get_collider_mE70B84C4312B567344F60992A6067855F2C3A7A9_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method) { int32_t _offset = 1; RaycastHit_t19695F18F9265FE5425062BBA6A4D330480538C3 * _thisAdjusted = reinterpret_cast<RaycastHit_t19695F18F9265FE5425062BBA6A4D330480538C3 *>(__this + _offset); return RaycastHit_get_collider_mE70B84C4312B567344F60992A6067855F2C3A7A9(_thisAdjusted, method); } // UnityEngine.Vector3 UnityEngine.RaycastHit::get_point() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 RaycastHit_get_point_m0E564B2A72C7A744B889AE9D596F3EFA55059001 (RaycastHit_t19695F18F9265FE5425062BBA6A4D330480538C3 * __this, const RuntimeMethod* method) { Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 V_0; memset((&V_0), 0, sizeof(V_0)); { Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_0 = __this->get_m_Point_0(); V_0 = L_0; goto IL_000a; } IL_000a: { Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_1 = V_0; return L_1; } } IL2CPP_EXTERN_C Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 RaycastHit_get_point_m0E564B2A72C7A744B889AE9D596F3EFA55059001_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method) { int32_t _offset = 1; RaycastHit_t19695F18F9265FE5425062BBA6A4D330480538C3 * _thisAdjusted = reinterpret_cast<RaycastHit_t19695F18F9265FE5425062BBA6A4D330480538C3 *>(__this + _offset); return RaycastHit_get_point_m0E564B2A72C7A744B889AE9D596F3EFA55059001(_thisAdjusted, method); } // UnityEngine.Vector3 UnityEngine.RaycastHit::get_normal() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 RaycastHit_get_normal_mF736A6D09D98D63AB7E5BF10F38AEBFC177A1D94 (RaycastHit_t19695F18F9265FE5425062BBA6A4D330480538C3 * __this, const RuntimeMethod* method) { Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 V_0; memset((&V_0), 0, sizeof(V_0)); { Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_0 = __this->get_m_Normal_1(); V_0 = L_0; goto IL_000a; } IL_000a: { Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_1 = V_0; return L_1; } } IL2CPP_EXTERN_C Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 RaycastHit_get_normal_mF736A6D09D98D63AB7E5BF10F38AEBFC177A1D94_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method) { int32_t _offset = 1; RaycastHit_t19695F18F9265FE5425062BBA6A4D330480538C3 * _thisAdjusted = reinterpret_cast<RaycastHit_t19695F18F9265FE5425062BBA6A4D330480538C3 *>(__this + _offset); return RaycastHit_get_normal_mF736A6D09D98D63AB7E5BF10F38AEBFC177A1D94(_thisAdjusted, method); } // System.Single UnityEngine.RaycastHit::get_distance() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float RaycastHit_get_distance_m1CBA60855C35F29BBC348D374BBC76386A243543 (RaycastHit_t19695F18F9265FE5425062BBA6A4D330480538C3 * __this, const RuntimeMethod* method) { float V_0 = 0.0f; { float L_0 = __this->get_m_Distance_3(); V_0 = L_0; goto IL_000a; } IL_000a: { float L_1 = V_0; return L_1; } } IL2CPP_EXTERN_C float RaycastHit_get_distance_m1CBA60855C35F29BBC348D374BBC76386A243543_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method) { int32_t _offset = 1; RaycastHit_t19695F18F9265FE5425062BBA6A4D330480538C3 * _thisAdjusted = reinterpret_cast<RaycastHit_t19695F18F9265FE5425062BBA6A4D330480538C3 *>(__this + _offset); return RaycastHit_get_distance_m1CBA60855C35F29BBC348D374BBC76386A243543(_thisAdjusted, method); } #ifdef __clang__ #pragma clang diagnostic pop #endif
44.562319
247
0.848055
[ "object" ]
2c762793acbc806fda07a93ee353b7266b9c3bdd
26,247
cpp
C++
DXSDK30/sdk/samples/iklowns/cglevel.cpp
prefetchnta/dxsdk_old
beb6a7bd52dd1ae8460cf9dc810113f1e87a56fc
[ "CC0-1.0" ]
1
2022-03-21T06:31:34.000Z
2022-03-21T06:31:34.000Z
DXSDK30/sdk/samples/iklowns/cglevel.cpp
prefetchnta/dxsdk_old
beb6a7bd52dd1ae8460cf9dc810113f1e87a56fc
[ "CC0-1.0" ]
null
null
null
DXSDK30/sdk/samples/iklowns/cglevel.cpp
prefetchnta/dxsdk_old
beb6a7bd52dd1ae8460cf9dc810113f1e87a56fc
[ "CC0-1.0" ]
null
null
null
/*===========================================================================*\ | | File: cglevel.cpp | | Description: | |----------------------------------------------------------------------------- | | Copyright (C) 1995-1996 Microsoft Corporation. All Rights Reserved. | | Written by Moss Bay Engineering, Inc. under contract to Microsoft Corporation | \*===========================================================================*/ /************************************************************************** (C) Copyright 1995-1996 Microsoft Corp. All rights reserved. You have a royalty-free right to use, modify, reproduce and distribute the Sample Files (and/or any modified version) in any way you find useful, provided that you agree that Microsoft has no warranty obligations or liability for any Sample Application Files which are modified. we do not recomend you base your game on IKlowns, start with one of the other simpler sample apps in the GDK **************************************************************************/ #include <windows.h> #include <linklist.h> #include "cggraph.h" #include "cglevel.h" #include "cgtimer.h" #include "cgchdll.h" #include "cgchrint.h" #include "strrec.h" #include "cginput.h" #include "cgchar.h" #include "cgimage.h" #include "cgmidi.h" #include "cgremote.h" #include "cgsound.h" #include "cgglobl.h" #include "cgtext.h" #include "cgrsrce.h" void dbgprintf(char *fmt,...); extern LPSTR NewStringResource( HINSTANCE hInst, int idString ); extern void GetRectFromProfile(RECT &, LPSTR, LPSTR, LPSTR); extern CGameTimer * Timer; static RECT WholeScreen = { 0,0,SCREEN_WIDTH,SCREEN_HEIGHT }; HDC LoadBitmapFile ( LPSTR pBitmapFile ); #define BASE_HWND ghMainWnd /*---------------------------------------------------------------------------*\ | | Class CGameLevel | | DESCRIPTION: | | | \*---------------------------------------------------------------------------*/ // this is ONLY for the Klown; it must match the corresponding entry in cgkrusty.cpp typedef struct { int curState; int LastMouseX; int LastMouseY; DWORD timeLastUpdate; int HitsLeft; int pushedState; CGameCharacter * myPie; int type; // 0 = main; 1=computer; 2= second; int IGotKilled; } KLOWN_DATA; extern int gGameMode; CGameLevel::CGameLevel( char *pFileName, TCHAR * pLevelName, CGameTimer* pTimer, CGameInput* pInput, CGameScreen* pScreen ) : mpGraphics( NULL ), mpTimer( pTimer ), mpInput( pInput ), mpScreen( pScreen ), mOffsetX( 0 ), mOffsetY( 0 ), mFrameTime( 0 ), mpGraphicsKey( NULL ), mFastKlown( FALSE ), mpProfile( NULL ) { char DllList[256]; mMainKlown = NULL; // first scan internal table of characters: LoadCharInfo( NULL ); // Grab info from the GAM file; look for character DLLs and load them... lstrcpy(DllList, ""); GetPrivateProfileString("General", "DLLS", "", DllList, 255, pFileName); if (strlen(DllList) > 0) { CStringRecord crec(DllList, ","); int x; char dlldir[260]; char *p; lstrcpy( dlldir, pFileName ); p = strrchr( dlldir, '/' ); if ( p == NULL ) p = strrchr( dlldir, '\\' ); if ( p != NULL ) lstrcpy( p + 1, "*.dll" ); for (x=0; x<crec.GetNumFields(); x++) { LoadMyDLL(dlldir, crec[x]); } } MatchProfile(pFileName); char prof[256]; GetPrivateProfileString( pLevelName, mpProfile, pLevelName, // default to level name prof, sizeof(prof), pFileName ); pLevName = new char [lstrlen(prof)+1]; lstrcpy(pLevName, prof); pFilName = new char [lstrlen(pFileName)+1]; lstrcpy(pFilName, pFileName); // Load up any sound effects that are designated as preload. char SoundList[255]; GetPrivateProfileString(pLevName, "PreloadSounds", "", SoundList, sizeof(SoundList) , pFileName); if (strlen(SoundList) > 0) { CStringRecord crec(SoundList, ","); for (int x=0; x<crec.GetNumFields(); x++) { new CSoundEffect(crec[x], 0, FALSE, gSoundMode); } } // init mMaxWorldX = GetPrivateProfileInt(pLevName, "WorldX", SCREEN_HEIGHT, pFileName) / 2; mMaxWorldY = GetPrivateProfileInt(pLevName, "WorldY", SCREEN_WIDTH, pFileName) / 2; mOffsetX = GetPrivateProfileInt(pLevName, "StartX", 0, pFileName); mOffsetY = GetPrivateProfileInt(pLevName, "StartY", 0, pFileName); // now create the characters as needed SetCurrentLevel(this); { // set the screen's palette char paletteFile[256]; GetPrivateProfileString( pLevName, "Palette", "", paletteFile, sizeof( paletteFile ), pFileName ); pScreen->SetPalette( paletteFile ); } char graphicsName[256]; GetPrivateProfileString( pLevName, "Graphics", "", graphicsName, sizeof( graphicsName ), pFileName ); // keep a copy of the section name mpGraphicsKey = new char[lstrlen(graphicsName)+1]; lstrcpy( mpGraphicsKey, graphicsName ); mpGraphics = new CGameDisplayList(pFileName, graphicsName, this); // Add computer opponent(s), second klown, if needed: mGameType = gGameMode; mNumComputerKlowns = mGameType == 0 ? 1 : 0 ; memset(&mComputerKlowns[0], 0, sizeof(mComputerKlowns)); GetPrivateProfileString("General", "RoboKlown", "", DllList, sizeof(DllList), pFileName); int posx, posy; mMainKlown->GetXY(&posx, &posy); for (int x=0; x<mNumComputerKlowns; x++) { // create new klown, computer generated mComputerKlowns[x] = new CGameCharacter(pFileName, DllList, graphicsName, this, mMainKlown->GetMinZ(), mMainKlown->GetMaxZ(), posx + mMainKlown->GetCurWidth() * 2, posy, NULL); if (mComputerKlowns[x]) { mpGraphics->Insert(mComputerKlowns[x]); KLOWN_DATA *data = (KLOWN_DATA *) mComputerKlowns[x]->mpPrivateData; if (data) data->type = 1; // computer opponent; } } // if playing other person on same machine, create opponent; if (mGameType == 1) { // create second klown GetPrivateProfileString("General", "SecondKlown", "", DllList, sizeof(DllList), pFileName); mSecondKlown = new CGameCharacter(pFileName, DllList, graphicsName, this, mMainKlown->GetMinZ(), mMainKlown->GetMaxZ(), posx + mMainKlown->GetCurWidth() * 2 , posy, NULL); if (mSecondKlown) { mpGraphics->Insert(mSecondKlown); KLOWN_DATA *data = (KLOWN_DATA *) mSecondKlown->mpPrivateData; if (data) data->type = 2; // second (human) opponent; } } else mSecondKlown = NULL; mpUpdateList = new CGameUpdateList; mpUpdateList->AddRect(WholeScreen); } CGameCharacter * CGameLevel::Add ( char *name, int curz, int curx, int cury, void *pNewObjID) { CGameCharacter * newchar; if (mpGraphics == NULL) return(NULL); newchar = new CGameCharacter(pFilName, name, mpGraphicsKey, this, curz, curz, curx, cury, pNewObjID); if (newchar) { mpGraphics->Insert(newchar); } return(newchar); } CGameLevel::~CGameLevel( ) { delete[] mpProfile; delete mpGraphics; delete pLevName; delete pFilName; delete mpGraphicsKey; delete mpUpdateList; } BOOL gameover = FALSE; BOOL quit = FALSE; BOOL showing = FALSE; BOOL showFrameRate = FALSE; void CGameLevel::GameOver() { gameover = TRUE; } void CGameLevel::StopAnimating() { showing = FALSE; } void CGameLevel::Animate( HWND hwndParent, CGameScreen * pScreen ) { SetCapture( hwndParent ); // so we get mouse clicks // turn off the cursor HCURSOR hOldCursor = SetCursor( NULL ); // pScreen->SetMode( SCREEN_WIDTH, SCREEN_HEIGHT, 8 ); showing = TRUE; MSG msg; Timer->Time = timeGetTime(); // * 60 / 1000; UINT lastTime = Timer->Time; mFrameTime = lastTime; UINT elapsed = 0; #define DEBOUNCE_FRAMES 12 static int debounceF2 = 0; static int debounceF3 = 0; static int debounceF5 = 0; static int debounceF9 = 0; #define FRAMERATE #define SCORE_WIDTH 64 #define SCORE_HEIGHT 64 CGameDSBitBuffer* pScoreFrameBufferLeft; CGameDSBitBuffer* pScoreFrameBufferRight; HDC hdcWindow = GetDC(hwndParent); HDC hdcScoreLeft = CreateCompatibleDC(hdcWindow); HDC hdcScoreRight = CreateCompatibleDC(hdcWindow); ReleaseDC(hwndParent, hdcWindow); pScoreFrameBufferLeft = new CGameDSBitBuffer( SCORE_WIDTH, SCORE_HEIGHT); pScoreFrameBufferRight = new CGameDSBitBuffer( SCORE_WIDTH, SCORE_HEIGHT); SelectObject(hdcScoreLeft, pScoreFrameBufferLeft->GetHBitmap()); SelectObject(hdcScoreRight, pScoreFrameBufferRight->GetHBitmap()); SetBkMode(hdcScoreLeft, TRANSPARENT); SetBkMode(hdcScoreRight, TRANSPARENT); // set up our cool font LOGFONT logFont; HANDLE hFont; memset(&logFont, 0, sizeof(LOGFONT)); logFont.lfHeight = SCORE_HEIGHT; //maxHeight; logFont.lfPitchAndFamily = FF_ROMAN; hFont = CreateFontIndirect(&logFont); SelectObject(hdcScoreLeft, hFont); SetTextColor(hdcScoreLeft, PALETTEINDEX(4)); SelectObject(hdcScoreRight, hFont); SetTextColor(hdcScoreRight, PALETTEINDEX(4)); int lastScoreLeft = -1; int lastScoreRight = -1; #ifdef FRAMERATE #define FR_WIDTH 32 #define FR_HEIGHT 32 UINT frames = 0; UINT frameTime = timeGetTime(); // create a memory bitmap for our frame text CGameDSBitBuffer* pFrameBuffer; HDC hdc = GetDC( hwndParent ); HDC hdcFrame = CreateCompatibleDC( hdc ); pFrameBuffer = new CGameDSBitBuffer( FR_WIDTH, FR_HEIGHT); SelectObject( hdcFrame, pFrameBuffer->GetHBitmap() ); // set up our cool font LOGFONT logFont2; HANDLE hFont2; memset(&logFont2, 0, sizeof(LOGFONT)); logFont2.lfHeight = FR_HEIGHT; //maxHeight; logFont2.lfPitchAndFamily = FF_ROMAN; hFont2 = CreateFontIndirect(&logFont2); SelectObject(hdcFrame, hFont2); SetTextColor(hdcFrame, COLOR_RED); SetBkMode(hdcFrame, TRANSPARENT); memset(pFrameBuffer->GetBits(), 1, FR_WIDTH * FR_HEIGHT); TextOut( hdcFrame, 0,0, "30", 2 ); frames = 0; #endif // FRAMERATE Timer->Resume(); if (gMusicOn) { resumeMusic(); } #ifndef DEBUG HANDLE hprocess; hprocess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, GetCurrentProcessId()); SetPriorityClass(hprocess, HIGH_PRIORITY_CLASS ); CloseHandle(hprocess); #endif while ( showing ) { Timer->Time = timeGetTime(); UINT time = Timer->Time; if ( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE | PM_NOYIELD ) ) { TranslateMessage(&msg); if ((msg.message == WM_ACTIVATEAPP) && (LOWORD(msg.wParam) == WA_INACTIVE)) { showing = FALSE; DispatchMessage(&msg); continue; } else DispatchMessage(&msg); } if (mpInput->GetKeyboard(VK_ESCAPE) || mpInput->GetKeyboard(VK_F12)) { showing = FALSE; if (!mpInput->GetKeyboard(VK_CONTROL)) { quit = TRUE; } continue; } // toggles need to be debounced if (mpInput->GetKeyboard(VK_F2) && (debounceF2 == 0)) { // mute! gMusicOn = !gMusicOn; if (gMusicOn) { resumeMusic(); } else { pauseMusic(); } debounceF2 = DEBOUNCE_FRAMES; } if (debounceF2) --debounceF2; if (mpInput->GetKeyboard(VK_F3) && (debounceF3 == 0)) { extern BOOL gbQuiet; SetSilence(!gbQuiet); debounceF3 = DEBOUNCE_FRAMES; } if (debounceF3) --debounceF3; if (mpInput->GetKeyboard(VK_F9) && (debounceF9 == 0)) { mFastKlown = !mFastKlown; debounceF9 = DEBOUNCE_FRAMES; } if (debounceF9) --debounceF9; #ifdef FRAMERATE if (mpInput->GetKeyboard(VK_F5) && (debounceF5 == 0)) { showFrameRate = !showFrameRate; debounceF5 = DEBOUNCE_FRAMES; } if (debounceF5) --debounceF5; #endif lastTime = time; // If we are playing a network game, we // poll here synchronously for the remote network activity { extern void PollForRemoteReceive( void ); if ( mGameType > 1 ) { PollForRemoteReceive(); } } // !!! if we want to limit our framerate, put a check here for elapsed time { mFrameTime = time; // let each object update position, get input, etc mpGraphics->Update(this, mpUpdateList); // let each object render its graphical image mpGraphics->Render(this, pScreen, mpUpdateList); mpUpdateList->Clear(); // get the correct score to show... there is always at least *one* KLOWN_DATA * pKlown; RECT score_rect; char scorebuf[5]; pKlown = (KLOWN_DATA *) mMainKlown->mpPrivateData; score_rect.left = 10; score_rect.right = 10+SCORE_WIDTH; score_rect.top = 10; score_rect.bottom = 10+SCORE_HEIGHT; mpUpdateList->AddRect(score_rect); if (pKlown->HitsLeft != lastScoreLeft) { lastScoreLeft = pKlown->HitsLeft; wsprintf(scorebuf, "%d", pKlown->HitsLeft); memset(pScoreFrameBufferLeft->GetBits(), 1, SCORE_WIDTH * SCORE_HEIGHT); TextOut(hdcScoreLeft, 0, 0, scorebuf, lstrlen(scorebuf)); } pScreen->TransRender(10,10,SCORE_WIDTH, SCORE_HEIGHT, pScoreFrameBufferLeft,0,0); switch (mGameType) { case 0: // against computer pKlown = (KLOWN_DATA *) mComputerKlowns[0]->mpPrivateData; break; case 1: pKlown = (KLOWN_DATA *) mSecondKlown->mpPrivateData; break; default: pKlown = NULL; break; } if (pKlown != NULL) { score_rect.left = SCREEN_WIDTH -10 - SCORE_WIDTH; score_rect.right = SCREEN_WIDTH -10; mpUpdateList->AddRect(score_rect); if (pKlown->HitsLeft != lastScoreRight) { lastScoreRight = pKlown->HitsLeft; wsprintf(scorebuf, "%d", pKlown->HitsLeft); memset(pScoreFrameBufferRight->GetBits(), 1, SCORE_WIDTH * SCORE_HEIGHT); TextOut(hdcScoreRight, 0, 0, scorebuf, lstrlen(scorebuf)); } pScreen->TransRender(SCREEN_WIDTH -10-SCORE_WIDTH,10, SCORE_WIDTH, SCORE_HEIGHT, pScoreFrameBufferRight,0,0); } #ifdef FRAMERATE if (showFrameRate) { ++frames; UINT newTime = timeGetTime(); UINT dTime = newTime - frameTime; if (dTime >= 1000 ) { char buf[4]; memset(pFrameBuffer->GetBits(), 1, FR_WIDTH * FR_HEIGHT); wsprintf(buf, "%d", frames / (dTime / 1000) ); TextOut( hdcFrame, 0,0, buf, lstrlen(buf) ); frames = 0; frameTime = newTime; } pScreen->TransRender( 320 - (FR_WIDTH >> 1), 10, FR_WIDTH, FR_HEIGHT, pFrameBuffer, 0, 0 ); } else { // keep frametime updated frameTime = time; } #endif // FRAMERATE // update the screen pScreen->PageFlip(); mpInput->UpdateJoystick(); if (gameover) { RECT rect; char tempstring[20]; pKlown = (KLOWN_DATA *) mMainKlown->mpPrivateData; Sleep(2000); GetPrivateProfileString( pLevName, "WinLose", "end.bmp", tempstring, 19, pFilName); CGameDIB * myDib = new CGameDIB(tempstring); CGameDSBitBuffer * myBuf = new CGameDSBitBuffer(myDib); if (myBuf) { RECT rectdtop; HDC hdcWindow = GetDC(hwndParent); HDC hdc = CreateCompatibleDC(hdcWindow); ReleaseDC(hwndParent, hdcWindow); rectdtop.left = 0; rectdtop.right = SCREEN_WIDTH; rectdtop.top = 0; rectdtop.bottom = SCREEN_HEIGHT; mpUpdateList->AddRect(rectdtop); SelectObject(hdc, myBuf->GetHBitmap()); // make the gameover bitmap fill current screen rect = rectdtop; CGameText * pCtext = new CGameText (hdc, &rect, 12,1); if (pCtext) { int ix, ixend; pKlown = (KLOWN_DATA *) mMainKlown->mpPrivateData; pKlown->curState = 0; ix = pKlown->IGotKilled ? IDS_LOSE_START : IDS_WIN_START; ixend = pKlown->IGotKilled ? IDS_LOSE_END : IDS_WIN_END; // load strings... while (ix <= ixend) { char *pChoice = NewStringResource(ghInst, ix); pCtext->AddLine(pChoice, COLOR_YELLOW); ++ix; } // Overlay text on bitmap pCtext->TextBlt(); delete pCtext; } // // Display option screen! pScreen->Render( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, myBuf, 0, 0, SRCCOPY ); pScreen->PageFlip(); Sleep(5000); pScreen->PageFlip(); DeleteDC(hdc); delete myBuf; } delete myDib; // reset igotkilled flag... pKlown->IGotKilled = 0; if (mComputerKlowns[0]) { pKlown = (KLOWN_DATA *) mComputerKlowns[0]->mpPrivateData; if (pKlown) { pKlown->curState = 0; pKlown->IGotKilled = 0; } } if (mSecondKlown) { pKlown = (KLOWN_DATA *) mSecondKlown->mpPrivateData; if (pKlown) { pKlown->curState = 0; pKlown->IGotKilled = 0; } } gameover = FALSE; lastScoreLeft = lastScoreRight = -1; } // if (gameover) } // limit block } // while Timer->Pause(); SetCursor( hOldCursor ); ReleaseCapture( ); if (gMusicOn) { pauseMusic(); } #ifndef DEBUG hprocess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, GetCurrentProcessId()); SetPriorityClass(hprocess, IDLE_PRIORITY_CLASS ); CloseHandle(hprocess); #endif #ifdef FRAMERATE DeleteDC( hdcFrame ); DeleteObject(hFont2); delete pFrameBuffer; #endif DeleteDC( hdcScoreLeft ); DeleteDC( hdcScoreRight ); DeleteObject(hFont); delete pScoreFrameBufferLeft; delete pScoreFrameBufferRight; ReleaseDC( hwndParent, hdc ); if (quit) PostQuitMessage(0); } void CGameLevel::ForceOnScreen(int *x, int *y, int wide, int high, BOOL primary) { // if the x or y coords are off screen: // 1) force screen to be there - unless // 2) the coords are impossible, then adjust them! #define ROUGH_WIDTH 96 // keep main char in center of screen static RECT center = { SCREEN_WIDTH / 4, 0, SCREEN_WIDTH - (SCREEN_WIDTH / 4) - ROUGH_WIDTH, SCREEN_HEIGHT }; if (*x < -mMaxWorldX) *x = -mMaxWorldX; else { if (*x > (mMaxWorldX-wide)) *x = mMaxWorldX-wide; } if (*y < -mMaxWorldY) *y = -mMaxWorldY; else { if (*y > (mMaxWorldY-wide)) *y = mMaxWorldY-wide; } if (primary) { if ((*x < Screen2WorldX(center.left)) && (mOffsetX > -mMaxWorldX)) { mOffsetX = max(-mMaxWorldX, mOffsetX - (Screen2WorldX(center.left) - *x)); mpUpdateList->AddRect(WholeScreen); } else { if ((*x > Screen2WorldX(center.right)) && (mOffsetX < (mMaxWorldX-SCREEN_WIDTH))) { mOffsetX = min((mMaxWorldX-SCREEN_WIDTH), mOffsetX + (*x - Screen2WorldX(center.right))); mpUpdateList->AddRect(WholeScreen); } } if ((*y < Screen2WorldY(center.top)) && (mOffsetY > -mMaxWorldY)) { mOffsetY = max(-mMaxWorldY, mOffsetY - (Screen2WorldY(center.top) - *y)); mpUpdateList->AddRect(WholeScreen); } else { if ((*y > Screen2WorldY(center.bottom)) && (mOffsetY < (mMaxWorldY-SCREEN_HEIGHT))) { mOffsetY = min((mMaxWorldY-SCREEN_HEIGHT), mOffsetY + (*y - Screen2WorldY(center.bottom))); mpUpdateList->AddRect(WholeScreen); } } } } void CGameLevel::MatchProfile( char* pGamFile ) { static char* pDefault = "Default"; char profBuf[256]; char dataBuf[256]; // first check to see if we need to force a given profile GetPrivateProfileString( "General", "ForceProfile", "", // no default profBuf, sizeof( profBuf ), pGamFile ); if (lstrlen(profBuf) >0) { mpProfile = new char[lstrlen(profBuf)+1]; lstrcpy( mpProfile, profBuf ); } else { GetPrivateProfileString( "Profiles", NULL, // get all "", // no default profBuf, sizeof( profBuf ), pGamFile ); for (char *pChar = profBuf; *pChar; pChar++) { GetPrivateProfileString( "Profiles", pChar, "", dataBuf, sizeof( dataBuf ), pGamFile ); // parse the data string into fields CStringRecord fields( dataBuf, "," ); MC_PROCESSOR processor = (MC_PROCESSOR) atoi(fields[0]); MC_BUSTYPE bus = (MC_BUSTYPE) atoi(fields[1]); // memory fields are in megabytes DWORD sysMem = atoi(fields[2]) * 1024 * 1024; DWORD vidMem = atoi(fields[3]) * 1024 * 1024; MC_VIDSYS vidSys = (MC_VIDSYS) atoi(fields[4]); if ((gMachineCaps.processor >= processor) && (gMachineCaps.bus >= bus) && (gMachineCaps.sysMemory >= sysMem) && (gMachineCaps.vidMemory >= vidMem) && (gMachineCaps.vidSystem >= vidSys)) { mpProfile = new char[lstrlen(pChar)+1]; lstrcpy( mpProfile, pChar ); break; } pChar += lstrlen( pChar ); // move beyond terminator } // if we didn't find it, use default if (mpProfile == NULL) { mpProfile = new char[lstrlen(pDefault)+1]; lstrcpy( mpProfile, pDefault ); } } }
29.590755
117
0.497809
[ "render", "object" ]
2c7e127272c7fb2094fd52c9d3e7b5b16dcc107d
49,775
cpp
C++
d-mon/dstr.cpp
DavydMon/plib_ios
10de286c9b517e9f9a39c306256b3d4a24f11da3
[ "MIT" ]
null
null
null
d-mon/dstr.cpp
DavydMon/plib_ios
10de286c9b517e9f9a39c306256b3d4a24f11da3
[ "MIT" ]
null
null
null
d-mon/dstr.cpp
DavydMon/plib_ios
10de286c9b517e9f9a39c306256b3d4a24f11da3
[ "MIT" ]
null
null
null
/* $Id:$ $Change:$ $DateTime:$ $Author:$ */ #include <string.h> #include "dmain.h" #include "dstr.h" #ifdef LINUX namespace dmon { #endif const char dlib_hex_symbol_table[16]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; const char *dlib_word_hex_symbols_table[256] = { "00","01","02","03","04","05","06","07","08","09","0A","0B","0C","0D","0E","0F", "10","11","12","13","14","15","16","17","18","19","1A","1B","1C","1D","1E","1F", "20","21","22","23","24","25","26","27","28","29","2A","2B","2C","2D","2E","2F", "30","31","32","33","34","35","36","37","38","39","3A","3B","3C","3D","3E","3F", "40","41","42","43","44","45","46","47","48","49","4A","4B","4C","4D","4E","4F", "50","51","52","53","54","55","56","57","58","59","5A","5B","5C","5D","5E","5F", "60","61","62","63","64","65","66","67","68","69","6A","6B","6C","6D","6E","6F", "70","71","72","73","74","75","76","77","78","79","7A","7B","7C","7D","7E","7F", "80","81","82","83","84","85","86","87","88","89","8A","8B","8C","8D","8E","8F", "90","91","92","93","94","95","96","97","98","99","9A","9B","9C","9D","9E","9F", "A0","A1","A2","A3","A4","A5","A6","A7","A8","A9","AA","AB","AC","AD","AE","AF", "B0","B1","B2","B3","B4","B5","B6","B7","B8","B9","BA","BB","BC","BD","BE","BF", "C0","C1","C2","C3","C4","C5","C6","C7","C8","C9","CA","CB","CC","CD","CE","CF", "D0","D1","D2","D3","D4","D5","D6","D7","D8","D9","DA","DB","DC","DD","DE","DF", "E0","E1","E2","E3","E4","E5","E6","E7","E8","E9","EA","EB","EC","ED","EE","EF", "F0","F1","F2","F3","F4","F5","F6","F7","F8","F9","FA","FB","FC","FD","FE","FF" }; const char *dlib_word_hex_symbols_table_a[256] = { "00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f", "10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f", "20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f", "30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f", "40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f", "50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f", "60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f", "70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f", "80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f", "90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f", "a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af", "b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf", "c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf", "d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df", "e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef", "f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff" }; byte dlib_hex_table[256] = { 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff }; char* dispace(char *str,bool enter) { if(!str) return 0; while(*str) { if(!(*str == 0x20 || *str == 0x09)) { if(!enter) break; else if(!((*str == 0x0d) || (*str == 0x0a))) break; } str++; } return str; } char* dispace_fixlen(char *str,dword str_len,bool enter,dword *dl) { dword l = 0; if(!str) return 0; for(dword i=0;i<str_len;i++) { if(!(*str == 0x20 || *str == 0x09)) { if(!enter) break; else if(!((*str == 0x0d) || (*str == 0x0a))) break; } str++; l++; } if(dl) *dl = l; return str; } char* dnspace(char *str) { if(!str) return 0; while(*str > 0x20) str++; return str; } char* dnspace_fixlen(char *str,dword str_len,dword *dl) { dword l = 0; if(!str) return 0; for(dword i=0;i<str_len;i++) { if(*str <= 0x20) break; str++; l++; } if(dl) *dl = l; return str; } char* dnsymbol_fixlen(char *str,dword str_len,char symbol,bool space,bool cs,dword *dl) { dword l = 0; char s; if(!str) return 0; for(dword i=0;i<str_len;i++) { s = *str; if(s == symbol) break; if(space && (s == ' ')) break; if(cs && (*str < 0x20)) break; str++; l++; } if(dl) *dl = l; return str; } inline char* dnspace_i(char *str) { if(!str) return 0; while(*str > 0x20) str++; return str; } char* dstr_trim(char *str,bool enter) { dword i,len; char *s; if(!str) return 0; str = (char*)dispace(str,enter); if(!str) return 0; len = dstrlen(str); if(len) { s = str + len - 1; for(i=0;i<len;i++) { if(!((*s == 0x20) || (*s == 0x09))) { if(!enter) break; else if(!((*s == 0x0d) || (*s == 0x0a))) break; } s--; } *(s+1) = 0; } return str; } char* dend_line_fixlen(char *str,dword str_len,dword *dl) { dword l = 0; if(!str) return 0; for(dword i=0;i<str_len;i++) { if((*str == 0x0d) || (*str == 0x0a)) { break; } str++; l++; } if(dl) *dl = l; return str; } char* dnext_line_fixlen(char *str,dword str_len,dword *dl) { dword l = 0; if(!str) return 0; for(dword i=0;i<str_len;i++) { if(*str == 0x0a) { str++; l++; break; } str++; l++; } if(dl) *dl = l; return str; } char* diabc(char *str) { byte t; if(!str) return 0; while(*str) { t = *str; if(t < 0x30) break; if((t > 0x39) && (t < 0x41)) break; if((t > 0x5a) && (t < 0x5f)) break; if((t == 0x60) || (t > 0x7a)) break; str++; } return str; } void dstrcpy(char *str1,char *str2) { if(!str1 || !str2) return; while(*str2) { *str1 = *str2; str1++; str2++; } *str1 = 0; } void dstrncpy(char *str1,char *str2,dword maxlen) { if(!str1 || !str2 || !maxlen) return; while(*str2) { if(!maxlen) break; maxlen--; *str1 = *str2; str1++; str2++; } *str1 = 0; } void dstrcat(char *str1,char *str2) { if(!str1 || !str2) return; while(*str1) str1++; while(*str2) { *str1 = *str2; str1++; str2++; } *str1 = 0; } dword dstrlen(char *str) { dword len = 0; if(!str) return 0; while(*str) { len++; str++; } return len; } dword datod(char *str) { byte symbol; dword ret=0; if(!str) return 0; while(*str) { symbol = *str; symbol -= 0x30; if(symbol > 9) return ret; if(ret > 0x19999999) return 0; ret = (ret * 10); ret = (ret + symbol); str++; } return ret; } dword daton_array(byte *data,dword maxlen,char *str,dword len) { byte symbol; dword ret = 0; if(!data || !str) return 0; for(dword i=0;i<len;i++) { symbol = str[i]; symbol -= 0x30; if(symbol > 9) return ret; if(!maxlen) return 0; data[i] = symbol; ret++; maxlen--; } return ret; } /* byte ddtoa(dword number,char *str,byte count,byte symbol,bool space) { char bcd[5],dest[16]; char *p_bcd,*p_dest,*p_ret; byte c,i,ret; p_bcd = bcd; p_dest = (dest + 1); dest[0] = 48; if(space) { dest[11] = 32; dest[12] = 0; ret = 12; } else { dest[11] = 0; ret = 11; } for(i=0;i<5;i++) bcd[i] = 0; c = count; if(count == 0) c = 1; else if(count > 10) c = 10; c--; __asm { push eax push ebx push ecx push edx mov eax,number mov ecx,32 next: push ecx mov ecx,5 mov ebx,p_bcd j0: mov dl,[ebx] and dl,0fh cmp dl,5 jc j1 add [byte ptr ebx],3 j1: mov dl,[ebx] and dl,0f0h cmp dl,80 jc j2 add [byte ptr ebx],48 j2: inc ebx loop j0 shl eax,1 mov ecx,5 dec ebx j3: rcl byte ptr [ebx],byte ptr 1 dec ebx loop j3 pop ecx loop next mov ecx,5 mov ebx,p_bcd mov edx,p_dest next2: mov al,[ebx] and al,0f0h ror al,4 add al,48 mov [edx],al inc edx mov al,[ebx] and al,0fh add al,48 mov [edx],al inc edx inc ebx loop next2 pop edx pop ecx pop ebx pop eax } p_dest = (p_dest + 9 - c); p_ret = p_dest; for(i=0;i<c;i++) { if(*p_dest != 48) break; *p_dest = symbol; p_dest++; } if(symbol == 0) p_ret = p_dest; ret += (byte)(dest - p_ret); memcpy(str,p_ret,ret); str[ret] = 0; return ret; } */ byte ddtoa(dword value,char *str,byte count,byte symbol,byte end_space_count) { char buf[12]; char *p; dword temp; byte d,i,c,ret; if(!str) return 0; p = buf + 11; c = 0; do { temp = (value / 10); d = (unsigned) (value - (temp * 10)); value = temp; *p-- = (char) (d + '0'); c++; } while (value > 0); p++; ret = c; if(symbol) { if(count > c) { ret = count; count = (count - c); for(i=0;i<count;i++) *str++ = symbol; } } for(i=0;i<c;i++) *str++ = *p++; if(end_space_count) { for(i=0;i<end_space_count;i++) *str++ = ' '; ret += end_space_count; } *str = 0; return ret; } byte dqtoa(qword value,char *str,byte count,byte symbol,byte end_space_count) { char buf[22]; char *p; qword temp; byte d,i,c,ret; if(!str) return 0; p = buf + 21; c = 0; do { temp = (value / 10); d = (unsigned) (value - (temp * 10)); value = temp; *p-- = (char) (d + '0'); c++; } while (value > 0); p++; ret = c; if(symbol) { if(count > c) { ret = count; count = (count - c); for(i=0;i<count;i++) *str++ = symbol; } } for(i=0;i<c;i++) *str++ = *p++; if(end_space_count) { for(i=0;i<end_space_count;i++) *str++ = ' '; ret += end_space_count; } *str = 0; return ret; } byte ddtoaf(dword value,char *str) { char buf[12]; char *p; dword temp; byte d,i,c,ret; if(!str) return 0; p = buf + 11; c = 0; do { temp = (value / 10); d = (unsigned) (value - (temp * 10)); value = temp; *p-- = (char) (d + '0'); c++; } while (value > 0); p++; ret = c; for(i=0;i<c;i++) *str++ = *p++; *str = 0; return ret; } byte dqtoaf(qword value,char *str) { char buf[22]; char *p; qword temp; byte d,i,c,ret; if(!str) return 0; p = buf + 21; c = 0; do { temp = (value / 10); d = (unsigned) (value - (temp * 10)); value = temp; *p-- = (char) (d + '0'); c++; } while (value > 0); p++; ret = c; for(i=0;i<c;i++) *str++ = *p++; *str = 0; return ret; } byte ddtoaex(dword value,char *str,dword str_max_size,byte count,byte symbol,byte end_space_count) { char buf[12]; char *p,*s; dword temp; byte d,i,c,ret; if(!str || !str_max_size) return 0; s = str; p = buf + 11; c = 0; do { temp = (value / 10); d = (unsigned) (value - (temp * 10)); value = temp; *p-- = (char) (d + '0'); c++; } while (value > 0); p++; ret = c; if(symbol) { if(count > c) { ret = count; count = (count - c); if((dword)count > str_max_size) { *s = 0; return 0; } for(i=0;i<count;i++) *str++ = symbol; str_max_size -= count; } } if((dword)c > str_max_size) { *s = 0; return 0; } for(i=0;i<c;i++) *str++ = *p++; str_max_size -= c; if(end_space_count) { if((dword)end_space_count > str_max_size) { *s = 0; return 0; } for(i=0;i<end_space_count;i++) *str++ = ' '; str_max_size -= end_space_count; ret += end_space_count; } if(!str_max_size) { *s = 0; return 0; } *str = 0; return ret; } byte dqtoaex(qword value,char *str,dword str_max_size,byte count,byte symbol,byte end_space_count) { char buf[22]; char *p,*s; qword temp; byte d,i,c,ret; if(!str || !str_max_size) return 0; s = str; p = buf + 21; c = 0; do { temp = (value / 10); d = (unsigned) (value - (temp * 10)); value = temp; *p-- = (char) (d + '0'); c++; } while (value > 0); p++; ret = c; if(symbol) { if(count > c) { ret = count; count = (count - c); if((dword)count > str_max_size) { *s = 0; return 0; } for(i=0;i<count;i++) *str++ = symbol; str_max_size -= count; } } if((dword)c > str_max_size) { *s = 0; return 0; } for(i=0;i<c;i++) *str++ = *p++; str_max_size -= c; if(end_space_count) { if((dword)end_space_count > str_max_size) { *s = 0; return 0; } for(i=0;i<end_space_count;i++) *str++ = ' '; str_max_size -= end_space_count; ret += end_space_count; } if(!str_max_size) { *s = 0; return 0; } *str = 0; return ret; } byte ddtoafex(dword value,char *str,dword str_max_size) { char buf[12]; char *p; dword temp; byte d,i,c,ret; if(!str || !str_max_size) return 0; p = buf + 11; c = 0; do { temp = (value / 10); d = (unsigned) (value - (temp * 10)); value = temp; *p-- = (char) (d + '0'); c++; } while (value > 0); p++; ret = c; if((dword)(c+1) > str_max_size) { *str = 0; return 0; } for(i=0;i<c;i++) *str++ = *p++; *str = 0; return ret; } byte dqtoafex(qword value,char *str,dword str_max_size) { char buf[22]; char *p; qword temp; byte d,i,c,ret; if(!str || !str_max_size) return 0; p = buf + 21; c = 0; do { temp = (value / 10); d = (unsigned) (value - (temp * 10)); value = temp; *p-- = (char) (d + '0'); c++; } while (value > 0); p++; ret = c; if((dword)(c+1) > str_max_size) { *str = 0; return 0; } for(i=0;i<c;i++) *str++ = *p++; *str = 0; return ret; } byte dltoa(sdword value,char *str,byte end_space_count) { byte ret; if(!str) return 0; if(value >= 0) return ddtoa((dword)value,str,10,0,end_space_count); ret = ddtoa((dword)(-(sdword)value),str+1,10,0,end_space_count); if(!ret) return 0; *str = '-'; return (ret + 1); } byte dsqtoa(sqword value,char *str,byte end_space_count) { byte ret; if(!str) return 0; if(value >= 0) return dqtoa((qword)value,str,20,0,end_space_count); ret = dqtoa((qword)(-(sqword)value),str+1,20,0,end_space_count); if(!ret) return 0; *str = '-'; return (ret + 1); } byte dltoaf(sdword value,char *str) { byte ret; if(!str) return 0; if(value >= 0) return ddtoaf((dword)value,str); ret = ddtoaf((dword)(-(sdword)value),str+1); if(!ret) return 0; *str = '-'; return (ret + 1); } byte dqstoaf(sqword value,char *str) { byte ret; if(!str) return 0; if(value >= 0) return dqtoaf((qword)value,str); ret = dqtoaf((qword)(-(sqword)value),str+1); if(!ret) return 0; *str = '-'; return (ret + 1); } byte dltoaex(sdword value,char *str,dword str_max_size,byte end_space_count) { byte ret; if(!str) return 0; if(value >= 0) return ddtoaex((dword)value,str,str_max_size,10,0,end_space_count); if(str_max_size < 2) return 0; ret = ddtoaex((dword)(-(sdword)value),str+1,str_max_size-1,10,0,end_space_count); if(!ret || ((dword)ret >= str_max_size)) { *str = 0; return 0; } *str = '-'; return (ret + 1); } byte dsqtoaex(sqword value,char *str,dword str_max_size,byte end_space_count) { byte ret; if(!str) return 0; if(value >= 0) return dqtoaex((qword)value,str,str_max_size,20,0,end_space_count); if(str_max_size < 2) return 0; ret = dqtoaex((qword)(-(sqword)value),str+1,str_max_size-1,20,0,end_space_count); if(!ret || ((dword)ret >= str_max_size)) { *str = 0; return 0; } *str = '-'; return (ret + 1); } byte dltoafex(sdword value,char *str,dword str_max_size) { byte ret; if(!str) return 0; if(value >= 0) return ddtoafex((dword)value,str,str_max_size); if(str_max_size < 2) return 0; ret = ddtoafex((dword)(-(sdword)value),str+1,str_max_size-1); if(!ret || ((dword)ret >= str_max_size)) { *str = 0; return 0; } *str = '-'; return (ret + 1); } byte dsqtoafex(sqword value,char *str,dword str_max_size) { byte ret; if(!str) return 0; if(value >= 0) return dqtoafex((qword)value,str,str_max_size); if(str_max_size < 2) return 0; ret = dqtoafex((qword)(-(sqword)value),str+1,str_max_size-1); if(!ret || ((dword)ret >= str_max_size)) { *str = 0; return 0; } *str = '-'; return (ret + 1); } byte dgetsymbolhex(byte symbol) { return dlib_hex_table[symbol]; } dword datodhex(char *str) { dword ret = 0; byte symbol,count=0; if(!str) return 0; while(*str) { if(count >= 8) return 0; symbol = dlib_hex_table[(byte)*str]; if(symbol == 0xff) return ret; ret = ret << 4; ret = ret | symbol; count++; str++; } return ret; } dword datodhexstr(char *str,byte *array,dword max) { dword count=0; byte value=0,v_count=0,symbol; if(!str || !array) return 0; while(*str) { symbol = dlib_hex_table[(byte)*str]; if(symbol == 0xff) { if(v_count != 0) *array = value; return count; } value = value << 4; value = value | symbol; v_count++; if(v_count > 1) { *array = value; array++; value = v_count = 0; } count++; if((max != 0) && (count >= max)) return count; str++; } return count; } byte ddtoahex(dword value,char *str,byte count,byte symbol,byte end_space_count) { char buf[16]; char *p; byte temp,c,ret; int i; if(!str) return 0 ; if(count > 8) count = 8; p = buf + sizeof(buf) - 1; c = 0; do { temp = (byte)(value & 0x0f); value = value >> 4; *p-- = dlib_hex_symbol_table[temp]; c++; } while (value > 0); p++; if(c > count) { p -= (count - c); c = count; } ret = c; if(symbol) { if(count > c) { ret = count; count = (count - c); for(i=0;i<count;i++) *str++ = symbol; } } for(i=0;i<c;i++) *str++ = *p++; if(end_space_count) { for(i=0;i<end_space_count;i++) *str++ = ' '; ret += end_space_count; } *str = 0; return ret; } byte ddtoahexf(dword value,char *str,byte count) { char buf[16]; char *p; byte temp,c,ret; int i; if(!str) return 0; if(count > 8) count = 8; p = buf + sizeof(buf) - 1; c = 0; do { temp = (byte)(value & 0x0f); value = value >> 4; *p-- = dlib_hex_symbol_table[temp]; c++; } while (value > 0); p++; if(c > count) { p -= (count - c); c = count; } ret = c; if(count > c) { ret = count; count = (count - c); for(i=0;i<count;i++) *str++ = '0'; } for(i=0;i<c;i++) *str++ = *p++; *str = 0; return ret; } byte dqtoahexf(qword value,char *str,byte count) { char buf[24]; char *p; byte temp,c,ret; int i; if(!str) return 0; if(count > 16) count = 16; p = buf + sizeof(buf) - 1; c = 0; do { temp = (byte)(value & 0x0f); value = value >> 4; *p-- = dlib_hex_symbol_table[temp]; c++; } while (value > 0); p++; if(c > count) { p -= (count - c); c = count; } ret = c; if(count > c) { ret = count; count = (count - c); for(i=0;i<count;i++) *str++ = '0'; } for(i=0;i<c;i++) *str++ = *p++; *str = 0; return ret; } byte ddtoahexex(dword value,char *str,dword str_max_size,byte count,byte symbol,byte end_space_count) { char buf[12]; char *p,*s; byte temp,c,ret; int i; if(!str || !str_max_size) return 0 ; s = str; if(count > 8) count = 8; p = buf + sizeof(buf) - 1; c = 0; do { temp = (byte)(value & 0x0f); value = value >> 4; *p-- = dlib_hex_symbol_table[temp]; c++; } while (value > 0); p++; if(c > count) { p -= (count - c); c = count; } ret = c; if(symbol) { if(count > c) { ret = count; count = (count - c); if((dword)count > str_max_size) { *s = 0; return 0; } for(i=0;i<count;i++) *str++ = symbol; str_max_size -= count; } } if((dword)c > str_max_size) { *s = 0; return 0; } for(i=0;i<c;i++) *str++ = *p++; str_max_size -= c; if(end_space_count) { if((dword)end_space_count > str_max_size) { *s = 0; return 0; } for(i=0;i<end_space_count;i++) *str++ = ' '; str_max_size -= end_space_count; ret += end_space_count; } if(!str_max_size) { *s = 0; return 0; } *str = 0; return ret; } byte dqtoahexex(qword value,char *str,dword str_max_size,byte count,byte symbol,byte end_space_count) { char buf[24]; char *p,*s; byte temp,c,ret; int i; if(!str || !str_max_size) return 0 ; s = str; if(count > 16) count = 16; p = buf + sizeof(buf) - 1; c = 0; do { temp = (byte)(value & 0x0f); value = value >> 4; *p-- = dlib_hex_symbol_table[temp]; c++; } while (value > 0); p++; if(c > count) { p -= (count - c); c = count; } ret = c; if(symbol) { if(count > c) { ret = count; count = (count - c); if((dword)count > str_max_size) { *s = 0; return 0; } for(i=0;i<count;i++) *str++ = symbol; str_max_size -= count; } } if((dword)c > str_max_size) { *s = 0; return 0; } for(i=0;i<c;i++) *str++ = *p++; str_max_size -= c; if(end_space_count) { if((dword)end_space_count > str_max_size) { *s = 0; return 0; } for(i=0;i<end_space_count;i++) *str++ = ' '; str_max_size -= end_space_count; ret += end_space_count; } if(!str_max_size) { *s = 0; return 0; } *str = 0; return ret; } byte ddtoahexfex(dword value,char *str,dword str_max_size,byte count) { char buf[16]; char *p,*s; byte temp,c,ret; int i; if(!str || !str_max_size) return 0; s = str; if(count > 8) count = 8; p = buf + sizeof(buf) - 1; c = 0; do { temp = (byte)(value & 0x0f); value = value >> 4; *p-- = dlib_hex_symbol_table[temp]; c++; } while (value > 0); p++; if(c > count) { p -= (count - c); c = count; } ret = c; if(count > c) { ret = count; count = (count - c); if((dword)count > str_max_size) { *s = 0; return 0; } for(i=0;i<count;i++) *str++ = '0'; str_max_size -= count; } if((dword)(c+1) > str_max_size) { *s = 0; return 0; } for(i=0;i<c;i++) *str++ = *p++; *str = 0; return ret; } byte dqtoahexfex(qword value,char *str,dword str_max_size,byte count) { char buf[24]; char *p,*s; byte temp,c,ret; int i; if(!str || !str_max_size) return 0; s = str; if(count > 16) count = 16; p = buf + sizeof(buf) - 1; c = 0; do { temp = (byte)(value & 0x0f); value = value >> 4; *p-- = dlib_hex_symbol_table[temp]; c++; } while (value > 0); p++; if(c > count) { p -= (count - c); c = count; } ret = c; if(count > c) { ret = count; count = (count - c); if((dword)count > str_max_size) { *s = 0; return 0; } for(i=0;i<count;i++) *str++ = '0'; str_max_size -= count; } if((dword)(c+1) > str_max_size) { *s = 0; return 0; } for(i=0;i<c;i++) *str++ = *p++; *str = 0; return ret; } void ddtoahex_byte(byte value,char *str) { if(!str) return; *(word*)str = *(word*)dlib_word_hex_symbols_table[value]; str[2] = 0; } void ddtoahex_byte_a(byte value,char *str) { if(!str) return; *(word*)str = *(word*)dlib_word_hex_symbols_table_a[value]; str[2] = 0; } void ddtoahex_word(word value,char *str) { if(!str) return; *(word*)str = *(word*)dlib_word_hex_symbols_table[(byte)(value >> 8)]; *(word*)(str+2) = *(word*)dlib_word_hex_symbols_table[(byte)value]; str[4] = 0; } void ddtoahex_word_a(word value,char *str) { if(!str) return; *(word*)str = *(word*)dlib_word_hex_symbols_table_a[(byte)(value >> 8)]; *(word*)(str+2) = *(word*)dlib_word_hex_symbols_table_a[(byte)value]; str[4] = 0; } void ddtoahex_dword(dword value,char *str) { if(!str) return; *(word*)str = *(word*)dlib_word_hex_symbols_table[(byte)(value >> 24)]; *(word*)(str+2) = *(word*)dlib_word_hex_symbols_table[(byte)(value >> 16)]; *(word*)(str+4) = *(word*)dlib_word_hex_symbols_table[(byte)(value >> 8)]; *(word*)(str+6) = *(word*)dlib_word_hex_symbols_table[(byte)value]; str[8] = 0; } void ddtoahex_dword_a(dword value,char *str) { if(!str) return; *(word*)str = *(word*)dlib_word_hex_symbols_table_a[(byte)(value >> 24)]; *(word*)(str+2) = *(word*)dlib_word_hex_symbols_table_a[(byte)(value >> 16)]; *(word*)(str+4) = *(word*)dlib_word_hex_symbols_table_a[(byte)(value >> 8)]; *(word*)(str+6) = *(word*)dlib_word_hex_symbols_table_a[(byte)value]; str[8] = 0; } void dqtoahex_qword(qword value,char *str) { if(!str) return; *(word*)str = *(word*)dlib_word_hex_symbols_table[(byte)(value >> 56)]; *(word*)(str+2) = *(word*)dlib_word_hex_symbols_table[(byte)(value >> 48)]; *(word*)(str+4) = *(word*)dlib_word_hex_symbols_table[(byte)(value >> 40)]; *(word*)(str+6) = *(word*)dlib_word_hex_symbols_table[(byte)(value >> 32)]; *(word*)(str+8) = *(word*)dlib_word_hex_symbols_table[(byte)(value >> 24)]; *(word*)(str+10) = *(word*)dlib_word_hex_symbols_table[(byte)(value >> 16)]; *(word*)(str+12) = *(word*)dlib_word_hex_symbols_table[(byte)(value >> 8)]; *(word*)(str+14) = *(word*)dlib_word_hex_symbols_table[(byte)value]; str[16] = 0; } void dqtoahex_qword_a(qword value,char *str) { if(!str) return; *(word*)str = *(word*)dlib_word_hex_symbols_table_a[(byte)(value >> 56)]; *(word*)(str+2) = *(word*)dlib_word_hex_symbols_table_a[(byte)(value >> 48)]; *(word*)(str+4) = *(word*)dlib_word_hex_symbols_table_a[(byte)(value >> 40)]; *(word*)(str+6) = *(word*)dlib_word_hex_symbols_table_a[(byte)(value >> 32)]; *(word*)(str+8) = *(word*)dlib_word_hex_symbols_table_a[(byte)(value >> 24)]; *(word*)(str+10) = *(word*)dlib_word_hex_symbols_table_a[(byte)(value >> 16)]; *(word*)(str+12) = *(word*)dlib_word_hex_symbols_table_a[(byte)(value >> 8)]; *(word*)(str+14) = *(word*)dlib_word_hex_symbols_table_a[(byte)value]; str[16] = 0; } byte dtokencmp(char *str,char *token) { char b1,b2; if(!str || !token) return 0x80; while(*str) { b1 = *token; if(b1 == 0) return 0x81; b2 = *str; if(b1 < b2) return 0xff; if(b1 > b2) return 0x01; token++; str++; } return 0; } char* dtokencmp(char *str,char *token,byte *ret) { byte b1,b2,r; if(!str || !token || !ret) return 0; r = 0; while(*str) { b1 = *token; if(b1 == 0) { r = 0x81; break; } b2 = *str; if(b1 < b2) { r = 0xff; break; } if(b1 > b2) { r = 0x01; break; } token++; str++; } *ret = r; return str; } char* dtokencmpl(char *str,char *token) { char b1,b2; if(!str || !token) return 0; while(*token) { b1 = *token; b2 = *str; if(b1 != b2) return 0; token++; str++; } return str; } char* dgettoken(char *str,char *token,dword *size,bool enter) { char *s1,*s2; dword len; if(!str || !token || !size) return 0; s1 = (char*)dispace(str,enter); if(*s1 == 0) return 0; s2 = (char*)diabc(s1); len = (dword)(s2 - s1); if(!len || (len > *size)) return 0; dstrncpy(token,s1,len); *size = len; return s2; } char* dgettoken_param(char *str,char *token,dword *size,dword *value,bool *usevalue) { char *s; char temp[10]; dword d; if(!str || !token || !size || !value || !usevalue) return 0; s = (char*)dgettoken(str,token,size,true); if(!s) return 0; s = (char*)dispace(s); if(*s != 0x5b) { *usevalue = false; *value = 0; } else { d = 10; s = (char*)dgettoken(s+1,temp,&d); if(!s) return 0; s = (char*)dispace(s); if(*s != 0x5d) return 0; *value = datod(temp); *usevalue = true; s = (char*)dispace(s+1,true); } return s; } char* dgetdworddec(char *str,dword *value) { dword result = 0; byte symbol; if(!str || !value) return 0; if( (byte)(str[0] - 0x30) > 9) return 0; while(*str) { symbol = *str; symbol -= 0x30; if(symbol > 9) break; if(result > 0x19999999) return 0; result = (result * 10); result = (result + symbol); str++; } *value = result; return str; } char* dgetqworddec(char *str,qword *value) { qword result = 0; byte symbol; if(!str || !value) return 0; if( (byte)(str[0] - 0x30) > 9) return 0; while(*str) { symbol = *str; symbol -= 0x30; if(symbol > 9) break; if(result > 0x1999999999999999) return 0; result = (result * 10); result = (result + symbol); str++; } *value = result; return str; } char* dgetdworddec_fixlen(char *str,dword str_len,dword *value,dword *dl) { dword result=0; byte symbol; dword l = 0; if(!str || !str_len || !value) return 0; if( (byte)(str[0] - 0x30) > 9) return 0; for(dword i=0;i<str_len;i++) { symbol = *str; symbol -= 0x30; if(symbol > 9) break; if(result > 0x19999999) return 0; result = (result * 10); result = (result + symbol); str++; l++; } *value = result; if(dl) *dl = l; return str; } char* dgetqworddec_fixlen(char *str,dword str_len,qword *value,dword *dl) { qword result=0; byte symbol; dword l = 0; if(!str || !str_len || !value) return 0; if( (byte)(str[0] - 0x30) > 9) return 0; for(dword i=0;i<str_len;i++) { symbol = *str; symbol -= 0x30; if(symbol > 9) break; if(result > 0x1999999999999999) return 0; result = (result * 10); result = (result + symbol); str++; l++; } *value = result; if(dl) *dl = l; return str; } char* dgetdwordhex(char *str,dword *value) { dword result=0; byte symbol,count=0; if(!str || !value) return 0; if(str[0] == 0) return 0; while(*str) { symbol = dlib_hex_table[(byte)*str]; if(symbol == 0xff) { if(!count) return 0; break; } if(count >= 8) return 0; result = result << 4; result = result | symbol; count++; str++; } *value = result; return str; } char* dgetdwordhex_fixlen(char *str,dword str_len,dword *value,dword *dl) { dword result=0; byte symbol,count=0; dword l = 0; if(!str || !str_len || !value) return 0; if(str[0] == 0) return 0; for(dword i=0;i<str_len;i++) { symbol = dlib_hex_table[(byte)*str]; if(symbol == 0xff) { if(!count) return 0; break; } if(count >= 8) return 0; result = result << 4; result = result | symbol; count++; str++; l++; } *value = result; if(dl) *dl = l; return str; } char* dgetqwordhex(char *str,qword *value) { qword result=0; byte symbol,count=0; if(!str || !value) return 0; if(str[0] == 0) return 0; while(*str) { symbol = dlib_hex_table[(byte)*str]; if(symbol == 0xff) { if(!count) return 0; break; } if(count >= 16) return 0; result = result << 4; result = result | symbol; count++; str++; } *value = result; return str; } char* dgetqwordhex_fixlen(char *str,dword str_len,qword *value,dword *dl) { qword result = 0; byte symbol,count = 0; dword l = 0; if(!str || !str_len || !value) return 0; if(str[0] == 0) return 0; for(dword i=0;i<str_len;i++) { symbol = dlib_hex_table[(byte)*str]; if(symbol == 0xff) { if(!count) return 0; break; } if(count >= 16) return 0; result = result << 4; result = result | symbol; count++; str++; l++; } *value = result; if(dl) *dl = l; return str; } bool dgethex_byte(char *str,byte *value) { byte result = 0; byte symbol; if(!str || !value) return 0; for(byte i=0;i<2;i++) { symbol = dlib_hex_table[(byte)*str]; if(symbol == 0xff) return false; result = result << 4; result = result | symbol; str++; } *value = result; return true; } bool dgethex_word(char *str,word *value) { word result = 0; byte symbol; if(!str || !value) return 0; for(byte i=0;i<4;i++) { symbol = dlib_hex_table[(byte)*str]; if(symbol == 0xff) return false; result = result << 4; result = result | symbol; str++; } *value = result; return true; } bool dgethex_dword(char *str,dword *value) { dword result = 0; byte symbol; if(!str || !value) return 0; for(byte i=0;i<8;i++) { symbol = dlib_hex_table[(byte)*str]; if(symbol == 0xff) return false; result = result << 4; result = result | symbol; str++; } *value = result; return true; } bool dgethex_qword(char *str,qword *value) { qword result = 0; byte symbol; if(!str || !value) return 0; for(byte i=0;i<16;i++) { symbol = dlib_hex_table[(byte)*str]; if(symbol == 0xff) return false; result = result << 4; result = result | symbol; str++; } *value = result; return true; } char* dgetdwordex(char *str,dword *value) { if(!str || !value) return 0; if( (byte)(str[0] - 0x30) > 9) return 0; if(str[0] == 0x30) { if((str[1] == 0x58) || (str[1] == 0x78)) return dgetdwordhex(str+2,value); } return dgetdworddec(str,value); } char* dgetdwordex_fixlen(char *str,dword str_len,dword *value,dword *dl) { if(!str || !str_len || !value) return 0; if( (byte)(str[0] - 0x30) > 9) return 0; if(str[0] == 0x30) { if(str_len > 2) if((str[1] == 0x58) || (str[1] == 0x78)) return dgetdwordhex_fixlen(str+2,str_len-2,value,dl); } return dgetdworddec_fixlen(str,str_len,value,dl); } char* dgetqwordex(char *str,qword *value) { if(!str || !value) return 0; if( (byte)(str[0] - 0x30) > 9) return 0; if(str[0] == 0x30) { if((str[1] == 0x58) || (str[1] == 0x78)) return dgetqwordhex(str+2,value); } return dgetqworddec(str,value); } char* dgetqwordex_fixlen(char *str,dword str_len,qword *value,dword *dl) { if(!str || !str_len || !value) return 0; if( (byte)(str[0] - 0x30) > 9) return 0; if(str[0] == 0x30) { if(str_len > 2) if((str[1] == 0x58) || (str[1] == 0x78)) return dgetqwordhex_fixlen(str+2,str_len-2,value,dl); } return dgetqworddec_fixlen(str,str_len,value,dl); } char* dgetbytedumpex(char *str,byte *array,dword *len) { dword value; dword l=0; dword maxlen; if(!len) return 0; maxlen = *len; *len = 0; if(!str || !array) return 0; while(*str) { if(maxlen) if(l >= maxlen) break; str = (char*)dispace(str); if( (str=dgetdwordex(str,&value)) == 0) return 0; if(value > 255) return 0; *array++ = (byte)value; l++; str = (char*)dispace(str); if((*str == 0x2c) || (*str == 0x2e)) str++; else if(*str == 0x3b) break; } *len = l; return str; } char* dgetbytedumpex_fixlen(char *str,dword str_len,byte *array,dword *dl) { dword value; dword l=0; dword maxlen; if(!dl) return 0; maxlen = *dl; *dl = 0; if(!str || !array) return 0; for(dword i=0;i<str_len;i++) { if(maxlen) if(l >= maxlen) break; str = (char*)dispace_fixlen(str,str_len - i,false); if( (str=dgetdwordex(str,&value)) == 0) return 0; if(value > 255) return 0; *array++ = (byte)value; l++; str = (char*)dispace_fixlen(str,str_len - i,false); if((*str == 0x2c) || (*str == 0x2e)) str++; else if(*str == 0x3b) break; } *dl = l; return str; } char* dgetworddumpex(char *str,word *array,dword *len) { dword value; dword l = 0; dword maxlen; if(!len) return 0; maxlen = *len; *len = 0; if(!str || !array) return 0; while(*str) { if(maxlen) if(l >= maxlen) break; str = (char*)dispace(str); if( (str=dgetdwordex(str,&value)) == 0) return 0; if(value > 65535) return 0; *array++ = (word)value; l++; str = (char*)dispace(str); if((*str == 0x2c) || (*str == 0x2e)) str++; else if(*str == 0x3b) break; } *len = l; return str; } char* dgetdworddumpex(char *str,dword *array,dword *len) { dword value; dword l = 0; dword maxlen; if(!len) return 0; maxlen = *len; *len = 0; if(!str || !array) return 0; while(*str) { if(maxlen) if(l >= maxlen) break; str = (char*)dispace(str); if( (str=dgetdwordex(str,&value)) == 0) return 0; *array++ = value; l++; str = (char*)dispace(str); if((*str == 0x2c) || (*str == 0x2e)) str++; else if(*str == 0x3b) break; } *len = l; return str; } char* dgetbytedumphex(char *str,byte *array,dword *len) { dword value; dword l=0; dword maxlen; if(!len) return 0; maxlen = *len; *len = 0; if(!str || !array) return 0; while(*str) { if(maxlen) if(l >= maxlen) break; str = (char*)dispace(str); if( (str=dgetdwordhex(str,&value)) == 0) return 0; if(value > 255) return 0; *array++ = (byte)value; l++; str = (char*)dispace(str); if((*str == 0x2c) || (*str == 0x2e)) str++; else if(*str == 0x3b) break; } *len = l; return str; } char* diptostr(char *str,dword ip) { char temp[4]; if(!str) return 0; *str = 0; ddtoa(((byte*)&ip)[3],temp); strcat(str,temp); strcat(str,s_point); ddtoa(((byte*)&ip)[2],temp); strcat(str,temp); strcat(str,s_point); ddtoa(((byte*)&ip)[1],temp); strcat(str,temp); strcat(str,s_point); ddtoa(((byte*)&ip)[0],temp); strcat(str,temp); return str; } char* diptostrex(char *str,dword max_len,dword ip,dword *dl) { char temp[4]; byte l; dword _dl = 0; if(!str) return 0; *str = 0; l = ddtoa(((byte*)&ip)[3],temp); if(((dword)l + 1) > max_len) return 0; memcpy(str,temp,l); str += l; *str++ = '.'; l++; max_len -= l; _dl += l; l = ddtoa(((byte*)&ip)[2],temp); if(((dword)l + 1) > max_len) return 0; memcpy(str,temp,l); str += l; *str++ = '.'; l++; max_len -= l; _dl += l; l = ddtoa(((byte*)&ip)[1],temp); if(((dword)l + 1) > max_len) return 0; memcpy(str,temp,l); str += l; *str++ = '.'; l++; max_len -= l; _dl += l; l = ddtoa(((byte*)&ip)[0],temp); if(((dword)l + 1) > max_len) return 0; memcpy(str,temp,l); str += l; _dl += l; *str = 0; if(dl) *dl = _dl; return str; } char* dipporttostr(char *str,dword ip,word port) { char temp[6]; if( (str=diptostr(str,ip)) == 0) return 0; ddtoa(port,temp); strcat(str,":"); strcat(str,temp); return str; } char* dporttostrex(char *str,dword max_len,word port,dword *dl) { char temp[6]; dword _dl; byte l; l = ddtoa(port,temp); if(((dword)l + 2) > max_len) return 0; *str++ = ':'; memcpy(str,temp,l); str += l; *str = 0; _dl = l + 1; if(dl) *dl = _dl; return str; } char* dipporttostrex(char *str,dword max_len,dword ip,word port,dword *dl) { dword _dl,_dl2; if( (str=diptostrex(str,max_len,ip,&_dl)) == 0) return 0; if(_dl > max_len) return 0; max_len -= _dl; str = dporttostrex(str,max_len,port,&_dl2); if(!str) return 0; _dl += _dl2; if(dl) *dl = _dl; return str; } char* dgetbytedecex(char *str,byte *value,char end_symbol) { dword v; while(*str) { if(*str > 0x20) break; str++; } if((*str < 0x30) || (*str > 0x39) ) return 0; str = dgetdworddec(str,&v); if(!str) return 0; if(v > 255) return 0; while(*str) { if(*str > 0x20) break; str++; } if(end_symbol) if(*str != end_symbol) return 0; *value = (byte)v; return str; } char* dgetbytedecex_fixlen(char *str,dword str_len,byte *value,char end_symbol,dword *dl) { dword v; dword _dl; while(*str) { if(*str > 0x20) break; str++; } if((*str < 0x30) || (*str > 0x39) ) return 0; str = dgetdworddec_fixlen(str,str_len,&v,&_dl); if(!str) return 0; if(v > 255) return 0; if(_dl > str_len) return 0; str_len -= _dl; for(dword i=0;i<str_len;i++) { if(*str > 0x20) break; str++; _dl++; } if(end_symbol) if(*str != end_symbol) return 0; *value = (byte)v; if(dl) *dl = _dl; return str; } char* dstrtoip(char *str,dword *ip) { dword _ip; byte v; if(!str || !ip) return 0; str = dgetbytedecex(str,&v,'.'); if(!str) return 0; str++; ((byte*)&_ip)[3] = (byte)v; str = dgetbytedecex(str,&v,'.'); if(!str) return 0; str++; ((byte*)&_ip)[2] = (byte)v; str = dgetbytedecex(str,&v,'.'); if(!str) return 0; str++; ((byte*)&_ip)[1] = (byte)v; str = dgetbytedecex(str,&v,0); if(!str) return 0; ((byte*)&_ip)[0] = (byte)v; *ip = _ip; return str; } char* dstrtoip_swap(char *str,dword *ip) { dword _ip; byte v; if(!str || !ip) return 0; str = dgetbytedecex(str,&v,'.'); if(!str) return 0; str++; ((byte*)&_ip)[0] = (byte)v; str = dgetbytedecex(str,&v,'.'); if(!str) return 0; str++; ((byte*)&_ip)[1] = (byte)v; str = dgetbytedecex(str,&v,'.'); if(!str) return 0; str++; ((byte*)&_ip)[2] = (byte)v; str = dgetbytedecex(str,&v,0); if(!str) return 0; ((byte*)&_ip)[3] = (byte)v; *ip = _ip; return str; } char* dstrtoipport(char *str,dword *ip,word *port) { dword _port; if(!port) return 0; str = dstrtoip(str,ip); if(!str) return 0; if(*str != ':') return 0; str = dispace(str + 1); if(!str) return 0; str = dgetdworddec(str,&_port); if(!str) return 0; if(_port > 65535) return 0; *port = (word)_port; return str; } char* dstrtoipport_swap(char *str,dword *ip,word *port) { dword _port; if(!port) return 0; str = dstrtoip_swap(str,ip); if(!str) return 0; if(*str != ':') return 0; str = dispace(str + 1); if(!str) return 0; str = dgetdworddec(str,&_port); if(!str) return 0; if(_port > 65535) return 0; *port = (word)_port; return str; } #define DSTRTOIP(end) \ {\ str = dgetbytedecex_fixlen(str,str_len,&v,end,&tdl);\ if(!str)\ return 0;\ if(tdl > str_len)\ return 0;\ str_len -= tdl;\ _dl += tdl;\ } char* dstrtoip_fixlen(char *str,dword str_len,dword *ip,dword *dl) { dword _ip; byte v; dword tdl,_dl=0; if(!str || !ip) return 0; DSTRTOIP('.'); if(!str_len) return 0; str++; str_len--; _dl++; ((byte*)&_ip)[3] = (byte)v; DSTRTOIP('.'); if(!str_len) return 0; str++; str_len--; _dl++; ((byte*)&_ip)[2] = (byte)v; DSTRTOIP('.'); if(!str_len) return 0; str++; str_len--; _dl++; ((byte*)&_ip)[1] = (byte)v; DSTRTOIP(0); ((byte*)&_ip)[0] = (byte)v; *ip = _ip; if(dl) *dl = _dl; return str; } char* dstrtoip_swap_fixlen(char *str,dword str_len,dword *ip,dword *dl) { dword _ip; byte v; dword tdl,_dl=0; if(!str || !ip) return 0; DSTRTOIP('.'); if(!str_len) return 0; str++; str_len--; _dl++; ((byte*)&_ip)[0] = (byte)v; DSTRTOIP('.'); if(!str_len) return 0; str++; str_len--; _dl++; ((byte*)&_ip)[1] = (byte)v; DSTRTOIP('.'); if(!str_len) return 0; str++; str_len--; _dl++; ((byte*)&_ip)[2] = (byte)v; DSTRTOIP(0); ((byte*)&_ip)[3] = (byte)v; *ip = _ip; if(dl) *dl = _dl; return str; } char* dstrtoport_fixlen(char *str,dword str_len,word *port,dword _dl,dword *dl) { dword _port; dword tdl; if(!port) return 0; if(!str_len) return 0; if(*str != ':') return 0; str++; str_len--; _dl++; str = dispace_fixlen(str,str_len,false,&tdl); if(!str) return 0; if(tdl > str_len) return 0; _dl += tdl; str = dgetdworddec_fixlen(str,str_len,&_port,&tdl); if(!str) return 0; if(tdl > str_len) return 0; _dl += tdl; if(_port > 65535) return 0; *port = (word)_port; if(dl) *dl = _dl; return str; } char* dstrtoipport_fixlen(char *str,dword str_len,dword *ip,word *port,dword *dl) { dword _dl; str = dstrtoip_fixlen(str,str_len,ip,&_dl); if(!str) return 0; if(_dl > str_len) return 0; str_len -= _dl; return dstrtoport_fixlen(str,str_len,port,_dl,dl); } char* dstrtoipport_swap_fixlen(char *str,dword str_len,dword *ip,word *port,dword *dl) { dword _dl; str = dstrtoip_swap_fixlen(str,str_len,ip,&_dl); if(!str) return 0; if(_dl > str_len) return 0; str_len -= _dl; return dstrtoport_fixlen(str,str_len,port,_dl,dl); } #undef DSTRTOIP #ifdef LINUX } #endif
15.30126
104
0.490869
[ "3d" ]
2c802d1135288769b258c55c31c094376db402a2
953
cpp
C++
C++/Algorithms/Dynamic Programming/Longest Increasing Subsequence.cpp
anandamit07/hacktoberfest2021
dba4da64a7dee2835d2e03bcdb0a71d28815d50d
[ "MIT" ]
null
null
null
C++/Algorithms/Dynamic Programming/Longest Increasing Subsequence.cpp
anandamit07/hacktoberfest2021
dba4da64a7dee2835d2e03bcdb0a71d28815d50d
[ "MIT" ]
null
null
null
C++/Algorithms/Dynamic Programming/Longest Increasing Subsequence.cpp
anandamit07/hacktoberfest2021
dba4da64a7dee2835d2e03bcdb0a71d28815d50d
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int LIS(vector<int> &arr, int n){ int lis[n]; lis[0] = 1; for (int i = 1; i < n; i++) { lis[i] = 1; for (int j = 0; j < i; j++){ if (arr[i] > arr[j] && lis[i] < lis[j] + 1){ lis[i] = lis[j] + 1; } } } int ans=0; for(int i=0;i<n;i++){ ans=max(ans,lis[i]); } return ans; } int main(){ int n; cin>>n; vector<int> v(n); for(int i=0;i<n;i++){ cin>>v[i]; } cout<<LIS(v,n)<<endl; return 0; } /* A more exiting and easy and faster code taken from CODEFORCES blog: int LIS(vector<int> &arr,int n){ multiset < int > s; for(int i=0,i<n;i++) { s.insert(arr[i]); auto it = s.upper_bound(arr[i]); if(it != s.end()) s.erase(it); } return (int)s.size(); } */
16.431034
69
0.406086
[ "vector" ]
2c80bc68434dabd6538ef215b42950ae1b03e0ca
1,182
cpp
C++
atcoder/arc/arc035_c_2.cpp
knuu/competitive-programming
16bc68fdaedd6f96ae24310d697585ca8836ab6e
[ "MIT" ]
1
2018-11-12T15:18:55.000Z
2018-11-12T15:18:55.000Z
atcoder/arc/arc035_c_2.cpp
knuu/competitive-programming
16bc68fdaedd6f96ae24310d697585ca8836ab6e
[ "MIT" ]
null
null
null
atcoder/arc/arc035_c_2.cpp
knuu/competitive-programming
16bc68fdaedd6f96ae24310d697585ca8836ab6e
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef long long int ll; typedef pair<int, int> P; typedef pair<ll, ll> Pll; typedef vector<int> Vi; //typedef tuple<int, int, int> T; #define FOR(i,s,x) for(int i=s;i<(int)(x);i++) #define REP(i,x) FOR(i,0,x) #define ALL(c) c.begin(), c.end() #define DUMP( x ) cerr << #x << " = " << ( x ) << endl const int dr[4] = {-1, 0, 1, 0}; const int dc[4] = {0, 1, 0, -1}; const ll INF = 1e17; int main() { // use scanf in CodeForces! cin.tie(0); ios_base::sync_with_stdio(false); int N, M; cin >> N >> M; vector<vector<ll>> A(N, vector<ll>(N, INF)); REP(i, N) A[i][i] = 0; REP(_, M) { int a, b, c; cin >> a >> b >> c; a--, b--; A[a][b] = A[b][a] = c; } REP(k, N) REP(i, N) REP(j, N) A[i][j] = min(A[i][j], A[i][k] + A[k][j]); int K; cin >> K; REP(_, K) { int x, y, z; cin >> x >> y >> z; x--, y--; if (z < A[x][y]) { A[x][y] = A[y][x] = z; REP(i, N) REP(j, N) A[i][j] = min(A[i][j], A[i][x] + A[x][j]); REP(i, N) REP(j, N) A[i][j] = min(A[i][j], A[i][y] + A[y][j]); } ll ans = 0; REP(i, N) FOR(j, i+1, N) ans += A[i][j]; cout << ans << endl; } return 0; }
23.176471
74
0.468697
[ "vector" ]
2c8139453b26c5d5895fadc8afb1934ff304d82a
230
hpp
C++
src/aoc2021/runners/Day1.hpp
LunarWatcher/AoC2021
e327d1ff54ec0b9aa655545f465304797d1b7da0
[ "MIT" ]
null
null
null
src/aoc2021/runners/Day1.hpp
LunarWatcher/AoC2021
e327d1ff54ec0b9aa655545f465304797d1b7da0
[ "MIT" ]
null
null
null
src/aoc2021/runners/Day1.hpp
LunarWatcher/AoC2021
e327d1ff54ec0b9aa655545f465304797d1b7da0
[ "MIT" ]
null
null
null
#pragma once #include "Runner.hpp" #include <vector> namespace aoc { class Day1 : public Runner { private: std::vector<int> input; std::string runner(int offset); public: Day1(); StrPair run() override; }; }
11.5
35
0.643478
[ "vector" ]
2c85f2341b73356e0e561039e44cac9f6b327d38
99
hpp
C++
Quark-Core/include/render/buffer/buffer.hpp
thehutch/Quark-Engine
4afa0372e44707b89eecae218882021b415e2578
[ "MIT" ]
null
null
null
Quark-Core/include/render/buffer/buffer.hpp
thehutch/Quark-Engine
4afa0372e44707b89eecae218882021b415e2578
[ "MIT" ]
null
null
null
Quark-Core/include/render/buffer/buffer.hpp
thehutch/Quark-Engine
4afa0372e44707b89eecae218882021b415e2578
[ "MIT" ]
null
null
null
#pragma once namespace QE { namespace Render { class Buffer { public: public: }; } }
7.071429
17
0.59596
[ "render" ]
2c897e2fc008b6707f988bd221b42aed7b1166a5
23,092
cpp
C++
src/Sandbox/main.cpp
evinstk/TantechEngine
6621b6d159629547c8d75a49ffdf099a8052a2f6
[ "MIT" ]
null
null
null
src/Sandbox/main.cpp
evinstk/TantechEngine
6621b6d159629547c8d75a49ffdf099a8052a2f6
[ "MIT" ]
2
2015-11-16T16:05:08.000Z
2015-11-16T16:06:10.000Z
src/Sandbox/main.cpp
evinstk/TantechEngine
6621b6d159629547c8d75a49ffdf099a8052a2f6
[ "MIT" ]
null
null
null
#include <SDL.h> #include <GL/glew.h> #include <SDL_opengl.h> #include <gl/GLU.h> #include <iostream> #include <math.h> #include <vector> #include <map> #include <functional> #include <algorithm> #include <fstream> #include <sstream> #include <lua.hpp> #include <LuaBridge.h> #include <glm/glm.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtx/transform.hpp> #include <bass.h> #include <queue> #include "types.h" #include "wrappers.h" #include "auxiliary.h" #include "player.h" #include "entity_manager.h" #include "transform_component.h" #include "physics_component.h" #include "physics_system.h" #include "platformer_physics_system.h" #include "bounding_box_component.h" #include "collision_system.h" #include "simple_render_component.h" #include "render_system.h" #include "texture.h" #include "shader.h" #include "tiled_map.h" #include "game_state.h" #include "tmx.h" #include "texture_manager.h" #include "mesh_manager.h" #include "animation_component.h" #include "animation_factory.h" #include "command_component.h" #include "command_system.h" using namespace te; namespace te { struct Sprite { TexturePtr pTexture; int w; int h; Sprite(TexturePtr pTexture, int w, int h) : pTexture(pTexture), w(w), h(h) {} }; class CollisionHandler : public Observer<CollisionEvent>, public Observer<MapCollisionEvent> { public: typedef std::pair<Entity, Entity> EntityPair; typedef std::pair<Entity, TiledMap*> EntityMapPair; std::map<EntityPair, std::function<void(Entity, Entity, float)>> map; std::map<EntityMapPair, std::function<void(Entity, TiledMap&, float)>> tiledCollisionMap; virtual void onNotify(const CollisionEvent& evt) { EntityPair pair = { evt.a, evt.b }; auto it = map.find(pair); if (it != map.end()) { it->second(evt.a, evt.b, evt.dt); } } virtual void onNotify(const MapCollisionEvent& evt) { EntityMapPair pair = { evt.entity, &evt.map }; auto it = tiledCollisionMap.find(pair); if (it != tiledCollisionMap.end()) { it->second(evt.entity, evt.map, evt.dt); } } }; class PauseGameState : public GameState { public: bool processInput(const SDL_Event& evt) { if (evt.type == SDL_KEYDOWN) { if (evt.key.keysym.sym == SDLK_SPACE) { queuePop(); } else if (evt.key.keysym.sym == SDLK_q) { queueClear(); } } return false; } bool update(float dt) { return false; } void draw() { //glClearColor(0.f, 1.f, 0.f, 0.5f); //glClear(GL_COLOR_BUFFER_BIT); } }; std::shared_ptr<GameState> gpSandboxState; std::shared_ptr<GameState> gpOtherState; class SwitchState : public GameState { public: virtual bool processInput(const SDL_Event& evt) { if (evt.type != SDL_KEYDOWN) { return false; } switch (evt.key.keysym.sym) { case SDLK_1: if (this != gpSandboxState.get()) { queuePop(); queuePush(gpSandboxState); } break; case SDLK_2: if (this != gpOtherState.get()) { queuePop(); queuePush(gpOtherState); } } return false; } }; class OtherGameState : public SwitchState { public: OtherGameState(std::shared_ptr<Shader> pShader) : SwitchState() , mpShader(pShader) , mpTMX(new TMX("tiled", "sample_map.lua")) , mpTextureManager(new TextureManager()) , mpMap(new TiledMap(mpTMX, mpShader, mpTextureManager.get())) {} //bool processInput(const SDL_Event& evt) //{ // return SwitchState::processInput(evt); //} bool update(float) { return true; } void draw() { mpMap->draw(); } private: std::shared_ptr<Shader> mpShader; std::shared_ptr<TMX> mpTMX; std::shared_ptr<TextureManager> mpTextureManager; std::shared_ptr<TiledMap> mpMap; }; class LuaGameState : public SwitchState { public: LuaGameState(std::shared_ptr<Shader> pShader, const glm::mat4& projection) : SwitchState() , mpShader(pShader) , mpTextureManager(new TextureManager()) , mpTMX(new TMX("tiled", "platformer.lua")) , mpMap(new TiledMap(mpTMX, mpShader, mpTextureManager.get())) , mCollisionHandler(new CollisionHandler()) , mpTransformComponent(new TransformComponent()) , mpPhysicsComponent(new PhysicsComponent()) , mpBoundingBoxComponent(new BoundingBoxComponent(mpTransformComponent)) , mpRenderComponent(new SimpleRenderComponent(projection)) , mpAnimationComponent(new AnimationComponent()) , mpCommandComponent(new CommandComponent()) , mEntityManager({mpTransformComponent, mpPhysicsComponent, mpBoundingBoxComponent, mpRenderComponent}) , mCommandSystem(mpCommandComponent) , mPhysicsSystem(mpPhysicsComponent, mpTransformComponent, mpBoundingBoxComponent, mpMap, 4) , mCollisionSystem(mpBoundingBoxComponent, {mCollisionHandler}) , mMapCollisionSystem(mpBoundingBoxComponent, mpMap, {mCollisionHandler}) , mRenderSystem(mpShader, mpRenderComponent, mpAnimationComponent, mpTransformComponent) , mKeyPressTable() , mKeyReleaseTable() , mFontCount(0) , mFontMap() , mChannel(0) , mView() { if (!(mChannel = BASS_StreamCreateFile(false, "sounds/arcade-beep-1.mp3", 0, 0, 0))) { throw std::runtime_error("Could not load sound."); } std::shared_ptr<MeshManager> pMeshManager(new MeshManager{ mpTMX, mpTextureManager }); Entity e = createEntity({ 7, 2, 2 }); //setPosition(e, glm::vec3(3, 3, 10)); //ac.setAnimations(e, *pTMX, pTMX->layers[3].objects[0], *pMeshManager); std::shared_ptr<AnimationFactory> pAnimationFactory(new AnimationFactory{ mpTMX, pMeshManager }); //std::shared_ptr<const Animation> pAnimation(new Animation(pAnimationFactory->create({ // {"animation", "walking"}, // {"character", "amygdala"} //}, true))); //std::shared_ptr<const Animation> pJesterAnimation(new Animation(pAnimationFactory->create({ // {"animation", "walking"}, // {"type", "jester"} //}))); //// Should be frozen using default tile mesh //std::shared_ptr<const Animation> pMonsterStill(new Animation(pAnimationFactory->create({ // {"type", "monster"} //}))); //mpAnimationComponent->setAnimations(e, { // {1, pAnimation}, // {2, pJesterAnimation}, // {3, pMonsterStill} //}, 1); //registerKeyPress('1', [=] { // mpAnimationComponent->setAnimation(e, 1); //}); //registerKeyPress('2', [=] { // mpAnimationComponent->setAnimation(e, 2); //}); //registerKeyPress('3', [=] { // mpAnimationComponent->setAnimation(e, 3); //}); mpCommandComponent->setTypeMask(e, EntityType::HUMAN|EntityType::MONSTER); mpBoundingBoxComponent->setBoundingBox(e, { 1, 1 }, { 0.5, 0.5 }); registerKeyPress('k', [=] { mCommandSystem.queueCommand(Command(EntityType::HUMAN, 0, [=](const Entity& e, float dt) { setVelocity(e, glm::vec2(0, 0.5f)); })); }); registerKeyRelease('k', [=] { mCommandSystem.queueCommand(Command(EntityType::HUMAN, 0, [=](const Entity& e, float dt) { setVelocity(e, glm::vec2(0, 0)); })); }); loadObjects(mpTMX, *mpShader, pMeshManager, mEntityManager, *mpTransformComponent, *mpAnimationComponent); } typedef unsigned int EntityHandle; typedef std::pair<Entity, Entity> EntityPair; typedef luabridge::LuaRef LuaVector; typedef luabridge::LuaRef LuaFunction; typedef unsigned int FontHandle; typedef unsigned int TextHandle; void pause() { queuePush(std::shared_ptr<PauseGameState>(new PauseGameState())); } void playSound() { BASS_ChannelPlay(mChannel, true); } Entity createEntity(glm::vec3 position, glm::vec2 velocity = glm::vec2(0, 0)) { Entity entity = mEntityManager.create(); mpTransformComponent->setLocalTransform( entity, glm::translate(position)); if (velocity != glm::vec2(0, 0)) { mpPhysicsComponent->setPhysics(entity, velocity); } return entity; } void destroyEntity(Entity entity) { mEntityManager.destroy(entity); } void setPosition(Entity entity, glm::vec2 position) { if (!exists(entity)) return; mpTransformComponent->setLocalTransform( entity, glm::translate(glm::vec3(position.x, position.y, 0))); } void setPosition(Entity entity, glm::vec3 position) { if (!exists(entity)) return; mpTransformComponent->setLocalTransform( entity, glm::translate(glm::mat4(), glm::vec3(position.x, position.y, position.z))); } glm::vec2 getPosition(Entity entity) { if (!exists(entity)) return glm::vec2(0.f, 0.f); glm::mat4 localTransform = mpTransformComponent->getLocalTransform(entity); glm::vec4 position = localTransform * glm::vec4(0.f, 0.f, 0.f, 1.f); return glm::vec2(position.x, position.y); } void setVelocity(Entity entity, glm::vec2 velocity) { if (!exists(entity)) return; mpPhysicsComponent->setPhysics(entity, velocity); } glm::vec2 getVelocity(Entity entity) { return mpPhysicsComponent->getVelocity(entity); } void setBoundingBox(Entity entity, glm::vec2 dimensions) { if (!exists(entity)) return; mpBoundingBoxComponent->setBoundingBox(entity, dimensions, { 0, 0 }); } void setSprite(Entity entity, glm::vec2 dimensions) { mpRenderComponent->setSprite(entity, dimensions, { 0, 0 }); } void scale(Entity entity, glm::vec3 scale) { mpTransformComponent->setLocalTransform( entity, glm::scale(mpTransformComponent->getLocalTransform(entity), scale)); } void setParent(Entity child, Entity parent) { mpTransformComponent->setParent(child, parent); } void handleCollision(Entity e1, Entity e2, std::function<void(Entity,Entity,float)> handler) { if (!exists(e1) || !exists(e2)) return; auto key = std::make_pair(e1, e2); auto it = mCollisionHandler->map.find(key); if (it == mCollisionHandler->map.end()) { mCollisionHandler->map.insert(std::make_pair( key, handler)); } else { it->second = handler; } } void handleMapCollision(Entity e, std::function<void(Entity, TiledMap&, float)> handler) { if (!exists(e)) return; auto key = std::make_pair(e, mpMap.get()); auto it = mCollisionHandler->tiledCollisionMap.find(key); if (it == mCollisionHandler->tiledCollisionMap.end()) { mCollisionHandler->tiledCollisionMap.insert(std::make_pair( key, handler)); } else { it->second = handler; } } void registerKeyPress(char character, std::function<void(void)> func) { auto it = mKeyPressTable.find(character); if (it == mKeyPressTable.end()) { mKeyPressTable.insert(std::make_pair(character, func)); } else { mKeyPressTable[character] = func; } } void registerKeyRelease(char character, std::function<void(void)> func) { auto it = mKeyReleaseTable.find(character); if (it == mKeyReleaseTable.end()) { mKeyReleaseTable.insert(std::make_pair(character, func)); } else { mKeyReleaseTable[character] = func; } } FontHandle loadFont(const std::string& filename, int ptSize) { FontPtr pFont = te::loadFont(filename, ptSize); mFontMap.insert(std::make_pair( mFontCount, pFont)); return mFontCount++; } bool exists(Entity entity) { return mEntityManager.isAlive(entity); } bool processInput(const SDL_Event& evt) { SwitchState::processInput(evt); if (evt.type == SDL_KEYDOWN) { auto it = mKeyPressTable.find(evt.key.keysym.sym); if (it != mKeyPressTable.end()) { it->second(); } } else if (evt.type == SDL_KEYUP) { auto it = mKeyReleaseTable.find(evt.key.keysym.sym); if (it != mKeyReleaseTable.end()) { it->second(); } } else if (evt.type == SDL_WINDOWEVENT) { if (evt.window.event == SDL_WINDOWEVENT_RESIZED) { adjustViewport(evt.window.data1, evt.window.data2, 16.f / 9.f, glViewport); } } return false; } bool update(float dt) { mCommandSystem.update(dt); mPhysicsSystem.update(dt); mCollisionSystem.update(dt); mRenderSystem.update(dt); //mMapCollisionSystem.update(dt); return false; } BoundingBox getBoundingBox(Entity entity) { return mpBoundingBoxComponent->getBoundingBox(entity); } BoundingBox getIntersection(Entity a, Entity b) { BoundingBox aRect = getBoundingBox(a); BoundingBox bRect = getBoundingBox(b); return te::getIntersection(aRect, bRect); } // HACKY! Only for test driver project void setView(const glm::mat4& view) { mView = view; } glm::mat4 getView() const { return mView; } void draw() { //mMap.draw(mView); mpMap->draw(mView); mRenderSystem.draw(mView); } private: std::shared_ptr<Shader> mpShader; std::shared_ptr<TextureManager> mpTextureManager; std::shared_ptr<const TMX> mpTMX; std::shared_ptr<TiledMap> mpMap; std::shared_ptr<CollisionHandler> mCollisionHandler; TransformPtr mpTransformComponent; PhysicsPtr mpPhysicsComponent; BoundingBoxPtr mpBoundingBoxComponent; SimpleRenderPtr mpRenderComponent; AnimationPtr mpAnimationComponent; CommandPtr mpCommandComponent; EntityManager mEntityManager; CommandSystem mCommandSystem; PlatformerPhysicsSystem mPhysicsSystem; CollisionSystem mCollisionSystem; MapCollisionSystem mMapCollisionSystem; RenderSystem mRenderSystem; std::map<char, std::function<void(void)>> mKeyPressTable; std::map<char, std::function<void(void)>> mKeyReleaseTable; FontHandle mFontCount; std::map<FontHandle, FontPtr> mFontMap; unsigned long mChannel; //std::map<Entity, GLuint> mVBOMap; //std::map<Entity, GLuint> mIBOMap; glm::mat4 mView; }; void fontExperiment(const FT_Library& ftLib) { FT_Face face; FT_Error error = FT_New_Face(ftLib, "fonts/Minecraftia-Regular.ttf", 0, &face); if (error == FT_Err_Unknown_File_Format) { throw std::runtime_error("Unsupported font format."); } else if (error) { throw std::runtime_error("Error loading font."); } } } int main(int argc, char** argv) { try { FT_Library ftLib; te::Initialization init(&ftLib); te::fontExperiment(ftLib); const int WIDTH = 1024; const int HEIGHT = 576; te::WindowPtr pGLWindow = te::createWindowOpenGL("Pong", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WIDTH, HEIGHT, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE); adjustViewport(WIDTH, HEIGHT, 16.f/9.f, glViewport); glClearColor(0.f, 0.f, 0.f, 1.f); glm::mat4 projection = glm::ortho<GLfloat>(0, 16, 9, 0, -100, 100); glm::mat4 model = glm::scale(glm::vec3(1.f / 21, 1.f / 21, 1)); std::shared_ptr<Shader> pShader{ new Shader{ projection, model } }; gpSandboxState = std::shared_ptr<GameState>{ new LuaGameState{ pShader, projection } }; gpOtherState = std::shared_ptr<OtherGameState>{ new OtherGameState{ pShader } }; StateStack stateStack(gpSandboxState); LuaGameState& state = (LuaGameState&)*gpSandboxState; // State initialization Entity ball = state.createEntity({ 8, 4.5, 5 }, { 0, -1 }); state.setSprite(ball, { 1, 1 }); state.setBoundingBox(ball, { 1, 1 }); Entity leftPaddle = state.createEntity({ 0.5, 4.5, 5 }); state.setSprite(leftPaddle, { 1, 3 }); state.setBoundingBox(leftPaddle, { 1, 3 }); Entity rightPaddle = state.createEntity({ 15.5, 4.5, 5 }); state.setSprite(rightPaddle, { 1, 3 }); state.setBoundingBox(rightPaddle, { 1, 3 }); auto handlePaddleCollision = [&state](Entity ball, Entity paddle, float dt) { glm::vec2 ballPos = state.getPosition(ball); glm::vec2 paddlePos = state.getPosition(paddle); glm::vec2 paddleToBall = ballPos - paddlePos; glm::vec2 ballVel = state.getVelocity(ball); glm::vec2 velocity = glm::length(ballVel) * glm::normalize(paddleToBall); state.setVelocity(ball, velocity); state.playSound(); }; state.handleCollision(ball, leftPaddle, handlePaddleCollision); state.handleCollision(ball, rightPaddle, handlePaddleCollision); auto handleGroundCollision = [&state](Entity paddle, TiledMap& map, float dt) { glm::vec2 paddleVel = state.getVelocity(paddle); if (paddleVel.y > 0) { paddleVel.y = 0; state.setVelocity(paddle, paddleVel); } }; state.handleMapCollision(leftPaddle, handleGroundCollision); state.registerKeyPress('w', [leftPaddle, &state]() { state.setVelocity(leftPaddle, glm::vec2(0, -8)); }); state.registerKeyPress('s', [leftPaddle, &state]() { state.setVelocity(leftPaddle, glm::vec2(0, 8)); }); state.registerKeyPress('a', [leftPaddle, &state]() { state.setVelocity(leftPaddle, glm::vec2(-8, 0)); }); state.registerKeyPress('d', [leftPaddle, &state]() { state.setVelocity(leftPaddle, glm::vec2(8, 0)); }); state.registerKeyPress('p', [rightPaddle, &state]() { state.setVelocity(rightPaddle, glm::vec2(0, -8)); }); state.registerKeyPress('l', [rightPaddle, &state]() { state.setVelocity(rightPaddle, glm::vec2(0, 8)); }); state.registerKeyRelease('w', [leftPaddle, &state]() { state.setVelocity(leftPaddle, glm::vec2(0, 0)); }); state.registerKeyRelease('s', [leftPaddle, &state]() { state.setVelocity(leftPaddle, glm::vec2(0, 0)); }); state.registerKeyRelease('a', [leftPaddle, &state]() { state.setVelocity(leftPaddle, glm::vec2(0, 0)); }); state.registerKeyRelease('d', [leftPaddle, &state]() { state.setVelocity(leftPaddle, glm::vec2(0, 0)); }); state.registerKeyRelease('p', [rightPaddle, &state]() { state.setVelocity(rightPaddle, glm::vec2(0, 0)); }); state.registerKeyRelease('l', [rightPaddle, &state]() { state.setVelocity(rightPaddle, glm::vec2(0, 0)); }); state.registerKeyPress(' ', [&state]() { state.pause(); }); state.registerKeyPress((char)SDLK_UP, [&state]() { state.setView(glm::translate(state.getView(), glm::vec3(0.f, 1.f, 0.f))); }); state.registerKeyPress((char)SDLK_DOWN, [&state]() { state.setView(glm::translate(state.getView(), glm::vec3(0.f, -1.f, 0.f))); }); state.registerKeyPress((char)SDLK_RIGHT, [&state]() { state.setView(glm::translate(state.getView(), glm::vec3(-1.f, 0.f, 0.f))); }); state.registerKeyPress((char)SDLK_LEFT, [&state]() { state.setView(glm::translate(state.getView(), glm::vec3(1.f, 0.f, 0.f))); }); Entity topWall = state.createEntity({ 50, -1, 5 }); state.setBoundingBox(topWall, { 100, 2 }); Entity bottomWall = state.createEntity({ 8, 10, 5 }); state.setBoundingBox(bottomWall, { 100, 2 }); auto handleWallCollision = [&state](Entity ball, Entity wall, float dt) { glm::vec2 velocity = state.getVelocity(ball); BoundingBox intersection = state.getIntersection(ball, wall); if (intersection.w > intersection.h) { velocity.y = -velocity.y; state.setVelocity(ball, velocity); } else { velocity.x = -velocity.x; state.setVelocity(ball, velocity); } }; state.handleCollision(ball, topWall, handleWallCollision); state.handleCollision(ball, bottomWall, handleWallCollision); // End state initialization executeStack(stateStack, *pGLWindow); } catch (std::exception e) { std::cerr << e.what() << std::endl; } return 0; }
34.465672
171
0.560107
[ "mesh", "vector", "model", "transform" ]
2c8b58b7f39e46f0ec0398662c25789787bf0db9
2,767
cpp
C++
UVA/UVA1424-Salesmen-DP.cpp
xehoth/OnlineJudgeCodes
013d31cccaaa1d2b6d652c2f5d5d6cb2e39884a7
[ "Apache-2.0" ]
7
2017-09-21T13:20:05.000Z
2020-03-02T03:03:04.000Z
UVA/UVA1424-Salesmen-DP.cpp
xehoth/OnlineJudgeCodes
013d31cccaaa1d2b6d652c2f5d5d6cb2e39884a7
[ "Apache-2.0" ]
null
null
null
UVA/UVA1424-Salesmen-DP.cpp
xehoth/OnlineJudgeCodes
013d31cccaaa1d2b6d652c2f5d5d6cb2e39884a7
[ "Apache-2.0" ]
3
2019-01-05T07:02:57.000Z
2019-06-13T08:23:13.000Z
/** * Copyright (c) 2017, xehoth * All rights reserved. * 「UVA 1424」Salesmen 05-10-2017 * DP * @author xehoth */ #include <bits/stdc++.h> namespace IO { inline char read() { static const int IN_LEN = 100000; static char buf[IN_LEN], *s, *t; s == t ? t = (s = buf) + fread(buf, 1, IN_LEN, stdin) : 0; return s == t ? -1 : *s++; } template <typename T> inline void read(T &x) { static char c; static bool iosig; for (c = read(), iosig = false; !isdigit(c); c = read()) { if (c == -1) return; c == '-' ? iosig = true : 0; } for (x = 0; isdigit(c); c = read()) x = x * 10 + (c ^ '0'); iosig ? x = -x : 0; } const int OUT_LEN = 100000; char obuf[OUT_LEN], *oh = obuf; inline void print(char c) { oh == obuf + OUT_LEN ? (fwrite(obuf, 1, OUT_LEN, stdout), oh = obuf) : 0; *oh++ = c; } template <typename T> inline void print(T x) { static int buf[30], cnt; if (x == 0) { print('0'); } else { x < 0 ? (print('-'), x = -x) : 0; for (cnt = 0; x; x /= 10) buf[++cnt] = x % 10 | 48; while (cnt) print((char)buf[cnt--]); } } inline void flush() { fwrite(obuf, 1, oh - obuf, stdout); } struct InputOutputStream { ~InputOutputStream() { flush(); } template <typename T> inline InputOutputStream &operator>>(T &x) { read(x); return *this; } template <typename T> inline InputOutputStream &operator<<(const T &x) { print(x); return *this; } } io; } namespace { using IO::io; const int MAXN = 110; std::vector<int> edge[MAXN + 1]; typedef std::vector<int>::iterator Iterator; int s[MAXN * 2 + 1], f[MAXN * 2 + 1][MAXN + 1]; inline void addEdge(const int u, const int v) { edge[u].push_back(v), edge[v].push_back(u); } inline void solve(const int n, const int m) { for (register int i = 0; i <= n; i++) edge[i].clear(); for (register int i = 0, u, v; i < m; i++) io >> u >> v, addEdge(u, v); register int len; io >> len; for (register int i = 1; i <= len; i++) io >> s[i]; for (register int i = 1; i <= len; i++) { memset(f[i], 0x3f, sizeof(int) * (n + 1)); for (register int u = 1; u <= n; u++) { for (Iterator v = edge[u].begin(); v != edge[u].end(); v++) f[i][*v] = std::min(f[i][*v], f[i - 1][u] + (s[i] != *v)); f[i][u] = std::min(f[i][u], f[i - 1][u] + (s[i] != u)); } } io << *std::min_element(f[len] + 1, f[len] + n + 1) << '\n'; } inline void solve() { register int T, n, m; io >> T; while (T--) { io >> n >> m; solve(n, m); } } } int main() { #ifdef DBG freopen("sample/1.in", "r", stdin); #endif solve(); return 0; }
22.314516
77
0.496205
[ "vector" ]
2c8e3f43b815b3fb8ff2bc43deaa2791f1b08608
4,236
cpp
C++
src/smartpeak/source/core/SequenceSegmentProcessor.cpp
dmccloskey/SmartPeak2
d3b42a938b225973117ddd4f9f5e5016034c09be
[ "MIT" ]
7
2020-07-16T02:51:26.000Z
2020-10-17T11:20:35.000Z
src/smartpeak/source/core/SequenceSegmentProcessor.cpp
dmccloskey/SmartPeak2
d3b42a938b225973117ddd4f9f5e5016034c09be
[ "MIT" ]
5
2020-08-02T20:18:31.000Z
2020-12-01T13:37:49.000Z
src/smartpeak/source/core/SequenceSegmentProcessor.cpp
dmccloskey/SmartPeak2
d3b42a938b225973117ddd4f9f5e5016034c09be
[ "MIT" ]
1
2020-07-25T07:41:22.000Z
2020-07-25T07:41:22.000Z
// -------------------------------------------------------------------------- // SmartPeak -- Fast and Accurate CE-, GC- and LC-MS(/MS) Data Processing // -------------------------------------------------------------------------- // Copyright The SmartPeak Team -- Novo Nordisk Foundation // Center for Biosustainability, Technical University of Denmark 2018-2021. // // 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 ANY OF THE AUTHORS OR THE CONTRIBUTING // INSTITUTIONS 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. // // -------------------------------------------------------------------------- // $Maintainer: Douglas McCloskey $ // $Authors: Douglas McCloskey, Pasquale Domenico Colaianni $ // -------------------------------------------------------------------------- #include <SmartPeak/core/SequenceSegmentProcessor.h> #include <SmartPeak/core/Filenames.h> #include <SmartPeak/core/MetaDataHandler.h> #include <SmartPeak/core/SampleType.h> #include <SmartPeak/core/SequenceHandler.h> #include <SmartPeak/core/Utilities.h> #include <SmartPeak/core/ApplicationHandler.h> #include <SmartPeak/core/FeatureFiltersUtils.h> #include <OpenMS/ANALYSIS/QUANTITATION/AbsoluteQuantitation.h> #include <OpenMS/METADATA/AbsoluteQuantitationStandards.h> #include <OpenMS/ANALYSIS/OPENSWATH/MRMFeatureFilter.h> #include <SmartPeak/io/InputDataValidation.h> #include <OpenMS/FORMAT/AbsoluteQuantitationStandardsFile.h> #include <OpenMS/FORMAT/AbsoluteQuantitationMethodFile.h> #include <OpenMS/FORMAT/MRMFeatureQCFile.h> // load featureFilter and featureQC #include <plog/Log.h> namespace SmartPeak { void SequenceSegmentProcessor::process( SequenceSegmentHandler& sequenceSegmentHandler_IO, const SequenceHandler& sequenceHandler_I, const ParameterSet& params_I, Filenames& filenames_I ) const { LOGD << "START " << getName() << ": " << sequenceSegmentHandler_IO.getSequenceSegmentName(); try { doProcess(sequenceSegmentHandler_IO, sequenceHandler_I, params_I, filenames_I); } catch (const std::exception& e) { LOGE << "END (ERROR) " << getName() << ": " << sequenceSegmentHandler_IO.getSequenceSegmentName() << " " << e.what(); throw; } LOGD << "END " << getName() << ": " << sequenceSegmentHandler_IO.getSequenceSegmentName(); } void SequenceSegmentProcessor::getSampleIndicesBySampleType( const SequenceSegmentHandler& sequenceSegmentHandler, const SequenceHandler& sequenceHandler, const SampleType sampleType, std::vector<size_t>& sampleIndices ) { sampleIndices.clear(); for (const size_t index : sequenceSegmentHandler.getSampleIndices()) { if (sequenceHandler.getSequence().at(index).getMetaData().getSampleType() == sampleType) { sampleIndices.push_back(index); } } } void SequenceSegmentProcessor::processForAllSegments( std::vector<SmartPeak::SequenceSegmentHandler>& sequence_segment_handlers, SequenceSegmentObservable* sequence_segment_observable, Filenames& filenames) { for (SequenceSegmentHandler& sequence_segment_handler : sequence_segment_handlers) { sequence_segment_observable_ = sequence_segment_observable; process(sequence_segment_handler, SequenceHandler(), {}, filenames); } } std::string SequenceSegmentProcessor::constructFilename(const std::string& filename, bool static_filename) const { if (static_filename) { return "${MAIN_DIR}/" + filename; } else { return "${FEATURES_OUTPUT_PATH}/${OUTPUT_SEQUENCE_SEGMENT_NAME}_" + filename; } } }
41.529412
123
0.693107
[ "vector" ]
2ca16932c73f3bdbb3baa8dd2b5cecfcaefbd13e
16,124
cpp
C++
Libraries/RobsJuceModules/rapt/Filters/Scientific/InfiniteImpulseResponseDesigner.cpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
34
2017-04-19T18:26:02.000Z
2022-02-15T17:47:26.000Z
Libraries/RobsJuceModules/rapt/Filters/Scientific/InfiniteImpulseResponseDesigner.cpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
307
2017-05-04T21:45:01.000Z
2022-02-03T00:59:01.000Z
Libraries/RobsJuceModules/rapt/Filters/Scientific/InfiniteImpulseResponseDesigner.cpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
4
2017-09-05T17:04:31.000Z
2021-12-15T21:24:28.000Z
// construction/destruction: template<class T> rsInfiniteImpulseResponseDesigner<T>::rsInfiniteImpulseResponseDesigner() { sampleRate = 44100.0; frequency = 1000.0; setBandwidth(1.0); // sets up lowerFrequency and upperFrequency gain = rsAmpToDb(T(0.25)); mode = LOWPASS; prototypeOrder = 2; } template<class T> rsInfiniteImpulseResponseDesigner<T>::~rsInfiniteImpulseResponseDesigner() { } // parameter settings: template<class T> void rsInfiniteImpulseResponseDesigner<T>::setSampleRate(T newSampleRate) { if( newSampleRate > 0.0 ) sampleRate = newSampleRate; } template<class T> void rsInfiniteImpulseResponseDesigner<T>::setMode(int newMode) { if( newMode >= BYPASS && newMode <= PEAK ) mode = newMode; else RS_DEBUG_BREAK; // newMode must be one of the numbers defined in enum 'modes' } template<class T> void rsInfiniteImpulseResponseDesigner<T>::setPrototypeOrder(int newOrder) { if( newOrder >= 1 ) prototypeOrder = newOrder; else RS_DEBUG_BREAK; // newOrder must be at least 1 } template<class T> void rsInfiniteImpulseResponseDesigner<T>::setApproximationMethod(int newApproximationMethod) { prototypeDesigner.setApproximationMethod(newApproximationMethod); } template<class T> void rsInfiniteImpulseResponseDesigner<T>::setFrequency(T newFrequency) { frequency = newFrequency; calculateLowerAndUpperFrequency(); } template<class T> void rsInfiniteImpulseResponseDesigner<T>::setBandwidth(T newBandwidth) { bandwidth = newBandwidth; calculateLowerAndUpperFrequency(); } template<class T> void rsInfiniteImpulseResponseDesigner<T>::setLowerFrequency(T newLowerFrequency) { if( newLowerFrequency > 0.0 ) lowerFrequency = newLowerFrequency; else RS_DEBUG_BREAK; // negative frequencies are not allowed } template<class T> void rsInfiniteImpulseResponseDesigner<T>::setUpperFrequency(T newUpperFrequency) { if( newUpperFrequency > 0.0 ) upperFrequency = newUpperFrequency; else RS_DEBUG_BREAK; // negative frequencies are not allowed } template<class T> void rsInfiniteImpulseResponseDesigner<T>::setGain(T newGain) { gain = newGain; } template<class T> void rsInfiniteImpulseResponseDesigner<T>::setRipple(T newRipple) { prototypeDesigner.setPassbandRipple(newRipple); prototypeDesigner.setPassbandGainRatio(T(1)-T(0.01)*newRipple); prototypeDesigner.setStopbandGainRatio(T(0.01)*newRipple); } template<class T> void rsInfiniteImpulseResponseDesigner<T>::setStopbandRejection(T newStopbandRejection) { prototypeDesigner.setStopbandRejection(newStopbandRejection); } // inquiry: template<class T> bool rsInfiniteImpulseResponseDesigner<T>::doesModeDoubleTheOrder() { if( mode == BANDPASS || mode == BANDREJECT || mode == PEAK ) return true; else return false; } template<class T> int rsInfiniteImpulseResponseDesigner<T>::getFinalFilterOrder() { if( doesModeDoubleTheOrder() == true ) return 2*prototypeOrder; else return prototypeOrder; } template<class T> int rsInfiniteImpulseResponseDesigner<T>::getNumBiquadStages() { int order = getFinalFilterOrder(); if( rsIsEven(order) ) return order/2; else return (order+1)/2; } template<class T> bool rsInfiniteImpulseResponseDesigner<T>::hasCurrentModeBandwidthParameter() { if( mode == BANDPASS || mode == BANDREJECT || mode == PEAK ) return true; else return false; } template<class T> bool rsInfiniteImpulseResponseDesigner<T>::hasCurrentModeGainParameter() { if( mode == LOW_SHELV || mode == HIGH_SHELV || mode == PEAK ) return true; else return false; } template<class T> bool rsInfiniteImpulseResponseDesigner<T>::hasCurrentModeRippleParameter() { if( prototypeDesigner.hasCurrentMethodRippleParameter() ) { if( mode != LOW_SHELV || mode != HIGH_SHELV || mode != PEAK ) return true; else return false; } else return false; } template<class T> bool rsInfiniteImpulseResponseDesigner<T>::hasCurrentModeRejectionParameter() { if( prototypeDesigner.hasCurrentMethodRejectionParameter() ) { if( mode != LOW_SHELV || mode != HIGH_SHELV || mode != PEAK ) return true; else return false; } else return false; } // coefficient retrieval: template<class T> void rsInfiniteImpulseResponseDesigner<T>::getPolesAndZeros(Complex* poles, Complex* zeros) { // calculate the required order and number of biquads for the filter: int finalOrder; if( mode == BANDPASS || mode == BANDREJECT || mode == PEAK ) finalOrder = 2*prototypeOrder; else finalOrder = prototypeOrder; // int numBiquads; // if( isEven(finalOrder) ) // numBiquads = finalOrder/2; // else // numBiquads = (finalOrder+1)/2; // set up the type for the prototype (lowpass/low-shelv): if( mode == LOW_SHELV || mode == HIGH_SHELV || mode == PEAK || mode == BYPASS ) prototypeDesigner.setPrototypeMode(rsPrototypeDesigner<T>::LOWSHELV_PROTOTYPE); else prototypeDesigner.setPrototypeMode(rsPrototypeDesigner<T>::LOWPASS_PROTOTYPE); T f1, f2, wd1, wd2, wa1, wa2; T fs = sampleRate; int k; // use sanity-checked local frequency variables here: f2 = upperFrequency; if( mode == BANDPASS || mode == BANDREJECT || mode == PEAK ) { f1 = lowerFrequency; if( f2 > T(0.999*0.5)*fs ) f2 = T(0.999*0.5)*fs; // ensure upper frequency < sampleRate/2 if( f1 > T(0.999)*f2 ) f1 = T(0.999)*f2; // ensure lower frequency < upper frequency } else { f1 = frequency; if( f1 > T(0.999*0.5)*fs ) f1 = T(0.999*0.5)*fs; // ensure frequency < sampleRate/2 } // prewarp the frequencies to the desired frequencies required for the design of the // (unnormalized) analog prototype filter: if( mode == BANDPASS || mode == BANDREJECT || mode == PEAK ) { wd1 = T(2*PI)*f1/fs; // normalized digital radian frequency 1 wa1 = T(2)*fs*tan(T(0.5)*wd1); // pre-warped analog radian frequency 1 wd2 = T(2*PI)*f2/fs; // normalized digital radian frequency 2 wa2 = T(2)*fs*tan(T(0.5)*wd2); // pre-warped analog radian frequency 2 } else { wd1 = T(2*PI)*f1/fs; // normalized digital radian frequency 1 wa1 = T(2)*fs*tan(T(0.5)*wd1); // pre-warped analog radian frequency 1 wd2 = 0.0; // unused wa2 = 0.0; // unused } // set up the prototype-designer according to the specifications: prototypeDesigner.setOrder(prototypeOrder); prototypeDesigner.setGain(gain); if( mode == LOWPASS || mode == HIGHPASS || mode == BANDPASS || mode == BANDREJECT ) prototypeDesigner.setReferenceGain(-RS_INF(T)); else prototypeDesigner.setReferenceGain(0.0); // allocate temporary memory: //Complex* protoPoles = new Complex[prototypeOrder]; //Complex* protoZeros = new Complex[prototypeOrder]; std::vector<Complex> pp(prototypeOrder), pz(prototypeOrder); Complex* protoPoles = &pp[0]; Complex* protoZeros = &pz[0]; // design the analog prototype filter: if( mode == HIGH_SHELV ) { // we need to cope with exchange of roles of poles and zeros for high-shelving (inverse) // chebychevs because the low-shelv -> high-shelv frequency transform exchanges these roles // once again: if( prototypeDesigner.getApproximationMethod() == rsPrototypeDesigner<T>::CHEBYCHEV ) { prototypeDesigner.setApproximationMethod(rsPrototypeDesigner<T>::INVERSE_CHEBYCHEV); prototypeDesigner.getPolesAndZeros(poles, zeros); prototypeDesigner.setApproximationMethod(rsPrototypeDesigner<T>::CHEBYCHEV); } else if( prototypeDesigner.getApproximationMethod() == rsPrototypeDesigner<T>::INVERSE_CHEBYCHEV ) { prototypeDesigner.setApproximationMethod(rsPrototypeDesigner<T>::CHEBYCHEV); prototypeDesigner.getPolesAndZeros(poles, zeros); prototypeDesigner.setApproximationMethod(rsPrototypeDesigner<T>::INVERSE_CHEBYCHEV); } else prototypeDesigner.getPolesAndZeros(poles, zeros); } else prototypeDesigner.getPolesAndZeros(poles, zeros); // because the PrototypeDesigner returns only one representant for each pair of complex // conjugate poles/zeros, we now create the full set here: if( rsIsOdd(prototypeOrder) ) { // copy the real pole/zero to the end: protoPoles[prototypeOrder-1] = poles[prototypeOrder/2]; protoZeros[prototypeOrder-1] = zeros[prototypeOrder/2]; } // for each complex pole/zero create a pair of complex conjugates: for(k=0; k<prototypeOrder/2; k++) { protoPoles[2*k] = poles[k]; protoPoles[2*k+1] = conj(poles[k]); protoZeros[2*k] = zeros[k]; protoZeros[2*k+1] = conj(zeros[k]); } // s-plane frequency transformation: switch( mode ) { case LOWPASS: rsPoleZeroMapper<T>::sPlanePrototypeToLowpass( protoPoles, protoZeros, poles, zeros, prototypeOrder, wa1); break; case HIGHPASS: rsPoleZeroMapper<T>::sPlanePrototypeToHighpass( protoPoles, protoZeros, poles, zeros, prototypeOrder, wa1); break; case BANDPASS: rsPoleZeroMapper<T>::sPlanePrototypeToBandpass( protoPoles, protoZeros, poles, zeros, prototypeOrder, wa1, wa2); break; case BANDREJECT: rsPoleZeroMapper<T>::sPlanePrototypeToBandreject(protoPoles, protoZeros, poles, zeros, prototypeOrder, wa1, wa2); break; case LOW_SHELV: rsPoleZeroMapper<T>::sPlanePrototypeToLowpass( protoPoles, protoZeros, poles, zeros, prototypeOrder, wa1); break; case HIGH_SHELV: { // this is ugly - rewrite the prototype design code such that all approximation methods can be treated uniformly: if( prototypeDesigner.needsSpecialHighShelvTransform() ) rsPoleZeroMapper<T>::sPlanePrototypeToHighShelv( protoPoles, protoZeros, poles, zeros, prototypeOrder, wa1); else rsPoleZeroMapper<T>::sPlanePrototypeToHighpass( protoPoles, protoZeros, poles, zeros, prototypeOrder, wa1); } break; case PEAK: rsPoleZeroMapper<T>::sPlanePrototypeToBandpass( protoPoles, protoZeros, poles, zeros, prototypeOrder, wa1, wa2); break; default: rsPoleZeroMapper<T>::sPlanePrototypeToLowpass( protoPoles, protoZeros, poles, zeros, prototypeOrder, wa1); break; }; //std::vector<Complex> pDbg, zDbg; // for debugging //pDbg = toVector(poles, finalOrder); //zDbg = toVector(zeros, finalOrder); // transform from the s-domain to the z-domain via the bilinear transform: T g; // not used actually rsPoleZeroMapper<T>::bilinearAnalogToDigital(poles, finalOrder, zeros, finalOrder, fs, &g); //pDbg = toVector(poles, finalOrder); //zDbg = toVector(zeros, finalOrder); } template<class T> void rsInfiniteImpulseResponseDesigner<T>::getBiquadCascadeCoefficients(T *b0, T *b1, T *b2, T *a1, T *a2) { // calculate the required order and number of biquads for the filter: int finalOrder, numBiquads; if( mode == BANDPASS || mode == BANDREJECT || mode == PEAK ) finalOrder = 2*prototypeOrder; else finalOrder = prototypeOrder; if( rsIsEven(finalOrder) ) numBiquads = finalOrder/2; else numBiquads = (finalOrder+1)/2; // set up the type for the prototype (lowpass/low-shelv): if( mode == LOW_SHELV || mode == HIGH_SHELV || mode == PEAK || mode == BYPASS ) { prototypeDesigner.setPrototypeMode(rsPrototypeDesigner<T>::LOWSHELV_PROTOTYPE); if( rsIsCloseTo(gain, 0.0, 0.001) || mode == BYPASS ) // gains of zero yield a 'bypass' filter { for(int b = 0; b < numBiquads; b++) // msvc gives an "unreachable code" warning here - but { // the code is definitely reachable...hmmm b0[b] = 1.0; b1[b] = 0.0; b2[b] = 0.0; a1[b] = 0.0; a2[b] = 0.0; return; } } } else prototypeDesigner.setPrototypeMode(rsPrototypeDesigner<T>::LOWPASS_PROTOTYPE); T f1, f2, wd1, wd2; // wa1, wa2; T fs = sampleRate; // use sanity-checked local frequency variables here: f2 = upperFrequency; if( mode == BANDPASS || mode == BANDREJECT || mode == PEAK ) { f1 = lowerFrequency; if( f2 > T(0.99*0.5)*fs ) f2 = T(0.99*0.5)*fs; // ensure upper frequency < sampleRate/2 if( f1 > T(0.99)*f2 ) f1 = T(0.99)*f2; // ensure lower frequency < upper frequency } else { f1 = frequency; if( f1 > T(0.99*0.5)*fs ) f1 = T(0.99*0.5)*fs; // ensure frequency < sampleRate/2 } // prewarp the frequencies to the desired frequencies required for the design of the // (unnormalized) analog prototype filter: if( mode == BANDPASS || mode == BANDREJECT || mode == PEAK ) { wd1 = T(2*PI)*f1/fs; // normalized digital radian frequency 1 //wa1 = 2.0*fs*tan(0.5*wd1); // pre-warped analog radian frequency 1 wd2 = T(2*PI)*f2/fs; // normalized digital radian frequency 2 //wa2 = 2.0*fs*tan(0.5*wd2); // pre-warped analog radian frequency 2 } else { wd1 = T(2*PI)*f1/fs; // normalized digital radian frequency 1 //wa1 = 2.0*fs*tan(0.5*wd1); // pre-warped analog radian frequency 1 wd2 = 0.0; // unused //wa2 = 0.0; // unused } std::vector<Complex> poles(finalOrder), zeros(finalOrder); getPolesAndZeros(&poles[0], &zeros[0]); // seems to return zeros in wrong order for elliptic bandpass rsFilterCoefficientConverter<T>::polesAndZerosToBiquadCascade(&poles[0], &zeros[0], finalOrder, b0, b1, b2, a1, a2); T deWarpedPassbandCenter = T(2) * atan(sqrt(tan(T(0.5)*wd1)*tan(T(0.5)*wd2))); normalizeGain(b0, b1, b2, a1, a2, deWarpedPassbandCenter, numBiquads); } template<class T> void rsInfiniteImpulseResponseDesigner<T>::getDirectFormCoefficients(T *b, T *a) { int numBiquads = getNumBiquadStages(); T *b0 = new T[numBiquads]; T *b1 = new T[numBiquads]; T *b2 = new T[numBiquads]; T *a1 = new T[numBiquads]; T *a2 = new T[numBiquads]; getBiquadCascadeCoefficients(b0, b1, b2, a1, a2); rsFilterCoefficientConverter<T>::biquadCascadeToDirectForm(numBiquads, b0, b1, b2, a1, a2, b, a); delete[] b0; delete[] b1; delete[] b2; delete[] a1; delete[] a2; } template<class T> void rsInfiniteImpulseResponseDesigner<T>::calculateLowerAndUpperFrequency() { lowerFrequency = frequency / pow(T(2), T(0.5)*bandwidth); upperFrequency = lowerFrequency * pow(T(2), bandwidth); } template<class T> void rsInfiniteImpulseResponseDesigner<T>::normalizeGain(T *b0, T *b1, T *b2, T *a1, T *a2, T wc, int numBiquads) { T w = 0.0; if( mode == LOWPASS || mode == BANDREJECT || mode == HIGH_SHELV || mode == PEAK ) // redundant w = 0.0; // normalize at DC else if( mode == HIGHPASS || mode == LOW_SHELV ) w = T(PI); // normalize at Nyquist frequency else if( mode == BANDPASS ) w = wc; // normalize at passband center frequency T normalizeFactor = T(1); if( prototypeDesigner.getPrototypeMode() == rsPrototypeDesigner<T>::LOWSHELV_PROTOTYPE ) { if( prototypeDesigner.getApproximationMethod() == rsPrototypeDesigner<T>::INVERSE_CHEBYCHEV || prototypeDesigner.getApproximationMethod() == rsPrototypeDesigner<T>::ELLIPTIC ) { if( rsIsEven(prototypeDesigner.getOrder()) ) { T factor = T(1)-prototypeDesigner.getPassbandGainRatio(); T excessDb = -factor * gain; normalizeFactor = rsDbToAmp(-excessDb/numBiquads); } } } else // prototype is lowpass { if( prototypeDesigner.getApproximationMethod() == rsPrototypeDesigner<T>::CHEBYCHEV || prototypeDesigner.getApproximationMethod() == rsPrototypeDesigner<T>::ELLIPTIC ) { if( rsIsEven(prototypeDesigner.getOrder()) ) { normalizeFactor = T(1) / rsDbToAmp(prototypeDesigner.getPassbandRipple()); if( doesModeDoubleTheOrder() ) normalizeFactor = pow(normalizeFactor, T(1) / prototypeDesigner.getOrder()); else normalizeFactor = pow(normalizeFactor, T(2) / prototypeDesigner.getOrder()); } } } rsFilterCoefficientConverter<T>::normalizeBiquadStages(b0, b1, b2, a1, a2, w, numBiquads, normalizeFactor); }
33.245361
139
0.685252
[ "vector", "transform" ]
2ca3d044cec80278d2ffcd494094f61e01584342
13,515
cpp
C++
be/src/exec/vectorized/chunks_sorter.cpp
niexiongchao/starRocks
afecea80e50ee505261fffc3cff5f546ee285475
[ "Zlib", "PSF-2.0", "Apache-2.0" ]
null
null
null
be/src/exec/vectorized/chunks_sorter.cpp
niexiongchao/starRocks
afecea80e50ee505261fffc3cff5f546ee285475
[ "Zlib", "PSF-2.0", "Apache-2.0" ]
null
null
null
be/src/exec/vectorized/chunks_sorter.cpp
niexiongchao/starRocks
afecea80e50ee505261fffc3cff5f546ee285475
[ "Zlib", "PSF-2.0", "Apache-2.0" ]
null
null
null
// This file is licensed under the Elastic License 2.0. Copyright 2021-present, StarRocks Limited. #include "exec/vectorized/chunks_sorter.h" #include "column/column_helper.h" #include "column/type_traits.h" #include "exec/vectorized/sorting/sort_permute.h" #include "exprs/expr.h" #include "gutil/casts.h" #include "runtime/current_thread.h" #include "runtime/runtime_state.h" #include "util/orlp/pdqsort.h" #include "util/stopwatch.hpp" namespace starrocks::vectorized { static void get_compare_results_colwise(size_t row_to_sort, Columns& order_by_columns, std::vector<CompareVector>& compare_results_array, std::vector<DataSegment>& data_segments, const std::vector<int>& sort_order_flags, const std::vector<int>& null_first_flags) { for (size_t i = 0; i < data_segments.size(); ++i) { size_t rows = data_segments[i].chunk->num_rows(); compare_results_array[i].resize(rows, 0); } size_t dats_segment_size = data_segments.size(); size_t size = order_by_columns.size(); for (size_t i = 0; i < dats_segment_size; i++) { std::vector<Datum> rhs_values; auto& segment = data_segments[i]; for (size_t col_idx = 0; col_idx < size; col_idx++) { rhs_values.push_back(order_by_columns[col_idx]->get(row_to_sort)); } compare_columns(segment.order_by_columns, compare_results_array[i], rhs_values, sort_order_flags, null_first_flags); } } // Deprecated // compare every row in incoming_column with number_of_row_to_compare row with base_column, // save result compare_results, and collect equal rows of incoming_column as rows_to_compare use to // comapre with next column. template <bool reversed> static void compare_between_rows(Column& incoming_column, Column& base_column, size_t number_of_row_to_compare, std::vector<uint64_t>* rows_to_compare, std::vector<int8_t>* compare_results, int null_first_flag) { uint64_t* indexes; uint64_t* next_index; size_t num_indexes = rows_to_compare->size(); next_index = indexes = rows_to_compare->data(); for (size_t i = 0; i < num_indexes; ++i) { uint64_t row = indexes[i]; int res = incoming_column.compare_at(row, number_of_row_to_compare, base_column, null_first_flag); /// Convert to (-1, 0, 1). if (res < 0) { (*compare_results)[row] = -1; } else if (res > 0) { (*compare_results)[row] = 1; } else { (*compare_results)[row] = 0; *next_index = row; ++next_index; } if constexpr (reversed) (*compare_results)[row] = -(*compare_results)[row]; } rows_to_compare->resize(next_index - rows_to_compare->data()); } // Deprecated // compare data from incoming_column with number_of_row_to_compare of base_column. static void compare_column_with_one_row(Column& incoming_column, Column& base_column, size_t number_of_row_to_compare, std::vector<uint64_t>* rows_to_compare, std::vector<int8_t>* compare_result, int sort_order_flag, int null_first_flag) { if (sort_order_flag < 0) { compare_between_rows<true>(incoming_column, base_column, number_of_row_to_compare, rows_to_compare, compare_result, null_first_flag); } else { compare_between_rows<false>(incoming_column, base_column, number_of_row_to_compare, rows_to_compare, compare_result, null_first_flag); } } // Deprecated // compare all indexs of rows_to_compare_array from data_segments with row_to_sort of order_by_columns // through every column until get result as compare_results_array. // rows_to_compare_array is used to save rows that should compare next column. static void get_compare_results(size_t row_to_sort, Columns& order_by_columns, std::vector<std::vector<uint64_t>>* rows_to_compare_array, std::vector<std::vector<int8_t>>* compare_results_array, std::vector<DataSegment>& data_segments, const std::vector<int>& sort_order_flags, const std::vector<int>& null_first_flags) { size_t dats_segment_size = data_segments.size(); size_t size = order_by_columns.size(); for (size_t i = 0; i < dats_segment_size; ++i) { for (size_t j = 0; j < size; ++j) { compare_column_with_one_row(*data_segments[i].order_by_columns[j], *order_by_columns[j], row_to_sort, &(*rows_to_compare_array)[i], &(*compare_results_array)[i], sort_order_flags[j], null_first_flags[j]); if ((*rows_to_compare_array)[i].empty()) break; } } } Status DataSegment::get_filter_array(std::vector<DataSegment>& data_segments, size_t number_of_rows_to_sort, std::vector<std::vector<uint8_t>>& filter_array, const std::vector<int>& sort_order_flags, const std::vector<int>& null_first_flags, uint32_t& least_num, uint32_t& middle_num) { size_t dats_segment_size = data_segments.size(); std::vector<CompareVector> compare_results_array(dats_segment_size); // first compare with last row of this chunk. { get_compare_results_colwise(number_of_rows_to_sort - 1, order_by_columns, compare_results_array, data_segments, sort_order_flags, null_first_flags); } // but we only have one compare. // compare with first row of this DataSegment, // then we set BEFORE_LAST_RESULT and IN_LAST_RESULT at filter_array. if (number_of_rows_to_sort == 1) { least_num = 0, middle_num = 0; filter_array.resize(dats_segment_size); for (size_t i = 0; i < dats_segment_size; ++i) { size_t rows = data_segments[i].chunk->num_rows(); filter_array[i].resize(rows); for (size_t j = 0; j < rows; ++j) { if (compare_results_array[i][j] < 0) { filter_array[i][j] = DataSegment::BEFORE_LAST_RESULT; ++least_num; } else { filter_array[i][j] = DataSegment::IN_LAST_RESULT; ++middle_num; } } } } else { std::vector<size_t> first_size_array; first_size_array.resize(dats_segment_size); middle_num = 0; filter_array.resize(dats_segment_size); for (size_t i = 0; i < dats_segment_size; ++i) { DataSegment& segment = data_segments[i]; size_t rows = segment.chunk->num_rows(); filter_array[i].resize(rows); size_t local_first_size = middle_num; for (size_t j = 0; j < rows; ++j) { if (compare_results_array[i][j] < 0) { filter_array[i][j] = DataSegment::IN_LAST_RESULT; ++middle_num; } } // obtain number of rows for second compare. first_size_array[i] = middle_num - local_first_size; } // second compare with first row of this chunk, use rows from first compare. { for (size_t i = 0; i < dats_segment_size; i++) { for (auto& cmp : compare_results_array[i]) { if (cmp < 0) { cmp = 0; } } } get_compare_results_colwise(0, order_by_columns, compare_results_array, data_segments, sort_order_flags, null_first_flags); } least_num = 0; for (size_t i = 0; i < dats_segment_size; ++i) { DataSegment& segment = data_segments[i]; size_t rows = segment.chunk->num_rows(); for (size_t j = 0; j < rows; ++j) { if (compare_results_array[i][j] < 0) { filter_array[i][j] = DataSegment::BEFORE_LAST_RESULT; ++least_num; } } } middle_num -= least_num; } return Status::OK(); } ChunksSorter::ChunksSorter(RuntimeState* state, const std::vector<ExprContext*>* sort_exprs, const std::vector<bool>* is_asc, const std::vector<bool>* is_null_first, size_t size_of_chunk_batch) : _state(state), _sort_exprs(sort_exprs), _size_of_chunk_batch(size_of_chunk_batch) { DCHECK(_sort_exprs != nullptr); DCHECK(is_asc != nullptr); DCHECK(is_null_first != nullptr); DCHECK_EQ(_sort_exprs->size(), is_asc->size()); DCHECK_EQ(is_asc->size(), is_null_first->size()); size_t col_num = is_asc->size(); _sort_order_flag.resize(col_num); _null_first_flag.resize(col_num); for (size_t i = 0; i < is_asc->size(); ++i) { _sort_order_flag[i] = is_asc->at(i) ? 1 : -1; if (is_asc->at(i)) { _null_first_flag[i] = is_null_first->at(i) ? -1 : 1; } else { _null_first_flag[i] = is_null_first->at(i) ? 1 : -1; } } } ChunksSorter::~ChunksSorter() {} void ChunksSorter::setup_runtime(RuntimeProfile* profile, const std::string& parent_timer) { _build_timer = ADD_CHILD_TIMER(profile, "1-BuildingTime", parent_timer); _sort_timer = ADD_CHILD_TIMER(profile, "2-SortingTime", parent_timer); _merge_timer = ADD_CHILD_TIMER(profile, "3-MergingTime", parent_timer); _output_timer = ADD_CHILD_TIMER(profile, "4-OutputTime", parent_timer); } Status ChunksSorter::finish(RuntimeState* state) { TRY_CATCH_BAD_ALLOC(RETURN_IF_ERROR(done(state))); _is_sink_complete = true; return Status::OK(); } bool ChunksSorter::sink_complete() { return _is_sink_complete; } vectorized::ChunkPtr ChunksSorter::materialize_chunk_before_sort(vectorized::Chunk* chunk, TupleDescriptor* materialized_tuple_desc, const SortExecExprs& sort_exec_exprs, const std::vector<OrderByType>& order_by_types) { vectorized::ChunkPtr materialize_chunk = std::make_shared<vectorized::Chunk>(); // materialize all sorting columns: replace old columns with evaluated columns const size_t row_num = chunk->num_rows(); const auto& slots_in_row_descriptor = materialized_tuple_desc->slots(); const auto& slots_in_sort_exprs = sort_exec_exprs.sort_tuple_slot_expr_ctxs(); DCHECK_EQ(slots_in_row_descriptor.size(), slots_in_sort_exprs.size()); for (size_t i = 0; i < slots_in_sort_exprs.size(); ++i) { ExprContext* expr_ctx = slots_in_sort_exprs[i]; ColumnPtr col = expr_ctx->evaluate(chunk); if (col->is_constant()) { if (col->is_nullable()) { // Constant null column doesn't have original column data type information, // so replace it by a nullable column of original data type filled with all NULLs. ColumnPtr new_col = ColumnHelper::create_column(order_by_types[i].type_desc, true); new_col->append_nulls(row_num); materialize_chunk->append_column(new_col, slots_in_row_descriptor[i]->id()); } else { // Case 1: an expression may generate a constant column which will be reused by // another call of evaluate(). We clone its data column to resize it as same as // the size of the chunk, so that Chunk::num_rows() can return the right number // if this ConstColumn is the first column of the chunk. // Case 2: an expression may generate a constant column for one Chunk, but a // non-constant one for another Chunk, we replace them all by non-constant columns. auto* const_col = down_cast<ConstColumn*>(col.get()); const auto& data_col = const_col->data_column(); auto new_col = data_col->clone_empty(); new_col->append(*data_col, 0, 1); new_col->assign(row_num, 0); if (order_by_types[i].is_nullable) { ColumnPtr nullable_column = NullableColumn::create(ColumnPtr(new_col.release()), NullColumn::create(row_num, 0)); materialize_chunk->append_column(nullable_column, slots_in_row_descriptor[i]->id()); } else { materialize_chunk->append_column(ColumnPtr(new_col.release()), slots_in_row_descriptor[i]->id()); } } } else { // When get a non-null column, but it should be nullable, we wrap it with a NullableColumn. if (!col->is_nullable() && order_by_types[i].is_nullable) { col = NullableColumn::create(col, NullColumn::create(col->size(), 0)); } materialize_chunk->append_column(col, slots_in_row_descriptor[i]->id()); } } return materialize_chunk; } } // namespace starrocks::vectorized
45.505051
120
0.602368
[ "vector" ]
2ca6ff31886ce3b3740903e510a8197189c02f14
4,018
hpp
C++
obs-studio/UI/qt-wrappers.hpp
noelemahcz/libobspp
029472b973e5a1985f883242f249848385df83a3
[ "MIT" ]
null
null
null
obs-studio/UI/qt-wrappers.hpp
noelemahcz/libobspp
029472b973e5a1985f883242f249848385df83a3
[ "MIT" ]
null
null
null
obs-studio/UI/qt-wrappers.hpp
noelemahcz/libobspp
029472b973e5a1985f883242f249848385df83a3
[ "MIT" ]
null
null
null
/****************************************************************************** Copyright (C) 2013 by Hugh Bailey <obs.jim@gmail.com> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ #pragma once #include <QApplication> #include <QMessageBox> #include <QWidget> #include <QWindow> #include <QThread> #include <obs.hpp> #include <functional> #include <memory> #include <vector> #define QT_UTF8(str) QString::fromUtf8(str, -1) #define QT_TO_UTF8(str) str.toUtf8().constData() class QDataStream; class QComboBox; class QWidget; class QLayout; class QString; struct gs_window; class OBSMessageBox { public: static QMessageBox::StandardButton question(QWidget *parent, const QString &title, const QString &text, QMessageBox::StandardButtons buttons = QMessageBox::StandardButtons(QMessageBox::Yes | QMessageBox::No), QMessageBox::StandardButton defaultButton = QMessageBox::NoButton); static void information(QWidget *parent, const QString &title, const QString &text); static void warning(QWidget *parent, const QString &title, const QString &text, bool enableRichText = false); static void critical(QWidget *parent, const QString &title, const QString &text); }; void OBSErrorBox(QWidget *parent, const char *msg, ...); bool QTToGSWindow(QWindow *window, gs_window &gswindow); uint32_t TranslateQtKeyboardEventModifiers(Qt::KeyboardModifiers mods); QDataStream & operator<<(QDataStream &out, const std::vector<std::shared_ptr<OBSSignal>> &signal_vec); QDataStream &operator>>(QDataStream &in, std::vector<std::shared_ptr<OBSSignal>> &signal_vec); QDataStream &operator<<(QDataStream &out, const OBSScene &scene); QDataStream &operator>>(QDataStream &in, OBSScene &scene); QDataStream &operator<<(QDataStream &out, const OBSSceneItem &si); QDataStream &operator>>(QDataStream &in, OBSSceneItem &si); QThread *CreateQThread(std::function<void()> func); void ExecuteFuncSafeBlock(std::function<void()> func); void ExecuteFuncSafeBlockMsgBox(std::function<void()> func, const QString &title, const QString &text); /* allows executing without message boxes if starting up, otherwise with a * message box */ void EnableThreadedMessageBoxes(bool enable); void ExecThreadedWithoutBlocking(std::function<void()> func, const QString &title, const QString &text); class SignalBlocker { QWidget *widget; bool blocked; public: inline explicit SignalBlocker(QWidget *widget_) : widget(widget_) { blocked = widget->blockSignals(true); } inline ~SignalBlocker() { widget->blockSignals(blocked); } }; void DeleteLayout(QLayout *layout); static inline Qt::ConnectionType WaitConnection() { return QThread::currentThread() == qApp->thread() ? Qt::DirectConnection : Qt::BlockingQueuedConnection; } bool LineEditCanceled(QEvent *event); bool LineEditChanged(QEvent *event); void SetComboItemEnabled(QComboBox *c, int idx, bool enabled); void setThemeID(QWidget *widget, const QString &themeID); QString SelectDirectory(QWidget *parent, QString title, QString path); QString SaveFile(QWidget *parent, QString title, QString path, QString extensions); QString OpenFile(QWidget *parent, QString title, QString path, QString extensions); QStringList OpenFiles(QWidget *parent, QString title, QString path, QString extensions);
32.934426
79
0.720757
[ "vector" ]
2ca8b1dafb19b1a980d5361bce055e3eaf445f98
2,667
cpp
C++
game/Player.cpp
carbonacat/pokitto-tasui-example
eb4847833785cf28610d83cd13dc200be65dc2cf
[ "Apache-2.0" ]
null
null
null
game/Player.cpp
carbonacat/pokitto-tasui-example
eb4847833785cf28610d83cd13dc200be65dc2cf
[ "Apache-2.0" ]
null
null
null
game/Player.cpp
carbonacat/pokitto-tasui-example
eb4847833785cf28610d83cd13dc200be65dc2cf
[ "Apache-2.0" ]
null
null
null
#include "game/Player.hpp" #include "game/EnvTools.hpp" #include "ToiletPaper.h" namespace game { static constexpr Vector2 toiletPaperOrigin = {8, 8}; // Lifecycle. void Player::prepareForExploration() noexcept { _sprite.play(dude, Dude::walkS); } void Player::updateExploration() noexcept { using PB = Pokitto::Buttons; auto oldPosition = _position; Vector2 move { (PB::leftBtn() ? -_speed : 0) + (PB::rightBtn() ? _speed : 0), (PB::upBtn() ? -_speed : 0) + (PB::downBtn() ? _speed : 0) }; // Updating the rendered direction. if (move.x > 0) { if (_sprite.animation != Dude::walkE) _sprite.play(dude, Dude::walkE); } else if (move.x < 0) { if (_sprite.animation != Dude::walkW) _sprite.play(dude, Dude::walkW); } else if (move.y > 0) { if (_sprite.animation != Dude::walkS) _sprite.play(dude, Dude::walkS); } else if (move.y < 0) { if (_sprite.animation != Dude::walkN) _sprite.play(dude, Dude::walkN); } // Updating position separately for each axis so the Player can slide on walls. if (move.x != 0) { _position.x += move.x; if (EnvTools::tileAtPosition(_position) & Collide) _position.x -= move.x; } if (move.y != 0) { _position.y += move.y; if (EnvTools::tileAtPosition(_position) & Collide) _position.y -= move.y; } _updateSpeedWithCurrentTile(); } void Player::render(const Vector2& cameraPosition, bool withTP) noexcept { using PD = Pokitto::Display; if (withTP) { _tpTimer += (_tpTimer < 18) ? 1 : 0; } else _tpTimer -= (_tpTimer > 0) ? 1 : 0; if (_tpTimer != 0) PD::drawSprite(_position.x - cameraPosition.x - toiletPaperOrigin.x, _position.y - cameraPosition.y - toiletPaperOrigin.y - _tpTimer, ToiletPaper, false, false, 0); _sprite.draw(_position.x - cameraPosition.x - _spriteOrigin.x, _position.y - cameraPosition.y - _spriteOrigin.y, false, false, 0); } // Modes. void Player::_updateSpeedWithCurrentTile() noexcept { if (EnvTools::tileAtPosition(_position) & WalkOnGrass) _speed = Speeds::grass; else _speed = Speeds::regular; } }
28.677419
176
0.512936
[ "render" ]
2ca9f03817b92f48a9410faf92cc63dd8fb98a0c
9,227
cc
C++
onnxruntime/core/providers/openvino/ov_versions/utils.cc
lchang20/onnxruntime
97b8f6f394ae02c73ed775f456fd85639c91ced1
[ "MIT" ]
6,036
2019-05-07T06:03:57.000Z
2022-03-31T17:59:54.000Z
onnxruntime/core/providers/openvino/ov_versions/utils.cc
lchang20/onnxruntime
97b8f6f394ae02c73ed775f456fd85639c91ced1
[ "MIT" ]
5,730
2019-05-06T23:04:55.000Z
2022-03-31T23:55:56.000Z
onnxruntime/core/providers/openvino/ov_versions/utils.cc
lchang20/onnxruntime
97b8f6f394ae02c73ed775f456fd85639c91ced1
[ "MIT" ]
1,566
2019-05-07T01:30:07.000Z
2022-03-31T17:06:50.000Z
// Copyright(C) 2019 Intel Corporation // Licensed under the MIT License #include "core/providers/shared_library/provider_api.h" #if defined(_MSC_VER) #pragma warning(disable : 4244 4245 5208) #elif __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" #endif #include <ngraph/ngraph.hpp> #include <ngraph/frontend/onnx_import/onnx.hpp> #if defined(_MSC_VER) #pragma warning(default : 4244 4245) #elif __GNUC__ #pragma GCC diagnostic pop #endif namespace onnxruntime { namespace openvino_ep { //Gets the input count of given node int GetInputCount(const Node* node, const InitializedTensorSet& initializer_set) { int count = 0; for (const auto& input : node->InputDefs()) { auto name = input->Name(); auto it = initializer_set.find(name); if (it == initializer_set.end()) { count++; } } return count; } //Ops which are supported only in models(as intermediate nodes) and not in unit tests bool IsOpSupportedOnlyInModel(std::string name) { std::set<std::string> ops_supported_only_in_model = { "Cast", "Concat", "ConstantOfShape", "Dropout", "Expand", "EyeLike", "Exp", "GatherND", "Identity", "NonMaxSuppression", "NonZero", "Not", "OneHot", "Pad", "Range", "ReduceMin", "Resize", "Round", "Shape", "Split", "TopK"}; return ops_supported_only_in_model.find(name) != ops_supported_only_in_model.end(); } void AppendClusterToSubGraph(const std::vector<NodeIndex>& nodes, const std::vector<std::string>& inputs, const std::vector<std::string>& outputs, std::vector<std::unique_ptr<ComputeCapability>>& result) { static size_t op_counter = 0; auto meta_def = IndexedSubGraph_MetaDef::Create(); meta_def->name() = "OpenVINO-EP-subgraph_" + std::to_string(++op_counter); meta_def->domain() = kNGraphDomain; meta_def->since_version() = 1; meta_def->status() = ONNX_NAMESPACE::EXPERIMENTAL; meta_def->inputs() = inputs; meta_def->outputs() = outputs; auto sub_graph = IndexedSubGraph::Create(); sub_graph->Nodes() = nodes; sub_graph->SetMetaDef(std::move(meta_def)); result.push_back(ComputeCapability::Create(std::move(sub_graph))); } int GetOnnxOpSet(const GraphViewer& graph_viewer) { const auto& dm_to_ver = graph_viewer.DomainToVersionMap(); return dm_to_ver.at(kOnnxDomain); } std::map<std::string, std::set<std::string>> GetNgSupportedOps(const int onnx_opset) { std::map<std::string, std::set<std::string>> ng_supported_ops; ng_supported_ops.emplace(kOnnxDomain, ngraph::onnx_import::get_supported_operators(onnx_opset, kOnnxDomain)); const std::set<std::string> ng_disabled_ops = {"LSTM"}; //Place-holder for ops not supported. for (const auto& disabled_op : ng_disabled_ops) { ng_supported_ops.at(kOnnxDomain).erase(disabled_op); } return ng_supported_ops; } /** * Returns a vector clusters(or node_idx). For each unsupported node, the graph is split into 3 parts. * supported_cluster + (UNsupported_node + rest_of_the_graph). This functions returns vector of all supported_clusters by nGraph */ std::vector<std::vector<NodeIndex>> GetPartitionedClusters(const std::vector<NodeIndex>& topological_order, const std::vector<NodeIndex>& unsupported_nodes) { std::vector<std::vector<NodeIndex>> ng_clusters; auto prev = topological_order.begin(); for (const auto& unsup_node : unsupported_nodes) { auto it = std::find(prev, topological_order.end(), unsup_node); // Create a cluster vector[supported_node_idx, unsupported_node_idx) and append it to return list. std::vector<NodeIndex> this_cluster{prev, it}; if (!this_cluster.empty()) { ng_clusters.push_back(std::move(this_cluster)); } // Point prev to node idx past this unsuported node. prev = ++it; } //Tail std::vector<NodeIndex> this_cluster{prev, topological_order.end()}; if (!this_cluster.empty()) { ng_clusters.push_back(std::move(this_cluster)); } return ng_clusters; } void IdentifyConnectedNodes(const GraphViewer& graph_viewer, NodeIndex curr_node_index, std::vector<NodeIndex>& cluster, std::vector<NodeIndex>& sub_cluster) { if (std::find(cluster.begin(), cluster.end(), curr_node_index) == cluster.end()) return; sub_cluster.emplace_back(curr_node_index); cluster.erase(std::remove(cluster.begin(), cluster.end(), curr_node_index), cluster.end()); auto curr_node = graph_viewer.GetNode(curr_node_index); for (auto node = curr_node->InputNodesBegin(); node != curr_node->InputNodesEnd(); ++node) { IdentifyConnectedNodes(graph_viewer, (*node).Index(), cluster, sub_cluster); } for (auto node = curr_node->OutputNodesBegin(); node != curr_node->OutputNodesEnd(); ++node) { IdentifyConnectedNodes(graph_viewer, (*node).Index(), cluster, sub_cluster); } } std::vector<std::vector<NodeIndex>> GetConnectedClusters(const GraphViewer& graph_viewer, const std::vector<std::vector<NodeIndex>>& clusters) { std::vector<std::vector<NodeIndex>> connected_clusters; for (auto this_cluster : clusters) { while (this_cluster.size() > 0) { std::vector<NodeIndex> sub_cluster; IdentifyConnectedNodes(graph_viewer, this_cluster[0], this_cluster, sub_cluster); connected_clusters.emplace_back(sub_cluster); } } return connected_clusters; } void GetInputsOutputsOfCluster(const GraphViewer& graph_viewer, const std::vector<NodeIndex>& cluster, const std::unordered_set<std::string>& ng_required_initializers, /*out*/ std::vector<std::string>& cluster_graph_inputs, /*out*/ std::vector<std::string>& cluster_inputs, /*out*/ std::vector<std::string>& constant_inputs, /*out*/ std::vector<std::string>& cluster_outputs) { std::unordered_set<std::string> input_args; std::vector<std::string> ordered_input_args; std::unordered_set<std::string> output_args; std::unordered_set<std::string> external_output_args; for (const auto& node_idx : cluster) { const auto& node = graph_viewer.GetNode(node_idx); // Collect all inputs and outputs node->ForEachDef( [&input_args, &ordered_input_args, &output_args](const NodeArg& node_arg, bool is_input) { if (node_arg.Name() != "") { if (is_input) { if (!input_args.count(node_arg.Name())) { ordered_input_args.push_back(node_arg.Name()); } input_args.insert(node_arg.Name()); } else { output_args.insert(node_arg.Name()); } } }, true); // Check if output of this node is used by nodes outside this_cluster. If yes add this to cluster outputs for (auto it = node->OutputNodesBegin(); it != node->OutputNodesEnd(); ++it) { const auto& ext_node = graph_viewer.GetNode((*it).Index()); if (std::find(cluster.begin(), cluster.end(), ext_node->Index()) == cluster.end()) { // Node is external to this_cluster. Search through its inputs to find the output that is generated by this_cluster. std::set<std::string> ext_node_inputs; ext_node->ForEachDef( [&ext_node_inputs](const NodeArg& arg, bool is_input) { if (is_input) { ext_node_inputs.insert(arg.Name()); } }, true); for (const auto& out_def : node->OutputDefs()) { if (ext_node_inputs.find(out_def->Name()) != ext_node_inputs.end()) { external_output_args.insert(out_def->Name()); } } } } } //Extract initializers used by this_cluster. std::unordered_set<std::string> original_graph_inputs; for (const auto& node_arg : graph_viewer.GetInputsIncludingInitializers()) { original_graph_inputs.insert(node_arg->Name()); } const auto& initializers = graph_viewer.GetAllInitializedTensors(); for (const auto& in_arg : ordered_input_args) { if ((initializers.count(in_arg) && !original_graph_inputs.count(in_arg)) || ng_required_initializers.count(in_arg)) { constant_inputs.push_back(in_arg); } } for (const auto& in_arg : ordered_input_args) { if (!output_args.count(in_arg) && !((initializers.count(in_arg) && !original_graph_inputs.count(in_arg)) || ng_required_initializers.count(in_arg))) { cluster_inputs.push_back(in_arg); } } for (const auto& input : cluster_inputs) { cluster_graph_inputs.push_back(input); } for (const auto& in_arg : constant_inputs) { cluster_inputs.push_back(in_arg); } std::copy(external_output_args.begin(), external_output_args.end(), std::back_inserter(cluster_outputs)); for (const auto& node_arg : graph_viewer.GetOutputs()) { const auto& name = node_arg->Name(); if (output_args.count(name) && !external_output_args.count(name)) { cluster_outputs.push_back(name); } } } } // namespace openvino_ep } // namespace onnxruntime
36.184314
159
0.669015
[ "shape", "vector" ]
2cbadcf9061c27c208ce40b924c92bae5e7831fa
3,092
cpp
C++
AdvancedLevel_C++/1004. Counting Leaves (30) .cpp
XXlijiulong/ProgramTrouble
c6353bda1c2584a8f45a2c3b2f64ecf92500fc4f
[ "Apache-2.0" ]
null
null
null
AdvancedLevel_C++/1004. Counting Leaves (30) .cpp
XXlijiulong/ProgramTrouble
c6353bda1c2584a8f45a2c3b2f64ecf92500fc4f
[ "Apache-2.0" ]
null
null
null
AdvancedLevel_C++/1004. Counting Leaves (30) .cpp
XXlijiulong/ProgramTrouble
c6353bda1c2584a8f45a2c3b2f64ecf92500fc4f
[ "Apache-2.0" ]
null
null
null
1004. Counting Leaves (30) A family hierarchy is usually presented by a pedigree tree. Your job is to count those family members who have no child. Input Each input file contains one test case. Each case starts with a line containing 0 < N < 100, the number of nodes in a tree, and M (< N), the number of non-leaf nodes. Then M lines follow, each in the format: ID K ID[1] ID[2] ... ID[K] where ID is a two-digit number representing a given non-leaf node, K is the number of its children, followed by a sequence of two-digit ID's of its children. For the sake of simplicity, let us fix the root ID to be 01. Output For each test case, you are supposed to count those family members who have no child for every seniority level starting from the root. The numbers must be printed in a line, separated by a space, and there must be no extra space at the end of each line. The sample case represents a tree with only 2 nodes, where 01 is the root and 02 is its only child. Hence on the root 01 level, there is 0 leaf node; and on the next level, there is 1 leaf node. Then we should output "0 1" in a line. Sample Input 2 1 01 1 02 Sample Output 0 1 题目大意:给出一棵树,问每一层各有多少个叶子结点。 分析:可以用dfs也可以用bfs。 dfs的话,用二维数组保存每一个有孩子结点的结点以及他们的孩子结点,从根结点开始遍历,直到遇到叶子结点,就将当前层数depth的book[depth]++; 标记第depth层拥有的叶子结点数,最后输出 如果用bfs,设立两个数组,第一个level,保存i结点的层数,为了bfs的时候可以让当前结点的层数是它的父结点层数+1,第二个数组book,保存i层所拥有的叶子结点的个数。变量maxlevel保存最大的层数~~ dfs: #include <iostream> #include <vector> #include <algorithm> using namespace std; vector<int> v[100]; int book[100], maxdepth = -1; void dfs(int index, int depth) { if(v[index].size() == 0) { book[depth]++; maxdepth = max(maxdepth, depth); return ; } for(int i = 0; i < v[index].size(); i++) dfs(v[index][i], depth + 1); } int main() { int n, m, k, node, c; scanf("%d %d", &n, &m); for(int i = 0; i < m; i++) { scanf("%d %d",&node, &k); for(int j = 0; j < k; j++) { scanf("%d", &c); v[node].push_back(c); } } dfs(1, 0); printf("%d", book[0]); for(int i = 1; i <= maxdepth; i++) printf(" %d", book[i]); return 0; } bfs: #include <cstdio> #include <queue> #include <vector> #include <algorithm> using namespace std; int level[100], book[100], maxlevel = -1; vector<int> v[100]; void bfs() { queue<int> q; q.push(1); level[1] = 0; while(!q.empty()) { int index = q.front(); q.pop(); maxlevel = max(level[index], maxlevel); if(v[index].size() == 0) book[level[index]]++; for(int i = 0; i < v[index].size(); i++) { q.push(v[index][i]); level[v[index][i]] = level[index] + 1; } } } int main() { int n, m, k, node, c; scanf("%d %d", &n, &m); for(int i = 0; i < m; i++) { scanf("%d %d",&node, &k); for(int j = 0; j < k; j++) { scanf("%d", &c); v[node].push_back(c); } } bfs(); printf("%d", book[0]); for(int i = 1; i <= maxlevel; i++) printf(" %d", book[i]); return 0; }
32.893617
253
0.598642
[ "vector" ]
2cc9209629d962702a7c623b44f898c92f390fd1
14,288
cpp
C++
Engine/source/EtRendering/SceneRendering/ShadedSceneRenderer.cpp
NeroBurner/ETEngine
3fe039ff65cd1355957bcfce3f851fa411a86d94
[ "MIT" ]
null
null
null
Engine/source/EtRendering/SceneRendering/ShadedSceneRenderer.cpp
NeroBurner/ETEngine
3fe039ff65cd1355957bcfce3f851fa411a86d94
[ "MIT" ]
null
null
null
Engine/source/EtRendering/SceneRendering/ShadedSceneRenderer.cpp
NeroBurner/ETEngine
3fe039ff65cd1355957bcfce3f851fa411a86d94
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "ShadedSceneRenderer.h" #include <EtCore/Content/ResourceManager.h> #include <EtRendering/GlobalRenderingSystems/GlobalRenderingSystems.h> #include <EtRendering/SceneStructure/RenderScene.h> #include <EtRendering/GraphicsTypes/EnvironmentMap.h> #include <EtRendering/MaterialSystem/MaterialData.h> #include <EtRendering/PlanetTech/StarField.h> namespace et { namespace render { //======================= // Shaded Scene Renderer //======================= //--------------------------------- // ShadedSceneRenderer::GetCurrent // // Utility function to retrieve the scene renderer for the currently active viewport // ShadedSceneRenderer* ShadedSceneRenderer::GetCurrent() { Viewport* const viewport = Viewport::GetCurrentViewport(); if (viewport == nullptr) { return nullptr; } I_ViewportRenderer* const viewRenderer = viewport->GetViewportRenderer(); if (viewRenderer == nullptr) { return nullptr; } ET_ASSERT(viewRenderer->GetType() == typeid(ShadedSceneRenderer)); return static_cast<ShadedSceneRenderer*>(viewRenderer); } //-------------------------------------------------------------------------- //--------------------------------- // ShadedSceneRenderer::c-tor // ShadedSceneRenderer::ShadedSceneRenderer(render::Scene* const renderScene) : I_ViewportRenderer() , m_RenderScene(renderScene) { } //--------------------------------- // ShadedSceneRenderer::d-tor // // make sure all the singletons this system requires are uninitialized // ShadedSceneRenderer::~ShadedSceneRenderer() { RenderingSystems::RemoveReference(); } //------------------------------------------- // ShadedSceneRenderer::InitRenderingSystems // // Create required buffers and subrendering systems etc // void ShadedSceneRenderer::InitRenderingSystems() { RenderingSystems::AddReference(); m_TextRenderer.Initialize(); m_SpriteRenderer.Initialize(); m_ShadowRenderer.Initialize(); m_PostProcessing.Initialize(); m_GBuffer.Initialize(); m_GBuffer.Enable(true); m_SSR.Initialize(); m_ClearColor = vec3(200.f / 255.f, 114.f / 255.f, 200.f / 255.f)*0.0f; m_SkyboxShader = core::ResourceManager::Instance()->GetAssetData<ShaderData>("FwdSkyboxShader.glsl"_hash); m_IsInitialized = true; } //--------------------------------- // ShadedSceneRenderer::OnResize // void ShadedSceneRenderer::OnResize(ivec2 const dim) { m_Dimensions = dim; if (!m_IsInitialized) { return; } m_PostProcessing.~PostProcessingRenderer(); new(&m_PostProcessing) PostProcessingRenderer(); m_PostProcessing.Initialize(); m_SSR.~ScreenSpaceReflections(); new(&m_SSR) ScreenSpaceReflections(); m_SSR.Initialize(); } //--------------------------------- // ShadedSceneRenderer::OnRender // // Main scene drawing function // void ShadedSceneRenderer::OnRender(T_FbLoc const targetFb) { I_GraphicsApiContext* const api = Viewport::GetCurrentApiContext(); // Global variables for all rendering systems //******************************************** RenderingSystems::Instance()->GetSharedVarController().UpdataData(m_Camera, m_GBuffer); //Shadow Mapping //************** api->DebugPushGroup("shadow map generation"); api->SetDepthEnabled(true); api->SetCullEnabled(true); auto lightIt = m_RenderScene->GetDirectionalLightsShaded().begin(); auto shadowIt = m_RenderScene->GetDirectionalShadowData().begin(); while ((lightIt != m_RenderScene->GetDirectionalLightsShaded().end()) && (shadowIt != m_RenderScene->GetDirectionalShadowData().end())) { mat4 const& transform = m_RenderScene->GetNodes()[lightIt->m_NodeId]; m_ShadowRenderer.MapDirectional(transform, *shadowIt, this); lightIt++; shadowIt++; } api->DebugPopGroup(); //Deferred Rendering //****************** api->DebugPushGroup("deferred render pass"); //Step one: Draw the data onto gBuffer m_GBuffer.Enable(); //reset viewport api->SetViewport(ivec2(0), m_Dimensions); api->DebugPushGroup("clear previous pass"); api->SetClearColor(vec4(m_ClearColor, 1.f)); api->Clear(E_ClearFlag::Color | E_ClearFlag::Depth); api->DebugPopGroup(); // draw terrains api->DebugPushGroup("terrains"); api->SetCullEnabled(false); Patch& patch = RenderingSystems::Instance()->GetPatch(); for (Planet& planet : m_RenderScene->GetTerrains()) { if (planet.GetTriangulator().Update(m_RenderScene->GetNodes()[planet.GetNodeId()], m_Camera)) { planet.GetTriangulator().GenerateGeometry(); } //Bind patch instances patch.BindInstances(planet.GetTriangulator().GetPositions()); patch.UploadDistanceLUT(planet.GetTriangulator().GetDistanceLUT()); patch.Draw(planet, m_RenderScene->GetNodes()[planet.GetNodeId()]); } api->DebugPopGroup(); // render opaque objects to GBuffer api->DebugPushGroup("opaque objects"); api->SetCullEnabled(true); DrawMaterialCollectionGroup(m_RenderScene->GetOpaqueRenderables()); api->DebugPopGroup(); api->DebugPushGroup("extensions"); m_Events.Notify(E_RenderEvent::RenderDeferred, new RenderEventData(this, m_GBuffer.Get())); api->DebugPopGroup(); api->DebugPopGroup(); api->DebugPushGroup("lighting pass"); // render ambient IBL api->DebugPushGroup("image based lighting"); api->SetFaceCullingMode(E_FaceCullMode::Back); api->SetCullEnabled(false); m_SSR.EnableInput(); m_GBuffer.Draw(); api->DebugPopGroup(); //copy Z-Buffer from gBuffer api->DebugPushGroup("blit"); api->BindReadFramebuffer(m_GBuffer.Get()); api->BindDrawFramebuffer(m_SSR.GetTargetFBO()); api->CopyDepthReadToDrawFbo(m_Dimensions, m_Dimensions); api->DebugPopGroup(); // Render Light Volumes api->DebugPushGroup("light volumes"); api->SetDepthEnabled(false); api->SetBlendEnabled(true); api->SetBlendEquation(E_BlendEquation::Add); api->SetBlendFunction(E_BlendFactor::One, E_BlendFactor::One); api->SetCullEnabled(true); api->SetFaceCullingMode(E_FaceCullMode::Front); // pointlights api->DebugPushGroup("point lights"); for (Light const& pointLight : m_RenderScene->GetPointLights()) { mat4 const& transform = m_RenderScene->GetNodes()[pointLight.m_NodeId]; float const scale = etm::length(etm::decomposeScale(transform)); vec3 const pos = etm::decomposePosition(transform); RenderingSystems::Instance()->GetPointLightVolume().Draw(pos, scale, pointLight.m_Color); } api->DebugPopGroup(); // direct api->DebugPushGroup("directional lights"); for (Light const& dirLight : m_RenderScene->GetDirectionalLights()) { mat4 const& transform = m_RenderScene->GetNodes()[dirLight.m_NodeId]; vec3 const dir = (transform * vec4(vec3::FORWARD, 1.f)).xyz; RenderingSystems::Instance()->GetDirectLightVolume().Draw(dir, dirLight.m_Color); } api->DebugPopGroup(); // direct with shadow api->DebugPushGroup("directional lights shadowed"); lightIt = m_RenderScene->GetDirectionalLightsShaded().begin(); shadowIt = m_RenderScene->GetDirectionalShadowData().begin(); while ((lightIt != m_RenderScene->GetDirectionalLightsShaded().end()) && (shadowIt != m_RenderScene->GetDirectionalShadowData().end())) { Light const& dirLight = *lightIt; DirectionalShadowData const& shadow = *shadowIt; mat4 const& transform = m_RenderScene->GetNodes()[dirLight.m_NodeId]; vec3 const dir = (transform * vec4(vec3::FORWARD, 1.f)).xyz; RenderingSystems::Instance()->GetDirectLightVolume().DrawShadowed(dir, dirLight.m_Color, shadow); lightIt++; shadowIt++; } api->DebugPopGroup(); api->SetFaceCullingMode(E_FaceCullMode::Back); api->SetBlendEnabled(false); api->SetCullEnabled(false); api->DebugPopGroup(); // light volumes api->DebugPushGroup("extensions"); m_Events.Notify(E_RenderEvent::RenderLights, new RenderEventData(this, m_SSR.GetTargetFBO())); api->DebugPopGroup(); // draw SSR api->DebugPushGroup("reflections"); m_PostProcessing.EnableInput(); m_SSR.Draw(); api->DebugPopGroup(); // copy depth again api->DebugPushGroup("blit"); api->BindReadFramebuffer(m_SSR.GetTargetFBO()); api->BindDrawFramebuffer(m_PostProcessing.GetTargetFBO()); api->CopyDepthReadToDrawFbo(m_Dimensions, m_Dimensions); api->DebugPopGroup(); api->DebugPopGroup(); // lighting //Forward Rendering //****************** api->DebugPushGroup("forward render pass"); api->SetDepthEnabled(true); // draw skybox api->DebugPushGroup("skybox"); Skybox const& skybox = m_RenderScene->GetSkybox(); if (skybox.m_EnvironmentMap != nullptr) { api->SetShader(m_SkyboxShader.get()); m_SkyboxShader->Upload("skybox"_hash, skybox.m_EnvironmentMap->GetRadiance()); m_SkyboxShader->Upload("numMipMaps"_hash, skybox.m_EnvironmentMap->GetNumMipMaps()); m_SkyboxShader->Upload("roughness"_hash, skybox.m_Roughness); api->SetDepthFunction(E_DepthFunc::LEqual); RenderingSystems::Instance()->GetPrimitiveRenderer().Draw<primitives::Cube>(); } api->DebugPopGroup(); // draw stars api->DebugPushGroup("stars"); StarField const* const starfield = m_RenderScene->GetStarfield(); if (starfield != nullptr) { starfield->Draw(m_Camera); } api->DebugPopGroup(); // forward rendering api->DebugPushGroup("forward renderables"); api->SetCullEnabled(true); DrawMaterialCollectionGroup(m_RenderScene->GetForwardRenderables()); api->DebugPopGroup(); api->DebugPushGroup("extensions"); m_Events.Notify(E_RenderEvent::RenderForward, new RenderEventData(this, m_PostProcessing.GetTargetFBO())); api->DebugPopGroup(); // draw atmospheres api->DebugPushGroup("atmospheres"); if (m_RenderScene->GetAtmosphereInstances().size() > 0u) { api->SetFaceCullingMode(E_FaceCullMode::Front); api->SetDepthEnabled(false); api->SetBlendEnabled(true); api->SetBlendEquation(E_BlendEquation::Add); api->SetBlendFunction(E_BlendFactor::One, E_BlendFactor::One); for (AtmosphereInstance const& atmoInst : m_RenderScene->GetAtmosphereInstances()) { vec3 const pos = etm::decomposePosition(m_RenderScene->GetNodes()[atmoInst.nodeId]); ET_ASSERT(atmoInst.lightId != core::INVALID_SLOT_ID); Light const& sun = m_RenderScene->GetLight(atmoInst.lightId); vec3 const sunDir = etm::normalize((m_RenderScene->GetNodes()[sun.m_NodeId] * vec4(vec3::FORWARD, 1.f)).xyz); m_RenderScene->GetAtmosphere(atmoInst.atmosphereId).Draw(pos, atmoInst.height, atmoInst.groundRadius, sunDir); } api->SetFaceCullingMode(E_FaceCullMode::Back); api->SetBlendEnabled(false); api->SetDepthEnabled(true); } api->DebugPopGroup(); api->DebugPopGroup(); // forward render pass // add scene sprites before the overlay pass api->DebugPushGroup("post processing pass"); SpriteRenderer::E_ScalingMode const scalingMode = SpriteRenderer::E_ScalingMode::Texture; for (Sprite const& sprite : m_RenderScene->GetSprites()) { mat4 const& transform = m_RenderScene->GetNodes()[sprite.node]; vec3 pos, scale; quat rot; etm::decomposeTRS(transform, pos, rot, scale); m_SpriteRenderer.Draw(sprite.texture.get(), pos.xy, sprite.color, sprite.pivot, scale.xy, rot.Roll(), pos.z, scalingMode); } // post processing api->SetCullEnabled(false); m_PostProcessing.Draw(targetFb, m_RenderScene->GetPostProcessingSettings(), this); api->DebugPopGroup(); // post processing pass } //--------------------------------- // ShadedSceneRenderer::DrawShadow // // Render the scene to the depth buffer of the current framebuffer // void ShadedSceneRenderer::DrawShadow(I_Material const* const nullMaterial) { I_GraphicsApiContext* const api = Viewport::GetCurrentApiContext(); // No need to set shaders or upload material parameters as that is the calling functions responsibility for (MaterialCollection::Mesh const& mesh : m_RenderScene->GetShadowCasters().m_Meshes) { api->BindVertexArray(mesh.m_VAO); for (T_NodeId const node : mesh.m_Instances) { // #todo: collect a list of transforms and draw this instanced mat4 const& transform = m_RenderScene->GetNodes()[node]; Sphere instSphere = Sphere((transform * vec4(mesh.m_BoundingVolume.pos, 1.f)).xyz, etm::length(etm::decomposeScale(transform)) * mesh.m_BoundingVolume.radius); if (true) // #todo: light frustum check { nullMaterial->GetBaseMaterial()->GetShader()->Upload("model"_hash, transform); api->DrawElements(E_DrawMode::Triangles, mesh.m_IndexCount, mesh.m_IndexDataType, 0); } } } } //-------------------------------------------------- // ShadedSceneRenderer::DrawMaterialCollectionGroup // // Draws all meshes in a list of shaders // void ShadedSceneRenderer::DrawMaterialCollectionGroup(core::slot_map<MaterialCollection> const& collectionGroup) { I_GraphicsApiContext* const api = Viewport::GetCurrentApiContext(); for (MaterialCollection const& collection : collectionGroup) { api->SetShader(collection.m_Shader.get()); for (MaterialCollection::MaterialInstance const& material : collection.m_Materials) { ET_ASSERT(collection.m_Shader.get() == material.m_Material->GetBaseMaterial()->GetShader()); collection.m_Shader->UploadParameterBlock(material.m_Material->GetParameters()); for (MaterialCollection::Mesh const& mesh : material.m_Meshes) { api->BindVertexArray(mesh.m_VAO); for (T_NodeId const node : mesh.m_Instances) { // #todo: collect a list of transforms and draw this instanced mat4 const& transform = m_RenderScene->GetNodes()[node]; Sphere instSphere = Sphere((transform * vec4(mesh.m_BoundingVolume.pos, 1.f)).xyz, etm::length(etm::decomposeScale(transform)) * mesh.m_BoundingVolume.radius); if (m_Camera.GetFrustum().ContainsSphere(instSphere) != VolumeCheck::OUTSIDE) { collection.m_Shader->Upload("model"_hash, transform); api->DrawElements(E_DrawMode::Triangles, mesh.m_IndexCount, mesh.m_IndexDataType, 0); } } } } } } //----------------------------------- // ShadedSceneRenderer::DrawOverlays // // Post scene things which should be drawn to the viewport before anti aliasing // void ShadedSceneRenderer::DrawOverlays(T_FbLoc const targetFb) { I_GraphicsApiContext* const api = Viewport::GetCurrentApiContext(); api->DebugPushGroup("draw overlays"); m_SpriteRenderer.Draw(); m_TextRenderer.Draw(); api->DebugPushGroup("extensions"); m_Events.Notify(E_RenderEvent::RenderOutlines, new RenderEventData(this, targetFb)); api->DebugPopGroup(); // extensions api->DebugPopGroup(); // draw overlays } } // namespace render } // namespace et
30.793103
136
0.720605
[ "mesh", "render", "model", "transform" ]
2ccfd70e7e4651bbecd6e49425e76d3be808899a
4,915
cc
C++
src/Coordinates.cc
GandalfTea/enginehmw
29a363eed0b294ce76a90cd7da1b9c60b8c1839d
[ "MIT" ]
null
null
null
src/Coordinates.cc
GandalfTea/enginehmw
29a363eed0b294ce76a90cd7da1b9c60b8c1839d
[ "MIT" ]
null
null
null
src/Coordinates.cc
GandalfTea/enginehmw
29a363eed0b294ce76a90cd7da1b9c60b8c1839d
[ "MIT" ]
null
null
null
#include <Coordinates.h> namespace MEGA { // Quanternions Quaternion::Quaternion( float s, float v1, float v2, float v3 ) : s(s), v1(v1), v2(v2), v3(v3) { m = sqrt( pow(s, 2) + pow(v1, 2) + pow(v2, 2) + pow(v3, 2) ); } // Euler -> Quaternion Quaternion::Quaternion( EulerAngle src ) { float x = src.phi/2; float y = src.theta/2; float z = src.psi/2; s = sin(x) * cos(y) * cos(z) - cos(x) * sin(y) * sin(z); v1 = cos(x) * sin(y) * cos(z) + sin(x) * cos(y) * sin(z); v2 = cos(x) * cos(y) * sin(z) - sin(x) * sin(y) * cos(z); v3 = cos(x) * cos(y) * cos(z) + sin(x) * sin(y) * sin(z); m = sqrt( pow(s, 2) + pow(v1, 2) + pow(v2, 2) + pow(v3, 2) ); } // Rotation Matrix -> Quaternion Quaternion::Quaternion( Matrix<F64C1> src ) { //assert( src.t() * src == Matrix<F32C1>.eye(4); //assert( src.det = 1 ); // TODO: Check for division by zero, sqrt of negative num and de-orthogonalised matrix float trace = src.at(0, 0) + src.at(1, 1) + src.at(2, 2); if(trace > 0) { float S = sqrt( 1.0f + trace) * 2; s = 0.25 *S; v1 = ( src.at(2, 1) - src.at(1, 2) ) / S; v2 = ( src.at(0, 2) - src.at(2, 0) ) / S; v3 = ( src.at(1, 0) - src.at(0, 1) ) / S; } else if( (src.at(0, 0) > src.at(1, 1)) & (src.at(0, 0) > src.at(2, 2))) { float S = sqrt(1.0 + src.at(0, 0) - src.at(1, 1) - src.at(2, 2)) * 2; s = ( src.at(2, 1) - src.at(1, 2) ) / S; v1 = 0.25 *S; v2 = ( src.at(0, 1) - src.at(1, 0) ) / S; v3 = ( src.at(0, 2) - src.at(2, 0) ) / S; } else if( src.at(1, 1) > src.at(2, 2)) { float S = sqrt(1.0 + src.at(1, 1) - src.at(0, 0) - src.at(2, 2)) * 2; s = ( src.at(0, 2) - src.at(2, 0) ) / S; v1 = ( src.at(0, 1) - src.at(1, 0) ) / S; v2 = 0.25 *S; v3 = ( src.at(1, 2) - src.at(2, 1) ) / S; } else { float S = sqrt(1.0 + src.at(2, 2) - src.at(0, 0) - src.at(1, 1)) * 2; s = ( src.at(1, 0) - src.at(0, 1) ) / S; v1 = ( src.at(0, 2) - src.at(2, 0) ) / S; v2 = ( src.at(1, 2) - src.at(2, 1) ) / S; v3 = 0.25 *S; } m = sqrt( pow(s, 2) + pow(v1, 2) + pow(v2, 2) + pow(v3, 2) ); } // Quaternion -> Rotation Matrix Matrix<F64C1> Quaternion::toRotMat() { std::vector<double> R_data; R_data.push_back( 1 - 2*( v2 * v2 + v3 * v3)); // wrong R_data.push_back( 2*( v1 * v2 - s * v3)); // wrong R_data.push_back( 2*( v1 * v3 + s * v2)); R_data.push_back( 2*( v1 * v2 + s * v3)); // wrong R_data.push_back( 2*( s * s + v2 * v2) - 1); R_data.push_back( 2*( v2 * v3 - s * v1)); // wrong R_data.push_back( 2*( v1 * v3 - s * v2)); R_data.push_back( 2*( v2 * v3 + s * v1)); // wrong R_data.push_back( 2*( s * s + v3 * v3) - 1); //wrong Matrix<F64C1> R (3, 3, R_data); return R; } float Quaternion::innerProduct( Quaternion lhs, Quaternion rhs ) { return lhs.s*rhs.s + lhs.v1*rhs.v1 + lhs.v2*rhs.v2 + lhs.v3*rhs.v3; } Quaternion::~Quaternion() {} // EULER ANGLE EulerAngle::EulerAngle( Quaternion src ) { auto t0 = 2.0 * ( src.s * src.v1 + src.v1 * src.v3 ); auto t1 = 1.0 - 2.0 * ( pow(src.s, 2) + pow(src.v1, 2)); phi = atan2(t0, t1); auto t2 = 2.0 * ( src.s * src.v1 - src.v1 * src.v3 ); (t2 > 1.0) ? t2= 1.0 : t2; (t2 < -1.0) ? t2=-1.0 : t2; theta = asin(t2); auto t3 = 2.0 * ( src.s * src.v1 + src.v1 * src.v3 ); auto t4 = 1.0 - 2.0 * ( pow(src.v1, 2) + pow(src.v2, 2)); psi = atan2(t3, t4); } // Rotation Matrix -> Euler Angles EulerAngle::EulerAngle( Matrix<F64C1> src ) { if( src.at(2, 0) != 1 || src.at(2, 0) != -1) { theta = -asin(src.at(2,0)); //theta2 = M_PI - theta; phi = atan2( src.at(2, 1) / cos(theta), src.at(2, 2) / cos(theta)); //phi2 = atan2( src.at(3, 2) / cos(theta2), src.at(3, 3) / cos(theta2)); psi = atan2( src.at(1, 0) / cos(theta), src.at(1, 0) / cos(theta)); //psi2 = atan2( arc.at(2, 1) / cos(theta2), src.at(1, 1) / cos(theta2)); } else { psi = 0; if( src.at(2, 0) == -1) { theta = M_PI / 2; phi = psi + atan2( src.at(0, 1), src.at(0, 2) ); } else { theta = -M_PI / 2; phi = -psi + atan2( -src.at(0, 1), -src.at(0, 2) ); } } } Matrix<F64C1> EulerAngle::toRotMat() { std::vector<double> R_x { 1, 0, 0, 0, cos(phi), -sin(phi), 0, sin(phi), cos(phi) }; std::vector<double> R_y { cos(theta), 0, sin(theta), 0, 1, 0, -sin(theta), 0, cos(theta) }; std::vector<double> R_z { cos(psi), -sin(psi), 0, sin(psi), cos(psi), 0, 0, 0, 1 }; Matrix<F64C1> Rx(3, 3, R_x); Matrix<F64C1> Ry(3, 3, R_y); Matrix<F64C1> Rz(3, 3, R_z); Matrix<F64C1> temp = Ry.dot(Rz); Matrix<F64C1> R = Rx.dot(temp); return R; } EulerAngle::~EulerAngle() {} }// namespace
29.431138
88
0.478128
[ "vector" ]
2cd1bd61e9d288ac995f2374235a1c387da82845
12,825
cc
C++
L1Trigger/L1TTrackMatch/plugins/L1TkFastVertexProducer.cc
tklijnsma/cmssw
d7f103c459dd195eaa651ce0c30e4bd4bfd0fe43
[ "Apache-2.0" ]
1
2020-07-12T11:51:32.000Z
2020-07-12T11:51:32.000Z
L1Trigger/L1TTrackMatch/plugins/L1TkFastVertexProducer.cc
tklijnsma/cmssw
d7f103c459dd195eaa651ce0c30e4bd4bfd0fe43
[ "Apache-2.0" ]
3
2020-02-19T08:33:16.000Z
2020-03-13T10:02:19.000Z
L1Trigger/L1TTrackMatch/plugins/L1TkFastVertexProducer.cc
tklijnsma/cmssw
d7f103c459dd195eaa651ce0c30e4bd4bfd0fe43
[ "Apache-2.0" ]
1
2018-01-22T10:20:10.000Z
2018-01-22T10:20:10.000Z
// -*- C++ -*- // // // Original Author: Emmanuelle Perez,40 1-A28,+41227671915, // Created: Tue Nov 12 17:03:19 CET 2013 // $Id$ // // // system include files #include <memory> #include <string> // user include files #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/EDProducer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/Framework/interface/EventSetup.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "DataFormats/L1TrackTrigger/interface/TTTypes.h" //////////////////////////// // DETECTOR GEOMETRY HEADERS #include "MagneticField/Engine/interface/MagneticField.h" #include "Geometry/Records/interface/TrackerTopologyRcd.h" #include "DataFormats/TrackerCommon/interface/TrackerTopology.h" #include "DataFormats/L1TCorrelator/interface/TkPrimaryVertex.h" //////////////////////////// // HepMC products #include "DataFormats/HepMCCandidate/interface/GenParticle.h" #include "SimDataFormats/GeneratorProducts/interface/HepMCProduct.h" #include "DataFormats/Candidate/interface/Candidate.h" #include "TH1F.h" using namespace l1t; // // class declaration // class L1TkFastVertexProducer : public edm::EDProducer { public: typedef TTTrack<Ref_Phase2TrackerDigi_> L1TTTrackType; typedef std::vector<L1TTTrackType> L1TTTrackCollectionType; explicit L1TkFastVertexProducer(const edm::ParameterSet&); ~L1TkFastVertexProducer() override; static void fillDescriptions(edm::ConfigurationDescriptions& descriptions); private: void beginJob() override; void produce(edm::Event&, const edm::EventSetup&) override; void endJob() override; //virtual void beginRun(edm::Run&, edm::EventSetup const&); // ----------member data --------------------------- float zMax_; // in cm float DeltaZ; // in cm float chi2Max_; float pTMinTra_; // in GeV float pTMax_; // in GeV, saturation / truncation value int highPtTracks_; // saturate or truncate int nStubsmin_; // minimum number of stubs int nStubsPSmin_; // minimum number of stubs in PS modules int nBinning_; // number of bins used in the temp histogram bool monteCarloVertex_; // //const StackedTrackerGeometry* theStackedGeometry; bool doPtComp_; bool doTightChi2_; int weight_; // weight (power) of pT 0 , 1, 2 TH1F* htmp_; TH1F* htmp_weight_; const edm::EDGetTokenT<edm::HepMCProduct> hepmcToken; const edm::EDGetTokenT<std::vector<reco::GenParticle> > genparticleToken; const edm::EDGetTokenT<std::vector<TTTrack<Ref_Phase2TrackerDigi_> > > trackToken; }; // // constants, enums and typedefs // // // static data member definitions // // // constructors and destructor // L1TkFastVertexProducer::L1TkFastVertexProducer(const edm::ParameterSet& iConfig) : hepmcToken(consumes<edm::HepMCProduct>(iConfig.getParameter<edm::InputTag>("HepMCInputTag"))), genparticleToken( consumes<std::vector<reco::GenParticle> >(iConfig.getParameter<edm::InputTag>("GenParticleInputTag"))), trackToken(consumes<std::vector<TTTrack<Ref_Phase2TrackerDigi_> > >( iConfig.getParameter<edm::InputTag>("L1TrackInputTag"))) { zMax_ = (float)iConfig.getParameter<double>("ZMAX"); chi2Max_ = (float)iConfig.getParameter<double>("CHI2MAX"); pTMinTra_ = (float)iConfig.getParameter<double>("PTMINTRA"); pTMax_ = (float)iConfig.getParameter<double>("PTMAX"); highPtTracks_ = iConfig.getParameter<int>("HighPtTracks"); nStubsmin_ = iConfig.getParameter<int>("nStubsmin"); nStubsPSmin_ = iConfig.getParameter<int>("nStubsPSmin"); nBinning_ = iConfig.getParameter<int>("nBinning"); monteCarloVertex_ = iConfig.getParameter<bool>("MonteCarloVertex"); doPtComp_ = iConfig.getParameter<bool>("doPtComp"); doTightChi2_ = iConfig.getParameter<bool>("doTightChi2"); weight_ = iConfig.getParameter<int>("WEIGHT"); int nbins = nBinning_; // should be odd float xmin = -30; float xmax = +30; htmp_ = new TH1F("htmp_", ";z (cm); Tracks", nbins, xmin, xmax); htmp_weight_ = new TH1F("htmp_weight_", ";z (cm); Tracks", nbins, xmin, xmax); produces<TkPrimaryVertexCollection>(); } L1TkFastVertexProducer::~L1TkFastVertexProducer() { // do anything here that needs to be done at desctruction time // (e.g. close files, deallocate resources etc.) } // // member functions // // ------------ method called to produce the data ------------ void L1TkFastVertexProducer::produce(edm::Event& iEvent, const edm::EventSetup& iSetup) { using namespace edm; std::unique_ptr<TkPrimaryVertexCollection> result(new TkPrimaryVertexCollection); // Tracker Topology edm::ESHandle<TrackerTopology> tTopoHandle_; iSetup.get<TrackerTopologyRcd>().get(tTopoHandle_); const TrackerTopology* tTopo = tTopoHandle_.product(); htmp_->Reset(); htmp_weight_->Reset(); // ---------------------------------------------------------------------- if (monteCarloVertex_) { // MC info ... retrieve the zvertex edm::Handle<edm::HepMCProduct> HepMCEvt; iEvent.getByToken(hepmcToken, HepMCEvt); edm::Handle<std::vector<reco::GenParticle> > GenParticleHandle; iEvent.getByToken(genparticleToken, GenParticleHandle); const double mm = 0.1; float zvtx_gen = -999; if (HepMCEvt.isValid()) { // using HepMCEvt const HepMC::GenEvent* MCEvt = HepMCEvt->GetEvent(); for (HepMC::GenEvent::vertex_const_iterator ivertex = MCEvt->vertices_begin(); ivertex != MCEvt->vertices_end(); ++ivertex) { bool hasParentVertex = false; // Loop over the parents looking to see if they are coming from a production vertex for (HepMC::GenVertex::particle_iterator iparent = (*ivertex)->particles_begin(HepMC::parents); iparent != (*ivertex)->particles_end(HepMC::parents); ++iparent) if ((*iparent)->production_vertex()) { hasParentVertex = true; break; } // Reject those vertices with parent vertices if (hasParentVertex) continue; // Get the position of the vertex HepMC::FourVector pos = (*ivertex)->position(); zvtx_gen = pos.z() * mm; break; // there should be one single primary vertex } // end loop over gen vertices } else if (GenParticleHandle.isValid()) { std::vector<reco::GenParticle>::const_iterator genpartIter; for (genpartIter = GenParticleHandle->begin(); genpartIter != GenParticleHandle->end(); ++genpartIter) { int status = genpartIter->status(); if (status != 3) continue; if (genpartIter->numberOfMothers() == 0) continue; // the incoming hadrons float part_zvertex = genpartIter->vz(); zvtx_gen = part_zvertex; break; // } } else { throw cms::Exception("L1TkFastVertexProducer") << "\nerror: try to retrieve the MC vertex (monteCarloVertex_ = True) " << "\nbut the input file contains neither edm::HepMCProduct> nor vector<reco::GenParticle>. Exit" << std::endl; } // std::cout<<zvtx_gen<<endl; TkPrimaryVertex genvtx(zvtx_gen, -999.); result->push_back(genvtx); iEvent.put(std::move(result)); return; } edm::Handle<L1TTTrackCollectionType> L1TTTrackHandle; iEvent.getByToken(trackToken, L1TTTrackHandle); if (!L1TTTrackHandle.isValid()) { throw cms::Exception("L1TkFastVertexProducer") << "\nWarning: L1TkTrackCollection with not found in the event. Exit" << std::endl; return; } L1TTTrackCollectionType::const_iterator trackIter; for (trackIter = L1TTTrackHandle->begin(); trackIter != L1TTTrackHandle->end(); ++trackIter) { float z = trackIter->POCA().z(); float chi2 = trackIter->chi2(); float pt = trackIter->momentum().perp(); float eta = trackIter->momentum().eta(); //.............................................................. float wt = pow(pt, weight_); // calculating the weight for tks in as pt^0,pt^1 or pt^2 based on weight_ if (std::abs(z) > zMax_) continue; if (chi2 > chi2Max_) continue; if (pt < pTMinTra_) continue; // saturation or truncation : if (pTMax_ > 0 && pt > pTMax_) { if (highPtTracks_ == 0) continue; // ignore this track if (highPtTracks_ == 1) pt = pTMax_; // saturate } // get the number of stubs and the number of stubs in PS layers float nPS = 0.; // number of stubs in PS modules float nstubs = 0; // get pointers to stubs associated to the L1 track const std::vector<edm::Ref<edmNew::DetSetVector<TTStub<Ref_Phase2TrackerDigi_> >, TTStub<Ref_Phase2TrackerDigi_> > >& theStubs = trackIter->getStubRefs(); int tmp_trk_nstub = (int)theStubs.size(); if (tmp_trk_nstub < 0) { LogTrace("L1TkFastVertexProducer") << " ... could not retrieve the vector of stubs in L1TkFastVertexProducer::SumPtVertex " << std::endl; continue; } // loop over the stubs for (unsigned int istub = 0; istub < (unsigned int)theStubs.size(); istub++) { nstubs++; bool isPS = false; DetId detId(theStubs.at(istub)->getDetId()); if (detId.det() == DetId::Detector::Tracker) { if (detId.subdetId() == StripSubdetector::TOB && tTopo->tobLayer(detId) <= 3) isPS = true; else if (detId.subdetId() == StripSubdetector::TID && tTopo->tidRing(detId) <= 9) isPS = true; } if (isPS) nPS++; } // end loop over stubs if (nstubs < nStubsmin_) continue; if (nPS < nStubsPSmin_) continue; // quality cuts from Louise S, based on the pt-stub compatibility (June 20, 2014) int trk_nstub = (int)trackIter->getStubRefs().size(); float chi2dof = chi2 / (2 * trk_nstub - 4); if (doPtComp_) { float trk_consistency = trackIter->stubPtConsistency(); //if (trk_nstub < 4) continue; // done earlier //if (chi2 > 100.0) continue; // done earlier if (trk_nstub == 4) { if (std::abs(eta) < 2.2 && trk_consistency > 10) continue; else if (std::abs(eta) > 2.2 && chi2dof > 5.0) continue; } } if (doTightChi2_) { if (pt > 10.0 && chi2dof > 5.0) continue; } htmp_->Fill(z); htmp_weight_->Fill(z, wt); // changed from "pt" to "wt" which is some power of pt (0,1 or 2) } // end loop over tracks // sliding windows... maximize bin i + i-1 + i+1 float zvtx_sliding = -999; float sigma_max = -999; int nb = htmp_->GetNbinsX(); for (int i = 2; i <= nb - 1; i++) { float a0 = htmp_->GetBinContent(i - 1); float a1 = htmp_->GetBinContent(i); float a2 = htmp_->GetBinContent(i + 1); float sigma = a0 + a1 + a2; if (sigma > sigma_max) { sigma_max = sigma; float z0 = htmp_->GetBinCenter(i - 1); float z1 = htmp_->GetBinCenter(i); float z2 = htmp_->GetBinCenter(i + 1); zvtx_sliding = (a0 * z0 + a1 * z1 + a2 * z2) / sigma; } } zvtx_sliding = -999; sigma_max = -999; for (int i = 2; i <= nb - 1; i++) { float a0 = htmp_weight_->GetBinContent(i - 1); float a1 = htmp_weight_->GetBinContent(i); float a2 = htmp_weight_->GetBinContent(i + 1); float sigma = a0 + a1 + a2; if (sigma > sigma_max) { sigma_max = sigma; float z0 = htmp_weight_->GetBinCenter(i - 1); float z1 = htmp_weight_->GetBinCenter(i); float z2 = htmp_weight_->GetBinCenter(i + 1); zvtx_sliding = (a0 * z0 + a1 * z1 + a2 * z2) / sigma; } } TkPrimaryVertex vtx4(zvtx_sliding, sigma_max); result->push_back(vtx4); iEvent.put(std::move(result)); } // ------------ method called once each job just before starting event loop ------------ void L1TkFastVertexProducer::beginJob() {} // ------------ method called once each job just after ending the event loop ------------ void L1TkFastVertexProducer::endJob() {} // ------------ method called when starting to processes a run ------------ //void L1TkFastVertexProducer::beginRun(edm::Run& iRun, edm::EventSetup const& iSetup) {} // ------------ method fills 'descriptions' with the allowed parameters for the module ------------ void L1TkFastVertexProducer::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { //The following says we do not know what parameters are allowed so do no validation // Please change this to state exactly what you do use, even if it is no parameters edm::ParameterSetDescription desc; desc.setUnknown(); descriptions.addDefault(desc); } //define this as a plug-in DEFINE_FWK_MODULE(L1TkFastVertexProducer);
33.225389
121
0.647797
[ "geometry", "vector" ]
2cd85683bbb05633e26024198844b12afe0b62f8
91,860
cxx
C++
vtr/toro/TRP_RelativePlace/TRP_RelativePlaceHandler.cxx
haojunliu/OpenFPGA
b0c4f27077f698aae59bbcbd3ca002f22ba2a5a1
[ "BSD-2-Clause" ]
31
2016-02-15T02:57:28.000Z
2021-06-02T10:40:25.000Z
vtr/toro/TRP_RelativePlace/TRP_RelativePlaceHandler.cxx
haojunliu/OpenFPGA
b0c4f27077f698aae59bbcbd3ca002f22ba2a5a1
[ "BSD-2-Clause" ]
null
null
null
vtr/toro/TRP_RelativePlace/TRP_RelativePlaceHandler.cxx
haojunliu/OpenFPGA
b0c4f27077f698aae59bbcbd3ca002f22ba2a5a1
[ "BSD-2-Clause" ]
6
2017-02-08T21:51:51.000Z
2021-06-02T10:40:40.000Z
//===========================================================================// // Purpose : Method definitions for the TRP_RelativePlaceHandler class. // // Public methods include: // - NewInstance, DeleteInstance, GetInstance, HasInstance // - Configure // - Reset // - InitialPlace // - Place // - IsCandidate // - IsValid // // Protected methods include: // - TRP_RelativePlaceHandler_c, ~TRP_RelativePlaceHandler_c // // Private methods include: // - AddSideConstraint_ // - NewSideConstraint_ // - MergeSideConstraints_ // - ExistingSideConstraint_ // - HasExistingSideConstraint_ // - IsAvailableSideConstraint_ // - SetVPR_Placement_ // - ResetVPR_Placement_ // - ResetRelativeMacroList_ // - ResetRelativeBlockList_ // - InitialPlaceMacros_ // - InitialPlaceMacroNodes_ // - InitialPlaceMacroResetCoords_ // - InitialPlaceMacroIsLegal_ // - InitialPlaceMacroIsOpen_ // - PlaceSwapMacros_ // - PlaceSwapUpdate_ // - PlaceMacroIsRelativeCoord_ // - PlaceMacroIsAvailableCoord_ // - PlaceMacroResetRotate_ // - PlaceMacroIsLegalRotate_ // - PlaceMacroIsValidRotate_ // - PlaceMacroUpdateMoveList_ // - PlaceMacroIsLegalMoveList_ // - FindRandomRotateMode_ // - FindRandomOriginPoint_ // - FindRandomRelativeNodeIndex_ // - FindRelativeMacroIndex_ // - FindRelativeNodeIndex_ // - FindRelativeMacro_ // - FindRelativeNode_ // - FindRelativeBlock_ // - FindGridPointBlockName_ // - FindGridPointBlockIndex_ // - FindGridPointType_ // - IsEmptyGridPoint_ // - IsWithinGrid_ // - DecideAntiSide_ // - ShowMissingBlockNameError_ // - ShowInvalidConstraintError_ // //===========================================================================// //---------------------------------------------------------------------------// // Copyright (C) 2013 Jeff Rudolph, Texas Instruments (jrudolph@ti.com) // // // // This program is free software; you can redistribute it and/or modify it // // under the terms of the GNU General Public License as published by the // // Free Software Foundation; version 3 of the License, or any later version. // // // // This program is distributed in the hope that it will be useful, but // // WITHOUT ANY WARRANTY; without even an implied warranty of MERCHANTABILITY // // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // // for more details. // // // // You should have received a copy of the GNU General Public License along // // with this program; if not, see <http://www.gnu.org/licenses>. // //---------------------------------------------------------------------------// #include <cstdio> #include <cstring> #include <string> using namespace std; #include "TC_Typedefs.h" #include "TC_MemoryUtils.h" #include "TCT_Generic.h" #include "TIO_PrintHandler.h" #include "TGO_StringUtils.h" #include "TRP_Typedefs.h" #include "TRP_RelativeMove.h" #include "TRP_RelativePlaceHandler.h" // Initialize the relative place handler "singleton" class, as needed TRP_RelativePlaceHandler_c* TRP_RelativePlaceHandler_c::pinstance_ = 0; //===========================================================================// // Method : TRP_RelativePlaceHandler_c // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 01/15/13 jeffr : Original //===========================================================================// TRP_RelativePlaceHandler_c::TRP_RelativePlaceHandler_c( void ) : relativeMacroList_( TRP_RELATIVE_MACRO_LIST_DEF_CAPACITY ), relativeBlockList_( TRP_RELATIVE_BLOCK_LIST_DEF_CAPACITY ) { this->placeOptions_.rotateEnable = false; this->placeOptions_.maxPlaceRetryCt = 0; this->placeOptions_.maxMacroRetryCt = 0; this->vpr_.gridArray = 0; this->vpr_.nx = 0; this->vpr_.ny = 0; this->vpr_.blockArray = 0; this->vpr_.blockCount = 0; this->vpr_.typeArray = 0; this->vpr_.typeCount = 0; this->vpr_.freeLocationArray = 0; this->vpr_.legalPosArray = 0; this->vpr_.pfreeLocationArray = 0; this->vpr_.plegalPosArray = 0; pinstance_ = 0; } //===========================================================================// // Method : ~TRP_RelativePlaceHandler_c // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 01/15/13 jeffr : Original //===========================================================================// TRP_RelativePlaceHandler_c::~TRP_RelativePlaceHandler_c( void ) { } //===========================================================================// // Method : NewInstance // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 01/15/13 jeffr : Original //===========================================================================// void TRP_RelativePlaceHandler_c::NewInstance( void ) { pinstance_ = new TC_NOTHROW TRP_RelativePlaceHandler_c; } //===========================================================================// // Method : DeleteInstance // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 01/15/13 jeffr : Original //===========================================================================// void TRP_RelativePlaceHandler_c::DeleteInstance( void ) { if( pinstance_ ) { delete pinstance_; pinstance_ = 0; } } //===========================================================================// // Method : GetInstance // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 01/15/13 jeffr : Original //===========================================================================// TRP_RelativePlaceHandler_c& TRP_RelativePlaceHandler_c::GetInstance( bool newInstance ) { if( !pinstance_ ) { if( newInstance ) { NewInstance( ); } } return( *pinstance_ ); } //===========================================================================// // Method : HasInstance // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 01/15/13 jeffr : Original //===========================================================================// bool TRP_RelativePlaceHandler_c::HasInstance( void ) { return( pinstance_ ? true : false ); } //===========================================================================// // Method : Configure // Description : Configure a relative place handler (singleton) based on // VPR's block array (ie. instance list), along with Toro's // block list and associated options. This may include // defining any relative macros based on relative placement // constraints. // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 01/15/13 jeffr : Original //===========================================================================// bool TRP_RelativePlaceHandler_c::Configure( bool placeOptions_rotateEnable, // See Toro's placement options size_t placeOptions_maxPlaceRetryCt, // " size_t placeOptions_maxMacroRetryCt, // " const TPO_InstList_t& toro_circuitBlockList ) // Defined by Toro's block list { bool ok = true; // Start by caching placement options and VPR data (for later reference) this->placeOptions_.rotateEnable = placeOptions_rotateEnable; this->placeOptions_.maxPlaceRetryCt = placeOptions_maxPlaceRetryCt; this->placeOptions_.maxMacroRetryCt = placeOptions_maxMacroRetryCt; // Continue by setting relative block and macro list estimated capacities int toro_circuitBlockCount = static_cast<int>( toro_circuitBlockList.GetLength( )); this->relativeMacroList_.SetCapacity( toro_circuitBlockCount ); this->relativeBlockList_.SetCapacity( toro_circuitBlockCount ); // Initialize the local relative block list based on Toro's block list for( size_t i = 0; i < toro_circuitBlockList.GetLength( ); ++i ) { const TPO_Inst_c& toro_circuitBlock = *toro_circuitBlockList[i]; const char* pszBlockName = toro_circuitBlock.GetName( ); TRP_RelativeBlock_c relativeBlock( pszBlockName ); this->relativeBlockList_.Add( relativeBlock ); } // Update the local relative block list based on Toro's block list // (specifically, update based on any relative placement constraints) for( size_t i = 0; i < toro_circuitBlockList.GetLength( ); ++i ) { const TPO_Inst_c& toro_circuitBlock = *toro_circuitBlockList[i]; const TPO_RelativeList_t& placeRelativeList = toro_circuitBlock.GetPlaceRelativeList( ); if( !placeRelativeList.IsValid( )) continue; const char* pszFromBlockName = toro_circuitBlock.GetName( ); for( size_t j = 0; j < placeRelativeList.GetLength( ); ++j ) { const TPO_Relative_t& placeRelative = *placeRelativeList[j]; const char* pszToBlockName = placeRelative.GetName( ); TC_SideMode_t side = placeRelative.GetSide( ); // Add a new relative placement side constraint // (by default, this also includes appropriate validation) ok = this->AddSideConstraint_( pszFromBlockName, pszToBlockName, side ); if( !ok ) break; } if( !ok ) break; } return( ok ); } //===========================================================================// // Method : Reset // Description : Resets the relative place handler in order to clear any // existing placement information in VPR's grid array, the // local relative macro list, and local relative block list. // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 01/15/13 jeffr : Original //===========================================================================// bool TRP_RelativePlaceHandler_c::Reset( t_grid_tile** vpr_gridArray, int vpr_nx, int vpr_ny, t_block* vpr_blockArray, int vpr_blockCount, const t_type_descriptor* vpr_typeArray, int vpr_typeCount, int* vpr_freeLocationArray, t_legal_pos** vpr_legalPosArray ) { bool ok = true; // Set local reference to VPR's grid array, then reset placement information this->vpr_.gridArray = vpr_gridArray; this->vpr_.nx = vpr_nx; this->vpr_.ny = vpr_ny; this->vpr_.blockArray = vpr_blockArray; this->vpr_.blockCount = vpr_blockCount; this->vpr_.typeArray = const_cast< t_type_descriptor* >( vpr_typeArray ); this->vpr_.typeCount = vpr_typeCount; this->vpr_.freeLocationArray = vpr_freeLocationArray; this->vpr_.legalPosArray = vpr_legalPosArray; this->ResetVPR_Placement_( this->vpr_.gridArray, this->vpr_.nx, this->vpr_.ny, this->vpr_.blockArray, this->vpr_.blockCount, this->vpr_.typeCount, this->vpr_.freeLocationArray, this->vpr_.legalPosArray, &this->vpr_.pfreeLocationArray, &this->vpr_.plegalPosArray ); // Reset placement and type information for relative macro and block lists ok = this->ResetRelativeBlockList_( this->vpr_.blockArray, this->vpr_.blockCount, &this->relativeBlockList_ ); if( ok ) { this->ResetRelativeMacroList_( this->relativeBlockList_, &this->relativeMacroList_ ); } return( ok ); } //===========================================================================// // Method : InitialPlace // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 01/15/13 jeffr : Original //===========================================================================// bool TRP_RelativePlaceHandler_c::InitialPlace( t_grid_tile** vpr_gridArray, int vpr_nx, int vpr_ny, t_block* vpr_blockArray, int vpr_blockCount, const t_type_descriptor* vpr_typeArray, int vpr_typeCount, int* vpr_freeLocationArray, t_legal_pos** vpr_legalPosArray ) { bool ok = true; // At least one relative placement constraint has been defined bool placedAllMacros = true; // Define how many times we can retry when searching for initial placement size_t maxPlaceCt = this->placeOptions_.maxPlaceRetryCt; size_t tryPlaceCt = 0; while( tryPlaceCt < maxPlaceCt ) { // Reset VPR grid array, and relative macro and block lists, then try place ok = this->Reset( vpr_gridArray, vpr_nx, vpr_ny, vpr_blockArray, vpr_blockCount, vpr_typeArray, vpr_typeCount, vpr_freeLocationArray, vpr_legalPosArray ); if( !ok ) break; ok = this->InitialPlaceMacros_( &placedAllMacros ); if( !ok ) break; if( placedAllMacros ) break; ++tryPlaceCt; if( tryPlaceCt < maxPlaceCt ) { TIO_PrintHandler_c& printHandler = TIO_PrintHandler_c::GetInstance( ); printHandler.Info( "Retrying initial relative macro placement, attempt %d of %d...\n", tryPlaceCt, maxPlaceCt ); } } if( !placedAllMacros ) // Failed to comply - the Force is weak here { ok = this->Reset( vpr_gridArray, vpr_nx, vpr_ny, vpr_blockArray, vpr_blockCount, vpr_typeArray, vpr_typeCount, vpr_freeLocationArray, vpr_legalPosArray ); TIO_PrintHandler_c& printHandler = TIO_PrintHandler_c::GetInstance( ); ok = printHandler.Error( "Failed to find initial placement based on given relative placement constraints.\n" ); } return( ok ); } //===========================================================================// // Method : Place // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 01/15/13 jeffr : Original //===========================================================================// bool TRP_RelativePlaceHandler_c::Place( int x1, int y1, int z1, int x2, int y2, int z2, t_pl_blocks_to_be_moved& vpr_blocksAffected ) { TGO_Point_c fromPoint( x1, y1, z1 ); TGO_Point_c toPoint( x2, y2, z2 ); return( this->Place( fromPoint, toPoint, vpr_blocksAffected )); } //===========================================================================// bool TRP_RelativePlaceHandler_c::Place( const TGO_Point_c& fromPoint, const TGO_Point_c& toPoint, t_pl_blocks_to_be_moved& vpr_blocksAffected ) { bool ok = true; if( this->PlaceMacroIsRelativeCoord_( fromPoint ) || this->PlaceMacroIsRelativeCoord_( toPoint )) { // Reset relative macros based on latest VPR block placement coordinates // (which may no longer match if the most recent macro move was rejected) this->PlaceResetMacros_( ); // Search for valid relative move list based on "from" and "to" grid points TRP_RelativeMoveList_t relativeMoveList; ok = this->PlaceSwapMacros_( fromPoint, toPoint, &relativeMoveList ); if( ok ) { // Load VPR's "blocks_affected" array based on relative move list for( size_t i = 0; i < relativeMoveList.GetLength( ); ++i ) { const TRP_RelativeMove_c& relativeMove = *relativeMoveList[i]; this->PlaceSwapUpdate_( relativeMove, vpr_blocksAffected ); } } } return( ok ); } //===========================================================================// // Method : IsCandidate // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 01/15/13 jeffr : Original //===========================================================================// bool TRP_RelativePlaceHandler_c::IsCandidate( int x1, int y1, int z1, int x2, int y2, int z2 ) const { TGO_Point_c fromPoint( x1, y1, z1 ); TGO_Point_c toPoint( x2, y2, z2 ); return( this->IsCandidate( fromPoint, toPoint )); } //===========================================================================// bool TRP_RelativePlaceHandler_c::IsCandidate( const TGO_Point_c& fromPoint, const TGO_Point_c& toPoint ) const { return( this->PlaceMacroIsRelativeCoord_( fromPoint ) || this->PlaceMacroIsRelativeCoord_( toPoint ) ? true : false ); } //===========================================================================// // Method : IsValid // Description : Returns TRUE if at least one relative macro exists // (ie. at least one placement constraint has been defined). // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 01/15/13 jeffr : Original //===========================================================================// bool TRP_RelativePlaceHandler_c::IsValid( void ) const { return( this->relativeMacroList_.IsValid( ) ? true : false ); } //===========================================================================// // Method : AddSideConstraint_ // Description : Adds a new relative placement constraint based on the // given "from"|"to" names and side. // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 01/15/13 jeffr : Original //===========================================================================// bool TRP_RelativePlaceHandler_c::AddSideConstraint_( const char* pszFromBlockName, const char* pszToBlockName, TC_SideMode_t side, size_t relativeMacroIndex ) { bool ok = true; // Look up "from" and "to" relative macro indices based on given block names TRP_RelativeBlock_c* pfromBlock = this->relativeBlockList_.Find( pszFromBlockName ); TRP_RelativeBlock_c* ptoBlock = this->relativeBlockList_.Find( pszToBlockName ); if( pfromBlock && ptoBlock ) { ok = this->AddSideConstraint_( pfromBlock, ptoBlock, side, relativeMacroIndex ); } else { if( !pfromBlock ) { ok = this->ShowMissingBlockNameError_( pszFromBlockName ); } if( !ptoBlock ) { ok = this->ShowMissingBlockNameError_( pszToBlockName ); } } return( ok ); } //===========================================================================// bool TRP_RelativePlaceHandler_c::AddSideConstraint_( TRP_RelativeBlock_c* pfromBlock, TRP_RelativeBlock_c* ptoBlock, TC_SideMode_t side, size_t relativeMacroIndex ) { bool ok = true; TC_SideMode_t antiSide = this->DecideAntiSide_( side ); if( !pfromBlock->HasRelativeMacroIndex( ) && !ptoBlock->HasRelativeMacroIndex( )) { // No relative macros are currently asso. with either "from" or "to" block // Add new relative macro, along with asso. "from" and "to" relative nodes this->NewSideConstraint_( pfromBlock, ptoBlock, side, relativeMacroIndex ); } else if( pfromBlock->HasRelativeMacroIndex( ) && !ptoBlock->HasRelativeMacroIndex( )) { // Update existing relative macro based on "from" block, add a "to" block string srFromBlockName, srToBlockName; ok = this->ExistingSideConstraint_( *pfromBlock, ptoBlock, side, &srFromBlockName, &srToBlockName ); if( !ok ) { // Side is already in use for the existing macro "from" node, report error ok = this->ShowInvalidConstraintError_( *pfromBlock, *ptoBlock, side, srFromBlockName, srToBlockName ); } } else if( !pfromBlock->HasRelativeMacroIndex( ) && ptoBlock->HasRelativeMacroIndex( )) { // Update existing relative macro based on "to" block, add a "from" block string srToBlockName, srFromBlockName; ok = this->ExistingSideConstraint_( *ptoBlock, pfromBlock, antiSide, &srToBlockName, &srFromBlockName ); if( !ok ) { // Side is already in use for the existing macro "to" node, report error ok = this->ShowInvalidConstraintError_( *ptoBlock, *pfromBlock, antiSide, srToBlockName, srFromBlockName ); } } else if( pfromBlock->HasRelativeMacroIndex( ) && ptoBlock->HasRelativeMacroIndex( )) { if( pfromBlock->GetRelativeMacroIndex( ) == ptoBlock->GetRelativeMacroIndex( )) { // Same macro index => "from" and "to" blocks are from same relative macro // Verify side constraint is "existing" wrt. "from" and "to" relative nodes string srFromBlockName, srToBlockName; if( this->HasExistingSideConstraint_( *pfromBlock, *ptoBlock, side, &srFromBlockName, &srToBlockName )) { // Move along, nothing to see here (given relative constraint is redundant) } else { ok = this->ShowInvalidConstraintError_( *pfromBlock, *ptoBlock, side, srFromBlockName, srToBlockName ); } } else { // Diff macro index => "from" and "to" blocks are from different relative macros // Verify side constraint is "available" wrt. "from" and "to" relative nodes bool fromAvailable = true; bool toAvailable = true; string srFromBlockName, srToBlockName; if( this->IsAvailableSideConstraint_( *pfromBlock, *ptoBlock, side, &fromAvailable, &toAvailable, &srFromBlockName, &srToBlockName )) { // Merge the "from" and "to" relative macros based on common side constraint ok = this->MergeSideConstraints_( pfromBlock, ptoBlock, side ); } else { if( !fromAvailable ) { ok = this->ShowInvalidConstraintError_( *pfromBlock, *ptoBlock, antiSide, srFromBlockName, srToBlockName ); } if( !toAvailable ) { ok = this->ShowInvalidConstraintError_( *ptoBlock, *pfromBlock, antiSide, srToBlockName, srFromBlockName ); } } } } return( ok ); } //===========================================================================// // Method : NewSideConstraint_ // Description : Add a new relative macro, along with the associated // "from" and "to" relative nodes, based on the given side // constraint. // // Note: This method assumes no relative macros are already // associated with either the "from" or "to" relative // blocks. // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 01/15/13 jeffr : Original //===========================================================================// void TRP_RelativePlaceHandler_c::NewSideConstraint_( TRP_RelativeBlock_c* pfromBlock, TRP_RelativeBlock_c* ptoBlock, TC_SideMode_t side, size_t relativeMacroIndex ) { // First, add new relative macro (or use existing, per optional parameter) if( relativeMacroIndex == TRP_RELATIVE_MACRO_UNDEFINED ) { relativeMacroIndex = this->relativeMacroList_.GetLength( ); TRP_RelativeMacro_c relativeMacro; this->relativeMacroList_.Add( relativeMacro ); } TRP_RelativeMacro_c* prelativeMacro = this->relativeMacroList_[relativeMacroIndex]; // Next, add new relative nodes based on given block names and side const char* pszFromBlockName = pfromBlock->GetName( ); const char* pszToBlockName = ptoBlock->GetName( ); size_t fromNodeIndex = TRP_RELATIVE_NODE_UNDEFINED; size_t toNodeIndex = TRP_RELATIVE_NODE_UNDEFINED; prelativeMacro->Add( pszFromBlockName, pszToBlockName, side, &fromNodeIndex, &toNodeIndex ); // Finally, update relative block macro and node indices pfromBlock->SetRelativeMacroIndex( relativeMacroIndex ); pfromBlock->SetRelativeNodeIndex( fromNodeIndex ); ptoBlock->SetRelativeMacroIndex( relativeMacroIndex ); ptoBlock->SetRelativeNodeIndex( toNodeIndex ); } //===========================================================================// void TRP_RelativePlaceHandler_c::NewSideConstraint_( const TRP_RelativeBlock_c& fromBlock, const TRP_RelativeBlock_c& toBlock, TC_SideMode_t side ) { size_t relativeMacroIndex = fromBlock.GetRelativeMacroIndex( ); size_t fromNodeIndex = fromBlock.GetRelativeNodeIndex( ); size_t toNodeIndex = toBlock.GetRelativeNodeIndex( ); // First, find existing relative macro TRP_RelativeMacro_c* prelativeMacro = this->relativeMacroList_[relativeMacroIndex]; // Next, add new relative nodes based on given block names and side prelativeMacro->Add( fromNodeIndex, toNodeIndex, side ); } //===========================================================================// // Method : MergeSideConstraints_ // Description : Merge the "from" and "to" relative macros based on a // common side constraint. // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 01/15/13 jeffr : Original //===========================================================================// bool TRP_RelativePlaceHandler_c::MergeSideConstraints_( TRP_RelativeBlock_c* pfromBlock, TRP_RelativeBlock_c* ptoBlock, TC_SideMode_t side ) { bool ok = true; size_t fromMacroIndex = pfromBlock->GetRelativeMacroIndex( ); size_t toMacroIndex = ptoBlock->GetRelativeMacroIndex( ); TRP_RelativeMacro_c& toMacro = *this->relativeMacroList_[toMacroIndex]; // Start by clearing all block indices asso. with existing "to" relative macro for( size_t i = 0; i < toMacro.GetLength( ); ++i ) { const TRP_RelativeNode_c& toNode = *toMacro[i]; const char* pszToBlockName = toNode.GetBlockName( ); TRP_RelativeBlock_c* ptoBlock_ = this->relativeBlockList_.Find( pszToBlockName ); ptoBlock_->Reset( ); } // Then, iterate the "to" relative macro... // Recursively add side constraints to existing "from" relative macro for( size_t i = 0; i < toMacro.GetLength( ); ++i ) { const TRP_RelativeNode_c& toNode = *toMacro[i]; // Apply merge to each possible node side this->MergeSideConstraints_( fromMacroIndex, toMacro, toNode, TC_SIDE_LEFT ); this->MergeSideConstraints_( fromMacroIndex, toMacro, toNode, TC_SIDE_RIGHT ); this->MergeSideConstraints_( fromMacroIndex, toMacro, toNode, TC_SIDE_LOWER ); this->MergeSideConstraints_( fromMacroIndex, toMacro, toNode, TC_SIDE_UPPER ); } // And, add common "from->to" side constraint in existing "from" relative macro this->NewSideConstraint_( *pfromBlock, *ptoBlock, side ); // All done with the original "to" relative macro... // but need to leave an empty macro in the list to avoid having to // re-index all existing relative block index references toMacro.Clear( ); return( ok ); } //===========================================================================// bool TRP_RelativePlaceHandler_c::MergeSideConstraints_( size_t fromMacroIndex, const TRP_RelativeMacro_c& toMacro, const TRP_RelativeNode_c& toNode, TC_SideMode_t side ) { bool ok = true; if( toNode.HasSideIndex( side )) { const char* pszToBlockName = toNode.GetBlockName( ); size_t neighborNodeIndex = toNode.GetSideIndex( side ); const TRP_RelativeNode_c& neighborNode = *toMacro[neighborNodeIndex]; const char* pszNeighborBlockName = neighborNode.GetBlockName( ); ok = this->AddSideConstraint_( pszToBlockName, pszNeighborBlockName, side, fromMacroIndex ); } return( ok ); } //===========================================================================// // Method : ExistingSideConstraint_ // Description : Update an existing relative macro and "from" relative // node with a new "to" relative node, based on the given // side constraint. // // Note: This method assumes a relative macro is currently // associated with the "from" relative block. // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 01/15/13 jeffr : Original //===========================================================================// bool TRP_RelativePlaceHandler_c::ExistingSideConstraint_( const TRP_RelativeBlock_c& fromBlock, TRP_RelativeBlock_c* ptoBlock, TC_SideMode_t side, string* psrFromBlockName, string* psrToBlockName ) { bool ok = true; // Find existing relative macro and node based on "from" block's indices size_t relativeMacroIndex = fromBlock.GetRelativeMacroIndex( ); size_t fromNodeIndex = fromBlock.GetRelativeNodeIndex( ); TRP_RelativeMacro_c* prelativeMacro = this->relativeMacroList_[relativeMacroIndex]; const TRP_RelativeNode_c& fromNode = *prelativeMacro->Find( fromNodeIndex ); if( !fromNode.HasSideIndex( side )) { // Side is available on existing macro "from" node, now add a "to" node // Add new "to" relative node const char* pszToBlockName = ptoBlock->GetName( ); size_t toNodeIndex = TRP_RELATIVE_NODE_UNDEFINED; prelativeMacro->Add( fromNodeIndex, pszToBlockName, side, &toNodeIndex ); // And, update relative block macro and node indices ptoBlock->SetRelativeMacroIndex( relativeMacroIndex ); ptoBlock->SetRelativeNodeIndex( toNodeIndex ); } else { // Side is already in use for existing macro "from" node, return error ok = false; } if( psrFromBlockName ) { *psrFromBlockName = fromBlock.GetBlockName( ); } if( psrToBlockName ) { size_t toNodeIndex = fromNode.GetSideIndex( side ); const TRP_RelativeNode_c* ptoNode = prelativeMacro->Find( toNodeIndex ); *psrToBlockName = ( ptoNode ? ptoNode->GetBlockName( ) : "" ); } return( ok ); } //===========================================================================// // Method : HasExistingSideConstraint_ // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 01/15/13 jeffr : Original //===========================================================================// bool TRP_RelativePlaceHandler_c::HasExistingSideConstraint_( const TRP_RelativeBlock_c& fromBlock, const TRP_RelativeBlock_c& toBlock, TC_SideMode_t side, string* psrFromBlockName, string* psrToBlockName ) const { bool isExisting = false; size_t fromMacroIndex = fromBlock.GetRelativeMacroIndex( ); size_t fromNodeIndex = fromBlock.GetRelativeNodeIndex( ); size_t toMacroIndex = toBlock.GetRelativeMacroIndex( ); size_t toNodeIndex = toBlock.GetRelativeNodeIndex( ); if(( fromMacroIndex != TRP_RELATIVE_MACRO_UNDEFINED ) && ( toMacroIndex != TRP_RELATIVE_MACRO_UNDEFINED )) { if(( fromMacroIndex == toMacroIndex ) && ( fromNodeIndex != toNodeIndex )) { const TRP_RelativeMacro_c& relativeMacro = *this->relativeMacroList_[fromMacroIndex]; const TRP_RelativeNode_c& fromNode = *relativeMacro[fromNodeIndex]; const TRP_RelativeNode_c& toNode = *relativeMacro[toNodeIndex]; TC_SideMode_t antiSide = this->DecideAntiSide_( side ); if(( fromNode.GetSideIndex( side ) == toNodeIndex ) && ( toNode.GetSideIndex( antiSide ) == fromNodeIndex )) { isExisting = true; } if( psrFromBlockName ) { fromNodeIndex = ( toNode.HasSideIndex( side ) ? toNode.GetSideIndex( side ) : fromNodeIndex ); const TRP_RelativeNode_c* pfromNode = relativeMacro[fromNodeIndex]; *psrFromBlockName = ( pfromNode ? pfromNode->GetBlockName( ) : "" ); } if( psrToBlockName ) { toNodeIndex = ( fromNode.HasSideIndex( antiSide ) ? fromNode.GetSideIndex( antiSide ) : toNodeIndex ); const TRP_RelativeNode_c* ptoNode = relativeMacro[toNodeIndex]; *psrToBlockName = ( ptoNode ? ptoNode->GetBlockName( ) : "" ); } } } return( isExisting ); } //===========================================================================// // Method : IsAvailableSideConstraint_ // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 01/15/13 jeffr : Original //===========================================================================// bool TRP_RelativePlaceHandler_c::IsAvailableSideConstraint_( const TRP_RelativeBlock_c& fromBlock, const TRP_RelativeBlock_c& toBlock, TC_SideMode_t side, bool* pfromAvailable, bool* ptoAvailable, string* psrFromBlockName, string* psrToBlockName ) const { bool isAvailable = false; size_t fromMacroIndex = fromBlock.GetRelativeMacroIndex( ); size_t fromNodeIndex = fromBlock.GetRelativeNodeIndex( ); size_t toMacroIndex = toBlock.GetRelativeMacroIndex( ); size_t toNodeIndex = toBlock.GetRelativeNodeIndex( ); if(( fromMacroIndex != TRP_RELATIVE_MACRO_UNDEFINED ) && ( toMacroIndex != TRP_RELATIVE_MACRO_UNDEFINED )) { if( fromMacroIndex != toMacroIndex ) { const TRP_RelativeMacro_c& fromMacro = *this->relativeMacroList_[fromMacroIndex]; const TRP_RelativeMacro_c& toMacro = *this->relativeMacroList_[toMacroIndex]; const TRP_RelativeNode_c& fromNode = *fromMacro[fromNodeIndex]; const TRP_RelativeNode_c& toNode = *toMacro[toNodeIndex]; TC_SideMode_t antiSide = this->DecideAntiSide_( side ); if(( fromNode.GetSideIndex( side ) == TRP_RELATIVE_NODE_UNDEFINED ) && ( toNode.GetSideIndex( antiSide ) == TRP_RELATIVE_NODE_UNDEFINED )) { isAvailable = true; } if( pfromAvailable ) { *pfromAvailable = ( fromNode.GetSideIndex( side ) == TRP_RELATIVE_NODE_UNDEFINED ? true : false ); } if( ptoAvailable ) { *ptoAvailable = ( toNode.GetSideIndex( side ) == TRP_RELATIVE_NODE_UNDEFINED ? true : false ); } if( psrFromBlockName ) { fromNodeIndex = toNode.GetSideIndex( antiSide ); const TRP_RelativeNode_c* pfromNode = fromMacro.Find( fromNodeIndex ); *psrFromBlockName = ( pfromNode ? pfromNode->GetBlockName( ) : "" ); } if( psrToBlockName ) { toNodeIndex = fromNode.GetSideIndex( side ); const TRP_RelativeNode_c* ptoNode = toMacro.Find( toNodeIndex ); *psrToBlockName = ( ptoNode ? ptoNode->GetBlockName( ) : "" ); } } } return( isAvailable ); } //===========================================================================// // Method : SetVPR_Placement_ // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 01/15/13 jeffr : Original //===========================================================================// void TRP_RelativePlaceHandler_c::SetVPR_Placement_( const TRP_RelativeMacro_c& relativeMacro, const TRP_RelativeBlockList_t& relativeBlockList, t_grid_tile** vpr_gridArray, t_block* vpr_blockArray ) { for( size_t i = 0; i < relativeMacro.GetLength( ); ++i ) { const TRP_RelativeNode_c& relativeNode = *relativeMacro[i]; const TGO_Point_c& vpr_gridPoint = relativeNode.GetVPR_GridPoint( ); const char* pszBlockName = relativeNode.GetBlockName( ); const TRP_RelativeBlock_c& relativeBlock = *relativeBlockList.Find( pszBlockName ); int vpr_blockIndex = relativeBlock.GetVPR_Index( ); int x = vpr_gridPoint.x; int y = vpr_gridPoint.y; int z = vpr_gridPoint.z; vpr_gridArray[x][y].blocks[z] = vpr_blockIndex; vpr_gridArray[x][y].usage++; vpr_blockArray[vpr_blockIndex].x = x; vpr_blockArray[vpr_blockIndex].y = y; vpr_blockArray[vpr_blockIndex].z = z; } } //===========================================================================// // Method : ResetVPR_Placement_ // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 01/15/13 jeffr : Original //===========================================================================// void TRP_RelativePlaceHandler_c::ResetVPR_Placement_( t_grid_tile** vpr_gridArray, int vpr_nx, int vpr_ny, t_block* vpr_blockArray, int vpr_blockCount, int vpr_typeCount, int* vpr_freeLocationArray, t_legal_pos** vpr_legalPosArray, int** pvpr_freeLocationArray, t_legal_pos*** pvpr_legalPosArray ) { // For reference, see place.c - initial_placement() code snippet... for( int x = 0; x <= vpr_nx + 1; ++x ) { for( int y = 0; y <= vpr_ny + 1; ++y ) { if( !vpr_gridArray[x][y].type ) continue; for( int z = 0; z < vpr_gridArray[x][y].type->capacity; ++z ) { vpr_gridArray[x][y].blocks[z] = EMPTY; } vpr_gridArray[x][y].usage = 0; } } for( int blockIndex = 0; blockIndex < vpr_blockCount; ++blockIndex ) { vpr_blockArray[blockIndex].x = EMPTY; vpr_blockArray[blockIndex].y = EMPTY; vpr_blockArray[blockIndex].z = EMPTY; } if( !*pvpr_freeLocationArray ) { *pvpr_freeLocationArray = static_cast< int* >( TC_calloc( vpr_typeCount, sizeof(int))); for( int typeIndex = 0; typeIndex <= vpr_typeCount; ++typeIndex ) { (*pvpr_freeLocationArray)[typeIndex] = vpr_freeLocationArray[typeIndex]; } } for( int typeIndex = 0; typeIndex <= vpr_typeCount; ++typeIndex ) { vpr_freeLocationArray[typeIndex] = (*pvpr_freeLocationArray)[typeIndex]; } if( !*pvpr_legalPosArray ) { *pvpr_legalPosArray = static_cast< t_legal_pos** >( TC_calloc( vpr_typeCount, sizeof(t_legal_pos*))); for( int typeIndex = 0; typeIndex < vpr_typeCount; ++typeIndex ) { int freeCount = vpr_freeLocationArray[typeIndex]; (*pvpr_legalPosArray)[typeIndex] = static_cast< t_legal_pos* >( TC_calloc( freeCount, sizeof(t_legal_pos))); for( int freeIndex = 0; freeIndex < vpr_freeLocationArray[typeIndex]; ++freeIndex ) { (*pvpr_legalPosArray)[typeIndex][freeIndex].x = vpr_legalPosArray[typeIndex][freeIndex].x; (*pvpr_legalPosArray)[typeIndex][freeIndex].y = vpr_legalPosArray[typeIndex][freeIndex].y; (*pvpr_legalPosArray)[typeIndex][freeIndex].z = vpr_legalPosArray[typeIndex][freeIndex].z; } } } for( int typeIndex = 0; typeIndex <= vpr_typeCount; ++typeIndex ) { for( int freeIndex = 0; freeIndex < vpr_freeLocationArray[typeIndex]; ++freeIndex ) { vpr_legalPosArray[typeIndex][freeIndex].x = (*pvpr_legalPosArray)[typeIndex][freeIndex].x; vpr_legalPosArray[typeIndex][freeIndex].y = (*pvpr_legalPosArray)[typeIndex][freeIndex].y; vpr_legalPosArray[typeIndex][freeIndex].z = (*pvpr_legalPosArray)[typeIndex][freeIndex].z; } } } //===========================================================================// // Method : ResetRelativeMacroList_ // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 01/15/13 jeffr : Original //===========================================================================// void TRP_RelativePlaceHandler_c::ResetRelativeMacroList_( const TRP_RelativeBlockList_t& relativeBlockList, TRP_RelativeMacroList_t* prelativeMacroList ) { // Reset all macro node 'vpr_type' fields based on relative block list for( size_t i = 0; i < prelativeMacroList->GetLength( ); ++i ) { TRP_RelativeMacro_c* prelativeMacro = (*prelativeMacroList)[i]; for( size_t j = 0; j < prelativeMacro->GetLength( ); ++j ) { TRP_RelativeNode_c* prelativeNode = (*prelativeMacro)[j]; TGO_Point_c vpr_gridPoint; prelativeNode->SetVPR_GridPoint( vpr_gridPoint ); const char* pszBlockName = prelativeNode->GetBlockName( ); const TRP_RelativeBlock_c* prelativeBlock = relativeBlockList.Find( pszBlockName ); if( !prelativeBlock ) continue; const t_type_descriptor* vpr_type = prelativeBlock->GetVPR_Type( ); prelativeNode->SetVPR_Type( vpr_type ); } } } //===========================================================================// // Method : ResetRelativeBlockList_ // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 01/15/13 jeffr : Original //===========================================================================// bool TRP_RelativePlaceHandler_c::ResetRelativeBlockList_( t_block* vpr_blockArray, int vpr_blockCount, TRP_RelativeBlockList_t* prelativeBlockList ) { bool ok = true; // Initialize relative block list based on given VPR block array types for( int blockIndex = 0; blockIndex < vpr_blockCount; ++blockIndex ) { const char* pszBlockName = vpr_blockArray[blockIndex].name; TRP_RelativeBlock_c* prelativeBlock = prelativeBlockList->Find( pszBlockName ); if( !prelativeBlock ) continue; int vpr_index = blockIndex; prelativeBlock->SetVPR_Index( vpr_index ); const t_type_descriptor* vpr_type = vpr_blockArray[blockIndex].type; prelativeBlock->SetVPR_Type( vpr_type ); } // Validate relative block list based on local VPR block name list TRP_RelativeBlockList_t vpr_blockList( vpr_blockCount ); for( int blockIndex = 0; blockIndex < vpr_blockCount; ++blockIndex ) { const char* pszBlockName = vpr_blockArray[blockIndex].name; vpr_blockList.Add( pszBlockName ); } for( size_t i = 0; i < prelativeBlockList->GetLength( ); ++i ) { const TRP_RelativeBlock_c& relativeBlock = *(*prelativeBlockList)[i]; const char* pszBlockName = relativeBlock.GetBlockName( ); if( !vpr_blockList.IsMember( pszBlockName )) { ok = this->ShowMissingBlockNameError_( pszBlockName ); if( !ok ) break; } } return( ok ); } //===========================================================================// // Method : InitialPlaceMacros_ // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 01/15/13 jeffr : Original //===========================================================================// bool TRP_RelativePlaceHandler_c::InitialPlaceMacros_( bool* pplacedAllMacros ) { bool ok = true; bool foundAllPlacements = true; for( size_t i = 0; i < this->relativeMacroList_.GetLength( ); ++i ) { TRP_RelativeMacro_c* prelativeMacro = this->relativeMacroList_[i]; // Reset (ie. clear) and existing macro placement coords this->InitialPlaceMacroResetCoords_( ); // Define how many times we can retry when searching for an initial placement size_t maxMacroCt = this->placeOptions_.maxMacroRetryCt * prelativeMacro->GetLength( ); size_t tryMacroCt = 0; while( tryMacroCt < maxMacroCt ) { bool validPlacement = false; bool triedPlacement = false; bool foundPlacement = false; ok = this->InitialPlaceMacroNodes_( prelativeMacro, &validPlacement, &triedPlacement, &foundPlacement ); if( !ok ) break; foundAllPlacements = validPlacement; if( !validPlacement ) break; if( !triedPlacement ) continue; if( foundPlacement ) break; ++tryMacroCt; if( tryMacroCt < maxMacroCt ) { TIO_PrintHandler_c& printHandler = TIO_PrintHandler_c::GetInstance( ); printHandler.Info( "Retrying relative macro placement, attempt %d of %d...\n", tryMacroCt, maxMacroCt ); } } if( tryMacroCt > maxMacroCt ) { foundAllPlacements = false; } if( !foundAllPlacements ) break; } if( !foundAllPlacements ) // Failed to place at least one of the relative macros { TIO_PrintHandler_c& printHandler = TIO_PrintHandler_c::GetInstance( ); ok = printHandler.Warning( "Failed initial relative placement based on given relative placement constraints.\n" ); } if( *pplacedAllMacros ) { *pplacedAllMacros = foundAllPlacements; } return( ok ); } //===========================================================================// // Method : InitialPlaceMacroNodes_ // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 01/15/13 jeffr : Original //===========================================================================// bool TRP_RelativePlaceHandler_c::InitialPlaceMacroNodes_( TRP_RelativeMacro_c* prelativeMacro, bool* pvalidPlacement, bool* ptriedPlacement, bool* pfoundPlacement ) { bool ok = true; *pvalidPlacement = false; *ptriedPlacement = false; *pfoundPlacement = false; // Select a random relative node index based on relative macro length size_t relativeNodeIndex = this->FindRandomRelativeNodeIndex_( *prelativeMacro ); // Select a random (and available) point from within VPR's grid array TGO_Point_c origin = this->FindRandomOriginPoint_( *prelativeMacro, relativeNodeIndex ); // Select a random rotate mode (if enabled) TGO_RotateMode_t rotate = this->FindRandomRotateMode_( ); // Test if we already tried this combination of node, origin, and rotate if( origin.IsValid( ) && this->InitialPlaceMacroIsLegal_( relativeNodeIndex, origin, rotate )) { *pvalidPlacement = true; *ptriedPlacement = true; if( this->InitialPlaceMacroIsOpen_( *prelativeMacro, relativeNodeIndex, origin, rotate )) { // Accept current relative placement node, origin, and rotate prelativeMacro->Set( relativeNodeIndex, origin, rotate ); // And, update VPR's grid and block arrays based on relative macro this->SetVPR_Placement_( *prelativeMacro, this->relativeBlockList_, this->vpr_.gridArray, this->vpr_.blockArray ); *pfoundPlacement = true; } else { const TRP_RelativeNode_c& relativeNode = *prelativeMacro->Find( relativeNodeIndex ); const char* pszBlockName = relativeNode.GetBlockName( ); string srOrigin; origin.ExtractString( &srOrigin ); string srRotate; TGO_ExtractStringRotateMode( rotate, &srRotate ); TIO_PrintHandler_c& printHandler = TIO_PrintHandler_c::GetInstance( ); ok = printHandler.Warning( "Failed relative macro placement based on reference block \"%s\" at origin (%s) and rotate %s.\n", TIO_PSZ_STR( pszBlockName ), TIO_SR_STR( srOrigin ), TIO_SR_STR( srRotate )); } } else if( origin.IsValid( )) { *pvalidPlacement = true; } return( ok ); } //===========================================================================// // Method : InitialPlaceMacroResetCoords_ // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 01/15/13 jeffr : Original //===========================================================================// void TRP_RelativePlaceHandler_c::InitialPlaceMacroResetCoords_( void ) { TRP_RotateMaskHash_t* protateMaskHash = &this->initialPlaceMacroCoords_; protateMaskHash->Clear( ); } //===========================================================================// // Method : InitialPlaceMacroIsLegal_ // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 01/15/13 jeffr : Original //===========================================================================// bool TRP_RelativePlaceHandler_c::InitialPlaceMacroIsLegal_( size_t relativeNodeIndex, const TGO_Point_c& origin, TGO_RotateMode_t rotate ) const { bool isLegal = true; TRP_RotateMaskHash_t* protateMaskHash = const_cast< TRP_RotateMaskHash_t* >( &this->initialPlaceMacroCoords_ ); TRP_RotateMaskKey_c rotateMaskKey( origin, relativeNodeIndex ); TRP_RotateMaskValue_c* protateMaskValue; if( protateMaskHash->Find( rotateMaskKey, &protateMaskValue ) && !protateMaskValue->GetBit( rotate )) { isLegal = false; } else { isLegal = true; if( !protateMaskHash->IsMember( rotateMaskKey )) { TRP_RotateMaskValue_c rotateMaskValue( this->placeOptions_.rotateEnable ); protateMaskHash->Add( rotateMaskKey, rotateMaskValue ); protateMaskHash->Find( rotateMaskKey, &protateMaskValue ); } protateMaskValue->ClearBit( rotate ); } return( isLegal ); } //===========================================================================// // Method : InitialPlaceMacroIsOpen_ // Description : Returns TRUE if the given relative macro placement origin // point and associated transform is open, as determined by // the current state of VPR's grid array. // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 01/15/13 jeffr : Original //===========================================================================// bool TRP_RelativePlaceHandler_c::InitialPlaceMacroIsOpen_( const TRP_RelativeMacro_c& relativeMacro, size_t relativeNodeIndex, const TGO_Point_c& origin, TGO_RotateMode_t rotate ) const { bool isOpen = false; TRP_RelativeMacro_c relativeMacro_( relativeMacro ); relativeMacro_.Set( relativeNodeIndex, origin, rotate ); for( size_t i = 0; i < relativeMacro_.GetLength( ); ++i ) { const TRP_RelativeNode_c& relativeNode = *relativeMacro_[i]; // Query VPR's grid array to test (1) open && (2) matching type ptr const TGO_Point_c& gridPoint = relativeNode.GetVPR_GridPoint( ); const t_type_descriptor* vpr_type = relativeNode.GetVPR_Type( ); if(( this->IsEmptyGridPoint_( gridPoint )) && ( this->FindGridPointType_( gridPoint ) == vpr_type )) { isOpen = true; continue; } else { isOpen = false; break; } } return( isOpen ); } //===========================================================================// bool TRP_RelativePlaceHandler_c::InitialPlaceMacroIsOpen_( size_t relativeMacroIndex, size_t relativeNodeIndex, const TGO_Point_c& origin, TGO_RotateMode_t rotate ) const { bool isOpen = false; const TRP_RelativeMacro_c* prelativeMacro = this->relativeMacroList_[relativeMacroIndex]; if( prelativeMacro ) { isOpen = this->InitialPlaceMacroIsOpen_( *prelativeMacro, relativeNodeIndex, origin, rotate ); } return( isOpen ); } //===========================================================================// // Method : PlaceResetMacros_ // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 01/15/13 jeffr : Original //===========================================================================// void TRP_RelativePlaceHandler_c::PlaceResetMacros_( void ) { for( size_t i = 0; i < this->relativeMacroList_.GetLength( ); ++i ) { TRP_RelativeMacro_c* prelativeMacro = this->relativeMacroList_[i]; for( size_t j = 0; j < prelativeMacro->GetLength( ); ++j ) { TRP_RelativeNode_c* prelativeNode = (*prelativeMacro)[j]; const char* pszBlockName = prelativeNode->GetBlockName( ); const TRP_RelativeBlock_c& relativeBlock = *this->relativeBlockList_.Find( pszBlockName ); int vpr_index = relativeBlock.GetVPR_Index( ); TGO_Point_c vpr_gridPoint( this->vpr_.blockArray[vpr_index].x, this->vpr_.blockArray[vpr_index].y, this->vpr_.blockArray[vpr_index].z ); prelativeNode->SetVPR_GridPoint( vpr_gridPoint ); } } } //===========================================================================// // Method : PlaceSwapMacros_ // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 01/15/13 jeffr : Original //===========================================================================// bool TRP_RelativePlaceHandler_c::PlaceSwapMacros_( const TGO_Point_c& fromPoint, const TGO_Point_c& toPoint, TRP_RelativeMoveList_t* prelativeMoveList ) { TRP_RelativeMoveList_t fromToMoveList; TRP_RelativeMoveList_t toFromMoveList; bool foundPlaceSwap = false; // Iterate attempt to swap "from" => "to" based available (optional) rotation this->PlaceMacroResetRotate_( TRP_PLACE_MACRO_ROTATE_TO ); while( this->PlaceMacroIsValidRotate_( TRP_PLACE_MACRO_ROTATE_TO )) { // Select a random rotate mode (if enabled) TGO_RotateMode_t toRotate = this->FindRandomRotateMode_( ); if( this->PlaceMacroIsLegalRotate_( TRP_PLACE_MACRO_ROTATE_TO, toRotate )) { fromToMoveList.Clear( ); // Query if "to" is available based on "from" origin and "to" transform // (and return list of "from->to" moves corresponding to availability) if( this->PlaceMacroIsAvailableCoord_( fromPoint, toPoint, toRotate, &fromToMoveList )) { // Iterate attempt to swap "to" => "from" based available rotation this->PlaceMacroResetRotate_( TRP_PLACE_MACRO_ROTATE_FROM ); while( this->PlaceMacroIsValidRotate_( TRP_PLACE_MACRO_ROTATE_FROM )) { // Select a random rotate mode (if enabled) TGO_RotateMode_t fromRotate = this->FindRandomRotateMode_( ); if( this->PlaceMacroIsLegalRotate_( TRP_PLACE_MACRO_ROTATE_FROM, fromRotate )) { toFromMoveList.Clear( ); // Query if "from" is available based on "to" origin and inverse // (and return list of "to->from" moves corresponding to availability) if( this->PlaceMacroIsAvailableCoord_( toPoint, fromPoint, fromRotate, &toFromMoveList ) && this->PlaceMacroIsLegalMoveList_( fromToMoveList, toFromMoveList )) { // Found swappable "from" and "to" move lists foundPlaceSwap = true; break; } } } if( foundPlaceSwap ) break; } } } if( foundPlaceSwap ) { prelativeMoveList->Add( fromToMoveList ); prelativeMoveList->Add( toFromMoveList ); this->PlaceMacroUpdateMoveList_( prelativeMoveList ); } return( foundPlaceSwap ); } //===========================================================================// // Method : PlaceSwapUpdate_ // Reference : Set VPR's setup_blocks_affected function // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 01/15/13 jeffr : Original //===========================================================================// void TRP_RelativePlaceHandler_c::PlaceSwapUpdate_( const TRP_RelativeMove_c& relativeMove, t_pl_blocks_to_be_moved& vpr_blocksAffected ) const { const TGO_Point_c& fromPoint = relativeMove.GetFromPoint( ); const TGO_Point_c& toPoint = relativeMove.GetToPoint( ); // Update relative node grid points per from/to points, as needed TRP_RelativeNode_c* pfromNode = this->FindRelativeNode_( fromPoint ); if( pfromNode ) { pfromNode->SetVPR_GridPoint( toPoint ); } TRP_RelativeNode_c* ptoNode = this->FindRelativeNode_( toPoint ); if( ptoNode ) { ptoNode->SetVPR_GridPoint( fromPoint ); } // Find VPR's global "block" array indices per from/to points int fromBlockIndex = this->FindGridPointBlockIndex_( fromPoint ); bool fromEmpty = relativeMove.GetFromEmpty( ); bool toEmpty = relativeMove.GetToEmpty( ); // Update VPR's global "block" array using locally cached reference this->vpr_.blockArray[fromBlockIndex].x = toPoint.x; this->vpr_.blockArray[fromBlockIndex].y = toPoint.y; this->vpr_.blockArray[fromBlockIndex].z = toPoint.z; // Update VPR's global "blocks_affected" array using locally passed reference int i = vpr_blocksAffected.num_moved_blocks; vpr_blocksAffected.moved_blocks[i].block_num = fromBlockIndex; vpr_blocksAffected.moved_blocks[i].xold = fromPoint.x; vpr_blocksAffected.moved_blocks[i].yold = fromPoint.y; vpr_blocksAffected.moved_blocks[i].zold = fromPoint.z; vpr_blocksAffected.moved_blocks[i].xnew = toPoint.x; vpr_blocksAffected.moved_blocks[i].ynew = toPoint.y; vpr_blocksAffected.moved_blocks[i].znew = toPoint.z; vpr_blocksAffected.moved_blocks[i].swapped_to_was_empty = toEmpty; vpr_blocksAffected.moved_blocks[i].swapped_from_is_empty = fromEmpty; vpr_blocksAffected.num_moved_blocks ++; } //===========================================================================// // Method : PlaceMacroIsRelativeCoord_ // Description : Returns TRUE if the given VPR grid array coordinate is // associated with a relative macro. // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 01/15/13 jeffr : Original //===========================================================================// bool TRP_RelativePlaceHandler_c::PlaceMacroIsRelativeCoord_( const TGO_Point_c& point ) const { bool isMacro = false; // Find relative block based on VPR's grid array point const TRP_RelativeBlock_c* prelativeBlock = this->FindRelativeBlock_( point ); // Decide if relative block has a relative macro associated with it if( prelativeBlock && prelativeBlock->HasRelativeMacroIndex( ) && prelativeBlock->HasRelativeNodeIndex( )) { isMacro = true; } return( isMacro ); } //===========================================================================// // Method : PlaceMacroIsAvailableCoord_ // Description : Returns TRUE if the given relative macro placement can be // transformed to a legal placement based on the current // state of VPR's grid array. Optionally, returns a list of // moves corresponding to the availability testing. // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 01/15/13 jeffr : Original //===========================================================================// bool TRP_RelativePlaceHandler_c::PlaceMacroIsAvailableCoord_( const TGO_Point_c& fromOrigin, const TGO_Point_c& toOrigin, TGO_RotateMode_t toRotate, TRP_RelativeMoveList_t* prelativeMoveList ) const { bool isAvailable = true; size_t fromMacroIndex = this->FindRelativeMacroIndex_( fromOrigin ); size_t toMacroIndex = this->FindRelativeMacroIndex_( toOrigin ); TRP_RelativeMacro_c fromMacro_; const TRP_RelativeMacro_c* pfromMacro = this->FindRelativeMacro_( fromOrigin ); if( !pfromMacro ) { fromMacro_.Add( ); fromMacro_.Set( 0, fromOrigin ); pfromMacro = &fromMacro_; } TRP_RelativeMoveList_t relativeMoveList( 2 * pfromMacro->GetLength( )); for( size_t i = 0; i < pfromMacro->GetLength( ); ++i ) { const TRP_RelativeNode_c& fromNode = *(*pfromMacro)[i]; TGO_Point_c fromPoint = fromNode.GetVPR_GridPoint( ); // Apply transform to relative node's grid point (based on origin point) TGO_Transform_c toTransform( toOrigin, toRotate, fromOrigin, fromPoint ); TGO_Point_c toPoint; toTransform.Apply( toOrigin, &toPoint ); // Validate that transformed point is still valid wrt. VPR's grid array if( !this->IsWithinGrid_( toPoint )) { isAvailable = false; break; } // Validate that we are attempting between non-identifical macros if( fromMacroIndex == toMacroIndex ) { isAvailable = false; break; } const t_type_descriptor* vpr_fromType = this->FindGridPointType_( fromPoint ); const t_type_descriptor* vpr_toType = this->FindGridPointType_( toPoint ); if( vpr_fromType != vpr_toType ) { // VPR's grid types do not match => location is *not* available isAvailable = false; break; } if( this->IsEmptyGridPoint_( fromPoint )) { // VPR's grid location is empty => really not much we can do today continue; } if( this->IsEmptyGridPoint_( toPoint )) { // VPR's grid location is empty => it is available // Add move "from" relative macro node -> "to" empty block location TRP_RelativeMove_c fromMove( fromMacroIndex, fromPoint, toPoint ); relativeMoveList.Add( fromMove ); continue; } const TRP_RelativeBlock_c* pfromBlock = this->FindRelativeBlock_( fromPoint ); if( !pfromBlock || !pfromBlock->HasRelativeMacroIndex( )) { // VPR's grid block name is not asso. with a relative macro => not available continue; } const TRP_RelativeBlock_c* ptoBlock = this->FindRelativeBlock_( toPoint ); if( !ptoBlock || !ptoBlock->HasRelativeMacroIndex( )) { // VPR's grid block name is not asso. with a relative macro => it is available // Add move "from" relative macro node -> "to" single block location, // and add move "to" single block -> "from" relative macro node // (since "to" block location not a member of a relative macro) TRP_RelativeMove_c fromMove( fromMacroIndex, fromPoint, toPoint ); TRP_RelativeMove_c toMove( toPoint, fromMacroIndex, fromPoint ); relativeMoveList.Add( fromMove ); relativeMoveList.Add( toMove ); continue; } if( ptoBlock && ptoBlock->GetRelativeMacroIndex( ) == toMacroIndex ) { // VPR's grid block name matches the given "to" relative macro => it is available // Add move "from" relative macro node -> "to" single block location, // but ignore move "to" relative macro node -> "from" relative macro node // (since "to" move will be captured by to->from availability processing) TRP_RelativeMove_c fromMove( fromMacroIndex, fromPoint, toMacroIndex, toPoint ); relativeMoveList.Add( fromMove ); continue; } // If we arrive at this point, then we know that VPR's grid block must // be a member of some other unrelated relative macro isAvailable = FALSE; break; } if( isAvailable ) { // Add list of local moves to the optional relative move list prelativeMoveList->Add( relativeMoveList ); } return( isAvailable ); // TRUE => all relative nodes can be transformed } //===========================================================================// // Method : PlaceMacroResetRotate_ // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 01/15/13 jeffr : Original //===========================================================================// void TRP_RelativePlaceHandler_c::PlaceMacroResetRotate_( TRP_PlaceMacroRotateMode_t mode ) { TRP_RotateMaskValue_c* protateMaskValue = ( mode == TRP_PLACE_MACRO_ROTATE_FROM ? &this->fromPlaceMacroRotate_ : &this->toPlaceMacroRotate_ ); protateMaskValue->Init( this->placeOptions_.rotateEnable ); } //===========================================================================// // Method : PlaceMacroIsLegalRotate_ // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 01/15/13 jeffr : Original //===========================================================================// bool TRP_RelativePlaceHandler_c::PlaceMacroIsLegalRotate_( TRP_PlaceMacroRotateMode_t mode, TGO_RotateMode_t rotate ) const { bool isLegal = true; const TRP_RotateMaskValue_c* pplaceMacroRotate = ( mode == TRP_PLACE_MACRO_ROTATE_FROM ? &this->fromPlaceMacroRotate_ : &this->toPlaceMacroRotate_ ); TRP_RotateMaskValue_c* protateMaskValue = const_cast< TRP_RotateMaskValue_c* >( pplaceMacroRotate ); if( !protateMaskValue->GetBit( rotate )) { isLegal = false; } else { isLegal = true; protateMaskValue->ClearBit( rotate ); } return( isLegal ); } //===========================================================================// // Method : PlaceMacroIsValidRotate_ // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 01/15/13 jeffr : Original //===========================================================================// bool TRP_RelativePlaceHandler_c::PlaceMacroIsValidRotate_( TRP_PlaceMacroRotateMode_t mode ) const { const TRP_RotateMaskValue_c* pplaceMacroRotate = ( mode == TRP_PLACE_MACRO_ROTATE_FROM ? &this->fromPlaceMacroRotate_ : &this->toPlaceMacroRotate_ ); return( pplaceMacroRotate->IsValid( ) ? true : false ); } //===========================================================================// // Method : PlaceMacroUpdateMoveList_ // Description : Updates a relative move list to insure the "fromEmpty" // and "toEmpty" values accurately reflect when a grid point // will become empty after a relative move. This situation // may occur undetected in "PlaceMacroIsAvailableCoord_()" // if a move has been made from a relative macro node point // that is not subsequently used by another move (which can // occur due to different random "from" and "to" rotate // modes). This relative move list update is needed in order // to insure that VPR's 'blocks_affected array' is // subsequently correctly loaded by "PlaceSwapUpdate_()" // such that the 'swapped_to_empty' fields properly indicate // when a move leaves a grid point empty. // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 01/15/13 jeffr : Original //===========================================================================// void TRP_RelativePlaceHandler_c::PlaceMacroUpdateMoveList_( TRP_RelativeMoveList_t* prelativeMoveList ) const { for( size_t i = 0; i < prelativeMoveList->GetLength( ); ++i ) { TRP_RelativeMove_c* prelativeMove = (*prelativeMoveList)[i]; const TGO_Point_c& fromPoint = prelativeMove->GetFromPoint( ); const TGO_Point_c& toPoint = prelativeMove->GetToPoint( ); bool fromEmpty = true; bool toEmpty = true; for( size_t j = 0; j < prelativeMoveList->GetLength( ); ++j ) { const TRP_RelativeMove_c& relativeMove = *(*prelativeMoveList)[j]; if( relativeMove.GetToPoint( ) == fromPoint ) { fromEmpty = false; } if( relativeMove.GetFromPoint( ) == toPoint ) { toEmpty = false; } } prelativeMove->SetFromEmpty( fromEmpty ); prelativeMove->SetToEmpty( toEmpty ); } } //===========================================================================// // Method : PlaceMacroIsLegalMoveList_ // Description : Returns TRUE if-and-only-if no two relative moves share // the same "to" point. This situation may exist undetected // during "PlaceMacroIsAvailableCoord_()" if two relative // macros are near enough to each other and they end of // sharing a common "to" point. // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 01/15/13 jeffr : Original //===========================================================================// bool TRP_RelativePlaceHandler_c::PlaceMacroIsLegalMoveList_( const TRP_RelativeMoveList_t& fromToMoveList, const TRP_RelativeMoveList_t& toFromMoveList ) const { bool isLegal = true; for( size_t i = 0; i < toFromMoveList.GetLength( ); ++i ) { const TRP_RelativeMove_c& toFromMove = *toFromMoveList[i]; for( size_t j = 0; j < fromToMoveList.GetLength( ); ++j ) { const TRP_RelativeMove_c& fromToMove = *fromToMoveList[j]; if( toFromMove.GetToPoint( ) == fromToMove.GetToPoint( )) { // Found at least two relative moves that share same "to" point isLegal = false; } if( !isLegal ) break; } if( !isLegal ) break; } return( isLegal ); } //===========================================================================// // Method : FindRandomRotateMode_ // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 01/15/13 jeffr : Original //===========================================================================// TGO_RotateMode_t TRP_RelativePlaceHandler_c::FindRandomRotateMode_( void ) const { // Select a random rotate mode (if enabled) int rotate = ( this->placeOptions_.rotateEnable ? TCT_Rand( 1, TGO_ROTATE_MAX - 1 ) : TGO_ROTATE_R0 ); return( static_cast< TGO_RotateMode_t >( rotate )); } //===========================================================================// // Method : FindRandomOriginPoint_ // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 01/15/13 jeffr : Original //===========================================================================// TGO_Point_c TRP_RelativePlaceHandler_c::FindRandomOriginPoint_( const TRP_RelativeMacro_c& relativeMacro, size_t relativeNodeIndex ) const { const TRP_RelativeNodeList_t& relativeNodeList = relativeMacro.GetRelativeNodeList( ); const TRP_RelativeNode_c& relativeNode = *relativeNodeList[relativeNodeIndex]; return( this->FindRandomOriginPoint_( relativeNode )); } //===========================================================================// TGO_Point_c TRP_RelativePlaceHandler_c::FindRandomOriginPoint_( const TRP_RelativeNode_c& relativeNode ) const { const char* pszBlockName = relativeNode.GetBlockName( ); return( this->FindRandomOriginPoint_( pszBlockName )); } //===========================================================================// TGO_Point_c TRP_RelativePlaceHandler_c::FindRandomOriginPoint_( const char* pszBlockName ) const { TGO_Point_c originPoint; const TRP_RelativeBlock_c& relativeBlock = *this->relativeBlockList_.Find( pszBlockName ); const t_type_descriptor* vpr_type = relativeBlock.GetVPR_Type( ); int typeIndex = ( vpr_type ? vpr_type->index : EMPTY ); int posIndex = 0; if(( typeIndex != EMPTY ) && ( this->vpr_.freeLocationArray[typeIndex] >= 0 )) { // Attempt to select a random (and available) point from within VPR's grid array // (based on VPR's internal 'free_locations' and 'legal_pos' structures) for( size_t i = 0; i < TRP_FIND_RANDOM_ORIGIN_POINT_MAX_ATTEMPTS; ++i ) { posIndex = TCT_Rand( 0, this->vpr_.freeLocationArray[typeIndex] - 1 ); int x = this->vpr_.legalPosArray[typeIndex][posIndex].x; int y = this->vpr_.legalPosArray[typeIndex][posIndex].y; int z = this->vpr_.legalPosArray[typeIndex][posIndex].z; if( this->vpr_.gridArray[x][y].blocks[z] == EMPTY ) { originPoint.Set( x, y, z ); break; } } } if(( typeIndex != EMPTY ) && ( this->vpr_.freeLocationArray[typeIndex] >= 0 ) && ( !originPoint.IsValid( ))) { // Handle case where we failed to find placement location // (due to exceeding the max number of random placement attempts) TIO_PrintHandler_c& printHandler = TIO_PrintHandler_c::GetInstance( ); printHandler.Warning( "Failed initial relative macro placement for block \"%s\" after %u random tries.\n", TIO_PSZ_STR( pszBlockName ), TRP_FIND_RANDOM_ORIGIN_POINT_MAX_ATTEMPTS ); printHandler.Info( "%sAttempting to find available location based on exhaustive search of all free locations.\n", TIO_PREFIX_WARNING_SPACE ); // Perform an exhaustive search for 1st free location for( posIndex = 0; posIndex < this->vpr_.freeLocationArray[typeIndex]; ++posIndex ) { int x = this->vpr_.legalPosArray[typeIndex][posIndex].x; int y = this->vpr_.legalPosArray[typeIndex][posIndex].y; int z = this->vpr_.legalPosArray[typeIndex][posIndex].z; if( this->vpr_.gridArray[x][y].blocks[z] == EMPTY ) { originPoint.Set( x, y, z ); break; } } } if(( typeIndex != EMPTY ) && ( this->vpr_.freeLocationArray[typeIndex] >= 0 ) && ( !originPoint.IsValid( ))) { // Handle case where we still failed to find placement location // (even after an exhaustive iteration over all free locations) TIO_PrintHandler_c& printHandler = TIO_PrintHandler_c::GetInstance( ); printHandler.Error( "Initial relative placement failed!\n" ); printHandler.Info( "%sCould not place block \"%s\", no free locations of type \"%s\".\n", TIO_PREFIX_ERROR_SPACE, TIO_PSZ_STR( pszBlockName ), TIO_PSZ_STR( this->vpr_.typeArray[typeIndex].name )); } if(( typeIndex != EMPTY ) && ( this->vpr_.freeLocationArray[typeIndex] >= 0 ) && ( originPoint.IsValid( ))) { // Update VPR's 'free_locations' and 'legal_pos' structures to prevent // randomly finding same origin point again - IFF rotate not enabled // (for further reference, see VPR's initial_place_blocks() function) if( !this->placeOptions_.rotateEnable ) { int lastIndex = this->vpr_.freeLocationArray[typeIndex] - 1; if( lastIndex >= 0 ) { this->vpr_.legalPosArray[typeIndex][posIndex] = this->vpr_.legalPosArray[typeIndex][lastIndex]; } --this->vpr_.freeLocationArray[typeIndex]; } } return( originPoint ); } //===========================================================================// // Method : FindRandomRelativeNodeIndex_ // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 01/15/13 jeffr : Original //===========================================================================// size_t TRP_RelativePlaceHandler_c::FindRandomRelativeNodeIndex_( const TRP_RelativeMacro_c& relativeMacro ) const { size_t relativeNodeIndex = TCT_Rand( static_cast<size_t>( 0 ), relativeMacro.GetLength( ) - 1 ); return( relativeNodeIndex ); } //===========================================================================// // Method : FindRelativeMacroIndex_ // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 01/15/13 jeffr : Original //===========================================================================// size_t TRP_RelativePlaceHandler_c::FindRelativeMacroIndex_( const TGO_Point_c& point ) const { size_t relativeMacroIndex = TRP_RELATIVE_MACRO_UNDEFINED; if( this->IsWithinGrid_( point )) { // Find relative block based on VPR's grid array point const TRP_RelativeBlock_c* prelativeBlock = this->FindRelativeBlock_( point ); // Find relative macro index, if any, based on relative block if( prelativeBlock ) { relativeMacroIndex = prelativeBlock->GetRelativeMacroIndex( ); } } return( relativeMacroIndex ); } //===========================================================================// // Method : FindRelativeNodeIndex_ // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 01/15/13 jeffr : Original //===========================================================================// size_t TRP_RelativePlaceHandler_c::FindRelativeNodeIndex_( const TGO_Point_c& point ) const { size_t relativeNodeIndex = TRP_RELATIVE_NODE_UNDEFINED; if( this->IsWithinGrid_( point )) { // Find relative block based on VPR's grid array point const TRP_RelativeBlock_c* prelativeBlock = this->FindRelativeBlock_( point ); // Find relative node index, if any, based on relative block if( prelativeBlock ) { relativeNodeIndex = prelativeBlock->GetRelativeNodeIndex( ); } } return( relativeNodeIndex ); } //===========================================================================// // Method : FindRelativeMacro_ // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 01/15/13 jeffr : Original //===========================================================================// TRP_RelativeMacro_c* TRP_RelativePlaceHandler_c::FindRelativeMacro_( const TGO_Point_c& point ) const { TRP_RelativeMacro_c* prelativeMacro = 0; if( this->IsWithinGrid_( point )) { // Find relative macro index based on VPR's grid array point size_t relativeMacroIndex = this->FindRelativeMacroIndex_( point ); // Find relative macro, if any, based on relative macro index prelativeMacro = this->relativeMacroList_[relativeMacroIndex]; } return( prelativeMacro ); } //===========================================================================// // Method : FindRelativeNode_ // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 01/15/13 jeffr : Original //===========================================================================// TRP_RelativeNode_c* TRP_RelativePlaceHandler_c::FindRelativeNode_( const TGO_Point_c& point ) const { TRP_RelativeNode_c* prelativeNode = 0; if( this->IsWithinGrid_( point )) { // Find relative macro and node indices based on VPR's grid array point size_t relativeMacroIndex = this->FindRelativeMacroIndex_( point ); size_t relativeNodeIndex = this->FindRelativeNodeIndex_( point ); // Find relative macro, if any, based on relative macro index const TRP_RelativeMacro_c* prelativeMacro = 0; prelativeMacro = this->relativeMacroList_[relativeMacroIndex]; if( prelativeMacro ) { prelativeNode = (*prelativeMacro)[relativeNodeIndex]; } } return( prelativeNode ); } //===========================================================================// // Method : FindRelativeBlock_ // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 01/15/13 jeffr : Original //===========================================================================// const TRP_RelativeBlock_c* TRP_RelativePlaceHandler_c::FindRelativeBlock_( const TGO_Point_c& point ) const { const TRP_RelativeBlock_c* prelativeBlock = 0; if( this->IsWithinGrid_( point )) { // Look up VPR block name based on VPR's grid array const char* pszBlockName = this->FindGridPointBlockName_( point ); // Find relative block, if any, based on VPR's block name prelativeBlock = this->relativeBlockList_.Find( pszBlockName ); } return( prelativeBlock ); } //===========================================================================// // Method : FindGridPointBlockName_ // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 01/15/13 jeffr : Original //===========================================================================// const char* TRP_RelativePlaceHandler_c::FindGridPointBlockName_( const TGO_Point_c& point ) const { const char* pszBlockName = 0; int blockIndex = this->FindGridPointBlockIndex_( point ); if( blockIndex != EMPTY ) { pszBlockName = this->vpr_.blockArray[blockIndex].name; } return( pszBlockName ); } //===========================================================================// // Method : FindGridPointBlockIndex_ // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 01/15/13 jeffr : Original //===========================================================================// int TRP_RelativePlaceHandler_c::FindGridPointBlockIndex_( const TGO_Point_c& point ) const { int blockIndex = EMPTY; if( this->IsWithinGrid_( point )) { int x = point.x; int y = point.y; int z = point.z; blockIndex = this->vpr_.gridArray[x][y].blocks[z]; } return( blockIndex ); } //===========================================================================// // Method : FindGridPointType_ // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 01/15/13 jeffr : Original //===========================================================================// const t_type_descriptor* TRP_RelativePlaceHandler_c::FindGridPointType_( const TGO_Point_c& point ) const { const t_type_descriptor* vpr_type = 0; if( this->IsWithinGrid_( point )) { int x = point.x; int y = point.y; vpr_type = this->vpr_.gridArray[x][y].type; } return( vpr_type ); } //===========================================================================// // Method : IsEmptyGridPoint_ // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 01/15/13 jeffr : Original //===========================================================================// bool TRP_RelativePlaceHandler_c::IsEmptyGridPoint_( const TGO_Point_c& point ) const { bool isEmpty = false; if( this->IsWithinGrid_( point )) { int x = point.x; int y = point.y; int z = point.z; isEmpty = ( this->vpr_.gridArray[x][y].blocks[z] == EMPTY ? true : false ); } return( isEmpty ); } //===========================================================================// // Method : IsWithinGrid_ // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 01/15/13 jeffr : Original //===========================================================================// bool TRP_RelativePlaceHandler_c::IsWithinGrid_( const TGO_Point_c& point ) const { bool isWithin = ( point.x >= 0 && point.x <= this->vpr_.nx && point.y >= 0 && point.y <= this->vpr_.ny ? true : false ); return( isWithin ); } //===========================================================================// // Method : DecideAntiSide_ // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 01/15/13 jeffr : Original //===========================================================================// TC_SideMode_t TRP_RelativePlaceHandler_c::DecideAntiSide_( TC_SideMode_t side ) const { TC_SideMode_t antiSide = TC_SIDE_UNDEFINED; switch( side ) { case TC_SIDE_LEFT: antiSide = TC_SIDE_RIGHT; break; case TC_SIDE_RIGHT: antiSide = TC_SIDE_LEFT; break; case TC_SIDE_LOWER: antiSide = TC_SIDE_UPPER; break; case TC_SIDE_UPPER: antiSide = TC_SIDE_LOWER; break; default: break; } return( antiSide ); } //===========================================================================// // Method : ShowMissingBlockNameError_ // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 01/15/13 jeffr : Original //===========================================================================// bool TRP_RelativePlaceHandler_c::ShowMissingBlockNameError_( const char* pszBlockName ) const { TIO_PrintHandler_c& printHandler = TIO_PrintHandler_c::GetInstance( ); bool ok = printHandler.Error( "Invalid relative placement constraint!\n" ); printHandler.Info( "%sBlock \"%s\" was not found in VPR's block list.\n", TIO_PREFIX_ERROR_SPACE, TIO_PSZ_STR( pszBlockName )); return( ok ); } //===========================================================================// // Method : ShowInvalidConstraintError_ // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 01/15/13 jeffr : Original //===========================================================================// bool TRP_RelativePlaceHandler_c::ShowInvalidConstraintError_( const TRP_RelativeBlock_c& fromBlock, const TRP_RelativeBlock_c& toBlock, TC_SideMode_t side, const string& srExistingFromBlockName, const string& srExistingToBlockName ) const { const char* pszFromBlockName = fromBlock.GetName( ); const char* pszToBlockName = toBlock.GetName( ); string srSide; TC_ExtractStringSideMode( side, &srSide ); TIO_PrintHandler_c& printHandler = TIO_PrintHandler_c::GetInstance( ); bool ok = printHandler.Error( "Invalid relative placement constraint!\n" ); if( srExistingFromBlockName.length( ) && srExistingToBlockName.length( )) { printHandler.Info( "%sConstraint already exists between \"%s\" and \"%s\".\n", TIO_PREFIX_ERROR_SPACE, TIO_SR_STR( srExistingFromBlockName ), TIO_SR_STR( srExistingToBlockName )); } printHandler.Info( "%sIgnoring constraint from \"%s\" to \"%s\" on side '%s'.\n", TIO_PREFIX_ERROR_SPACE, TIO_PSZ_STR( pszFromBlockName ), TIO_PSZ_STR( pszToBlockName ), TIO_SR_STR( srSide )); return( ok ); }
39.139327
134
0.535946
[ "transform" ]
2cdadbd11aa08879e925482db742e694b66c87d3
31,446
cpp
C++
Video_inpainting_matlab/Patch_match/patch_match_tools.cpp
zhukevgeniy/video-inpainting
0f650df61a802c17b2efdfa132211026a7e42eba
[ "MIT" ]
null
null
null
Video_inpainting_matlab/Patch_match/patch_match_tools.cpp
zhukevgeniy/video-inpainting
0f650df61a802c17b2efdfa132211026a7e42eba
[ "MIT" ]
null
null
null
Video_inpainting_matlab/Patch_match/patch_match_tools.cpp
zhukevgeniy/video-inpainting
0f650df61a802c17b2efdfa132211026a7e42eba
[ "MIT" ]
null
null
null
//this function defines the functions which are tools used for the //spatio-temporal patch_match algorithm #include "patch_match_tools.h" //check if the displacement values have already been used template <class T> bool check_already_used_patch( nTupleVolume<T> *dispField, int x, int y, int t, int dispX, int dispY, int dispT) { if ( (((int)dispField->get_value(x,y,t,0)) == dispX) && (((int)dispField->get_value(x,y,t,1)) == dispY) && (((int)dispField->get_value(x,y,t,2)) == dispT) ) return 1; else return 0; } //check if the pixel is occluded template <class T> int check_is_occluded( nTupleVolume<T> *imgVolOcc, int x, int y, int t) { if (imgVolOcc->xSize == 0) return 0; if ( (imgVolOcc->get_value(x,y,t,0)) > 0) return 1; else return 0; } template <class T> float calclulate_patch_error(nTupleVolume<T> *departVolume,nTupleVolume<T> *arrivalVolume,nTupleVolume<T> *dispField, nTupleVolume<T> *occVol, int xA, int yA, int tA, float minError, const parameterStruct *params) { int xB, yB, tB; float errorOut; xB = (xA) + (int)dispField->get_value(xA,yA,tA,0); yB = (yA) + (int)dispField->get_value(xA,yA,tA,1); tB = (tA) + (int)dispField->get_value(xA,yA,tA,2); errorOut = ssd_patch_measure(departVolume, arrivalVolume,dispField,occVol, xA, yA, tA, xB, yB, tB, minError, params); return(errorOut); } template <class T> int check_disp_field(nTupleVolume<T> *dispField, nTupleVolume<T> *departVolume, nTupleVolume<T> *arrivalVolume, nTupleVolume<T> *occVol, const parameterStruct *params) { int dispValX,dispValY,dispValT,hPatchSizeX,hPatchSizeY,hPatchSizeT; int xB,yB,tB; int i,j,k,returnVal; hPatchSizeX = (int)floor((float)((departVolume->patchSizeX)/2)); //half the patch size hPatchSizeY = (int)floor((float)((departVolume->patchSizeY)/2)); //half the patch size hPatchSizeT = (int)floor((float)((departVolume->patchSizeT)/2)); //half the patch size returnVal = 0; for (k=hPatchSizeT; k< ((dispField->tSize) -hPatchSizeT); k++) for (j=hPatchSizeY; j< ((dispField->ySize) -hPatchSizeY); j++) for (i=hPatchSizeX; i< ((dispField->xSize) -hPatchSizeX); i++) { dispValX = (int)dispField->get_value(i,j,k,0); dispValY = (int)dispField->get_value(i,j,k,1); dispValT = (int)dispField->get_value(i,j,k,2); xB = dispValX + i; yB = dispValY + j; tB = dispValT + k; if ( check_in_inner_boundaries(arrivalVolume, xB, yB, tB,params) == 0) { MY_PRINTF("Error, the displacement is incorrect.\n"); MY_PRINTF("xA : %d\n yA : %d\n tA : %d\n",i,j,k); MY_PRINTF(" dispValX : %d\n dispValY : %d\n dispValT : %d\n",dispValX,dispValY,dispValT); MY_PRINTF(" xB : %d\n yB : %d\n tB : %d\n",xB,yB,tB); returnVal= -1; } else if (check_is_occluded(occVol,xB,yB,tB) == 1) { MY_PRINTF("Error, the displacement leads to an occluded pixel.\n"); MY_PRINTF(" xB : %d\n yB : %d\n tB : %d\n",xB,yB,tB); returnVal= -1; } } return(returnVal); } template <class T> void patch_match_full_search(nTupleVolume<T> *dispField, nTupleVolume<T> *imgVolA,nTupleVolume<T> *imgVolB, nTupleVolume<T> *occVol, nTupleVolume<T> *modVol, const parameterStruct *params) { float minSSD,ssdTemp; int hPatchSizeX, hPatchSizeY, hPatchSizeT; int i,j,k,ii,jj,kk; int bestX, bestY, bestT; hPatchSizeX = (int)floor((float)((dispField->patchSizeX)/2)); //half the patch size hPatchSizeY = (int)floor((float)((dispField->patchSizeY)/2)); //half the patch size hPatchSizeT = (int)floor((float)((dispField->patchSizeT)/2)); //half the patch size //#pragma omp parallel for shared(dispField, occVol, imgVolA, imgVolB) private(kk,jj,ii,minSSD,ssdTemp,bestX,bestY,bestT,i,j,k) for (k=hPatchSizeT; k< ((dispField->tSize) -hPatchSizeT); k++) for (j=hPatchSizeY; j< ((dispField->ySize) -hPatchSizeY); j++) { for (i=hPatchSizeX; i< ((dispField->xSize) -hPatchSizeX); i++) { minSSD = FLT_MAX; if (modVol->xSize >0) if (modVol->get_value(i,j,k,0) == 0) //if we don't want to modify this match continue; //search for the best match for (kk=hPatchSizeT; kk< ((dispField->tSize) -hPatchSizeT); kk++) for (jj=hPatchSizeY; jj< ((dispField->ySize) -hPatchSizeY); jj++) for (ii=hPatchSizeX; ii< ((dispField->xSize) -hPatchSizeX); ii++) { if (occVol->xSize >0) if (check_is_occluded(occVol,ii,jj,kk)) //if this pixel is occluded, continue continue; ssdTemp = ssd_patch_measure<T>(imgVolA, imgVolB, dispField,occVol, i, j, k,ii, jj, kk, minSSD,params); if ( (ssdTemp != -1) && (ssdTemp <= minSSD)) //we have a new best match { minSSD = ssdTemp; bestX = ii - i; bestY = jj - j; bestT = kk - k; } } dispField->set_value(i,j,k,0,(T)bestX); dispField->set_value(i,j,k,1,(T)bestY); dispField->set_value(i,j,k,2,(T)bestT); dispField->set_value(i,j,k,3,minSSD); } } } template <class T> void initialise_displacement_field(nTupleVolume<T> *dispField, nTupleVolume<T> *departVolume, nTupleVolume<T> *arrivalVolume, nTupleVolume<T> *firstGuessVolume, nTupleVolume<T> *occVol, const parameterStruct *params) { //declarations int i,j,k, xDisp, yDisp, tDisp, hPatchSizeX, hPatchSizeY, hPatchSizeT, hPatchSizeCeilX, hPatchSizeCeilY, hPatchSizeCeilT; int xMin,xMax,yMin,yMax,tMin,tMax; int xFirst,yFirst,tFirst; int isNotOcc, currShift,currLinInd; float ssdTemp; hPatchSizeX = (int)floor(((float)arrivalVolume->patchSizeX)/2); hPatchSizeY = (int)floor(((float)arrivalVolume->patchSizeY)/2); hPatchSizeT = (int)floor(((float)arrivalVolume->patchSizeT)/2); hPatchSizeCeilX = (int)ceil(((float)arrivalVolume->patchSizeX)/2); hPatchSizeCeilY = (int)ceil(((float)arrivalVolume->patchSizeY)/2); hPatchSizeCeilT = (int)ceil(((float)arrivalVolume->patchSizeT)/2); for (i=0; i< (dispField->xSize); i++) for (j=0; j< (dispField->ySize); j++) for (k=0; k< (dispField->tSize); k++) { isNotOcc = 0; //if there is a valid first guess while(isNotOcc == 0) { //if there is a first guess, and it is in the inner boundaries, and respects the minimum shift distance if ( (firstGuessVolume->xSize >0) && (check_in_inner_boundaries(arrivalVolume,i+(int)firstGuessVolume->get_value(i,j,k,0),j+ (int)firstGuessVolume->get_value(i,j,k,1),k+(int)firstGuessVolume->get_value(i,j,k,2),params ) ) ) { //if it is not occluded, we take the initial first guess and continue if (!check_is_occluded(occVol,i+(int)firstGuessVolume->get_value(i,j,k,0),j+(int)firstGuessVolume->get_value(i,j,k,1), k+(int)firstGuessVolume->get_value(i,j,k,2)) ) { xDisp = (int)firstGuessVolume->get_value(i,j,k,0); yDisp = (int)firstGuessVolume->get_value(i,j,k,1); tDisp = (int)firstGuessVolume->get_value(i,j,k,2); isNotOcc = 1; continue; } else //otherwise, we set up the calculation of a random initial starting point, centred on the initial guess { xFirst = i+(int)firstGuessVolume->get_value(i,j,k,0); yFirst = j+(int)firstGuessVolume->get_value(i,j,k,1); tFirst = k+(int)firstGuessVolume->get_value(i,j,k,2); xMin = max_int(xFirst-params->w,hPatchSizeX); xMax = min_int(xFirst+params->w,arrivalVolume->xSize - hPatchSizeX -1); yMin = max_int(yFirst-params->w,hPatchSizeY); yMax = min_int(yFirst+params->w,arrivalVolume->ySize - hPatchSizeY -1); tMin = max_int(tFirst-params->w,hPatchSizeT); tMax = min_int(tFirst+params->w,arrivalVolume->tSize - hPatchSizeT -1); } } else //by default, set the displacement to float_max { dispField->set_value(i,j,k,0,(T)FLT_MAX); dispField->set_value(i,j,k,1,(T)FLT_MAX); dispField->set_value(i,j,k,2,(T)FLT_MAX); } if (arrivalVolume->xSize == arrivalVolume->patchSizeX) //special case where the patch size is the size of the dimension { xDisp = 0; } else{ if ( (dispField->get_value(i,j,k,0) == FLT_MAX) || (firstGuessVolume->xSize == 0)) //default behaviour { xDisp = ((rand()%( (arrivalVolume->xSize) -2*hPatchSizeCeilX-1)) + hPatchSizeX)-i; } else //based on an initial guess { xDisp = (int)(round_float(rand_float_range((float)(xMin),(float)(xMax))) - i); } } if (arrivalVolume->ySize == arrivalVolume->patchSizeY) //special case where the patch size is the size of the dimension { yDisp = 0; } else{ if ( (dispField->get_value(i,j,k,1) == FLT_MAX) || (firstGuessVolume->xSize == 0)) //default behaviour { yDisp = ((rand()%( (arrivalVolume->ySize) -2*hPatchSizeCeilY-1)) + hPatchSizeY)-j; } else //based on an initial guess { yDisp = (int)(round_float(rand_float_range((float)(yMin),(float)(yMax))) - j); } } if (arrivalVolume->tSize == arrivalVolume->patchSizeT) //special case where the patch size is the size of the dimension { tDisp = 0; } else{ if ( (dispField->get_value(i,j,k,2) == FLT_MAX) || (firstGuessVolume->xSize == 0)) //default behaviour { tDisp = ((rand()%( (arrivalVolume->tSize) -2*hPatchSizeCeilT-1)) + hPatchSizeT)-k; } else //based on an initial guess { tDisp = (int)(round_float(rand_float_range((float)(tMin),(float)(tMax))) - k); } } isNotOcc = (!(check_is_occluded(occVol,xDisp+i,yDisp+j,tDisp+k)) &&(check_in_inner_boundaries(arrivalVolume,xDisp+i,yDisp+j,tDisp+k,params))) ; } //if everything is all right, set the displacements dispField->set_value(i,j,k,0, (T)(xDisp)); dispField->set_value(i,j,k,1, (T)(yDisp)); dispField->set_value(i,j,k,2, (T)(tDisp)); if (check_in_inner_boundaries(departVolume,i,j,k,params)) ssdTemp = ssd_patch_measure<T>(departVolume, arrivalVolume, dispField,occVol, i, j, k, i+xDisp, j+yDisp, k+tDisp, -1,params); else ssdTemp = FLT_MAX; dispField->set_value(i,j,k,3,(T)ssdTemp); //set the ssd error } } template <class T> int patch_match_random_search(nTupleVolume<T> *dispField, nTupleVolume<T> *imgVolA, nTupleVolume<T> *imgVolB, nTupleVolume<T> *occVol, nTupleVolume<T> *modVol, const parameterStruct *params) { //create random number seed int xRand,yRand,tRand; int randMinX,randMaxX,randMinY,randMaxY,randMinT,randMaxT; int i,j,k,z,hPatchSizeX,hPatchSizeY,hPatchSizeT, zMax; int xTemp,yTemp,tTemp,wTemp,wMax; int *xDisp, *yDisp, *tDisp; int isCorrectShift,currShift,currLinInd; float ssdTemp; int nbModified = 0; clock_t startTime; hPatchSizeX = (int)floor((float)((dispField->patchSizeX)/2)); //half the patch size hPatchSizeY = (int)floor((float)((dispField->patchSizeY)/2)); //half the patch size hPatchSizeT = (int)floor((float)((dispField->patchSizeT)/2)); //half the patch size xDisp = new int[1]; yDisp = new int[1]; tDisp = new int[1]; //calculate the maximum z (patch search index) wMax = min_int(params->w, max_int(max_int(imgVolB->xSize,imgVolB->ySize),imgVolB->tSize)); zMax = (int)ceil((float) (- (log((float)(wMax)))/(log((float)(params->alpha)))) ); nTupleVolume<int> *wValues = new nTupleVolume<int>(1,zMax,1,1,imgVolA->indexing); //store the values of the maximum search parameters for (int z=0; z<zMax; z++) { wValues->set_value(z,0,0,0, (int)round_float((params->w)*((float)pow((float)params->alpha,z))) ); } //#pragma omp parallel for shared(dispField, occVol, imgVolA, imgVolB,nbModified) private(ssdTemp,xTemp,yTemp,tTemp,wTemp,randMinX,randMaxX,randMinY,randMaxY,randMinT,randMaxT,xRand,yRand,tRand,i,j,k,z) for (k=0; k< ((dispField->tSize) ); k++) for (j=0; j< ((dispField->ySize) ); j++) for (i=0; i< ((dispField->xSize) ); i++) { if (modVol->xSize >0) if (modVol->get_value(i,j,k,0) == 0) //if we don't want to modify this match continue; ssdTemp = dispField->get_value(i,j,k,3); //get the saved ssd value for (z=0; z<zMax; z++) //test for different search indices { xTemp = i+(int)dispField->get_value(i,j,k,0); //get the arrival position of the current offset yTemp = j+(int)dispField->get_value(i,j,k,1); //get the arrival position of the current offset tTemp = k+(int)dispField->get_value(i,j,k,2); //get the arrival position of the current offset wTemp = wValues->get_value(z,0,0,0); // X values randMinX = max_int(xTemp - wTemp,hPatchSizeX); randMaxX = min_int(xTemp + wTemp,imgVolB->xSize - hPatchSizeX - 1); // Y values randMinY = max_int(yTemp - wTemp,hPatchSizeY); randMaxY = min_int(yTemp + wTemp,imgVolB->ySize - hPatchSizeY - 1); // T values randMinT = max_int(tTemp - wTemp,hPatchSizeT); randMaxT = min_int(tTemp + wTemp,imgVolB->tSize - hPatchSizeT - 1); //new positions in the image imgB xRand = rand_int_range(randMinX, randMaxX); //random values between xMin and xMax, clamped to the sizes of the image B yRand = rand_int_range(randMinY, randMaxY); //random values between yMin and yMax, clamped to the sizes of the image B tRand = rand_int_range(randMinT, randMaxT); //random values between tMin and tMax, clamped to the sizes of the image B if (check_is_occluded(occVol,xRand,yRand,tRand)) continue; //the new position is occluded if (check_in_inner_boundaries(imgVolB,xRand,yRand,tRand,params) == 0) continue; //the new position is not in the inner boundaries ssdTemp = ssd_patch_measure(imgVolA, imgVolB, dispField,occVol, i, j, k, xRand, yRand, tRand, ssdTemp,params); if (ssdTemp != -1) //we have a better match { dispField->set_value(i,j,k,0, (T)(xRand-i)); dispField->set_value(i,j,k,1, (T)(yRand-j)); dispField->set_value(i,j,k,2, (T)(tRand-k)); dispField->set_value(i,j,k,3, (T)(ssdTemp)); nbModified = nbModified+1; } else ssdTemp = dispField->get_value(i,j,k,3); //set the saved ssd value bakc to its proper (not -1) value } } delete xDisp; delete yDisp; delete tDisp; delete wValues; return(nbModified); } //one iteration of the propagation of the patch match algorithm template <class T> int patch_match_propagation(nTupleVolume<T> *dispField, nTupleVolume<T> *departVolume, nTupleVolume<T> *arrivalVolume, nTupleVolume<T> *occVol, nTupleVolume<T> *modVol, const parameterStruct *params, int iterationNb) { //declarations int i,j,k, hPatchSizeX, hPatchSizeY, hPatchSizeT, *correctInd; int nbModified; int coordDispX,coordDispY, coordDispT; float currentError, *minVector; hPatchSizeX = (int)floor((float)((departVolume->patchSizeX)/2)); //half the patch size hPatchSizeY = (int)floor((float)((departVolume->patchSizeY)/2)); //half the patch size hPatchSizeT = (int)floor((float)((departVolume->patchSizeT)/2)); //half the patch size correctInd = (int*)malloc((size_t)sizeof(int)); minVector = (float*)malloc((size_t)3*sizeof(float)); //iterate over all displacements (do not go to edge, where the patches may not be defined) nbModified = 0; if (iterationNb&1) //if we are on an odd iteration { for (k=((dispField->tSize)-1); k>= 0; k--) for (j=((dispField->ySize) -1); j>= 0; j--) for (i=((dispField->xSize) -1); i>= 0; i--) { if (modVol->xSize >0) if (modVol->get_value(i,j,k,0) == 0) //if we don't want to modify this match continue; //calculate the error of the current displacement currentError = dispField->get_value(i,j,k,3); get_min_correct_error(dispField,departVolume,arrivalVolume,occVol, i, j, k, iterationNb&1, correctInd,minVector,currentError,params); //if the best displacement is the current one. Note : we have taken into account the case //where none of the diplacements around the current pixel are valid if (*correctInd == -1) //if the best displacement is the current one { dispField->set_value(i,j,k,3,currentError); } else //we copy the displacement from another better one { if ((*correctInd) == 0){ copy_pixel_values_nTuple_volume(dispField,dispField, min_int(i+1,((int)dispField->xSize)-1), j, k, i, j, k); nbModified++; } else if((*correctInd) == 1){ copy_pixel_values_nTuple_volume(dispField,dispField, i, min_int(j+1,((int)dispField->ySize)-1), k, i, j, k); nbModified++; } else if( (*correctInd) == 2){ copy_pixel_values_nTuple_volume(dispField,dispField, i, j, min_int(k+1,((int)dispField->tSize)-1), i, j, k); nbModified++; } else MY_PRINTF("Error, correct ind not chosen\n."); //now calculate the error of the patch matching currentError = calclulate_patch_error<T>(departVolume,arrivalVolume,dispField,occVol,i,j,k, -1,params); dispField->set_value(i,j,k,3,currentError); } } } else //if we are on an even iteration { for (k=0; k< ((dispField->tSize) ); k++) for (j=0; j< ((dispField->ySize) ); j++) for (i=0; i< ((dispField->xSize) ); i++) { if (modVol->xSize >0) if (modVol->get_value(i,j,k,0) == 0) //if we don't want to modify this match continue; //calculate the error of the current displacement currentError = currentError = dispField->get_value(i,j,k,3);//calclulate_patch_error(departVolume,arrivalVolume,dispField,occVol,i,j,k, -1,params); //get the upper, left and before patch distances get_min_correct_error(dispField,departVolume,arrivalVolume,occVol, i, j, k, iterationNb&1, correctInd, minVector,currentError,params); //if the best displacement is the current one. Note : we have taken into account the case //where none of the diplacements around the current pixel are valid if (*correctInd == -1) { dispField->set_value(i,j,k,3,currentError); } else //we copy the displacement from another better one { if ( (*correctInd) == 0){ coordDispX = (int)dispField->get_value(max_int(i-1,0),j,k,0); coordDispY = (int)dispField->get_value(max_int(i-1,0),j,k,1); coordDispT = (int)dispField->get_value(max_int(i-1,0),j,k,2); copy_pixel_values_nTuple_volume(dispField,dispField, max_int(i-1,0), j, k, i, j, k); nbModified++; } else if( (*correctInd) == 1){ coordDispX = (int)dispField->get_value(i,max_int(j-1,0),k,0); coordDispY = (int)dispField->get_value(i,max_int(j-1,0),k,1); coordDispT = (int)dispField->get_value(i,max_int(j-1,0),k,2); copy_pixel_values_nTuple_volume(dispField,dispField, i, max_int(j-1,0), k, i, j, k); nbModified++; } else if( (*correctInd) == 2){ copy_pixel_values_nTuple_volume(dispField,dispField, i, j, max_int(k-1,0), i, j, k); nbModified++; } else MY_PRINTF("Error, correct ind not chosen\n."); //now calculate the error of the patch matching currentError = calclulate_patch_error<T>(departVolume,arrivalVolume,dispField,occVol,i,j,k, -1,params); dispField->set_value(i,j,k,3,currentError); } } } free(correctInd); free(minVector); return(nbModified); } //this function returns the minimum error of the patch differences around the pixel at (i,j,k) //and returns the index of the best position in correctInd : // -1 : none are correct // 0 : left/right // 1 : upper/lower // 2 : before/after template <class T> float get_min_correct_error(nTupleVolume<T> *dispField,nTupleVolume<T> *departVol,nTupleVolume<T> *arrivalVol, nTupleVolume<T> *occVol, int x, int y, int t, int beforeOrAfter, int *correctInd, float *minVector, float minError, const parameterStruct *params) { float minVal; int i, coordDispX,coordDispY,coordDispT; int dispX, dispY, dispT; minVal = minError; *correctInd = -1; //initialise the correctInd vector to -1 for (i=0;i<NDIMS;i++) minVector[i] = -1; if (beforeOrAfter == 0) //we are looking left, upper, before : we are on an even iteration { dispX = (int)dispField->get_value((int)max_int(x-1,0),y,t,0); dispY = (int)dispField->get_value((int)max_int(x-1,0),y,t,1); dispT = (int)dispField->get_value((int)max_int(x-1,0),y,t,2); if ( check_in_inner_boundaries(arrivalVol,x+dispX,y+dispY,t+dispT,params) && (!check_is_occluded(occVol, x+dispX, y+dispY, t+dispT)) && (!check_already_used_patch( dispField, x, y, t, dispX, dispY, dispT))) minVector[0] = ssd_patch_measure(departVol, arrivalVol, dispField,occVol,x,y,t,x+dispX,y+dispY,t+dispT,minError,params); dispX = (int)dispField->get_value(x,(int)max_int(y-1,0),t,0); dispY = (int)dispField->get_value(x,(int)max_int(y-1,0),t,1); dispT = (int)dispField->get_value(x,(int)max_int(y-1,0),t,2); if ( check_in_inner_boundaries(arrivalVol,x+dispX,y+dispY,t+dispT,params) && (!check_is_occluded(occVol, x+dispX, y+dispY, t+dispT)) && (!check_already_used_patch( dispField, x, y, t, dispX, dispY, dispT))) minVector[1] = ssd_patch_measure(departVol, arrivalVol, dispField,occVol,x,y,t,x+dispX,y+dispY,t+dispT,minError,params); dispX = (int)dispField->get_value(x,y,(int)max_int(t-1,0),0); dispY = (int)dispField->get_value(x,y,(int)max_int(t-1,0),1); dispT = (int)dispField->get_value(x,y,(int)max_int(t-1,0),2); if ( check_in_inner_boundaries(arrivalVol,x+dispX,y+dispY,t+dispT,params) && (!check_is_occluded(occVol, x+dispX, y+dispY, t+dispT)) && (!check_already_used_patch( dispField, x, y, t, dispX, dispY, dispT))) minVector[2] = ssd_patch_measure(departVol, arrivalVol, dispField,occVol,x,y,t,x+dispX,y+dispY,t+dispT,minError,params);// for (i=0;i<NDIMS;i++) { if (minVector[i] == -1) continue; if ( minVector[i] < minVal) { switch (i){ case 0 : coordDispX = (int)dispField->get_value(max_int(x-1,0),y,t,0); coordDispY = (int)dispField->get_value(max_int(x-1,0),y,t,1); coordDispT = (int)dispField->get_value(max_int(x-1,0),y,t,2); // // if ( check_in_inner_boundaries(arrivalVol,x+coordDispX,y+coordDispY,t+coordDispT,params) && // // (!check_is_occluded(occVol, x+coordDispX, y+coordDispY, t+coordDispT)) && // // check_min_shift_distance(coordDispX, coordDispY, coordDispT,params)) // // { minVal = minVector[i]; *correctInd = 0; // // } break; case 1 : coordDispX = (int)dispField->get_value(x,max_int(y-1,0),t,0); coordDispY = (int)dispField->get_value(x,max_int(y-1,0),t,1); coordDispT = (int)dispField->get_value(x,max_int(y-1,0),t,2); // // if ( check_in_inner_boundaries(arrivalVol,x+coordDispX,y+coordDispY,t+coordDispT,params) && // // (!check_is_occluded(occVol, x+coordDispX, y+coordDispY, t+coordDispT)) && // // check_min_shift_distance(coordDispX, coordDispY, coordDispT,params)) // // { minVal = minVector[i]; *correctInd = 1; // // } break; case 2 : coordDispX = (int)dispField->get_value(x,y,max_int(t-1,0),0); coordDispY = (int)dispField->get_value(x,y,max_int(t-1,0),1); coordDispT = (int)dispField->get_value(x,y,max_int(t-1,0),2); // // if ( check_in_inner_boundaries(arrivalVol,x+coordDispX,y+coordDispY,t+coordDispT,params) && // // (!check_is_occluded(occVol, x+coordDispX, y+coordDispY, t+coordDispT)) && // // check_min_shift_distance(coordDispX, coordDispY, coordDispT,params)) // // { minVal = minVector[i]; *correctInd = 2; // } break; default : MY_PRINTF("Error in get_min_correct_error. The index i : %d is above 3.\n",i); } } } } else //we are looking right, lower, after { dispX = (int)dispField->get_value((int)min_int(x+1,(departVol->xSize)-1),y,t,0); dispY = (int)dispField->get_value((int)min_int(x+1,(departVol->xSize)-1),y,t,1); dispT = (int)dispField->get_value((int)min_int(x+1,(departVol->xSize)-1),y,t,2); if ( check_in_inner_boundaries(arrivalVol,x+dispX,y+dispY,t+dispT,params) && (!check_is_occluded(occVol, x+dispX, y+dispY, t+dispT)) && (!check_already_used_patch( dispField, x, y, t, dispX, dispY, dispT))) minVector[0] = ssd_patch_measure(departVol, arrivalVol, dispField,occVol,x,y,t,x+dispX,y+dispY,t+dispT,minError,params); dispX = (int)dispField->get_value(x,(int)min_int(y+1,(departVol->ySize)-1),t,0); dispY = (int)dispField->get_value(x,(int)min_int(y+1,(departVol->ySize)-1),t,1); dispT = (int)dispField->get_value(x,(int)min_int(y+1,(departVol->ySize)-1),t,2); if ( check_in_inner_boundaries(arrivalVol,x+dispX,y+dispY,t+dispT,params) && (!check_is_occluded(occVol, x+dispX, y+dispY, t+dispT)) && (!check_already_used_patch( dispField, x, y, t, dispX, dispY, dispT))) minVector[1] = ssd_patch_measure(departVol, arrivalVol, dispField,occVol,x,y,t,x+dispX,y+dispY,t+dispT,minError,params); dispX = (int)dispField->get_value(x,y,(int)min_int(t+1,(departVol->tSize)-1),0); dispY = (int)dispField->get_value(x,y,(int)min_int(t+1,(departVol->tSize)-1),1); dispT = (int)dispField->get_value(x,y,(int)min_int(t+1,(departVol->tSize)-1),2); if ( check_in_inner_boundaries(arrivalVol,x+dispX,y+dispY,t+dispT,params) && (!check_is_occluded(occVol, x+dispX, y+dispY, t+dispT)) && (!check_already_used_patch( dispField, x, y, t, dispX, dispY, dispT))) minVector[2] = ssd_patch_measure(departVol, arrivalVol,dispField,occVol,x,y,t,x+dispX,y+dispY,t+dispT,minError,params); for (i=0;i<NDIMS;i++) { if (minVector[i] == -1) continue; if ( minVector[i] < minVal) { switch (i){ case 0 : coordDispX = (int)dispField->get_value(min_int(x+1,((int)dispField->xSize)-1),y,t,0); coordDispY = (int)dispField->get_value(min_int(x+1,((int)dispField->xSize)-1),y,t,1); coordDispT = (int)dispField->get_value(min_int(x+1,((int)dispField->xSize)-1),y,t,2); // // if ( check_in_inner_boundaries(arrivalVol,x+coordDispX,y+coordDispY,t+coordDispT,params) && // // (!check_is_occluded(occVol, x+coordDispX, y+coordDispY, t+coordDispT)) && // // check_min_shift_distance(coordDispX, coordDispY, coordDispT,params)) // // { minVal = minVector[i]; *correctInd = 0; // } break; case 1 : coordDispX = (int)dispField->get_value(x,min_int(y+1,((int)dispField->ySize)-1),t,0); coordDispY = (int)dispField->get_value(x,min_int(y+1,((int)dispField->ySize)-1),t,1); coordDispT = (int)dispField->get_value(x,min_int(y+1,((int)dispField->ySize)-1),t,2); // // if ( check_in_inner_boundaries(arrivalVol,x+coordDispX,y+coordDispY,t+coordDispT,params) && // // (!check_is_occluded(occVol, x+coordDispX, y+coordDispY, t+coordDispT)) && // // check_min_shift_distance(coordDispX, coordDispY, coordDispT,params)) // // { minVal = minVector[i]; *correctInd = 1; // } break; case 2 : coordDispX = (int)dispField->get_value(x,y,min_int(t+1,((int)dispField->tSize)-1),0); coordDispY = (int)dispField->get_value(x,y,min_int(t+1,((int)dispField->tSize)-1),1); coordDispT = (int)dispField->get_value(x,y,min_int(t+1,((int)dispField->tSize)-1),2); // // if ( check_in_inner_boundaries(arrivalVol,x+coordDispX,y+coordDispY,t+coordDispT,params) && // // (!check_is_occluded(occVol, x+coordDispX, y+coordDispY, t+coordDispT)) && // // check_min_shift_distance(coordDispX, coordDispY, coordDispT,params)) // // { minVal = minVector[i]; *correctInd = 2; // } break; default : MY_PRINTF("Error in get_min_correct_error. The index i : %d is above 3.\n",i); } } } } if ( (*correctInd) == -1) //if none of the displacements are valid { minVal = -1; } return(minVal); }
48.378462
251
0.580233
[ "vector" ]
2cddb7c37d71b0bd47158501176591214dd1171a
7,327
cpp
C++
plugins/flowvis/src/flowvis.cpp
UniStuttgart-VISUS/implicit-topology
a7e0d5dd7253264e9feb2ae3d4dd44db5321d3e5
[ "BSD-3-Clause" ]
2
2020-10-16T10:15:37.000Z
2021-01-21T13:06:00.000Z
plugins/flowvis/src/flowvis.cpp
UniStuttgart-VISUS/implicit-topology
a7e0d5dd7253264e9feb2ae3d4dd44db5321d3e5
[ "BSD-3-Clause" ]
null
null
null
plugins/flowvis/src/flowvis.cpp
UniStuttgart-VISUS/implicit-topology
a7e0d5dd7253264e9feb2ae3d4dd44db5321d3e5
[ "BSD-3-Clause" ]
1
2021-01-28T01:19:54.000Z
2021-01-28T01:19:54.000Z
/* * flowvis.cpp * Copyright (C) 2018-2019 by MegaMol Team * Alle Rechte vorbehalten. */ #include "stdafx.h" #include "flowvis/flowvis.h" #include "mmcore/api/MegaMolCore.std.h" #include "mmcore/utility/plugins/Plugin200Instance.h" #include "mmcore/versioninfo.h" #include "vislib/vislibversion.h" #include "clip_plane.h" #include "critical_points.h" #include "extract_model_matrix.h" #include "glyph_data_reader.h" #include "implicit_topology.h" #include "implicit_topology_reader.h" #include "implicit_topology_writer.h" #include "line_strip.h" #include "periodic_orbits.h" #include "periodic_orbits_theisel.h" #include "stl_data_source.h" #include "streamlines_2d.h" #include "vector_field_reader.h" #include "draw_texture_3d.h" #include "draw_to_texture.h" #include "glyph_renderer_2d.h" #include "render_to_file.h" #include "triangle_mesh_renderer_2d.h" #include "triangle_mesh_renderer_3d.h" #include "glyph_data_call.h" #include "implicit_topology_call.h" #include "matrix_call.h" #include "mesh_data_call.h" #include "mouse_click_call.h" #include "triangle_mesh_call.h" #include "vector_field_call.h" /* anonymous namespace hides this type from any other object files */ namespace { /** Implementing the instance class of this plugin */ class plugin_instance : public ::megamol::core::utility::plugins::Plugin200Instance { public: /** ctor */ plugin_instance(void) : ::megamol::core::utility::plugins::Plugin200Instance( /* machine-readable plugin assembly name */ "flowvis", /* human-readable plugin description */ "Plugin for flow visualization") { // here we could perform addition initialization }; /** Dtor */ virtual ~plugin_instance(void) { // here we could perform addition de-initialization } /** Registers modules and calls */ virtual void registerClasses(void) { // register modules here: this->module_descriptions.RegisterAutoDescription<megamol::flowvis::clip_plane>(); this->module_descriptions.RegisterAutoDescription<megamol::flowvis::critical_points>(); this->module_descriptions.RegisterAutoDescription<megamol::flowvis::extract_model_matrix>(); this->module_descriptions.RegisterAutoDescription<megamol::flowvis::glyph_data_reader>(); this->module_descriptions.RegisterAutoDescription<megamol::flowvis::implicit_topology>(); this->module_descriptions.RegisterAutoDescription<megamol::flowvis::implicit_topology_reader>(); this->module_descriptions.RegisterAutoDescription<megamol::flowvis::implicit_topology_writer>(); this->module_descriptions.RegisterAutoDescription<megamol::flowvis::line_strip>(); this->module_descriptions.RegisterAutoDescription<megamol::flowvis::periodic_orbits>(); this->module_descriptions.RegisterAutoDescription<megamol::flowvis::periodic_orbits_theisel>(); this->module_descriptions.RegisterAutoDescription<megamol::flowvis::stl_data_source>(); this->module_descriptions.RegisterAutoDescription<megamol::flowvis::streamlines_2d>(); this->module_descriptions.RegisterAutoDescription<megamol::flowvis::vector_field_reader>(); // register renderer here: this->module_descriptions.RegisterAutoDescription<megamol::flowvis::draw_texture_3d>(); this->module_descriptions.RegisterAutoDescription<megamol::flowvis::draw_to_texture>(); this->module_descriptions.RegisterAutoDescription<megamol::flowvis::glyph_renderer_2d>(); this->module_descriptions.RegisterAutoDescription<megamol::flowvis::render_to_file>(); this->module_descriptions.RegisterAutoDescription<megamol::flowvis::triangle_mesh_renderer_2d>(); this->module_descriptions.RegisterAutoDescription<megamol::flowvis::triangle_mesh_renderer_3d>(); // register calls here: this->call_descriptions.RegisterAutoDescription<megamol::flowvis::glyph_data_call>(); this->call_descriptions.RegisterAutoDescription<megamol::flowvis::implicit_topology_reader_call>(); this->call_descriptions.RegisterAutoDescription<megamol::flowvis::implicit_topology_writer_call>(); this->call_descriptions.RegisterAutoDescription<megamol::flowvis::matrix_call>(); this->call_descriptions.RegisterAutoDescription<megamol::flowvis::mesh_data_call>(); this->call_descriptions.RegisterAutoDescription<megamol::flowvis::mouse_click_call>(); this->call_descriptions.RegisterAutoDescription<megamol::flowvis::triangle_mesh_call>(); this->call_descriptions.RegisterAutoDescription<megamol::flowvis::vector_field_call>(); } MEGAMOLCORE_PLUGIN200UTIL_IMPLEMENT_plugininstance_connectStatics }; } /* * mmplgPluginAPIVersion */ FLOWVIS_API int mmplgPluginAPIVersion(void) { MEGAMOLCORE_PLUGIN200UTIL_IMPLEMENT_mmplgPluginAPIVersion } /* * mmplgGetPluginCompatibilityInfo */ FLOWVIS_API ::megamol::core::utility::plugins::PluginCompatibilityInfo * mmplgGetPluginCompatibilityInfo( ::megamol::core::utility::plugins::ErrorCallback onError) { // compatibility information with core and vislib using ::megamol::core::utility::plugins::PluginCompatibilityInfo; using ::megamol::core::utility::plugins::LibraryVersionInfo; PluginCompatibilityInfo *ci = new PluginCompatibilityInfo; ci->libs_cnt = 2; ci->libs = new LibraryVersionInfo[2]; SetLibraryVersionInfo(ci->libs[0], "MegaMolCore", MEGAMOL_CORE_MAJOR_VER, MEGAMOL_CORE_MINOR_VER, MEGAMOL_CORE_COMP_REV, 0 #if defined(DEBUG) || defined(_DEBUG) | MEGAMOLCORE_PLUGIN200UTIL_FLAGS_DEBUG_BUILD #endif #if defined(MEGAMOL_CORE_DIRTY) && (MEGAMOL_CORE_DIRTY != 0) | MEGAMOLCORE_PLUGIN200UTIL_FLAGS_DIRTY_BUILD #endif ); SetLibraryVersionInfo(ci->libs[1], "vislib", vislib::VISLIB_VERSION_MAJOR, vislib::VISLIB_VERSION_MINOR, vislib::VISLIB_VERSION_REVISION, 0 #if defined(DEBUG) || defined(_DEBUG) | MEGAMOLCORE_PLUGIN200UTIL_FLAGS_DEBUG_BUILD #endif #if defined(VISLIB_DIRTY_BUILD) && (VISLIB_DIRTY_BUILD != 0) | MEGAMOLCORE_PLUGIN200UTIL_FLAGS_DIRTY_BUILD #endif ); // // If you want to test additional compatibilties, add the corresponding versions here // return ci; } /* * mmplgReleasePluginCompatibilityInfo */ FLOWVIS_API void mmplgReleasePluginCompatibilityInfo( ::megamol::core::utility::plugins::PluginCompatibilityInfo* ci) { // release compatiblity data on the correct heap MEGAMOLCORE_PLUGIN200UTIL_IMPLEMENT_mmplgReleasePluginCompatibilityInfo(ci) } /* * mmplgGetPluginInstance */ FLOWVIS_API ::megamol::core::utility::plugins::AbstractPluginInstance* mmplgGetPluginInstance( ::megamol::core::utility::plugins::ErrorCallback onError) { MEGAMOLCORE_PLUGIN200UTIL_IMPLEMENT_mmplgGetPluginInstance(plugin_instance, onError) } /* * mmplgReleasePluginInstance */ FLOWVIS_API void mmplgReleasePluginInstance( ::megamol::core::utility::plugins::AbstractPluginInstance* pi) { MEGAMOLCORE_PLUGIN200UTIL_IMPLEMENT_mmplgReleasePluginInstance(pi) }
39.181818
111
0.736864
[ "object" ]
2cdf3bb8132c3a35f05948d84355a4455cb30736
3,667
cpp
C++
client/ogre/src/window_ogre.cpp
qiujiangkun/Escape
c7238f7770271291a65e1f2f5682ac7bb3af1482
[ "MIT" ]
1
2020-02-21T08:27:17.000Z
2020-02-21T08:27:17.000Z
client/ogre/src/window_ogre.cpp
qiujiangkun/Escape
c7238f7770271291a65e1f2f5682ac7bb3af1482
[ "MIT" ]
null
null
null
client/ogre/src/window_ogre.cpp
qiujiangkun/Escape
c7238f7770271291a65e1f2f5682ac7bb3af1482
[ "MIT" ]
1
2020-03-24T04:49:13.000Z
2020-03-24T04:49:13.000Z
// // Created by jack on 20-2-25. // #include "window_ogre.h" using namespace Escape; bool InputState::keyPressed(const OgreBites::KeyboardEvent &evt) { if(evt.keysym.sym < MAX_KEY_NUM) keys[evt.keysym.sym] = true; else { // std::cerr << "Cannot handle key down " << evt.keysym.sym << std::endl; } return false; } void InputState::frameRendered(const Ogre::FrameEvent &evt) {} bool InputState::keyReleased(const OgreBites::KeyboardEvent &evt) { if(evt.keysym.sym < MAX_KEY_NUM) keys[evt.keysym.sym] = false; else { // std::cerr << "Cannot handle key up " << evt.keysym.sym << std::endl; } return false; } bool InputState::touchMoved(const OgreBites::TouchFingerEvent &evt) { return false; } bool InputState::touchPressed(const OgreBites::TouchFingerEvent &evt) { return false; } bool InputState::touchReleased(const OgreBites::TouchFingerEvent &evt) { return false; } bool InputState::mouseMoved(const OgreBites::MouseMotionEvent &evt) { mouse_x = evt.x; mouse_y = evt.y; return false; } bool InputState::mouseWheelRolled(const OgreBites::MouseWheelEvent &evt) { return false; } bool InputState::mousePressed(const OgreBites::MouseButtonEvent &evt) { mouse_x = evt.x; mouse_y = evt.y; mouse[evt.button] = true; return false; } bool InputState::mouseReleased(const OgreBites::MouseButtonEvent &evt) { mouse_x = evt.x; mouse_y = evt.y; mouse[evt.button] = false; return false; } bool InputState::textInput(const OgreBites::TextInputEvent &evt) { return false; } WindowOgre::WindowOgre(const std::string &title, int width, int height) : Window(title, width, height), OgreBites::ApplicationContext(title) { running = true; // TODO set window size initApp(); addInputListener(&input); } void WindowOgre::processInput() { if (input.keys[OgreBites::SDLK_ESCAPE]) stop(); } void WindowOgre::update(float delta) { this->delta = delta; processInput(); render(); root->renderOneFrame(delta); postProcess(); } void WindowOgre::render() { } void WindowOgre::postProcess() { } void WindowOgre::stop() { closed = true; } bool WindowOgre::isRunning() { return !closed && !root->endRenderingQueued(); } WindowOgre::~WindowOgre() { closeApp(); } void WindowOgre::windowResized(Ogre::RenderWindow *rw) { unsigned int width, height, depth; rw->getMetrics(width, height, depth); windowResized((int)width, (int)height); } void WindowOgre::windowResized(int width, int height) { Window::windowResized(width, height); } void WindowOgre::setup() { OgreBites::ApplicationContext::setup(); root = getRoot(); scnMgr = root->createSceneManager(); Ogre::RTShader::ShaderGenerator *shadergen = Ogre::RTShader::ShaderGenerator::getSingletonPtr(); shadergen->addSceneManager(scnMgr); Ogre::Light *light = scnMgr->createLight("MainLight"); light->setType(Ogre::Light::LT_DIRECTIONAL); Ogre::SceneNode *lightNode = scnMgr->getRootSceneNode()->createChildSceneNode(); lightNode->setPosition(0, 0, 100); lightNode->attachObject(light); camNode = scnMgr->getRootSceneNode()->createChildSceneNode(); camNode->setPosition(0, 0, 100); camNode->lookAt(Ogre::Vector3(0, 0, 0), Ogre::Node::TS_PARENT); cam = scnMgr->createCamera("myCam"); cam->setNearClipDistance(5); // specific to this sample cam->setAutoAspectRatio(true); cam->setProjectionType(Ogre::PT_ORTHOGRAPHIC); cam->setOrthoWindowHeight(50); camNode->attachObject(cam); // and tell it to render into the main window getRenderWindow()->addViewport(cam); }
27.571429
140
0.686392
[ "render" ]
2ce31a54e97ceb590e3f5ff32418a7c86ff34ecc
5,447
cpp
C++
test/src/3d/scene/renderer3d/lighting/shadow/light/LightSplitShadowMapTest.cpp
petitg1987/urchinEngine
a14a57ac49a19237d748d2eafc7c2a38a45b95d6
[ "BSL-1.0" ]
18
2020-06-12T00:04:46.000Z
2022-01-11T14:56:19.000Z
test/src/3d/scene/renderer3d/lighting/shadow/light/LightSplitShadowMapTest.cpp
petitg1987/urchinEngine
a14a57ac49a19237d748d2eafc7c2a38a45b95d6
[ "BSL-1.0" ]
null
null
null
test/src/3d/scene/renderer3d/lighting/shadow/light/LightSplitShadowMapTest.cpp
petitg1987/urchinEngine
a14a57ac49a19237d748d2eafc7c2a38a45b95d6
[ "BSL-1.0" ]
6
2020-08-16T15:58:41.000Z
2022-03-05T13:17:50.000Z
#include <cppunit/TestSuite.h> #include <cppunit/TestCaller.h> #include <3d/scene/renderer3d/lighting/shadow/light/LightSplitShadowMapTest.h> #include <AssertHelper.h> using namespace urchin; void LightSplitShadowMapTest::modelsInFrustumSplit() { auto modelOctreeManager = buildModelOctreeManager({ Point3<float>(1.0f, 2.0f, -3.0f), Point3<float>(1.0f, 2.0f, -10.0f) }); auto light = std::make_unique<SunLight>(Vector3<float>(1.0f, 0.0f, 0.0f)); auto lightShadowMap = std::make_unique<LightShadowMap>(*light, *modelOctreeManager, 300.0f, nullptr, 3, nullptr); auto lightSplitShadowMap = lightShadowMap->addLightSplitShadowMap(); Frustum<float> frustumSplit(90.0f, 1.0f, 0.01f, 100.0f); lightSplitShadowMap.update(frustumSplit, false); AssertHelper::assertUnsignedIntEquals(lightSplitShadowMap.getModels().size(), 2); AssertHelper::assertPoint3FloatEquals(lightSplitShadowMap.getShadowCasterReceiverBox().getMin(), Point3<float>(-10.5f, 1.5f, -101.0f) - LightSplitShadowMap::LIGHT_BOX_MARGIN, std::numeric_limits<float>::epsilon()); AssertHelper::assertPoint3FloatEquals(lightSplitShadowMap.getShadowCasterReceiverBox().getMax(), Point3<float>(-2.5f, 2.5f, -1.5f) + LightSplitShadowMap::LIGHT_BOX_MARGIN, std::numeric_limits<float>::epsilon()); } void LightSplitShadowMapTest::modelsOutsideFrustumSplit() { auto modelOctreeManager = buildModelOctreeManager({ Point3<float>(1.0f, 2.0f, -110.0f), //model not visible and doesn't produce shadow in the frustum split Point3<float>(-500.0f, 2.0f, -3.0f), //model not visible and too far to produce shadow in the frustum split Point3<float>(500.0f, 2.0f, -3.0f), //model not visible and in the wrong direction to produce shadow in the frustum split }); auto light = std::make_unique<SunLight>(Vector3<float>(1.0f, 0.0f, 0.0f)); auto lightShadowMap = std::make_unique<LightShadowMap>(*light, *modelOctreeManager, 300.0f, nullptr, 3, nullptr); auto lightSplitShadowMap = lightShadowMap->addLightSplitShadowMap(); Frustum<float> frustumSplit(90.0f, 1.0f, 0.01f, 100.0f); lightSplitShadowMap.update(frustumSplit, false); AssertHelper::assertUnsignedIntEquals(lightSplitShadowMap.getModels().size(), 0); AssertHelper::assertPoint3FloatEquals(lightSplitShadowMap.getShadowCasterReceiverBox().getMin(), Point3<float>(0.0f, 0.0f, 0.0f) - LightSplitShadowMap::LIGHT_BOX_MARGIN, std::numeric_limits<float>::epsilon()); AssertHelper::assertPoint3FloatEquals(lightSplitShadowMap.getShadowCasterReceiverBox().getMax(), Point3<float>(0.0f, 0.0f, 0.0f) + LightSplitShadowMap::LIGHT_BOX_MARGIN, std::numeric_limits<float>::epsilon()); } void LightSplitShadowMapTest::modelOutsideFrustumProducingShadow() { auto modelOctreeManager = buildModelOctreeManager({ Point3<float>(-250.0f, 2.0f, -3.0f), //model not visible but produces shadow in the frustum split }); auto light = std::make_unique<SunLight>(Vector3<float>(1.0f, 0.0f, 0.0f)); auto lightShadowMap = std::make_unique<LightShadowMap>(*light, *modelOctreeManager, 300.0f, nullptr, 3, nullptr); auto lightSplitShadowMap = lightShadowMap->addLightSplitShadowMap(); Frustum<float> frustumSplit(90.0f, 1.0f, 0.01f, 100.0f); lightSplitShadowMap.update(frustumSplit, false); AssertHelper::assertUnsignedIntEquals(lightSplitShadowMap.getModels().size(), 1); AssertHelper::assertPoint3FloatEquals(lightSplitShadowMap.getShadowCasterReceiverBox().getMin(), Point3<float>(-3.5f, 1.5f, -101.0f) - LightSplitShadowMap::LIGHT_BOX_MARGIN, std::numeric_limits<float>::epsilon()); AssertHelper::assertPoint3FloatEquals(lightSplitShadowMap.getShadowCasterReceiverBox().getMax(), Point3<float>(-2.5f, 2.5f, 249.5f) + LightSplitShadowMap::LIGHT_BOX_MARGIN, std::numeric_limits<float>::epsilon()); } std::unique_ptr<OctreeManager<Model>> LightSplitShadowMapTest::buildModelOctreeManager(const std::vector<Point3<float>> &modelPositions) { auto modelOctreeManager = std::make_unique<OctreeManager<Model>>(10.0f); for (const auto& modelPosition : modelPositions) { auto model = Model::fromMeshesFile(""); //default model size: 1.0 x 1.0 x 1.0 model->setPosition(modelPosition); modelOctreeManager->addOctreeable(std::move(model)); } return modelOctreeManager; } CppUnit::Test* LightSplitShadowMapTest::suite() { auto* suite = new CppUnit::TestSuite("ShadowManagerTest"); suite->addTest(new CppUnit::TestCaller<LightSplitShadowMapTest>("modelsInFrustumSplit", &LightSplitShadowMapTest::modelsInFrustumSplit)); suite->addTest(new CppUnit::TestCaller<LightSplitShadowMapTest>("modelsOutsideFrustumSplit", &LightSplitShadowMapTest::modelsOutsideFrustumSplit)); suite->addTest(new CppUnit::TestCaller<LightSplitShadowMapTest>("modelOutsideFrustumProducingShadow", &LightSplitShadowMapTest::modelOutsideFrustumProducingShadow)); return suite; }
59.206522
169
0.685331
[ "vector", "model", "3d" ]
2ce3d44a047e61a23a7f0a1b3c9cb266b4199a25
9,210
cc
C++
arcane/src/arcane/mesh/ItemConnectivitySynchronizer.cc
cedricga91/framework
143eeccb5bf375df4a3f11b888681f84f60380c6
[ "Apache-2.0" ]
16
2021-09-20T12:37:01.000Z
2022-03-18T09:19:14.000Z
arcane/src/arcane/mesh/ItemConnectivitySynchronizer.cc
cedricga91/framework
143eeccb5bf375df4a3f11b888681f84f60380c6
[ "Apache-2.0" ]
66
2021-09-17T13:49:39.000Z
2022-03-30T16:24:07.000Z
arcane/src/arcane/mesh/ItemConnectivitySynchronizer.cc
cedricga91/framework
143eeccb5bf375df4a3f11b888681f84f60380c6
[ "Apache-2.0" ]
11
2021-09-27T16:48:55.000Z
2022-03-23T19:06:56.000Z
// -*- tab-width: 2; indent-tabs-mode: nil; coding: utf-8-with-signature -*- //----------------------------------------------------------------------------- // Copyright 2000-2022 CEA (www.cea.fr) IFPEN (www.ifpenergiesnouvelles.com) // See the top-level COPYRIGHT file for details. // SPDX-License-Identifier: Apache-2.0 //----------------------------------------------------------------------------- /*---------------------------------------------------------------------------*/ /* ItemConnectivitySynchronizer.cc (C) 2000-2021 */ /* */ /* Synchronization des connectivités. */ /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ #include "arcane/mesh/ItemConnectivitySynchronizer.h" #include "arcane/mesh/IItemConnectivityGhostPolicy.h" #include <algorithm> /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ namespace Arcane { /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ ItemConnectivitySynchronizer:: ItemConnectivitySynchronizer(IItemConnectivity* connectivity, IItemConnectivityGhostPolicy* ghost_policy) : m_connectivity(connectivity) , m_ghost_policy(ghost_policy) , m_parallel_mng(m_connectivity->targetFamily()->mesh()->parallelMng()) , m_added_ghost(m_parallel_mng->commSize()) { } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void ItemConnectivitySynchronizer:: synchronize() { // Compute ghost element for ToFamily mesh::ExtraGhostItemsManager extra_ghost_mng(this); extra_ghost_mng.addExtraGhostItemsBuilder(this); extra_ghost_mng.computeExtraGhostItems(); } void ItemConnectivitySynchronizer:: computeExtraItemsToSend() { // Get, for each rank k, ToFamily item that have to be shared with rank k, the m_data_to_send.clear(); Int32ConstArrayView ranks = m_ghost_policy->communicatingRanks(); m_data_to_send.resize(m_parallel_mng->commSize()); const Int32 my_rank = m_parallel_mng->commRank(); for (Integer i = 0; i < ranks.size(); ++i){ Integer rank = ranks[i]; Int32Array& data_to_send = m_data_to_send[rank]; Int32SharedArray shared_items = m_ghost_policy->sharedItems(rank,m_connectivity->targetFamily()->name()); Int32SharedArray shared_items_connected_items = m_ghost_policy->sharedItemsConnectedItems(rank,m_connectivity->sourceFamily()->name()); _getItemToSend(shared_items,shared_items_connected_items, rank); data_to_send.add(shared_items.size()); data_to_send.addRange(shared_items); data_to_send.addRange(shared_items_connected_items); data_to_send.addRange(my_rank,shared_items.size()); // shared item owner } } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void ItemConnectivitySynchronizer:: serializeGhostItems(ISerializer* buffer,Int32ConstArrayView ghost_item_info) { // Treat ghost item info : split into item_uids, nb_dof_per_item, dof_uids Integer nb_shared_item = ghost_item_info[0]; Int32ConstArrayView shared_item_lids = ghost_item_info.subConstView(1,nb_shared_item); Int32ConstArrayView shared_item_connected_item_lids = ghost_item_info.subConstView(nb_shared_item+1,nb_shared_item); Int32ConstArrayView shared_item_owners = ghost_item_info.subConstView(2*nb_shared_item+1,nb_shared_item); // Convert in uids (items must belong to current process) Int64SharedArray shared_item_uids(nb_shared_item); Int64SharedArray shared_item_connected_item_uids(nb_shared_item); Integer i = 0, j= 0; ENUMERATE_ITEM(item,m_connectivity->targetFamily()->view(shared_item_lids)){ shared_item_uids[i++] = item->uniqueId().asInt64(); } ENUMERATE_ITEM(item,m_connectivity->sourceFamily()->view(shared_item_connected_item_lids)){ shared_item_connected_item_uids[j++] = item->uniqueId().asInt64(); } // Serialize item_uid, nb_dof, shared_item_connected_item_uids buffer->setMode(ISerializer::ModeReserve); buffer->reserve(DT_Int64,1); buffer->reserveSpan(shared_item_uids); buffer->reserveSpan(shared_item_connected_item_uids); buffer->reserveSpan(shared_item_owners); buffer->allocateBuffer(); buffer->setMode(ISerializer::ModePut); buffer->putInt64(nb_shared_item); buffer->putSpan(shared_item_uids); buffer->putSpan(shared_item_connected_item_uids); buffer->putSpan(shared_item_owners); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void ItemConnectivitySynchronizer:: addExtraGhostItems (ISerializer* buffer) { // Deserialiser le buffer et faire un addGhost classique, puis faire la connexion grace a l'item property buffer->setMode(ISerializer::ModeGet); Int64 nb_shared_items = buffer->getInt64(); Int64SharedArray shared_item_uids(nb_shared_items); Int64SharedArray shared_item_connected_items_uids(nb_shared_items); Int32SharedArray shared_items_owners(nb_shared_items); buffer->getSpan(shared_item_uids); buffer->getSpan(shared_item_connected_items_uids); buffer->getSpan(shared_items_owners); // Remove possible repetition in shared_items and impact owners. Necessary to add these items in the family Int64SharedArray shared_item_uids_to_add(shared_item_uids); IntegerSharedArray shared_item_owners_to_add(shared_items_owners); _removeDuplicatedValues(shared_item_uids_to_add,shared_item_owners_to_add); // Add shared items Int32SharedArray shared_item_lids_added(shared_item_uids_to_add.size()); m_connectivity->targetFamily()->addGhostItems(shared_item_uids_to_add,shared_item_lids_added,shared_item_owners_to_add); m_connectivity->targetFamily()->endUpdate(); // update connectivity Int32SharedArray shared_item_lids(nb_shared_items); bool do_fatal = true; // shared_items have been adde to the family m_connectivity->targetFamily() ->itemsUniqueIdToLocalId(shared_item_lids,shared_item_uids,do_fatal); // shared_item_connected_item are not compulsory present on the new subdomain where shared_items have been send. // Send shared_item_connected_items_uids to GhostPolicy where they will be handled (possibly converted to lid if they are present). m_ghost_policy->updateConnectivity(shared_item_lids,shared_item_connected_items_uids); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void ItemConnectivitySynchronizer:: _getItemToSend(Int32SharedArray& shared_items, Int32SharedArray& shared_items_connected_items, const Integer rank) { // Filter: don't add ghost twice. The synchronizer remember the ghost added and don't add them twice. Int64SharedArray shared_items_uids(shared_items.size()); ItemVectorView shared_items_view = m_connectivity->targetFamily()->view(shared_items); for (Integer i = 0; i < shared_items_view.size(); ++i) shared_items_uids[i] = shared_items_view[i].uniqueId().asInt64(); std::set<Int64>& added_ghost = m_added_ghost[rank]; // reverse order to handle index changes due to remove for (Integer i = shared_items_uids.size()-1; i >=0 ; --i ){ if (!added_ghost.insert(shared_items_uids[i]).second){ // check if already added ghost shared_items.remove(i); shared_items_connected_items.remove(i); } } } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void ItemConnectivitySynchronizer:: _removeDuplicatedValues(Int64SharedArray& shared_item_uids, IntegerSharedArray& shared_item_owners) { // Reverse order for the loop : otherwise wrong !! (since elements are removed and thus index are modified) std::set<Int64> shared_uids_set; for (Integer i = shared_item_uids.size()-1; i >= 0 ; --i){ if (! shared_uids_set.insert(shared_item_uids[i]).second){ // element already in the set, remove it from both arrays. shared_item_uids.remove(i); shared_item_owners.remove(i); } } } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ ISubDomain* ItemConnectivitySynchronizer:: subDomain() { return m_connectivity->targetFamily()->mesh()->subDomain(); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ } // End namespace Arcane /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/
44.926829
139
0.600651
[ "mesh" ]
2ce6a0f806e21aa4be05bb05e5ed4a9062a4a29b
8,927
cpp
C++
tests/opt_ext_test.cpp
alessandro90/cpputils
45ebd28be73cabc3a38f09cfc08779f72f518772
[ "MIT" ]
null
null
null
tests/opt_ext_test.cpp
alessandro90/cpputils
45ebd28be73cabc3a38f09cfc08779f72f518772
[ "MIT" ]
3
2022-02-26T23:37:11.000Z
2022-03-13T17:48:03.000Z
tests/opt_ext_test.cpp
alessandro90/cpputils
45ebd28be73cabc3a38f09cfc08779f72f518772
[ "MIT" ]
null
null
null
#include "catch2/catch_test_macros.hpp" #include "cpputils/functional/opt_ext.hpp" #include <memory> #include <optional> #include <tuple> using namespace cpputils; namespace { using intopt = std::optional<int>; auto const increment = [](int i) -> int { return i + 1; }; auto const sum = [](int a, int b) -> int { return a + b; }; auto const increment_opt = [](int i) -> intopt { return {i + 1}; }; auto const sum_opt = [](int a, int b) -> intopt { return {a + b}; }; auto const return_v = [](int v) { return [v]() { return v; }; }; auto const increase = [](auto &...vs) { (++vs, ...); }; auto const increase_ref = [](int &v) { return [&v]() { ++v; }; }; } // namespace TEST_CASE("opt test", "[map]") { // NOLINT { auto const out = map(increment, intopt{}); REQUIRE(!out.has_value()); } { auto const out = map(increment, intopt{0}); REQUIRE(out.has_value()); REQUIRE(out.value() == 1); } { auto const out = map(sum, intopt{}, intopt{1}); REQUIRE(!out.has_value()); } { auto const out = map(sum, intopt{1}, intopt{}); REQUIRE(!out.has_value()); } { auto const out = map(sum, intopt{}, intopt{}); REQUIRE(!out.has_value()); } { auto const out = map(sum, intopt{1}, intopt{2}); REQUIRE(out.has_value()); REQUIRE(out.value() == 3); } // { auto const out = map(increment_opt, intopt{}); REQUIRE(!out.has_value()); } { auto const out = map(increment_opt, intopt{0}); REQUIRE(out.has_value()); REQUIRE(out.value() == 1); } { auto const out = map(sum_opt, intopt{}, intopt{1}); REQUIRE(!out.has_value()); } { auto const out = map(sum_opt, intopt{1}, intopt{}); REQUIRE(!out.has_value()); } { auto const out = map(sum_opt, intopt{}, intopt{}); REQUIRE(!out.has_value()); } { auto const out = map(sum_opt, intopt{1}, intopt{2}); REQUIRE(out.has_value()); REQUIRE(out.value() == 3); } } TEST_CASE("opt test", "[try_or]") { // NOLINT { auto const out = try_or(increment, 0, intopt{}); REQUIRE(out == 0); } { auto const out = try_or(increment, 0, intopt{1}); REQUIRE(out == 2); } { auto const out = try_or(sum, -1, intopt{}, intopt{}); REQUIRE(out == -1); } { auto const out = try_or(sum, -1, intopt{}, intopt{0}); REQUIRE(out == -1); } { auto const out = try_or(sum, -1, intopt{0}, intopt{}); REQUIRE(out == -1); } { auto const out = try_or(sum, -1, intopt{1}, intopt{1}); REQUIRE(out == 2); } } TEST_CASE("opt test", "[try_or_else]") { // NOLINT { auto const out = try_or_else(increment, return_v(0), intopt{}); REQUIRE(out == 0); } { auto const out = try_or_else(increment, return_v(0), intopt{1}); REQUIRE(out == 2); } { auto const out = try_or_else(sum, return_v(-1), intopt{}, intopt{}); REQUIRE(out == -1); } { auto const out = try_or_else(sum, return_v(-1), intopt{}, intopt{0}); REQUIRE(out == -1); } { auto const out = try_or_else(sum, return_v(-1), intopt{0}, intopt{}); REQUIRE(out == -1); } { auto const out = try_or_else(sum, return_v(-1), intopt{1}, intopt{1}); REQUIRE(out == 2); } } TEST_CASE("opt test", "[apply]") { // NOLINT { intopt a{}; intopt b{}; apply(increase, a, b); REQUIRE(!a.has_value()); REQUIRE(!b.has_value()); } { intopt a{0}; intopt b{}; apply(increase, a, b); REQUIRE(a.has_value()); REQUIRE(a.value() == 0); REQUIRE(!b.has_value()); } { intopt a{}; intopt b{0}; apply(increase, a, b); REQUIRE(!a.has_value()); REQUIRE(b.has_value()); REQUIRE(b.value() == 0); } { intopt a{1}; intopt b{2}; apply(increase, a, b); REQUIRE(a.has_value()); REQUIRE(b.has_value()); REQUIRE(a.value() == 2); REQUIRE(b.value() == 3); } { intopt a{1}; intopt b{2}; intopt c{10}; apply(increase, a, b, c); REQUIRE(a.has_value()); REQUIRE(b.has_value()); REQUIRE(c.has_value()); REQUIRE(a.value() == 2); REQUIRE(c.value() == 11); } } TEST_CASE("opt test", "[apply_or_else]") { // NOLINT { intopt a{}; intopt b{}; int v{}; apply_or_else(increase, increase_ref(v), a, b); REQUIRE(!a.has_value()); REQUIRE(!b.has_value()); REQUIRE(v == 1); } { intopt a{0}; intopt b{}; int v{}; apply_or_else(increase, increase_ref(v), a, b); REQUIRE(a.has_value()); REQUIRE(a.value() == 0); REQUIRE(!b.has_value()); REQUIRE(v == 1); } { intopt a{}; intopt b{0}; int v{}; apply_or_else(increase, increase_ref(v), a, b); REQUIRE(!a.has_value()); REQUIRE(b.has_value()); REQUIRE(b.value() == 0); REQUIRE(v == 1); } { intopt a{1}; intopt b{2}; int v{}; apply_or_else(increase, increase_ref(v), a, b); REQUIRE(a.has_value()); REQUIRE(b.has_value()); REQUIRE(a.value() == 2); REQUIRE(b.value() == 3); REQUIRE(v == 0); } { intopt a{1}; intopt b{2}; intopt c{10}; int v{}; apply_or_else(increase, increase_ref(v), a, b, c); REQUIRE(a.has_value()); REQUIRE(b.has_value()); REQUIRE(c.has_value()); REQUIRE(a.value() == 2); REQUIRE(c.value() == 11); REQUIRE(v == 0); } } TEST_CASE("opt test", "[transform]") { // NOLINT { auto const out = intopt{0} >> transform(increment) >> transform(increment_opt); REQUIRE(out.has_value()); REQUIRE(out.value() == 2); } { auto const out = intopt{} >> transform(increment) >> transform(increment_opt); REQUIRE(!out.has_value()); } { auto const out = intopt{0} >> transform(increment) >> transform([](int x) { if (x == 1) { return intopt{}; } return intopt{2}; }); REQUIRE(!out.has_value()); } } TEST_CASE("opt test", "[if_value]") { // NOLINT { intopt a{}; auto const &b = a >> if_value(increase); REQUIRE(!a.has_value()); REQUIRE(&a == &b); } { intopt a{0}; auto const &b = a >> if_value(increase); REQUIRE(a.has_value()); REQUIRE(a.value() == 1); REQUIRE(&a == &b); } } TEST_CASE("opt test", "[or_else]") { // NOLINT { intopt a{}; int v{}; auto const &b = a >> or_else(increase_ref(v)); REQUIRE(&a == &b); REQUIRE(v == 1); REQUIRE(!a.has_value()); } { intopt a{0}; int v{}; auto const &b = a >> or_else(increase_ref(v)); REQUIRE(&a == &b); REQUIRE(v == 0); REQUIRE(a.has_value()); REQUIRE(a.value() == 0); } } TEST_CASE("opt test", "[unwrap]") { // NOLINT { intopt a{}; try { std::ignore = a >> unwrap(); FAIL("You should not get here"); } catch (std::bad_optional_access const &) { SUCCEED(""); } } { intopt a{1}; auto const &v = a >> unwrap(); REQUIRE(&v == std::addressof(a.value())); } } TEST_CASE("opt test", "[unwrap_or]") { // NOLINT { intopt a{}; auto const b = a >> unwrap_or(1); REQUIRE(b == 1); } { intopt a{1}; auto const b = a >> unwrap_or(-1); REQUIRE(b == 1); } } TEST_CASE("opt test", "[unwrap_or_else]") { // NOLINT { intopt a{}; auto const b = a >> unwrap_or_else(return_v(1)); REQUIRE(b == 1); } { intopt a{1}; auto const b = a >> unwrap_or_else(return_v(-1)); REQUIRE(b == 1); } } TEST_CASE("opt test", "[to_optional]") { // NOLINT REQUIRE(to_optional(10) == std::optional{10}); STATIC_REQUIRE(std::is_same_v<decltype(to_optional(10)), std::optional<int>>); { auto const opt = std::optional{0}; auto const &opt2 = to_optional(opt); REQUIRE(&opt == &opt2); } { std::optional<int> opt{}; REQUIRE(to_optional(opt) == std::optional<int>{}); } }
25.005602
82
0.473059
[ "transform" ]
f8e6a42d899d407000deffebf767d14922818bcd
783
cpp
C++
feedback-set/lib/src/lib/env.cpp
hmtbgc/combopt-zero
458426d6396e9023805475948f77f58fad8ede9d
[ "MIT" ]
32
2020-05-03T09:51:05.000Z
2022-02-19T20:13:04.000Z
feedback-set/lib/src/lib/env.cpp
omosan0627/combopt-zero
3a40b477dd651933d1483c3c2d1592a4e93ebd8d
[ "MIT" ]
5
2020-06-02T12:57:47.000Z
2021-01-29T07:34:16.000Z
feedback-set/lib/src/lib/env.cpp
omosan0627/combopt-zero
3a40b477dd651933d1483c3c2d1592a4e93ebd8d
[ "MIT" ]
10
2020-06-30T18:29:31.000Z
2022-02-19T19:32:07.000Z
#include "env.h" #include <map> #include <utility> bool is_end(const Graph& g) { int n = g.num_nodes; UnionFind uf(n); for (auto& p : g.edge_list) { if (!uf.unite(p.first, p.second)) return false; } return true; } Graph step(const Graph& g, int action) { std::vector<std::pair<int, int>> edges; std::map<int, int> nodes; for (auto& p : g.edge_list) { int u = p.first, v = p.second; if (u == action || v == action) continue; edges.emplace_back(u, v); nodes[u]; nodes[v]; } int num_nodes = 0; for (auto& p : nodes) { p.second = num_nodes++; } Graph ret(num_nodes); for (auto& e : edges) { ret.add_edge(nodes[e.first], nodes[e.second]); } return ret; }
21.162162
55
0.538953
[ "vector" ]
f8e7666e93f7d6a89cbf941cd4dc0bfbcd9389b9
689
cpp
C++
LeetCode/Problems/Algorithms/#347_TopKFrequentElements_sol1_priority_queue_O(NlogK)_32ms_13.9MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
1
2022-01-26T14:50:07.000Z
2022-01-26T14:50:07.000Z
LeetCode/Problems/Algorithms/#347_TopKFrequentElements_sol1_priority_queue_O(NlogK)_32ms_13.9MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
LeetCode/Problems/Algorithms/#347_TopKFrequentElements_sol1_priority_queue_O(NlogK)_32ms_13.9MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
class Solution { public: vector<int> topKFrequent(vector<int>& nums, int k) { unordered_map<int, int> cnt; for(int num: nums){ cnt[num] += 1; } priority_queue<pair<int, int>> pq; for(int num: nums){ if(cnt.count(num)){ pq.push({-cnt[num], num}); if(pq.size() > k){ pq.pop(); } cnt.erase(num); } } vector<int> answer; while(!pq.empty()){ answer.push_back(pq.top().second); pq.pop(); } return answer; } };
24.607143
57
0.37881
[ "vector" ]
f8e854a83764397a8adbd6d44daa78b9b8023367
3,368
cc
C++
compiler/mcr_cc/llvm/asm_arm_thumb.cc
Paschalis/android-llvm
317f7fd4b736a0511a2273a2487915c34cf8933e
[ "Apache-2.0" ]
20
2021-06-24T16:38:42.000Z
2022-01-20T16:15:57.000Z
compiler/mcr_cc/llvm/asm_arm_thumb.cc
Paschalis/android-llvm
317f7fd4b736a0511a2273a2487915c34cf8933e
[ "Apache-2.0" ]
null
null
null
compiler/mcr_cc/llvm/asm_arm_thumb.cc
Paschalis/android-llvm
317f7fd4b736a0511a2273a2487915c34cf8933e
[ "Apache-2.0" ]
4
2021-11-03T06:01:12.000Z
2022-02-24T02:57:31.000Z
/** * Copyright (C) 2021 Paschalis Mpeis (paschalis.mpeis-AT-gmail.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. * */ #include "asm_arm_thumb.h" #include <llvm/IR/DerivedTypes.h> #include "arch/arm/registers_arm.h" #include "art_method.h" #include "ir_builder.h" #include "thread.h" #include "llvm_macros_irb.h" using namespace ::llvm; namespace art { namespace LLVM { namespace ArmThumb { void nop(IRBuilder* irb) { FunctionType* ty = FunctionType::get(irb->getVoidTy(), false); InlineAsm* nop = InlineAsm::get(ty, "nop;", "", true); irb->CreateCall(nop); } void SetThreadRegister(IRBuilder* irb, Value* thread_self) { std::vector<Type*> params{irb->getVoidPointerType()}; FunctionType *asmTy= FunctionType::get(irb->getVoidTy(), params, false); std::vector<Value*> args; args.push_back(thread_self); arm::Register thread_register = arm::Register::TR; std::stringstream ss; ss << "mov " << thread_register << ", $0"; D3LOG(INFO) << "SetThreadRegister: asm: " << ss.str(); InlineAsm* setR9 = InlineAsm:: get(asmTy, ss.str(), "r", false); irb->CreateCall(setR9, args); } Value* GetThreadRegister(IRBuilder* irb) { FunctionType* asmTy = FunctionType::get(irb->getVoidPointerType(), false); arm::Register thread_register = arm::Register::TR; std::stringstream ss; ss << "mov $0, " << thread_register; D3LOG(INFO) << "GetThreadRegister: asm: " << ss.str(); InlineAsm* getR9 = InlineAsm:: get(asmTy, ss.str(), "=r", false); return irb->CreateCall(getR9); } Value* LoadStateAndFlagsASM(IRBuilder* irb) { FunctionType *asmTy = FunctionType::get(irb->getInt16Ty(), false); arm::Register thread_register = arm::Register::TR; std::stringstream ss; uint32_t offset_state_and_flags = Thread::ThreadFlagsOffset<kArmPointerSize>().Int32Value(); ss << "ldrh.w $0, [" << thread_register << ", #" << std::to_string(offset_state_and_flags) << "]"; InlineAsm* ldrhw = InlineAsm:: get(asmTy, ss.str(), "=r", false); return irb->CreateCall(ldrhw); } void GenerateMemoryBarrier(IRBuilder* irb, MemBarrierKind kind) { D1LOG(INFO) << "ArmThumb::GenerateMemoryBarrier: dmb " << kind; // LLVM IR: fence acquire; // dmb ishld std::string flavour = ""; switch (kind) { case MemBarrierKind::kAnyStore: case MemBarrierKind::kLoadAny: case MemBarrierKind::kAnyAny: flavour = "ish"; break; case MemBarrierKind::kStoreStore: flavour = "ishst"; break; default: DLOG(FATAL) << "Unexpected memory barrier " << kind; } FunctionType *ty = FunctionType::get(irb->getVoidTy(), false); std::string dmb = "dmb " + flavour; InlineAsm* ia= InlineAsm::get(ty, dmb, "~{memory}", true); irb->CreateCall(ia); } #include "llvm_macros_undef.h" } // namespace ArmThumb } // namespace LLVM } // namespace art
27.834711
75
0.678741
[ "vector" ]
f8eb05b3b9f916f84c8b493e2ca4b7b83a096b15
1,201
cpp
C++
Online Judges/CodeForces/580C - Kefa and Park/main.cpp
AnneLivia/URI-Online
02ff972be172a62b8abe25030c3676f6c04efd1b
[ "MIT" ]
64
2019-03-17T08:56:28.000Z
2022-01-14T02:31:21.000Z
Online Judges/CodeForces/580C - Kefa and Park/main.cpp
AnneLivia/URI-Online
02ff972be172a62b8abe25030c3676f6c04efd1b
[ "MIT" ]
1
2020-12-24T07:16:30.000Z
2021-03-23T20:51:05.000Z
Online Judges/CodeForces/580C - Kefa and Park/main.cpp
AnneLivia/URI-Online
02ff972be172a62b8abe25030c3676f6c04efd1b
[ "MIT" ]
19
2019-05-25T10:48:16.000Z
2022-01-07T10:07:46.000Z
#include <iostream> #include <vector> #include <stack> using namespace std; vector<vector<int> > g; vector<int> vi, cat, pre; void dfs(int v, int contC, int& cont, int m) { vi[v] = 1; int cats = 0, leaf = 0; if(contC > m) return; for (int i = 0; i < (int)g[v].size(); i++) { if(!vi[g[v][i]]) { leaf++; pre[g[v][i]] = v; if(cat[g[v][i]] && !cat[pre[g[v][i]]]) { dfs(g[v][i], 1, cont, m); } else if (!cat[g[v][i]] && !cat[pre[g[v][i]]]){ dfs(g[v][i], 0, cont, m); } else { dfs(g[v][i], contC + cat[g[v][i]], cont, m); } } } if(!leaf) { // leaf has no child if(contC <= m) cont++; } } int main() { int n, m, u, v; cin >> n >> m; g.assign(n, vector<int>()); cat.assign(n, 0); pre.assign(n, -1); vi.assign(n, 0); for (int i = 0; i < n; i++) { cin >> cat[i]; } while(--n) { cin >> u >> v; g[u - 1].push_back(v - 1); g[v - 1].push_back(u - 1); } int cont = 0; dfs(0, cat[0], cont, m); cout << cont << endl; return 0; }
20.016667
60
0.393838
[ "vector" ]
f8ec75d7a6c3f994f048868177f1086aff881e26
4,649
cc
C++
src/magic_event/looper.cc
jeasonzs/magic_event
163b962859b809687261a18c61ce58fbef9f41a0
[ "MIT" ]
1
2021-02-02T02:46:32.000Z
2021-02-02T02:46:32.000Z
src/magic_event/looper.cc
jeasonzs/magic_event
163b962859b809687261a18c61ce58fbef9f41a0
[ "MIT" ]
null
null
null
src/magic_event/looper.cc
jeasonzs/magic_event
163b962859b809687261a18c61ce58fbef9f41a0
[ "MIT" ]
null
null
null
// // Created by jeason on 2021/1/14. // #include "magic_event/looper.h" #include "magic_event/utils/time_utils.h" #include <memory> #include <sys/socket.h> namespace magic_event { using EventType = PollEvent::EventType; PollEvent::EventSet channel2event_set(const Channel& channel) { PollEvent::EventSet set; set.set(EventType::kEventRead, channel.enable_read()); set.set(EventType::kEventWrite, channel.enable_write()); set.set(EventType::kEventClose); set.set(EventType::kEventError); return set; } Looper::Looper() : poller_(create_poller()), running_(true) { poll_thread_ = std::make_unique<std::thread>([this] { Loop(); }); } Looper::~Looper() { running_ = false; poller_->Wakeup(); if (poll_thread_->joinable()) { poll_thread_->join(); } } void Looper::Run(Functor functor) { if (InLoop()) { functor(); } else { std::unique_lock<std::mutex> lock(mutex_); functors_.push_back(functor); lock.unlock(); poller_->Wakeup(); } } TimerPtr Looper::RunDelay(Functor functor, time_t delay) { TimePoint time = steady_clock::now() + milliseconds(delay); TimerPtr timer = std::make_shared<Timer>(time, milliseconds(0), functor); Run([this, timer] { timer_list_.Insert(timer); poller_->WakeupAt(timer_list_.First()->time_point()); }); return timer; } TimerPtr Looper::RunEvery(Functor functor, time_t period) { auto _period = milliseconds(period); TimePoint time = steady_clock::now() + _period; TimerPtr timer = std::make_shared<Timer>(time, _period, functor); Run([this, timer] { timer_list_.Insert(timer); poller_->WakeupAt(timer_list_.First()->time_point()); }); return timer; } void Looper::Cancel(TimerPtr timer) { Run([this, timer] { timer_list_.Erase(timer); if (auto first = timer_list_.First()) { poller_->WakeupAt(first->time_point()); } }); } void Looper::Loop() { std::vector<PollEvent> events; while (running_) { events.clear(); auto reason = poller_->Poll(events, 100 * 1000); #ifdef DEBUG std::cout << this << " reason: " << reason.reason_set() << std::endl; #endif if (reason.reason_set().test( PollReason::ReasonType::kReasonWakeupAt)) { auto expired = timer_list_.Expired(); for (auto& timer : expired) { timer->functor()(); if (timer->restart()) { timer_list_.Insert(timer); } } if (auto first = timer_list_.First()) { poller_->WakeupAt(first->time_point()); } } if (reason.reason_set().test( PollReason::ReasonType::kReasonIo)) { for (auto event : events) { auto iter = channel_map_.find(event.fd()); if (iter == channel_map_.end()) { continue; } if (event.event_set().test(EventType::kEventRead)) { iter->second.HandleRead(); } if (event.event_set().test(EventType::kEventWrite)) { iter->second.HandleWrite(); } if (event.event_set().test(EventType::kEventClose) && !event.event_set().test(EventType::kEventRead)) { iter->second.HandleClose(); } if (event.event_set().test(EventType::kEventError)) { int opt_val; auto opt_len = static_cast<socklen_t>(sizeof opt_val); if (getsockopt(iter->second.fd(), SOL_SOCKET, SO_ERROR, &opt_val, &opt_len) < 0) { iter->second.HandleError(errno); } else { iter->second.HandleError(opt_val); } } } } std::vector<Functor> functors; std::unique_lock<std::mutex> lock(mutex_); std::swap(functors, functors_); lock.unlock(); for (auto functor : functors) { functor(); } } } void Looper::AddChannel(const Channel& channel) { Run([this, channel] { channel_map_.insert(std::make_pair(channel.fd(), channel)); PollEvent event(channel.fd(), channel2event_set(channel)); poller_->AddEvent(event); }); } void Looper::EditChannel(const Channel& channel) { Run([this, channel] { auto iter = channel_map_.find(channel.fd()); if (iter != channel_map_.end()) { PollEvent event(channel.fd(), channel2event_set(channel)); poller_->EditEvent(event); } }); } void Looper::RemoveChannel(const Channel& channel) { Run([this, channel] { auto iter = channel_map_.find(channel.fd()); if (iter != channel_map_.end()) { PollEvent event(channel.fd(), channel2event_set(channel)); poller_->RemoveEvent(event); channel_map_.erase(iter); } }); } bool Looper::InLoop() { return std::this_thread::get_id() == poll_thread_->get_id(); } }
26.872832
92
0.627232
[ "vector" ]
f8eef808696a28ea0db54b8f196ffc02d15e7997
5,677
cpp
C++
tests/PTransformBench.cpp
gergondet/SpaceVecAlg
b5a92d961c7b52f147908c779dfa024c4c302f08
[ "BSD-2-Clause" ]
null
null
null
tests/PTransformBench.cpp
gergondet/SpaceVecAlg
b5a92d961c7b52f147908c779dfa024c4c302f08
[ "BSD-2-Clause" ]
null
null
null
tests/PTransformBench.cpp
gergondet/SpaceVecAlg
b5a92d961c7b52f147908c779dfa024c4c302f08
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright 2012-2019 CNRS-UM LIRMM, CNRS-AIST JRL */ // includes // std #include <iostream> // boost #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE PTranformd bench #include <boost/math/constants/constants.hpp> #include <boost/test/unit_test.hpp> #include <boost/timer/timer.hpp> // The inclusion of boost chrono was commented in timer.hpp for boost >= 1.60. // Because of this, the auto-link feature does not incude the chrono library // anymore, what causes a link error. // (see also https://svn.boost.org/trac/boost/ticket/11862) // We add manually the line. // Possible alternative: include only for specific version of boost and // auto-link capable compiler #include <boost/chrono/chrono.hpp> // SpaceVecAlg #include <SpaceVecAlg/SpaceVecAlg> typedef Eigen::Matrix<double, 6, Eigen::Dynamic> Matrix6Xd; BOOST_AUTO_TEST_CASE(PTransfromd_PTransformd) { using namespace sva; const std::size_t size = 10000000; std::vector<PTransformd> pt1(size, PTransformd::Identity()); std::vector<PTransformd> pt2(size, PTransformd::Identity()); std::vector<PTransformd> ptRes(size); std::cout << "PTransform vs PTransform" << std::endl; { boost::timer::auto_cpu_timer t; for(std::size_t i = 0; i < size; ++i) { ptRes[i] = pt1[i] * pt2[i]; } } std::cout << std::endl; } BOOST_AUTO_TEST_CASE(PTransfromd_MotionVec) { using namespace sva; const std::size_t size = 10000000; std::vector<PTransformd> pt1(size, PTransformd::Identity()); std::vector<MotionVecd> mv(size, MotionVecd(Eigen::Vector6d::Random())); std::vector<MotionVecd> mvRes(size); std::cout << "PTransform vs MotionVec" << std::endl; { boost::timer::auto_cpu_timer t; for(std::size_t i = 0; i < size; ++i) { mvRes[i] = pt1[i] * mv[i]; } } std::cout << std::endl; } BOOST_AUTO_TEST_CASE(PTransfromd_MotionEigen) { using namespace sva; const std::size_t size = 10000000; const std::size_t cols = 3; std::vector<PTransformd> pt1(size, PTransformd::Identity()); std::vector<Matrix6Xd> mv(size, Matrix6Xd::Random(6, cols)); std::vector<Matrix6Xd> mvRes(size, Matrix6Xd(6, cols)); std::cout << "PTransform vs MotionEigen" << std::endl; { boost::timer::auto_cpu_timer t; for(std::size_t i = 0; i < size; ++i) { pt1[i].mul(mv[i], mvRes[i]); } } std::cout << std::endl; } BOOST_AUTO_TEST_CASE(PTransfromd_as_matrix_MotionEigen) { using namespace sva; const std::size_t size = 10000000; const std::size_t cols = 3; std::vector<PTransformd> pt1(size, PTransformd::Identity()); std::vector<Matrix6Xd> mv(size, Matrix6Xd::Random(6, cols)); std::vector<Matrix6Xd> mvRes(size, Matrix6Xd(6, cols)); std::cout << "PTransform as matrix vs MotionEigen" << std::endl; { boost::timer::auto_cpu_timer t; for(std::size_t i = 0; i < size; ++i) { mvRes[i].noalias() = pt1[i].matrix() * mv[i]; } } std::cout << std::endl; } BOOST_AUTO_TEST_CASE(PTransfromd_MotionEigen_as_motion) { using namespace sva; const std::size_t size = 10000000; const std::size_t cols = 3; std::vector<PTransformd> pt1(size, PTransformd::Identity()); std::vector<Matrix6Xd> mv(size, Matrix6Xd::Random(6, cols)); std::vector<Matrix6Xd> mvRes(size, Matrix6Xd(6, cols)); std::cout << "PTransform vs MotionEigen as MotionVec" << std::endl; { boost::timer::auto_cpu_timer t; for(std::size_t i = 0; i < size; ++i) { for(std::size_t j = 0; j < cols; ++j) { mvRes[i].col(j).noalias() = (pt1[i] * MotionVecd(mv[i].col(j))).vector(); } } } std::cout << std::endl; } BOOST_AUTO_TEST_CASE(PTransfromd_inv_MotionVec) { using namespace sva; const std::size_t size = 10000000; std::vector<PTransformd> pt1(size, PTransformd::Identity()); std::vector<MotionVecd> mv(size, MotionVecd(Eigen::Vector6d::Random())); std::vector<MotionVecd> mvRes(size); std::cout << "PTransform_inv vs MotionVec" << std::endl; { boost::timer::auto_cpu_timer t; for(std::size_t i = 0; i < size; ++i) { mvRes[i] = pt1[i].inv() * mv[i]; } } std::cout << std::endl; } BOOST_AUTO_TEST_CASE(PTransfromd_invMul_MotionVec) { using namespace sva; const std::size_t size = 10000000; std::vector<PTransformd> pt1(size, PTransformd::Identity()); std::vector<MotionVecd> mv(size, MotionVecd(Eigen::Vector6d::Random())); std::vector<MotionVecd> mvRes(size); std::cout << "PTransform_invMul vs MotionVec" << std::endl; { boost::timer::auto_cpu_timer t; for(std::size_t i = 0; i < size; ++i) { mvRes[i] = pt1[i].invMul(mv[i]); } } std::cout << std::endl; } BOOST_AUTO_TEST_CASE(PTransfromd_dual_ForceVec) { using namespace sva; const std::size_t size = 10000000; std::vector<PTransformd> pt1(size, PTransformd::Identity()); std::vector<ForceVecd> mv(size, ForceVecd(Eigen::Vector6d::Random())); std::vector<ForceVecd> mvRes(size); std::cout << "PTransform dual vs ForceVec" << std::endl; { boost::timer::auto_cpu_timer t; for(std::size_t i = 0; i < size; ++i) { mvRes[i] = pt1[i].dualMul(mv[i]); } } std::cout << std::endl; } BOOST_AUTO_TEST_CASE(PTransfromd_trans_ForceVec) { using namespace sva; const std::size_t size = 10000000; std::vector<PTransformd> pt1(size, PTransformd::Identity()); std::vector<ForceVecd> mv(size, ForceVecd(Eigen::Vector6d::Random())); std::vector<ForceVecd> mvRes(size); std::cout << "PTransform trans vs ForceVec" << std::endl; { boost::timer::auto_cpu_timer t; for(std::size_t i = 0; i < size; ++i) { mvRes[i] = pt1[i].transMul(mv[i]); } } std::cout << std::endl; }
26.528037
81
0.657566
[ "vector" ]
f8f0e67ce51fcd566dbb909129ad03027377a9fc
3,512
cpp
C++
StiGame/gui/Layout.cpp
jordsti/stigame
6ac0ae737667b1c77da3ef5007f5c4a3a080045a
[ "MIT" ]
8
2015-02-03T20:23:49.000Z
2022-02-15T07:51:05.000Z
StiGame/gui/Layout.cpp
jordsti/stigame
6ac0ae737667b1c77da3ef5007f5c4a3a080045a
[ "MIT" ]
null
null
null
StiGame/gui/Layout.cpp
jordsti/stigame
6ac0ae737667b1c77da3ef5007f5c4a3a080045a
[ "MIT" ]
2
2017-02-13T18:04:00.000Z
2020-08-24T03:21:37.000Z
#include "Layout.h" #include "PRect.h" namespace StiGame { namespace Gui { Layout::Layout(std::string name) : Item(name) { //ctor mouse = MPoint(); handleKey = true; verticalAlign = LVA_Middle; horizontalAlign = LHA_Center; childsChanged = false; drawBorder = true; } Layout::~Layout() { //dtor } void Layout::setDrawBorder(bool m_drawBorder) { drawBorder = m_drawBorder; } void Layout::addChild(Item *item) { container.add(item); childsChanged = true; } void Layout::removeChild(Item *item) { container.remove(item); childsChanged = true; } Item* Layout::getChildAt(int index) { return container.itemAt(index); } unsigned int Layout::childsCount() { return container.size(); } void Layout::onClick(Point *relpt) { mouse.setPoint(relpt); ItemIterator it = container.iterator(); it.publishOnClick(relpt->getX(), relpt->getY()); } void Layout::onMouseMotion(Point *relpt) { mouse.setPoint(relpt); ItemIterator it = container.iterator(); it.publishOnMouseMotion(relpt->getX(), relpt->getY()); } void Layout::resized() { setChildsPosition(); } void Layout::onKeyUp(SDL_KeyboardEvent *evt) { ItemIterator it = container.iterator(); it.publishOnKeyUp(evt); } Surface *Layout::render() { //todo if(childsChanged) { setChildsPosition(); childsChanged = false; } Surface *buffer = new Surface(width, height); buffer->fill(background); for(ItemIterator it = container.iterator(); it.next();) { Surface *itemBuffer = it.item()->render(); buffer->blit(itemBuffer, it.item()); delete itemBuffer; } if(drawBorder) { PRect border = PRect(); border.setDimension(width, height); buffer->draw(&border, foreground); } return buffer; } void Layout::onTextInput(char *text) { container.iterator().publishTextInput(text); } void Layout::setVerticalAlign(LayoutVerticalAlign m_verticalAlign) { verticalAlign = m_verticalAlign; } void Layout::setHorizontalAlign(LayoutHorizontalAlign m_horizontalAlign) { horizontalAlign = m_horizontalAlign; } LayoutVerticalAlign Layout::getVerticalAlign(void) { return verticalAlign; } LayoutHorizontalAlign Layout::getHorizontalAlign(void) { return horizontalAlign; } } } #ifdef C_WRAPPER extern "C" { void Layout_addChild(StiGame::Gui::Layout *layout, StiGame::Gui::Item *item) { layout->addChild(item); } void Layout_removeChild(StiGame::Gui::Layout *layout, StiGame::Gui::Item *item) { layout->removeChild(item); } StiGame::Gui::Item* Layout_getChildAt(StiGame::Gui::Layout *layout, int index) { return layout->getChildAt(index); } unsigned int Layout_childsCount(StiGame::Gui::Layout *layout) { return layout->childsCount(); } int Layout_getVerticalAlign(StiGame::Gui::Layout *layout) { return layout->getVerticalAlign(); } int Layout_getHorizontalAlign(StiGame::Gui::Layout *layout) { return layout->getHorizontalAlign(); } void Layout_setVerticalAlign(StiGame::Gui::Layout *layout, int align) { layout->setVerticalAlign(static_cast<StiGame::Gui::LayoutVerticalAlign>(align)); } void Layout_setHorizontalAlign(StiGame::Gui::Layout *layout, int align) { layout->setHorizontalAlign(static_cast<StiGame::Gui::LayoutHorizontalAlign>(align)); } } #endif // C_WRAPPER
18.983784
92
0.665433
[ "render" ]
f8fb1703ccc29637ebebfaac2f7bafdef6e57423
502
hpp
C++
test/helper.hpp
openbmc/google-ipmi-sys
f647e99165065feabb35aa744059cf6a2af46f1e
[ "Apache-2.0" ]
2
2020-01-16T02:04:13.000Z
2021-01-13T21:47:30.000Z
test/helper.hpp
openbmc/google-ipmi-sys
f647e99165065feabb35aa744059cf6a2af46f1e
[ "Apache-2.0" ]
null
null
null
test/helper.hpp
openbmc/google-ipmi-sys
f647e99165065feabb35aa744059cf6a2af46f1e
[ "Apache-2.0" ]
3
2019-12-10T21:56:33.000Z
2021-03-02T23:56:06.000Z
#pragma once #include "handler_mock.hpp" #include <ipmid/api-types.hpp> #include <span> #include <utility> #include <gtest/gtest.h> namespace google { namespace ipmi { // Validate the return code and the data for the IPMI reply. // Returns the subcommand and the optional informations. std::pair<std::uint8_t, std::vector<std::uint8_t>> ValidateReply(::ipmi::RspType<std::uint8_t, std::vector<uint8_t>> reply, bool hasData = true); } // namespace ipmi } // namespace google
20.916667
76
0.701195
[ "vector" ]
f8fcf7e01b07847a73123ccb63dc8bfa68de8d0a
43,807
cpp
C++
libs/VersionedStorage-cpp/tests/HeaderBlock-test.cpp
ivte-ms/MixedReality-Sharing
edb38467be6dcd09447962a3c1f998fe700b8832
[ "MIT" ]
24
2019-12-11T18:56:39.000Z
2021-12-28T02:48:59.000Z
libs/VersionedStorage-cpp/tests/HeaderBlock-test.cpp
ivte-ms/MixedReality-Sharing
edb38467be6dcd09447962a3c1f998fe700b8832
[ "MIT" ]
23
2019-12-11T20:21:30.000Z
2020-02-12T12:12:05.000Z
libs/VersionedStorage-cpp/tests/HeaderBlock-test.cpp
ivte-ms/MixedReality-Sharing
edb38467be6dcd09447962a3c1f998fe700b8832
[ "MIT" ]
14
2019-12-11T18:56:44.000Z
2021-06-09T18:13:10.000Z
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #include "pch.h" #include "src/HeaderBlock.h" #include <Microsoft/MixedReality/Sharing/VersionedStorage/KeyDescriptorWithHandle.h> #include <Microsoft/MixedReality/Sharing/Common/Testing/Testing.h> #include "TestBehavior.h" #include "src/StateBlock.h" #include <algorithm> #include <memory> #include <numeric> #include <random> namespace Microsoft::MixedReality::Sharing::VersionedStorage::Detail { class HeaderBlock_Test : public ::testing::Test { protected: ~HeaderBlock_Test() override { behavior_->CheckLeakingHandles(); EXPECT_EQ(behavior_.use_count(), 1); } protected: static constexpr uint64_t kBaseVersion = 111'222'333'444'555ull; std::shared_ptr<TestBehavior> behavior_{std::make_shared<TestBehavior>()}; KeyDescriptorWithHandle MakeKeyDescriptor(uint64_t id) const noexcept { return {*behavior_, behavior_->MakeKey(id), true}; } PayloadHandle MakePayload(uint64_t id) const noexcept { return behavior_->MakePayload(id); } static bool HasLeftChild(const KeyStateView& key_state_view) noexcept { assert(!key_state_view.state_block_->is_scratch_buffer_mode()); return key_state_view.state_block_->left_tree_child_ != DataBlockLocation::kInvalid; } static bool HasRightChild(const KeyStateView& key_state_view) noexcept { assert(!key_state_view.state_block_->is_scratch_buffer_mode()); return key_state_view.state_block_->right_tree_child_ != DataBlockLocation::kInvalid; } static bool IsLeaf(const KeyStateView& key_state_view) noexcept { assert(!key_state_view.state_block_->is_scratch_buffer_mode()); return key_state_view.state_block_->left_tree_child_ == DataBlockLocation::kInvalid && key_state_view.state_block_->right_tree_child_ == DataBlockLocation::kInvalid; } }; TEST_F(HeaderBlock_Test, CreateBlob_0_min_index_capacity) { HeaderBlock* header_block = HeaderBlock::CreateBlob(*behavior_, 12345, 0); ASSERT_NE(header_block, nullptr); EXPECT_EQ(header_block->base_version(), 12345); EXPECT_EQ(behavior_->total_allocated_pages_count(), 1); MutatingBlobAccessor accessor(*header_block); // The header_block is always created together with its base version; the // caller is responsible for populating it with the correct state before // presenting it to other threads. EXPECT_EQ(header_block->stored_versions_count(), 1); EXPECT_EQ(accessor.keys_count(), 0); EXPECT_EQ(accessor.subkeys_count(), 0); // One index block (mask is 1 less). EXPECT_EQ(header_block->index_blocks_mask(), 0); // When there is only one index slot, it's allowed to be overpopulated. EXPECT_EQ(accessor.remaining_index_slots_capacity(), 7); // There are 64 blocks total; 1 is occupied by the header, and 1 is occupied // by the index. Note that the trailing data block is already used by the // base version's reference count. EXPECT_EQ(header_block->data_blocks_capacity(), 62); EXPECT_EQ(accessor.available_data_blocks_count(), 61); EXPECT_TRUE(accessor.CanInsertStateBlocks(7)); EXPECT_FALSE(accessor.CanInsertStateBlocks(8)); header_block->RemoveSnapshotReference(12345, *behavior_); } TEST_F(HeaderBlock_Test, CreateBlob_8_min_index_capacity) { HeaderBlock* header_block = HeaderBlock::CreateBlob(*behavior_, 12345, 8); ASSERT_NE(header_block, nullptr); EXPECT_EQ(header_block->base_version(), 12345); EXPECT_EQ(behavior_->total_allocated_pages_count(), 1); MutatingBlobAccessor accessor(*header_block); // The header_block is always created together with its base version; the // caller is responsible for populating it with the correct state before // presenting it to other threads. EXPECT_EQ(header_block->stored_versions_count(), 1); EXPECT_EQ(accessor.keys_count(), 0); EXPECT_EQ(accessor.subkeys_count(), 0); // Two index blocks (mask is 1 less). EXPECT_EQ(header_block->index_blocks_mask(), 1); // Since there is more than one index block, we only allow up to 4 slots per // block. EXPECT_EQ(accessor.remaining_index_slots_capacity(), 8); // There are 64 blocks total; 1 is occupied by the header, and 2 are occupied // by the index. Note that the trailing data block is already used by the // base version's reference count. EXPECT_EQ(header_block->data_blocks_capacity(), 61); EXPECT_EQ(accessor.available_data_blocks_count(), 60); EXPECT_TRUE(accessor.CanInsertStateBlocks(8)); EXPECT_FALSE(accessor.CanInsertStateBlocks(9)); header_block->RemoveSnapshotReference(12345, *behavior_); } TEST_F(HeaderBlock_Test, CreateBlob_32_min_index_capacity) { HeaderBlock* header_block = HeaderBlock::CreateBlob(*behavior_, 12345, 32); ASSERT_NE(header_block, nullptr); EXPECT_EQ(header_block->base_version(), 12345); EXPECT_EQ(behavior_->total_allocated_pages_count(), 2); MutatingBlobAccessor accessor(*header_block); // The header_block is always created together with its base version; the // caller is responsible for populating it with the correct state before // presenting it to other threads. EXPECT_EQ(header_block->stored_versions_count(), 1); EXPECT_EQ(accessor.keys_count(), 0); EXPECT_EQ(accessor.subkeys_count(), 0); // 8 index blocks (mask is 1 less). EXPECT_EQ(header_block->index_blocks_mask(), 7); // Since there is more than one index block, we only allow up to 4 slots per // block. EXPECT_EQ(accessor.remaining_index_slots_capacity(), 32); // There are 128 blocks total; 1 is occupied by the header, and 8 are occupied // by the index. Note that the trailing data block is already used by the // base version's reference count. EXPECT_EQ(header_block->data_blocks_capacity(), 119); EXPECT_EQ(accessor.available_data_blocks_count(), 118); EXPECT_TRUE(accessor.CanInsertStateBlocks(32)); EXPECT_FALSE(accessor.CanInsertStateBlocks(33)); header_block->RemoveSnapshotReference(12345, *behavior_); } TEST_F(HeaderBlock_Test, populate_block_index_with_keys) { // Populating the blob with various keys and checking that the internal data // structures behave adequately. // Each key ends up in: // * Hash index. // * Sorted list of keys. // * Tree of keys (used for fast insertion, not exposed to readers). // The trickiest part is the tree, and here we check all the relevant code // paths of the insertion procedure. HeaderBlock* header_block = HeaderBlock::CreateBlob(*behavior_, kBaseVersion, 7); ASSERT_NE(header_block, nullptr); EXPECT_EQ(behavior_->total_allocated_pages_count(), 1); MutatingBlobAccessor accessor(*header_block); EXPECT_EQ(accessor.remaining_index_slots_capacity(), 7); EXPECT_TRUE(accessor.CanInsertStateBlocks(7)); EXPECT_FALSE(accessor.CanInsertStateBlocks(8)); // Returns KeyHandle{~0ull} if the child is missing, which would normally be a // valid handle, but here it's used as a marker. auto GetLeftChildKey = [&](const KeyStateView& key_state_view) noexcept { if (!HasLeftChild(key_state_view)) return KeyHandle{~0ull}; DataBlockLocation left = key_state_view.state_block_->left_tree_child_; return accessor.GetBlockAt<KeyStateBlock>(left).key_; }; auto GetRightChildKey = [&](const KeyStateView& key_state_view) noexcept { if (!HasRightChild(key_state_view)) return KeyHandle{~0ull}; DataBlockLocation right = key_state_view.state_block_->right_tree_child_; return accessor.GetBlockAt<KeyStateBlock>(right).key_; }; { KeyStateAndIndexView view = accessor.FindKeyStateAndIndex(MakeKeyDescriptor(20)); EXPECT_EQ(view.index_block_slot_, nullptr); EXPECT_EQ(view.state_block_, nullptr); EXPECT_EQ(view.version_block_, nullptr); } // Inserting key 20. This is the simplest case, since there is no other keys, // and thus the key will be inserted as a head of the list and the root of the // tree (of keys). accessor.InsertKeyBlock(*behavior_, behavior_->MakeKey(20)); EXPECT_EQ(behavior_->GetKeyReferenceCount(KeyHandle{20}), 1); KeyStateAndIndexView view_20 = accessor.FindKeyStateAndIndex(MakeKeyDescriptor(20)); ASSERT_NE(view_20.state_block_, nullptr); EXPECT_EQ(view_20.key(), KeyHandle{20}); EXPECT_TRUE(IsLeaf(view_20)); { auto it = accessor.begin(); ASSERT_NE(it, accessor.end()); EXPECT_EQ(it->version_block_, nullptr); EXPECT_EQ(it->state_block_, view_20.state_block_); ++it; EXPECT_EQ(it, accessor.end()); } // Inserting key 10. It's less than the previous one, so it should be inserted // as a left child of the key 20. Then the AA-tree invariant should become // broken, and the skew operation will be performed, repairing the tree. // The new node (10) will become the new root. accessor.InsertKeyBlock(*behavior_, behavior_->MakeKey(10)); EXPECT_EQ(behavior_->GetKeyReferenceCount(KeyHandle{10}), 1); KeyStateAndIndexView view_10 = accessor.FindKeyStateAndIndex(MakeKeyDescriptor(10)); ASSERT_NE(view_10.state_block_, nullptr); EXPECT_EQ(view_10.key(), KeyHandle{10}); // The tree looks like this (the number in () is the level of the node): // 10(0) | // \ | // 20(0) | EXPECT_EQ(view_10.state_block_->tree_level(), 0); EXPECT_EQ(view_20.state_block_->tree_level(), 0); EXPECT_FALSE(HasLeftChild(view_10)); EXPECT_EQ(GetRightChildKey(view_10), KeyHandle{20}); EXPECT_TRUE(IsLeaf(view_20)); { auto it = accessor.begin(); ASSERT_NE(it, accessor.end()); EXPECT_EQ(it->version_block_, nullptr); EXPECT_EQ(it->state_block_, view_10.state_block_); ++it; ASSERT_NE(it, accessor.end()); EXPECT_EQ(it->version_block_, nullptr); EXPECT_EQ(it->state_block_, view_20.state_block_); ++it; EXPECT_EQ(it, accessor.end()); } // Inserting key 5. It's less than the root, and thus should be // inserted as the left child. It will break the invariant, but since // the root has the right child, the invariant can't be repaired by // skewing the tree. Instead, the level of the root will be // incremented. accessor.InsertKeyBlock(*behavior_, behavior_->MakeKey(5)); EXPECT_EQ(behavior_->GetKeyReferenceCount(KeyHandle{5}), 1); KeyStateAndIndexView view_5 = accessor.FindKeyStateAndIndex(MakeKeyDescriptor(5)); ASSERT_NE(view_5.state_block_, nullptr); EXPECT_EQ(view_5.key(), KeyHandle{5}); // The tree looks like this (the number in () is the level of the node): // 10(1) | // / \ | // 5(0) 20(0) | EXPECT_EQ(view_5.state_block_->tree_level(), 0); EXPECT_EQ(view_10.state_block_->tree_level(), 1); EXPECT_EQ(view_20.state_block_->tree_level(), 0); EXPECT_EQ(GetLeftChildKey(view_10), KeyHandle{5}); EXPECT_EQ(GetRightChildKey(view_10), KeyHandle{20}); EXPECT_TRUE(IsLeaf(view_5)); EXPECT_TRUE(IsLeaf(view_20)); { auto it = accessor.begin(); ASSERT_NE(it, accessor.end()); EXPECT_EQ(it->version_block_, nullptr); EXPECT_EQ(it->state_block_, view_5.state_block_); ++it; ASSERT_NE(it, accessor.end()); EXPECT_EQ(it->version_block_, nullptr); EXPECT_EQ(it->state_block_, view_10.state_block_); ++it; ASSERT_NE(it, accessor.end()); EXPECT_EQ(it->version_block_, nullptr); EXPECT_EQ(it->state_block_, view_20.state_block_); ++it; EXPECT_EQ(it, accessor.end()); } // Inserting key 4. It's less than the root, and the left child is // already present. Therefore the insertion should recurse into adding // it as a child to 5. But then the invariant will become broken, and // the subtree will become skewed. accessor.InsertKeyBlock(*behavior_, behavior_->MakeKey(4)); EXPECT_EQ(behavior_->GetKeyReferenceCount(KeyHandle{4}), 1); KeyStateAndIndexView view_4 = accessor.FindKeyStateAndIndex(MakeKeyDescriptor(4)); ASSERT_NE(view_4.state_block_, nullptr); EXPECT_EQ(view_4.key(), KeyHandle{4}); // The tree looks like this (the number in () is the level of the node): // 10(1) | // / \ | // 4(0) 20(0) | // \ | // 5(0) | EXPECT_EQ(view_4.state_block_->tree_level(), 0); EXPECT_EQ(view_5.state_block_->tree_level(), 0); EXPECT_EQ(view_10.state_block_->tree_level(), 1); EXPECT_EQ(view_20.state_block_->tree_level(), 0); EXPECT_EQ(GetLeftChildKey(view_10), KeyHandle{4}); EXPECT_EQ(GetRightChildKey(view_10), KeyHandle{20}); EXPECT_FALSE(HasLeftChild(view_4)); EXPECT_EQ(GetRightChildKey(view_4), KeyHandle{5}); EXPECT_TRUE(IsLeaf(view_5)); EXPECT_TRUE(IsLeaf(view_20)); { auto it = accessor.begin(); ASSERT_NE(it, accessor.end()); EXPECT_EQ(it->version_block_, nullptr); EXPECT_EQ(it->state_block_, view_4.state_block_); ++it; ASSERT_NE(it, accessor.end()); EXPECT_EQ(it->version_block_, nullptr); EXPECT_EQ(it->state_block_, view_5.state_block_); ++it; ASSERT_NE(it, accessor.end()); EXPECT_EQ(it->version_block_, nullptr); EXPECT_EQ(it->state_block_, view_10.state_block_); ++it; ASSERT_NE(it, accessor.end()); EXPECT_EQ(it->version_block_, nullptr); EXPECT_EQ(it->state_block_, view_20.state_block_); ++it; EXPECT_EQ(it, accessor.end()); } // Inserting key 3. It should break the invariant twice. The first // time it will be repaired by incrementing the level, the second time // the skew operation will be performed. This test should validate // that children are properly preserved during the skew operation. accessor.InsertKeyBlock(*behavior_, behavior_->MakeKey(3)); EXPECT_EQ(behavior_->GetKeyReferenceCount(KeyHandle{3}), 1); KeyStateAndIndexView view_3 = accessor.FindKeyStateAndIndex(MakeKeyDescriptor(3)); ASSERT_NE(view_3.state_block_, nullptr); EXPECT_EQ(view_3.key(), KeyHandle{3}); // The tree looks like this (the number in () is the level of the node): // 4(1) | // / \ | // 3(0) 10(1) | // / \ | // 5(0) 20(0) | EXPECT_EQ(view_3.state_block_->tree_level(), 0); EXPECT_EQ(view_4.state_block_->tree_level(), 1); EXPECT_EQ(view_5.state_block_->tree_level(), 0); EXPECT_EQ(view_10.state_block_->tree_level(), 1); EXPECT_EQ(view_20.state_block_->tree_level(), 0); EXPECT_EQ(GetLeftChildKey(view_10), KeyHandle{5}); EXPECT_EQ(GetRightChildKey(view_10), KeyHandle{20}); EXPECT_EQ(GetLeftChildKey(view_4), KeyHandle{3}); EXPECT_EQ(GetRightChildKey(view_4), KeyHandle{10}); EXPECT_TRUE(IsLeaf(view_3)); EXPECT_TRUE(IsLeaf(view_5)); EXPECT_TRUE(IsLeaf(view_20)); { auto it = accessor.begin(); ASSERT_NE(it, accessor.end()); EXPECT_EQ(it->version_block_, nullptr); EXPECT_EQ(it->state_block_, view_3.state_block_); ++it; ASSERT_NE(it, accessor.end()); EXPECT_EQ(it->version_block_, nullptr); EXPECT_EQ(it->state_block_, view_4.state_block_); ++it; ASSERT_NE(it, accessor.end()); EXPECT_EQ(it->version_block_, nullptr); EXPECT_EQ(it->state_block_, view_5.state_block_); ++it; ASSERT_NE(it, accessor.end()); EXPECT_EQ(it->version_block_, nullptr); EXPECT_EQ(it->state_block_, view_10.state_block_); ++it; ASSERT_NE(it, accessor.end()); EXPECT_EQ(it->version_block_, nullptr); EXPECT_EQ(it->state_block_, view_20.state_block_); ++it; EXPECT_EQ(it, accessor.end()); } // Inserting key 15. It should recurse into the right subtree and be inserted // with one skew. accessor.InsertKeyBlock(*behavior_, behavior_->MakeKey(15)); EXPECT_EQ(behavior_->GetKeyReferenceCount(KeyHandle{15}), 1); KeyStateAndIndexView view_15 = accessor.FindKeyStateAndIndex(MakeKeyDescriptor(15)); ASSERT_NE(view_15.state_block_, nullptr); EXPECT_EQ(view_15.key(), KeyHandle{15}); // The tree looks like this (the number in () is the level of the node): // 4(1) | // / \ | // 3(0) 10(1) | // / \ | // 5(0) 15(0) | // \ | // 20(0) | EXPECT_EQ(view_3.state_block_->tree_level(), 0); EXPECT_EQ(view_4.state_block_->tree_level(), 1); EXPECT_EQ(view_5.state_block_->tree_level(), 0); EXPECT_EQ(view_10.state_block_->tree_level(), 1); EXPECT_EQ(view_15.state_block_->tree_level(), 0); EXPECT_EQ(view_20.state_block_->tree_level(), 0); EXPECT_EQ(GetLeftChildKey(view_10), KeyHandle{5}); EXPECT_EQ(GetRightChildKey(view_10), KeyHandle{15}); EXPECT_EQ(GetLeftChildKey(view_4), KeyHandle{3}); EXPECT_EQ(GetRightChildKey(view_4), KeyHandle{10}); EXPECT_FALSE(HasLeftChild(view_15)); EXPECT_EQ(GetRightChildKey(view_15), KeyHandle{20}); EXPECT_TRUE(IsLeaf(view_3)); EXPECT_TRUE(IsLeaf(view_5)); EXPECT_TRUE(IsLeaf(view_20)); { auto it = accessor.begin(); ASSERT_NE(it, accessor.end()); EXPECT_EQ(it->version_block_, nullptr); EXPECT_EQ(it->state_block_, view_3.state_block_); ++it; ASSERT_NE(it, accessor.end()); EXPECT_EQ(it->version_block_, nullptr); EXPECT_EQ(it->state_block_, view_4.state_block_); ++it; ASSERT_NE(it, accessor.end()); EXPECT_EQ(it->version_block_, nullptr); EXPECT_EQ(it->state_block_, view_5.state_block_); ++it; ASSERT_NE(it, accessor.end()); EXPECT_EQ(it->version_block_, nullptr); EXPECT_EQ(it->state_block_, view_10.state_block_); ++it; ASSERT_NE(it, accessor.end()); EXPECT_EQ(it->version_block_, nullptr); EXPECT_EQ(it->state_block_, view_15.state_block_); ++it; ASSERT_NE(it, accessor.end()); EXPECT_EQ(it->version_block_, nullptr); EXPECT_EQ(it->state_block_, view_20.state_block_); ++it; EXPECT_EQ(it, accessor.end()); } // Inserting key 12 (as a left child of key 15). At first, this will increment // the level of the key 15, but then the level of the node 4(1) will be the // same as the level of its right grandchild (key 15). This will be repaired // with a split operation. accessor.InsertKeyBlock(*behavior_, behavior_->MakeKey(12)); EXPECT_EQ(behavior_->GetKeyReferenceCount(KeyHandle{12}), 1); KeyStateAndIndexView view_12 = accessor.FindKeyStateAndIndex(MakeKeyDescriptor(12)); ASSERT_NE(view_12.state_block_, nullptr); EXPECT_EQ(view_12.key(), KeyHandle{12}); // The tree looks like this (the number in () is the level of the node): // 10(2) | // / \ | // 4(1) 15(1) | // / \ / \ | // 3(0) 5(0) 12(0) 20(0) | EXPECT_EQ(view_3.state_block_->tree_level(), 0); EXPECT_EQ(view_4.state_block_->tree_level(), 1); EXPECT_EQ(view_5.state_block_->tree_level(), 0); EXPECT_EQ(view_10.state_block_->tree_level(), 2); EXPECT_EQ(view_12.state_block_->tree_level(), 0); EXPECT_EQ(view_15.state_block_->tree_level(), 1); EXPECT_EQ(view_20.state_block_->tree_level(), 0); EXPECT_EQ(GetLeftChildKey(view_10), KeyHandle{4}); EXPECT_EQ(GetRightChildKey(view_10), KeyHandle{15}); EXPECT_EQ(GetLeftChildKey(view_4), KeyHandle{3}); EXPECT_EQ(GetRightChildKey(view_4), KeyHandle{5}); EXPECT_EQ(GetLeftChildKey(view_15), KeyHandle{12}); EXPECT_EQ(GetRightChildKey(view_15), KeyHandle{20}); EXPECT_TRUE(IsLeaf(view_3)); EXPECT_TRUE(IsLeaf(view_5)); EXPECT_TRUE(IsLeaf(view_12)); EXPECT_TRUE(IsLeaf(view_20)); { auto it = accessor.begin(); ASSERT_NE(it, accessor.end()); EXPECT_EQ(it->version_block_, nullptr); EXPECT_EQ(it->state_block_, view_3.state_block_); ++it; ASSERT_NE(it, accessor.end()); EXPECT_EQ(it->version_block_, nullptr); EXPECT_EQ(it->state_block_, view_4.state_block_); ++it; ASSERT_NE(it, accessor.end()); EXPECT_EQ(it->version_block_, nullptr); EXPECT_EQ(it->state_block_, view_5.state_block_); ++it; ASSERT_NE(it, accessor.end()); EXPECT_EQ(it->version_block_, nullptr); EXPECT_EQ(it->state_block_, view_10.state_block_); ++it; ASSERT_NE(it, accessor.end()); EXPECT_EQ(it->version_block_, nullptr); EXPECT_EQ(it->state_block_, view_12.state_block_); ++it; ASSERT_NE(it, accessor.end()); EXPECT_EQ(it->version_block_, nullptr); EXPECT_EQ(it->state_block_, view_15.state_block_); ++it; ASSERT_NE(it, accessor.end()); EXPECT_EQ(it->version_block_, nullptr); EXPECT_EQ(it->state_block_, view_20.state_block_); ++it; EXPECT_EQ(it, accessor.end()); } // Can't insert any extra blocks. EXPECT_FALSE(accessor.CanInsertStateBlocks(1)); header_block->RemoveSnapshotReference(kBaseVersion, *behavior_); } TEST_F(HeaderBlock_Test, populate_block_index_with_keys_and_subkeys) { // Inserting multiple keys and subkeys into the index. // This checks that subkey blocks are attaching themselves to correct key // blocks, and the collections of subkeys belonging to different keys are not // interfering. HeaderBlock* header_block = HeaderBlock::CreateBlob(*behavior_, kBaseVersion, 32); ASSERT_NE(header_block, nullptr); EXPECT_EQ(behavior_->total_allocated_pages_count(), 2); MutatingBlobAccessor accessor(*header_block); EXPECT_EQ(accessor.remaining_index_slots_capacity(), 32); ASSERT_TRUE(accessor.CanInsertStateBlocks(32)); EXPECT_FALSE(accessor.CanInsertStateBlocks(33)); // Each key will have 9 subkeys for (uint64_t key = 0; key < 3; ++key) { accessor.InsertKeyBlock(*behavior_, behavior_->MakeKey(key)); KeyStateAndIndexView key_state_view = accessor.FindKeyStateAndIndex(MakeKeyDescriptor(key)); ASSERT_TRUE(key_state_view.state_block_); EXPECT_EQ(key_state_view.key(), KeyHandle{key}); for (uint64_t i = 0; i < 9; ++i) { uint64_t subkey = 123'000'000'000 + key * 100'000 + i; accessor.InsertSubkeyBlock(*behavior_, *key_state_view.state_block_, subkey); SubkeyStateAndIndexView subkey_state_view = accessor.FindSubkeyStateAndIndex(MakeKeyDescriptor(key), subkey); SubkeyStateBlock* block = subkey_state_view.state_block_; ASSERT_TRUE(block); EXPECT_EQ(block->key_, KeyHandle{key}); EXPECT_EQ(block->subkey_, subkey); } } // We should be able to iterate over all keys, and over all subkeys within // each key. KeyBlockIterator key_it = accessor.begin(); for (uint64_t key = 0; key < 3; ++key) { ASSERT_NE(key_it, accessor.end()); EXPECT_EQ(key_it->version_block_, nullptr); EXPECT_EQ(key_it->key(), KeyHandle{key}); SubkeyBlockIterator subkey_it = accessor.GetSubkeys(*key_it).begin(); for (uint64_t i = 0; i < 9; ++i) { uint64_t subkey = 123'000'000'000 + key * 100'000 + i; ASSERT_NE(subkey_it, SubkeyBlockIterator::End{}); EXPECT_EQ(subkey_it->version_block_, nullptr); EXPECT_EQ(subkey_it->key(), KeyHandle{key}); EXPECT_EQ(subkey_it->subkey(), subkey); ++subkey_it; } EXPECT_EQ(subkey_it, SubkeyBlockIterator::End{}); ++key_it; } ASSERT_EQ(key_it, accessor.end()); EXPECT_TRUE(accessor.CanInsertStateBlocks(2)); EXPECT_FALSE(accessor.CanInsertStateBlocks(3)); header_block->RemoveSnapshotReference(kBaseVersion, *behavior_); } TEST_F(HeaderBlock_Test, insertion_order_fuzzing) { // Tries inserting a predefined set of subkeys in various random orders, // expecting that the subkeys are discoverable and ordered after the // insertion. Testing::RunInParallel(300, [this](uint64_t begin_id, uint64_t end_id) { static constexpr size_t kIndexCapacity = 1024; std::vector<uint64_t> subkeys(kIndexCapacity - 1); std::iota(subkeys.begin(), subkeys.end(), 123'000'000'000ull); std::mt19937 rng{std::random_device{}()}; for (uint64_t run_id = begin_id; run_id < end_id; ++run_id) { HeaderBlock* header_block = HeaderBlock::CreateBlob(*behavior_, kBaseVersion, kIndexCapacity); ASSERT_NE(header_block, nullptr); MutatingBlobAccessor accessor(*header_block); EXPECT_EQ(accessor.remaining_index_slots_capacity(), kIndexCapacity); EXPECT_TRUE(accessor.CanInsertStateBlocks(kIndexCapacity)); EXPECT_FALSE(accessor.CanInsertStateBlocks(kIndexCapacity + 1)); accessor.InsertKeyBlock(*behavior_, behavior_->MakeKey(5)); KeyStateAndIndexView key_state_view = accessor.FindKeyStateAndIndex(MakeKeyDescriptor(5)); ASSERT_TRUE(key_state_view.state_block_); EXPECT_EQ(key_state_view.key(), KeyHandle{5}); std::shuffle(begin(subkeys), end(subkeys), rng); EXPECT_TRUE(accessor.CanInsertStateBlocks(subkeys.size())); EXPECT_FALSE(accessor.CanInsertStateBlocks(subkeys.size() + 1)); for (uint64_t subkey : subkeys) { accessor.InsertSubkeyBlock(*behavior_, *key_state_view.state_block_, subkey); } // The index is full EXPECT_FALSE(accessor.CanInsertStateBlocks(1)); KeyBlockIterator key_it = accessor.begin(); ASSERT_NE(key_it, accessor.end()); EXPECT_EQ(key_it->version_block_, nullptr); EXPECT_EQ(key_it->key(), KeyHandle{5}); SubkeyBlockIterator subkey_it = accessor.GetSubkeys(*key_it).begin(); const auto search_key = MakeKeyDescriptor(5); // Iterator traverses through subkeys in sorted order. for (size_t i = 0; i < subkeys.size(); ++i) { const uint64_t subkey = 123'000'000'000ull + i; ASSERT_NE(subkey_it, SubkeyBlockIterator::End{}); EXPECT_EQ(subkey_it->version_block_, nullptr); EXPECT_EQ(subkey_it->key(), KeyHandle{5}); EXPECT_EQ(subkey_it->subkey(), subkey); // The subkey can also be found directly. const SubkeyStateBlock* block = accessor.FindSubkeyState(search_key, subkey).state_block_; ASSERT_TRUE(block); EXPECT_EQ(block->key_, KeyHandle{5}); EXPECT_EQ(block->subkey_, subkey); ++subkey_it; } EXPECT_EQ(subkey_it, SubkeyBlockIterator::End{}); ++key_it; EXPECT_EQ(key_it, accessor.end()); header_block->RemoveSnapshotReference(kBaseVersion, *behavior_); } }); } TEST_F(HeaderBlock_Test, subkey_hashes_fuzzing) { // Tries inserting random unique subkeys in various random orders, expecting // that the subkeys are discoverable and ordered after the insertion. // This test is likely to encounter all kinds of small hash collisions, // index block overflows etc. Testing::RunInParallel(1000, [this](uint64_t begin_id, uint64_t end_id) { static constexpr size_t kIndexCapacity = 256; std::vector<uint64_t> sorted_subkeys(kIndexCapacity - 1); std::vector<uint64_t> shuffled_subkeys(kIndexCapacity - 1); std::mt19937 rng{std::random_device{}()}; std::uniform_int_distribution<uint64_t> distribution(0, ~0ull); for (uint64_t run_id = begin_id; run_id < end_id; ++run_id) { for (auto& subkey : shuffled_subkeys) subkey = distribution(rng); sorted_subkeys = shuffled_subkeys; std::sort(begin(sorted_subkeys), end(sorted_subkeys)); if (std::unique(begin(sorted_subkeys), end(sorted_subkeys)) != end(sorted_subkeys)) { // The collision between subkeys is unlikely, so we simply skip the // iteration in case of it. // The test below expects all random subkeys to be unique. continue; } HeaderBlock* header_block = HeaderBlock::CreateBlob(*behavior_, kBaseVersion, kIndexCapacity); ASSERT_NE(header_block, nullptr); MutatingBlobAccessor accessor(*header_block); EXPECT_EQ(accessor.remaining_index_slots_capacity(), kIndexCapacity); EXPECT_TRUE(accessor.CanInsertStateBlocks(kIndexCapacity)); EXPECT_FALSE(accessor.CanInsertStateBlocks(kIndexCapacity + 1)); accessor.InsertKeyBlock(*behavior_, behavior_->MakeKey(5)); KeyStateAndIndexView key_state_view = accessor.FindKeyStateAndIndex(MakeKeyDescriptor(5)); ASSERT_TRUE(key_state_view.state_block_); EXPECT_EQ(key_state_view.key(), KeyHandle{5}); ASSERT_TRUE(accessor.CanInsertStateBlocks(shuffled_subkeys.size())); EXPECT_FALSE(accessor.CanInsertStateBlocks(shuffled_subkeys.size() + 1)); for (uint64_t subkey : shuffled_subkeys) accessor.InsertSubkeyBlock(*behavior_, *key_state_view.state_block_, subkey); // The index is full EXPECT_FALSE(accessor.CanInsertStateBlocks(1)); KeyBlockIterator key_it = accessor.begin(); ASSERT_NE(key_it, accessor.end()); EXPECT_EQ(key_it->version_block_, nullptr); EXPECT_EQ(key_it->key(), KeyHandle{5}); SubkeyBlockIterator subkey_it = accessor.GetSubkeys(*key_it).begin(); const auto search_key = MakeKeyDescriptor(5); // Iterator traverses through subkeys in sorted order. for (uint64_t subkey : sorted_subkeys) { ASSERT_NE(subkey_it, SubkeyBlockIterator::End{}); EXPECT_EQ(subkey_it->version_block_, nullptr); EXPECT_EQ(subkey_it->key(), KeyHandle{5}); EXPECT_EQ(subkey_it->subkey(), subkey); // The subkey can also be found directly. const SubkeyStateBlock* block = accessor.FindSubkeyState(search_key, subkey).state_block_; ASSERT_TRUE(block); EXPECT_EQ(block->key_, KeyHandle{5}); EXPECT_EQ(block->subkey_, subkey); ++subkey_it; } EXPECT_EQ(subkey_it, SubkeyBlockIterator::End{}); ++key_it; EXPECT_EQ(key_it, accessor.end()); header_block->RemoveSnapshotReference(kBaseVersion, *behavior_); } }); } TEST_F(HeaderBlock_Test, empty_versions) { // Inserting a number of empty versions with no changes and verifying that // they consume the state blocks. HeaderBlock* header_block = HeaderBlock::CreateBlob(*behavior_, kBaseVersion, 7); ASSERT_NE(header_block, nullptr); EXPECT_EQ(behavior_->total_allocated_pages_count(), 1); MutatingBlobAccessor accessor(*header_block); EXPECT_EQ(accessor.remaining_index_slots_capacity(), 7); // There are 64 blocks total; 1 is occupied by the header, and 1 is occupied // by the index. An extra block stores the refcount for the base version. EXPECT_EQ(header_block->data_blocks_capacity(), 62); EXPECT_EQ(accessor.available_data_blocks_count(), 61); for (int i = 0; i < 15; ++i) { ASSERT_TRUE(accessor.AddVersion()); } // All 16 versions (including the base one, that was created by CreateBlob() // call) should fit into one block. EXPECT_EQ(accessor.available_data_blocks_count(), 61); // Each group of 16 versions consumes an extra block for (uint32_t group_id = 0; group_id < 61; ++group_id) { for (int i = 0; i < 16; ++i) { ASSERT_TRUE(accessor.AddVersion()); EXPECT_EQ(accessor.available_data_blocks_count(), 60 - group_id); } } // No more versions can be added. EXPECT_FALSE(accessor.AddVersion()); for (uint64_t i = 0; i < 16 * 62; ++i) { header_block->RemoveSnapshotReference(kBaseVersion + i, *behavior_); } } class PrepareTransaction_Test : public HeaderBlock_Test { public: PrepareTransaction_Test() : header_block_{HeaderBlock::CreateBlob(*behavior_, kBaseVersion, 7)}, accessor_{*header_block_} { EXPECT_NE(header_block_, nullptr); // There are 64 blocks total; 1 is occupied by the header, and 1 is // occupied by the index. An extra block stores the refcount for the base // version. EXPECT_EQ(header_block_->data_blocks_capacity(), 62); EXPECT_EQ(accessor_.available_data_blocks_count(), 61); // Adding a key and a few subkeys accessor_.InsertKeyBlock(*behavior_, behavior_->MakeKey(5)); KeyStateView key_state_view = accessor_.FindKeyState(MakeKeyDescriptor(5)); for (uint64_t subkey = 0; subkey < 6; ++subkey) { accessor_.InsertSubkeyBlock(*behavior_, *key_state_view.state_block_, subkey); } EXPECT_EQ(accessor_.available_data_blocks_count(), 54); } protected: static bool KeyMatches(const KeyStateView& key_state_view, uint64_t key) noexcept { return key_state_view.state_block_ && key_state_view.key() == KeyHandle{key}; } uint32_t GetSubkeyCountForVersion(uint64_t version) noexcept { if (KeyStateView view = accessor_.FindKeyState(MakeKeyDescriptor(5))) return view.GetSubkeysCount(MakeVersionOffset(version, kBaseVersion)); return 0; } static bool KeySubkeyMatch(const SubkeyStateView& subkey_state_view, uint64_t key, uint64_t subkey) noexcept { return subkey_state_view.state_block_ && subkey_state_view.key() == KeyHandle{key} && subkey_state_view.subkey() == subkey; } VersionedPayloadHandle Find(uint64_t version, uint64_t subkey) { if (SubkeyStateView view = accessor_.FindSubkeyState(MakeKeyDescriptor(5), subkey)) return view.GetPayload(version); return {}; } HeaderBlock* header_block_; MutatingBlobAccessor accessor_; }; TEST_F(PrepareTransaction_Test, inserting_subkey_version) { uint64_t subkey = 2; SubkeyStateAndIndexView subkey_state_view = accessor_.FindSubkeyStateAndIndex(MakeKeyDescriptor(5), subkey); ASSERT_TRUE(accessor_.ReserveSpaceForTransaction(subkey_state_view, kBaseVersion, true)); EXPECT_TRUE(KeySubkeyMatch(subkey_state_view, 5, subkey)); EXPECT_FALSE(subkey_state_view.version_block_); // The operation didn't consume any version blocks EXPECT_EQ(accessor_.available_data_blocks_count(), 54); // This takes the ownership of the payload, and the reference should be // released when the block is destroyed. subkey_state_view.state_block_->PushFromWriterThread(kBaseVersion, MakePayload(42)); // The subkey doesn't exist before this version EXPECT_FALSE(Find(0, subkey)); EXPECT_FALSE(Find(kBaseVersion - 1, subkey)); // The subkey exists after this version. for (uint64_t i = 0; i < 10; ++i) { ASSERT_TRUE(Find(kBaseVersion + i, subkey)); EXPECT_EQ(Find(kBaseVersion + i, subkey).payload(), PayloadHandle{42}); EXPECT_EQ(Find(kBaseVersion + i, subkey).version(), kBaseVersion); } ASSERT_TRUE(accessor_.AddVersion()); // Now trying without a precondition, but attempting to write the payload // that is already there. EXPECT_TRUE(accessor_.ReserveSpaceForTransaction(subkey_state_view, kBaseVersion + 1, false)); // The operation didn't consume any version blocks EXPECT_EQ(accessor_.available_data_blocks_count(), 54); subkey_state_view.state_block_->PushFromWriterThread(kBaseVersion + 1, {}); // The subkey doesn't exist before the first version EXPECT_FALSE(Find(kBaseVersion - 1, subkey)); // Payload 42 is still visible to the base version ASSERT_TRUE(Find(kBaseVersion, subkey)); EXPECT_EQ(Find(kBaseVersion, subkey).payload(), PayloadHandle{42}); EXPECT_EQ(Find(kBaseVersion, subkey).version(), kBaseVersion); // But in the next version it's deleted EXPECT_FALSE(Find(kBaseVersion + 1, subkey)); // This version should allocate a new version block (with both existing // versions and enough space for one more version). ASSERT_TRUE(accessor_.AddVersion()); EXPECT_EQ(accessor_.available_data_blocks_count(), 54); ASSERT_TRUE(accessor_.ReserveSpaceForTransaction(subkey_state_view, kBaseVersion + 2, true)); // The operation consumed one version block. EXPECT_EQ(accessor_.available_data_blocks_count(), 53); EXPECT_TRUE(subkey_state_view.version_block_); subkey_state_view.version_block_->PushFromWriterThread(kBaseVersion + 2, MakePayload(43)); // The subkey doesn't exist before the first version. EXPECT_FALSE(Find(kBaseVersion - 1, subkey)); // Payload 42 is duplicated in the new version block. ASSERT_TRUE(Find(kBaseVersion, subkey)); EXPECT_EQ(Find(kBaseVersion, subkey).payload(), PayloadHandle{42}); EXPECT_EQ(Find(kBaseVersion, subkey).version(), kBaseVersion); // The deletion marker for the next version is also duplicated. EXPECT_FALSE(Find(kBaseVersion + 1, subkey)); // Newly published version is visible. ASSERT_TRUE(Find(kBaseVersion + 2, subkey)); EXPECT_EQ(Find(kBaseVersion + 2, subkey).payload(), PayloadHandle{43}); EXPECT_EQ(Find(kBaseVersion + 2, subkey).version(), kBaseVersion + 2); // This version should fit into existing version block. ASSERT_TRUE(accessor_.AddVersion()); ASSERT_TRUE(accessor_.ReserveSpaceForTransaction(subkey_state_view, kBaseVersion + 3, false)); // The operation didn't consume a version block. EXPECT_EQ(accessor_.available_data_blocks_count(), 53); EXPECT_TRUE(subkey_state_view.version_block_); subkey_state_view.version_block_->PushFromWriterThread(kBaseVersion + 3, {}); EXPECT_FALSE(Find(kBaseVersion - 1, subkey)); ASSERT_TRUE(Find(kBaseVersion, subkey)); EXPECT_EQ(Find(kBaseVersion, subkey).payload(), PayloadHandle{42}); EXPECT_EQ(Find(kBaseVersion, subkey).version(), kBaseVersion); EXPECT_FALSE(Find(kBaseVersion + 1, subkey)); ASSERT_TRUE(Find(kBaseVersion + 2, subkey)); EXPECT_EQ(Find(kBaseVersion + 2, subkey).payload(), PayloadHandle{43}); EXPECT_EQ(Find(kBaseVersion + 2, subkey).version(), kBaseVersion + 2); EXPECT_FALSE(Find(kBaseVersion + 3, subkey)); // Forgetting about the version where the payload was deleted the first // time. This will influence which versions will survive the reallocation of // the version block. header_block_->RemoveSnapshotReference(kBaseVersion + 1, *behavior_); ASSERT_TRUE(accessor_.AddVersion()); ASSERT_TRUE(accessor_.ReserveSpaceForTransaction(subkey_state_view, kBaseVersion + 4, true)); // The operation consumed two new version blocks. EXPECT_EQ(accessor_.available_data_blocks_count(), 51); EXPECT_TRUE(subkey_state_view.version_block_); subkey_state_view.version_block_->PushFromWriterThread(kBaseVersion + 4, MakePayload(44)); EXPECT_FALSE(Find(kBaseVersion - 1, subkey)); ASSERT_TRUE(Find(kBaseVersion, subkey)); EXPECT_EQ(Find(kBaseVersion, subkey).payload(), PayloadHandle{42}); EXPECT_EQ(Find(kBaseVersion, subkey).version(), kBaseVersion); // The information about this version did not migrate to the new version // block (because we removed the reference to this version above). Because // of that, we see the previous version instead of a deletion marker. In the // actual use case scenario we would never perform a search for an // unreferenced version, but here this checks the reallocation strategy. ASSERT_TRUE(Find(kBaseVersion + 1, subkey)); EXPECT_EQ(Find(kBaseVersion + 1, subkey).payload(), PayloadHandle{42}); // Note: inserted in the previous version (the deletion marker that was here // instead is now missing). EXPECT_EQ(Find(kBaseVersion + 1, subkey).version(), kBaseVersion); ASSERT_TRUE(Find(kBaseVersion + 2, subkey)); EXPECT_EQ(Find(kBaseVersion + 2, subkey).payload(), PayloadHandle{43}); EXPECT_EQ(Find(kBaseVersion + 2, subkey).version(), kBaseVersion + 2); EXPECT_FALSE(Find(kBaseVersion + 3, subkey)); ASSERT_TRUE(Find(kBaseVersion + 4, subkey)); EXPECT_EQ(Find(kBaseVersion + 4, subkey).payload(), PayloadHandle{44}); EXPECT_EQ(Find(kBaseVersion + 4, subkey).version(), kBaseVersion + 4); header_block_->RemoveSnapshotReference(kBaseVersion, *behavior_); header_block_->RemoveSnapshotReference(kBaseVersion + 2, *behavior_); header_block_->RemoveSnapshotReference(kBaseVersion + 3, *behavior_); header_block_->RemoveSnapshotReference(kBaseVersion + 4, *behavior_); } TEST_F(PrepareTransaction_Test, inserting_key_versions) { // First, pushing 3 subkey counts (all of them should fit into the in-place // storage within the state block) for (uint32_t i = 0; i < 3; ++i) { KeyStateAndIndexView key_state_view = accessor_.FindKeyStateAndIndex(MakeKeyDescriptor(5)); uint32_t new_count = 9000 + i; ASSERT_TRUE(accessor_.ReserveSpaceForTransaction(key_state_view)); EXPECT_TRUE(KeyMatches(key_state_view, 5)); EXPECT_FALSE(key_state_view.version_block_); // The operation didn't consume any version blocks EXPECT_EQ(accessor_.available_data_blocks_count(), 54); ASSERT_TRUE(key_state_view.state_block_->has_empty_slots_thread_unsafe()); key_state_view.state_block_->PushSubkeysCountFromWriterThread( VersionOffset{i}, new_count); // All inserted versions are visible for (uint32_t j = 0; j <= i; ++j) { EXPECT_EQ(GetSubkeyCountForVersion(kBaseVersion + j), 9000 + j); } ASSERT_TRUE(accessor_.AddVersion()); } // The next 4 versions will use a version block. // (the existing 3 versions will be copied there since they are referenced). for (uint32_t i = 3; i < 7; ++i) { KeyStateAndIndexView key_state_view = accessor_.FindKeyStateAndIndex(MakeKeyDescriptor(5)); const uint32_t new_count = 9000 + i; ASSERT_TRUE(accessor_.ReserveSpaceForTransaction(key_state_view)); EXPECT_TRUE(KeyMatches(key_state_view, 5)); ASSERT_TRUE(key_state_view.version_block_); // All versions are in the same version block. EXPECT_EQ(accessor_.available_data_blocks_count(), 53); ASSERT_TRUE(key_state_view.version_block_->has_empty_slots_thread_unsafe()); key_state_view.version_block_->PushSubkeysCountFromWriterThread( VersionOffset{i}, new_count); // All inserted versions are visible for (uint32_t j = 0; j <= i; ++j) { EXPECT_EQ(GetSubkeyCountForVersion(kBaseVersion + j), 9000 + j); } EXPECT_TRUE(accessor_.AddVersion()); } // Dereferencing a single version. header_block_->RemoveSnapshotReference(kBaseVersion + 2, *behavior_); KeyStateAndIndexView key_state_view = accessor_.FindKeyStateAndIndex(MakeKeyDescriptor(5)); ASSERT_TRUE(accessor_.ReserveSpaceForTransaction(key_state_view)); EXPECT_TRUE(KeyMatches(key_state_view, 5)); ASSERT_TRUE(key_state_view.version_block_); // Two new blocks were allocated, since 6 out of 7 previous versions are // still alive and have to be preserved. EXPECT_EQ(accessor_.available_data_blocks_count(), 51); EXPECT_EQ(key_state_view.version_block_->capacity(), 15); EXPECT_EQ(key_state_view.version_block_->size_relaxed(), 6); key_state_view.version_block_->PushSubkeysCountFromWriterThread( VersionOffset{7}, 9007); EXPECT_EQ(key_state_view.version_block_->size_relaxed(), 7); EXPECT_EQ(GetSubkeyCountForVersion(kBaseVersion), 9000); EXPECT_EQ(GetSubkeyCountForVersion(kBaseVersion + 1), 9001); // This version was unreferenced above and didn't migrate into the new // version blocks, so the storage doesn't know that at some the value was // 9002. In the actual use case scenario we would never perform a search for // an unreferenced version, but here this checks the reallocation strategy. // 9001 here is not a typo: EXPECT_EQ(GetSubkeyCountForVersion(kBaseVersion + 2), 9001); EXPECT_EQ(GetSubkeyCountForVersion(kBaseVersion + 3), 9003); EXPECT_EQ(GetSubkeyCountForVersion(kBaseVersion + 4), 9004); EXPECT_EQ(GetSubkeyCountForVersion(kBaseVersion + 5), 9005); EXPECT_EQ(GetSubkeyCountForVersion(kBaseVersion + 6), 9006); EXPECT_EQ(GetSubkeyCountForVersion(kBaseVersion + 7), 9007); for (int i = 0; i < 8; ++i) { // Version kBaseVersion + 2 was unreferenced during the test if (i != 2) { header_block_->RemoveSnapshotReference(kBaseVersion + i, *behavior_); } } } } // namespace Microsoft::MixedReality::Sharing::VersionedStorage::Detail
39.680254
84
0.710663
[ "vector" ]
f8fffb4b8f014cad74d08cc701151dc896dfacbd
1,603
cpp
C++
aws-cpp-sdk-rekognition/source/model/StartFaceDetectionRequest.cpp
lintonv/aws-sdk-cpp
15e19c265ffce19d2046b18aa1b7307fc5377e58
[ "Apache-2.0" ]
1
2022-02-12T08:09:30.000Z
2022-02-12T08:09:30.000Z
aws-cpp-sdk-rekognition/source/model/StartFaceDetectionRequest.cpp
lintonv/aws-sdk-cpp
15e19c265ffce19d2046b18aa1b7307fc5377e58
[ "Apache-2.0" ]
1
2021-10-14T16:57:00.000Z
2021-10-18T10:47:24.000Z
aws-cpp-sdk-rekognition/source/model/StartFaceDetectionRequest.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/rekognition/model/StartFaceDetectionRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Rekognition::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; StartFaceDetectionRequest::StartFaceDetectionRequest() : m_videoHasBeenSet(false), m_clientRequestTokenHasBeenSet(false), m_notificationChannelHasBeenSet(false), m_faceAttributes(FaceAttributes::NOT_SET), m_faceAttributesHasBeenSet(false), m_jobTagHasBeenSet(false) { } Aws::String StartFaceDetectionRequest::SerializePayload() const { JsonValue payload; if(m_videoHasBeenSet) { payload.WithObject("Video", m_video.Jsonize()); } if(m_clientRequestTokenHasBeenSet) { payload.WithString("ClientRequestToken", m_clientRequestToken); } if(m_notificationChannelHasBeenSet) { payload.WithObject("NotificationChannel", m_notificationChannel.Jsonize()); } if(m_faceAttributesHasBeenSet) { payload.WithString("FaceAttributes", FaceAttributesMapper::GetNameForFaceAttributes(m_faceAttributes)); } if(m_jobTagHasBeenSet) { payload.WithString("JobTag", m_jobTag); } return payload.View().WriteReadable(); } Aws::Http::HeaderValueCollection StartFaceDetectionRequest::GetRequestSpecificHeaders() const { Aws::Http::HeaderValueCollection headers; headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "RekognitionService.StartFaceDetection")); return headers; }
22.263889
106
0.762944
[ "model" ]
5d046db8b032c2f006e354bb31dacdfa8b42143b
25,047
tpp
C++
src/Mesh.tpp
asterycs/rtsr
176bf342581daa58f84eaffc6d34034a98cfa255
[ "MIT" ]
13
2018-07-09T23:38:29.000Z
2022-01-05T09:06:46.000Z
src/Mesh.tpp
haohanxingkong/rtsr
176bf342581daa58f84eaffc6d34034a98cfa255
[ "MIT" ]
2
2019-01-05T14:38:55.000Z
2019-02-14T18:33:46.000Z
src/Mesh.tpp
haohanxingkong/rtsr
176bf342581daa58f84eaffc6d34034a98cfa255
[ "MIT" ]
5
2018-08-22T12:30:28.000Z
2022-01-20T13:09:24.000Z
#include "Mesh.hpp" #include "igl/barycentric_coordinates.h" #include "Util.hpp" #include <Eigen/QR> #include <iostream> #include <cstdlib> #include <iostream> template <typename T> using Mat = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>; template <typename T> using VecC3 = Eigen::Matrix<T, 3, 1>; template <typename T> using VecC2 = Eigen::Matrix<T, 2, 1>; template <typename T> using VecR3 = Eigen::Matrix<T, 1, 3>; template <typename T> Mesh<T>::Mesh() { #ifdef ENABLE_CUDA std::cout << " ----**** Creating mesh with CUDA solver ****----" << std::endl; #else std::cout << " ----**** Creating mesh with CPU solver ****----" << std::endl; #endif color_counter = Eigen::MatrixXi::Zero(TEXTURE_RESOLUTION, TEXTURE_RESOLUTION); texture.red = Eigen::Matrix<unsigned char, Eigen::Dynamic, Eigen::Dynamic>::Constant(TEXTURE_RESOLUTION,TEXTURE_RESOLUTION, static_cast<unsigned char>(115)); texture.green = Eigen::Matrix<unsigned char, Eigen::Dynamic, Eigen::Dynamic>::Constant(TEXTURE_RESOLUTION,TEXTURE_RESOLUTION, static_cast<unsigned char>(115)); texture.blue = Eigen::Matrix<unsigned char, Eigen::Dynamic, Eigen::Dynamic>::Constant(TEXTURE_RESOLUTION,TEXTURE_RESOLUTION, static_cast<unsigned char>(115)); } template <typename T> Mesh<T>::~Mesh() { std::ofstream residual_file; residual_file.open("error.csv"); residual_file << "pc_idx,level,iteration,residuals\n"; for (int pci = 0; pci < residuals.size(); ++pci) { for (int li = 0; li < residuals[pci].size(); ++li) { for (int it = 0; it < residuals[pci][li].size(); ++it) residual_file << pci << "," << li << "," << it << "," << residuals[pci][li][it] << std::endl; } } residual_file.close(); } template <typename T> void Mesh<T>::cleanup() { #ifdef ENABLE_CUDA cudaDeviceSynchronize(); #endif for (auto& m : JtJ) m.clear(); for (auto& v : Jtz) v.clear(); } inline int subdivided_side_length(const int level, const int base_resolution) { return (base_resolution-1)*static_cast<int>(std::pow(2,level))+1; } template <typename T> void upsample(const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& V, const Eigen::MatrixXi& F, Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& V_out, Eigen::MatrixXi& F_out) { const int old_resolution = static_cast<int>(std::sqrt(static_cast<double>(V.rows()))); const int resolution = subdivided_side_length(1, old_resolution); const int faces = (resolution - 1) * (resolution - 1) * 2; const int vertices = resolution * resolution; F_out = Eigen::MatrixXi::Zero(faces, 3); V_out = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>::Zero(vertices, 3); #pragma omp parallel for for (int y_step = 0; y_step < old_resolution-1; ++y_step) { for (int x_step = 0; x_step < old_resolution-1; ++x_step) { Eigen::Vector3i f_u = F.row(x_step*2 + y_step*(old_resolution-1)*2); Eigen::Vector3i f_l = F.row(x_step*2 + y_step*(old_resolution-1)*2 + 1); const VecC3<T> old_v0 = V.row(f_u(0)); const VecC3<T> old_v1 = V.row(f_u(1)); const VecC3<T> old_v2 = V.row(f_u(2)); const VecC3<T> old_v3 = V.row(f_l(0)); const VecC3<T> old_v4 = V.row(f_l(1)); //const TvecC3 old_v5 = V.row(f_l(2)); const VecC3<T> v0 = old_v0; const VecC3<T> v1 = (old_v0 + old_v1) * T(0.5); const VecC3<T> v2 = old_v1; const VecC3<T> v3 = (old_v0 + old_v2) * T(0.5); const VecC3<T> v4 = (old_v2 + old_v1) * T(0.5); const VecC3<T> v5 = (old_v3 + old_v1) * T(0.5); const VecC3<T> v6 = old_v2; const VecC3<T> v7 = (old_v3 + old_v4) * T(0.5); const VecC3<T> v8 = old_v3; const int new_v_xi = x_step * 2; const int new_v_yi = y_step * 2; int v0i = new_v_xi + new_v_yi * resolution, v1i = new_v_xi + 1 + new_v_yi * resolution, v2i = new_v_xi + 2+ new_v_yi * resolution, v3i = new_v_xi + (new_v_yi+1) * resolution, v4i = new_v_xi + 1 + (new_v_yi+1) * resolution, v5i = new_v_xi + 2 + (new_v_yi+1) * resolution, v6i = new_v_xi + (new_v_yi+2) * resolution, v7i = new_v_xi + 1 + (new_v_yi+2) * resolution, v8i = new_v_xi + 2 + (new_v_yi+2) * resolution; V_out.row(v0i) = v0; V_out.row(v1i) = v1; V_out.row(v3i) = v3; V_out.row(v4i) = v4; if (x_step == old_resolution-2) { V_out.row(v2i) = v2; V_out.row(v5i) = v5; } if (y_step == old_resolution-2) { V_out.row(v6i) = v6; V_out.row(v7i) = v7; } if (x_step == old_resolution - 2 && y_step == old_resolution-2) V_out.row(v8i) = v8; const int new_f_xi = x_step * 2; const int new_f_yi = y_step * 2; F_out.row(2*new_f_xi + new_f_yi * (resolution-1) * 2) << v0i,v1i,v3i; F_out.row(2*new_f_xi + 1 + new_f_yi * (resolution-1) * 2) << v4i,v3i,v1i; F_out.row(2*new_f_xi + 2 + new_f_yi * (resolution-1) * 2) << v1i,v2i,v4i; F_out.row(2*new_f_xi + 3 + new_f_yi * (resolution-1) * 2) << v5i,v4i,v2i; F_out.row(2*new_f_xi + (new_f_yi+1) * (resolution-1)*2) << v3i,v4i,v6i; F_out.row(2*new_f_xi + 1 + (new_f_yi+1) * (resolution-1)*2) << v7i,v6i,v4i; F_out.row(2*new_f_xi + 2 + (new_f_yi+1) * (resolution-1)*2) << v4i,v5i,v7i; F_out.row(2*new_f_xi + 3 + (new_f_yi+1) * (resolution-1)*2) << v8i,v7i,v5i; } } } template <typename T> void upsample(const unsigned int levels, const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& V, const Eigen::MatrixXi& F, Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& V_out, Eigen::MatrixXi& F_out) { if (levels < 1) { V_out = V; F_out = F; return; } Eigen::MatrixXi F_in = F; Mat<T> V_in = V; for (unsigned int i = 0; i < levels; ++i) { upsample(V_in, F_in, V_out, F_out); F_in = F_out; V_in = V_out; } } // Compute barycentric coordinates based on the corner points of a triangle template <typename T> void barycentric(const VecC2<T>& p, const Eigen::Matrix<T, 2, 1>& a, const Eigen::Matrix<T, 2, 1>& b, const Eigen::Matrix<T, 2, 1>& c, T &u, T &v, T &w) { Eigen::Matrix<T, 2, 1> v0 = b - a, v1 = c - a, v2 = p - a; T a00 = v0.dot(v0); T a01 = v0.dot(v1); T a11 = v1.dot(v1); T a20 = v2.dot(v0); T a21 = v2.dot(v1); T den = 1 / (a00 * a11 - a01 * a01); v = (a11 * a20 - a01 * a21) * den; w = (a00 * a21 - a01 * a20) * den; u = T(1.0) - v - w; } template <typename T> template <typename Derived> void Mesh<T>::align_to_point_cloud(const Eigen::MatrixBase<Derived>& P) { const VecR3<T> bb_min = P.colwise().minCoeff(); const VecR3<T> bb_max = P.colwise().maxCoeff(); const VecR3<T> bb_d = (bb_max - bb_min).cwiseAbs(); JtJ.resize(MESH_LEVELS); Jtz.resize(MESH_LEVELS); V.resize(MESH_LEVELS); F.resize(MESH_LEVELS); const int max_resolution = subdivided_side_length(MESH_LEVELS - 1, MESH_RESOLUTION); const Eigen::Matrix<T, 2, 1> a(0.f, 0.f), b(1.f, 0.f), c(0.f, 1.f), d(1.f, 1.f); for (int li = 0; li < MESH_LEVELS; ++li) { const T scaling_factor(MESH_SCALING_FACTOR); const int resolution = subdivided_side_length(li, MESH_RESOLUTION); // Scaling matrix const Eigen::Transform<T, 3, Eigen::Affine> scaling(Eigen::Scaling(VecC3<T>(scaling_factor*bb_d(0)/T(resolution), 0.f,scaling_factor*bb_d(2)/T(resolution)))); //const TvecR3 pc_mean = P.colwise().mean(); // P_centr: mean of the point cloud VecR3<T> P_centr = bb_min + 0.5f*(bb_max - bb_min); P_centr(1) = 0.0; const Eigen::Transform<T, 3, Eigen::Affine> t(Eigen::Translation<T, 3>(P_centr.transpose())); transform = t.matrix(); V[li].resize(resolution*resolution, 3); F[li].resize((resolution-1)*(resolution-1)*2, 3); JtJ[li].resize(resolution); Jtz[li].resize(resolution); #pragma omp parallel for for (int z_step = 0; z_step < resolution; ++z_step) { for (int x_step = 0; x_step < resolution; ++x_step) { Eigen::Matrix<T, 1, 4> v; v << VecR3<T>(T(x_step)-T(resolution-1)/2.f,T(0.0), T(z_step)-T(resolution-1)/2.f),T(1.0); VecR3<T> pos; if (li == 0) // Only transform the first layer. Subsequent layers only denot a difference between the first pos << (v * scaling.matrix().transpose() * transform.transpose()).template head<3>(); else pos << (v * scaling.matrix().transpose()).template head<3>(); V[li].row(x_step + z_step*resolution) << pos; } } #pragma omp parallel for for (int y_step = 0; y_step < resolution-1; ++y_step) { for (int x_step = 0; x_step < resolution-1; ++x_step) { F[li].row(x_step*2 + y_step*(resolution-1)*2) << x_step+ y_step *resolution,x_step+1+y_step* resolution,x_step+(y_step+1)*resolution; F[li].row(x_step*2 + y_step*(resolution-1)*2 + 1) << x_step+1+(y_step+1)*resolution,x_step+ (y_step+1)*resolution,x_step+1+y_step*resolution; } } const int factor = static_cast<int>(std::pow(2, MESH_LEVELS - li - 1)); // Place constraints for every vertex on the highest resolution grid for all levels for (int i = 0; i < (max_resolution-1) * (max_resolution-1); ++i) { const int x = i % (max_resolution-1); const int y = i / (max_resolution-1); const int gx = x / factor; const int gy = y / factor; const int t = (gx + (resolution-1) * gy) * 2; // inside current resolution rect const T tx(static_cast<T>(x % factor) / static_cast<T>(factor)); const T ty(static_cast<T>(y % factor) / static_cast<T>(factor)); T u,v,w; const VecC2<T> p(tx, ty); if (tx + ty > T(1.)) { // lower right triangle barycentric(p, d, c, b, u, v, w); JtJ[li].update_triangle(t+1, u, v); Jtz[li].update_triangle(t+1, u, v, 0.f); } else { // upper left triangle barycentric(p, a, b, c, u, v, w); JtJ[li].update_triangle(t, u, v); Jtz[li].update_triangle(t, u, v, 0.f); } // Special cases > last cell, last column, last row if (x + 1 >= max_resolution - 1 && y + 1 >= max_resolution - 1) { const VecC2<T> p2(T(1.), T(1.)); barycentric(p2, d, c, b, u, v, w); JtJ[li].update_triangle(t+1, u, v); Jtz[li].update_triangle(t+1, u, v, 0.f); } if (x + 1 >= max_resolution - 1) { const VecC2<T> p2(T(1.), ty); barycentric(p2, d, c, b, u, v, w); JtJ[li].update_triangle(t+1, u, v); Jtz[li].update_triangle(t+1, u, v, 0.f); } if (y + 1 >= max_resolution - 1) { const VecC2<T> p2(tx, T(1.)); barycentric(p2, d, c, b, u, v, w); JtJ[li].update_triangle(t+1, u, v); Jtz[li].update_triangle(t+1, u, v, 0.f); } } } } template <typename T> void Mesh<T>::get_mesh(const unsigned int level, Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& V_out, Eigen::MatrixXi& F_out, ColorData& colordata) const { const int mesh_resolution = JtJ[level].get_mesh_width(); colordata.UV.resize(mesh_resolution*mesh_resolution, 2); const T tdx = T(1.0) / (mesh_resolution-1); for(int i = 0; i < mesh_resolution; i++) { for(int j = 0; j < mesh_resolution; j++) { const int index = j * mesh_resolution + i; colordata.UV(index, 0) = i*tdx; colordata.UV(index, 1) = j*tdx; } } colordata.texture.red = texture.red; colordata.texture.green = texture.green; colordata.texture.blue = texture.blue; get_mesh(level, V_out, F_out); } template <typename T> void Mesh<T>::get_mesh(const unsigned int level, Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& V_out, Eigen::MatrixXi& F_out) const { if (level < 1 || level > MESH_LEVELS - 1) { V_out = V[0]; F_out = F[0]; } else { upsample(level, V[0], F[0], V_out, F_out); for (unsigned int li = 1; li <= level; ++li) { Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> V_upsampled; Eigen::MatrixXi F_upsampled; upsample(level-li, V[li], F[li], V_upsampled, F_upsampled); V_out.col(1) += V_upsampled.col(1); } } } // Project all points onto the 2D plane, we only need to project onto XZ plane as the algorithm only runs on height fields // Also why we only need to project only when the input point cloud changes template <typename T> void Mesh<T>::project_points(const int level, Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& bc) const { bc = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>::Zero(current_target_point_cloud.rows(), 3); Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> Vl; Eigen::MatrixXi Fl; get_mesh(level, Vl, Fl); const int resolution = subdivided_side_length(level, MESH_RESOLUTION); // Upper left triangle. Used to compute the index of the triangle that is hit const VecC2<T> V_ul(Vl.row(0)(0), Vl.row(0)(2)); const VecC2<T> V_00(Vl.row(Fl.row(0)(0))(0), Vl.row(Fl.row(0)(0))(2)); const VecC2<T> V_01(Vl.row(Fl.row(0)(1))(0), Vl.row(Fl.row(0)(1))(2)); const VecC2<T> V_10(Vl.row(Fl.row(0)(2))(0), Vl.row(Fl.row(0)(2))(2)); const double dx = (V_01- V_00).norm(); const double dy = (V_10 - V_00).norm(); #pragma omp parallel for for (int pi = 0; pi < current_target_point_cloud.rows(); ++pi) { const VecC2<T> current_point(current_target_point_cloud.row(pi)(0), current_target_point_cloud.row(pi)(2)); const VecC2<T> offset(current_point - V_ul); const int c = static_cast<int>(offset(0) / dx); const int r = static_cast<int>(offset(1) / dy); const int inner_size = resolution - 1; // Indices are outside of mesh borders => a triangle cannot be hit if (c >= inner_size || r >= inner_size || c < 0 || r < 0) { bc.row(pi) << -1, T(0.0), T(0.0); continue; } const VecC3<T> ul_3d = Vl.row(c + r*resolution); const VecC3<T> br_3d = Vl.row(c + 1 + (r+1)*resolution); const VecC2<T> ul_reference(ul_3d(0), ul_3d(2)); const VecC2<T> br_reference(br_3d(0), br_3d(2)); const double ul_squared_dist = (ul_reference - current_point).squaredNorm(); const double br_squared_dist = (br_reference - current_point).squaredNorm(); VecC2<T> v_a; VecC2<T> v_b; VecC2<T> v_c; int f_idx = -1; // Find corner vertices of hit triangle if (ul_squared_dist <= br_squared_dist) { f_idx = 2 * c + r * 2 * inner_size; v_a << Vl.row(c + r*resolution)(0), Vl.row(c + r*resolution)(2); v_b << Vl.row(c+1 + r*resolution)(0),Vl.row(c+1 + r*resolution)(2); v_c << Vl.row(c + (r+1)*resolution)(0),Vl.row(c + (r+1)*resolution)(2); }else { f_idx = 2 * c + r * 2 * inner_size + 1; v_a << Vl.row(c+1 + (r+1)*resolution)(0),Vl.row(c+1 + (r+1)*resolution)(2); v_b << Vl.row(c + (r+1)*resolution)(0),Vl.row(c + (r+1)*resolution)(2); v_c << Vl.row(c+1 + r*resolution)(0),Vl.row(c+1 + r*resolution)(2); } T u,v,w; barycentric(current_point, v_a, v_b, v_c, u, v, w); bc.row(pi) << T(f_idx), u, v; } } template <typename T> void Mesh<T>::set_target_point_cloud(const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& P) { current_target_point_cloud = P; residuals.push_back(std::vector<std::vector<T>>(MESH_LEVELS-1)); // First fuse to base level Mat<T> bc; project_points(0, bc); update_JtJ(0, bc); // Update lh update_Jtz(0, bc, current_target_point_cloud.col(1)); for (int li = 1; li < MESH_LEVELS; ++li) { Mat<T> V_upsampled; Eigen::MatrixXi F_upsampled; get_mesh(li, V_upsampled, F_upsampled); project_points(li, bc); update_JtJ(li, bc); // Update lh } } template <typename T> void Mesh<T>::set_target_point_cloud(const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& P, const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& C) { set_target_point_cloud(P); if (C.rows() != P.rows()) return; const VecC3<T> bb_min = V[0].row(0); const VecC3<T> bb_max = V[0].row(V[0].rows()-1); const T cdx = (bb_max(0)-bb_min(0)) / static_cast<T>(TEXTURE_RESOLUTION-1); const T cdz = (bb_max(2)-bb_min(2)) / static_cast<T>(TEXTURE_RESOLUTION-1); for(int i=0; i<current_target_point_cloud.rows(); i++) { T x = current_target_point_cloud(i, 0) - bb_min(0); T z = current_target_point_cloud(i, 2) - bb_min(2); x = std::floor(x / cdx); z = std::floor(z / cdz); const int xi = static_cast<int>(x); const int zi = static_cast<int>(z); if (xi >= color_counter.rows() || zi >= color_counter.cols() || xi < 0 || zi < 0) continue; const int count = color_counter(xi, zi); texture.red(xi, zi) = static_cast<unsigned char>((texture.red(xi, zi) * count + (C(i,0)*255)) / (count + 1)); texture.green(xi, zi) = static_cast<unsigned char>((texture.green(xi, zi) * count + (C(i,1)*255)) / (count + 1)); texture.blue(xi, zi) = static_cast<unsigned char>((texture.blue(xi, zi) * count + (C(i,2)*255)) / (count + 1)); ++color_counter(xi, zi); } } template <typename T> void Mesh<T>::update_JtJ(const int level, const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& bc) { for (int i = 0; i < bc.rows(); ++i) { const VecR3<T>& row = bc.row(i); if (static_cast<int>(row(0)) == -1) continue; JtJ[level].update_triangle(static_cast<int>(row(0)), row(1), row(2)); } } template <typename T> void Mesh<T>::update_Jtz(const int level, const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& bc, const Eigen::Matrix<T, Eigen::Dynamic, 1>& z) { for (int i = 0; i < bc.rows(); ++i) { const VecR3<T>& row = bc.row(i); if (static_cast<int>(row(0)) == -1) continue; Jtz[level].update_triangle(static_cast<int>(row(0)), row(1), row(2), z(i)); } } template <typename T> void Mesh<T>::solve(const int iterations) { // First fuse to ba se level Mat<T> bc; // lh and rh for first layer already updated in set_target_point_cloud #ifdef ENABLE_CUDA sor_gpu(iterations, 0, V[0].col(1)); #else sor_parallel(iterations, 0, V[0].col(1)); #endif for (int li = 1; li < MESH_LEVELS; ++li) { Mat<T> residual_height = Mat<T>::Zero(current_target_point_cloud.rows(), current_target_point_cloud.cols()); Mat<T> V_upsampled; Eigen::MatrixXi F_upsampled; get_mesh(li, V_upsampled, F_upsampled); project_points(li, bc); // Compute residual #pragma omp parallel for for (int pi = 0; pi < bc.rows(); ++pi) { if (static_cast<int>(bc.row(pi)(0)) == -1) // No hit continue; const VecC3<T> v0 = V_upsampled.row(F_upsampled.row(static_cast<int>(bc.row(pi)(0)))(0)); const VecC3<T> v1 = V_upsampled.row(F_upsampled.row(static_cast<int>(bc.row(pi)(0)))(1)); const VecC3<T> v2 = V_upsampled.row(F_upsampled.row(static_cast<int>(bc.row(pi)(0)))(2)); // Ideally these should be equal, then there is no error const VecC3<T> solved_point = bc.row(pi)(1) * v0 + bc.row(pi)(2) * v1 + (1.f - bc.row(pi)(1) - bc.row(pi)(2)) * v2; const VecC3<T> measured_point = current_target_point_cloud.row(pi); residual_height.row(pi) = measured_point - solved_point; } residuals.back()[li-1].push_back(residual_height.array().sum()); // Update equation rh with residual update_Jtz(li, bc, residual_height.col(1)); #ifdef ENABLE_CUDA sor_gpu(iterations, li, V[li].col(1)); #else sor_parallel(iterations, li, V[li].col(1)); #endif } } // Basic solve without any parallelism template <typename T> void Mesh<T>::sor(const int iterations, const int level, Eigen::Ref<Eigen::Matrix<T, Eigen::Dynamic, 1>> h) const { const auto& Jtz_vec = Jtz[level]; const auto& Jtj_mat = JtJ[level]; // For each iteration, solve system for each vertex for(int it = 0; it < iterations; it++) { for (int vi = 0; vi < h.rows(); vi++) sor_inner(vi, Jtj_mat, Jtz_vec, h.data()); } } /* Solve system for a single vertex vi in the mesh vi is the vertex index, JtJ is the MatrixGrid, matrix on the lhs Jtz is the vector on the rhs h is an array of the vertex heights */ template <typename T> CUDA_HOST_DEVICE inline void sor_inner(const int vi, const JtJMatrixGrid<T>& JtJ, const JtzVector<T>& Jtz_vec, T* h) { T xn = Jtz_vec.get(vi); T acc = 0; T vals[6]; int ids[6]; T a; JtJ.get_matrix_values_for_vertex(vi, vals, ids, a); for (int j = 0; j < 6; ++j) acc += vals[j] * h[ids[j]]; xn -= acc; // Weighting of previous height vs newly solved height // only use new height if w = 1. const T w = 1.0; h[vi] = (1.f-w) * h[vi] + w*xn/a; } // Run solve in parallel by using four-color reordering template <typename T> void Mesh<T>::sor_parallel(const int iterations, const int level, Eigen::Ref<Eigen::Matrix<T, Eigen::Dynamic, 1>> h) const { const auto& Jtz_vec = Jtz[level]; const auto& Jtj_mat = JtJ[level]; const int resolution = JtJ[level].get_mesh_width(); for(int it = 0; it < iterations; it++) { #pragma omp parallel for collapse(2) for (int x = 0; x < resolution; x+=2) for (int y = 0; y < resolution; y+=2) { const int vi = x + y * resolution; sor_inner(vi, Jtj_mat, Jtz_vec, h.data()); } #pragma omp parallel for collapse(2) for (int x = 1; x < resolution; x+=2) for (int y = 0; y < resolution; y+=2) { const int vi = x + y * resolution; sor_inner(vi, Jtj_mat, Jtz_vec, h.data()); } #pragma omp parallel for collapse(2) for (int x = 0; x < resolution; x+=2) for (int y = 1; y < resolution; y+=2) { const int vi = x + y * resolution; sor_inner(vi, Jtj_mat, Jtz_vec, h.data()); } #pragma omp parallel for collapse(2) for (int x = 1; x < resolution; x+=2) for (int y = 1; y < resolution; y+=2) { const int vi = x + y * resolution; sor_inner(vi, Jtj_mat, Jtz_vec, h.data()); } } } // Define CUDA specific functions here #ifdef ENABLE_CUDA // This function solves a single iteration for a point based on the index // xoffset and yoffset define the offset of the four-color reordering __global__ void solve_kernel(const int xoffset, const int yoffset, const int mesh_width, const JtzVector<float> Jtz_vec, const JtJMatrixGrid<float> JtJ_mat, float* h) { const int idx = blockIdx.x * blockDim.x + threadIdx.x; if (idx >= mesh_width*mesh_width) { return; } const int x = ((idx) % mesh_width); const int y = ((idx) / mesh_width); const int vi = x + y * mesh_width; // Make sure that indices is okay for our offsets if ((x % 2 == xoffset) && (y % 2 == yoffset)) sor_inner(vi, JtJ_mat, Jtz_vec, h); } // GPU solve for non-float meshes, does not work template <typename T> void Mesh<T>::sor_gpu(const int, const int, Eigen::Ref<Eigen::Matrix<T, Eigen::Dynamic, 1>>) { assert(false && "GPU solver works only with float meshes"); } /* Function for solving the system on the GPU using CUDA Similar to the parallel solve this method uses four-color reordering and therefore there are four solve_kernel calls, GPU solver also only works with float meshes */ template <> void Mesh<float>::sor_gpu(const int iterations, const int level, Eigen::Ref<Eigen::Matrix<float, Eigen::Dynamic, 1>> h) { const JtJMatrixGrid<float> JtJ_mat = JtJ[level]; const JtzVector<float> Jtz_vec = Jtz[level]; const int mesh_width = JtJ[level].get_mesh_width(); const int mesh_width_squared = mesh_width*mesh_width; const int mat_width = JtJ[level].get_matrix_width(); //const int mat_width_squared = mat_width*mat_width; float *devH; CUDA_CHECK(cudaMalloc(&devH, h.rows() * sizeof(float))); CUDA_CHECK(cudaMemcpy(devH, h.data(), h.rows() * sizeof(float), cudaMemcpyHostToDevice)); dim3 block(64); dim3 grid((mesh_width_squared + block.x - 1) / block.x); for (int it = 0; it < iterations; it++) { solve_kernel<<<grid, block>>>(0, 0, mesh_width, Jtz_vec, JtJ_mat, devH); cudaDeviceSynchronize(); solve_kernel<<<grid, block>>>(1, 0, mesh_width, Jtz_vec, JtJ_mat, devH); cudaDeviceSynchronize(); solve_kernel<<<grid, block>>>(0, 1, mesh_width, Jtz_vec, JtJ_mat, devH); cudaDeviceSynchronize(); solve_kernel<<<grid, block>>>(1, 1, mesh_width, Jtz_vec, JtJ_mat, devH); cudaDeviceSynchronize(); } CUDA_CHECK(cudaMemcpy(h.data(), devH, h.rows() * sizeof(float), cudaMemcpyDeviceToHost)); CUDA_CHECK(cudaFree(devH)); } #endif
33.440587
206
0.604863
[ "mesh", "vector", "transform" ]
5d0b2449a296b0aa15a872508470f878bbe01c17
10,220
hh
C++
notebooks/tutorial04/wavefem.hh
dokempf/dune-jupyter-course
1da9c0c2a056952a738e8c7f5aa5aa00fb59442c
[ "BSD-3-Clause" ]
1
2022-01-21T03:16:12.000Z
2022-01-21T03:16:12.000Z
notebooks/tutorial04/wavefem.hh
dokempf/dune-jupyter-course
1da9c0c2a056952a738e8c7f5aa5aa00fb59442c
[ "BSD-3-Clause" ]
21
2021-04-22T13:52:59.000Z
2021-10-04T13:31:59.000Z
notebooks/tutorial04/wavefem.hh
dokempf/dune-jupyter-course
1da9c0c2a056952a738e8c7f5aa5aa00fb59442c
[ "BSD-3-Clause" ]
1
2021-04-21T08:20:02.000Z
2021-04-21T08:20:02.000Z
#include<vector> #include<dune/common/exceptions.hh> #include<dune/common/fvector.hh> #include<dune/geometry/referenceelements.hh> #include<dune/geometry/type.hh> #include<dune/pdelab/common/geometrywrapper.hh> #include<dune/pdelab/common/quadraturerules.hh> #include<dune/pdelab/localoperator/defaultimp.hh> #include<dune/pdelab/localoperator/pattern.hh> #include<dune/pdelab/localoperator/flags.hh> #include<dune/pdelab/localoperator/idefault.hh> #include<dune/pdelab/finiteelement/localbasiscache.hh> /** a local operator for the spatial part of the wave equation as a first order system in time * * \f{align*}{ * -c^2\Delta u_1(x) &=& 0 x\in\Omega, \\ * -u_0(x) &=& 0 x\in\Omega, \\ * u_1(x) &=& 0 x\in\partial\Omega \\ * no boundary condition for u_1 * \f} * * We assume that both components use the same finite element space. * \tparam FEM is a finite element map of the space used for both components */ template<typename FEM> class WaveFEM : public Dune::PDELab::FullVolumePattern, public Dune::PDELab::LocalOperatorDefaultFlags, public Dune::PDELab::InstationaryLocalOperatorDefaultMethods<double> { // types using LocalBasis = typename FEM::Traits::FiniteElementType::Traits::LocalBasisType; using RF = typename LocalBasis::Traits::RangeFieldType; // private data members Dune::PDELab::LocalBasisCache<LocalBasis> cache; // a cache for local basis evaluations RF c; // the wave speed public: // pattern assembly flags enum { doPatternVolume = true }; // residual assembly flags enum { doAlphaVolume = true }; //! constructor stores a copy of the parameter object WaveFEM (RF c_) : c(c_) {} //! volume integral depending on test and ansatz functions template<typename EG, typename LFSU, typename X, typename LFSV, typename R> void alpha_volume (const EG& eg, const LFSU& lfsu, const X& x, const LFSV& lfsv, R& r) const { // select the two components (but assume Galerkin scheme U=V) using namespace Dune::TypeTree::Indices; auto lfsu0 = lfsu.child(_0); auto lfsu1 = lfsu.child(_1); // types & dimension const int dim = EG::Entity::dimension; // select quadrature rule auto geo = eg.geometry(); const int order = 2*lfsu0.finiteElement().localBasis().order(); auto rule = Dune::PDELab::quadratureRule(geo,order); // loop over quadrature points for (const auto& ip : rule) { // evaluate basis functions; Assume basis is the same for both components auto& phihat = cache.evaluateFunction(ip.position(),lfsu0.finiteElement().localBasis()); // evaluate u1 RF u1=0.0; for (std::size_t i=0; i<lfsu0.size(); i++) u1 += x(lfsu1,i)*phihat[i]; // evaluate gradient of shape functions auto& gradphihat = cache.evaluateJacobian(ip.position(),lfsu0.finiteElement().localBasis()); // transform gradients of shape functions to real element const auto S = geo.jacobianInverseTransposed(ip.position()); auto gradphi = makeJacobianContainer(lfsu0); for (std::size_t i=0; i<lfsu0.size(); i++) S.mv(gradphihat[i][0],gradphi[i][0]); // compute gradient of u0 Dune::FieldVector<RF,dim> gradu0(0.0); for (std::size_t i=0; i<lfsu0.size(); i++) gradu0.axpy(x(lfsu0,i),gradphi[i][0]); // integrate both equations RF factor = ip.weight() * geo.integrationElement(ip.position()); for (std::size_t i=0; i<lfsu0.size(); i++) { r.accumulate(lfsu0,i,c*c*(gradu0*gradphi[i][0])*factor); r.accumulate(lfsu1,i,-u1*phihat[i]*factor); } } } //! jacobian contribution of volume term template<typename EG, typename LFSU, typename X, typename LFSV, typename M> void jacobian_volume (const EG& eg, const LFSU& lfsu, const X& x, const LFSV& lfsv, M& mat) const { // select the two components (assume Galerkin scheme U=V) using namespace Dune::TypeTree::Indices; auto lfsu0 = lfsu.child(_0); auto lfsu1 = lfsu.child(_1); // select quadrature rule auto geo = eg.geometry(); const int order = 2*lfsu0.finiteElement().localBasis().order(); auto rule = Dune::PDELab::quadratureRule(geo,order); // loop over quadrature points for (const auto& ip : rule) { // evaluate basis functions; Assume basis is the same for both components auto& phihat = cache.evaluateFunction(ip.position(),lfsu0.finiteElement().localBasis()); // evaluate gradient of shape functions auto& gradphihat = cache.evaluateJacobian(ip.position(),lfsu0.finiteElement().localBasis()); // transform gradients of shape functions to real element const auto S = geo.jacobianInverseTransposed(ip.position()); auto gradphi = makeJacobianContainer(lfsu0); for (std::size_t i=0; i<lfsu0.size(); i++) S.mv(gradphihat[i][0],gradphi[i][0]); // integrate both equations RF factor = ip.weight() * geo.integrationElement(ip.position()); for (std::size_t j=0; j<lfsu0.size(); j++) for (std::size_t i=0; i<lfsu0.size(); i++) { mat.accumulate(lfsu0,i,lfsu0,j,c*c*(gradphi[j][0]*gradphi[i][0])*factor); mat.accumulate(lfsu1,i,lfsu1,j,-phihat[j]*phihat[i]*factor); } } } //! apply local jacobian of the volume term -> nonlinear variant template<typename EG, typename LFSU, typename X, typename LFSV, typename R> void jacobian_apply_volume (const EG& eg, const LFSU& lfsu, const X& x, const X& z, const LFSV& lfsv, R& r) const { alpha_volume(eg,lfsu,z,lfsv,r); } //! apply local jacobian of the volume term -> linear variant template<typename EG, typename LFSU, typename X, typename LFSV, typename R> void jacobian_apply_volume (const EG& eg, const LFSU& lfsu, const X& x, const LFSV& lfsv, R& r) const { alpha_volume(eg,lfsu,x,lfsv,r); } }; /** a local operator for the temporal operator in the wave equation assuming identical components * * \f{align*}{ \int_\Omega uv dx * \f} * \tparam FEM Type of a finite element map */ template<typename FEM> class WaveL2 : public Dune::PDELab::FullVolumePattern, public Dune::PDELab::LocalOperatorDefaultFlags, public Dune::PDELab::InstationaryLocalOperatorDefaultMethods<double> { // types using LocalBasis = typename FEM::Traits::FiniteElementType::Traits::LocalBasisType; using RF = typename LocalBasis::Traits::RangeFieldType; // private data members Dune::PDELab::LocalBasisCache<LocalBasis> cache; // a cache for local basis evaluations public: // pattern assembly flags enum { doPatternVolume = true }; // residual assembly flags enum { doAlphaVolume = true }; // volume integral depending on test and ansatz functions template<typename EG, typename LFSU, typename X, typename LFSV, typename R> void alpha_volume (const EG& eg, const LFSU& lfsu, const X& x, const LFSV& lfsv, R& r) const { // select the two components (assume Galerkin scheme U=V) using namespace Dune::TypeTree::Indices; auto lfsu0 = lfsu.child(_0); auto lfsu1 = lfsu.child(_1); // select quadrature rule auto geo = eg.geometry(); const int order = 2*lfsu0.finiteElement().localBasis().order(); auto rule = Dune::PDELab::quadratureRule(geo,order); // loop over quadrature points for (const auto& ip : rule) { // evaluate basis functions at first child auto& phihat = cache.evaluateFunction(ip.position(),lfsu0.finiteElement().localBasis()); // evaluate u0 RF u0=0.0, u1=0.0; for (std::size_t i=0; i<lfsu0.size(); i++) { u0 += x(lfsu0,i)*phihat[i]; u1 += x(lfsu1,i)*phihat[i]; } // integration factor RF factor = ip.weight() * geo.integrationElement(ip.position()); // integrate u*phi_i for (std::size_t i=0; i<lfsu0.size(); i++) { r.accumulate(lfsu0,i,u1*phihat[i]*factor); r.accumulate(lfsu1,i,u0*phihat[i]*factor); } } } //! jacobian contribution of volume term template<typename EG, typename LFSU, typename X, typename LFSV, typename M> void jacobian_volume (const EG& eg, const LFSU& lfsu, const X& x, const LFSV& lfsv, M& mat) const { // get first child, assuming PowerGridFunctionSpace using namespace Dune::TypeTree::Indices; auto lfsu0 = lfsu.child(_0); auto lfsu1 = lfsu.child(_1); // select quadrature rule auto geo = eg.geometry(); const int order = 2*lfsu0.finiteElement().localBasis().order(); auto rule = Dune::PDELab::quadratureRule(geo,order); // loop over quadrature points for (const auto& ip : rule) { // evaluate basis functions at first child auto& phihat = cache.evaluateFunction(ip.position(),lfsu0.finiteElement().localBasis()); // integration factor RF factor = ip.weight() * geo.integrationElement(ip.position()); // loop over all components for (std::size_t j=0; j<lfsu0.size(); j++) for (std::size_t i=0; i<lfsu0.size(); i++) { mat.accumulate(lfsu0,i,lfsu1,j,phihat[j]*phihat[i]*factor); mat.accumulate(lfsu1,i,lfsu0,j,phihat[j]*phihat[i]*factor); } } } //! apply local jacobian of the volume term -> nonlinear variant template<typename EG, typename LFSU, typename X, typename LFSV, typename R> void jacobian_apply_volume (const EG& eg, const LFSU& lfsu, const X& x, const X& z, const LFSV& lfsv, R& r) const { alpha_volume(eg,lfsu,z,lfsv,r); } //! apply local jacobian of the volume term -> linear variant template<typename EG, typename LFSU, typename X, typename LFSV, typename R> void jacobian_apply_volume (const EG& eg, const LFSU& lfsu, const X& x, const LFSV& lfsv, R& r) const { alpha_volume(eg,lfsu,x,lfsv,r); } };
36.113074
100
0.639628
[ "geometry", "object", "shape", "vector", "transform" ]
5d190f304801bc3ee06bc63f8a5e690f7dbea6cb
5,006
cpp
C++
source/loader/windows/driver_discovery_win.cpp
fogflower/level-zero
7b2002369e0671687f3986fd5085e205bb41be26
[ "MIT" ]
1
2020-04-30T03:55:17.000Z
2020-04-30T03:55:17.000Z
source/loader/windows/driver_discovery_win.cpp
fogflower/level-zero
7b2002369e0671687f3986fd5085e205bb41be26
[ "MIT" ]
null
null
null
source/loader/windows/driver_discovery_win.cpp
fogflower/level-zero
7b2002369e0671687f3986fd5085e205bb41be26
[ "MIT" ]
null
null
null
/* * * Copyright (C) 2020 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "source/loader/driver_discovery.h" #include <Windows.h> #include <cassert> #include <cfgmgr32.h> #include <devpkey.h> #include <devguid.h> namespace loader { std::vector<DriverLibraryPath> discoverDriversBasedOnDisplayAdapters(); std::vector<DriverLibraryPath> discoverEnabledDrivers() { return discoverDriversBasedOnDisplayAdapters(); } bool isDeviceAvailable(DEVINST devnode) { ULONG devStatus = {}; ULONG devProblem = {}; auto configErr = CM_Get_DevNode_Status(&devStatus, &devProblem, devnode, 0); if (CR_SUCCESS != configErr) { assert(false && "CM_Get_DevNode_Status failed"); return false; } bool isInInvalidState = (devStatus & DN_HAS_PROBLEM) && (devProblem == CM_PROB_NEED_RESTART); isInInvalidState |= (DN_NEED_RESTART == (devStatus & DN_NEED_RESTART)); return false == isInInvalidState; } DriverLibraryPath readDriverPathForDisplayAdapter(DEVINST dnDevNode) { static constexpr char levelZeroDriverPathKey[] = "LevelZeroDriverPath"; HKEY hkey = {}; CONFIGRET configErr = CM_Open_DevNode_Key(dnDevNode, KEY_QUERY_VALUE, 0, RegDisposition_OpenExisting, &hkey, CM_REGISTRY_SOFTWARE); if (CR_SUCCESS != configErr) { assert(false && "CM_Open_DevNode_Key failed"); return ""; } DWORD regValueType = {}; DWORD pathSize = {}; LSTATUS regOpStatus = RegQueryValueExA(hkey, levelZeroDriverPathKey, NULL, &regValueType, NULL, &pathSize); std::string driverPath; if ((ERROR_SUCCESS == regOpStatus) && (REG_SZ == regValueType)) { driverPath.resize(pathSize); regOpStatus = RegQueryValueExA(hkey, levelZeroDriverPathKey, NULL, &regValueType, (LPBYTE) & *driverPath.begin(), &pathSize); if (ERROR_SUCCESS != regOpStatus) { assert(false && "RegQueryValueExA failed"); driverPath.clear(); } } regOpStatus = RegCloseKey(hkey); assert((ERROR_SUCCESS == regOpStatus) && "RegCloseKey failed"); return driverPath; } std::wstring readDisplayAdaptersDeviceIdsList() { OLECHAR displayGuidStr[MAX_GUID_STRING_LEN]; int strFromGuidErr = StringFromGUID2(GUID_DEVCLASS_DISPLAY, displayGuidStr, MAX_GUID_STRING_LEN); if (MAX_GUID_STRING_LEN != strFromGuidErr) { assert(false && "StringFromGUID2 failed"); return L""; } std::wstring deviceIdList; CONFIGRET getDeviceIdListErr = CR_BUFFER_SMALL; while (CR_BUFFER_SMALL == getDeviceIdListErr) { ULONG deviceIdListSize = {}; ULONG deviceIdListFlags = CM_GETIDLIST_FILTER_CLASS | CM_GETIDLIST_FILTER_PRESENT; auto getDeviceIdListSizeErr = CM_Get_Device_ID_List_SizeW(&deviceIdListSize, displayGuidStr, deviceIdListFlags); if (CR_SUCCESS != getDeviceIdListSizeErr) { assert(false && "CM_Get_Device_ID_List_size failed"); break; } deviceIdList.resize(deviceIdListSize); getDeviceIdListErr = CM_Get_Device_ID_ListW(displayGuidStr, &*deviceIdList.begin(), deviceIdListSize, deviceIdListFlags); } return deviceIdList; } std::vector<DriverLibraryPath> discoverDriversBasedOnDisplayAdapters() { std::vector<DriverLibraryPath> enabledDrivers; auto deviceIdList = readDisplayAdaptersDeviceIdsList(); if (deviceIdList.empty()) { return enabledDrivers; } auto isNotDeviceListEnd = [](wchar_t *it) { return '\0' != it[0]; }; auto getNextDeviceInList = [](wchar_t *it) { return it + wcslen(it) + 1; }; auto deviceIdIt = &*deviceIdList.begin(); for (; isNotDeviceListEnd(deviceIdIt); deviceIdIt = getNextDeviceInList(deviceIdIt)) { DEVINST devinst = {}; if (CR_SUCCESS != CM_Locate_DevNodeW(&devinst, deviceIdIt, 0)) { assert(false && "CM_Locate_DevNodeW failed"); continue; } if (false == isDeviceAvailable(devinst)) { continue; } auto driverPath = readDriverPathForDisplayAdapter(devinst); if (driverPath.empty()) { continue; } bool alreadyOnTheList = (enabledDrivers.end() != std::find(enabledDrivers.begin(), enabledDrivers.end(), driverPath)); if (alreadyOnTheList) { continue; } enabledDrivers.push_back(std::move(driverPath)); } return enabledDrivers; } } // namespace loader
33.152318
126
0.604874
[ "vector" ]
5d222b021aeee8a32a8d98b028260116df34dfc7
21,806
cc
C++
extensions/browser/api/declarative_net_request/declarative_net_request_api.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
extensions/browser/api/declarative_net_request/declarative_net_request_api.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
extensions/browser/api/declarative_net_request/declarative_net_request_api.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2018 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 "extensions/browser/api/declarative_net_request/declarative_net_request_api.h" #include <memory> #include <set> #include <utility> #include <vector> #include "base/bind.h" #include "base/containers/contains.h" #include "base/containers/cxx20_erase.h" #include "base/task/post_task.h" #include "base/task/task_runner_util.h" #include "base/time/time.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "extensions/browser/api/declarative_net_request/action_tracker.h" #include "extensions/browser/api/declarative_net_request/composite_matcher.h" #include "extensions/browser/api/declarative_net_request/constants.h" #include "extensions/browser/api/declarative_net_request/file_backed_ruleset_source.h" #include "extensions/browser/api/declarative_net_request/rules_monitor_service.h" #include "extensions/browser/api/declarative_net_request/ruleset_manager.h" #include "extensions/browser/api/declarative_net_request/ruleset_matcher.h" #include "extensions/browser/api/declarative_net_request/utils.h" #include "extensions/browser/api/extensions_api_client.h" #include "extensions/browser/extension_file_task_runner.h" #include "extensions/browser/extension_prefs.h" #include "extensions/browser/extensions_browser_client.h" #include "extensions/browser/quota_service.h" #include "extensions/common/api/declarative_net_request.h" #include "extensions/common/api/declarative_net_request/constants.h" #include "extensions/common/api/declarative_net_request/dnr_manifest_data.h" #include "extensions/common/error_utils.h" #include "extensions/common/extension_id.h" #include "third_party/abseil-cpp/absl/types/optional.h" namespace extensions { namespace { namespace dnr_api = api::declarative_net_request; // Returns whether |extension| can call getMatchedRules for the specified // |tab_id| and populates |error| if it can't. If no tab ID is specified, then // the API call is for all tabs. bool CanCallGetMatchedRules(content::BrowserContext* browser_context, const Extension* extension, absl::optional<int> tab_id, std::string* error) { bool can_call = declarative_net_request::HasDNRFeedbackPermission(extension, tab_id); if (!can_call) *error = declarative_net_request::kErrorGetMatchedRulesMissingPermissions; return can_call; } } // namespace DeclarativeNetRequestUpdateDynamicRulesFunction:: DeclarativeNetRequestUpdateDynamicRulesFunction() = default; DeclarativeNetRequestUpdateDynamicRulesFunction:: ~DeclarativeNetRequestUpdateDynamicRulesFunction() = default; ExtensionFunction::ResponseAction DeclarativeNetRequestUpdateDynamicRulesFunction::Run() { using Params = dnr_api::UpdateDynamicRules::Params; std::u16string error; std::unique_ptr<Params> params(Params::Create(args(), &error)); EXTENSION_FUNCTION_VALIDATE(params); EXTENSION_FUNCTION_VALIDATE(error.empty()); std::vector<int> rule_ids_to_remove; if (params->options.remove_rule_ids) rule_ids_to_remove = std::move(*params->options.remove_rule_ids); std::vector<api::declarative_net_request::Rule> rules_to_add; if (params->options.add_rules) rules_to_add = std::move(*params->options.add_rules); // Early return if there is nothing to do. if (rule_ids_to_remove.empty() && rules_to_add.empty()) return RespondNow(NoArguments()); auto* rules_monitor_service = declarative_net_request::RulesMonitorService::Get(browser_context()); DCHECK(rules_monitor_service); DCHECK(extension()); auto callback = base::BindOnce( &DeclarativeNetRequestUpdateDynamicRulesFunction::OnDynamicRulesUpdated, this); rules_monitor_service->UpdateDynamicRules( *extension(), std::move(rule_ids_to_remove), std::move(rules_to_add), std::move(callback)); return RespondLater(); } void DeclarativeNetRequestUpdateDynamicRulesFunction::OnDynamicRulesUpdated( absl::optional<std::string> error) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (error) Respond(Error(std::move(*error))); else Respond(NoArguments()); } DeclarativeNetRequestGetDynamicRulesFunction:: DeclarativeNetRequestGetDynamicRulesFunction() = default; DeclarativeNetRequestGetDynamicRulesFunction:: ~DeclarativeNetRequestGetDynamicRulesFunction() = default; ExtensionFunction::ResponseAction DeclarativeNetRequestGetDynamicRulesFunction::Run() { auto source = declarative_net_request::FileBackedRulesetSource::CreateDynamic( browser_context(), extension()->id()); auto read_dynamic_rules = base::BindOnce( [](const declarative_net_request::FileBackedRulesetSource& source) { return source.ReadJSONRulesUnsafe(); }, std::move(source)); base::PostTaskAndReplyWithResult( GetExtensionFileTaskRunner().get(), FROM_HERE, std::move(read_dynamic_rules), base::BindOnce( &DeclarativeNetRequestGetDynamicRulesFunction::OnDynamicRulesFetched, this)); return RespondLater(); } void DeclarativeNetRequestGetDynamicRulesFunction::OnDynamicRulesFetched( declarative_net_request::ReadJSONRulesResult read_json_result) { using Status = declarative_net_request::ReadJSONRulesResult::Status; LogReadDynamicRulesStatus(read_json_result.status); DCHECK(read_json_result.status == Status::kSuccess || read_json_result.rules.empty()); // Unlike errors such as kJSONParseError, which normally denote corruption, a // read error is probably a transient error. Hence raise an error instead of // returning an empty list. if (read_json_result.status == Status::kFileReadError) { Respond(Error(declarative_net_request::kInternalErrorGettingDynamicRules)); return; } Respond(ArgumentList( dnr_api::GetDynamicRules::Results::Create(read_json_result.rules))); } DeclarativeNetRequestUpdateSessionRulesFunction:: DeclarativeNetRequestUpdateSessionRulesFunction() = default; DeclarativeNetRequestUpdateSessionRulesFunction:: ~DeclarativeNetRequestUpdateSessionRulesFunction() = default; ExtensionFunction::ResponseAction DeclarativeNetRequestUpdateSessionRulesFunction::Run() { using Params = dnr_api::UpdateSessionRules::Params; std::u16string error; std::unique_ptr<Params> params(Params::Create(args(), &error)); EXTENSION_FUNCTION_VALIDATE(params); EXTENSION_FUNCTION_VALIDATE(error.empty()); std::vector<int> rule_ids_to_remove; if (params->options.remove_rule_ids) rule_ids_to_remove = std::move(*params->options.remove_rule_ids); std::vector<api::declarative_net_request::Rule> rules_to_add; if (params->options.add_rules) rules_to_add = std::move(*params->options.add_rules); // Early return if there is nothing to do. if (rule_ids_to_remove.empty() && rules_to_add.empty()) return RespondNow(NoArguments()); auto* rules_monitor_service = declarative_net_request::RulesMonitorService::Get(browser_context()); DCHECK(rules_monitor_service); rules_monitor_service->UpdateSessionRules( *extension(), std::move(rule_ids_to_remove), std::move(rules_to_add), base::BindOnce(&DeclarativeNetRequestUpdateSessionRulesFunction:: OnSessionRulesUpdated, this)); return RespondLater(); } void DeclarativeNetRequestUpdateSessionRulesFunction::OnSessionRulesUpdated( absl::optional<std::string> error) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (error) Respond(Error(std::move(*error))); else Respond(NoArguments()); } DeclarativeNetRequestGetSessionRulesFunction:: DeclarativeNetRequestGetSessionRulesFunction() = default; DeclarativeNetRequestGetSessionRulesFunction:: ~DeclarativeNetRequestGetSessionRulesFunction() = default; ExtensionFunction::ResponseAction DeclarativeNetRequestGetSessionRulesFunction::Run() { auto* rules_monitor_service = declarative_net_request::RulesMonitorService::Get(browser_context()); DCHECK(rules_monitor_service); return RespondNow(OneArgument( rules_monitor_service->GetSessionRulesValue(extension_id()).Clone())); } DeclarativeNetRequestUpdateEnabledRulesetsFunction:: DeclarativeNetRequestUpdateEnabledRulesetsFunction() = default; DeclarativeNetRequestUpdateEnabledRulesetsFunction:: ~DeclarativeNetRequestUpdateEnabledRulesetsFunction() = default; ExtensionFunction::ResponseAction DeclarativeNetRequestUpdateEnabledRulesetsFunction::Run() { using Params = dnr_api::UpdateEnabledRulesets::Params; using RulesetID = declarative_net_request::RulesetID; using DNRManifestData = declarative_net_request::DNRManifestData; std::u16string error; std::unique_ptr<Params> params(Params::Create(args(), &error)); EXTENSION_FUNCTION_VALIDATE(params); EXTENSION_FUNCTION_VALIDATE(error.empty()); std::set<RulesetID> ids_to_disable; std::set<RulesetID> ids_to_enable; const DNRManifestData::ManifestIDToRulesetMap& public_id_map = DNRManifestData::GetManifestIDToRulesetMap(*extension()); if (params->options.enable_ruleset_ids) { for (const std::string& public_id_to_enable : *params->options.enable_ruleset_ids) { auto it = public_id_map.find(public_id_to_enable); if (it == public_id_map.end()) { return RespondNow(Error(ErrorUtils::FormatErrorMessage( declarative_net_request::kInvalidRulesetIDError, public_id_to_enable))); } ids_to_enable.insert(it->second->id); } } if (params->options.disable_ruleset_ids) { for (const std::string& public_id_to_disable : *params->options.disable_ruleset_ids) { auto it = public_id_map.find(public_id_to_disable); if (it == public_id_map.end()) { return RespondNow(Error(ErrorUtils::FormatErrorMessage( declarative_net_request::kInvalidRulesetIDError, public_id_to_disable))); } // |ruleset_ids_to_enable| takes priority over |ruleset_ids_to_disable|. RulesetID id = it->second->id; if (base::Contains(ids_to_enable, id)) continue; ids_to_disable.insert(id); } } if (ids_to_enable.empty() && ids_to_disable.empty()) return RespondNow(NoArguments()); auto* rules_monitor_service = declarative_net_request::RulesMonitorService::Get(browser_context()); DCHECK(rules_monitor_service); DCHECK(extension()); rules_monitor_service->UpdateEnabledStaticRulesets( *extension(), std::move(ids_to_disable), std::move(ids_to_enable), base::BindOnce(&DeclarativeNetRequestUpdateEnabledRulesetsFunction:: OnEnabledStaticRulesetsUpdated, this)); return did_respond() ? AlreadyResponded() : RespondLater(); } void DeclarativeNetRequestUpdateEnabledRulesetsFunction:: OnEnabledStaticRulesetsUpdated(absl::optional<std::string> error) { if (error) Respond(Error(std::move(*error))); else Respond(NoArguments()); } DeclarativeNetRequestGetEnabledRulesetsFunction:: DeclarativeNetRequestGetEnabledRulesetsFunction() = default; DeclarativeNetRequestGetEnabledRulesetsFunction:: ~DeclarativeNetRequestGetEnabledRulesetsFunction() = default; ExtensionFunction::ResponseAction DeclarativeNetRequestGetEnabledRulesetsFunction::Run() { auto* rules_monitor_service = declarative_net_request::RulesMonitorService::Get(browser_context()); DCHECK(rules_monitor_service); std::vector<std::string> public_ids; declarative_net_request::CompositeMatcher* matcher = rules_monitor_service->ruleset_manager()->GetMatcherForExtension( extension_id()); if (matcher) { DCHECK(extension()); public_ids = GetPublicRulesetIDs(*extension(), *matcher); // Exclude any reserved ruleset IDs since they would correspond to // non-static rulesets. base::EraseIf(public_ids, [](const std::string& id) { DCHECK(!id.empty()); return id[0] == declarative_net_request::kReservedRulesetIDPrefix; }); } return RespondNow( ArgumentList(dnr_api::GetEnabledRulesets::Results::Create(public_ids))); } // static bool DeclarativeNetRequestGetMatchedRulesFunction::disable_throttling_for_test_ = false; DeclarativeNetRequestGetMatchedRulesFunction:: DeclarativeNetRequestGetMatchedRulesFunction() = default; DeclarativeNetRequestGetMatchedRulesFunction:: ~DeclarativeNetRequestGetMatchedRulesFunction() = default; ExtensionFunction::ResponseAction DeclarativeNetRequestGetMatchedRulesFunction::Run() { using Params = dnr_api::GetMatchedRules::Params; std::u16string error; std::unique_ptr<Params> params(Params::Create(args(), &error)); EXTENSION_FUNCTION_VALIDATE(params); EXTENSION_FUNCTION_VALIDATE(error.empty()); absl::optional<int> tab_id; base::Time min_time_stamp = base::Time::Min(); if (params->filter) { if (params->filter->tab_id) tab_id = *params->filter->tab_id; if (params->filter->min_time_stamp) min_time_stamp = base::Time::FromJsTime(*params->filter->min_time_stamp); } // Return an error if an invalid tab ID is specified. The unknown tab ID is // valid as it would cause the API call to return all rules matched that were // not associated with any currently open tabs. if (tab_id && *tab_id != extension_misc::kUnknownTabId && !ExtensionsBrowserClient::Get()->IsValidTabId(browser_context(), *tab_id)) { return RespondNow(Error(ErrorUtils::FormatErrorMessage( declarative_net_request::kTabNotFoundError, base::NumberToString(*tab_id)))); } std::string permission_error; if (!CanCallGetMatchedRules(browser_context(), extension(), tab_id, &permission_error)) { return RespondNow(Error(permission_error)); } declarative_net_request::RulesMonitorService* rules_monitor_service = declarative_net_request::RulesMonitorService::Get(browser_context()); DCHECK(rules_monitor_service); declarative_net_request::ActionTracker& action_tracker = rules_monitor_service->action_tracker(); dnr_api::RulesMatchedDetails details; details.rules_matched_info = action_tracker.GetMatchedRules(*extension(), tab_id, min_time_stamp); return RespondNow( ArgumentList(dnr_api::GetMatchedRules::Results::Create(details))); } void DeclarativeNetRequestGetMatchedRulesFunction::GetQuotaLimitHeuristics( QuotaLimitHeuristics* heuristics) const { QuotaLimitHeuristic::Config limit = { dnr_api::MAX_GETMATCHEDRULES_CALLS_PER_INTERVAL, base::Minutes(dnr_api::GETMATCHEDRULES_QUOTA_INTERVAL)}; heuristics->push_back(std::make_unique<QuotaService::TimedLimit>( limit, std::make_unique<QuotaLimitHeuristic::SingletonBucketMapper>(), "MAX_GETMATCHEDRULES_CALLS_PER_INTERVAL")); } bool DeclarativeNetRequestGetMatchedRulesFunction::ShouldSkipQuotaLimiting() const { return user_gesture() || disable_throttling_for_test_; } DeclarativeNetRequestSetExtensionActionOptionsFunction:: DeclarativeNetRequestSetExtensionActionOptionsFunction() = default; DeclarativeNetRequestSetExtensionActionOptionsFunction:: ~DeclarativeNetRequestSetExtensionActionOptionsFunction() = default; ExtensionFunction::ResponseAction DeclarativeNetRequestSetExtensionActionOptionsFunction::Run() { using Params = dnr_api::SetExtensionActionOptions::Params; std::u16string error; std::unique_ptr<Params> params(Params::Create(args(), &error)); EXTENSION_FUNCTION_VALIDATE(params); EXTENSION_FUNCTION_VALIDATE(error.empty()); declarative_net_request::RulesMonitorService* rules_monitor_service = declarative_net_request::RulesMonitorService::Get(browser_context()); DCHECK(rules_monitor_service); ExtensionPrefs* prefs = ExtensionPrefs::Get(browser_context()); declarative_net_request::ActionTracker& action_tracker = rules_monitor_service->action_tracker(); bool use_action_count_as_badge_text = prefs->GetDNRUseActionCountAsBadgeText(extension_id()); if (params->options.display_action_count_as_badge_text && *params->options.display_action_count_as_badge_text != use_action_count_as_badge_text) { use_action_count_as_badge_text = *params->options.display_action_count_as_badge_text; prefs->SetDNRUseActionCountAsBadgeText(extension_id(), use_action_count_as_badge_text); // If the preference is switched on, update the extension's badge text // with the number of actions matched for this extension. Otherwise, clear // the action count for the extension's icon and show the default badge // text if set. if (use_action_count_as_badge_text) action_tracker.OnActionCountAsBadgeTextPreferenceEnabled(extension_id()); else { DCHECK(ExtensionsAPIClient::Get()); ExtensionsAPIClient::Get()->ClearActionCount(browser_context(), *extension()); } } if (params->options.tab_update) { if (!use_action_count_as_badge_text) { return RespondNow( Error(declarative_net_request:: kIncrementActionCountWithoutUseAsBadgeTextError)); } const auto& update_options = *params->options.tab_update; int tab_id = update_options.tab_id; if (!ExtensionsBrowserClient::Get()->IsValidTabId(browser_context(), tab_id)) { return RespondNow(Error(ErrorUtils::FormatErrorMessage( declarative_net_request::kTabNotFoundError, base::NumberToString(tab_id)))); } action_tracker.IncrementActionCountForTab(extension_id(), tab_id, update_options.increment); } return RespondNow(NoArguments()); } DeclarativeNetRequestIsRegexSupportedFunction:: DeclarativeNetRequestIsRegexSupportedFunction() = default; DeclarativeNetRequestIsRegexSupportedFunction:: ~DeclarativeNetRequestIsRegexSupportedFunction() = default; ExtensionFunction::ResponseAction DeclarativeNetRequestIsRegexSupportedFunction::Run() { using Params = dnr_api::IsRegexSupported::Params; std::u16string error; std::unique_ptr<Params> params(Params::Create(args(), &error)); EXTENSION_FUNCTION_VALIDATE(params); EXTENSION_FUNCTION_VALIDATE(error.empty()); bool is_case_sensitive = params->regex_options.is_case_sensitive ? *params->regex_options.is_case_sensitive : true; bool require_capturing = params->regex_options.require_capturing ? *params->regex_options.require_capturing : false; re2::RE2 regex(params->regex_options.regex, declarative_net_request::CreateRE2Options(is_case_sensitive, require_capturing)); dnr_api::IsRegexSupportedResult result; if (regex.ok()) { result.is_supported = true; } else { result.is_supported = false; result.reason = regex.error_code() == re2::RE2::ErrorPatternTooLarge ? dnr_api::UNSUPPORTED_REGEX_REASON_MEMORYLIMITEXCEEDED : dnr_api::UNSUPPORTED_REGEX_REASON_SYNTAXERROR; } return RespondNow( ArgumentList(dnr_api::IsRegexSupported::Results::Create(result))); } DeclarativeNetRequestGetAvailableStaticRuleCountFunction:: DeclarativeNetRequestGetAvailableStaticRuleCountFunction() = default; DeclarativeNetRequestGetAvailableStaticRuleCountFunction:: ~DeclarativeNetRequestGetAvailableStaticRuleCountFunction() = default; ExtensionFunction::ResponseAction DeclarativeNetRequestGetAvailableStaticRuleCountFunction::Run() { auto* rules_monitor_service = declarative_net_request::RulesMonitorService::Get(browser_context()); DCHECK(rules_monitor_service); declarative_net_request::CompositeMatcher* composite_matcher = rules_monitor_service->ruleset_manager()->GetMatcherForExtension( extension_id()); // First get the total enabled static rule count for the extension. size_t enabled_static_rule_count = GetEnabledStaticRuleCount(composite_matcher); size_t static_rule_limit = static_cast<size_t>(declarative_net_request::GetMaximumRulesPerRuleset()); DCHECK_LE(enabled_static_rule_count, static_rule_limit); const declarative_net_request::GlobalRulesTracker& global_rules_tracker = rules_monitor_service->global_rules_tracker(); size_t available_allocation = global_rules_tracker.GetAvailableAllocation(extension_id()); size_t guaranteed_static_minimum = declarative_net_request::GetStaticGuaranteedMinimumRuleCount(); // If an extension's rule count is below the guaranteed minimum, include the // difference. size_t available_static_rule_count = 0; if (enabled_static_rule_count < guaranteed_static_minimum) { available_static_rule_count = (guaranteed_static_minimum - enabled_static_rule_count) + available_allocation; } else { size_t used_global_allocation = enabled_static_rule_count - guaranteed_static_minimum; DCHECK_GE(available_allocation, used_global_allocation); available_static_rule_count = available_allocation - used_global_allocation; } // Ensure conversion to int below doesn't underflow. DCHECK_LE(available_static_rule_count, static_cast<size_t>(std::numeric_limits<int>::max())); return RespondNow( OneArgument(base::Value(static_cast<int>(available_static_rule_count)))); } } // namespace extensions
38.390845
87
0.751261
[ "vector" ]
5d23a28ad8d5107bd777904d0dced44fe01cb5bf
2,656
cpp
C++
Algorithm/LeetCode/98-isValidBST/98-isValidBST.cpp
nchkdxlq/Algorithm
a89aec4859a1e2a1367113bf17345ef4a5c40a91
[ "MIT" ]
1
2019-05-25T06:18:10.000Z
2019-05-25T06:18:10.000Z
Algorithm/LeetCode/98-isValidBST/98-isValidBST.cpp
nchkdxlq/Algorithm
a89aec4859a1e2a1367113bf17345ef4a5c40a91
[ "MIT" ]
null
null
null
Algorithm/LeetCode/98-isValidBST/98-isValidBST.cpp
nchkdxlq/Algorithm
a89aec4859a1e2a1367113bf17345ef4a5c40a91
[ "MIT" ]
null
null
null
// // 98-isValidBST.cpp // LeetCode // // Created by Knox on 2019/7/15. // Copyright © 2019 nchkdxlq. All rights reserved. // #include "98-isValidBST.hpp" #include "STLHelper.hpp" #include "TreeHelper.hpp" using namespace BTree; /** 给定一个二叉树,判断其是否是一个有效的二叉搜索树。 假设一个二叉搜索树具有如下特征: 节点的左子树只包含小于当前节点的数。 节点的右子树只包含大于当前节点的数。 所有左子树和右子树自身必须也是二叉搜索树。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/validate-binary-search-tree 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ namespace isValidBST_98 { class Solution { public: bool isValidBST(TreeNode* root) { // return v1_isValidBST(root); return v2_isValidBST(root); } private: /** 思路: 利用BST中序遍历是升序数组的特性,判断前一个结点是否小于当前结点的值,如果不满足,则不是BST 时间复杂度:O(n) 最坏的情况数据是怎样的??? 空间复杂度:O(n) stack存储结点 */ bool v1_isValidBST(TreeNode* root) { stack<TreeNode *> __stack; TreeNode *pre = nullptr; // 迭代的方式中序遍历 while(root || !__stack.empty()) { while (root) { __stack.push(root); root = root->left; } root = __stack.top(); __stack.pop(); if (pre && pre->val >= root->val) { return false; } pre = root; root = root->right; } return true; } /* @undo 上述思路可以用递归法实现。首先将结点的值与上界和下界(如果有)比较。然后,对左子树和右子树递归进行该过程 还是不很理解 ## 复杂度分析 - 时间复杂度:O(n) - 空间复杂度:O(n) */ bool v2_isValidBST(TreeNode *root) { return helper(root, nullptr, nullptr); } bool helper(TreeNode *root, TreeNode *max, TreeNode *min) { if (root == nullptr) return true; if (max && max->val <= root->val) return false; if (min && min->val >= root->val) return false; if (!helper(root->left, root, min)) return false; if (!helper(root->right, max, root)) return false; return true; } }; } void __98_entry() { vector<int> nums = {5,1,4,INT_MAX,INT_MAX,3,6}; // false nums = {2,1,3}; // true // nums = {1,1}; // false TreeNode *root = create_binaryTree(nums); bool ret = isValidBST_98::Solution().isValidBST(root); cout << (ret ? "true" : "false") << endl; }
21.419355
67
0.479669
[ "vector" ]
5d2851d3fa4f34c23b752e84f68f8d5357ad3907
228,970
hpp
C++
cisco-ios-xr/ydk/models/cisco_ios_xr/fragmented/Cisco_IOS_XR_bundlemgr_oper_1.hpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
17
2016-12-02T05:45:49.000Z
2022-02-10T19:32:54.000Z
cisco-ios-xr/ydk/models/cisco_ios_xr/fragmented/Cisco_IOS_XR_bundlemgr_oper_1.hpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
2
2017-03-27T15:22:38.000Z
2019-11-05T08:30:16.000Z
cisco-ios-xr/ydk/models/cisco_ios_xr/fragmented/Cisco_IOS_XR_bundlemgr_oper_1.hpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
11
2016-12-02T05:45:52.000Z
2019-11-07T08:28:17.000Z
#ifndef _CISCO_IOS_XR_BUNDLEMGR_OPER_1_ #define _CISCO_IOS_XR_BUNDLEMGR_OPER_1_ #include <memory> #include <vector> #include <string> #include <ydk/types.hpp> #include <ydk/errors.hpp> #include "Cisco_IOS_XR_bundlemgr_oper_0.hpp" namespace cisco_ios_xr { namespace Cisco_IOS_XR_bundlemgr_oper { class BundleInformation::Lacp::LacpBundles::LacpBundle::LacpBundleChildrenMembers::LacpBundleChildrenMember::PartnerInfo::PortInfo : public ydk::Entity { public: PortInfo(); ~PortInfo(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf key; //type: uint16 ydk::YLeaf state; //type: uint8 class System; //type: BundleInformation::Lacp::LacpBundles::LacpBundle::LacpBundleChildrenMembers::LacpBundleChildrenMember::PartnerInfo::PortInfo::System class Port; //type: BundleInformation::Lacp::LacpBundles::LacpBundle::LacpBundleChildrenMembers::LacpBundleChildrenMember::PartnerInfo::PortInfo::Port std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::Lacp::LacpBundles::LacpBundle::LacpBundleChildrenMembers::LacpBundleChildrenMember::PartnerInfo::PortInfo::System> system; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::Lacp::LacpBundles::LacpBundle::LacpBundleChildrenMembers::LacpBundleChildrenMember::PartnerInfo::PortInfo::Port> port; }; // BundleInformation::Lacp::LacpBundles::LacpBundle::LacpBundleChildrenMembers::LacpBundleChildrenMember::PartnerInfo::PortInfo class BundleInformation::Lacp::LacpBundles::LacpBundle::LacpBundleChildrenMembers::LacpBundleChildrenMember::PartnerInfo::PortInfo::System : public ydk::Entity { public: System(); ~System(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf system_prio; //type: uint16 class SystemMacAddr; //type: BundleInformation::Lacp::LacpBundles::LacpBundle::LacpBundleChildrenMembers::LacpBundleChildrenMember::PartnerInfo::PortInfo::System::SystemMacAddr std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::Lacp::LacpBundles::LacpBundle::LacpBundleChildrenMembers::LacpBundleChildrenMember::PartnerInfo::PortInfo::System::SystemMacAddr> system_mac_addr; }; // BundleInformation::Lacp::LacpBundles::LacpBundle::LacpBundleChildrenMembers::LacpBundleChildrenMember::PartnerInfo::PortInfo::System class BundleInformation::Lacp::LacpBundles::LacpBundle::LacpBundleChildrenMembers::LacpBundleChildrenMember::PartnerInfo::PortInfo::System::SystemMacAddr : public ydk::Entity { public: SystemMacAddr(); ~SystemMacAddr(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf macaddr; //type: string }; // BundleInformation::Lacp::LacpBundles::LacpBundle::LacpBundleChildrenMembers::LacpBundleChildrenMember::PartnerInfo::PortInfo::System::SystemMacAddr class BundleInformation::Lacp::LacpBundles::LacpBundle::LacpBundleChildrenMembers::LacpBundleChildrenMember::PartnerInfo::PortInfo::Port : public ydk::Entity { public: Port(); ~Port(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf link_priority; //type: uint16 ydk::YLeaf link_number; //type: uint16 }; // BundleInformation::Lacp::LacpBundles::LacpBundle::LacpBundleChildrenMembers::LacpBundleChildrenMember::PartnerInfo::PortInfo::Port class BundleInformation::Lacp::LacpBundles::LacpBundle::LacpBundleChildrenMembers::LacpBundleChildrenMember::AdditionalInfo : public ydk::Entity { public: AdditionalInfo(); ~AdditionalInfo(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf mbr_type; //type: BmdMemberTypeEnum class Local; //type: BundleInformation::Lacp::LacpBundles::LacpBundle::LacpBundleChildrenMembers::LacpBundleChildrenMember::AdditionalInfo::Local class Foreign; //type: BundleInformation::Lacp::LacpBundles::LacpBundle::LacpBundleChildrenMembers::LacpBundleChildrenMember::AdditionalInfo::Foreign std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::Lacp::LacpBundles::LacpBundle::LacpBundleChildrenMembers::LacpBundleChildrenMember::AdditionalInfo::Local> local; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::Lacp::LacpBundles::LacpBundle::LacpBundleChildrenMembers::LacpBundleChildrenMember::AdditionalInfo::Foreign> foreign; }; // BundleInformation::Lacp::LacpBundles::LacpBundle::LacpBundleChildrenMembers::LacpBundleChildrenMember::AdditionalInfo class BundleInformation::Lacp::LacpBundles::LacpBundle::LacpBundleChildrenMembers::LacpBundleChildrenMember::AdditionalInfo::Local : public ydk::Entity { public: Local(); ~Local(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf interface_handle; //type: string }; // BundleInformation::Lacp::LacpBundles::LacpBundle::LacpBundleChildrenMembers::LacpBundleChildrenMember::AdditionalInfo::Local class BundleInformation::Lacp::LacpBundles::LacpBundle::LacpBundleChildrenMembers::LacpBundleChildrenMember::AdditionalInfo::Foreign : public ydk::Entity { public: Foreign(); ~Foreign(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf peer_address; //type: string ydk::YLeaf member_name; //type: string }; // BundleInformation::Lacp::LacpBundles::LacpBundle::LacpBundleChildrenMembers::LacpBundleChildrenMember::AdditionalInfo::Foreign class BundleInformation::Lacp::LacpMembers : public ydk::Entity { public: LacpMembers(); ~LacpMembers(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class LacpMember; //type: BundleInformation::Lacp::LacpMembers::LacpMember ydk::YList lacp_member; }; // BundleInformation::Lacp::LacpMembers class BundleInformation::Lacp::LacpMembers::LacpMember : public ydk::Entity { public: LacpMember(); ~LacpMember(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf member_interface; //type: string class LacpMemberAncestor; //type: BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor class LacpMemberItem; //type: BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberItem std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor> lacp_member_ancestor; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberItem> lacp_member_item; }; // BundleInformation::Lacp::LacpMembers::LacpMember class BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor : public ydk::Entity { public: LacpMemberAncestor(); ~LacpMemberAncestor(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class BundleData; //type: BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::BundleData class MemberData; //type: BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::MemberData std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::BundleData> bundle_data; ydk::YList member_data; }; // BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor class BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::BundleData : public ydk::Entity { public: BundleData(); ~BundleData(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf actor_operational_key; //type: uint16 ydk::YLeaf partner_system_priority; //type: uint16 ydk::YLeaf partner_system_mac_address; //type: string ydk::YLeaf partner_operational_key; //type: uint16 class ActorBundleData; //type: BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::BundleData::ActorBundleData class BundleSystemId; //type: BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::BundleData::BundleSystemId std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::BundleData::ActorBundleData> actor_bundle_data; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::BundleData::BundleSystemId> bundle_system_id; }; // BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::BundleData class BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::BundleData::ActorBundleData : public ydk::Entity { public: ActorBundleData(); ~ActorBundleData(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf bundle_interface_name; //type: string ydk::YLeaf available_bandwidth; //type: uint32 ydk::YLeaf effective_bandwidth; //type: uint32 ydk::YLeaf configured_bandwidth; //type: uint32 ydk::YLeaf minimum_active_links; //type: uint8 ydk::YLeaf maximum_active_links; //type: uint8 ydk::YLeaf maximum_active_links_source; //type: BmWhichSystem ydk::YLeaf minimum_bandwidth; //type: uint32 ydk::YLeaf primary_member; //type: string ydk::YLeaf bundle_status; //type: BmBdlState ydk::YLeaf active_member_count; //type: uint16 ydk::YLeaf standby_member_count; //type: uint16 ydk::YLeaf configured_member_count; //type: uint16 ydk::YLeaf mac_source; //type: BmBdlMacSource ydk::YLeaf mac_source_member; //type: string ydk::YLeaf inter_chassis; //type: boolean ydk::YLeaf is_active; //type: boolean ydk::YLeaf lacp_status; //type: BmFeatureStatus ydk::YLeaf mlacp_status; //type: BmFeatureStatus ydk::YLeaf ipv4bfd_status; //type: BmFeatureStatus ydk::YLeaf link_order_status; //type: BmFeatureStatus ydk::YLeaf ipv6bfd_status; //type: BmFeatureStatus ydk::YLeaf load_balance_hash_type; //type: string ydk::YLeaf load_balance_locality_threshold; //type: uint16 ydk::YLeaf suppression_timer; //type: uint16 ydk::YLeaf wait_while_timer; //type: uint16 ydk::YLeaf collector_max_delay; //type: uint16 ydk::YLeaf cisco_extensions; //type: boolean ydk::YLeaf lacp_nonrevertive; //type: boolean ydk::YLeaf iccp_group_id; //type: uint32 ydk::YLeaf active_foreign_member_count; //type: uint16 ydk::YLeaf configured_foreign_member_count; //type: uint16 ydk::YLeaf switchover_type; //type: BmdMlacpSwitchover ydk::YLeaf maximize_threshold_value_links; //type: uint32 ydk::YLeaf maximize_threshold_value_band_width; //type: uint32 ydk::YLeaf mlacp_mode; //type: BundleMlacpMode ydk::YLeaf recovery_delay; //type: uint16 ydk::YLeaf singleton; //type: boolean class MacAddress; //type: BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::BundleData::ActorBundleData::MacAddress class BfdConfig; //type: BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::BundleData::ActorBundleData::BfdConfig std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::BundleData::ActorBundleData::MacAddress> mac_address; ydk::YList bfd_config; }; // BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::BundleData::ActorBundleData class BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::BundleData::ActorBundleData::MacAddress : public ydk::Entity { public: MacAddress(); ~MacAddress(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf address; //type: string }; // BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::BundleData::ActorBundleData::MacAddress class BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::BundleData::ActorBundleData::BfdConfig : public ydk::Entity { public: BfdConfig(); ~BfdConfig(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf bundle_status; //type: BmdBfdBdlState ydk::YLeaf start_timer; //type: uint32 ydk::YLeaf nbr_unconfig_timer; //type: uint32 ydk::YLeaf pref_multiplier; //type: uint16 ydk::YLeaf pref_min_interval; //type: uint32 ydk::YLeaf pref_echo_min_interval; //type: uint32 ydk::YLeaf fast_detect; //type: boolean ydk::YLeaf mode_info; //type: uint32 class DestinationAddress; //type: BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::BundleData::ActorBundleData::BfdConfig::DestinationAddress std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::BundleData::ActorBundleData::BfdConfig::DestinationAddress> destination_address; }; // BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::BundleData::ActorBundleData::BfdConfig class BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::BundleData::ActorBundleData::BfdConfig::DestinationAddress : public ydk::Entity { public: DestinationAddress(); ~DestinationAddress(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf af; //type: BmAfId ydk::YLeaf ipv4; //type: string ydk::YLeaf ipv6; //type: string }; // BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::BundleData::ActorBundleData::BfdConfig::DestinationAddress class BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::BundleData::BundleSystemId : public ydk::Entity { public: BundleSystemId(); ~BundleSystemId(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf system_prio; //type: uint16 class SystemMacAddr; //type: BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::BundleData::BundleSystemId::SystemMacAddr std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::BundleData::BundleSystemId::SystemMacAddr> system_mac_addr; }; // BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::BundleData::BundleSystemId class BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::BundleData::BundleSystemId::SystemMacAddr : public ydk::Entity { public: SystemMacAddr(); ~SystemMacAddr(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf macaddr; //type: string }; // BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::BundleData::BundleSystemId::SystemMacAddr class BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::MemberData : public ydk::Entity { public: MemberData(); ~MemberData(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf selected_aggregator_id; //type: uint32 ydk::YLeaf attached_aggregator_id; //type: uint32 ydk::YLeaf selection_state; //type: LacpSelState ydk::YLeaf period_state; //type: LacpPeriodState ydk::YLeaf receive_machine_state; //type: Rxstates ydk::YLeaf mux_state; //type: BmMuxstate ydk::YLeaf actor_churn_state; //type: LacpChurnstates ydk::YLeaf partner_churn_state; //type: LacpChurnstates ydk::YLeaf iccp_group_id; //type: uint32 class ActorInfo; //type: BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::MemberData::ActorInfo class PartnerInfo; //type: BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::MemberData::PartnerInfo class AdditionalInfo; //type: BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::MemberData::AdditionalInfo std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::MemberData::ActorInfo> actor_info; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::MemberData::PartnerInfo> partner_info; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::MemberData::AdditionalInfo> additional_info; }; // BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::MemberData class BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::MemberData::ActorInfo : public ydk::Entity { public: ActorInfo(); ~ActorInfo(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf tx_period; //type: uint32 class PortInfo; //type: BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::MemberData::ActorInfo::PortInfo std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::MemberData::ActorInfo::PortInfo> port_info; }; // BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::MemberData::ActorInfo class BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::MemberData::ActorInfo::PortInfo : public ydk::Entity { public: PortInfo(); ~PortInfo(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf key; //type: uint16 ydk::YLeaf state; //type: uint8 class System; //type: BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::MemberData::ActorInfo::PortInfo::System class Port; //type: BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::MemberData::ActorInfo::PortInfo::Port std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::MemberData::ActorInfo::PortInfo::System> system; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::MemberData::ActorInfo::PortInfo::Port> port; }; // BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::MemberData::ActorInfo::PortInfo class BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::MemberData::ActorInfo::PortInfo::System : public ydk::Entity { public: System(); ~System(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf system_prio; //type: uint16 class SystemMacAddr; //type: BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::MemberData::ActorInfo::PortInfo::System::SystemMacAddr std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::MemberData::ActorInfo::PortInfo::System::SystemMacAddr> system_mac_addr; }; // BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::MemberData::ActorInfo::PortInfo::System class BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::MemberData::ActorInfo::PortInfo::System::SystemMacAddr : public ydk::Entity { public: SystemMacAddr(); ~SystemMacAddr(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf macaddr; //type: string }; // BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::MemberData::ActorInfo::PortInfo::System::SystemMacAddr class BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::MemberData::ActorInfo::PortInfo::Port : public ydk::Entity { public: Port(); ~Port(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf link_priority; //type: uint16 ydk::YLeaf link_number; //type: uint16 }; // BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::MemberData::ActorInfo::PortInfo::Port class BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::MemberData::PartnerInfo : public ydk::Entity { public: PartnerInfo(); ~PartnerInfo(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf tx_period; //type: uint32 class PortInfo; //type: BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::MemberData::PartnerInfo::PortInfo std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::MemberData::PartnerInfo::PortInfo> port_info; }; // BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::MemberData::PartnerInfo class BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::MemberData::PartnerInfo::PortInfo : public ydk::Entity { public: PortInfo(); ~PortInfo(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf key; //type: uint16 ydk::YLeaf state; //type: uint8 class System; //type: BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::MemberData::PartnerInfo::PortInfo::System class Port; //type: BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::MemberData::PartnerInfo::PortInfo::Port std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::MemberData::PartnerInfo::PortInfo::System> system; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::MemberData::PartnerInfo::PortInfo::Port> port; }; // BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::MemberData::PartnerInfo::PortInfo class BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::MemberData::PartnerInfo::PortInfo::System : public ydk::Entity { public: System(); ~System(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf system_prio; //type: uint16 class SystemMacAddr; //type: BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::MemberData::PartnerInfo::PortInfo::System::SystemMacAddr std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::MemberData::PartnerInfo::PortInfo::System::SystemMacAddr> system_mac_addr; }; // BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::MemberData::PartnerInfo::PortInfo::System class BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::MemberData::PartnerInfo::PortInfo::System::SystemMacAddr : public ydk::Entity { public: SystemMacAddr(); ~SystemMacAddr(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf macaddr; //type: string }; // BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::MemberData::PartnerInfo::PortInfo::System::SystemMacAddr class BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::MemberData::PartnerInfo::PortInfo::Port : public ydk::Entity { public: Port(); ~Port(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf link_priority; //type: uint16 ydk::YLeaf link_number; //type: uint16 }; // BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::MemberData::PartnerInfo::PortInfo::Port class BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::MemberData::AdditionalInfo : public ydk::Entity { public: AdditionalInfo(); ~AdditionalInfo(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf mbr_type; //type: BmdMemberTypeEnum class Local; //type: BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::MemberData::AdditionalInfo::Local class Foreign; //type: BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::MemberData::AdditionalInfo::Foreign std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::MemberData::AdditionalInfo::Local> local; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::MemberData::AdditionalInfo::Foreign> foreign; }; // BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::MemberData::AdditionalInfo class BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::MemberData::AdditionalInfo::Local : public ydk::Entity { public: Local(); ~Local(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf interface_handle; //type: string }; // BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::MemberData::AdditionalInfo::Local class BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::MemberData::AdditionalInfo::Foreign : public ydk::Entity { public: Foreign(); ~Foreign(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf peer_address; //type: string ydk::YLeaf member_name; //type: string }; // BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberAncestor::MemberData::AdditionalInfo::Foreign class BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberItem : public ydk::Entity { public: LacpMemberItem(); ~LacpMemberItem(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf selected_aggregator_id; //type: uint32 ydk::YLeaf attached_aggregator_id; //type: uint32 ydk::YLeaf selection_state; //type: LacpSelState ydk::YLeaf period_state; //type: LacpPeriodState ydk::YLeaf receive_machine_state; //type: Rxstates ydk::YLeaf mux_state; //type: BmMuxstate ydk::YLeaf actor_churn_state; //type: LacpChurnstates ydk::YLeaf partner_churn_state; //type: LacpChurnstates ydk::YLeaf iccp_group_id; //type: uint32 class ActorInfo; //type: BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberItem::ActorInfo class PartnerInfo; //type: BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberItem::PartnerInfo class AdditionalInfo; //type: BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberItem::AdditionalInfo std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberItem::ActorInfo> actor_info; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberItem::PartnerInfo> partner_info; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberItem::AdditionalInfo> additional_info; }; // BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberItem class BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberItem::ActorInfo : public ydk::Entity { public: ActorInfo(); ~ActorInfo(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf tx_period; //type: uint32 class PortInfo; //type: BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberItem::ActorInfo::PortInfo std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberItem::ActorInfo::PortInfo> port_info; }; // BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberItem::ActorInfo class BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberItem::ActorInfo::PortInfo : public ydk::Entity { public: PortInfo(); ~PortInfo(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf key; //type: uint16 ydk::YLeaf state; //type: uint8 class System; //type: BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberItem::ActorInfo::PortInfo::System class Port; //type: BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberItem::ActorInfo::PortInfo::Port std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberItem::ActorInfo::PortInfo::System> system; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberItem::ActorInfo::PortInfo::Port> port; }; // BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberItem::ActorInfo::PortInfo class BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberItem::ActorInfo::PortInfo::System : public ydk::Entity { public: System(); ~System(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf system_prio; //type: uint16 class SystemMacAddr; //type: BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberItem::ActorInfo::PortInfo::System::SystemMacAddr std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberItem::ActorInfo::PortInfo::System::SystemMacAddr> system_mac_addr; }; // BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberItem::ActorInfo::PortInfo::System class BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberItem::ActorInfo::PortInfo::System::SystemMacAddr : public ydk::Entity { public: SystemMacAddr(); ~SystemMacAddr(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf macaddr; //type: string }; // BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberItem::ActorInfo::PortInfo::System::SystemMacAddr class BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberItem::ActorInfo::PortInfo::Port : public ydk::Entity { public: Port(); ~Port(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf link_priority; //type: uint16 ydk::YLeaf link_number; //type: uint16 }; // BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberItem::ActorInfo::PortInfo::Port class BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberItem::PartnerInfo : public ydk::Entity { public: PartnerInfo(); ~PartnerInfo(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf tx_period; //type: uint32 class PortInfo; //type: BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberItem::PartnerInfo::PortInfo std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberItem::PartnerInfo::PortInfo> port_info; }; // BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberItem::PartnerInfo class BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberItem::PartnerInfo::PortInfo : public ydk::Entity { public: PortInfo(); ~PortInfo(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf key; //type: uint16 ydk::YLeaf state; //type: uint8 class System; //type: BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberItem::PartnerInfo::PortInfo::System class Port; //type: BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberItem::PartnerInfo::PortInfo::Port std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberItem::PartnerInfo::PortInfo::System> system; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberItem::PartnerInfo::PortInfo::Port> port; }; // BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberItem::PartnerInfo::PortInfo class BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberItem::PartnerInfo::PortInfo::System : public ydk::Entity { public: System(); ~System(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf system_prio; //type: uint16 class SystemMacAddr; //type: BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberItem::PartnerInfo::PortInfo::System::SystemMacAddr std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberItem::PartnerInfo::PortInfo::System::SystemMacAddr> system_mac_addr; }; // BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberItem::PartnerInfo::PortInfo::System class BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberItem::PartnerInfo::PortInfo::System::SystemMacAddr : public ydk::Entity { public: SystemMacAddr(); ~SystemMacAddr(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf macaddr; //type: string }; // BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberItem::PartnerInfo::PortInfo::System::SystemMacAddr class BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberItem::PartnerInfo::PortInfo::Port : public ydk::Entity { public: Port(); ~Port(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf link_priority; //type: uint16 ydk::YLeaf link_number; //type: uint16 }; // BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberItem::PartnerInfo::PortInfo::Port class BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberItem::AdditionalInfo : public ydk::Entity { public: AdditionalInfo(); ~AdditionalInfo(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf mbr_type; //type: BmdMemberTypeEnum class Local; //type: BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberItem::AdditionalInfo::Local class Foreign; //type: BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberItem::AdditionalInfo::Foreign std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberItem::AdditionalInfo::Local> local; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberItem::AdditionalInfo::Foreign> foreign; }; // BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberItem::AdditionalInfo class BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberItem::AdditionalInfo::Local : public ydk::Entity { public: Local(); ~Local(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf interface_handle; //type: string }; // BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberItem::AdditionalInfo::Local class BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberItem::AdditionalInfo::Foreign : public ydk::Entity { public: Foreign(); ~Foreign(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf peer_address; //type: string ydk::YLeaf member_name; //type: string }; // BundleInformation::Lacp::LacpMembers::LacpMember::LacpMemberItem::AdditionalInfo::Foreign class BundleInformation::MlacpBundleCounters : public ydk::Entity { public: MlacpBundleCounters(); ~MlacpBundleCounters(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class IccpGroups; //type: BundleInformation::MlacpBundleCounters::IccpGroups class Bundles; //type: BundleInformation::MlacpBundleCounters::Bundles class Nodes; //type: BundleInformation::MlacpBundleCounters::Nodes std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBundleCounters::IccpGroups> iccp_groups; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBundleCounters::Bundles> bundles; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBundleCounters::Nodes> nodes; }; // BundleInformation::MlacpBundleCounters class BundleInformation::MlacpBundleCounters::IccpGroups : public ydk::Entity { public: IccpGroups(); ~IccpGroups(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class IccpGroup; //type: BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup ydk::YList iccp_group; }; // BundleInformation::MlacpBundleCounters::IccpGroups class BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup : public ydk::Entity { public: IccpGroup(); ~IccpGroup(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf iccp_group; //type: uint32 class IccpGroupItem; //type: BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem> iccp_group_item; }; // BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup class BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem : public ydk::Entity { public: IccpGroupItem(); ~IccpGroupItem(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class IccpGroupData; //type: BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::IccpGroupData class NodeData; //type: BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::NodeData std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::IccpGroupData> iccp_group_data; ydk::YList node_data; }; // BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem class BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::IccpGroupData : public ydk::Entity { public: IccpGroupData(); ~IccpGroupData(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf iccp_group_id; //type: uint32 class MlacpSyncRequestsOnAllLocalPorts; //type: BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::IccpGroupData::MlacpSyncRequestsOnAllLocalPorts class MlacpSyncRequestsOnAllLocalBundles; //type: BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::IccpGroupData::MlacpSyncRequestsOnAllLocalBundles class BundleData; //type: BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::IccpGroupData::BundleData std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::IccpGroupData::MlacpSyncRequestsOnAllLocalPorts> mlacp_sync_requests_on_all_local_ports; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::IccpGroupData::MlacpSyncRequestsOnAllLocalBundles> mlacp_sync_requests_on_all_local_bundles; ydk::YList bundle_data; }; // BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::IccpGroupData class BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::IccpGroupData::MlacpSyncRequestsOnAllLocalPorts : public ydk::Entity { public: MlacpSyncRequestsOnAllLocalPorts(); ~MlacpSyncRequestsOnAllLocalPorts(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf last_time_cleared; //type: uint64 ydk::YLeaf time_since_cleared; //type: uint64 class ReceivedSyncRequests; //type: BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::IccpGroupData::MlacpSyncRequestsOnAllLocalPorts::ReceivedSyncRequests std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::IccpGroupData::MlacpSyncRequestsOnAllLocalPorts::ReceivedSyncRequests> received_sync_requests; }; // BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::IccpGroupData::MlacpSyncRequestsOnAllLocalPorts class BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::IccpGroupData::MlacpSyncRequestsOnAllLocalPorts::ReceivedSyncRequests : public ydk::Entity { public: ReceivedSyncRequests(); ~ReceivedSyncRequests(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf all_syncs; //type: uint32 ydk::YLeaf config_syncs; //type: uint32 ydk::YLeaf state_syncs; //type: uint32 }; // BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::IccpGroupData::MlacpSyncRequestsOnAllLocalPorts::ReceivedSyncRequests class BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::IccpGroupData::MlacpSyncRequestsOnAllLocalBundles : public ydk::Entity { public: MlacpSyncRequestsOnAllLocalBundles(); ~MlacpSyncRequestsOnAllLocalBundles(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf last_time_cleared; //type: uint64 ydk::YLeaf time_since_cleared; //type: uint64 class ReceivedSyncRequests; //type: BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::IccpGroupData::MlacpSyncRequestsOnAllLocalBundles::ReceivedSyncRequests std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::IccpGroupData::MlacpSyncRequestsOnAllLocalBundles::ReceivedSyncRequests> received_sync_requests; }; // BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::IccpGroupData::MlacpSyncRequestsOnAllLocalBundles class BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::IccpGroupData::MlacpSyncRequestsOnAllLocalBundles::ReceivedSyncRequests : public ydk::Entity { public: ReceivedSyncRequests(); ~ReceivedSyncRequests(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf all_syncs; //type: uint32 ydk::YLeaf config_syncs; //type: uint32 ydk::YLeaf state_syncs; //type: uint32 }; // BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::IccpGroupData::MlacpSyncRequestsOnAllLocalBundles::ReceivedSyncRequests class BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::IccpGroupData::BundleData : public ydk::Entity { public: BundleData(); ~BundleData(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf bundle_name; //type: string class MlacpTlvCounters; //type: BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::IccpGroupData::BundleData::MlacpTlvCounters std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::IccpGroupData::BundleData::MlacpTlvCounters> mlacp_tlv_counters; }; // BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::IccpGroupData::BundleData class BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::IccpGroupData::BundleData::MlacpTlvCounters : public ydk::Entity { public: MlacpTlvCounters(); ~MlacpTlvCounters(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf sent_config_tl_vs; //type: uint32 ydk::YLeaf sent_state_tl_vs; //type: uint32 ydk::YLeaf sent_priority_tl_vs; //type: uint32 ydk::YLeaf received_priority_tl_vs; //type: uint32 ydk::YLeaf received_nak_tl_vs; //type: uint32 ydk::YLeaf last_time_cleared; //type: uint64 ydk::YLeaf time_since_cleared; //type: uint64 ydk::YLeaf last_unexpected_event; //type: uint64 class ReceivedSyncRequests; //type: BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::IccpGroupData::BundleData::MlacpTlvCounters::ReceivedSyncRequests std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::IccpGroupData::BundleData::MlacpTlvCounters::ReceivedSyncRequests> received_sync_requests; }; // BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::IccpGroupData::BundleData::MlacpTlvCounters class BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::IccpGroupData::BundleData::MlacpTlvCounters::ReceivedSyncRequests : public ydk::Entity { public: ReceivedSyncRequests(); ~ReceivedSyncRequests(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf all_syncs; //type: uint32 ydk::YLeaf config_syncs; //type: uint32 ydk::YLeaf state_syncs; //type: uint32 }; // BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::IccpGroupData::BundleData::MlacpTlvCounters::ReceivedSyncRequests class BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::NodeData : public ydk::Entity { public: NodeData(); ~NodeData(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class NodeData_; //type: BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::NodeData::NodeData_ class BundleData; //type: BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::NodeData::BundleData std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::NodeData::NodeData_> node_data; ydk::YList bundle_data; }; // BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::NodeData class BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::NodeData::NodeData_ : public ydk::Entity { public: NodeData_(); ~NodeData_(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf node_id; //type: uint32 class MlacpSyncRequestsOnAllForeignPorts; //type: BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::NodeData::NodeData_::MlacpSyncRequestsOnAllForeignPorts class MlacpSyncRequestsOnAllForeignBundles; //type: BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::NodeData::NodeData_::MlacpSyncRequestsOnAllForeignBundles std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::NodeData::NodeData_::MlacpSyncRequestsOnAllForeignPorts> mlacp_sync_requests_on_all_foreign_ports; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::NodeData::NodeData_::MlacpSyncRequestsOnAllForeignBundles> mlacp_sync_requests_on_all_foreign_bundles; }; // BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::NodeData::NodeData_ class BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::NodeData::NodeData_::MlacpSyncRequestsOnAllForeignPorts : public ydk::Entity { public: MlacpSyncRequestsOnAllForeignPorts(); ~MlacpSyncRequestsOnAllForeignPorts(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf last_time_cleared; //type: uint64 ydk::YLeaf time_since_cleared; //type: uint64 class ReceivedSyncRequests; //type: BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::NodeData::NodeData_::MlacpSyncRequestsOnAllForeignPorts::ReceivedSyncRequests std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::NodeData::NodeData_::MlacpSyncRequestsOnAllForeignPorts::ReceivedSyncRequests> received_sync_requests; }; // BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::NodeData::NodeData_::MlacpSyncRequestsOnAllForeignPorts class BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::NodeData::NodeData_::MlacpSyncRequestsOnAllForeignPorts::ReceivedSyncRequests : public ydk::Entity { public: ReceivedSyncRequests(); ~ReceivedSyncRequests(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf all_syncs; //type: uint32 ydk::YLeaf config_syncs; //type: uint32 ydk::YLeaf state_syncs; //type: uint32 }; // BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::NodeData::NodeData_::MlacpSyncRequestsOnAllForeignPorts::ReceivedSyncRequests class BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::NodeData::NodeData_::MlacpSyncRequestsOnAllForeignBundles : public ydk::Entity { public: MlacpSyncRequestsOnAllForeignBundles(); ~MlacpSyncRequestsOnAllForeignBundles(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf last_time_cleared; //type: uint64 ydk::YLeaf time_since_cleared; //type: uint64 class ReceivedSyncRequests; //type: BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::NodeData::NodeData_::MlacpSyncRequestsOnAllForeignBundles::ReceivedSyncRequests std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::NodeData::NodeData_::MlacpSyncRequestsOnAllForeignBundles::ReceivedSyncRequests> received_sync_requests; }; // BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::NodeData::NodeData_::MlacpSyncRequestsOnAllForeignBundles class BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::NodeData::NodeData_::MlacpSyncRequestsOnAllForeignBundles::ReceivedSyncRequests : public ydk::Entity { public: ReceivedSyncRequests(); ~ReceivedSyncRequests(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf all_syncs; //type: uint32 ydk::YLeaf config_syncs; //type: uint32 ydk::YLeaf state_syncs; //type: uint32 }; // BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::NodeData::NodeData_::MlacpSyncRequestsOnAllForeignBundles::ReceivedSyncRequests class BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::NodeData::BundleData : public ydk::Entity { public: BundleData(); ~BundleData(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf bundle_name; //type: string class MlacpTlvCounters; //type: BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::NodeData::BundleData::MlacpTlvCounters std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::NodeData::BundleData::MlacpTlvCounters> mlacp_tlv_counters; }; // BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::NodeData::BundleData class BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::NodeData::BundleData::MlacpTlvCounters : public ydk::Entity { public: MlacpTlvCounters(); ~MlacpTlvCounters(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf sent_config_tl_vs; //type: uint32 ydk::YLeaf sent_state_tl_vs; //type: uint32 ydk::YLeaf sent_priority_tl_vs; //type: uint32 ydk::YLeaf received_priority_tl_vs; //type: uint32 ydk::YLeaf received_nak_tl_vs; //type: uint32 ydk::YLeaf last_time_cleared; //type: uint64 ydk::YLeaf time_since_cleared; //type: uint64 ydk::YLeaf last_unexpected_event; //type: uint64 class ReceivedSyncRequests; //type: BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::NodeData::BundleData::MlacpTlvCounters::ReceivedSyncRequests std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::NodeData::BundleData::MlacpTlvCounters::ReceivedSyncRequests> received_sync_requests; }; // BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::NodeData::BundleData::MlacpTlvCounters class BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::NodeData::BundleData::MlacpTlvCounters::ReceivedSyncRequests : public ydk::Entity { public: ReceivedSyncRequests(); ~ReceivedSyncRequests(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf all_syncs; //type: uint32 ydk::YLeaf config_syncs; //type: uint32 ydk::YLeaf state_syncs; //type: uint32 }; // BundleInformation::MlacpBundleCounters::IccpGroups::IccpGroup::IccpGroupItem::NodeData::BundleData::MlacpTlvCounters::ReceivedSyncRequests class BundleInformation::MlacpBundleCounters::Bundles : public ydk::Entity { public: Bundles(); ~Bundles(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class Bundle; //type: BundleInformation::MlacpBundleCounters::Bundles::Bundle ydk::YList bundle; }; // BundleInformation::MlacpBundleCounters::Bundles class BundleInformation::MlacpBundleCounters::Bundles::Bundle : public ydk::Entity { public: Bundle(); ~Bundle(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf bundle_interface; //type: string class BundleItem; //type: BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem> bundle_item; }; // BundleInformation::MlacpBundleCounters::Bundles::Bundle class BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem : public ydk::Entity { public: BundleItem(); ~BundleItem(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class IccpGroup; //type: BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup ydk::YList iccp_group; }; // BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem class BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup : public ydk::Entity { public: IccpGroup(); ~IccpGroup(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class IccpGroupData; //type: BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::IccpGroupData class NodeData; //type: BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::NodeData std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::IccpGroupData> iccp_group_data; ydk::YList node_data; }; // BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup class BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::IccpGroupData : public ydk::Entity { public: IccpGroupData(); ~IccpGroupData(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf iccp_group_id; //type: uint32 class MlacpSyncRequestsOnAllLocalPorts; //type: BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::IccpGroupData::MlacpSyncRequestsOnAllLocalPorts class MlacpSyncRequestsOnAllLocalBundles; //type: BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::IccpGroupData::MlacpSyncRequestsOnAllLocalBundles class BundleData; //type: BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::IccpGroupData::BundleData std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::IccpGroupData::MlacpSyncRequestsOnAllLocalPorts> mlacp_sync_requests_on_all_local_ports; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::IccpGroupData::MlacpSyncRequestsOnAllLocalBundles> mlacp_sync_requests_on_all_local_bundles; ydk::YList bundle_data; }; // BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::IccpGroupData class BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::IccpGroupData::MlacpSyncRequestsOnAllLocalPorts : public ydk::Entity { public: MlacpSyncRequestsOnAllLocalPorts(); ~MlacpSyncRequestsOnAllLocalPorts(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf last_time_cleared; //type: uint64 ydk::YLeaf time_since_cleared; //type: uint64 class ReceivedSyncRequests; //type: BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::IccpGroupData::MlacpSyncRequestsOnAllLocalPorts::ReceivedSyncRequests std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::IccpGroupData::MlacpSyncRequestsOnAllLocalPorts::ReceivedSyncRequests> received_sync_requests; }; // BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::IccpGroupData::MlacpSyncRequestsOnAllLocalPorts class BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::IccpGroupData::MlacpSyncRequestsOnAllLocalPorts::ReceivedSyncRequests : public ydk::Entity { public: ReceivedSyncRequests(); ~ReceivedSyncRequests(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf all_syncs; //type: uint32 ydk::YLeaf config_syncs; //type: uint32 ydk::YLeaf state_syncs; //type: uint32 }; // BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::IccpGroupData::MlacpSyncRequestsOnAllLocalPorts::ReceivedSyncRequests class BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::IccpGroupData::MlacpSyncRequestsOnAllLocalBundles : public ydk::Entity { public: MlacpSyncRequestsOnAllLocalBundles(); ~MlacpSyncRequestsOnAllLocalBundles(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf last_time_cleared; //type: uint64 ydk::YLeaf time_since_cleared; //type: uint64 class ReceivedSyncRequests; //type: BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::IccpGroupData::MlacpSyncRequestsOnAllLocalBundles::ReceivedSyncRequests std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::IccpGroupData::MlacpSyncRequestsOnAllLocalBundles::ReceivedSyncRequests> received_sync_requests; }; // BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::IccpGroupData::MlacpSyncRequestsOnAllLocalBundles class BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::IccpGroupData::MlacpSyncRequestsOnAllLocalBundles::ReceivedSyncRequests : public ydk::Entity { public: ReceivedSyncRequests(); ~ReceivedSyncRequests(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf all_syncs; //type: uint32 ydk::YLeaf config_syncs; //type: uint32 ydk::YLeaf state_syncs; //type: uint32 }; // BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::IccpGroupData::MlacpSyncRequestsOnAllLocalBundles::ReceivedSyncRequests class BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::IccpGroupData::BundleData : public ydk::Entity { public: BundleData(); ~BundleData(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf bundle_name; //type: string class MlacpTlvCounters; //type: BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::IccpGroupData::BundleData::MlacpTlvCounters std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::IccpGroupData::BundleData::MlacpTlvCounters> mlacp_tlv_counters; }; // BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::IccpGroupData::BundleData class BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::IccpGroupData::BundleData::MlacpTlvCounters : public ydk::Entity { public: MlacpTlvCounters(); ~MlacpTlvCounters(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf sent_config_tl_vs; //type: uint32 ydk::YLeaf sent_state_tl_vs; //type: uint32 ydk::YLeaf sent_priority_tl_vs; //type: uint32 ydk::YLeaf received_priority_tl_vs; //type: uint32 ydk::YLeaf received_nak_tl_vs; //type: uint32 ydk::YLeaf last_time_cleared; //type: uint64 ydk::YLeaf time_since_cleared; //type: uint64 ydk::YLeaf last_unexpected_event; //type: uint64 class ReceivedSyncRequests; //type: BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::IccpGroupData::BundleData::MlacpTlvCounters::ReceivedSyncRequests std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::IccpGroupData::BundleData::MlacpTlvCounters::ReceivedSyncRequests> received_sync_requests; }; // BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::IccpGroupData::BundleData::MlacpTlvCounters class BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::IccpGroupData::BundleData::MlacpTlvCounters::ReceivedSyncRequests : public ydk::Entity { public: ReceivedSyncRequests(); ~ReceivedSyncRequests(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf all_syncs; //type: uint32 ydk::YLeaf config_syncs; //type: uint32 ydk::YLeaf state_syncs; //type: uint32 }; // BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::IccpGroupData::BundleData::MlacpTlvCounters::ReceivedSyncRequests class BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::NodeData : public ydk::Entity { public: NodeData(); ~NodeData(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class NodeData_; //type: BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::NodeData::NodeData_ class BundleData; //type: BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::NodeData::BundleData std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::NodeData::NodeData_> node_data; ydk::YList bundle_data; }; // BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::NodeData class BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::NodeData::NodeData_ : public ydk::Entity { public: NodeData_(); ~NodeData_(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf node_id; //type: uint32 class MlacpSyncRequestsOnAllForeignPorts; //type: BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::NodeData::NodeData_::MlacpSyncRequestsOnAllForeignPorts class MlacpSyncRequestsOnAllForeignBundles; //type: BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::NodeData::NodeData_::MlacpSyncRequestsOnAllForeignBundles std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::NodeData::NodeData_::MlacpSyncRequestsOnAllForeignPorts> mlacp_sync_requests_on_all_foreign_ports; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::NodeData::NodeData_::MlacpSyncRequestsOnAllForeignBundles> mlacp_sync_requests_on_all_foreign_bundles; }; // BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::NodeData::NodeData_ class BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::NodeData::NodeData_::MlacpSyncRequestsOnAllForeignPorts : public ydk::Entity { public: MlacpSyncRequestsOnAllForeignPorts(); ~MlacpSyncRequestsOnAllForeignPorts(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf last_time_cleared; //type: uint64 ydk::YLeaf time_since_cleared; //type: uint64 class ReceivedSyncRequests; //type: BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::NodeData::NodeData_::MlacpSyncRequestsOnAllForeignPorts::ReceivedSyncRequests std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::NodeData::NodeData_::MlacpSyncRequestsOnAllForeignPorts::ReceivedSyncRequests> received_sync_requests; }; // BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::NodeData::NodeData_::MlacpSyncRequestsOnAllForeignPorts class BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::NodeData::NodeData_::MlacpSyncRequestsOnAllForeignPorts::ReceivedSyncRequests : public ydk::Entity { public: ReceivedSyncRequests(); ~ReceivedSyncRequests(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf all_syncs; //type: uint32 ydk::YLeaf config_syncs; //type: uint32 ydk::YLeaf state_syncs; //type: uint32 }; // BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::NodeData::NodeData_::MlacpSyncRequestsOnAllForeignPorts::ReceivedSyncRequests class BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::NodeData::NodeData_::MlacpSyncRequestsOnAllForeignBundles : public ydk::Entity { public: MlacpSyncRequestsOnAllForeignBundles(); ~MlacpSyncRequestsOnAllForeignBundles(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf last_time_cleared; //type: uint64 ydk::YLeaf time_since_cleared; //type: uint64 class ReceivedSyncRequests; //type: BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::NodeData::NodeData_::MlacpSyncRequestsOnAllForeignBundles::ReceivedSyncRequests std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::NodeData::NodeData_::MlacpSyncRequestsOnAllForeignBundles::ReceivedSyncRequests> received_sync_requests; }; // BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::NodeData::NodeData_::MlacpSyncRequestsOnAllForeignBundles class BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::NodeData::NodeData_::MlacpSyncRequestsOnAllForeignBundles::ReceivedSyncRequests : public ydk::Entity { public: ReceivedSyncRequests(); ~ReceivedSyncRequests(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf all_syncs; //type: uint32 ydk::YLeaf config_syncs; //type: uint32 ydk::YLeaf state_syncs; //type: uint32 }; // BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::NodeData::NodeData_::MlacpSyncRequestsOnAllForeignBundles::ReceivedSyncRequests class BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::NodeData::BundleData : public ydk::Entity { public: BundleData(); ~BundleData(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf bundle_name; //type: string class MlacpTlvCounters; //type: BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::NodeData::BundleData::MlacpTlvCounters std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::NodeData::BundleData::MlacpTlvCounters> mlacp_tlv_counters; }; // BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::NodeData::BundleData class BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::NodeData::BundleData::MlacpTlvCounters : public ydk::Entity { public: MlacpTlvCounters(); ~MlacpTlvCounters(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf sent_config_tl_vs; //type: uint32 ydk::YLeaf sent_state_tl_vs; //type: uint32 ydk::YLeaf sent_priority_tl_vs; //type: uint32 ydk::YLeaf received_priority_tl_vs; //type: uint32 ydk::YLeaf received_nak_tl_vs; //type: uint32 ydk::YLeaf last_time_cleared; //type: uint64 ydk::YLeaf time_since_cleared; //type: uint64 ydk::YLeaf last_unexpected_event; //type: uint64 class ReceivedSyncRequests; //type: BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::NodeData::BundleData::MlacpTlvCounters::ReceivedSyncRequests std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::NodeData::BundleData::MlacpTlvCounters::ReceivedSyncRequests> received_sync_requests; }; // BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::NodeData::BundleData::MlacpTlvCounters class BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::NodeData::BundleData::MlacpTlvCounters::ReceivedSyncRequests : public ydk::Entity { public: ReceivedSyncRequests(); ~ReceivedSyncRequests(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf all_syncs; //type: uint32 ydk::YLeaf config_syncs; //type: uint32 ydk::YLeaf state_syncs; //type: uint32 }; // BundleInformation::MlacpBundleCounters::Bundles::Bundle::BundleItem::IccpGroup::NodeData::BundleData::MlacpTlvCounters::ReceivedSyncRequests class BundleInformation::MlacpBundleCounters::Nodes : public ydk::Entity { public: Nodes(); ~Nodes(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class Node; //type: BundleInformation::MlacpBundleCounters::Nodes::Node ydk::YList node; }; // BundleInformation::MlacpBundleCounters::Nodes class BundleInformation::MlacpBundleCounters::Nodes::Node : public ydk::Entity { public: Node(); ~Node(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf node; //type: string class NodeItem; //type: BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem> node_item; }; // BundleInformation::MlacpBundleCounters::Nodes::Node class BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem : public ydk::Entity { public: NodeItem(); ~NodeItem(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class IccpGroupData; //type: BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::IccpGroupData class NodeData; //type: BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::NodeData std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::IccpGroupData> iccp_group_data; ydk::YList node_data; }; // BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem class BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::IccpGroupData : public ydk::Entity { public: IccpGroupData(); ~IccpGroupData(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf iccp_group_id; //type: uint32 class MlacpSyncRequestsOnAllLocalPorts; //type: BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::IccpGroupData::MlacpSyncRequestsOnAllLocalPorts class MlacpSyncRequestsOnAllLocalBundles; //type: BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::IccpGroupData::MlacpSyncRequestsOnAllLocalBundles class BundleData; //type: BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::IccpGroupData::BundleData std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::IccpGroupData::MlacpSyncRequestsOnAllLocalPorts> mlacp_sync_requests_on_all_local_ports; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::IccpGroupData::MlacpSyncRequestsOnAllLocalBundles> mlacp_sync_requests_on_all_local_bundles; ydk::YList bundle_data; }; // BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::IccpGroupData class BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::IccpGroupData::MlacpSyncRequestsOnAllLocalPorts : public ydk::Entity { public: MlacpSyncRequestsOnAllLocalPorts(); ~MlacpSyncRequestsOnAllLocalPorts(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf last_time_cleared; //type: uint64 ydk::YLeaf time_since_cleared; //type: uint64 class ReceivedSyncRequests; //type: BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::IccpGroupData::MlacpSyncRequestsOnAllLocalPorts::ReceivedSyncRequests std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::IccpGroupData::MlacpSyncRequestsOnAllLocalPorts::ReceivedSyncRequests> received_sync_requests; }; // BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::IccpGroupData::MlacpSyncRequestsOnAllLocalPorts class BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::IccpGroupData::MlacpSyncRequestsOnAllLocalPorts::ReceivedSyncRequests : public ydk::Entity { public: ReceivedSyncRequests(); ~ReceivedSyncRequests(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf all_syncs; //type: uint32 ydk::YLeaf config_syncs; //type: uint32 ydk::YLeaf state_syncs; //type: uint32 }; // BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::IccpGroupData::MlacpSyncRequestsOnAllLocalPorts::ReceivedSyncRequests class BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::IccpGroupData::MlacpSyncRequestsOnAllLocalBundles : public ydk::Entity { public: MlacpSyncRequestsOnAllLocalBundles(); ~MlacpSyncRequestsOnAllLocalBundles(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf last_time_cleared; //type: uint64 ydk::YLeaf time_since_cleared; //type: uint64 class ReceivedSyncRequests; //type: BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::IccpGroupData::MlacpSyncRequestsOnAllLocalBundles::ReceivedSyncRequests std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::IccpGroupData::MlacpSyncRequestsOnAllLocalBundles::ReceivedSyncRequests> received_sync_requests; }; // BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::IccpGroupData::MlacpSyncRequestsOnAllLocalBundles class BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::IccpGroupData::MlacpSyncRequestsOnAllLocalBundles::ReceivedSyncRequests : public ydk::Entity { public: ReceivedSyncRequests(); ~ReceivedSyncRequests(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf all_syncs; //type: uint32 ydk::YLeaf config_syncs; //type: uint32 ydk::YLeaf state_syncs; //type: uint32 }; // BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::IccpGroupData::MlacpSyncRequestsOnAllLocalBundles::ReceivedSyncRequests class BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::IccpGroupData::BundleData : public ydk::Entity { public: BundleData(); ~BundleData(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf bundle_name; //type: string class MlacpTlvCounters; //type: BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::IccpGroupData::BundleData::MlacpTlvCounters std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::IccpGroupData::BundleData::MlacpTlvCounters> mlacp_tlv_counters; }; // BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::IccpGroupData::BundleData class BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::IccpGroupData::BundleData::MlacpTlvCounters : public ydk::Entity { public: MlacpTlvCounters(); ~MlacpTlvCounters(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf sent_config_tl_vs; //type: uint32 ydk::YLeaf sent_state_tl_vs; //type: uint32 ydk::YLeaf sent_priority_tl_vs; //type: uint32 ydk::YLeaf received_priority_tl_vs; //type: uint32 ydk::YLeaf received_nak_tl_vs; //type: uint32 ydk::YLeaf last_time_cleared; //type: uint64 ydk::YLeaf time_since_cleared; //type: uint64 ydk::YLeaf last_unexpected_event; //type: uint64 class ReceivedSyncRequests; //type: BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::IccpGroupData::BundleData::MlacpTlvCounters::ReceivedSyncRequests std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::IccpGroupData::BundleData::MlacpTlvCounters::ReceivedSyncRequests> received_sync_requests; }; // BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::IccpGroupData::BundleData::MlacpTlvCounters class BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::IccpGroupData::BundleData::MlacpTlvCounters::ReceivedSyncRequests : public ydk::Entity { public: ReceivedSyncRequests(); ~ReceivedSyncRequests(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf all_syncs; //type: uint32 ydk::YLeaf config_syncs; //type: uint32 ydk::YLeaf state_syncs; //type: uint32 }; // BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::IccpGroupData::BundleData::MlacpTlvCounters::ReceivedSyncRequests class BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::NodeData : public ydk::Entity { public: NodeData(); ~NodeData(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class NodeData_; //type: BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::NodeData::NodeData_ class BundleData; //type: BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::NodeData::BundleData std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::NodeData::NodeData_> node_data; ydk::YList bundle_data; }; // BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::NodeData class BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::NodeData::NodeData_ : public ydk::Entity { public: NodeData_(); ~NodeData_(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf node_id; //type: uint32 class MlacpSyncRequestsOnAllForeignPorts; //type: BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::NodeData::NodeData_::MlacpSyncRequestsOnAllForeignPorts class MlacpSyncRequestsOnAllForeignBundles; //type: BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::NodeData::NodeData_::MlacpSyncRequestsOnAllForeignBundles std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::NodeData::NodeData_::MlacpSyncRequestsOnAllForeignPorts> mlacp_sync_requests_on_all_foreign_ports; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::NodeData::NodeData_::MlacpSyncRequestsOnAllForeignBundles> mlacp_sync_requests_on_all_foreign_bundles; }; // BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::NodeData::NodeData_ class BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::NodeData::NodeData_::MlacpSyncRequestsOnAllForeignPorts : public ydk::Entity { public: MlacpSyncRequestsOnAllForeignPorts(); ~MlacpSyncRequestsOnAllForeignPorts(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf last_time_cleared; //type: uint64 ydk::YLeaf time_since_cleared; //type: uint64 class ReceivedSyncRequests; //type: BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::NodeData::NodeData_::MlacpSyncRequestsOnAllForeignPorts::ReceivedSyncRequests std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::NodeData::NodeData_::MlacpSyncRequestsOnAllForeignPorts::ReceivedSyncRequests> received_sync_requests; }; // BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::NodeData::NodeData_::MlacpSyncRequestsOnAllForeignPorts class BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::NodeData::NodeData_::MlacpSyncRequestsOnAllForeignPorts::ReceivedSyncRequests : public ydk::Entity { public: ReceivedSyncRequests(); ~ReceivedSyncRequests(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf all_syncs; //type: uint32 ydk::YLeaf config_syncs; //type: uint32 ydk::YLeaf state_syncs; //type: uint32 }; // BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::NodeData::NodeData_::MlacpSyncRequestsOnAllForeignPorts::ReceivedSyncRequests class BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::NodeData::NodeData_::MlacpSyncRequestsOnAllForeignBundles : public ydk::Entity { public: MlacpSyncRequestsOnAllForeignBundles(); ~MlacpSyncRequestsOnAllForeignBundles(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf last_time_cleared; //type: uint64 ydk::YLeaf time_since_cleared; //type: uint64 class ReceivedSyncRequests; //type: BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::NodeData::NodeData_::MlacpSyncRequestsOnAllForeignBundles::ReceivedSyncRequests std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::NodeData::NodeData_::MlacpSyncRequestsOnAllForeignBundles::ReceivedSyncRequests> received_sync_requests; }; // BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::NodeData::NodeData_::MlacpSyncRequestsOnAllForeignBundles class BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::NodeData::NodeData_::MlacpSyncRequestsOnAllForeignBundles::ReceivedSyncRequests : public ydk::Entity { public: ReceivedSyncRequests(); ~ReceivedSyncRequests(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf all_syncs; //type: uint32 ydk::YLeaf config_syncs; //type: uint32 ydk::YLeaf state_syncs; //type: uint32 }; // BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::NodeData::NodeData_::MlacpSyncRequestsOnAllForeignBundles::ReceivedSyncRequests class BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::NodeData::BundleData : public ydk::Entity { public: BundleData(); ~BundleData(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf bundle_name; //type: string class MlacpTlvCounters; //type: BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::NodeData::BundleData::MlacpTlvCounters std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::NodeData::BundleData::MlacpTlvCounters> mlacp_tlv_counters; }; // BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::NodeData::BundleData class BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::NodeData::BundleData::MlacpTlvCounters : public ydk::Entity { public: MlacpTlvCounters(); ~MlacpTlvCounters(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf sent_config_tl_vs; //type: uint32 ydk::YLeaf sent_state_tl_vs; //type: uint32 ydk::YLeaf sent_priority_tl_vs; //type: uint32 ydk::YLeaf received_priority_tl_vs; //type: uint32 ydk::YLeaf received_nak_tl_vs; //type: uint32 ydk::YLeaf last_time_cleared; //type: uint64 ydk::YLeaf time_since_cleared; //type: uint64 ydk::YLeaf last_unexpected_event; //type: uint64 class ReceivedSyncRequests; //type: BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::NodeData::BundleData::MlacpTlvCounters::ReceivedSyncRequests std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::NodeData::BundleData::MlacpTlvCounters::ReceivedSyncRequests> received_sync_requests; }; // BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::NodeData::BundleData::MlacpTlvCounters class BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::NodeData::BundleData::MlacpTlvCounters::ReceivedSyncRequests : public ydk::Entity { public: ReceivedSyncRequests(); ~ReceivedSyncRequests(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf all_syncs; //type: uint32 ydk::YLeaf config_syncs; //type: uint32 ydk::YLeaf state_syncs; //type: uint32 }; // BundleInformation::MlacpBundleCounters::Nodes::Node::NodeItem::NodeData::BundleData::MlacpTlvCounters::ReceivedSyncRequests class BundleInformation::Protect : public ydk::Entity { public: Protect(); ~Protect(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class ProtectBundles; //type: BundleInformation::Protect::ProtectBundles std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::Protect::ProtectBundles> protect_bundles; }; // BundleInformation::Protect class BundleInformation::Protect::ProtectBundles : public ydk::Entity { public: ProtectBundles(); ~ProtectBundles(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class ProtectBundle; //type: BundleInformation::Protect::ProtectBundles::ProtectBundle ydk::YList protect_bundle; }; // BundleInformation::Protect::ProtectBundles class BundleInformation::Protect::ProtectBundles::ProtectBundle : public ydk::Entity { public: ProtectBundle(); ~ProtectBundle(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf bundle_interface; //type: string class ProtectBundleItem; //type: BundleInformation::Protect::ProtectBundles::ProtectBundle::ProtectBundleItem std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::Protect::ProtectBundles::ProtectBundle::ProtectBundleItem> protect_bundle_item; }; // BundleInformation::Protect::ProtectBundles::ProtectBundle class BundleInformation::Protect::ProtectBundles::ProtectBundle::ProtectBundleItem : public ydk::Entity { public: ProtectBundleItem(); ~ProtectBundleItem(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf bundle_interface_handle; //type: string ydk::YLeaf interface_up; //type: boolean ydk::YLeaf registered; //type: boolean ydk::YLeaf slow_path_up; //type: boolean ydk::YLeaf slow_path_trigger; //type: boolean ydk::YLeaf minimum_active_links; //type: uint32 ydk::YLeaf minimum_bandwidth; //type: uint32 ydk::YLeaf event_type; //type: BmdBagTarget ydk::YLeaf time_stamp; //type: uint64 class MemberInfo; //type: BundleInformation::Protect::ProtectBundles::ProtectBundle::ProtectBundleItem::MemberInfo ydk::YList member_info; }; // BundleInformation::Protect::ProtectBundles::ProtectBundle::ProtectBundleItem class BundleInformation::Protect::ProtectBundles::ProtectBundle::ProtectBundleItem::MemberInfo : public ydk::Entity { public: MemberInfo(); ~MemberInfo(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf interface_handle; //type: string ydk::YLeaf underlying_link_id; //type: uint16 ydk::YLeaf link_order_number; //type: uint16 ydk::YLeaf bandwidth; //type: uint32 ydk::YLeaf node; //type: string ydk::YLeaf active; //type: boolean ydk::YLeaf notification_received; //type: boolean ydk::YLeaf slow_path_up; //type: boolean ydk::YLeaf time_stamp; //type: uint64 }; // BundleInformation::Protect::ProtectBundles::ProtectBundle::ProtectBundleItem::MemberInfo class BundleInformation::MlacpBrief : public ydk::Entity { public: MlacpBrief(); ~MlacpBrief(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class MlacpBundleBriefs; //type: BundleInformation::MlacpBrief::MlacpBundleBriefs class MlacpBriefIccpGroups; //type: BundleInformation::MlacpBrief::MlacpBriefIccpGroups std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBrief::MlacpBundleBriefs> mlacp_bundle_briefs; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBrief::MlacpBriefIccpGroups> mlacp_brief_iccp_groups; }; // BundleInformation::MlacpBrief class BundleInformation::MlacpBrief::MlacpBundleBriefs : public ydk::Entity { public: MlacpBundleBriefs(); ~MlacpBundleBriefs(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class MlacpBundleBrief; //type: BundleInformation::MlacpBrief::MlacpBundleBriefs::MlacpBundleBrief ydk::YList mlacp_bundle_brief; }; // BundleInformation::MlacpBrief::MlacpBundleBriefs class BundleInformation::MlacpBrief::MlacpBundleBriefs::MlacpBundleBrief : public ydk::Entity { public: MlacpBundleBrief(); ~MlacpBundleBrief(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf bundle_interface; //type: string class MlacpBundleItemBrief; //type: BundleInformation::MlacpBrief::MlacpBundleBriefs::MlacpBundleBrief::MlacpBundleItemBrief std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBrief::MlacpBundleBriefs::MlacpBundleBrief::MlacpBundleItemBrief> mlacp_bundle_item_brief; }; // BundleInformation::MlacpBrief::MlacpBundleBriefs::MlacpBundleBrief class BundleInformation::MlacpBrief::MlacpBundleBriefs::MlacpBundleBrief::MlacpBundleItemBrief : public ydk::Entity { public: MlacpBundleItemBrief(); ~MlacpBundleItemBrief(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class MlacpData; //type: BundleInformation::MlacpBrief::MlacpBundleBriefs::MlacpBundleBrief::MlacpBundleItemBrief::MlacpData ydk::YList mlacp_data; }; // BundleInformation::MlacpBrief::MlacpBundleBriefs::MlacpBundleBrief::MlacpBundleItemBrief class BundleInformation::MlacpBrief::MlacpBundleBriefs::MlacpBundleBrief::MlacpBundleItemBrief::MlacpData : public ydk::Entity { public: MlacpData(); ~MlacpData(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class IccpGroupData; //type: BundleInformation::MlacpBrief::MlacpBundleBriefs::MlacpBundleBrief::MlacpBundleItemBrief::MlacpData::IccpGroupData class BundleData; //type: BundleInformation::MlacpBrief::MlacpBundleBriefs::MlacpBundleBrief::MlacpBundleItemBrief::MlacpData::BundleData std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBrief::MlacpBundleBriefs::MlacpBundleBrief::MlacpBundleItemBrief::MlacpData::IccpGroupData> iccp_group_data; ydk::YList bundle_data; }; // BundleInformation::MlacpBrief::MlacpBundleBriefs::MlacpBundleBrief::MlacpBundleItemBrief::MlacpData class BundleInformation::MlacpBrief::MlacpBundleBriefs::MlacpBundleBrief::MlacpBundleItemBrief::MlacpData::IccpGroupData : public ydk::Entity { public: IccpGroupData(); ~IccpGroupData(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf iccp_group_id; //type: uint32 ydk::YLeaf singleton; //type: boolean ydk::YLeaf connect_timer_running; //type: uint64 class NodeData; //type: BundleInformation::MlacpBrief::MlacpBundleBriefs::MlacpBundleBrief::MlacpBundleItemBrief::MlacpData::IccpGroupData::NodeData ydk::YList node_data; }; // BundleInformation::MlacpBrief::MlacpBundleBriefs::MlacpBundleBrief::MlacpBundleItemBrief::MlacpData::IccpGroupData class BundleInformation::MlacpBrief::MlacpBundleBriefs::MlacpBundleBrief::MlacpBundleItemBrief::MlacpData::IccpGroupData::NodeData : public ydk::Entity { public: NodeData(); ~NodeData(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf mlacp_node_id; //type: uint8 ydk::YLeaf ldp_id; //type: string ydk::YLeaf version_number; //type: uint32 ydk::YLeaf node_state; //type: BmdMlacpNodeStateEnum ydk::YLeaf iccp_group_state; //type: BmdMlacpNodeSyncEnum class SystemId; //type: BundleInformation::MlacpBrief::MlacpBundleBriefs::MlacpBundleBrief::MlacpBundleItemBrief::MlacpData::IccpGroupData::NodeData::SystemId std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBrief::MlacpBundleBriefs::MlacpBundleBrief::MlacpBundleItemBrief::MlacpData::IccpGroupData::NodeData::SystemId> system_id; }; // BundleInformation::MlacpBrief::MlacpBundleBriefs::MlacpBundleBrief::MlacpBundleItemBrief::MlacpData::IccpGroupData::NodeData class BundleInformation::MlacpBrief::MlacpBundleBriefs::MlacpBundleBrief::MlacpBundleItemBrief::MlacpData::IccpGroupData::NodeData::SystemId : public ydk::Entity { public: SystemId(); ~SystemId(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf system_prio; //type: uint16 class SystemMacAddr; //type: BundleInformation::MlacpBrief::MlacpBundleBriefs::MlacpBundleBrief::MlacpBundleItemBrief::MlacpData::IccpGroupData::NodeData::SystemId::SystemMacAddr std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBrief::MlacpBundleBriefs::MlacpBundleBrief::MlacpBundleItemBrief::MlacpData::IccpGroupData::NodeData::SystemId::SystemMacAddr> system_mac_addr; }; // BundleInformation::MlacpBrief::MlacpBundleBriefs::MlacpBundleBrief::MlacpBundleItemBrief::MlacpData::IccpGroupData::NodeData::SystemId class BundleInformation::MlacpBrief::MlacpBundleBriefs::MlacpBundleBrief::MlacpBundleItemBrief::MlacpData::IccpGroupData::NodeData::SystemId::SystemMacAddr : public ydk::Entity { public: SystemMacAddr(); ~SystemMacAddr(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf macaddr; //type: string }; // BundleInformation::MlacpBrief::MlacpBundleBriefs::MlacpBundleBrief::MlacpBundleItemBrief::MlacpData::IccpGroupData::NodeData::SystemId::SystemMacAddr class BundleInformation::MlacpBrief::MlacpBundleBriefs::MlacpBundleBrief::MlacpBundleItemBrief::MlacpData::BundleData : public ydk::Entity { public: BundleData(); ~BundleData(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf bundle_interface_key; //type: uint16 ydk::YLeaf media_type; //type: BundleMedia ydk::YLeaf redundancy_object_id; //type: uint64 class MlacpBundleData; //type: BundleInformation::MlacpBrief::MlacpBundleBriefs::MlacpBundleBrief::MlacpBundleItemBrief::MlacpData::BundleData::MlacpBundleData class MlacpMemberData; //type: BundleInformation::MlacpBrief::MlacpBundleBriefs::MlacpBundleBrief::MlacpBundleItemBrief::MlacpData::BundleData::MlacpMemberData ydk::YList mlacp_bundle_data; ydk::YList mlacp_member_data; }; // BundleInformation::MlacpBrief::MlacpBundleBriefs::MlacpBundleBrief::MlacpBundleItemBrief::MlacpData::BundleData class BundleInformation::MlacpBrief::MlacpBundleBriefs::MlacpBundleBrief::MlacpBundleItemBrief::MlacpData::BundleData::MlacpBundleData : public ydk::Entity { public: MlacpBundleData(); ~MlacpBundleData(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf bundle_name; //type: string ydk::YLeaf mlacp_node_id; //type: uint8 ydk::YLeaf aggregator_id; //type: uint16 ydk::YLeaf bundle_state; //type: BmdMlacpBdlStateEnum ydk::YLeaf port_priority; //type: uint16 class MacAddress; //type: BundleInformation::MlacpBrief::MlacpBundleBriefs::MlacpBundleBrief::MlacpBundleItemBrief::MlacpData::BundleData::MlacpBundleData::MacAddress std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBrief::MlacpBundleBriefs::MlacpBundleBrief::MlacpBundleItemBrief::MlacpData::BundleData::MlacpBundleData::MacAddress> mac_address; }; // BundleInformation::MlacpBrief::MlacpBundleBriefs::MlacpBundleBrief::MlacpBundleItemBrief::MlacpData::BundleData::MlacpBundleData class BundleInformation::MlacpBrief::MlacpBundleBriefs::MlacpBundleBrief::MlacpBundleItemBrief::MlacpData::BundleData::MlacpBundleData::MacAddress : public ydk::Entity { public: MacAddress(); ~MacAddress(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf address; //type: string }; // BundleInformation::MlacpBrief::MlacpBundleBriefs::MlacpBundleBrief::MlacpBundleItemBrief::MlacpData::BundleData::MlacpBundleData::MacAddress class BundleInformation::MlacpBrief::MlacpBundleBriefs::MlacpBundleBrief::MlacpBundleItemBrief::MlacpData::BundleData::MlacpMemberData : public ydk::Entity { public: MlacpMemberData(); ~MlacpMemberData(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf port_name; //type: string ydk::YLeaf interface_handle; //type: string ydk::YLeaf mlacp_node_id; //type: uint8 ydk::YLeaf port_number; //type: uint16 ydk::YLeaf operational_priority; //type: uint16 ydk::YLeaf configured_priority; //type: uint16 ydk::YLeaf member_state; //type: BmdMlacpMbrStateEnum }; // BundleInformation::MlacpBrief::MlacpBundleBriefs::MlacpBundleBrief::MlacpBundleItemBrief::MlacpData::BundleData::MlacpMemberData class BundleInformation::MlacpBrief::MlacpBriefIccpGroups : public ydk::Entity { public: MlacpBriefIccpGroups(); ~MlacpBriefIccpGroups(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class MlacpBriefIccpGroup; //type: BundleInformation::MlacpBrief::MlacpBriefIccpGroups::MlacpBriefIccpGroup ydk::YList mlacp_brief_iccp_group; }; // BundleInformation::MlacpBrief::MlacpBriefIccpGroups class BundleInformation::MlacpBrief::MlacpBriefIccpGroups::MlacpBriefIccpGroup : public ydk::Entity { public: MlacpBriefIccpGroup(); ~MlacpBriefIccpGroup(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf iccp_group; //type: uint32 class MlacpBriefIccpGroupItem; //type: BundleInformation::MlacpBrief::MlacpBriefIccpGroups::MlacpBriefIccpGroup::MlacpBriefIccpGroupItem std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBrief::MlacpBriefIccpGroups::MlacpBriefIccpGroup::MlacpBriefIccpGroupItem> mlacp_brief_iccp_group_item; }; // BundleInformation::MlacpBrief::MlacpBriefIccpGroups::MlacpBriefIccpGroup class BundleInformation::MlacpBrief::MlacpBriefIccpGroups::MlacpBriefIccpGroup::MlacpBriefIccpGroupItem : public ydk::Entity { public: MlacpBriefIccpGroupItem(); ~MlacpBriefIccpGroupItem(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class IccpGroupData; //type: BundleInformation::MlacpBrief::MlacpBriefIccpGroups::MlacpBriefIccpGroup::MlacpBriefIccpGroupItem::IccpGroupData class BundleData; //type: BundleInformation::MlacpBrief::MlacpBriefIccpGroups::MlacpBriefIccpGroup::MlacpBriefIccpGroupItem::BundleData std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBrief::MlacpBriefIccpGroups::MlacpBriefIccpGroup::MlacpBriefIccpGroupItem::IccpGroupData> iccp_group_data; ydk::YList bundle_data; }; // BundleInformation::MlacpBrief::MlacpBriefIccpGroups::MlacpBriefIccpGroup::MlacpBriefIccpGroupItem class BundleInformation::MlacpBrief::MlacpBriefIccpGroups::MlacpBriefIccpGroup::MlacpBriefIccpGroupItem::IccpGroupData : public ydk::Entity { public: IccpGroupData(); ~IccpGroupData(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf iccp_group_id; //type: uint32 ydk::YLeaf singleton; //type: boolean ydk::YLeaf connect_timer_running; //type: uint64 class NodeData; //type: BundleInformation::MlacpBrief::MlacpBriefIccpGroups::MlacpBriefIccpGroup::MlacpBriefIccpGroupItem::IccpGroupData::NodeData ydk::YList node_data; }; // BundleInformation::MlacpBrief::MlacpBriefIccpGroups::MlacpBriefIccpGroup::MlacpBriefIccpGroupItem::IccpGroupData class BundleInformation::MlacpBrief::MlacpBriefIccpGroups::MlacpBriefIccpGroup::MlacpBriefIccpGroupItem::IccpGroupData::NodeData : public ydk::Entity { public: NodeData(); ~NodeData(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf mlacp_node_id; //type: uint8 ydk::YLeaf ldp_id; //type: string ydk::YLeaf version_number; //type: uint32 ydk::YLeaf node_state; //type: BmdMlacpNodeStateEnum ydk::YLeaf iccp_group_state; //type: BmdMlacpNodeSyncEnum class SystemId; //type: BundleInformation::MlacpBrief::MlacpBriefIccpGroups::MlacpBriefIccpGroup::MlacpBriefIccpGroupItem::IccpGroupData::NodeData::SystemId std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBrief::MlacpBriefIccpGroups::MlacpBriefIccpGroup::MlacpBriefIccpGroupItem::IccpGroupData::NodeData::SystemId> system_id; }; // BundleInformation::MlacpBrief::MlacpBriefIccpGroups::MlacpBriefIccpGroup::MlacpBriefIccpGroupItem::IccpGroupData::NodeData class BundleInformation::MlacpBrief::MlacpBriefIccpGroups::MlacpBriefIccpGroup::MlacpBriefIccpGroupItem::IccpGroupData::NodeData::SystemId : public ydk::Entity { public: SystemId(); ~SystemId(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf system_prio; //type: uint16 class SystemMacAddr; //type: BundleInformation::MlacpBrief::MlacpBriefIccpGroups::MlacpBriefIccpGroup::MlacpBriefIccpGroupItem::IccpGroupData::NodeData::SystemId::SystemMacAddr std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBrief::MlacpBriefIccpGroups::MlacpBriefIccpGroup::MlacpBriefIccpGroupItem::IccpGroupData::NodeData::SystemId::SystemMacAddr> system_mac_addr; }; // BundleInformation::MlacpBrief::MlacpBriefIccpGroups::MlacpBriefIccpGroup::MlacpBriefIccpGroupItem::IccpGroupData::NodeData::SystemId class BundleInformation::MlacpBrief::MlacpBriefIccpGroups::MlacpBriefIccpGroup::MlacpBriefIccpGroupItem::IccpGroupData::NodeData::SystemId::SystemMacAddr : public ydk::Entity { public: SystemMacAddr(); ~SystemMacAddr(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf macaddr; //type: string }; // BundleInformation::MlacpBrief::MlacpBriefIccpGroups::MlacpBriefIccpGroup::MlacpBriefIccpGroupItem::IccpGroupData::NodeData::SystemId::SystemMacAddr class BundleInformation::MlacpBrief::MlacpBriefIccpGroups::MlacpBriefIccpGroup::MlacpBriefIccpGroupItem::BundleData : public ydk::Entity { public: BundleData(); ~BundleData(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf bundle_interface_key; //type: uint16 ydk::YLeaf media_type; //type: BundleMedia ydk::YLeaf redundancy_object_id; //type: uint64 class MlacpBundleData; //type: BundleInformation::MlacpBrief::MlacpBriefIccpGroups::MlacpBriefIccpGroup::MlacpBriefIccpGroupItem::BundleData::MlacpBundleData class MlacpMemberData; //type: BundleInformation::MlacpBrief::MlacpBriefIccpGroups::MlacpBriefIccpGroup::MlacpBriefIccpGroupItem::BundleData::MlacpMemberData ydk::YList mlacp_bundle_data; ydk::YList mlacp_member_data; }; // BundleInformation::MlacpBrief::MlacpBriefIccpGroups::MlacpBriefIccpGroup::MlacpBriefIccpGroupItem::BundleData class BundleInformation::MlacpBrief::MlacpBriefIccpGroups::MlacpBriefIccpGroup::MlacpBriefIccpGroupItem::BundleData::MlacpBundleData : public ydk::Entity { public: MlacpBundleData(); ~MlacpBundleData(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf bundle_name; //type: string ydk::YLeaf mlacp_node_id; //type: uint8 ydk::YLeaf aggregator_id; //type: uint16 ydk::YLeaf bundle_state; //type: BmdMlacpBdlStateEnum ydk::YLeaf port_priority; //type: uint16 class MacAddress; //type: BundleInformation::MlacpBrief::MlacpBriefIccpGroups::MlacpBriefIccpGroup::MlacpBriefIccpGroupItem::BundleData::MlacpBundleData::MacAddress std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::MlacpBrief::MlacpBriefIccpGroups::MlacpBriefIccpGroup::MlacpBriefIccpGroupItem::BundleData::MlacpBundleData::MacAddress> mac_address; }; // BundleInformation::MlacpBrief::MlacpBriefIccpGroups::MlacpBriefIccpGroup::MlacpBriefIccpGroupItem::BundleData::MlacpBundleData class BundleInformation::MlacpBrief::MlacpBriefIccpGroups::MlacpBriefIccpGroup::MlacpBriefIccpGroupItem::BundleData::MlacpBundleData::MacAddress : public ydk::Entity { public: MacAddress(); ~MacAddress(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf address; //type: string }; // BundleInformation::MlacpBrief::MlacpBriefIccpGroups::MlacpBriefIccpGroup::MlacpBriefIccpGroupItem::BundleData::MlacpBundleData::MacAddress class BundleInformation::MlacpBrief::MlacpBriefIccpGroups::MlacpBriefIccpGroup::MlacpBriefIccpGroupItem::BundleData::MlacpMemberData : public ydk::Entity { public: MlacpMemberData(); ~MlacpMemberData(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf port_name; //type: string ydk::YLeaf interface_handle; //type: string ydk::YLeaf mlacp_node_id; //type: uint8 ydk::YLeaf port_number; //type: uint16 ydk::YLeaf operational_priority; //type: uint16 ydk::YLeaf configured_priority; //type: uint16 ydk::YLeaf member_state; //type: BmdMlacpMbrStateEnum }; // BundleInformation::MlacpBrief::MlacpBriefIccpGroups::MlacpBriefIccpGroup::MlacpBriefIccpGroupItem::BundleData::MlacpMemberData class BundleInformation::Mlacp : public ydk::Entity { public: Mlacp(); ~Mlacp(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class MlacpBundles; //type: BundleInformation::Mlacp::MlacpBundles class MlacpIccpGroups; //type: BundleInformation::Mlacp::MlacpIccpGroups std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::Mlacp::MlacpBundles> mlacp_bundles; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::Mlacp::MlacpIccpGroups> mlacp_iccp_groups; }; // BundleInformation::Mlacp class BundleInformation::Mlacp::MlacpBundles : public ydk::Entity { public: MlacpBundles(); ~MlacpBundles(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class MlacpBundle; //type: BundleInformation::Mlacp::MlacpBundles::MlacpBundle ydk::YList mlacp_bundle; }; // BundleInformation::Mlacp::MlacpBundles class BundleInformation::Mlacp::MlacpBundles::MlacpBundle : public ydk::Entity { public: MlacpBundle(); ~MlacpBundle(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf bundle_interface; //type: string class MlacpBundleItem; //type: BundleInformation::Mlacp::MlacpBundles::MlacpBundle::MlacpBundleItem std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::Mlacp::MlacpBundles::MlacpBundle::MlacpBundleItem> mlacp_bundle_item; }; // BundleInformation::Mlacp::MlacpBundles::MlacpBundle class BundleInformation::Mlacp::MlacpBundles::MlacpBundle::MlacpBundleItem : public ydk::Entity { public: MlacpBundleItem(); ~MlacpBundleItem(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class MlacpData; //type: BundleInformation::Mlacp::MlacpBundles::MlacpBundle::MlacpBundleItem::MlacpData ydk::YList mlacp_data; }; // BundleInformation::Mlacp::MlacpBundles::MlacpBundle::MlacpBundleItem class BundleInformation::Mlacp::MlacpBundles::MlacpBundle::MlacpBundleItem::MlacpData : public ydk::Entity { public: MlacpData(); ~MlacpData(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class IccpGroupData; //type: BundleInformation::Mlacp::MlacpBundles::MlacpBundle::MlacpBundleItem::MlacpData::IccpGroupData class BundleData; //type: BundleInformation::Mlacp::MlacpBundles::MlacpBundle::MlacpBundleItem::MlacpData::BundleData std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::Mlacp::MlacpBundles::MlacpBundle::MlacpBundleItem::MlacpData::IccpGroupData> iccp_group_data; ydk::YList bundle_data; }; // BundleInformation::Mlacp::MlacpBundles::MlacpBundle::MlacpBundleItem::MlacpData class BundleInformation::Mlacp::MlacpBundles::MlacpBundle::MlacpBundleItem::MlacpData::IccpGroupData : public ydk::Entity { public: IccpGroupData(); ~IccpGroupData(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf iccp_group_id; //type: uint32 ydk::YLeaf singleton; //type: boolean ydk::YLeaf connect_timer_running; //type: uint64 class NodeData; //type: BundleInformation::Mlacp::MlacpBundles::MlacpBundle::MlacpBundleItem::MlacpData::IccpGroupData::NodeData ydk::YList node_data; }; // BundleInformation::Mlacp::MlacpBundles::MlacpBundle::MlacpBundleItem::MlacpData::IccpGroupData class BundleInformation::Mlacp::MlacpBundles::MlacpBundle::MlacpBundleItem::MlacpData::IccpGroupData::NodeData : public ydk::Entity { public: NodeData(); ~NodeData(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf mlacp_node_id; //type: uint8 ydk::YLeaf ldp_id; //type: string ydk::YLeaf version_number; //type: uint32 ydk::YLeaf node_state; //type: BmdMlacpNodeStateEnum ydk::YLeaf iccp_group_state; //type: BmdMlacpNodeSyncEnum class SystemId; //type: BundleInformation::Mlacp::MlacpBundles::MlacpBundle::MlacpBundleItem::MlacpData::IccpGroupData::NodeData::SystemId std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::Mlacp::MlacpBundles::MlacpBundle::MlacpBundleItem::MlacpData::IccpGroupData::NodeData::SystemId> system_id; }; // BundleInformation::Mlacp::MlacpBundles::MlacpBundle::MlacpBundleItem::MlacpData::IccpGroupData::NodeData class BundleInformation::Mlacp::MlacpBundles::MlacpBundle::MlacpBundleItem::MlacpData::IccpGroupData::NodeData::SystemId : public ydk::Entity { public: SystemId(); ~SystemId(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf system_prio; //type: uint16 class SystemMacAddr; //type: BundleInformation::Mlacp::MlacpBundles::MlacpBundle::MlacpBundleItem::MlacpData::IccpGroupData::NodeData::SystemId::SystemMacAddr std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::Mlacp::MlacpBundles::MlacpBundle::MlacpBundleItem::MlacpData::IccpGroupData::NodeData::SystemId::SystemMacAddr> system_mac_addr; }; // BundleInformation::Mlacp::MlacpBundles::MlacpBundle::MlacpBundleItem::MlacpData::IccpGroupData::NodeData::SystemId class BundleInformation::Mlacp::MlacpBundles::MlacpBundle::MlacpBundleItem::MlacpData::IccpGroupData::NodeData::SystemId::SystemMacAddr : public ydk::Entity { public: SystemMacAddr(); ~SystemMacAddr(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf macaddr; //type: string }; // BundleInformation::Mlacp::MlacpBundles::MlacpBundle::MlacpBundleItem::MlacpData::IccpGroupData::NodeData::SystemId::SystemMacAddr class BundleInformation::Mlacp::MlacpBundles::MlacpBundle::MlacpBundleItem::MlacpData::BundleData : public ydk::Entity { public: BundleData(); ~BundleData(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf bundle_interface_key; //type: uint16 ydk::YLeaf media_type; //type: BundleMedia ydk::YLeaf redundancy_object_id; //type: uint64 class MlacpBundleData; //type: BundleInformation::Mlacp::MlacpBundles::MlacpBundle::MlacpBundleItem::MlacpData::BundleData::MlacpBundleData class MlacpMemberData; //type: BundleInformation::Mlacp::MlacpBundles::MlacpBundle::MlacpBundleItem::MlacpData::BundleData::MlacpMemberData ydk::YList mlacp_bundle_data; ydk::YList mlacp_member_data; }; // BundleInformation::Mlacp::MlacpBundles::MlacpBundle::MlacpBundleItem::MlacpData::BundleData class BundleInformation::Mlacp::MlacpBundles::MlacpBundle::MlacpBundleItem::MlacpData::BundleData::MlacpBundleData : public ydk::Entity { public: MlacpBundleData(); ~MlacpBundleData(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf bundle_name; //type: string ydk::YLeaf mlacp_node_id; //type: uint8 ydk::YLeaf aggregator_id; //type: uint16 ydk::YLeaf bundle_state; //type: BmdMlacpBdlStateEnum ydk::YLeaf port_priority; //type: uint16 class MacAddress; //type: BundleInformation::Mlacp::MlacpBundles::MlacpBundle::MlacpBundleItem::MlacpData::BundleData::MlacpBundleData::MacAddress std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_bundlemgr_oper::BundleInformation::Mlacp::MlacpBundles::MlacpBundle::MlacpBundleItem::MlacpData::BundleData::MlacpBundleData::MacAddress> mac_address; }; // BundleInformation::Mlacp::MlacpBundles::MlacpBundle::MlacpBundleItem::MlacpData::BundleData::MlacpBundleData class BundleInformation::Mlacp::MlacpBundles::MlacpBundle::MlacpBundleItem::MlacpData::BundleData::MlacpBundleData::MacAddress : public ydk::Entity { public: MacAddress(); ~MacAddress(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf address; //type: string }; // BundleInformation::Mlacp::MlacpBundles::MlacpBundle::MlacpBundleItem::MlacpData::BundleData::MlacpBundleData::MacAddress class BundleInformation::Mlacp::MlacpBundles::MlacpBundle::MlacpBundleItem::MlacpData::BundleData::MlacpMemberData : public ydk::Entity { public: MlacpMemberData(); ~MlacpMemberData(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf port_name; //type: string ydk::YLeaf interface_handle; //type: string ydk::YLeaf mlacp_node_id; //type: uint8 ydk::YLeaf port_number; //type: uint16 ydk::YLeaf operational_priority; //type: uint16 ydk::YLeaf configured_priority; //type: uint16 ydk::YLeaf member_state; //type: BmdMlacpMbrStateEnum }; // BundleInformation::Mlacp::MlacpBundles::MlacpBundle::MlacpBundleItem::MlacpData::BundleData::MlacpMemberData class BundleInformation::Mlacp::MlacpIccpGroups : public ydk::Entity { public: MlacpIccpGroups(); ~MlacpIccpGroups(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class MlacpIccpGroup; //type: BundleInformation::Mlacp::MlacpIccpGroups::MlacpIccpGroup ydk::YList mlacp_iccp_group; }; // BundleInformation::Mlacp::MlacpIccpGroups } } #endif /* _CISCO_IOS_XR_BUNDLEMGR_OPER_1_ */
60.334651
251
0.729349
[ "vector" ]
5d33fc6af64bbfe0a831717310ac1ec757245e77
37,860
cpp
C++
aegisub/src/audio_display.cpp
rcombs/Aegisub
58f35cd31c7f0f5728e0a28e6a7a9fd6fce70c50
[ "ISC" ]
1
2018-02-12T02:44:57.000Z
2018-02-12T02:44:57.000Z
aegisub/src/audio_display.cpp
rcombs/Aegisub
58f35cd31c7f0f5728e0a28e6a7a9fd6fce70c50
[ "ISC" ]
null
null
null
aegisub/src/audio_display.cpp
rcombs/Aegisub
58f35cd31c7f0f5728e0a28e6a7a9fd6fce70c50
[ "ISC" ]
2
2018-02-12T03:46:24.000Z
2018-02-12T14:36:07.000Z
// Copyright (c) 2005, Rodrigo Braz Monteiro // Copyright (c) 2009-2010, Niels Martin Hansen // 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 Aegisub Group 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. // // Aegisub Project http://www.aegisub.org/ /// @file audio_display.cpp /// @brief Display audio in the main UI /// @ingroup audio_ui /// #include "config.h" #include "audio_display.h" #include "ass_time.h" #include "audio_colorscheme.h" #include "audio_controller.h" #include "audio_renderer.h" #include "audio_renderer_spectrum.h" #include "audio_renderer_waveform.h" #include "audio_timing.h" #include "block_cache.h" #include "compat.h" #include "include/aegisub/context.h" #include "include/aegisub/hotkey.h" #include "options.h" #include "selection_controller.h" #include "utils.h" #include "video_context.h" #include <libaegisub/util.h> #include <algorithm> #include <wx/dcbuffer.h> #include <wx/dcclient.h> #include <wx/mousestate.h> /// @brief Colourscheme-based UI colour provider /// /// This class provides UI colours corresponding to the supplied audio colour /// scheme. /// /// SetColourScheme must be called to set the active colour scheme before /// colours can be retrieved class UIColours { wxColour light_colour; ///< Light unfocused colour from the colour scheme wxColour dark_colour; ///< Dark unfocused colour from the colour scheme wxColour sel_colour; ///< Selection unfocused colour from the colour scheme wxColour light_focused_colour; ///< Light focused colour from the colour scheme wxColour dark_focused_colour; ///< Dark focused colour from the colour scheme wxColour sel_focused_colour; ///< Selection focused colour from the colour scheme bool focused; ///< Use the focused colours? public: /// Constructor UIColours() : focused(false) { } /// Set the colour scheme to load colours from /// @param name Name of the colour scheme void SetColourScheme(std::string const& name) { std::string opt_prefix = "Colour/Schemes/" + name + "/UI/"; light_colour = to_wx(OPT_GET(opt_prefix + "Light")->GetColor()); dark_colour = to_wx(OPT_GET(opt_prefix + "Dark")->GetColor()); sel_colour = to_wx(OPT_GET(opt_prefix + "Selection")->GetColor()); opt_prefix = "Colour/Schemes/" + name + "/UI Focused/"; light_focused_colour = to_wx(OPT_GET(opt_prefix + "Light")->GetColor()); dark_focused_colour = to_wx(OPT_GET(opt_prefix + "Dark")->GetColor()); sel_focused_colour = to_wx(OPT_GET(opt_prefix + "Selection")->GetColor()); } /// Set whether to use the focused or unfocused colours /// @param focused If true, focused colours will be returned void SetFocused(bool focused) { this->focused = focused; } /// Get the current Light colour wxColour Light() const { return focused ? light_focused_colour : light_colour; } /// Get the current Dark colour wxColour Dark() const { return focused ? dark_focused_colour : dark_colour; } /// Get the current Selection colour wxColour Selection() const { return focused ? sel_focused_colour : sel_colour; } }; class AudioDisplayScrollbar : public AudioDisplayInteractionObject { static const int height = 15; static const int min_width = 10; wxRect bounds; wxRect thumb; bool dragging; ///< user is dragging with the primary mouse button int data_length; ///< total amount of data in control int page_length; ///< amount of data in one page int position; ///< first item displayed int sel_start; ///< first data item in selection int sel_length; ///< number of data items in selection UIColours colours; ///< Colour provider /// Containing display to send scroll events to AudioDisplay *display; // Recalculate thumb bounds from position and length data void RecalculateThumb() { thumb.width = std::max<int>(min_width, (int64_t)bounds.width * page_length / data_length); thumb.height = height; thumb.x = int((int64_t)bounds.width * position / data_length); thumb.y = bounds.y; } public: AudioDisplayScrollbar(AudioDisplay *display) : dragging(false) , data_length(1) , page_length(1) , position(0) , sel_start(-1) , sel_length(0) , display(display) { } /// The audio display has changed size void SetDisplaySize(const wxSize &display_size) { bounds.x = 0; bounds.y = display_size.y - height; bounds.width = display_size.x; bounds.height = height; page_length = display_size.x; RecalculateThumb(); } void SetColourScheme(std::string const& name) { colours.SetColourScheme(name); } const wxRect & GetBounds() const { return bounds; } int GetPosition() const { return position; } int SetPosition(int new_position) { // These two conditionals can't be swapped, otherwise the position can become // negative if the entire data is shorter than one page. if (new_position + page_length >= data_length) new_position = data_length - page_length - 1; if (new_position < 0) new_position = 0; position = new_position; RecalculateThumb(); return position; } void SetSelection(int new_start, int new_length) { sel_start = (int64_t)new_start * bounds.width / data_length; sel_length = (int64_t)new_length * bounds.width / data_length; } void ChangeLengths(int new_data_length, int new_page_length) { data_length = new_data_length; page_length = new_page_length; RecalculateThumb(); } bool OnMouseEvent(wxMouseEvent &event) override { if (event.LeftIsDown()) { const int thumb_left = event.GetPosition().x - thumb.width/2; const int data_length_less_page = data_length - page_length; const int shaft_length_less_thumb = bounds.width - thumb.width; display->ScrollPixelToLeft((int64_t)data_length_less_page * thumb_left / shaft_length_less_thumb); dragging = true; } else if (event.LeftUp()) { dragging = false; } return dragging; } void Paint(wxDC &dc, bool has_focus) { colours.SetFocused(has_focus); dc.SetPen(wxPen(colours.Light())); dc.SetBrush(wxBrush(colours.Dark())); dc.DrawRectangle(bounds); if (sel_length > 0 && sel_start >= 0) { dc.SetPen(wxPen(colours.Selection())); dc.SetBrush(wxBrush(colours.Selection())); dc.DrawRectangle(wxRect(sel_start, bounds.y, sel_length, bounds.height)); } dc.SetPen(wxPen(colours.Light())); dc.SetBrush(*wxTRANSPARENT_BRUSH); dc.DrawRectangle(bounds); dc.SetPen(wxPen(colours.Light())); dc.SetBrush(wxBrush(colours.Light())); dc.DrawRectangle(thumb); } }; const int AudioDisplayScrollbar::min_width; class AudioDisplayTimeline : public AudioDisplayInteractionObject { int duration; ///< Total duration in ms double ms_per_pixel; ///< Milliseconds per pixel int pixel_left; ///< Leftmost visible pixel (i.e. scroll position) wxRect bounds; wxPoint drag_lastpos; bool dragging; enum Scale { Sc_Millisecond, Sc_Centisecond, Sc_Decisecond, Sc_Second, Sc_Decasecond, Sc_Minute, Sc_Decaminute, Sc_Hour, Sc_Decahour, // If anyone needs this they should reconsider their project Sc_MAX = Sc_Decahour }; Scale scale_minor; int scale_major_modulo; ///< If minor_scale_mark_index % scale_major_modulo == 0 the mark is a major mark double scale_minor_divisor; ///< Absolute scale-mark index multiplied by this number gives sample index for scale mark AudioDisplay *display; ///< Containing audio display UIColours colours; ///< Colour provider public: AudioDisplayTimeline(AudioDisplay *display) : duration(0) , ms_per_pixel(1.0) , pixel_left(0) , dragging(false) , display(display) { int width, height; display->GetTextExtent("0123456789:.", &width, &height); bounds.height = height + 4; } void SetColourScheme(std::string const& name) { colours.SetColourScheme(name); } void SetDisplaySize(const wxSize &display_size) { // The size is without anything that goes below the timeline (like scrollbar) bounds.width = display_size.x; bounds.x = 0; bounds.y = 0; } int GetHeight() const { return bounds.height; } const wxRect & GetBounds() const { return bounds; } void ChangeAudio(int new_duration) { duration = new_duration; } void ChangeZoom(double new_ms_per_pixel) { ms_per_pixel = new_ms_per_pixel; double px_sec = 1000.0 / ms_per_pixel; if (px_sec > 3000) { scale_minor = Sc_Millisecond; scale_minor_divisor = 1.0; scale_major_modulo = 10; } else if (px_sec > 300) { scale_minor = Sc_Centisecond; scale_minor_divisor = 10.0; scale_major_modulo = 10; } else if (px_sec > 30) { scale_minor = Sc_Decisecond; scale_minor_divisor = 100.0; scale_major_modulo = 10; } else if (px_sec > 3) { scale_minor = Sc_Second; scale_minor_divisor = 1000.0; scale_major_modulo = 10; } else if (px_sec > 1.0/3.0) { scale_minor = Sc_Decasecond; scale_minor_divisor = 10000.0; scale_major_modulo = 6; } else if (px_sec > 1.0/9.0) { scale_minor = Sc_Minute; scale_minor_divisor = 60000.0; scale_major_modulo = 10; } else if (px_sec > 1.0/90.0) { scale_minor = Sc_Decaminute; scale_minor_divisor = 600000.0; scale_major_modulo = 6; } else { scale_minor = Sc_Hour; scale_minor_divisor = 3600000.0; scale_major_modulo = 10; } } void SetPosition(int new_pixel_left) { pixel_left = std::max(new_pixel_left, 0); } bool OnMouseEvent(wxMouseEvent &event) override { if (event.LeftDown()) { drag_lastpos = event.GetPosition(); dragging = true; } else if (event.LeftIsDown()) { display->ScrollPixelToLeft(pixel_left - event.GetPosition().x + drag_lastpos.x); drag_lastpos = event.GetPosition(); dragging = true; } else if (event.LeftUp()) { dragging = false; } return dragging; } void Paint(wxDC &dc) { int bottom = bounds.y + bounds.height; // Background dc.SetPen(wxPen(colours.Dark())); dc.SetBrush(wxBrush(colours.Dark())); dc.DrawRectangle(bounds); // Top line dc.SetPen(wxPen(colours.Light())); dc.DrawLine(bounds.x, bottom-1, bounds.x+bounds.width, bottom-1); // Prepare for writing text dc.SetTextBackground(colours.Dark()); dc.SetTextForeground(colours.Light()); // Figure out the first scale mark to show int ms_left = int(pixel_left * ms_per_pixel); int next_scale_mark = int(ms_left / scale_minor_divisor); if (next_scale_mark * scale_minor_divisor < ms_left) next_scale_mark += 1; assert(next_scale_mark * scale_minor_divisor >= ms_left); // Draw scale marks int next_scale_mark_pos; int last_text_right = -1; int last_hour = -1, last_minute = -1; if (duration < 3600) last_hour = 0; // Trick to only show hours if audio is longer than 1 hour do { next_scale_mark_pos = int(next_scale_mark * scale_minor_divisor / ms_per_pixel) - pixel_left; bool mark_is_major = next_scale_mark % scale_major_modulo == 0; if (mark_is_major) dc.DrawLine(next_scale_mark_pos, bottom-6, next_scale_mark_pos, bottom-1); else dc.DrawLine(next_scale_mark_pos, bottom-4, next_scale_mark_pos, bottom-1); // Print time labels on major scale marks if (mark_is_major && next_scale_mark_pos > last_text_right) { double mark_time = next_scale_mark * scale_minor_divisor / 1000.0; int mark_hour = (int)(mark_time / 3600); int mark_minute = (int)(mark_time / 60) % 60; double mark_second = mark_time - mark_hour*3600.0 - mark_minute*60.0; wxString time_string; bool changed_hour = mark_hour != last_hour; bool changed_minute = mark_minute != last_minute; if (changed_hour) { time_string = wxString::Format("%d:%02d:", mark_hour, mark_minute); last_hour = mark_hour; last_minute = mark_minute; } else if (changed_minute) { time_string = wxString::Format("%d:", mark_minute); last_minute = mark_minute; } if (scale_minor >= Sc_Decisecond) time_string += wxString::Format("%02d", (int)mark_second); else if (scale_minor == Sc_Centisecond) time_string += wxString::Format("%02.1f", mark_second); else time_string += wxString::Format("%02.2f", mark_second); int tw, th; dc.GetTextExtent(time_string, &tw, &th); last_text_right = next_scale_mark_pos + tw; dc.DrawText(time_string, next_scale_mark_pos, 0); } next_scale_mark += 1; } while (next_scale_mark_pos < bounds.width); } }; class AudioMarkerInteractionObject : public AudioDisplayInteractionObject { // Object-pair being interacted with std::vector<AudioMarker*> markers; AudioTimingController *timing_controller; // Audio display drag is happening on AudioDisplay *display; // Mouse button used to initiate the drag wxMouseButton button_used; // Default to snapping to snappable markers bool default_snap; // Range in pixels to snap at int snap_range; public: AudioMarkerInteractionObject(std::vector<AudioMarker*> markers, AudioTimingController *timing_controller, AudioDisplay *display, wxMouseButton button_used) : markers(std::move(markers)) , timing_controller(timing_controller) , display(display) , button_used(button_used) , default_snap(OPT_GET("Audio/Snap/Enable")->GetBool()) , snap_range(OPT_GET("Audio/Snap/Distance")->GetInt()) { } bool OnMouseEvent(wxMouseEvent &event) override { if (event.Dragging()) { timing_controller->OnMarkerDrag( markers, display->TimeFromRelativeX(event.GetPosition().x), default_snap != event.ShiftDown() ? display->TimeFromAbsoluteX(snap_range) : 0); } // We lose the marker drag if the button used to initiate it goes up return !event.ButtonUp(button_used); } /// Get the position in milliseconds of this group of markers int GetPosition() const { return markers.front()->GetPosition(); } }; class AudioStyleRangeMerger : public AudioRenderingStyleRanges { typedef std::map<int, AudioRenderingStyle> style_map; public: typedef style_map::iterator iterator; private: style_map points; void Split(int point) { auto it = points.lower_bound(point); if (it == points.end() || it->first != point) { assert(it != points.begin()); points[point] = (--it)->second; } } void Restyle(int start, int end, AudioRenderingStyle style) { assert(points.lower_bound(end) != points.end()); for (auto pt = points.lower_bound(start); pt->first < end; ++pt) { if (style > pt->second) pt->second = style; } } public: AudioStyleRangeMerger() { points[0] = AudioStyle_Normal; } void AddRange(int start, int end, AudioRenderingStyle style) override { if (start < 0) start = 0; if (end < start) return; Split(start); Split(end); Restyle(start, end, style); } iterator begin() { return points.begin(); } iterator end() { return points.end(); } }; AudioDisplay::AudioDisplay(wxWindow *parent, AudioController *controller, agi::Context *context) : wxWindow(parent, -1, wxDefaultPosition, wxDefaultSize, wxWANTS_CHARS|wxBORDER_SIMPLE) , audio_open_connection(controller->AddAudioOpenListener(&AudioDisplay::OnAudioOpen, this)) , context(context) , audio_renderer(agi::util::make_unique<AudioRenderer>()) , controller(controller) , scrollbar(agi::util::make_unique<AudioDisplayScrollbar>(this)) , timeline(agi::util::make_unique<AudioDisplayTimeline>(this)) { style_ranges[0] = AudioStyle_Normal; audio_renderer->SetAmplitudeScale(scale_amplitude); SetZoomLevel(0); SetMinClientSize(wxSize(-1, 70)); SetBackgroundStyle(wxBG_STYLE_PAINT); SetThemeEnabled(false); Bind(wxEVT_LEFT_DOWN, &AudioDisplay::OnMouseEvent, this); Bind(wxEVT_MIDDLE_DOWN, &AudioDisplay::OnMouseEvent, this); Bind(wxEVT_RIGHT_DOWN, &AudioDisplay::OnMouseEvent, this); Bind(wxEVT_LEFT_UP, &AudioDisplay::OnMouseEvent, this); Bind(wxEVT_MIDDLE_UP, &AudioDisplay::OnMouseEvent, this); Bind(wxEVT_RIGHT_UP, &AudioDisplay::OnMouseEvent, this); Bind(wxEVT_MOTION, &AudioDisplay::OnMouseEvent, this); Bind(wxEVT_ENTER_WINDOW, &AudioDisplay::OnMouseEnter, this); Bind(wxEVT_LEAVE_WINDOW, &AudioDisplay::OnMouseLeave, this); Bind(wxEVT_PAINT, &AudioDisplay::OnPaint, this); Bind(wxEVT_SIZE, &AudioDisplay::OnSize, this); Bind(wxEVT_KILL_FOCUS, &AudioDisplay::OnFocus, this); Bind(wxEVT_SET_FOCUS, &AudioDisplay::OnFocus, this); Bind(wxEVT_CHAR_HOOK, &AudioDisplay::OnKeyDown, this); Bind(wxEVT_KEY_DOWN, &AudioDisplay::OnKeyDown, this); scroll_timer.Bind(wxEVT_TIMER, &AudioDisplay::OnScrollTimer, this); } AudioDisplay::~AudioDisplay() { } void AudioDisplay::ScrollBy(int pixel_amount) { ScrollPixelToLeft(scroll_left + pixel_amount); } void AudioDisplay::ScrollPixelToLeft(int pixel_position) { const int client_width = GetClientRect().GetWidth(); if (pixel_position + client_width >= pixel_audio_width) pixel_position = pixel_audio_width - client_width; if (pixel_position < 0) pixel_position = 0; scroll_left = pixel_position; scrollbar->SetPosition(scroll_left); timeline->SetPosition(scroll_left); Refresh(); } void AudioDisplay::ScrollTimeRangeInView(const TimeRange &range) { int client_width = GetClientRect().GetWidth(); int range_begin = AbsoluteXFromTime(range.begin()); int range_end = AbsoluteXFromTime(range.end()); int range_len = range_end - range_begin; // Remove 5 % from each side of the client area. int leftadjust = client_width / 20; int client_left = scroll_left + leftadjust; client_width = client_width * 9 / 10; // Is everything already in view? if (range_begin >= client_left && range_end <= client_left+client_width) return; // The entire range can fit inside the view, center it if (range_len < client_width) { ScrollPixelToLeft(range_begin - (client_width-range_len)/2 - leftadjust); } // Range doesn't fit in view and we're viewing a middle part of it, just leave it alone else if (range_begin < client_left && range_end > client_left+client_width) { // nothing } // Right edge is in view, scroll it as far to the right as possible else if (range_end >= client_left && range_end < client_left+client_width) { ScrollPixelToLeft(range_end - client_width - leftadjust); } // Nothing is in view or the left edge is in view, scroll left edge as far to the left as possible else { ScrollPixelToLeft(range_begin - leftadjust); } } void AudioDisplay::SetZoomLevel(int new_zoom_level) { zoom_level = new_zoom_level; const int factor = GetZoomLevelFactor(zoom_level); const int base_pixels_per_second = 50; /// @todo Make this customisable const double base_ms_per_pixel = 1000.0 / base_pixels_per_second; const double new_ms_per_pixel = 100.0 * base_ms_per_pixel / factor; if (ms_per_pixel == new_ms_per_pixel) return; int client_width = GetClientSize().GetWidth(); double cursor_pos = track_cursor_pos >= 0 ? track_cursor_pos - scroll_left : client_width / 2.0; double cursor_time = (scroll_left + cursor_pos) * ms_per_pixel; ms_per_pixel = new_ms_per_pixel; pixel_audio_width = std::max(1, int(controller->GetDuration() / ms_per_pixel)); audio_renderer->SetMillisecondsPerPixel(ms_per_pixel); scrollbar->ChangeLengths(pixel_audio_width, client_width); timeline->ChangeZoom(ms_per_pixel); ScrollPixelToLeft(AbsoluteXFromTime(cursor_time) - cursor_pos); if (track_cursor_pos >= 0) track_cursor_pos = AbsoluteXFromTime(cursor_time); Refresh(); } wxString AudioDisplay::GetZoomLevelDescription(int level) const { const int factor = GetZoomLevelFactor(level); const int base_pixels_per_second = 50; /// @todo Make this customisable along with the above const int second_pixels = 100 * base_pixels_per_second / factor; return wxString::Format(_("%d%%, %d pixel/second"), factor, second_pixels); } int AudioDisplay::GetZoomLevelFactor(int level) { int factor = 100; if (level > 0) { factor += 25 * level; } else if (level < 0) { if (level >= -5) factor += 10 * level; else if (level >= -11) factor = 50 + (level+5) * 5; else factor = 20 + level + 11; if (factor <= 0) factor = 1; } return factor; } void AudioDisplay::SetAmplitudeScale(float scale) { audio_renderer->SetAmplitudeScale(scale); Refresh(); } void AudioDisplay::ReloadRenderingSettings() { std::string colour_scheme_name; if (OPT_GET("Audio/Spectrum")->GetBool()) { colour_scheme_name = OPT_GET("Colour/Audio Display/Spectrum")->GetString(); auto audio_spectrum_renderer = agi::util::make_unique<AudioSpectrumRenderer>(colour_scheme_name); int64_t spectrum_quality = OPT_GET("Audio/Renderer/Spectrum/Quality")->GetInt(); #ifdef WITH_FFTW3 // FFTW is so fast we can afford to upgrade quality by two levels spectrum_quality += 2; #endif spectrum_quality = mid<int64_t>(0, spectrum_quality, 5); // Quality indexes: 0 1 2 3 4 5 int spectrum_width[] = {8, 9, 9, 9, 10, 11}; int spectrum_distance[] = {8, 8, 7, 6, 6, 5}; audio_spectrum_renderer->SetResolution( spectrum_width[spectrum_quality], spectrum_distance[spectrum_quality]); audio_renderer_provider = std::move(audio_spectrum_renderer); } else { colour_scheme_name = OPT_GET("Colour/Audio Display/Waveform")->GetString(); audio_renderer_provider = agi::util::make_unique<AudioWaveformRenderer>(colour_scheme_name); } audio_renderer->SetRenderer(audio_renderer_provider.get()); scrollbar->SetColourScheme(colour_scheme_name); timeline->SetColourScheme(colour_scheme_name); Refresh(); } void AudioDisplay::OnPaint(wxPaintEvent&) { if (!audio_renderer_provider) return; wxAutoBufferedPaintDC dc(this); wxRect audio_bounds(0, audio_top, GetClientSize().GetWidth(), audio_height); bool redraw_scrollbar = false; bool redraw_timeline = false; for (wxRegionIterator region(GetUpdateRegion()); region; ++region) { wxRect updrect = region.GetRect(); redraw_scrollbar |= scrollbar->GetBounds().Intersects(updrect); redraw_timeline |= timeline->GetBounds().Intersects(updrect); if (audio_bounds.Intersects(updrect)) { TimeRange updtime( std::max(0, TimeFromRelativeX(updrect.x - foot_size)), std::max(0, TimeFromRelativeX(updrect.x + updrect.width + foot_size))); PaintAudio(dc, updtime, updrect); PaintMarkers(dc, updtime); PaintLabels(dc, updtime); } } if (track_cursor_pos >= 0) PaintTrackCursor(dc); if (redraw_scrollbar) scrollbar->Paint(dc, HasFocus()); if (redraw_timeline) timeline->Paint(dc); } void AudioDisplay::PaintAudio(wxDC &dc, TimeRange updtime, wxRect updrect) { auto pt = style_ranges.upper_bound(updtime.begin()); auto pe = style_ranges.upper_bound(updtime.end()); if (pt != style_ranges.begin()) --pt; while (pt != pe) { AudioRenderingStyle range_style = static_cast<AudioRenderingStyle>(pt->second); int range_x1 = std::max(updrect.x, RelativeXFromTime(pt->first)); int range_x2 = (++pt == pe) ? updrect.x + updrect.width : RelativeXFromTime(pt->first); if (range_x2 > range_x1) { audio_renderer->Render(dc, wxPoint(range_x1, audio_top), range_x1 + scroll_left, range_x2 - range_x1, range_style); } } } void AudioDisplay::PaintMarkers(wxDC &dc, TimeRange updtime) { AudioMarkerVector markers; controller->GetTimingController()->GetMarkers(updtime, markers); if (markers.empty()) return; wxDCPenChanger pen_retainer(dc, wxPen()); wxDCBrushChanger brush_retainer(dc, wxBrush()); for (const auto marker : markers) { int marker_x = RelativeXFromTime(marker->GetPosition()); dc.SetPen(marker->GetStyle()); dc.DrawLine(marker_x, audio_top, marker_x, audio_top+audio_height); if (marker->GetFeet() == AudioMarker::Feet_None) continue; dc.SetBrush(wxBrush(marker->GetStyle().GetColour())); dc.SetPen(*wxTRANSPARENT_PEN); if (marker->GetFeet() & AudioMarker::Feet_Left) PaintFoot(dc, marker_x, -1); if (marker->GetFeet() & AudioMarker::Feet_Right) PaintFoot(dc, marker_x, 1); } } void AudioDisplay::PaintFoot(wxDC &dc, int marker_x, int dir) { wxPoint foot_top[3] = { wxPoint(foot_size * dir, 0), wxPoint(0, 0), wxPoint(0, foot_size) }; wxPoint foot_bot[3] = { wxPoint(foot_size * dir, 0), wxPoint(0, -foot_size), wxPoint(0, 0) }; dc.DrawPolygon(3, foot_top, marker_x, audio_top); dc.DrawPolygon(3, foot_bot, marker_x, audio_top+audio_height); } void AudioDisplay::PaintLabels(wxDC &dc, TimeRange updtime) { std::vector<AudioLabelProvider::AudioLabel> labels; controller->GetTimingController()->GetLabels(updtime, labels); if (labels.empty()) return; wxDCFontChanger fc(dc); wxFont font = dc.GetFont(); font.SetWeight(wxFONTWEIGHT_BOLD); dc.SetFont(font); dc.SetTextForeground(*wxWHITE); for (auto const& label : labels) { wxSize extent = dc.GetTextExtent(label.text); int left = RelativeXFromTime(label.range.begin()); int width = AbsoluteXFromTime(label.range.length()); // If it doesn't fit, truncate if (width < extent.GetWidth()) { dc.SetClippingRegion(left, audio_top + 4, width, extent.GetHeight()); dc.DrawText(label.text, left, audio_top + 4); dc.DestroyClippingRegion(); } // Otherwise center in the range else { dc.DrawText(label.text, left + (width - extent.GetWidth()) / 2, audio_top + 4); } } } void AudioDisplay::PaintTrackCursor(wxDC &dc) { wxDCPenChanger penchanger(dc, wxPen(*wxWHITE)); dc.DrawLine(track_cursor_pos-scroll_left, audio_top, track_cursor_pos-scroll_left, audio_top+audio_height); if (track_cursor_label.empty()) return; wxDCFontChanger fc(dc); wxFont font = dc.GetFont(); wxString face_name = FontFace("Audio/Track Cursor"); if (!face_name.empty()) font.SetFaceName(face_name); font.SetWeight(wxFONTWEIGHT_BOLD); dc.SetFont(font); wxSize label_size(dc.GetTextExtent(track_cursor_label)); wxPoint label_pos(track_cursor_pos - scroll_left - label_size.x/2, audio_top + 2); label_pos.x = mid(2, label_pos.x, GetClientSize().GetWidth() - label_size.x - 2); int old_bg_mode = dc.GetBackgroundMode(); dc.SetBackgroundMode(wxTRANSPARENT); // Draw border dc.SetTextForeground(wxColour(64, 64, 64)); dc.DrawText(track_cursor_label, label_pos.x+1, label_pos.y+1); dc.DrawText(track_cursor_label, label_pos.x+1, label_pos.y-1); dc.DrawText(track_cursor_label, label_pos.x-1, label_pos.y+1); dc.DrawText(track_cursor_label, label_pos.x-1, label_pos.y-1); // Draw fill dc.SetTextForeground(*wxWHITE); dc.DrawText(track_cursor_label, label_pos.x, label_pos.y); dc.SetBackgroundMode(old_bg_mode); label_pos.x -= 2; label_pos.y -= 2; label_size.IncBy(4, 4); // If the rendered text changes size we have to draw it an extra time to make sure the entire thing was drawn bool need_extra_redraw = track_cursor_label_rect.GetSize() != label_size; track_cursor_label_rect.SetPosition(label_pos); track_cursor_label_rect.SetSize(label_size); if (need_extra_redraw) RefreshRect(track_cursor_label_rect, false); } void AudioDisplay::SetDraggedObject(AudioDisplayInteractionObject *new_obj) { dragged_object = new_obj; if (dragged_object && !HasCapture()) CaptureMouse(); else if (!dragged_object && HasCapture()) ReleaseMouse(); if (!dragged_object) audio_marker.reset(); } void AudioDisplay::SetTrackCursor(int new_pos, bool show_time) { if (new_pos == track_cursor_pos) return; int old_pos = track_cursor_pos; track_cursor_pos = new_pos; RefreshRect(wxRect(old_pos - scroll_left - 0, audio_top, 1, audio_height), false); RefreshRect(wxRect(new_pos - scroll_left - 0, audio_top, 1, audio_height), false); // Make sure the old label gets cleared away RefreshRect(track_cursor_label_rect, false); if (show_time) { AssTime new_label_time = TimeFromAbsoluteX(track_cursor_pos); track_cursor_label = to_wx(new_label_time.GetAssFormated()); track_cursor_label_rect.x += new_pos - old_pos; RefreshRect(track_cursor_label_rect, false); } else { track_cursor_label_rect.SetSize(wxSize(0,0)); track_cursor_label.Clear(); } } void AudioDisplay::RemoveTrackCursor() { SetTrackCursor(-1, false); } void AudioDisplay::OnMouseEnter(wxMouseEvent&) { if (OPT_GET("Audio/Auto/Focus")->GetBool()) SetFocus(); } void AudioDisplay::OnMouseLeave(wxMouseEvent&) { if (!controller->IsPlaying()) RemoveTrackCursor(); } void AudioDisplay::OnMouseEvent(wxMouseEvent& event) { // If we have focus, we get mouse move events on Mac even when the mouse is // outside our client rectangle, we don't want those. if (event.Moving() && !GetClientRect().Contains(event.GetPosition())) { event.Skip(); return; } if (event.IsButton()) SetFocus(); const int mouse_x = event.GetPosition().x; // Scroll the display after a mouse-up near one of the edges if ((event.LeftUp() || event.RightUp()) && OPT_GET("Audio/Auto/Scroll")->GetBool()) { const int width = GetClientSize().GetWidth(); if (mouse_x < width / 20) { ScrollBy(-width / 3); } else if (width - mouse_x < width / 20) { ScrollBy(width / 3); } } if (ForwardMouseEvent(event)) return; if (event.MiddleIsDown()) { context->videoController->JumpToTime(TimeFromRelativeX(mouse_x), agi::vfr::EXACT); return; } if (event.Moving() && !controller->IsPlaying()) { SetTrackCursor(scroll_left + mouse_x, OPT_GET("Audio/Display/Draw/Cursor Time")->GetBool()); } AudioTimingController *timing = controller->GetTimingController(); if (!timing) return; const int drag_sensitivity = int(OPT_GET("Audio/Start Drag Sensitivity")->GetInt() * ms_per_pixel); const int snap_sensitivity = OPT_GET("Audio/Snap/Enable")->GetBool() != event.ShiftDown() ? int(OPT_GET("Audio/Snap/Distance")->GetInt() * ms_per_pixel) : 0; // Not scrollbar, not timeline, no button action if (event.Moving()) { const int timepos = TimeFromRelativeX(mouse_x); if (timing->IsNearbyMarker(timepos, drag_sensitivity)) SetCursor(wxCursor(wxCURSOR_SIZEWE)); else SetCursor(wxNullCursor); return; } const int old_scroll_pos = scroll_left; if (event.LeftDown() || event.RightDown()) { const int timepos = TimeFromRelativeX(mouse_x); std::vector<AudioMarker*> markers = event.LeftDown() ? timing->OnLeftClick(timepos, event.CmdDown(), drag_sensitivity, snap_sensitivity) : timing->OnRightClick(timepos, event.CmdDown(), drag_sensitivity, snap_sensitivity); // Clicking should never result in the audio display scrolling ScrollPixelToLeft(old_scroll_pos); if (markers.size()) { RemoveTrackCursor(); audio_marker = agi::util::make_unique<AudioMarkerInteractionObject>(markers, timing, this, (wxMouseButton)event.GetButton()); SetDraggedObject(audio_marker.get()); return; } } } bool AudioDisplay::ForwardMouseEvent(wxMouseEvent &event) { // Handle any ongoing drag if (dragged_object && HasCapture()) { if (!dragged_object->OnMouseEvent(event)) { scroll_timer.Stop(); SetDraggedObject(nullptr); SetCursor(wxNullCursor); } return true; } else { // Something is wrong, we might have lost capture somehow. // Fix state and pretend it didn't happen. SetDraggedObject(nullptr); SetCursor(wxNullCursor); } const wxPoint mousepos = event.GetPosition(); AudioDisplayInteractionObject *new_obj = nullptr; // Check for scrollbar action if (scrollbar->GetBounds().Contains(mousepos)) { new_obj = scrollbar.get(); } // Check for timeline action else if (timeline->GetBounds().Contains(mousepos)) { SetCursor(wxCursor(wxCURSOR_SIZEWE)); new_obj = timeline.get(); } else { return false; } if (!controller->IsPlaying()) RemoveTrackCursor(); if (new_obj->OnMouseEvent(event)) SetDraggedObject(new_obj); return true; } void AudioDisplay::OnKeyDown(wxKeyEvent& event) { hotkey::check("Audio", context, event); } void AudioDisplay::OnSize(wxSizeEvent &) { // We changed size, update the sub-controls' internal data and redraw wxSize size = GetClientSize(); timeline->SetDisplaySize(wxSize(size.x, scrollbar->GetBounds().y)); scrollbar->SetDisplaySize(size); if (controller->GetTimingController()) { TimeRange sel(controller->GetTimingController()->GetPrimaryPlaybackRange()); scrollbar->SetSelection(AbsoluteXFromTime(sel.begin()), AbsoluteXFromTime(sel.length())); } audio_height = size.GetHeight(); audio_height -= scrollbar->GetBounds().GetHeight(); audio_height -= timeline->GetHeight(); audio_renderer->SetHeight(audio_height); audio_top = timeline->GetHeight(); Refresh(); } void AudioDisplay::OnFocus(wxFocusEvent &) { // The scrollbar indicates focus so repaint that RefreshRect(scrollbar->GetBounds(), false); } void AudioDisplay::OnAudioOpen(AudioProvider *provider) { if (!audio_renderer_provider) ReloadRenderingSettings(); audio_renderer->SetAudioProvider(provider); audio_renderer->SetCacheMaxSize(OPT_GET("Audio/Renderer/Spectrum/Memory Max")->GetInt() * 1024 * 1024); timeline->ChangeAudio(controller->GetDuration()); ms_per_pixel = 0; SetZoomLevel(zoom_level); Refresh(); if (provider) { if (connections.empty()) { connections.push_back(controller->AddAudioCloseListener(&AudioDisplay::OnAudioOpen, this, nullptr)); connections.push_back(controller->AddPlaybackPositionListener(&AudioDisplay::OnPlaybackPosition, this)); connections.push_back(controller->AddPlaybackStopListener(&AudioDisplay::RemoveTrackCursor, this)); connections.push_back(controller->AddTimingControllerListener(&AudioDisplay::OnTimingController, this)); connections.push_back(OPT_SUB("Audio/Spectrum", &AudioDisplay::ReloadRenderingSettings, this)); connections.push_back(OPT_SUB("Audio/Display/Waveform Style", &AudioDisplay::ReloadRenderingSettings, this)); connections.push_back(OPT_SUB("Colour/Audio Display/Spectrum", &AudioDisplay::ReloadRenderingSettings, this)); connections.push_back(OPT_SUB("Colour/Audio Display/Waveform", &AudioDisplay::ReloadRenderingSettings, this)); connections.push_back(OPT_SUB("Audio/Renderer/Spectrum/Quality", &AudioDisplay::ReloadRenderingSettings, this)); OnTimingController(); } } else { connections.clear(); } } void AudioDisplay::OnTimingController() { AudioTimingController *timing_controller = controller->GetTimingController(); if (timing_controller) { timing_controller->AddMarkerMovedListener(&AudioDisplay::OnMarkerMoved, this); timing_controller->AddUpdatedPrimaryRangeListener(&AudioDisplay::OnSelectionChanged, this); timing_controller->AddUpdatedStyleRangesListener(&AudioDisplay::OnStyleRangesChanged, this); OnStyleRangesChanged(); OnMarkerMoved(); } } void AudioDisplay::OnPlaybackPosition(int ms) { int pixel_position = AbsoluteXFromTime(ms); SetTrackCursor(pixel_position, false); if (OPT_GET("Audio/Lock Scroll on Cursor")->GetBool()) { int client_width = GetClientSize().GetWidth(); int edge_size = client_width / 20; if (scroll_left > 0 && pixel_position < scroll_left + edge_size) { ScrollPixelToLeft(std::max(pixel_position - edge_size, 0)); } else if (scroll_left + client_width < std::min(pixel_audio_width - 1, pixel_position + edge_size)) { ScrollPixelToLeft(std::min(pixel_position - client_width + edge_size, pixel_audio_width - client_width - 1)); } } } void AudioDisplay::OnSelectionChanged() { TimeRange sel(controller->GetPrimaryPlaybackRange()); scrollbar->SetSelection(AbsoluteXFromTime(sel.begin()), AbsoluteXFromTime(sel.length())); if (audio_marker) { if (!scroll_timer.IsRunning()) { // If the dragged object is outside the visible area, start the // scroll timer to shift it back into view int rel_x = RelativeXFromTime(audio_marker->GetPosition()); if (rel_x < 0 || rel_x >= GetClientSize().GetWidth()) { // 50ms is the default for this on Windows (hardcoded since // wxSystemSettings doesn't expose DragScrollDelay etc.) scroll_timer.Start(50, true); } } } else if (OPT_GET("Audio/Auto/Scroll")->GetBool() && sel.end() != 0) { ScrollTimeRangeInView(sel); } RefreshRect(scrollbar->GetBounds(), false); } void AudioDisplay::OnScrollTimer(wxTimerEvent &event) { if (!audio_marker) return; int rel_x = RelativeXFromTime(audio_marker->GetPosition()); int width = GetClientSize().GetWidth(); // If the dragged object is outside the visible area, scroll it into // view with a 5% margin if (rel_x < 0) { ScrollBy(rel_x - width / 20); } else if (rel_x >= width) { ScrollBy(rel_x - width + width / 20); } } void AudioDisplay::OnStyleRangesChanged() { if (!controller->GetTimingController()) return; AudioStyleRangeMerger asrm; controller->GetTimingController()->GetRenderingStyles(asrm); style_ranges.clear(); style_ranges.insert(asrm.begin(), asrm.end()); RefreshRect(wxRect(0, audio_top, GetClientSize().GetWidth(), audio_height), false); } void AudioDisplay::OnMarkerMoved() { RefreshRect(wxRect(0, audio_top, GetClientSize().GetWidth(), audio_height), false); }
29.508963
158
0.730983
[ "render", "object", "vector" ]
5d34c3e51f637b12ac83d1974f17b45c20b2d269
1,385
hpp
C++
inference-engine/src/low_precision_transformations/include/low_precision/split.hpp
Andruxin52rus/openvino
d824e371fe7dffb90e6d3d58e4e34adecfce4606
[ "Apache-2.0" ]
2
2020-11-18T14:14:06.000Z
2020-11-28T04:55:57.000Z
inference-engine/src/low_precision_transformations/include/low_precision/split.hpp
Andruxin52rus/openvino
d824e371fe7dffb90e6d3d58e4e34adecfce4606
[ "Apache-2.0" ]
30
2020-11-13T11:44:07.000Z
2022-02-21T13:03:16.000Z
inference-engine/src/low_precision_transformations/include/low_precision/split.hpp
mmakridi/openvino
769bb7709597c14debdaa356dd60c5a78bdfa97e
[ "Apache-2.0" ]
1
2021-07-28T17:30:46.000Z
2021-07-28T17:30:46.000Z
// Copyright (C) 2020 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #pragma once #include <vector> #include "layer_transformation.hpp" #include "ngraph/node.hpp" namespace ngraph { namespace pass { namespace low_precision { class TRANSFORMATIONS_API SplitTransformation : public LayerTransformation { public: SplitTransformation(const Params& params); void registerMatcherIn(GraphRewrite& pass, TransformationContext& context) const override; bool transform(TransformationContext& context, ngraph::pattern::Matcher& m) const override; bool isPrecisionPreserved(std::shared_ptr<Node> layer) const noexcept override; bool canBeTransformed(const TransformationContext& context, std::shared_ptr<Node> layer) const override; void updateOutputs( TransformationContext& context, std::vector<std::shared_ptr<ngraph::Node>> lastNodes, std::shared_ptr<ngraph::Node> originalNode) const; protected: ngraph::Shape getConstSplitShape( const std::vector<size_t>& constSplitLengths, const ngraph::Shape& constShape, const size_t axis, const size_t idx) const; virtual std::vector<size_t> getConstSplitLengths( const OutputVector& inputs, const ngraph::Shape& constShape, const size_t outputSize) const; }; } // namespace low_precision } // namespace pass } // namespace ngraph
34.625
108
0.742238
[ "shape", "vector", "transform" ]
5d3b1d52574399a2dbde83574ee67dea28957f2e
977
cpp
C++
USACO/Star League/Dynamic Programming 1/palin/sol.cpp
hardik0899/Competitive_Programming
199039ad7a26a5f48152fe231a9ca5ac8685a707
[ "MIT" ]
1
2020-10-16T18:14:30.000Z
2020-10-16T18:14:30.000Z
USACO/Star League/Dynamic Programming 1/palin/sol.cpp
hardik0899/Competitive_Programming
199039ad7a26a5f48152fe231a9ca5ac8685a707
[ "MIT" ]
null
null
null
USACO/Star League/Dynamic Programming 1/palin/sol.cpp
hardik0899/Competitive_Programming
199039ad7a26a5f48152fe231a9ca5ac8685a707
[ "MIT" ]
1
2021-01-06T04:45:38.000Z
2021-01-06T04:45:38.000Z
#define __USE_MINGW_ANSI_STDIO 0 #include <iostream> #include <stdio.h> #include <stdlib.h> #include <vector> #include <algorithm> #include <queue> #include <map> #include <set> #include <stack> #include <string.h> #include <math.h> using namespace std; #define PI 3.141592653589793 #define epsilon 0.000000001 #define INF 1000000000000 #define MOD 1000000007 int N, dp [5010][3]; char s [5010]; int main(){ //freopen("grassplant.in", "r", stdin); freopen("grassplant.out", "w", stdout); scanf("%d %s", &N, &s); dp[0][1] = 0; for(int i = 1; i < N; i++){ dp[i][1] = 0; if(s[i-1] == s[i]) dp[i-1][2] = 0; else dp[i-1][2] = 1; } for(int len = 3; len <= N; len++) for(int i = 0; i <= N-len; i++){ int j = i+len-1; if(s[i] == s[j]) dp[i][len%3] = dp[i+1][(len-2)%3]; else dp[i][len%3] = 1+min(dp[i][(len-1)%3], dp[i+1][(len-1)%3]); } cout << dp[0][N%3] << '\n'; return 0; }
23.829268
83
0.530194
[ "vector" ]
5d3f36f423aaa589cf70de1fea4dda4e67c2d2d4
1,859
cpp
C++
Contrib-Intel/RSD-PSME-RMM/common/ipmi/src/command/sdv/get_node_info.cpp
opencomputeproject/Rack-Manager
e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a
[ "MIT" ]
5
2019-11-11T07:57:26.000Z
2022-03-28T08:26:53.000Z
Contrib-Intel/RSD-PSME-RMM/common/ipmi/src/command/sdv/get_node_info.cpp
opencomputeproject/Rack-Manager
e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a
[ "MIT" ]
3
2019-09-05T21:47:07.000Z
2019-09-17T18:10:45.000Z
Contrib-Intel/RSD-PSME-RMM/common/ipmi/src/command/sdv/get_node_info.cpp
opencomputeproject/Rack-Manager
e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a
[ "MIT" ]
11
2019-07-20T00:16:32.000Z
2022-01-11T14:17:48.000Z
/*! * @section LICENSE * * @copyright * Copyright (c) 2015-2019 Intel Corporation * * @copyright * 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 * * @copyright * http://www.apache.org/licenses/LICENSE-2.0 * * @copyright * 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. * * @section DESCRIPTION * * @file get_node_info.cpp * * @brief ... * */ #include "ipmi/command/sdv/get_node_info.hpp" #include "ipmi/command/sdv/enums.hpp" using namespace ipmi; using namespace ipmi::command::sdv; request::GetNodeInfo::GetNodeInfo() : Request(sdv::NetFn::INTEL, sdv::Cmd::GET_NODE_INFO) { } request::GetNodeInfo::~GetNodeInfo() { } response::GetNodeInfo::GetNodeInfo() : Response(sdv::NetFn::INTEL, sdv::Cmd::GET_NODE_INFO, RESPONSE_SIZE) { } response::GetNodeInfo::~GetNodeInfo() { } void response::GetNodeInfo::unpack(const std::vector<std::uint8_t>& data) { m_nodes_no = data[OFFSET_NODES_NUMBER]; m_nodes_present.reserve(NODE_NUMBER); for (unsigned int index = 0; index < NODE_NUMBER; index++) { m_nodes_present[index] = NODE_PRESENT_MASK & data[OFFSET_NODES_PRESENT + index]; } } bool response::GetNodeInfo::is_present(std::size_t node_nr) const { if (node_nr < m_nodes_present.size()) { throw std::runtime_error("Node number too big: " + std::to_string(node_nr)); } return m_nodes_present[node_nr]; } std::size_t response::GetNodeInfo::get_nodes_number() const { return m_nodes_no; }
29.507937
110
0.713287
[ "vector" ]
5d4056a243038409a10508460ef5dc706af7651e
739
hpp
C++
VertexArray.hpp
mcgillowen/cpsc453-hw3
59b3d4c9d320d26d28668b830357f5606e09dd8d
[ "MIT" ]
null
null
null
VertexArray.hpp
mcgillowen/cpsc453-hw3
59b3d4c9d320d26d28668b830357f5606e09dd8d
[ "MIT" ]
null
null
null
VertexArray.hpp
mcgillowen/cpsc453-hw3
59b3d4c9d320d26d28668b830357f5606e09dd8d
[ "MIT" ]
null
null
null
// VertexArray.cpp // Class that holds the vertex information in a VertexArray object #ifndef VERTEX_ARRAY_HPP #define VERTEX_ARRAY_HPP #include <vector> #include <map> #include <string> #define GLFW_INCLUDE_GLCOREARB #define GL_GLEXT_PROTOTYPES #include <GLFW/glfw3.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include "ErrorChecking.hpp" using std::vector; using std::map; using std::string; class VertexArray { std::map<string,GLuint> buffers; public: GLuint id; unsigned int count; VertexArray(); VertexArray(int c); void addBuffer(string name, int index, vector<float> buffer); void updateBuffer(string name, vector<float> buffer); virtual ~VertexArray(); }; #endif // VERTEX_ARRAY_HPP
18.948718
66
0.751015
[ "object", "vector" ]
5d45c9adcca6530c72e1cc41bd161f1ff2c35a9f
41,052
cpp
C++
framework/PVRCore/textureio/TextureReaderPVR.cpp
amaiorano/Native_SDK
0a5b48fd1f4ad251f5b4f0e07c46744c4841255b
[ "MIT" ]
null
null
null
framework/PVRCore/textureio/TextureReaderPVR.cpp
amaiorano/Native_SDK
0a5b48fd1f4ad251f5b4f0e07c46744c4841255b
[ "MIT" ]
null
null
null
framework/PVRCore/textureio/TextureReaderPVR.cpp
amaiorano/Native_SDK
0a5b48fd1f4ad251f5b4f0e07c46744c4841255b
[ "MIT" ]
null
null
null
/*! \brief Implementation of methods of the TextureReaderPVR class. \file PVRCore/textureio/TextureReaderPVR.cpp \author PowerVR by Imagination, Developer Technology Team \copyright Copyright (c) Imagination Technologies Limited. */ //!\cond NO_DOXYGEN #include "PVRCore/textureio/TextureReaderPVR.h" #include "PVRCore/Log.h" using std::vector; namespace pvr { namespace assetReaders { namespace { /// <summary>Load the this texture meta data from a stream</summary> /// <param name="stream">Stream to load the meta data from</param> inline TextureMetaData loadTextureMetadataFromStream(const Stream& stream) { size_t dataRead = 0; uint32_t _fourCC; uint32_t _key; uint32_t _dataSize; stream.read(sizeof(_fourCC), 1, &_fourCC, dataRead); stream.read(sizeof(_key), 1, &_key, dataRead); stream.read(sizeof(_dataSize), 1, &_dataSize, dataRead); if (_dataSize <= 0) { throw FileIOError("TextureMetadata::loadFromStream: Could not read header from stream."); } TextureMetaData ret(_fourCC, _key, _dataSize, NULL); stream.read(1, _dataSize, ret.getData(), dataRead); return ret; } void mapLegacyEnumToNewFormat(const texture_legacy::PixelFormat legacyPixelType, PixelFormat& pixelType, ColorSpace& colorSpace, VariableType& channelType, bool& isPremultiplied) { // Default value. isPremultiplied = false; switch (legacyPixelType) { case texture_legacy::MGL_ARGB_4444: { pixelType = GeneratePixelType4<'a', 'r', 'g', 'b', 4, 4, 4, 4>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedShortNorm; break; } case texture_legacy::MGL_ARGB_1555: { pixelType = GeneratePixelType4<'a', 'r', 'g', 'b', 1, 5, 5, 5>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedShortNorm; break; } case texture_legacy::MGL_RGB_565: { pixelType = GeneratePixelType3<'r', 'g', 'b', 5, 6, 5>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedShortNorm; break; } case texture_legacy::MGL_RGB_555: { pixelType = GeneratePixelType4<'x', 'r', 'g', 'b', 1, 5, 5, 5>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedShortNorm; break; } case texture_legacy::MGL_RGB_888: { pixelType = GeneratePixelType3<'r', 'g', 'b', 8, 8, 8>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedIntegerNorm; break; } case texture_legacy::MGL_ARGB_8888: { pixelType = GeneratePixelType4<'a', 'r', 'g', 'b', 8, 8, 8, 8>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedIntegerNorm; break; } case texture_legacy::MGL_ARGB_8332: { pixelType = GeneratePixelType4<'a', 'r', 'g', 'b', 8, 3, 3, 2>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedShortNorm; break; } case texture_legacy::MGL_I_8: { pixelType = GeneratePixelType1<'i', 8>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedByteNorm; break; } case texture_legacy::MGL_AI_88: { pixelType = GeneratePixelType2<'a', 'i', 8, 8>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedShortNorm; break; } case texture_legacy::MGL_1_BPP: { pixelType = static_cast<uint64_t>(CompressedPixelFormat::BW1bpp); colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedByteNorm; break; } case texture_legacy::MGL_VY1UY0: { pixelType = static_cast<uint64_t>(CompressedPixelFormat::YUY2); colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedByteNorm; break; } case texture_legacy::MGL_Y1VY0U: { pixelType = static_cast<uint64_t>(CompressedPixelFormat::UYVY); colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedByteNorm; break; } case texture_legacy::MGL_PVRTC2: { pixelType = static_cast<uint64_t>(CompressedPixelFormat::PVRTCI_2bpp_RGBA); colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedByteNorm; break; } case texture_legacy::MGL_PVRTC4: { pixelType = static_cast<uint64_t>(CompressedPixelFormat::PVRTCI_4bpp_RGBA); colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedByteNorm; break; } case texture_legacy::GL_RGBA_4444: { pixelType = GeneratePixelType4<'r', 'g', 'b', 'a', 4, 4, 4, 4>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedShortNorm; break; } case texture_legacy::GL_RGBA_5551: { pixelType = GeneratePixelType4<'r', 'g', 'b', 'a', 5, 5, 5, 1>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedShortNorm; break; } case texture_legacy::GL_RGBA_8888: { pixelType = GeneratePixelType4<'r', 'g', 'b', 'a', 8, 8, 8, 8>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedByteNorm; break; } case texture_legacy::GL_RGB_565: { pixelType = GeneratePixelType3<'r', 'g', 'b', 5, 6, 5>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedShortNorm; break; } case texture_legacy::GL_RGB_555: { pixelType = GeneratePixelType4<'r', 'g', 'b', 'x', 5, 5, 5, 1>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedShortNorm; break; } case texture_legacy::GL_RGB_888: { pixelType = GeneratePixelType3<'r', 'g', 'b', 8, 8, 8>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedByteNorm; break; } case texture_legacy::GL_I_8: { pixelType = GeneratePixelType1<'l', 8>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedByteNorm; break; } case texture_legacy::GL_AI_88: { pixelType = GeneratePixelType2<'l', 'a', 8, 8>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedByteNorm; break; } case texture_legacy::GL_PVRTC2: { pixelType = static_cast<uint64_t>(CompressedPixelFormat::PVRTCI_2bpp_RGBA); colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedByteNorm; break; } case texture_legacy::GL_PVRTC4: { pixelType = static_cast<uint64_t>(CompressedPixelFormat::PVRTCI_4bpp_RGBA); colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedByteNorm; break; } case texture_legacy::GL_BGRA_8888: { pixelType = GeneratePixelType4<'b', 'g', 'r', 'a', 8, 8, 8, 8>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedByteNorm; break; } case texture_legacy::GL_A_8: { pixelType = GeneratePixelType1<'a', 8>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedByteNorm; break; } case texture_legacy::GL_PVRTCII4: { pixelType = static_cast<uint64_t>(CompressedPixelFormat::PVRTCII_4bpp); colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedByteNorm; break; } case texture_legacy::GL_PVRTCII2: { pixelType = static_cast<uint64_t>(CompressedPixelFormat::PVRTCII_2bpp); colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedByteNorm; break; } case texture_legacy::D3D_DXT1: { pixelType = static_cast<uint64_t>(CompressedPixelFormat::DXT1); colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedByteNorm; break; } case texture_legacy::D3D_DXT2: { pixelType = static_cast<uint64_t>(CompressedPixelFormat::DXT2); colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedByteNorm; isPremultiplied = true; break; } case texture_legacy::D3D_DXT3: { pixelType = CompressedPixelFormat::DXT3; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedByteNorm; break; } case texture_legacy::D3D_DXT4: { pixelType = static_cast<uint64_t>(CompressedPixelFormat::DXT4); colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedByteNorm; isPremultiplied = true; break; } case texture_legacy::D3D_DXT5: { pixelType = static_cast<uint64_t>(CompressedPixelFormat::DXT5); colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedByteNorm; break; } case texture_legacy::D3D_RGB_332: { pixelType = GeneratePixelType3<'r', 'g', 'b', 3, 3, 2>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedIntegerNorm; break; } case texture_legacy::D3D_AL_44: { pixelType = GeneratePixelType2<'a', 'l', 4, 4>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedIntegerNorm; break; } case texture_legacy::D3D_LVU_655: { pixelType = GeneratePixelType3<'l', 'g', 'r', 6, 5, 5>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::SignedIntegerNorm; break; } case texture_legacy::D3D_XLVU_8888: { pixelType = GeneratePixelType4<'x', 'l', 'g', 'r', 8, 8, 8, 8>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::SignedIntegerNorm; break; } case texture_legacy::D3D_QWVU_8888: { pixelType = GeneratePixelType4<'a', 'b', 'g', 'r', 8, 8, 8, 8>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::SignedIntegerNorm; break; } case texture_legacy::D3D_ABGR_2101010: { pixelType = GeneratePixelType4<'a', 'b', 'g', 'r', 2, 10, 10, 10>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedIntegerNorm; break; } case texture_legacy::D3D_ARGB_2101010: { pixelType = GeneratePixelType4<'a', 'r', 'g', 'b', 2, 10, 10, 10>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedIntegerNorm; break; } case texture_legacy::D3D_AWVU_2101010: { pixelType = GeneratePixelType4<'a', 'r', 'g', 'b', 2, 10, 10, 10>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedIntegerNorm; break; } case texture_legacy::D3D_GR_1616: { pixelType = GeneratePixelType2<'g', 'r', 16, 16>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedIntegerNorm; break; } case texture_legacy::D3D_VU_1616: { pixelType = GeneratePixelType2<'g', 'r', 16, 16>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::SignedIntegerNorm; break; } case texture_legacy::D3D_ABGR_16161616: { pixelType = GeneratePixelType4<'a', 'b', 'g', 'r', 16, 16, 16, 16>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedIntegerNorm; break; } case texture_legacy::D3D_R16F: { pixelType = GeneratePixelType1<'r', 16>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::SignedFloat; break; } case texture_legacy::D3D_GR_1616F: { pixelType = GeneratePixelType2<'g', 'r', 16, 16>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::SignedFloat; break; } case texture_legacy::D3D_ABGR_16161616F: { pixelType = GeneratePixelType4<'a', 'b', 'g', 'r', 16, 16, 16, 16>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::SignedFloat; break; } case texture_legacy::D3D_R32F: { pixelType = GeneratePixelType1<'r', 32>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::SignedFloat; break; } case texture_legacy::D3D_GR_3232F: { pixelType = GeneratePixelType2<'g', 'r', 32, 32>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::SignedFloat; break; } case texture_legacy::D3D_ABGR_32323232F: { pixelType = GeneratePixelType4<'a', 'b', 'g', 'r', 32, 32, 32, 32>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::SignedFloat; break; } case texture_legacy::e_etc_RGB_4BPP: { pixelType = CompressedPixelFormat::ETC1; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedByteNorm; break; } case texture_legacy::D3D_A8: { pixelType = GeneratePixelType1<'a', 8>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedIntegerNorm; break; } case texture_legacy::D3D_V8U8: { pixelType = GeneratePixelType2<'g', 'r', 8, 8>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::SignedIntegerNorm; break; } case texture_legacy::D3D_L16: { pixelType = GeneratePixelType1<'l', 16>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedIntegerNorm; break; } case texture_legacy::D3D_L8: { pixelType = GeneratePixelType1<'l', 8>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedIntegerNorm; break; } case texture_legacy::D3D_AL_88: { pixelType = GeneratePixelType2<'a', 'l', 8, 8>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedIntegerNorm; break; } case texture_legacy::D3D_UYVY: { pixelType = static_cast<uint64_t>(CompressedPixelFormat::UYVY); colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedByteNorm; break; } case texture_legacy::D3D_YUY2: { pixelType = static_cast<uint64_t>(CompressedPixelFormat::YUY2); colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedByteNorm; break; } case texture_legacy::DXGI_R32G32B32A32_FLOAT: { pixelType = GeneratePixelType4<'r', 'g', 'b', 'a', 32, 32, 32, 32>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::SignedFloat; break; } case texture_legacy::DXGI_R32G32B32A32_UINT: { pixelType = GeneratePixelType4<'r', 'g', 'b', 'a', 32, 32, 32, 32>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedInteger; break; } case texture_legacy::DXGI_R32G32B32A32_SINT: { pixelType = GeneratePixelType4<'r', 'g', 'b', 'a', 32, 32, 32, 32>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::SignedInteger; break; } case texture_legacy::DXGI_R32G32B32_FLOAT: { pixelType = GeneratePixelType3<'r', 'g', 'b', 32, 32, 32>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::SignedFloat; break; } case texture_legacy::DXGI_R32G32B32_UINT: { pixelType = GeneratePixelType3<'r', 'g', 'b', 32, 32, 32>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedInteger; break; } case texture_legacy::DXGI_R32G32B32_SINT: { pixelType = GeneratePixelType3<'r', 'g', 'b', 32, 32, 32>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::SignedInteger; break; } case texture_legacy::DXGI_R16G16B16A16_FLOAT: { pixelType = GeneratePixelType4<'r', 'g', 'b', 'a', 16, 16, 16, 16>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::SignedFloat; break; } case texture_legacy::DXGI_R16G16B16A16_UNORM: { pixelType = GeneratePixelType4<'r', 'g', 'b', 'a', 16, 16, 16, 16>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedShortNorm; break; } case texture_legacy::DXGI_R16G16B16A16_UINT: { pixelType = GeneratePixelType4<'r', 'g', 'b', 'a', 16, 16, 16, 16>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedShort; break; } case texture_legacy::DXGI_R16G16B16A16_SNORM: { pixelType = GeneratePixelType4<'r', 'g', 'b', 'a', 16, 16, 16, 16>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::SignedShortNorm; break; } case texture_legacy::DXGI_R16G16B16A16_SINT: { pixelType = GeneratePixelType4<'r', 'g', 'b', 'a', 16, 16, 16, 16>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::SignedShort; break; } case texture_legacy::DXGI_R32G32_FLOAT: { pixelType = GeneratePixelType2<'r', 'g', 32, 32>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::SignedFloat; break; } case texture_legacy::DXGI_R32G32_UINT: { pixelType = GeneratePixelType2<'r', 'g', 32, 32>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedInteger; break; } case texture_legacy::DXGI_R32G32_SINT: { pixelType = GeneratePixelType2<'r', 'g', 32, 32>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::SignedInteger; break; } case texture_legacy::DXGI_R10G10B10A2_UNORM: { pixelType = GeneratePixelType4<'r', 'g', 'b', 'a', 10, 10, 10, 2>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedIntegerNorm; break; } case texture_legacy::DXGI_R10G10B10A2_UINT: { pixelType = GeneratePixelType4<'r', 'g', 'b', 'a', 10, 10, 10, 2>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedInteger; break; } case texture_legacy::DXGI_R11G11B10_FLOAT: { pixelType = GeneratePixelType3<'r', 'g', 'b', 11, 11, 10>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::SignedFloat; break; } case texture_legacy::DXGI_R8G8B8A8_UNORM: { pixelType = GeneratePixelType4<'r', 'g', 'b', 'a', 8, 8, 8, 8>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedByteNorm; break; } case texture_legacy::DXGI_R8G8B8A8_UNORM_SRGB: { pixelType = GeneratePixelType4<'r', 'g', 'b', 'a', 8, 8, 8, 8>::ID; colorSpace = ColorSpace::sRGB; channelType = VariableType::UnsignedByteNorm; break; } case texture_legacy::DXGI_R8G8B8A8_UINT: { pixelType = GeneratePixelType4<'r', 'g', 'b', 'a', 8, 8, 8, 8>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedByte; break; } case texture_legacy::DXGI_R8G8B8A8_SNORM: { pixelType = GeneratePixelType4<'r', 'g', 'b', 'a', 8, 8, 8, 8>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::SignedByteNorm; break; } case texture_legacy::DXGI_R8G8B8A8_SINT: { pixelType = GeneratePixelType4<'r', 'g', 'b', 'a', 8, 8, 8, 8>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::SignedByte; break; } case texture_legacy::DXGI_R16G16_FLOAT: { pixelType = GeneratePixelType2<'r', 'g', 16, 16>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::SignedFloat; break; } case texture_legacy::DXGI_R16G16_UNORM: { pixelType = GeneratePixelType2<'r', 'g', 16, 16>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedShortNorm; break; } case texture_legacy::DXGI_R16G16_UINT: { pixelType = GeneratePixelType2<'r', 'g', 16, 16>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedShort; break; } case texture_legacy::DXGI_R16G16_SNORM: { pixelType = GeneratePixelType2<'r', 'g', 16, 16>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::SignedShortNorm; break; } case texture_legacy::DXGI_R16G16_SINT: { pixelType = GeneratePixelType2<'r', 'g', 16, 16>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::SignedShort; break; } case texture_legacy::DXGI_R32_FLOAT: { pixelType = GeneratePixelType1<'r', 32>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::SignedFloat; break; } case texture_legacy::DXGI_R32_UINT: { pixelType = GeneratePixelType1<'r', 32>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedInteger; break; } case texture_legacy::DXGI_R32_SINT: { pixelType = GeneratePixelType1<'r', 32>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::SignedInteger; break; } case texture_legacy::DXGI_R8G8_UNORM: { pixelType = GeneratePixelType2<'r', 'g', 8, 8>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedByteNorm; break; } case texture_legacy::DXGI_R8G8_UINT: { pixelType = GeneratePixelType2<'r', 'g', 8, 8>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedByte; break; } case texture_legacy::DXGI_R8G8_SNORM: { pixelType = GeneratePixelType2<'r', 'g', 8, 8>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::SignedByteNorm; break; } case texture_legacy::DXGI_R8G8_SINT: { pixelType = GeneratePixelType2<'r', 'g', 8, 8>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::SignedByte; break; } case texture_legacy::DXGI_R16_FLOAT: { pixelType = GeneratePixelType1<'r', 16>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::SignedFloat; break; } case texture_legacy::DXGI_R16_UNORM: { pixelType = GeneratePixelType1<'r', 16>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedShortNorm; break; } case texture_legacy::DXGI_R16_UINT: { pixelType = GeneratePixelType1<'r', 16>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedShort; break; } case texture_legacy::DXGI_R16_SNORM: { pixelType = GeneratePixelType1<'r', 16>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::SignedShortNorm; break; } case texture_legacy::DXGI_R16_SINT: { pixelType = GeneratePixelType1<'r', 16>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::SignedShort; break; } case texture_legacy::DXGI_R8_UNORM: { pixelType = GeneratePixelType1<'r', 8>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedByteNorm; break; } case texture_legacy::DXGI_R8_UINT: { pixelType = GeneratePixelType1<'r', 8>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedByte; break; } case texture_legacy::DXGI_R8_SNORM: { pixelType = GeneratePixelType1<'r', 8>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::SignedByteNorm; break; } case texture_legacy::DXGI_R8_SINT: { pixelType = GeneratePixelType1<'r', 8>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::SignedByte; break; } case texture_legacy::DXGI_A8_UNORM: { pixelType = GeneratePixelType1<'r', 8>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedByteNorm; break; } case texture_legacy::DXGI_R1_UNORM: { pixelType = static_cast<uint64_t>(CompressedPixelFormat::BW1bpp); colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedByteNorm; break; } case texture_legacy::DXGI_R9G9B9E5_SHAREDEXP: { pixelType = static_cast<uint64_t>(CompressedPixelFormat::SharedExponentR9G9B9E5); colorSpace = ColorSpace::lRGB; channelType = VariableType::SignedFloat; break; } case texture_legacy::DXGI_R8G8_B8G8_UNORM: { pixelType = static_cast<uint64_t>(CompressedPixelFormat::RGBG8888); colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedByteNorm; break; } case texture_legacy::DXGI_G8R8_G8B8_UNORM: { pixelType = static_cast<uint64_t>(CompressedPixelFormat::GRGB8888); colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedByteNorm; break; } case texture_legacy::DXGI_BC1_UNORM: { pixelType = static_cast<uint64_t>(CompressedPixelFormat::DXT1); colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedIntegerNorm; break; } case texture_legacy::DXGI_BC1_UNORM_SRGB: { pixelType = static_cast<uint64_t>(CompressedPixelFormat::DXT1); colorSpace = ColorSpace::sRGB; channelType = VariableType::UnsignedIntegerNorm; break; } case texture_legacy::DXGI_BC2_UNORM: { pixelType = static_cast<uint64_t>(CompressedPixelFormat::DXT3); colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedIntegerNorm; break; } case texture_legacy::DXGI_BC2_UNORM_SRGB: { pixelType = static_cast<uint64_t>(CompressedPixelFormat::DXT1); colorSpace = ColorSpace::sRGB; channelType = VariableType::UnsignedIntegerNorm; break; } case texture_legacy::DXGI_BC3_UNORM: { pixelType = static_cast<uint64_t>(CompressedPixelFormat::DXT5); colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedIntegerNorm; break; } case texture_legacy::DXGI_BC3_UNORM_SRGB: { pixelType = CompressedPixelFormat::DXT1; colorSpace = ColorSpace::sRGB; channelType = VariableType::UnsignedIntegerNorm; break; } case texture_legacy::DXGI_BC4_UNORM: { pixelType = CompressedPixelFormat::BC4; colorSpace = ColorSpace::sRGB; channelType = VariableType::UnsignedIntegerNorm; break; } case texture_legacy::DXGI_BC4_SNORM: { pixelType = CompressedPixelFormat::BC4; colorSpace = ColorSpace::lRGB; channelType = VariableType::SignedIntegerNorm; break; } case texture_legacy::DXGI_BC5_UNORM: { pixelType = CompressedPixelFormat::BC5; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedIntegerNorm; break; } case texture_legacy::DXGI_BC5_SNORM: { pixelType = CompressedPixelFormat::BC5; colorSpace = ColorSpace::lRGB; channelType = VariableType::SignedIntegerNorm; break; } case texture_legacy::VG_sRGBX_8888: { pixelType = GeneratePixelType4<'r', 'g', 'b', 'x', 8, 8, 8, 8>::ID; colorSpace = ColorSpace::sRGB; channelType = VariableType::UnsignedByteNorm; break; } case texture_legacy::VG_sRGBA_8888: { pixelType = GeneratePixelType4<'r', 'g', 'b', 'a', 8, 8, 8, 8>::ID; colorSpace = ColorSpace::sRGB; channelType = VariableType::UnsignedByteNorm; break; } case texture_legacy::VG_sRGBA_8888_PRE: { pixelType = GeneratePixelType4<'r', 'g', 'b', 'a', 8, 8, 8, 8>::ID; colorSpace = ColorSpace::sRGB; channelType = VariableType::UnsignedByteNorm; isPremultiplied = true; break; } case texture_legacy::VG_sRGB_565: { pixelType = GeneratePixelType3<'r', 'g', 'b', 5, 6, 5>::ID; colorSpace = ColorSpace::sRGB; channelType = VariableType::UnsignedShortNorm; break; } case texture_legacy::VG_sRGBA_5551: { pixelType = GeneratePixelType4<'r', 'g', 'b', 'a', 5, 5, 5, 1>::ID; colorSpace = ColorSpace::sRGB; channelType = VariableType::UnsignedShortNorm; break; } case texture_legacy::VG_sRGBA_4444: { pixelType = GeneratePixelType4<'r', 'g', 'b', 'a', 4, 4, 4, 4>::ID; colorSpace = ColorSpace::sRGB; channelType = VariableType::UnsignedShortNorm; break; } case texture_legacy::VG_sL_8: { pixelType = GeneratePixelType1<'l', 8>::ID; colorSpace = ColorSpace::sRGB; channelType = VariableType::UnsignedByteNorm; break; } case texture_legacy::VG_lRGBX_8888: { pixelType = GeneratePixelType4<'r', 'g', 'b', 'x', 8, 8, 8, 8>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedByteNorm; break; } case texture_legacy::VG_lRGBA_8888: { pixelType = GeneratePixelType4<'r', 'g', 'b', 'a', 8, 8, 8, 8>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedByteNorm; break; } case texture_legacy::VG_lRGBA_8888_PRE: { pixelType = GeneratePixelType4<'r', 'g', 'b', 'a', 8, 8, 8, 8>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedByteNorm; isPremultiplied = true; break; } case texture_legacy::VG_lL_8: { pixelType = GeneratePixelType1<'l', 8>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedByteNorm; break; } case texture_legacy::VG_A_8: { pixelType = GeneratePixelType1<'a', 8>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedByteNorm; break; } case texture_legacy::VG_BW_1: { pixelType = CompressedPixelFormat::BW1bpp; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedByteNorm; break; } case texture_legacy::VG_sXRGB_8888: { pixelType = GeneratePixelType4<'x', 'r', 'g', 'b', 8, 8, 8, 8>::ID; colorSpace = ColorSpace::sRGB; channelType = VariableType::UnsignedByteNorm; break; } case texture_legacy::VG_sARGB_8888: { pixelType = GeneratePixelType4<'a', 'r', 'g', 'b', 8, 8, 8, 8>::ID; colorSpace = ColorSpace::sRGB; channelType = VariableType::UnsignedByteNorm; break; } case texture_legacy::VG_sARGB_8888_PRE: { pixelType = GeneratePixelType4<'a', 'r', 'g', 'b', 8, 8, 8, 8>::ID; colorSpace = ColorSpace::sRGB; channelType = VariableType::UnsignedByteNorm; isPremultiplied = true; break; } case texture_legacy::VG_sARGB_1555: { pixelType = GeneratePixelType4<'a', 'r', 'g', 'b', 1, 5, 5, 5>::ID; colorSpace = ColorSpace::sRGB; channelType = VariableType::UnsignedShortNorm; break; } case texture_legacy::VG_sARGB_4444: { pixelType = GeneratePixelType4<'a', 'r', 'g', 'b', 4, 4, 4, 4>::ID; colorSpace = ColorSpace::sRGB; channelType = VariableType::UnsignedShortNorm; break; } case texture_legacy::VG_lXRGB_8888: { pixelType = GeneratePixelType4<'x', 'r', 'g', 'b', 8, 8, 8, 8>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedByteNorm; break; } case texture_legacy::VG_lARGB_8888: { pixelType = GeneratePixelType4<'a', 'r', 'g', 'b', 8, 8, 8, 8>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedByteNorm; break; } case texture_legacy::VG_lARGB_8888_PRE: { pixelType = GeneratePixelType4<'a', 'r', 'g', 'b', 8, 8, 8, 8>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedByteNorm; isPremultiplied = true; break; } case texture_legacy::VG_sBGRX_8888: { pixelType = GeneratePixelType4<'b', 'g', 'r', 'x', 8, 8, 8, 8>::ID; colorSpace = ColorSpace::sRGB; channelType = VariableType::UnsignedByteNorm; break; } case texture_legacy::VG_sBGRA_8888: { pixelType = GeneratePixelType4<'b', 'g', 'r', 'a', 8, 8, 8, 8>::ID; colorSpace = ColorSpace::sRGB; channelType = VariableType::UnsignedByteNorm; break; } case texture_legacy::VG_sBGRA_8888_PRE: { pixelType = GeneratePixelType4<'b', 'g', 'r', 'a', 8, 8, 8, 8>::ID; colorSpace = ColorSpace::sRGB; channelType = VariableType::UnsignedByteNorm; isPremultiplied = true; break; } case texture_legacy::VG_sBGR_565: { pixelType = GeneratePixelType3<'b', 'g', 'r', 5, 6, 5>::ID; colorSpace = ColorSpace::sRGB; channelType = VariableType::UnsignedShortNorm; break; } case texture_legacy::VG_sBGRA_5551: { pixelType = GeneratePixelType4<'b', 'g', 'r', 'a', 5, 5, 5, 1>::ID; colorSpace = ColorSpace::sRGB; channelType = VariableType::UnsignedShortNorm; break; } case texture_legacy::VG_sBGRA_4444: { pixelType = GeneratePixelType4<'b', 'g', 'r', 'x', 4, 4, 4, 4>::ID; colorSpace = ColorSpace::sRGB; channelType = VariableType::UnsignedShortNorm; break; } case texture_legacy::VG_lBGRX_8888: { pixelType = GeneratePixelType4<'b', 'g', 'r', 'x', 8, 8, 8, 8>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedByteNorm; break; } case texture_legacy::VG_lBGRA_8888: { pixelType = GeneratePixelType4<'b', 'g', 'r', 'a', 8, 8, 8, 8>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedByteNorm; break; } case texture_legacy::VG_lBGRA_8888_PRE: { pixelType = GeneratePixelType4<'b', 'g', 'r', 'a', 8, 8, 8, 8>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedByteNorm; isPremultiplied = true; break; } case texture_legacy::VG_sXBGR_8888: { pixelType = GeneratePixelType4<'x', 'b', 'g', 'r', 8, 8, 8, 8>::ID; colorSpace = ColorSpace::sRGB; channelType = VariableType::UnsignedByteNorm; break; } case texture_legacy::VG_sABGR_8888: { pixelType = GeneratePixelType4<'a', 'b', 'g', 'r', 8, 8, 8, 8>::ID; colorSpace = ColorSpace::sRGB; channelType = VariableType::UnsignedByteNorm; break; } case texture_legacy::VG_sABGR_8888_PRE: { pixelType = GeneratePixelType4<'a', 'b', 'g', 'r', 8, 8, 8, 8>::ID; colorSpace = ColorSpace::sRGB; channelType = VariableType::UnsignedByteNorm; isPremultiplied = true; break; } case texture_legacy::VG_sABGR_1555: { pixelType = GeneratePixelType4<'a', 'b', 'g', 'r', 1, 5, 5, 5>::ID; colorSpace = ColorSpace::sRGB; channelType = VariableType::UnsignedShortNorm; break; } case texture_legacy::VG_sABGR_4444: { pixelType = GeneratePixelType4<'x', 'b', 'g', 'r', 4, 4, 4, 4>::ID; colorSpace = ColorSpace::sRGB; channelType = VariableType::UnsignedShortNorm; break; } case texture_legacy::VG_lXBGR_8888: { pixelType = GeneratePixelType4<'x', 'b', 'g', 'r', 8, 8, 8, 8>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedByteNorm; break; } case texture_legacy::VG_lABGR_8888: { pixelType = GeneratePixelType4<'a', 'b', 'g', 'r', 8, 8, 8, 8>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedByteNorm; break; } case texture_legacy::VG_lABGR_8888_PRE: { pixelType = GeneratePixelType4<'a', 'b', 'g', 'r', 8, 8, 8, 8>::ID; colorSpace = ColorSpace::lRGB; channelType = VariableType::UnsignedByteNorm; isPremultiplied = true; break; } default: { pixelType = CompressedPixelFormat::NumCompressedPFs; colorSpace = ColorSpace::lRGB; channelType = VariableType::NumVarTypes; throw InvalidDataError("[TextureReaderPVR::mapLegacyEnumToNewFormat]: Could not match the old format to a new format"); } } } void convertTextureHeader2To3(const texture_legacy::HeaderV2& legacyHeader, TextureHeader& newHeader) { // Pixel type variables to obtain from the old header's information bool isPremultiplied; PixelFormat pixelType; ColorSpace colorSpace; VariableType channelType; // Map the old enum to the new format. mapLegacyEnumToNewFormat((texture_legacy::PixelFormat)(legacyHeader.pixelFormatAndFlags & 0xff), pixelType, colorSpace, channelType, isPremultiplied); // Check if this is a cube map. bool isCubeMap = (legacyHeader.pixelFormatAndFlags & texture_legacy::c_flagCubeMap) != 0; // Setup the new header based on the old values TextureHeader::Header pvrTextureHeaderV3; // Set the pixel type obtained from the legacy format pvrTextureHeaderV3.flags = isPremultiplied ? (TextureHeader::Header::PremultipliedFlag) : (0); pvrTextureHeaderV3.pixelFormat = pixelType.getPixelTypeId(); pvrTextureHeaderV3.colorSpace = colorSpace; pvrTextureHeaderV3.channelType = channelType; // Set the width and height pvrTextureHeaderV3.height = legacyHeader.height; pvrTextureHeaderV3.width = legacyHeader.width; // Set the number of surfaces and the depth if ((legacyHeader.pixelFormatAndFlags & texture_legacy::c_flagVolumeTexture) != 0) { pvrTextureHeaderV3.depth = legacyHeader.numSurfaces / (isCubeMap ? 6 : 1); pvrTextureHeaderV3.numSurfaces = 1; } else { pvrTextureHeaderV3.depth = 1; pvrTextureHeaderV3.numSurfaces = legacyHeader.numSurfaces / (isCubeMap ? 6 : 1); } // Check for the elusive "PVR!\0" no surfaces bug, and attempt to correct if (pvrTextureHeaderV3.numSurfaces == 0) { pvrTextureHeaderV3.numSurfaces = 1; } // Turn the original flag into a number of faces. pvrTextureHeaderV3.numFaces = (isCubeMap ? 6 : 1); // Legacy headers have a MIP Map count of 0 if there is only the top level. New Headers have a count of 1, so add 1. pvrTextureHeaderV3.numMipMaps = (legacyHeader.numMipMaps + 1); // Initialize the header with no meta data pvrTextureHeaderV3.metaDataSize = 0; // Create the new texture header. newHeader = TextureHeader(pvrTextureHeaderV3, 0, NULL); // Check for the texture being a normal map. if (legacyHeader.pixelFormatAndFlags & texture_legacy::c_flagBumpMap) { newHeader.setBumpMap(1.0f, "xyz"); } // Check for vertical flip orientation. if (legacyHeader.pixelFormatAndFlags & texture_legacy::c_flagVerticalFlip) { newHeader.setOrientation(TextureMetaData::AxisOrientationUp); } } } // namespace bool isPVR(const Stream& assetStream) { // Read the identifier texture_legacy::HeaderV2 header; size_t dataRead; assetStream.read(1, texture_legacy::c_headerSizeV2, &header, dataRead); // Check that the identifier matches one of the accepted formats. switch (header.headerSize) { case texture_legacy::c_headerSizeV1: return dataRead >= texture_legacy::c_headerSizeV1; case texture_legacy::c_headerSizeV2: return dataRead == texture_legacy::c_headerSizeV2 && header.pvrMagic == texture_legacy::c_identifierV2; case TextureHeader::Header::PVRv3: return dataRead >= std::min(texture_legacy::c_headerSizeV2, static_cast<uint32_t>(TextureHeader::Header::SizeOfHeader)); } return false; } Texture readPVR(const Stream& stream) { if (!stream.isReadable()) { throw InvalidOperationError("[pvr::assetReaders::readPVR] Attempted to read a non-readable assetStream"); } Texture asset; // Get the file header to Read. TextureHeader::Header textureFileHeader; try { // Read the texture header version uint32_t version; stream.readExact(sizeof(version), 1, &version); if (version == TextureHeader::Header::PVRv3) { // Read the flags stream.readExact(sizeof(textureFileHeader.flags), 1, &textureFileHeader.flags); // Read the pixel format stream.readExact(sizeof(textureFileHeader.pixelFormat), 1, &textureFileHeader.pixelFormat); // Read the color space stream.readExact(sizeof(textureFileHeader.colorSpace), 1, &textureFileHeader.colorSpace); // Read the channel type stream.readExact(sizeof(textureFileHeader.channelType), 1, &textureFileHeader.channelType); // Read the height stream.readExact(sizeof(textureFileHeader.height), 1, &textureFileHeader.height); // Read the width stream.readExact(sizeof(textureFileHeader.width), 1, &textureFileHeader.width); // Read the depth stream.readExact(sizeof(textureFileHeader.depth), 1, &textureFileHeader.depth); // Read the number of surfaces stream.readExact(sizeof(textureFileHeader.numSurfaces), 1, &textureFileHeader.numSurfaces); // Read the number of faces stream.readExact(sizeof(textureFileHeader.numFaces), 1, &textureFileHeader.numFaces); // Read the number of MIP maps stream.readExact(sizeof(textureFileHeader.numMipMaps), 1, &textureFileHeader.numMipMaps); // Read the meta data size, but store it for now. uint32_t tempMetaDataSize = 0; stream.readExact(sizeof(tempMetaDataSize), 1, &tempMetaDataSize); // Construct a texture header. // Set the meta data size to 0 textureFileHeader.metaDataSize = 0; TextureHeader textureHeader(textureFileHeader, 0, NULL); asset.initializeWithHeader(textureHeader); // Read the meta data uint32_t metaDataRead = 0; while (metaDataRead < tempMetaDataSize) { TextureMetaData metaDataBlock = loadTextureMetadataFromStream(stream); // Add the meta data asset.addMetaData(metaDataBlock); // Evaluate the meta data read metaDataRead = asset.getMetaDataSize(); } // Make sure the provided data size wasn't wrong. If it was, there are no guarantees about the contents of the texture data. if (metaDataRead > tempMetaDataSize) { throw InvalidDataError("[TextureReaderPVR::readAsset_] Metadata seems to be corrupted while reading."); } // Read the texture data stream.readExact(1, asset.getDataSize(), asset.getDataPointer()); } else if (version == texture_legacy::c_headerSizeV1 || version == texture_legacy::c_headerSizeV2) { // Read a V2 legacy header texture_legacy::HeaderV2 legacyHeader; // Read the header size legacyHeader.headerSize = version; // Read the height stream.readExact(sizeof(legacyHeader.height), 1, &legacyHeader.height); // Read the width stream.readExact(sizeof(legacyHeader.width), 1, &legacyHeader.width); // Read the MIP map count stream.readExact(sizeof(legacyHeader.numMipMaps), 1, &legacyHeader.numMipMaps); // Read the texture flags stream.readExact(sizeof(legacyHeader.pixelFormatAndFlags), 1, &legacyHeader.pixelFormatAndFlags); // Read the texture data size stream.readExact(sizeof(legacyHeader.dataSize), 1, &legacyHeader.dataSize); // Read the bit count of the texture format stream.readExact(sizeof(legacyHeader.bitCount), 1, &legacyHeader.bitCount); // Read the red mask stream.readExact(sizeof(legacyHeader.redBitMask), 1, &legacyHeader.redBitMask); // Read the green mask stream.readExact(sizeof(legacyHeader.greenBitMask), 1, &legacyHeader.greenBitMask); // Read the blue mask stream.readExact(sizeof(legacyHeader.blueBitMask), 1, &legacyHeader.blueBitMask); // Read the alpha mask stream.readExact(sizeof(legacyHeader.alphaBitMask), 1, &legacyHeader.alphaBitMask); if (version == texture_legacy::c_headerSizeV2) { // Read the magic number stream.readExact(sizeof(legacyHeader.pvrMagic), 1, &legacyHeader.pvrMagic); // Read the number of surfaces stream.readExact(sizeof(legacyHeader.numSurfaces), 1, &legacyHeader.numSurfaces); } else { legacyHeader.pvrMagic = texture_legacy::c_identifierV2; legacyHeader.numSurfaces = 1; } // Construct a texture header by converting the old one TextureHeader textureHeader; convertTextureHeader2To3(legacyHeader, textureHeader); // Copy the texture header to the asset. asset.initializeWithHeader(textureHeader); // Write the texture data for(uint32_t surface = 0; surface < asset.getNumArrayMembers(); ++surface) { for(uint32_t depth = 0; depth < asset.getDepth(); ++depth) { for(uint32_t face = 0; face < asset.getNumFaces(); ++face) { for(uint32_t mipMap = 0; mipMap < asset.getNumMipMapLevels(); ++mipMap) { uint32_t surfaceSize = asset.getDataSize(mipMap, false, false) / asset.getDepth(); unsigned char* surfacePointer = asset.getDataPointer(mipMap, surface, face) + depth * surfaceSize; // Write each surface, one at a time stream.readExact(1, surfaceSize, surfacePointer); } } } } } else { throw InvalidDataError("[TextureReaderPVR::readAsset_]: Unsupported PVR Version"); } } catch (const FileEOFError&) { throw InvalidDataError("[TextureReaderPVR::readAsset_]: Not a not a valid PVR file."); } return asset; } } // namespace assetReaders } // namespace pvr //!\endcond
26.691808
178
0.713729
[ "vector" ]
5d543ac23e727d1466356bbfb893494c53e819a6
3,895
cpp
C++
ext/DebugDraw/CDraw3DLine.cpp
barszram/IrrlichtBAW
71c88dc45f28ff1fb4d948ed792f3051ad47d664
[ "Apache-2.0" ]
3
2016-05-12T06:49:40.000Z
2016-10-31T17:57:53.000Z
ext/DebugDraw/CDraw3DLine.cpp
barszram/IrrlichtBAW
71c88dc45f28ff1fb4d948ed792f3051ad47d664
[ "Apache-2.0" ]
2
2019-10-02T14:59:45.000Z
2019-10-27T11:10:20.000Z
ext/DebugDraw/CDraw3DLine.cpp
Przemog1/IrrlichtBAW
d3f148c810d528df44598a47e8a96e6838a1cc3e
[ "Apache-2.0" ]
1
2016-06-27T09:21:36.000Z
2016-06-27T09:21:36.000Z
#include "../ext/DebugDraw/CDraw3DLine.h" #include "../ext/DebugDraw/Draw3DLineShaders.h" using namespace irr; using namespace video; using namespace scene; using namespace asset; using namespace ext; using namespace DebugDraw; core::smart_refctd_ptr<CDraw3DLine> CDraw3DLine::create(IVideoDriver* _driver) { return core::smart_refctd_ptr<CDraw3DLine>(new CDraw3DLine(_driver),core::dont_grab); } CDraw3DLine::CDraw3DLine(IVideoDriver* _driver) : m_driver(_driver), m_meshBuffer(core::make_smart_refctd_ptr<IGPUMeshBuffer>()) { auto callBack = new Draw3DLineCallBack(); m_material.MaterialType = (E_MATERIAL_TYPE) m_driver->getGPUProgrammingServices()->addHighLevelShaderMaterial( Draw3DLineVertexShader, nullptr,nullptr,nullptr, Draw3DLineFragmentShader, 2,EMT_SOLID, callBack, 0); callBack->drop(); m_meshBuffer->setPrimitiveType(EPT_LINES); m_meshBuffer->setIndexType(EIT_UNKNOWN); m_meshBuffer->setIndexCount(2); auto m_desc = _driver->createGPUMeshDataFormatDesc(); auto buff = core::smart_refctd_ptr<video::IGPUBuffer>(m_driver->getDefaultUpStreamingBuffer()->getBuffer(),core::dont_grab); m_desc->setVertexAttrBuffer(core::smart_refctd_ptr(buff),EVAI_ATTR0,EF_R32G32B32_SFLOAT,sizeof(S3DLineVertex), offsetof(S3DLineVertex, Position[0])); m_desc->setVertexAttrBuffer(core::smart_refctd_ptr(buff),EVAI_ATTR1,EF_R32G32B32A32_SFLOAT,sizeof(S3DLineVertex), offsetof(S3DLineVertex, Color[0])); m_meshBuffer->setMeshDataAndFormat(std::move(m_desc)); } void CDraw3DLine::draw( float fromX, float fromY, float fromZ, float toX, float toY, float toZ, float r, float g, float b, float a) { S3DLineVertex vertices[2] = { {{ fromX, fromY, fromZ }, { r, g, b, a }}, {{ toX, toY, toZ }, { r, g, b, a }} }; auto upStreamBuff = m_driver->getDefaultUpStreamingBuffer(); void* lineData[1] = { vertices }; static const uint32_t sizes[1] = { sizeof(S3DLineVertex) * 2 }; uint32_t offset[1] = { video::StreamingTransientDataBufferMT<>::invalid_address }; upStreamBuff->multi_place(1u, (const void* const*)lineData, (uint32_t*)&offset,(uint32_t*)&sizes,(uint32_t*)&alignments); if (upStreamBuff->needsManualFlushOrInvalidate()) { auto upStreamMem = upStreamBuff->getBuffer()->getBoundMemory(); m_driver->flushMappedMemoryRanges({{ upStreamMem,offset[0],sizes[0] }}); } m_meshBuffer->setBaseVertex(offset[0]/sizeof(S3DLineVertex)); m_driver->setTransform(E4X3TS_WORLD, core::matrix3x4SIMD()); m_driver->setMaterial(m_material); m_driver->drawMeshBuffer(m_meshBuffer.get()); upStreamBuff->multi_free(1u,(uint32_t*)&offset,(uint32_t*)&sizes,std::move(m_driver->placeFence())); } void CDraw3DLine::draw(const core::vector<std::pair<S3DLineVertex, S3DLineVertex>>& linesData) { auto upStreamBuff = m_driver->getDefaultUpStreamingBuffer(); const void* lineData[1] = { linesData.data() }; const uint32_t sizes[1] = { sizeof(S3DLineVertex) * linesData.size() * 2 }; uint32_t offset[1] = { video::StreamingTransientDataBufferMT<>::invalid_address }; upStreamBuff->multi_place(1u, (const void* const*)lineData, (uint32_t*)&offset,(uint32_t*)&sizes,(uint32_t*)&alignments); if (upStreamBuff->needsManualFlushOrInvalidate()) { auto upStreamMem = upStreamBuff->getBuffer()->getBoundMemory(); m_driver->flushMappedMemoryRanges({{ upStreamMem,offset[0],sizes[0] }}); } m_meshBuffer->setBaseVertex(offset[0]/sizeof(S3DLineVertex)); m_meshBuffer->setIndexCount(linesData.size() * 2); m_driver->setTransform(E4X3TS_WORLD, core::matrix3x4SIMD()); m_driver->setMaterial(m_material); m_driver->drawMeshBuffer(m_meshBuffer.get()); upStreamBuff->multi_free(1u,(uint32_t*)&offset,(uint32_t*)&sizes,std::move(m_driver->placeFence())); }
41
153
0.719897
[ "vector" ]
5d573f2d9543ed2d053019cab83d64564520a868
2,777
cpp
C++
tree.cpp
raviMaurya12/snippets-1
9846c8cf7e751f53b74531c19174bdf6874c1eea
[ "Unlicense" ]
2
2020-07-29T19:26:58.000Z
2020-07-30T19:37:34.000Z
tree.cpp
duckladydinh/snippets
f793a9062fae9183fc0812d40cde5cc70728b7a0
[ "Unlicense" ]
null
null
null
tree.cpp
duckladydinh/snippets
f793a9062fae9183fc0812d40cde5cc70728b7a0
[ "Unlicense" ]
null
null
null
// Common algorithms on trees // // To initialize, call dfs(root, -1). // // Globals: // - N is the number of nodes // - length[x] is the cost of the edge between x and it's parent // - adj[x] is a list of nodes adjacent to x // - jump[x][i] is the 2^i-th ancestor of x, or -1 if it doesn't exist // - depth[x] is the depth of node x (depth of the root is 0) // - dist[x] is the cost of the path from root to x // - discovery[x] is the discovery time in DFS order of the tree // - finish[x] is the finish time in DFS order of the tree // // Functions: // - dfs(root, -1) is used to initialize the globals // - is_ancestor(x, y) return true if x is an ancestor of y // - lca(x, y) returns the lowest common ancestor of x and y // - distance(x, y) returns the cost of the path between x and y // - num_edges(x, y) returns the number of edges on the path between x and y // - relative_child(x, y) returns the child of x on the path from x to it's descendant y // - kth(x, y, k) returns the k-th node on the path from x to y // // Time complexities: // - dfs: O(N) // - is_ancestor: O(1) // - lca: O(log N) // - distance: O(1) // - num_edges: O(1) // - relative_child: O(log N) // - kth: O(log N) // // Constants to configure: // - MAX is the maximum number of nodes // - LG is ceil(log2(MAX)) int N; llint length[MAX]; vector<int> adj[MAX]; int jump[MAX][LG]; int depth[MAX]; llint dist[MAX]; int tick; int discovery[MAX]; int finish[MAX]; void dfs(int x, int dad) { jump[x][0] = dad == -1 ? x : dad; FOR(i, 1, LG) jump[x][i] = jump[ jump[x][i-1] ][i-1]; discovery[x] = tick++; for (int y : adj[x]) { if (y == dad) continue; depth[y] = depth[x] + 1; dist[y] = dist[x] + length[y]; dfs(y, x); } finish[x] = tick++; } bool is_ancestor(int x, int y) { return discovery[x] <= discovery[y] && finish[y] <= finish[x]; } int lca(int x, int y) { if (is_ancestor(x, y)) return x; for (int i = LG-1; i >= 0; --i) if (!is_ancestor(jump[x][i], y)) x = jump[x][i]; return jump[x][0]; } llint distance(int x, int y) { return dist[x] + dist[y] - 2 * dist[lca(x, y)]; } int num_edges(int x, int y) { return depth[x] + depth[y] - 2 * depth[lca(x, y)]; } int relative_child(int x, int y) { assert(x != y); if (!is_ancestor(x, y)) return jump[x][0]; for (int i = LG-1; i >= 0; --i) if (depth[y] - (1<<i) > depth[x]) y = jump[y][i]; return y; } int kth(int x, int y, int k) { int p = lca(x, y); int d = num_edges(x, y); for (int i = LG-1; i >= 0; --i) { if (depth[x] - (1<<i) >= depth[p] && k - (1<<i) >= 0) { d -= 1<<i; k -= 1<<i; x = jump[x][i]; } if (depth[y] - (1<<i) >= depth[p] && d - (1<<i) >= k) { d -= 1<<i; y = jump[y][i]; } } return k == 0 ? x : y; }
25.018018
88
0.561757
[ "vector" ]
5d58f918d88106e53ce52a44f428f1f933dcfbfb
1,989
hpp
C++
include/msg/MessageMergeProcess.hpp
Yhgenomics/maraton-cli
64e982f46b12e3fabe3881d5c42872c259e21dca
[ "MIT" ]
null
null
null
include/msg/MessageMergeProcess.hpp
Yhgenomics/maraton-cli
64e982f46b12e3fabe3881d5c42872c259e21dca
[ "MIT" ]
null
null
null
include/msg/MessageMergeProcess.hpp
Yhgenomics/maraton-cli
64e982f46b12e3fabe3881d5c42872c259e21dca
[ "MIT" ]
null
null
null
#ifndef MESSAGE_MERGE_PROCESS_HPP_ #define MESSAGE_MERGE_PROCESS_HPP_ #include "Message.h" #include "json.hpp" #include <string> using namespace std; namespace Protocol { class MessageMergeProcess : public Message { public: // Getter of task_id_ string task_id() { return task_id_; } // Setter of task_id_ void task_id( string value ) { task_id_ = value; raw_data_[ "data" ][ "task_id" ] = value; } // Getter of uri_list_ vector<std::string> uri_list() { return uri_list_; } // Setter of uri_list_ void uri_list( vector<std::string> value ) { uri_list_ = value; raw_data_[ "data" ][ "uri_list" ] = value; } // Getter of merger_ string merger() { return merger_; } // Setter of merger_ void merger( string value ) { merger_ = value; raw_data_[ "data" ][ "merger" ] = value; } // Serilize Constructor MessageMergeProcess() : Message( PROTOCOL_VERSION , 171 , 0 ) { task_id( "" ); uri_list( ); merger( "" ); } // Deserilize Constructor MessageMergeProcess( Message* message ) : Message( *message ) { this->task_id_ = raw_data_[ "data" ][ "task_id" ].get<string>(); this->uri_list_ = raw_data_[ "data" ][ "uri_list" ].get<vector<std::string>>(); this->merger_ = raw_data_[ "data" ][ "merger" ].get<string>(); } private: string task_id_; vector<std::string> uri_list_; string merger_; }; // End of class define of MessageMergeProcess } // End of namespace Protocol #endif // !Message_Merge_Process_HPP_
24.256098
91
0.498743
[ "vector" ]
5d5acdc8cd1058f5c4504497d540bacf6e98f2e4
5,112
hpp
C++
include/operon/interpreter/interpreter.hpp
lf-shaw/operon
09a6ac1932d552b8be505f235318e50e923b0da1
[ "MIT" ]
50
2020-10-14T10:08:21.000Z
2022-03-10T12:55:05.000Z
include/operon/interpreter/interpreter.hpp
lf-shaw/operon
09a6ac1932d552b8be505f235318e50e923b0da1
[ "MIT" ]
16
2020-10-26T13:05:47.000Z
2022-02-22T20:24:41.000Z
include/operon/interpreter/interpreter.hpp
lf-shaw/operon
09a6ac1932d552b8be505f235318e50e923b0da1
[ "MIT" ]
16
2020-10-26T13:05:38.000Z
2022-01-14T02:52:13.000Z
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: Copyright 2019-2021 Heal Research #ifndef OPERON_INTERPRETER_HPP #define OPERON_INTERPRETER_HPP #include <algorithm> #include <optional> #include "core/dataset.hpp" #include "core/tree.hpp" #include "core/types.hpp" #include "interpreter/dispatch_table.hpp" namespace Operon { template<typename T> using Span = nonstd::span<T>; struct Interpreter { Interpreter(DispatchTable const& ft) : ftable(ft) { } Interpreter(DispatchTable&& ft) : ftable(std::move(ft)) { } Interpreter() : Interpreter(DispatchTable{}) { } // evaluate a tree and return a vector of values template <typename T> Operon::Vector<T> Evaluate(Tree const& tree, Dataset const& dataset, Range const range, T const* const parameters = nullptr) const noexcept { Operon::Vector<T> result(range.Size()); Evaluate<T>(tree, dataset, range, Operon::Span<T>(result), parameters); return result; } template <typename T> Operon::Vector<T> Evaluate(Tree const& tree, Dataset const& dataset, Range const range, size_t const batchSize, T const* const parameters = nullptr) const noexcept { Operon::Vector<T> result(range.Size()); Operon::Span<T> view(result); size_t n = range.Size() / batchSize; size_t m = range.Size() % batchSize; std::vector<size_t> indices(n + (m != 0)); std::iota(indices.begin(), indices.end(), 0ul); std::for_each(indices.begin(), indices.end(), [&](auto idx) { auto start = range.Start() + idx * batchSize; auto end = std::min(start + batchSize, range.End()); auto subview = view.subspan(idx * batchSize, end - start); Evaluate(tree, dataset, Range { start, end }, subview, parameters); }); return result; } template <typename T> void Evaluate(Tree const& tree, Dataset const& dataset, Range const range, Operon::Span<T> result, T const* const parameters = nullptr) const noexcept { const auto& nodes = tree.Nodes(); EXPECT(nodes.size() > 0); constexpr int S = static_cast<int>(detail::batch_size<T>::value); using M = Eigen::Array<T, S, Eigen::Dynamic, Eigen::ColMajor>; M m = M::Zero(S, nodes.size()); Eigen::Map<Eigen::Array<T, Eigen::Dynamic, 1, Eigen::ColMajor>> res(result.data(), result.size(), 1); struct NodeMeta { T param; Operon::Span<Operon::Scalar const> values; std::optional<DispatchTable::Callable<T> const> func; }; Operon::Vector<NodeMeta> meta; meta.reserve(nodes.size()); size_t idx = 0; for (size_t i = 0; i < nodes.size(); ++i) { auto const& n = nodes[i]; if (n.IsLeaf()) { auto v = parameters ? parameters[idx++] : T{n.Value}; Operon::Span<Operon::Scalar const> vals{}; if (n.IsConstant()) { m.col(i).setConstant(v); } if (n.IsVariable()) { vals = dataset.GetValues(n.HashValue).subspan(range.Start(), range.Size()); } meta.push_back({ v, vals, std::nullopt }); } else { meta.push_back({ T{}, {}, std::make_optional(ftable.Get<T>(n.HashValue)) }); } } auto lastCol = m.col(nodes.size() - 1); int numRows = static_cast<int>(range.Size()); for (int row = 0; row < numRows; row += S) { auto remainingRows = std::min(S, numRows - row); for (size_t i = 0; i < nodes.size(); ++i) { auto const& s = nodes[i]; auto const& [ param, values, func ] = meta[i]; if (s.Arity) { func.value()(m, nodes, i, range.Start() + row); } else if (s.IsVariable()) { Eigen::Map<const Eigen::Array<Operon::Scalar, Eigen::Dynamic, 1, Eigen::ColMajor>> seg(values.data() + row, remainingRows); m.col(i).segment(0, remainingRows) = meta[i].param * seg.cast<T>(); } } // the final result is found in the last section of the buffer corresponding to the root node res.segment(row, remainingRows) = lastCol.segment(0, remainingRows); } } template<typename T> static void Evaluate(DispatchTable& ft, Tree const& tree, Dataset const& dataset, Range const range, Operon::Span<T> result, T const* const parameters = nullptr) noexcept { Interpreter interpreter(ft); interpreter.Evaluate(tree, dataset, range, result, parameters); } template<typename T> static Operon::Vector<T> Evaluate(DispatchTable& ft, Tree const& tree, Dataset const& dataset, Range const range, T const* const parameters = nullptr) { Interpreter interpreter(ft); return interpreter.Evaluate(tree, dataset, range, parameters); } DispatchTable& GetDispatchTable() { return ftable; } DispatchTable const& GetDispatchTable() const { return ftable; } private: DispatchTable ftable; }; }; #endif
37.588235
176
0.597418
[ "vector" ]
5d5cffd40bedcd90d1aa1bd45518475652b6f2ee
2,709
hpp
C++
sw/3rd_party/VTK-7.1.0/ThirdParty/xdmf3/vtkxdmf3/core/XdmfSharedPtr.hpp
esean/stl_voro_fill
c569a4019ff80afbf85482c7193711ea85a7cafb
[ "MIT" ]
4
2019-05-30T01:52:12.000Z
2021-09-29T21:12:13.000Z
sw/3rd_party/VTK-7.1.0/ThirdParty/xdmf3/vtkxdmf3/core/XdmfSharedPtr.hpp
esean/stl_voro_fill
c569a4019ff80afbf85482c7193711ea85a7cafb
[ "MIT" ]
null
null
null
sw/3rd_party/VTK-7.1.0/ThirdParty/xdmf3/vtkxdmf3/core/XdmfSharedPtr.hpp
esean/stl_voro_fill
c569a4019ff80afbf85482c7193711ea85a7cafb
[ "MIT" ]
2
2019-08-30T23:36:13.000Z
2019-11-08T16:52:01.000Z
/*****************************************************************************/ /* XDMF */ /* eXtensible Data Model and Format */ /* */ /* Id : XdmfSharedPtr.hpp */ /* */ /* Author: */ /* Kenneth Leiter */ /* kenneth.leiter@arl.army.mil */ /* US Army Research Laboratory */ /* Aberdeen Proving Ground, MD */ /* */ /* Copyright @ 2011 US Army Research Laboratory */ /* All Rights Reserved */ /* See Copyright.txt for details */ /* */ /* This software is distributed WITHOUT ANY WARRANTY; without */ /* even the implied warranty of MERCHANTABILITY or FITNESS */ /* FOR A PARTICULAR PURPOSE. See the above copyright notice */ /* for more information. */ /* */ /*****************************************************************************/ #ifndef XDMFSHAREDPTR_HPP_ #define XDMFSHAREDPTR_HPP_ #ifdef __cplusplus #include "XdmfCoreConfig.hpp" #include <boost/shared_ptr.hpp> using boost::shared_ptr; #ifdef HAVE_BOOST_SHARED_DYNAMIC_CAST using boost::shared_dynamic_cast; #else template <typename T, typename U> shared_ptr<T> shared_dynamic_cast(shared_ptr<U> const & r) { typedef typename shared_ptr<T>::element_type E; E * p = dynamic_cast< E* >( r.get() ); return p? shared_ptr<T>( r, p ): shared_ptr<T>(); } #endif /* HAVE_BOOST_SHARED_DYNAMIC_CAST */ // Used by C wrappers to prevent shared pointers from prematurely deleting objects // Normally this would be completely against the point of shared pointers, // but the C wrapping requires that objects be seperated from the shared pointers. struct XdmfNullDeleter { template<typename T> void operator()(T*) {} }; #endif #endif /* XDMFSHAREDPTR_HPP_ */
43.693548
84
0.388335
[ "model" ]
5d613c90dc95cb2cb27c99b3eafa3ab3fccfee32
47,217
cpp
C++
apps/yocto_opengl.cpp
erez-o/yocto-gl
b722ae746433369ec891a5cd5b1975953951c491
[ "MIT" ]
2
2020-10-16T06:05:27.000Z
2021-03-31T03:58:56.000Z
apps/yocto_opengl.cpp
erez-o/yocto-gl
b722ae746433369ec891a5cd5b1975953951c491
[ "MIT" ]
null
null
null
apps/yocto_opengl.cpp
erez-o/yocto-gl
b722ae746433369ec891a5cd5b1975953951c491
[ "MIT" ]
null
null
null
// // Utilities to use OpenGL 3, GLFW and ImGui. // // // LICENSE: // // Copyright (c) 2016 -- 2019 Fabio Pellacini // // 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 "yocto_opengl.h" #include <stdarg.h> #include <algorithm> #include <atomic> #include <mutex> #ifdef __APPLE__ #define GL_SILENCE_DEPRECATION #endif #include "ext/glad/glad.h" #include <GLFW/glfw3.h> #include "ext/imgui/imgui.h" #include "ext/imgui/imgui_impl_glfw.h" #include "ext/imgui/imgui_impl_opengl3.h" #include "ext/imgui/imgui_internal.h" #define CUTE_FILES_IMPLEMENTATION #include "ext/cute_files.h" // ----------------------------------------------------------------------------- // PATH UTILITIES // ----------------------------------------------------------------------------- namespace yocto { static inline string normalize_path(const string& filename_) { auto filename = filename_; for (auto& c : filename) if (c == '\\') c = '/'; if (filename.size() > 1 && filename[0] == '/' && filename[1] == '/') { throw std::invalid_argument("absolute paths are not supported"); return filename_; } if (filename.size() > 3 && filename[1] == ':' && filename[2] == '/' && filename[3] == '/') { throw std::invalid_argument("absolute paths are not supported"); return filename_; } auto pos = (size_t)0; while ((pos = filename.find("//")) != filename.npos) filename = filename.substr(0, pos) + filename.substr(pos + 1); return filename; } // Get extension (not including '.'). static inline string get_extension(const string& filename_) { auto filename = normalize_path(filename_); auto pos = filename.rfind('.'); if (pos == string::npos) return ""; return filename.substr(pos + 1); } } // namespace yocto namespace yocto { void check_glerror() { if (glGetError() != GL_NO_ERROR) printf("gl error\n"); } void clear_glframebuffer(const vec4f& color, bool clear_depth) { glClearColor(color.x, color.y, color.z, color.w); if (clear_depth) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnable(GL_DEPTH_TEST); } else { glClear(GL_COLOR_BUFFER_BIT); } } void set_glviewport(const vec4i& viewport) { glViewport(viewport.x, viewport.y, viewport.z, viewport.w); } void set_glwireframe(bool enabled) { if (enabled) glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); else glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); } void set_glblending(bool enabled) { if (enabled) { glEnable(GL_BLEND); glBlendEquationSeparate(GL_FUNC_ADD, GL_FUNC_ADD); glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO); } else { glDisable(GL_BLEND); } } void init_glprogram( opengl_program& program, const char* vertex, const char* fragment) { assert(glGetError() == GL_NO_ERROR); glGenVertexArrays(1, &program.vertex_array_object_id); glBindVertexArray(program.vertex_array_object_id); assert(glGetError() == GL_NO_ERROR); int errflags; char errbuf[10000]; // create vertex assert(glGetError() == GL_NO_ERROR); program.vertex_shader_id = glCreateShader(GL_VERTEX_SHADER); glShaderSource(program.vertex_shader_id, 1, &vertex, NULL); glCompileShader(program.vertex_shader_id); glGetShaderiv(program.vertex_shader_id, GL_COMPILE_STATUS, &errflags); if (!errflags) { glGetShaderInfoLog(program.vertex_shader_id, 10000, 0, errbuf); throw std::runtime_error("shader not compiled with error\n"s + errbuf); } assert(glGetError() == GL_NO_ERROR); // create fragment assert(glGetError() == GL_NO_ERROR); program.fragment_shader_id = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(program.fragment_shader_id, 1, &fragment, NULL); glCompileShader(program.fragment_shader_id); glGetShaderiv(program.fragment_shader_id, GL_COMPILE_STATUS, &errflags); if (!errflags) { glGetShaderInfoLog(program.fragment_shader_id, 10000, 0, errbuf); throw std::runtime_error("shader not compiled with error\n"s + errbuf); } assert(glGetError() == GL_NO_ERROR); // create program assert(glGetError() == GL_NO_ERROR); program.program_id = glCreateProgram(); glAttachShader(program.program_id, program.vertex_shader_id); glAttachShader(program.program_id, program.fragment_shader_id); glLinkProgram(program.program_id); glValidateProgram(program.program_id); glGetProgramiv(program.program_id, GL_LINK_STATUS, &errflags); if (!errflags) { glGetProgramInfoLog(program.program_id, 10000, 0, errbuf); throw std::runtime_error("program not linked with error\n"s + errbuf); } glGetProgramiv(program.program_id, GL_VALIDATE_STATUS, &errflags); if (!errflags) { glGetProgramInfoLog(program.program_id, 10000, 0, errbuf); throw std::runtime_error("program not linked with error\n"s + errbuf); } assert(glGetError() == GL_NO_ERROR); } void delete_glprogram(opengl_program& program) { if (!program) return; glDeleteProgram(program.program_id); glDeleteShader(program.vertex_shader_id); glDeleteShader(program.fragment_shader_id); program = {}; } void init_gltexture(opengl_texture& texture, const vec2i& size, bool as_float, bool as_srgb, bool linear, bool mipmap) { texture = opengl_texture(); assert(glGetError() == GL_NO_ERROR); glGenTextures(1, &texture.texture_id); texture.size = size; glBindTexture(GL_TEXTURE_2D, texture.texture_id); if (as_float) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, size.x, size.y, 0, GL_RGBA, GL_FLOAT, nullptr); } else if (as_srgb) { glTexImage2D(GL_TEXTURE_2D, 0, GL_SRGB_ALPHA, size.x, size.y, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); } else { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, size.x, size.y, 0, GL_RGBA, GL_FLOAT, nullptr); } if (mipmap) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, (linear) ? GL_LINEAR_MIPMAP_LINEAR : GL_NEAREST_MIPMAP_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, (linear) ? GL_LINEAR : GL_NEAREST); } else { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, (linear) ? GL_LINEAR : GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, (linear) ? GL_LINEAR : GL_NEAREST); } assert(glGetError() == GL_NO_ERROR); } void update_gltexture( opengl_texture& texture, const image<vec4f>& img, bool mipmap) { assert(glGetError() == GL_NO_ERROR); glBindTexture(GL_TEXTURE_2D, texture.texture_id); glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, img.size().x, img.size().y, GL_RGBA, GL_FLOAT, img.data()); if (mipmap) glGenerateMipmap(GL_TEXTURE_2D); assert(glGetError() == GL_NO_ERROR); } void update_gltexture_region(opengl_texture& texture, const image<vec4f>& img, const image_region& region, bool mipmap) { assert(glGetError() == GL_NO_ERROR); glBindTexture(GL_TEXTURE_2D, texture.texture_id); auto clipped = image<vec4f>{}; get_region(clipped, img, region); glTexSubImage2D(GL_TEXTURE_2D, 0, region.min.x, region.min.y, region.size().x, region.size().y, GL_RGBA, GL_FLOAT, clipped.data()); if (mipmap) glGenerateMipmap(GL_TEXTURE_2D); assert(glGetError() == GL_NO_ERROR); } void update_gltexture( opengl_texture& texture, const image<vec4b>& img, bool mipmap) { assert(glGetError() == GL_NO_ERROR); glBindTexture(GL_TEXTURE_2D, texture.texture_id); glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, img.size().x, img.size().y, GL_RGBA, GL_UNSIGNED_BYTE, img.data()); if (mipmap) glGenerateMipmap(GL_TEXTURE_2D); assert(glGetError() == GL_NO_ERROR); } void update_gltexture_region(opengl_texture& texture, const image<vec4b>& img, const image_region& region, bool mipmap) { assert(glGetError() == GL_NO_ERROR); glBindTexture(GL_TEXTURE_2D, texture.texture_id); auto clipped = image<vec4b>{}; get_region(clipped, img, region); glTexSubImage2D(GL_TEXTURE_2D, 0, region.min.x, region.min.y, region.size().x, region.size().y, GL_RGBA, GL_UNSIGNED_BYTE, clipped.data()); if (mipmap) glGenerateMipmap(GL_TEXTURE_2D); assert(glGetError() == GL_NO_ERROR); } void delete_gltexture(opengl_texture& texture) { if (!texture) return; glDeleteTextures(1, &texture.texture_id); texture = {}; } template <typename T> void init_glarray_buffer_impl( opengl_arraybuffer& buffer, const vector<T>& array, bool dynamic) { buffer = opengl_arraybuffer{}; buffer.num = size(array); buffer.elem_size = sizeof(T); assert(glGetError() == GL_NO_ERROR); glGenBuffers(1, &buffer.buffer_id); glBindBuffer(GL_ARRAY_BUFFER, buffer.buffer_id); glBufferData(GL_ARRAY_BUFFER, size(array) * sizeof(T), array.data(), (dynamic) ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW); assert(glGetError() == GL_NO_ERROR); } void init_glarraybuffer( opengl_arraybuffer& buffer, const vector<float>& data, bool dynamic) { init_glarray_buffer_impl(buffer, data, dynamic); } void init_glarraybuffer( opengl_arraybuffer& buffer, const vector<vec2f>& data, bool dynamic) { init_glarray_buffer_impl(buffer, data, dynamic); } void init_glarraybuffer( opengl_arraybuffer& buffer, const vector<vec3f>& data, bool dynamic) { init_glarray_buffer_impl(buffer, data, dynamic); } void init_glarraybuffer( opengl_arraybuffer& buffer, const vector<vec4f>& data, bool dynamic) { init_glarray_buffer_impl(buffer, data, dynamic); } void delete_glarraybuffer(opengl_arraybuffer& buffer) { if (!buffer) return; glDeleteBuffers(1, &buffer.buffer_id); buffer = {}; } template <typename T> void init_glelementbuffer_impl( opengl_elementbuffer& buffer, const vector<T>& array, bool dynamic) { buffer = opengl_elementbuffer{}; buffer.num = size(array); buffer.elem_size = sizeof(T); assert(glGetError() == GL_NO_ERROR); glGenBuffers(1, &buffer.buffer_id); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer.buffer_id); glBufferData(GL_ELEMENT_ARRAY_BUFFER, size(array) * sizeof(T), array.data(), (dynamic) ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW); assert(glGetError() == GL_NO_ERROR); } void init_glelementbuffer( opengl_elementbuffer& buffer, const vector<int>& data, bool dynamic) { init_glelementbuffer_impl(buffer, data, dynamic); } void init_glelementbuffer( opengl_elementbuffer& buffer, const vector<vec2i>& data, bool dynamic) { init_glelementbuffer_impl(buffer, data, dynamic); } void init_glelementbuffer( opengl_elementbuffer& buffer, const vector<vec3i>& data, bool dynamic) { init_glelementbuffer_impl(buffer, data, dynamic); } void delete_glelementbuffer(opengl_elementbuffer& buffer) { if (!buffer) return; glDeleteBuffers(1, &buffer.buffer_id); buffer = {}; } void bind_glprogram(opengl_program& program) { glUseProgram(program.program_id); } void unbind_opengl_program() { glUseProgram(0); } int get_gluniform_location(const opengl_program& program, const char* name) { return glGetUniformLocation(program.program_id, name); } void set_gluniform(int locatiom, int value) { assert(glGetError() == GL_NO_ERROR); glUniform1i(locatiom, value); assert(glGetError() == GL_NO_ERROR); } void set_gluniform(int locatiom, const vec2i& value) { assert(glGetError() == GL_NO_ERROR); glUniform2i(locatiom, value.x, value.y); assert(glGetError() == GL_NO_ERROR); } void set_gluniform(int locatiom, const vec3i& value) { assert(glGetError() == GL_NO_ERROR); glUniform3i(locatiom, value.x, value.y, value.z); assert(glGetError() == GL_NO_ERROR); } void set_gluniform(int locatiom, const vec4i& value) { assert(glGetError() == GL_NO_ERROR); glUniform4i(locatiom, value.x, value.y, value.z, value.w); assert(glGetError() == GL_NO_ERROR); } void set_gluniform(int locatiom, float value) { assert(glGetError() == GL_NO_ERROR); glUniform1f(locatiom, value); assert(glGetError() == GL_NO_ERROR); } void set_gluniform(int locatiom, const vec2f& value) { assert(glGetError() == GL_NO_ERROR); glUniform2f(locatiom, value.x, value.y); assert(glGetError() == GL_NO_ERROR); } void set_gluniform(int locatiom, const vec3f& value) { assert(glGetError() == GL_NO_ERROR); glUniform3f(locatiom, value.x, value.y, value.z); assert(glGetError() == GL_NO_ERROR); } void set_gluniform(int locatiom, const vec4f& value) { assert(glGetError() == GL_NO_ERROR); glUniform4f(locatiom, value.x, value.y, value.z, value.w); assert(glGetError() == GL_NO_ERROR); } void set_gluniform(int locatiom, const mat4f& value) { assert(glGetError() == GL_NO_ERROR); glUniformMatrix4fv(locatiom, 1, false, &value.x.x); assert(glGetError() == GL_NO_ERROR); } void set_gluniform(int locatiom, const frame3f& value) { assert(glGetError() == GL_NO_ERROR); glUniformMatrix4x3fv(locatiom, 1, false, &value.x.x); assert(glGetError() == GL_NO_ERROR); } void set_gluniform_texture( int locatiom, const opengl_texture& texture, int unit) { assert(glGetError() == GL_NO_ERROR); glActiveTexture(GL_TEXTURE0 + unit); glBindTexture(GL_TEXTURE_2D, texture.texture_id); glUniform1i(locatiom, unit); assert(glGetError() == GL_NO_ERROR); } void set_gluniform_texture(opengl_program& program, const char* name, const opengl_texture& texture, int unit) { set_gluniform_texture(get_gluniform_location(program, name), texture, unit); } void set_gluniform_texture( int locatiom, int locatiom_on, const opengl_texture& texture, int unit) { assert(glGetError() == GL_NO_ERROR); if (texture.texture_id) { glActiveTexture(GL_TEXTURE0 + unit); glBindTexture(GL_TEXTURE_2D, texture.texture_id); glUniform1i(locatiom, unit); glUniform1i(locatiom_on, 1); } else { glUniform1i(locatiom_on, 0); } assert(glGetError() == GL_NO_ERROR); } void set_gluniform_texture(opengl_program& program, const char* name, const char* name_on, const opengl_texture& texture, int unit) { set_gluniform_texture(get_gluniform_location(program, name), get_gluniform_location(program, name_on), texture, unit); } int get_glvertexattrib_location( const opengl_program& program, const char* name) { return glGetAttribLocation(program.program_id, name); } void set_glvertexattrib( int locatiom, const opengl_arraybuffer& buffer, float value) { assert(glGetError() == GL_NO_ERROR); if (buffer.buffer_id) { glBindBuffer(GL_ARRAY_BUFFER, buffer.buffer_id); glEnableVertexAttribArray(locatiom); glVertexAttribPointer(locatiom, 1, GL_FLOAT, false, 0, nullptr); } else { glVertexAttrib1f(locatiom, value); } assert(glGetError() == GL_NO_ERROR); } void set_glvertexattrib( int locatiom, const opengl_arraybuffer& buffer, const vec2f& value) { assert(glGetError() == GL_NO_ERROR); if (buffer.buffer_id) { glBindBuffer(GL_ARRAY_BUFFER, buffer.buffer_id); glEnableVertexAttribArray(locatiom); glVertexAttribPointer(locatiom, 2, GL_FLOAT, false, 0, nullptr); } else { glVertexAttrib2f(locatiom, value.x, value.y); } assert(glGetError() == GL_NO_ERROR); } void set_glvertexattrib( int locatiom, const opengl_arraybuffer& buffer, const vec3f& value) { assert(glGetError() == GL_NO_ERROR); if (buffer.buffer_id) { glBindBuffer(GL_ARRAY_BUFFER, buffer.buffer_id); glEnableVertexAttribArray(locatiom); glVertexAttribPointer(locatiom, 3, GL_FLOAT, false, 0, nullptr); } else { glVertexAttrib3f(locatiom, value.x, value.y, value.z); } assert(glGetError() == GL_NO_ERROR); } void set_glvertexattrib( int locatiom, const opengl_arraybuffer& buffer, const vec4f& value) { assert(glGetError() == GL_NO_ERROR); if (buffer.buffer_id) { glBindBuffer(GL_ARRAY_BUFFER, buffer.buffer_id); glEnableVertexAttribArray(locatiom); glVertexAttribPointer(locatiom, 4, GL_FLOAT, false, 0, nullptr); } else { glVertexAttrib4f(locatiom, value.x, value.y, value.z, value.w); } assert(glGetError() == GL_NO_ERROR); } void draw_glpoints(const opengl_elementbuffer& buffer, int num) { glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer.buffer_id); glDrawElements(GL_POINTS, num, GL_UNSIGNED_INT, nullptr); } void draw_gllines(const opengl_elementbuffer& buffer, int num) { glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer.buffer_id); glDrawElements(GL_LINES, num * 2, GL_UNSIGNED_INT, nullptr); } void draw_gltriangles(const opengl_elementbuffer& buffer, int num) { glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer.buffer_id); glDrawElements(GL_TRIANGLES, num * 3, GL_UNSIGNED_INT, nullptr); } void draw_glimage(const opengl_texture& texture, int win_width, int win_height, const vec2f& image_center, float image_scale) { static opengl_program gl_prog = {}; static opengl_arraybuffer gl_texcoord = {}; static opengl_elementbuffer gl_triangles = {}; // initialization if (!gl_prog) { auto vert = R"( #version 330 in vec2 texcoord; out vec2 frag_texcoord; uniform vec2 window_size, image_size; uniform vec2 image_center; uniform float image_scale; void main() { vec2 pos = (texcoord - vec2(0.5,0.5)) * image_size * image_scale + image_center; gl_Position = vec4(2 * pos.x / window_size.x - 1, 1 - 2 * pos.y / window_size.y, 0, 1); frag_texcoord = texcoord; } )"; auto frag = R"( #version 330 in vec2 frag_texcoord; out vec4 frag_color; uniform sampler2D txt; void main() { frag_color = texture(txt, frag_texcoord); } )"; init_glprogram(gl_prog, vert, frag); init_glarraybuffer( gl_texcoord, vector<vec2f>{{0, 0}, {0, 1}, {1, 1}, {1, 0}}, false); init_glelementbuffer( gl_triangles, vector<vec3i>{{0, 1, 2}, {0, 2, 3}}, false); } // draw check_glerror(); bind_glprogram(gl_prog); set_gluniform_texture(gl_prog, "txt", texture, 0); set_gluniform( gl_prog, "window_size", vec2f{(float)win_width, (float)win_height}); set_gluniform(gl_prog, "image_size", vec2f{(float)texture.size.x, (float)texture.size.y}); set_gluniform(gl_prog, "image_center", image_center); set_gluniform(gl_prog, "image_scale", image_scale); set_glvertexattrib(gl_prog, "texcoord", gl_texcoord, zero2f); draw_gltriangles(gl_triangles, 2); unbind_opengl_program(); check_glerror(); } void draw_glimage_background(const opengl_texture& texture, int win_width, int win_height, const vec2f& image_center, float image_scale, float border_size) { static opengl_program gl_prog = {}; static opengl_arraybuffer gl_texcoord = {}; static opengl_elementbuffer gl_triangles = {}; // initialization if (!gl_prog) { auto vert = R"( #version 330 in vec2 texcoord; out vec2 frag_texcoord; uniform vec2 window_size, image_size, border_size; uniform vec2 image_center; uniform float image_scale; void main() { vec2 pos = (texcoord - vec2(0.5,0.5)) * (image_size + border_size*2) * image_scale + image_center; gl_Position = vec4(2 * pos.x / window_size.x - 1, 1 - 2 * pos.y / window_size.y, 0.1, 1); frag_texcoord = texcoord; } )"; auto frag = R"( #version 330 in vec2 frag_texcoord; out vec4 frag_color; uniform vec2 image_size, border_size; uniform float image_scale; void main() { ivec2 imcoord = ivec2(frag_texcoord * (image_size + border_size*2) - border_size); ivec2 tilecoord = ivec2(frag_texcoord * (image_size + border_size*2) * image_scale - border_size); ivec2 tile = tilecoord / 16; if(imcoord.x <= 0 || imcoord.y <= 0 || imcoord.x >= image_size.x || imcoord.y >= image_size.y) frag_color = vec4(0,0,0,1); else if((tile.x + tile.y) % 2 == 0) frag_color = vec4(0.1,0.1,0.1,1); else frag_color = vec4(0.3,0.3,0.3,1); } )"; init_glprogram(gl_prog, vert, frag); init_glarraybuffer( gl_texcoord, vector<vec2f>{{0, 0}, {0, 1}, {1, 1}, {1, 0}}, false); init_glelementbuffer( gl_triangles, vector<vec3i>{{0, 1, 2}, {0, 2, 3}}, false); } // draw bind_glprogram(gl_prog); set_gluniform( gl_prog, "window_size", vec2f{(float)win_width, (float)win_height}); set_gluniform(gl_prog, "image_size", vec2f{(float)texture.size.x, (float)texture.size.y}); set_gluniform( gl_prog, "border_size", vec2f{(float)border_size, (float)border_size}); set_gluniform(gl_prog, "image_center", image_center); set_gluniform(gl_prog, "image_scale", image_scale); set_glvertexattrib(gl_prog, "texcoord", gl_texcoord, zero2f); draw_gltriangles(gl_triangles, 2); unbind_opengl_program(); } void _glfw_refresh_callback(GLFWwindow* glfw) { auto& win = *(const opengl_window*)glfwGetWindowUserPointer(glfw); if (win.refresh_cb) win.refresh_cb(win); } void _glfw_drop_callback(GLFWwindow* glfw, int num, const char** paths) { auto& win = *(const opengl_window*)glfwGetWindowUserPointer(glfw); if (win.drop_cb) { auto pathv = vector<string>(); for (auto i = 0; i < num; i++) pathv.push_back(paths[i]); win.drop_cb(win, pathv); } } void init_glwindow(opengl_window& win, const vec2i& size, const string& title, void* user_pointer, refresh_glcallback refresh_cb) { // init glfw if (!glfwInit()) throw std::runtime_error("cannot initialize windowing system"); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #if __APPLE__ glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #endif // create window win = opengl_window(); win.win = glfwCreateWindow(size.x, size.y, title.c_str(), nullptr, nullptr); if (!win.win) throw std::runtime_error("cannot initialize windowing system"); glfwMakeContextCurrent(win.win); glfwSwapInterval(1); // Enable vsync // set user data glfwSetWindowRefreshCallback(win.win, _glfw_refresh_callback); glfwSetWindowUserPointer(win.win, &win); win.user_ptr = user_pointer; win.refresh_cb = refresh_cb; // init gl extensions if (!gladLoadGL()) throw std::runtime_error("cannot initialize OpenGL extensions"); } void delete_glwindow(opengl_window& win) { glfwDestroyWindow(win.win); glfwTerminate(); win.win = nullptr; } void* get_gluser_pointer(const opengl_window& win) { return win.user_ptr; } void set_drop_glcallback(opengl_window& win, drop_glcallback drop_cb) { win.drop_cb = drop_cb; glfwSetDropCallback(win.win, _glfw_drop_callback); } vec2i get_glframebuffer_size(const opengl_window& win, bool ignore_widgets) { auto size = zero2i; glfwGetFramebufferSize(win.win, &size.x, &size.y); if (ignore_widgets && win.widgets_width) { auto win_size = zero2i; glfwGetWindowSize(win.win, &win_size.x, &win_size.y); size.x -= (int)(win.widgets_width * (float)size.x / (float)win_size.x); } return size; } vec4i get_glframebuffer_viewport( const opengl_window& win, bool ignore_widgets) { auto viewport = zero4i; glfwGetFramebufferSize(win.win, &viewport.z, &viewport.w); if (ignore_widgets && win.widgets_width) { auto win_size = zero2i; glfwGetWindowSize(win.win, &win_size.x, &win_size.y); auto offset = (int)(win.widgets_width * (float)viewport.z / win_size.x); viewport.z -= offset; if (win.widgets_left) viewport.x += offset; } return viewport; } vec2i get_glwindow_size(const opengl_window& win, bool ignore_widgets) { auto size = zero2i; glfwGetWindowSize(win.win, &size.x, &size.y); if (ignore_widgets && win.widgets_width) size.x -= win.widgets_width; return size; } bool should_glwindow_close(const opengl_window& win) { return glfwWindowShouldClose(win.win); } void set_glwindow_close(const opengl_window& win, bool close) { glfwSetWindowShouldClose(win.win, close ? GLFW_TRUE : GLFW_FALSE); } vec2f get_glmouse_pos(const opengl_window& win, bool ignore_widgets) { double mouse_posx, mouse_posy; glfwGetCursorPos(win.win, &mouse_posx, &mouse_posy); auto pos = vec2f{(float)mouse_posx, (float)mouse_posy}; if (ignore_widgets && win.widgets_width && win.widgets_left) { pos.x -= win.widgets_width; } return pos; } bool get_glmouse_left(const opengl_window& win) { return glfwGetMouseButton(win.win, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS; } bool get_glmouse_right(const opengl_window& win) { return glfwGetMouseButton(win.win, GLFW_MOUSE_BUTTON_RIGHT) == GLFW_PRESS; } bool get_glalt_key(const opengl_window& win) { return glfwGetKey(win.win, GLFW_KEY_LEFT_ALT) == GLFW_PRESS || glfwGetKey(win.win, GLFW_KEY_RIGHT_ALT) == GLFW_PRESS; } bool get_glshift_key(const opengl_window& win) { return glfwGetKey(win.win, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS || glfwGetKey(win.win, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS; } void process_glevents(const opengl_window& win, bool wait) { if (wait) glfwWaitEvents(); else glfwPollEvents(); } void swap_glbuffers(const opengl_window& win) { glfwSwapBuffers(win.win); } void init_glwidgets(opengl_window& win, int width, bool left) { // init widgets ImGui::CreateContext(); ImGui::GetIO().IniFilename = nullptr; ImGui::GetStyle().WindowRounding = 0; ImGui_ImplGlfw_InitForOpenGL(win.win, true); #ifndef __APPLE__ ImGui_ImplOpenGL3_Init(); #else ImGui_ImplOpenGL3_Init("#version 330"); #endif ImGui::StyleColorsDark(); win.widgets_width = width; win.widgets_left = left; } bool get_glwidgets_active(const opengl_window& win) { auto io = &ImGui::GetIO(); return io->WantTextInput || io->WantCaptureMouse || io->WantCaptureKeyboard; } void begin_glwidgets(const opengl_window& win) { ImGui_ImplOpenGL3_NewFrame(); ImGui_ImplGlfw_NewFrame(); ImGui::NewFrame(); auto win_size = get_glwindow_size(win, false); if (win.widgets_left) { ImGui::SetNextWindowPos({0, 0}); ImGui::SetNextWindowSize({(float)win.widgets_width, (float)win_size.y}); } else { ImGui::SetNextWindowPos({(float)(win_size.x - win.widgets_width), 0}); ImGui::SetNextWindowSize({(float)win.widgets_width, (float)win_size.y}); } ImGui::SetNextWindowCollapsed(false); ImGui::SetNextWindowBgAlpha(1); } void end_glwidgets(const opengl_window& win) { ImGui::End(); ImGui::Render(); ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); } bool begin_glwidgets_window(const opengl_window& win, const char* title) { return ImGui::Begin(title, nullptr, // ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoSavedSettings); } bool begin_glheader(const opengl_window& win, const char* lbl) { if (!ImGui::CollapsingHeader(lbl)) return false; ImGui::PushID(lbl); return true; } void end_glheader(const opengl_window& win) { ImGui::PopID(); } bool begin_gltabbar(const opengl_window& win, const char* lbl) { if (!ImGui::BeginTabBar(lbl)) return false; ImGui::PushID(lbl); return true; } void end_gltabbar(const opengl_window& win) { ImGui::PopID(); ImGui::EndTabBar(); } bool begin_gltabitem(const opengl_window& win, const char* lbl) { if (!ImGui::BeginTabItem(lbl)) return false; ImGui::PushID(lbl); return true; } void end_gltabitem(const opengl_window& win) { ImGui::PopID(); ImGui::EndTabItem(); } void open_glmodal(const opengl_window& win, const char* lbl) { ImGui::OpenPopup(lbl); } void clear_glmodal(const opengl_window& win) { ImGui::CloseCurrentPopup(); } bool begin_glmodal(const opengl_window& win, const char* lbl) { return ImGui::BeginPopupModal(lbl); } void end_glmodal(const opengl_window& win) { ImGui::EndPopup(); } bool is_glmodal_open(const opengl_window& win, const char* lbl) { return ImGui::IsPopupOpen(lbl); } bool draw_glmessage( const opengl_window& win, const char* lbl, const string& message) { if (ImGui::BeginPopupModal(lbl)) { auto open = true; ImGui::Text("%s", message.c_str()); if (ImGui::Button("Ok")) { ImGui::CloseCurrentPopup(); open = false; } ImGui::EndPopup(); return open; } else { return false; } } struct filedialog_state { string dirname = ""; string filename = ""; vector<pair<string, bool>> entries = {}; bool save = false; bool remove_hidden = true; string filter = ""; vector<string> extensions = {}; filedialog_state() {} filedialog_state(const string& dirname, const string& filename, bool save, const string& filter) { this->save = save; set_filter(filter); set_dirname(dirname); set_filename(filename); } void set_dirname(const string& name) { dirname = name; dirname = normalize_path(dirname); if (dirname == "") dirname = "./"; if (dirname.back() != '/') dirname += '/'; refresh(); } void set_filename(const string& name) { filename = name; check_filename(); } void set_filter(const string& flt) { auto globs = vector<string>{""}; for (auto i = 0; i < flt.size(); i++) { if (flt[i] == ';') { globs.push_back(""); } else { globs.back() += flt[i]; } } filter = ""; extensions.clear(); for (auto pattern : globs) { if (pattern == "") continue; auto ext = get_extension(pattern); if (ext != "") { extensions.push_back(ext); filter += (filter == "") ? ("*." + ext) : (";*." + ext); } } } void check_filename() { if (filename.empty()) return; auto ext = get_extension(filename); if (std::find(extensions.begin(), extensions.end(), ext) == extensions.end()) { filename = ""; return; } if (!save && !exists_file(dirname + filename)) { filename = ""; return; } } void select_entry(int idx) { if (entries[idx].second) { set_dirname(dirname + entries[idx].first); } else { set_filename(entries[idx].first); } } void refresh() { entries.clear(); cf_dir_t dir; cf_dir_open(&dir, dirname.c_str()); while (dir.has_next) { cf_file_t file; cf_read_file(&dir, &file); cf_dir_next(&dir); if (remove_hidden && file.name[0] == '.') continue; if (file.is_dir) { entries.push_back({file.name + "/"s, true}); } else { entries.push_back({file.name, false}); } } cf_dir_close(&dir); std::sort(entries.begin(), entries.end(), [](auto& a, auto& b) { if (a.second == b.second) return a.first < b.first; return a.second; }); } string get_path() const { return dirname + filename; } bool exists_file(const string& filename) { auto f = fopen(filename.c_str(), "r"); if (!f) return false; fclose(f); return true; } }; bool draw_glfiledialog(const opengl_window& win, const char* lbl, string& path, bool save, const string& dirname, const string& filename, const string& filter) { static auto states = unordered_map<string, filedialog_state>{}; ImGui::SetNextWindowSize({500, 300}, ImGuiCond_FirstUseEver); if (ImGui::BeginPopupModal(lbl)) { if (states.find(lbl) == states.end()) { states[lbl] = filedialog_state{dirname, filename, save, filter}; } auto& state = states.at(lbl); char dir_buffer[1024]; strcpy(dir_buffer, state.dirname.c_str()); if (ImGui::InputText("dir", dir_buffer, sizeof(dir_buffer))) { state.set_dirname(dir_buffer); } auto current_item = -1; if (ImGui::ListBox( "entries", &current_item, [](void* data, int idx, const char** out_text) -> bool { auto& state = *(filedialog_state*)data; *out_text = state.entries[idx].first.c_str(); return true; }, &state, (int)state.entries.size())) { state.select_entry(current_item); } char file_buffer[1024]; strcpy(file_buffer, state.filename.c_str()); if (ImGui::InputText("file", file_buffer, sizeof(file_buffer))) { state.set_filename(file_buffer); } char filter_buffer[1024]; strcpy(filter_buffer, state.filter.c_str()); if (ImGui::InputText("filter", filter_buffer, sizeof(filter_buffer))) { state.set_filter(filter_buffer); } auto ok = false, exit = false; if (ImGui::Button("Ok")) { path = state.dirname + state.filename; ok = true; exit = true; } ImGui::SameLine(); if (ImGui::Button("Cancel")) { exit = true; } if (exit) { ImGui::CloseCurrentPopup(); states.erase(lbl); } ImGui::EndPopup(); return ok; } else { return false; } } bool draw_glbutton(const opengl_window& win, const char* lbl) { return ImGui::Button(lbl); } bool draw_glbutton(const opengl_window& win, const char* lbl, bool enabled) { if (enabled) { return ImGui::Button(lbl); } else { ImGui::PushItemFlag(ImGuiItemFlags_Disabled, true); ImGui::PushStyleVar(ImGuiStyleVar_Alpha, ImGui::GetStyle().Alpha * 0.5f); auto ok = ImGui::Button(lbl); ImGui::PopItemFlag(); ImGui::PopStyleVar(); return ok; } } void draw_gltext(const opengl_window& win, const string& text) { ImGui::Text("%s", text.c_str()); } void draw_gllabel( const opengl_window& win, const char* lbl, const string& texture) { ImGui::LabelText(lbl, "%s", texture.c_str()); } void draw_gllabel( const opengl_window& win, const char* lbl, const char* fmt, ...) { va_list args; va_start(args, fmt); ImGui::LabelTextV(lbl, fmt, args); va_end(args); } void draw_glseparator(const opengl_window& win) { ImGui::Separator(); } void continue_glline(const opengl_window& win) { ImGui::SameLine(); } bool draw_gltextinput( const opengl_window& win, const char* lbl, string& value) { char buffer[4096]; auto num = 0; for (auto c : value) buffer[num++] = c; buffer[num] = 0; auto edited = ImGui::InputText(lbl, buffer, sizeof(buffer)); if (edited) value = buffer; return edited; } bool draw_glslider(const opengl_window& win, const char* lbl, float& value, float min, float max) { return ImGui::SliderFloat(lbl, &value, min, max); } bool draw_glslider(const opengl_window& win, const char* lbl, vec2f& value, float min, float max) { return ImGui::SliderFloat2(lbl, &value.x, min, max); } bool draw_glslider(const opengl_window& win, const char* lbl, vec3f& value, float min, float max) { return ImGui::SliderFloat3(lbl, &value.x, min, max); } bool draw_glslider(const opengl_window& win, const char* lbl, vec4f& value, float min, float max) { return ImGui::SliderFloat4(lbl, &value.x, min, max); } bool draw_glslider( const opengl_window& win, const char* lbl, int& value, int min, int max) { return ImGui::SliderInt(lbl, &value, min, max); } bool draw_glslider( const opengl_window& win, const char* lbl, vec2i& value, int min, int max) { return ImGui::SliderInt2(lbl, &value.x, min, max); } bool draw_glslider( const opengl_window& win, const char* lbl, vec3i& value, int min, int max) { return ImGui::SliderInt3(lbl, &value.x, min, max); } bool draw_glslider( const opengl_window& win, const char* lbl, vec4i& value, int min, int max) { return ImGui::SliderInt4(lbl, &value.x, min, max); } bool draw_gldragger(const opengl_window& win, const char* lbl, float& value, float speed, float min, float max) { return ImGui::DragFloat(lbl, &value, speed, min, max); } bool draw_gldragger(const opengl_window& win, const char* lbl, vec2f& value, float speed, float min, float max) { return ImGui::DragFloat2(lbl, &value.x, speed, min, max); } bool draw_gldragger(const opengl_window& win, const char* lbl, vec3f& value, float speed, float min, float max) { return ImGui::DragFloat3(lbl, &value.x, speed, min, max); } bool draw_gldragger(const opengl_window& win, const char* lbl, vec4f& value, float speed, float min, float max) { return ImGui::DragFloat4(lbl, &value.x, speed, min, max); } bool draw_gldragger(const opengl_window& win, const char* lbl, int& value, float speed, int min, int max) { return ImGui::DragInt(lbl, &value, speed, min, max); } bool draw_gldragger(const opengl_window& win, const char* lbl, vec2i& value, float speed, int min, int max) { return ImGui::DragInt2(lbl, &value.x, speed, min, max); } bool draw_gldragger(const opengl_window& win, const char* lbl, vec3i& value, float speed, int min, int max) { return ImGui::DragInt3(lbl, &value.x, speed, min, max); } bool draw_gldragger(const opengl_window& win, const char* lbl, vec4i& value, float speed, int min, int max) { return ImGui::DragInt4(lbl, &value.x, speed, min, max); } bool draw_glcheckbox(const opengl_window& win, const char* lbl, bool& value) { return ImGui::Checkbox(lbl, &value); } bool draw_glcoloredit(const opengl_window& win, const char* lbl, vec3f& value) { auto flags = ImGuiColorEditFlags_Float; return ImGui::ColorEdit3(lbl, &value.x, flags); } bool draw_glcoloredit(const opengl_window& win, const char* lbl, vec4f& value) { auto flags = ImGuiColorEditFlags_Float; return ImGui::ColorEdit4(lbl, &value.x, flags); } bool draw_glhdrcoloredit( const opengl_window& win, const char* lbl, vec3f& value) { auto color = value; auto exposure = 0.0f; auto scale = max(color); if (scale > 1) { color /= scale; exposure = log2(scale); } auto edit_exposure = draw_glslider( win, (lbl + " [exp]"s).c_str(), exposure, 0, 10); auto edit_color = draw_glcoloredit(win, (lbl + " [col]"s).c_str(), color); if (edit_exposure || edit_color) { value = color * exp2(exposure); return true; } else { return false; } } bool draw_glhdrcoloredit( const opengl_window& win, const char* lbl, vec4f& value) { auto color = value; auto exposure = 0.0f; auto scale = max(xyz(color)); if (scale > 1) { xyz(color) /= scale; exposure = log2(scale); } auto edit_exposure = draw_glslider( win, (lbl + " [exp]"s).c_str(), exposure, 0, 10); auto edit_color = draw_glcoloredit(win, (lbl + " [col]"s).c_str(), color); if (edit_exposure || edit_color) { xyz(value) = xyz(color) * exp2(exposure); value.w = color.w; return true; } else { return false; } } bool begin_gltreenode(const opengl_window& win, const char* lbl) { return ImGui::TreeNode(lbl); } void end_gltreenode(const opengl_window& win) { ImGui::TreePop(); } bool begin_glselectabletreenode( const opengl_window& win, const char* lbl, bool& selected) { ImGuiTreeNodeFlags node_flags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick; if (selected) node_flags |= ImGuiTreeNodeFlags_Selected; auto open = ImGui::TreeNodeEx(lbl, node_flags, "%s", lbl); if (ImGui::IsItemClicked()) selected = true; return open; } void begin_glselectabletreeleaf( const opengl_window& win, const char* lbl, bool& selected) { ImGuiTreeNodeFlags node_flags = ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen; if (selected) node_flags |= ImGuiTreeNodeFlags_Selected; ImGui::TreeNodeEx(lbl, node_flags, "%s", lbl); if (ImGui::IsItemClicked()) selected = true; } bool draw_glcombobox(const opengl_window& win, const char* lbl, int& value, const vector<string>& labels) { if (!ImGui::BeginCombo(lbl, labels[value].c_str())) return false; auto old_val = value; for (auto i = 0; i < labels.size(); i++) { ImGui::PushID(i); if (ImGui::Selectable(labels[i].c_str(), value == i)) value = i; if (value == i) ImGui::SetItemDefaultFocus(); ImGui::PopID(); } ImGui::EndCombo(); return value != old_val; } bool draw_glcombobox(const opengl_window& win, const char* lbl, string& value, const vector<string>& labels) { if (!ImGui::BeginCombo(lbl, value.c_str())) return false; auto old_val = value; for (auto i = 0; i < labels.size(); i++) { ImGui::PushID(i); if (ImGui::Selectable(labels[i].c_str(), value == labels[i])) value = labels[i]; if (value == labels[i]) ImGui::SetItemDefaultFocus(); ImGui::PopID(); } ImGui::EndCombo(); return value != old_val; } bool draw_glcombobox(const opengl_window& win, const char* lbl, int& idx, int num, const std::function<const char*(int)>& labels, bool include_null) { if (!ImGui::BeginCombo(lbl, idx >= 0 ? labels(idx) : "<none>")) return false; auto old_idx = idx; if (include_null) { ImGui::PushID(100000); if (ImGui::Selectable("<none>", idx < 0)) idx = -1; if (idx < 0) ImGui::SetItemDefaultFocus(); ImGui::PopID(); } for (auto i = 0; i < num; i++) { ImGui::PushID(i); if (ImGui::Selectable(labels(i), idx == i)) idx = i; if (idx == i) ImGui::SetItemDefaultFocus(); ImGui::PopID(); } ImGui::EndCombo(); return idx != old_idx; } void begin_glchild( const opengl_window& win, const char* lbl, const vec2i& size) { ImGui::PushID(lbl); ImGui::BeginChild(lbl, ImVec2(size.x, size.y), false); } void end_glchild(const opengl_window& win) { ImGui::EndChild(); ImGui::PopID(); } void draw_glhistogram( const opengl_window& win, const char* lbl, const float* values, int count) { ImGui::PlotHistogram(lbl, values, count); } void draw_glhistogram( const opengl_window& win, const char* lbl, const vector<float>& values) { ImGui::PlotHistogram(lbl, values.data(), (int)values.size(), 0, nullptr, flt_max, flt_max, {0, 0}, 4); } void draw_glhistogram( const opengl_window& win, const char* lbl, const vector<vec2f>& values) { ImGui::PlotHistogram((lbl + " x"s).c_str(), (const float*)values.data() + 0, (int)values.size(), 0, nullptr, flt_max, flt_max, {0, 0}, sizeof(vec2f)); ImGui::PlotHistogram((lbl + " y"s).c_str(), (const float*)values.data() + 1, (int)values.size(), 0, nullptr, flt_max, flt_max, {0, 0}, sizeof(vec2f)); } void draw_glhistogram( const opengl_window& win, const char* lbl, const vector<vec3f>& values) { ImGui::PlotHistogram((lbl + " x"s).c_str(), (const float*)values.data() + 0, (int)values.size(), 0, nullptr, flt_max, flt_max, {0, 0}, sizeof(vec3f)); ImGui::PlotHistogram((lbl + " y"s).c_str(), (const float*)values.data() + 1, (int)values.size(), 0, nullptr, flt_max, flt_max, {0, 0}, sizeof(vec3f)); ImGui::PlotHistogram((lbl + " z"s).c_str(), (const float*)values.data() + 2, (int)values.size(), 0, nullptr, flt_max, flt_max, {0, 0}, sizeof(vec3f)); } void draw_glhistogram( const opengl_window& win, const char* lbl, const vector<vec4f>& values) { ImGui::PlotHistogram((lbl + " x"s).c_str(), (const float*)values.data() + 0, (int)values.size(), 0, nullptr, flt_max, flt_max, {0, 0}, sizeof(vec4f)); ImGui::PlotHistogram((lbl + " y"s).c_str(), (const float*)values.data() + 1, (int)values.size(), 0, nullptr, flt_max, flt_max, {0, 0}, sizeof(vec4f)); ImGui::PlotHistogram((lbl + " z"s).c_str(), (const float*)values.data() + 2, (int)values.size(), 0, nullptr, flt_max, flt_max, {0, 0}, sizeof(vec4f)); ImGui::PlotHistogram((lbl + " w"s).c_str(), (const float*)values.data() + 3, (int)values.size(), 0, nullptr, flt_max, flt_max, {0, 0}, sizeof(vec4f)); } // https://github.com/ocornut/imgui/issues/300 struct ImGuiAppLog { ImGuiTextBuffer Buf; ImGuiTextFilter Filter; ImVector<int> LineOffsets; // Index to lines offset bool ScrollToBottom; void Clear() { Buf.clear(); LineOffsets.clear(); } void AddLog(const char* msg, const char* lbl) { int old_size = Buf.size(); Buf.appendf("[%s] %s\n", lbl, msg); for (int new_size = Buf.size(); old_size < new_size; old_size++) if (Buf[old_size] == '\n') LineOffsets.push_back(old_size); ScrollToBottom = true; } void Draw() { if (ImGui::Button("Clear")) Clear(); ImGui::SameLine(); bool copy = ImGui::Button("Copy"); ImGui::SameLine(); Filter.Draw("Filter", -100.0f); ImGui::Separator(); ImGui::BeginChild("scrolling"); ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 1)); if (copy) ImGui::LogToClipboard(); if (Filter.IsActive()) { const char* buf_begin = Buf.begin(); const char* line = buf_begin; for (int line_no = 0; line != NULL; line_no++) { const char* line_end = (line_no < LineOffsets.Size) ? buf_begin + LineOffsets[line_no] : NULL; if (Filter.PassFilter(line, line_end)) ImGui::TextUnformatted(line, line_end); line = line_end && line_end[1] ? line_end + 1 : NULL; } } else { ImGui::TextUnformatted(Buf.begin()); } if (ScrollToBottom) ImGui::SetScrollHere(1.0f); ScrollToBottom = false; ImGui::PopStyleVar(); ImGui::EndChild(); } void Draw(const char* title, bool* p_opened = NULL) { ImGui::SetNextWindowSize(ImVec2(500, 400), ImGuiSetCond_FirstUseEver); ImGui::Begin(title, p_opened); Draw(); ImGui::End(); } }; std::mutex _log_mutex; ImGuiAppLog _log_widget; void log_glinfo(const opengl_window& win, const char* msg) { _log_mutex.lock(); _log_widget.AddLog(msg, "info"); _log_mutex.unlock(); } void log_glinfo(const opengl_window& win, const string& msg) { _log_mutex.lock(); _log_widget.AddLog(msg.c_str(), "info"); _log_mutex.unlock(); } void log_glerror(const opengl_window& win, const char* msg) { _log_mutex.lock(); _log_widget.AddLog(msg, "errn"); _log_mutex.unlock(); } void log_glerror(const opengl_window& win, const string& msg) { _log_mutex.lock(); _log_widget.AddLog(msg.c_str(), "errn"); _log_mutex.unlock(); } void clear_gllogs(const opengl_window& win) { _log_mutex.lock(); _log_widget.Clear(); _log_mutex.unlock(); } void draw_gllog(const opengl_window& win) { _log_mutex.lock(); _log_widget.Draw(); _log_mutex.unlock(); } } // namespace yocto
33.726429
114
0.679162
[ "render", "vector" ]
5d625b166e140e395b778dc702bb351f3466ad04
81,994
cpp
C++
jointlimits.cpp
orangeduck/Joint-Limits
1e48238f656bd8fe24a58dabe040c5a3ce122215
[ "MIT" ]
61
2021-11-11T17:57:46.000Z
2022-03-17T11:00:20.000Z
jointlimits.cpp
orangeduck/Joint-Limits
1e48238f656bd8fe24a58dabe040c5a3ce122215
[ "MIT" ]
3
2021-12-01T03:29:53.000Z
2022-01-10T21:40:50.000Z
jointlimits.cpp
orangeduck/Joint-Limits
1e48238f656bd8fe24a58dabe040c5a3ce122215
[ "MIT" ]
7
2021-11-12T10:47:18.000Z
2021-12-29T05:48:38.000Z
extern "C" { #include "raylib.h" #include "raymath.h" #define RAYGUI_IMPLEMENTATION #include "raygui.h" } #if defined(PLATFORM_WEB) #include <emscripten/emscripten.h> #endif #include "common.h" #include "vec.h" #include "mat.h" #include "quat.h" #include "spring.h" #include "array.h" #include "character.h" #include "database.h" #include <initializer_list> #include <vector> #include <functional> //-------------------------------------- static inline Vector3 to_Vector3(vec3 v) { return (Vector3){ v.x, v.y, v.z }; } //-------------------------------------- // Perform linear blend skinning and copy // result into mesh data. Update and upload // deformed vertex positions and normals to GPU void deform_character_mesh( Mesh& mesh, const character& c, const slice1d<vec3> bone_anim_positions, const slice1d<quat> bone_anim_rotations, const slice1d<int> bone_parents) { linear_blend_skinning_positions( slice1d<vec3>(mesh.vertexCount, (vec3*)mesh.vertices), c.positions, c.bone_weights, c.bone_indices, c.bone_rest_positions, c.bone_rest_rotations, bone_anim_positions, bone_anim_rotations); linear_blend_skinning_normals( slice1d<vec3>(mesh.vertexCount, (vec3*)mesh.normals), c.normals, c.bone_weights, c.bone_indices, c.bone_rest_rotations, bone_anim_rotations); UpdateMeshBuffer(mesh, 0, mesh.vertices, mesh.vertexCount * 3 * sizeof(float), 0); UpdateMeshBuffer(mesh, 2, mesh.normals, mesh.vertexCount * 3 * sizeof(float), 0); } Mesh make_character_mesh(character& c) { Mesh mesh = { 0 }; mesh.vertexCount = c.positions.size; mesh.triangleCount = c.triangles.size / 3; mesh.vertices = (float*)MemAlloc(c.positions.size * 3 * sizeof(float)); mesh.texcoords = (float*)MemAlloc(c.texcoords.size * 2 * sizeof(float)); mesh.normals = (float*)MemAlloc(c.normals.size * 3 * sizeof(float)); mesh.indices = (unsigned short*)MemAlloc(c.triangles.size * sizeof(unsigned short)); memcpy(mesh.vertices, c.positions.data, c.positions.size * 3 * sizeof(float)); memcpy(mesh.texcoords, c.texcoords.data, c.texcoords.size * 2 * sizeof(float)); memcpy(mesh.normals, c.normals.data, c.normals.size * 3 * sizeof(float)); memcpy(mesh.indices, c.triangles.data, c.triangles.size * sizeof(unsigned short)); UploadMesh(&mesh, true); return mesh; } //-------------------------------------- float orbit_camera_update_azimuth( const float azimuth, const float mouse_dx, const float dt) { return azimuth + 1.0f * dt * -mouse_dx; } float orbit_camera_update_altitude( const float altitude, const float mouse_dy, const float dt) { return clampf(altitude + 1.0f * dt * mouse_dy, 0.0, 0.4f * PIf); } float orbit_camera_update_distance( const float distance, const float dt) { return clampf(distance + 20.0f * dt * -GetMouseWheelMove(), 0.1f, 100.0f); } // Updates the camera using the orbit cam controls void orbit_camera_update( Camera3D& cam, float& camera_azimuth, float& camera_altitude, float& camera_distance, const vec3 target, const float mouse_dx, const float mouse_dy, const float dt) { camera_azimuth = orbit_camera_update_azimuth(camera_azimuth, mouse_dx, dt); camera_altitude = orbit_camera_update_altitude(camera_altitude, mouse_dy, dt); camera_distance = orbit_camera_update_distance(camera_distance, dt); quat rotation_azimuth = quat_from_angle_axis(camera_azimuth, vec3(0, 1, 0)); vec3 position = quat_mul_vec3(rotation_azimuth, vec3(0, 0, camera_distance)); vec3 axis = normalize(cross(position, vec3(0, 1, 0))); quat rotation_altitude = quat_from_angle_axis(camera_altitude, axis); vec3 eye = target + quat_mul_vec3(rotation_altitude, position); cam.target = (Vector3){ target.x, target.y, target.z }; cam.position = (Vector3){ eye.x, eye.y, eye.z }; UpdateCamera(&cam); } //-------------------------------------- static inline void quat_unroll_inplace(slice1d<quat> rotations) { // Make initial rotation be the "short way around" rotations(0) = quat_abs(rotations(0)); // Loop over following rotations for (int i = 1; i < rotations.size; i++) { // If more than 180 degrees away from previous frame // rotation then flip to opposite hemisphere if (quat_dot(rotations(i), rotations(i - 1)) < 0.0f) { rotations(i) = -rotations(i); } } } // This is similar to the previous function but we loop over // the ranges specified in the database to ensure we are // unrolling each animation individually static inline void quat_unroll_ranges_inplace( slice2d<quat> rotations, const slice1d<int> range_starts, const slice1d<int> range_stops) { for (int r = 0; r < range_starts.size; r++) { for (int j = 0; j < rotations.cols; j++) { rotations(range_starts(r), j) = quat_abs(rotations(range_starts(r), j)); } for (int i = range_starts(r) + 1; i < range_stops(r); i++) { for (int j = 0; j < rotations.cols; j++) { if (quat_dot(rotations(i, j), rotations(i - 1, j)) < 0.0f) { rotations(i, j) = -rotations(i, j); } } } } } static inline void compute_twist_axes( slice1d<vec3> twist_axes, const slice1d<vec3> reference_positions, const slice1d<int> bone_parents, const vec3 default_twist_axis = vec3(1, 0, 0), const float eps = 1e-8f) { twist_axes.zero(); for (int i = 0; i < bone_parents.size; i++) { // Compute average extension of child bones for (int j = 0; j < bone_parents.size; j++) { if (bone_parents(j) == i) { twist_axes(i) = twist_axes(i) + reference_positions(j); } } // If children found normalize, otherwise use default axis if (length(twist_axes(i)) > eps) { twist_axes(i) = normalize(twist_axes(i)); } else { twist_axes(i) = default_twist_axis; } } } // Subsamples a set of `points`. Returns the // number of subsampled points. Output array // `subsampled` must be large enough for the // case where all points are returned. static inline int subsample_naive( slice1d<vec3> subsampled, const slice1d<vec3> points, const float distance_threshold = 0.05f) { int count = 0; // Include first point subsampled(count) = points(0); count++; // Loop over other points for (int i = 1; i < points.size; i++) { // Include if no other subsampled point is within // `distance_threshold` of this point bool include = true; for (int j = 0; j < count; j++) { if (length(subsampled(j) - points(i)) < distance_threshold) { include = false; break; } } if (include) { // Add point and increment count subsampled(count) = points(i); count++; } } // Return number of subsampled points return count; } //-------------------------------------- static inline void fit_limit_orientations( vec3& limit_position, mat3& limit_rotation, const slice1d<vec3> limit_space_rotations) { limit_position = vec3(); // Compute Average Position for (int i = 0; i < limit_space_rotations.size; i++) { limit_position = limit_position + limit_space_rotations(i) / limit_space_rotations.size; } // Compute Inner Product mat3 inner_product = mat3_zero(); for (int i = 0; i < limit_space_rotations.size; i++) { vec3 v = limit_space_rotations(i) - limit_position; inner_product = inner_product + mat3( v.x * v.x, v.x * v.y, v.x * v.z, v.y * v.x, v.y * v.y, v.y * v.z, v.z * v.x, v.z * v.y, v.z * v.z) / limit_space_rotations.size; } // Perform SVD to extract rotation vec3 s; mat3 U, V; mat3_svd_piter(U, s, V, inner_product); limit_rotation = mat3_transpose(V); } //-------------------------------------- static inline void fit_rectangular_limits_basic( vec3& limit_min, vec3& limit_max, const slice1d<vec3> limit_space_rotations, const float padding = 0.05f) { // Set limits to opposite float min and max limit_min = vec3(FLT_MAX, FLT_MAX, FLT_MAX); limit_max = vec3(FLT_MIN, FLT_MIN, FLT_MIN); for (int i = 0; i < limit_space_rotations.size; i++) { // Find min and max on each dimension limit_min = min(limit_min, limit_space_rotations(i)); limit_max = max(limit_max, limit_space_rotations(i)); } // Add some padding if desired to expand limit a little limit_min -= vec3(padding, padding, padding); limit_max += vec3(padding, padding, padding); } static inline void fit_rectangular_limits( vec3& limit_min, vec3& limit_max, const vec3 limit_position, const mat3 limit_rotation, const slice1d<vec3> limit_space_rotations, const float padding = 0.05f) { limit_min = vec3(FLT_MAX, FLT_MAX, FLT_MAX); limit_max = vec3(FLT_MIN, FLT_MIN, FLT_MIN); for (int i = 0; i < limit_space_rotations.size; i++) { // Inverse transform point using position and rotation vec3 limit_point = mat3_transpose_mul_vec3( limit_rotation, limit_space_rotations(i) - limit_position); limit_min = min(limit_min, limit_point); limit_max = max(limit_max, limit_point); } limit_min -= vec3(padding, padding, padding); limit_max += vec3(padding, padding, padding); } static inline void fit_ellipsoid_limits( vec3& limit_scale, const vec3 limit_position, const mat3 limit_rotation, const slice1d<vec3> limit_space_rotations, const float padding = 0.05f) { // Estimate Scales limit_scale = vec3(padding, padding, padding); for (int i = 0; i < limit_space_rotations.size; i++) { vec3 limit_point = mat3_transpose_mul_vec3( limit_rotation, limit_space_rotations(i) - limit_position); limit_scale = max(limit_scale, abs(limit_point)); } // Compute required radius float radius = 0.0f; for (int i = 0; i < limit_space_rotations.size; i++) { vec3 limit_point = mat3_transpose_mul_vec3( limit_rotation, limit_space_rotations(i) - limit_position); radius = maxf(radius, length(limit_point / limit_scale)); } // Scale by required radius limit_scale = max(radius * limit_scale, vec3(padding, padding, padding)); } static inline void fit_kdop_limits( slice1d<float> limit_mins, slice1d<float> limit_maxs, const vec3 limit_position, const mat3 limit_rotation, const slice1d<vec3> limit_space_rotations, const slice1d<vec3> limit_kdop_axes, const float padding = 0.05f) { // Set limits to opposite float min and max limit_mins.set(FLT_MAX); limit_maxs.set(FLT_MIN); for (int i = 0; i < limit_space_rotations.size; i++) { // Inverse transform point using position and rotation vec3 limit_point = mat3_transpose_mul_vec3( limit_rotation, limit_space_rotations(i) - limit_position); for (int k = 0; k < limit_kdop_axes.size; k++) { // Find how much point extends on each kdop axis float limit_point_proj = dot(limit_kdop_axes(k), limit_point); limit_mins(k) = minf(limit_mins(k), limit_point_proj); limit_maxs(k) = maxf(limit_maxs(k), limit_point_proj); } } // Add some padding if desired to expand limit a little for (int k = 0; k < limit_kdop_axes.size; k++) { limit_mins(k) -= padding; limit_maxs(k) += padding; } } //-------------------------------------- static inline vec3 apply_rectangular_limit_basic( const vec3 limit_space_rotation, const vec3 limit_min, const vec3 limit_max) { return clamp(limit_space_rotation, limit_min, limit_max); } static inline vec3 apply_rectangular_limit( const vec3 limit_space_rotation, const vec3 limit_min, const vec3 limit_max, const vec3 limit_position, const mat3 limit_rotation) { // Inverse transform point using position and rotation vec3 limit_point = mat3_transpose_mul_vec3( limit_rotation, limit_space_rotation - limit_position); // Clamp point limit_point = clamp(limit_point, limit_min, limit_max); // Transform point using position and rotation return mat3_mul_vec3(limit_rotation, limit_point) + limit_position; } static inline vec3 apply_ellipsoid_limit( const vec3 limit_space_rotation, const vec3 limit_scale, const vec3 limit_position, const mat3 limit_rotation, const int iterations = 8, const float eps = 1e-5f) { // Inverse transform point using position and rotation vec3 limit_point = mat3_transpose_mul_vec3( limit_rotation, limit_space_rotation - limit_position); // If already inside ellipsoid just return if (length(limit_point / limit_scale) <= 1.0f) { return limit_space_rotation; } vec3 ss = limit_scale * limit_scale + eps; float ss_mid = (ss.y < ss.x) ? (ss.z < ss.x ? ss.x : ss.z) : (ss.z < ss.y ? ss.y : ss.z); float hmin = sqrtf(dot(limit_point * limit_point, ss * ss) / ss_mid) - ss_mid; hmin = maxf(hmin, (fabs(limit_point.x) - limit_scale.x) * limit_scale.x); hmin = maxf(hmin, (fabs(limit_point.y) - limit_scale.y) * limit_scale.y); hmin = maxf(hmin, (fabs(limit_point.z) - limit_scale.z) * limit_scale.z); if (dot(limit_point, limit_point / ss.x) > 1.0f && hmin < 0.0f) { hmin = 0; } float h = hmin; float hprev; // Iterations of Newton-Raphson for (int i = 0; i < iterations; i++) { vec3 wa = limit_point / (ss + h); vec3 pp = wa * wa * ss; hprev = h; h = h - (1.0f - sum(pp)) / (2.0f * sum(pp / (ss + h))); if (h < hmin) { h = 0.5f * (hprev + hmin); continue; } if (h <= hprev) { break; } } // Project onto surface limit_point = limit_point * ss / (ss + h); // Transform point using position and rotation return mat3_mul_vec3(limit_rotation, limit_point) + limit_position; } static inline vec3 apply_kdop_limit( const vec3 limit_space_rotation, const slice1d<float> limit_mins, const slice1d<float> limit_maxs, const vec3 limit_position, const mat3 limit_rotation, const slice1d<vec3> kdop_axes) { // Inverse transform point using position and rotation vec3 limit_point = mat3_transpose_mul_vec3( limit_rotation, limit_space_rotation - limit_position); for (int k = 0; k < kdop_axes.size; k++) { // Clamp point along given axes vec3 t0 = limit_point - limit_mins(k) * kdop_axes(k); vec3 t1 = limit_point - limit_maxs(k) * kdop_axes(k); limit_point -= minf(dot(t0, kdop_axes(k)), 0.0f) * kdop_axes(k); limit_point -= maxf(dot(t1, kdop_axes(k)), 0.0f) * kdop_axes(k); } // Transform point using position and rotation return mat3_mul_vec3(limit_rotation, limit_point) + limit_position; } static inline vec3 projection_soften( const vec3 original_position, const vec3 projected_position, const float falloff = 1.0f, const float radius = 0.1f, const float eps = 1e-5f) { float distance = length(projected_position - original_position); if (distance > eps) { // Compute how much softening to apply up to `radius` float softening = tanhf(falloff * distance) * radius; // Add softening toward original position return projected_position + normalize(original_position - projected_position) * softening; } else { // No projection applied return projected_position; } } enum { LIMIT_TYPE_RECTANGULAR = 0, LIMIT_TYPE_ELLIPSOID = 1, LIMIT_TYPE_KDOP = 2, }; static inline vec3 apply_limit( const vec3 limit_space_rotation, const int limit_type, const vec3 rectangular_limit_min, const vec3 rectangular_limit_max, const vec3 ellipsoid_limit_scale, const slice1d<float> kdop_limit_mins, const slice1d<float> kdop_limit_maxs, const vec3 limit_position, const mat3 limit_rotation, const slice1d<vec3> kdop_axes) { vec3 limit_space_rotation_projected = limit_space_rotation; if (limit_type == LIMIT_TYPE_RECTANGULAR) { limit_space_rotation_projected = apply_rectangular_limit( limit_space_rotation, rectangular_limit_min, rectangular_limit_max, limit_position, limit_rotation); } else if (limit_type == LIMIT_TYPE_ELLIPSOID) { limit_space_rotation_projected = apply_ellipsoid_limit( limit_space_rotation, ellipsoid_limit_scale, limit_position, limit_rotation); } else if (limit_type == LIMIT_TYPE_KDOP) { limit_space_rotation_projected = apply_kdop_limit( limit_space_rotation, kdop_limit_mins, kdop_limit_maxs, limit_position, limit_rotation, kdop_axes); } return limit_space_rotation_projected; } // This function is a bit absurd... but only // because we have so many potential options and // different ways of doing the joint limits. // In reality it makes more sense to break this // into separate functions for each approach we // might want to use. static inline void apply_joint_limit( quat& rotation, vec3& limit_space_rotation, vec3& limit_space_rotation_swing, vec3& limit_space_rotation_twist, vec3& limit_space_rotation_projected, vec3& limit_space_rotation_projected_swing, vec3& limit_space_rotation_projected_twist, const quat reference_rotation, const int limit_type, const vec3 rectangular_limit_min, const vec3 rectangular_limit_max, const vec3 rectangular_limit_min_swing, const vec3 rectangular_limit_max_swing, const vec3 rectangular_limit_min_twist, const vec3 rectangular_limit_max_twist, const vec3 ellipsoid_limit_scale, const vec3 ellipsoid_limit_scale_swing, const vec3 ellipsoid_limit_scale_twist, const slice1d<float> kdop_limit_mins, const slice1d<float> kdop_limit_maxs, const slice1d<float> kdop_limit_mins_swing, const slice1d<float> kdop_limit_maxs_swing, const slice1d<float> kdop_limit_mins_twist, const slice1d<float> kdop_limit_maxs_twist, const vec3 limit_position, const mat3 limit_rotation, const vec3 limit_position_swing, const mat3 limit_rotation_swing, const vec3 limit_position_twist, const mat3 limit_rotation_twist, const slice1d<vec3> kdop_axes, const bool swing_twist, const vec3 twist_axis, const bool projection_enabled, const bool projection_soften_enabled, const float projection_soften_falloff, const float projection_soften_radius) { if (swing_twist) { quat reference_rotation_swing, reference_rotation_twist; quat_swing_twist( reference_rotation_swing, reference_rotation_twist, quat_inv_mul(reference_rotation, rotation), twist_axis); limit_space_rotation_swing = quat_to_scaled_angle_axis(quat_abs(reference_rotation_swing)); limit_space_rotation_twist = quat_to_scaled_angle_axis(quat_abs(reference_rotation_twist)); limit_space_rotation_projected_swing = limit_space_rotation_swing; limit_space_rotation_projected_twist = limit_space_rotation_twist; if (projection_enabled) { limit_space_rotation_projected_swing = apply_limit( limit_space_rotation_swing, limit_type, rectangular_limit_min_swing, rectangular_limit_max_swing, ellipsoid_limit_scale_swing, kdop_limit_mins_swing, kdop_limit_maxs_swing, limit_position_swing, limit_rotation_swing, kdop_axes); limit_space_rotation_projected_twist = apply_limit( limit_space_rotation_twist, limit_type, rectangular_limit_min_twist, rectangular_limit_max_twist, ellipsoid_limit_scale_twist, kdop_limit_mins_twist, kdop_limit_maxs_twist, limit_position_twist, limit_rotation_twist, kdop_axes); } if (projection_soften_enabled) { limit_space_rotation_projected_swing = projection_soften( limit_space_rotation_swing, limit_space_rotation_projected_swing, projection_soften_falloff, projection_soften_radius); limit_space_rotation_projected_twist = projection_soften( limit_space_rotation_twist, limit_space_rotation_projected_twist, projection_soften_falloff, projection_soften_radius); } rotation = quat_mul(reference_rotation, quat_mul( quat_from_scaled_angle_axis(limit_space_rotation_projected_swing), quat_from_scaled_angle_axis(limit_space_rotation_projected_twist))); } else { limit_space_rotation = quat_to_scaled_angle_axis( quat_abs(quat_inv_mul(reference_rotation, rotation))); limit_space_rotation_projected = limit_space_rotation; if (projection_enabled) { limit_space_rotation_projected = apply_limit( limit_space_rotation, limit_type, rectangular_limit_min, rectangular_limit_max, ellipsoid_limit_scale, kdop_limit_mins, kdop_limit_maxs, limit_position, limit_rotation, kdop_axes); } if (projection_soften_enabled) { limit_space_rotation_projected = projection_soften( limit_space_rotation, limit_space_rotation_projected, projection_soften_falloff, projection_soften_radius); } rotation = quat_mul(reference_rotation, quat_from_scaled_angle_axis(limit_space_rotation_projected)); } } //-------------------------------------- // Rotate a joint to look toward some // given target position void ik_look_at( quat& bone_rotation, const quat global_parent_rotation, const quat global_rotation, const vec3 global_position, const vec3 child_position, const vec3 target_position, const float eps = 1e-5f) { vec3 curr_dir = normalize(child_position - global_position); vec3 targ_dir = normalize(target_position - global_position); if (fabs(1.0f - dot(curr_dir, targ_dir) > eps)) { bone_rotation = quat_inv_mul(global_parent_rotation, quat_mul(quat_between(curr_dir, targ_dir), global_rotation)); } } // Basic two-joint IK in the style of https://theorangeduck.com/page/simple-two-joint // Here I add a basic "forward vector" which acts like a kind of pole-vetor // to control the bending direction void ik_two_bone( quat& bone_root_lr, quat& bone_mid_lr, const vec3 bone_root, const vec3 bone_mid, const vec3 bone_end, const vec3 target, const vec3 fwd, const quat bone_root_gr, const quat bone_mid_gr, const quat bone_par_gr, const float max_length_buffer) { float max_extension = length(bone_root - bone_mid) + length(bone_mid - bone_end) - max_length_buffer; vec3 target_clamp = target; if (length(target - bone_root) > max_extension) { target_clamp = bone_root + max_extension * normalize(target - bone_root); } vec3 axis_dwn = normalize(bone_end - bone_root); vec3 axis_rot = normalize(cross(axis_dwn, fwd)); vec3 a = bone_root; vec3 b = bone_mid; vec3 c = bone_end; vec3 t = target_clamp; float lab = length(b - a); float lcb = length(b - c); float lat = length(t - a); float ac_ab_0 = acosf(clampf(dot(normalize(c - a), normalize(b - a)), -1.0f, 1.0f)); float ba_bc_0 = acosf(clampf(dot(normalize(a - b), normalize(c - b)), -1.0f, 1.0f)); float ac_ab_1 = acosf(clampf((lab * lab + lat * lat - lcb * lcb) / (2.0f * lab * lat), -1.0f, 1.0f)); float ba_bc_1 = acosf(clampf((lab * lab + lcb * lcb - lat * lat) / (2.0f * lab * lcb), -1.0f, 1.0f)); quat r0 = quat_from_angle_axis(ac_ab_1 - ac_ab_0, axis_rot); quat r1 = quat_from_angle_axis(ba_bc_1 - ba_bc_0, axis_rot); vec3 c_a = normalize(bone_end - bone_root); vec3 t_a = normalize(target_clamp - bone_root); quat r2 = quat_from_angle_axis( acosf(clampf(dot(c_a, t_a), -1.0f, 1.0f)), normalize(cross(c_a, t_a))); bone_root_lr = quat_inv_mul(bone_par_gr, quat_mul(r2, quat_mul(r0, bone_root_gr))); bone_mid_lr = quat_inv_mul(bone_root_gr, quat_mul(r1, bone_mid_gr)); } //-------------------------------------- void draw_axis(const vec3 pos, const quat rot, const float scale = 1.0f) { vec3 axis0 = pos + quat_mul_vec3(rot, scale * vec3(1.0f, 0.0f, 0.0f)); vec3 axis1 = pos + quat_mul_vec3(rot, scale * vec3(0.0f, 1.0f, 0.0f)); vec3 axis2 = pos + quat_mul_vec3(rot, scale * vec3(0.0f, 0.0f, 1.0f)); DrawLine3D(to_Vector3(pos), to_Vector3(axis0), RED); DrawLine3D(to_Vector3(pos), to_Vector3(axis1), GREEN); DrawLine3D(to_Vector3(pos), to_Vector3(axis2), BLUE); } void draw_axis(const vec3 pos, const mat3 rot, const float scale = 1.0f) { vec3 axis0 = pos + mat3_mul_vec3(rot, scale * vec3(1.0f, 0.0f, 0.0f)); vec3 axis1 = pos + mat3_mul_vec3(rot, scale * vec3(0.0f, 1.0f, 0.0f)); vec3 axis2 = pos + mat3_mul_vec3(rot, scale * vec3(0.0f, 0.0f, 1.0f)); DrawLine3D(to_Vector3(pos), to_Vector3(axis0), RED); DrawLine3D(to_Vector3(pos), to_Vector3(axis1), GREEN); DrawLine3D(to_Vector3(pos), to_Vector3(axis2), BLUE); } void draw_skeleton( const slice1d<vec3> bone_positions, const slice1d<quat> bone_rotations, const slice1d<int> bone_parents, const int joint_selected = -1) { for (int i = 1; i < bone_positions.size; i++) { DrawSphereWires( to_Vector3(bone_positions(i)), i == joint_selected ? 0.025 : 0.01f, 4, 8, i == joint_selected ? PINK : MAROON); } for (int i = 2; i < bone_positions.size; i++) { DrawLine3D( to_Vector3(bone_positions(i)), to_Vector3(bone_positions(bone_parents(i))), bone_parents(i) == joint_selected ? PINK : MAROON); } } int generate_sphere_line_count(int rings, int slices) { return (rings + 2) * slices * 3; } void generate_sphere_lines( slice1d<vec3> line_starts, slice1d<vec3> line_stops, int rings, int slices) { int count = generate_sphere_line_count(rings, slices); int index = 0; for (int i = 0; i < (rings + 2); i++) { for (int j = 0; j < slices; j++) { line_starts(index) = vec3( cosf(DEG2RAD*(270 + (180.0f/(rings + 1))*i))*sinf(DEG2RAD*(360.0f*j/slices)), sinf(DEG2RAD*(270 + (180.0f/(rings + 1))*i)), cosf(DEG2RAD*(270 + (180.0f/(rings + 1))*i))*cosf(DEG2RAD*(360.0f*j/slices))); line_stops(index) = vec3( cosf(DEG2RAD*(270 + (180.0f/(rings + 1))*(i + 1)))*sinf(DEG2RAD*(360.0f*(j + 1)/slices)), sinf(DEG2RAD*(270 + (180.0f/(rings + 1))*(i + 1))), cosf(DEG2RAD*(270 + (180.0f/(rings + 1))*(i + 1)))*cosf(DEG2RAD*(360.0f*(j + 1)/slices))); index++; line_starts(index) = vec3( cosf(DEG2RAD*(270 + (180.0f/(rings + 1))*(i + 1)))*sinf(DEG2RAD*(360.0f*(j + 1)/slices)), sinf(DEG2RAD*(270 + (180.0f/(rings + 1))*(i + 1))), cosf(DEG2RAD*(270 + (180.0f/(rings + 1))*(i + 1)))*cosf(DEG2RAD*(360.0f*(j + 1)/slices))); line_stops(index) = vec3( cosf(DEG2RAD*(270 + (180.0f/(rings + 1))*(i + 1)))*sinf(DEG2RAD*(360.0f*j/slices)), sinf(DEG2RAD*(270 + (180.0f/(rings + 1))*(i + 1))), cosf(DEG2RAD*(270 + (180.0f/(rings + 1))*(i + 1)))*cosf(DEG2RAD*(360.0f*j/slices))); index++; line_starts(index) = vec3( cosf(DEG2RAD*(270 + (180.0f/(rings + 1))*(i + 1)))*sinf(DEG2RAD*(360.0f*j/slices)), sinf(DEG2RAD*(270 + (180.0f/(rings + 1))*(i + 1))), cosf(DEG2RAD*(270 + (180.0f/(rings + 1))*(i + 1)))*cosf(DEG2RAD*(360.0f*j/slices))); line_stops(index) = vec3( cosf(DEG2RAD*(270 + (180.0f/(rings + 1))*i))*sinf(DEG2RAD*(360.0f*j/slices)), sinf(DEG2RAD*(270 + (180.0f/(rings + 1))*i)), cosf(DEG2RAD*(270 + (180.0f/(rings + 1))*i))*cosf(DEG2RAD*(360.0f*j/slices))); index++; } } assert(index == count); } void draw_limit_samples( const slice1d<vec3> subsampled_rotations, const vec3 limit_position, const mat3 limit_rotation, const vec3 space_offset, const float scale) { DrawCubeWires(to_Vector3(space_offset), scale * 2.0f * PIf, scale * 2.0f * PIf, scale * 2.0f * PIf, GRAY); draw_axis(space_offset + scale * limit_position, limit_rotation, 0.5f * scale * PIf); for (int i = 0; i < subsampled_rotations.size; i ++) { DrawSphereWires( to_Vector3(space_offset + scale * subsampled_rotations(i)), 0.005f, 4, 6, (Color){135, 60, 190, 50}); } } void draw_rectangular_limit_bounds( const vec3 limit_position, const mat3 limit_rotation, const vec3 rectangular_limit_min, const vec3 rectangular_limit_max, const vec3 space_offset, const float scale, const int sphere_rings = 32, const int sphere_slices = 64) { int line_count = generate_sphere_line_count(sphere_rings, sphere_slices); array1d<vec3> line_starts(line_count); array1d<vec3> line_stops(line_count); generate_sphere_lines(line_starts, line_stops, sphere_rings, sphere_slices); for (int i = 0; i < line_count; i++) { vec3 line_start = apply_rectangular_limit( 2.0f * PIf * line_starts(i), rectangular_limit_min, rectangular_limit_max, limit_position, limit_rotation); vec3 line_stop = apply_rectangular_limit( 2.0f * PIf * line_stops(i), rectangular_limit_min, rectangular_limit_max, limit_position, limit_rotation); DrawLine3D( to_Vector3(space_offset + scale * line_start), to_Vector3(space_offset + scale * line_stop), (Color){35, 190, 60, 64}); } } void draw_ellipsoid_limit_bounds( const vec3 limit_position, const mat3 limit_rotation, const vec3 ellipsoid_limit_scale, const vec3 space_offset, const float scale, const int sphere_rings = 32, const int sphere_slices = 64) { int line_count = generate_sphere_line_count(sphere_rings, sphere_slices); array1d<vec3> line_starts(line_count); array1d<vec3> line_stops(line_count); generate_sphere_lines(line_starts, line_stops, sphere_rings, sphere_slices); for (int i = 0; i < line_count; i++) { vec3 line_start = apply_ellipsoid_limit( 2.0f * PIf * line_starts(i), ellipsoid_limit_scale, limit_position, limit_rotation); vec3 line_stop = apply_ellipsoid_limit( 2.0f * PIf * line_stops(i), ellipsoid_limit_scale, limit_position, limit_rotation); DrawLine3D( to_Vector3(space_offset + scale * line_start), to_Vector3(space_offset + scale * line_stop), (Color){35, 190, 60, 64}); } } void draw_kdop_limit_bounds( const vec3 limit_position, const mat3 limit_rotation, const slice1d<float> kdop_limit_mins, const slice1d<float> kdop_limit_maxs, const slice1d<vec3> kdop_axes, const vec3 space_offset, const float scale, const int sphere_rings = 32, const int sphere_slices = 64) { int line_count = generate_sphere_line_count(sphere_rings, sphere_slices); array1d<vec3> line_starts(line_count); array1d<vec3> line_stops(line_count); generate_sphere_lines(line_starts, line_stops, sphere_rings, sphere_slices); for (int i = 0; i < line_count; i++) { vec3 line_start = apply_kdop_limit( 2.0f * PIf * line_starts(i), kdop_limit_mins, kdop_limit_maxs, limit_position, limit_rotation, kdop_axes); vec3 line_stop = apply_kdop_limit( 2.0f * PIf * line_stops(i), kdop_limit_mins, kdop_limit_maxs, limit_position, limit_rotation, kdop_axes); DrawLine3D( to_Vector3(space_offset + scale * line_start), to_Vector3(space_offset + scale * line_stop), (Color){35, 190, 60, 64}); } } void draw_current_limit( const vec3 projected_limit_space_rotation, const vec3 limit_space_rotation, const vec3 space_offset, const float scale) { DrawSphereWires( to_Vector3(space_offset + scale * limit_space_rotation), 0.025f, 4, 8, PINK); DrawSphereWires( to_Vector3(space_offset + scale * projected_limit_space_rotation), 0.025f, 4, 8, PINK); DrawLine3D( to_Vector3(space_offset + scale * limit_space_rotation), to_Vector3(space_offset + scale * projected_limit_space_rotation), PINK); } //-------------------------------------- void update_callback(void* args) { ((std::function<void()>*)args)->operator()(); } int main(void) { // Init Window const int screen_width = 1280; const int screen_height = 720; SetConfigFlags(FLAG_VSYNC_HINT); SetConfigFlags(FLAG_MSAA_4X_HINT); InitWindow(screen_width, screen_height, "raylib [joint limits]"); SetTargetFPS(60); // Camera Camera3D camera = { 0 }; camera.position = (Vector3){ 2.0f, 3.0f, 5.0f }; camera.target = (Vector3){ -0.5f, 1.0f, 0.0f }; camera.up = (Vector3){ 0.0f, 1.0f, 0.0f }; camera.fovy = 45.0f; camera.projection = CAMERA_PERSPECTIVE; float camera_azimuth = 0.0f; float camera_altitude = 0.4f; float camera_distance = 4.0f; // Ground Plane Shader ground_plane_shader = LoadShader("./resources/checkerboard.vs", "./resources/checkerboard.fs"); Mesh ground_plane_mesh = GenMeshPlane(20.0f, 20.0f, 10, 10); Model ground_plane_model = LoadModelFromMesh(ground_plane_mesh); ground_plane_model.materials[0].shader = ground_plane_shader; // Character character character_data; character_load(character_data, "./resources/character.bin"); Shader character_shader = LoadShader("./resources/character.vs", "./resources/character.fs"); Mesh character_mesh = make_character_mesh(character_data); Model character_model = LoadModelFromMesh(character_mesh); character_model.materials[0].shader = character_shader; // Load Animation Data and build Matching Database database db; database_load(db, "./resources/database.bin"); bool reference_pose = true; int frame_index = db.range_starts(0); // Controls int joint_index = 1; float rotation_x = 0.0f; float rotation_y = 0.0f; float rotation_z = 0.0f; // Projection bool limit_swing_twist = false; bool limit_type_edit = false; int limit_type = LIMIT_TYPE_RECTANGULAR; bool projection_enabled = true; bool projection_soften_enabled = true; float projection_soften_falloff = 1.0f; float projection_soften_radius = 0.1f; // IK bool ik_enabled = false; float ik_max_length_buffer = 0.015f; float ik_foot_height = 0.03f; float ik_toe_length = 0.15f; vec3 ik_target = vec3(-0.25f, 0.1f, 0.0f); // Lookat bool lookat_enabled = false; float lookat_azimuth = 0.0f; float lookat_altitude = 0.0f; float lookat_distance = 1.0f; vec3 lookat_target; // Pose Data array1d<vec3> reference_positions(db.nbones()); array1d<quat> reference_rotations(db.nbones()); backward_kinematics_full( reference_positions, reference_rotations, character_data.bone_rest_positions, character_data.bone_rest_rotations, db.bone_parents); array1d<vec3> global_bone_positions(db.nbones()); array1d<quat> global_bone_rotations(db.nbones()); array1d<bool> global_bone_computed(db.nbones()); array1d<vec3> adjusted_bone_positions = db.bone_positions(frame_index); array1d<quat> adjusted_bone_rotations = db.bone_rotations(frame_index); // Twist Axes array1d<vec3> twist_axes(db.nbones()); compute_twist_axes( twist_axes, reference_positions, db.bone_parents); // Reference Space array2d<quat> reference_space_rotations(db.nframes(), db.nbones()); array2d<quat> reference_space_rotations_swing(db.nframes(), db.nbones()); array2d<quat> reference_space_rotations_twist(db.nframes(), db.nbones()); for (int i = 0; i < db.nframes(); i++) { for (int j = 0; j < db.nbones(); j++) { reference_space_rotations(i, j) = quat_inv_mul( reference_rotations(j), db.bone_rotations(i, j)); quat_swing_twist( reference_space_rotations_swing(i, j), reference_space_rotations_twist(i, j), reference_space_rotations(i, j), twist_axes(j)); } } quat_unroll_ranges_inplace( reference_space_rotations, db.range_starts, db.range_stops); quat_unroll_ranges_inplace( reference_space_rotations_swing, db.range_starts, db.range_stops); quat_unroll_ranges_inplace( reference_space_rotations_twist, db.range_starts, db.range_stops); // Limit Space array2d<vec3> limit_space_rotations(db.nframes(), db.nbones()); array2d<vec3> limit_space_rotations_swing(db.nframes(), db.nbones()); array2d<vec3> limit_space_rotations_twist(db.nframes(), db.nbones()); for (int i = 0; i < db.nframes(); i++) { for (int j = 0; j < db.nbones(); j++) { limit_space_rotations(i, j) = quat_to_scaled_angle_axis(reference_space_rotations(i, j)); limit_space_rotations_swing(i, j) = quat_to_scaled_angle_axis(reference_space_rotations_swing(i, j)); limit_space_rotations_twist(i, j) = quat_to_scaled_angle_axis(reference_space_rotations_twist(i, j)); } } // Sub-sample Limit Space Samples array2d<vec3> limit_space_rotations_transpose(db.nbones(), db.nframes()); array2d<vec3> limit_space_rotations_transpose_swing(db.nbones(), db.nframes()); array2d<vec3> limit_space_rotations_transpose_twist(db.nbones(), db.nframes()); array2d_transpose(limit_space_rotations_transpose, limit_space_rotations); array2d_transpose(limit_space_rotations_transpose_swing, limit_space_rotations_swing); array2d_transpose(limit_space_rotations_transpose_twist, limit_space_rotations_twist); std::vector<array1d<vec3>> subsampled_limit_space_rotations(db.nbones()); std::vector<array1d<vec3>> subsampled_limit_space_rotations_swing(db.nbones()); std::vector<array1d<vec3>> subsampled_limit_space_rotations_twist(db.nbones()); for (int j = 0; j < db.nbones(); j++) { subsampled_limit_space_rotations[j].resize(db.nframes()); int count = subsample_naive( subsampled_limit_space_rotations[j], limit_space_rotations_transpose(j)); subsampled_limit_space_rotations[j].resize(count); subsampled_limit_space_rotations_swing[j].resize(db.nframes()); int count_swing = subsample_naive( subsampled_limit_space_rotations_swing[j], limit_space_rotations_transpose_swing(j)); subsampled_limit_space_rotations_swing[j].resize(count_swing); subsampled_limit_space_rotations_twist[j].resize(db.nframes()); int count_twist = subsample_naive( subsampled_limit_space_rotations_twist[j], limit_space_rotations_transpose_twist(j)); subsampled_limit_space_rotations_twist[j].resize(count_twist); } // Fit Limits array1d<vec3> limit_positions(db.nbones()); array1d<mat3> limit_rotations(db.nbones()); array1d<vec3> limit_positions_swing(db.nbones()); array1d<mat3> limit_rotations_swing(db.nbones()); array1d<vec3> limit_positions_twist(db.nbones()); array1d<mat3> limit_rotations_twist(db.nbones()); bool orient_limits = true; if (orient_limits) { for (int j = 0; j < db.nbones(); j++) { fit_limit_orientations( limit_positions(j), limit_rotations(j), subsampled_limit_space_rotations[j]); } for (int j = 0; j < db.nbones(); j++) { fit_limit_orientations( limit_positions_swing(j), limit_rotations_swing(j), subsampled_limit_space_rotations_swing[j]); } for (int j = 0; j < db.nbones(); j++) { fit_limit_orientations( limit_positions_twist(j), limit_rotations_twist(j), subsampled_limit_space_rotations_twist[j]); } } else { limit_positions.zero(); limit_rotations.set(mat3()); limit_positions_swing.zero(); limit_rotations_swing.set(mat3()); limit_positions_twist.zero(); limit_rotations_twist.set(mat3()); } // Rectangular Limits array1d<vec3> rectangular_limit_mins(db.nbones()); array1d<vec3> rectangular_limit_maxs(db.nbones()); array1d<vec3> rectangular_limit_mins_swing(db.nbones()); array1d<vec3> rectangular_limit_maxs_swing(db.nbones()); array1d<vec3> rectangular_limit_mins_twist(db.nbones()); array1d<vec3> rectangular_limit_maxs_twist(db.nbones()); for (int j = 0; j < db.nbones(); j++) { fit_rectangular_limits( rectangular_limit_mins(j), rectangular_limit_maxs(j), limit_positions(j), limit_rotations(j), subsampled_limit_space_rotations[j]); } for (int j = 0; j < db.nbones(); j++) { fit_rectangular_limits( rectangular_limit_mins_swing(j), rectangular_limit_maxs_swing(j), limit_positions_swing(j), limit_rotations_swing(j), subsampled_limit_space_rotations_swing[j]); } for (int j = 0; j < db.nbones(); j++) { fit_rectangular_limits( rectangular_limit_mins_twist(j), rectangular_limit_maxs_twist(j), limit_positions_twist(j), limit_rotations_twist(j), subsampled_limit_space_rotations_twist[j]); } // Ellipsoid Limits array1d<vec3> ellipsoid_limit_scales(db.nbones()); array1d<vec3> ellipsoid_limit_scales_swing(db.nbones()); array1d<vec3> ellipsoid_limit_scales_twist(db.nbones()); for (int j = 0; j < db.nbones(); j++) { fit_ellipsoid_limits( ellipsoid_limit_scales(j), limit_positions(j), limit_rotations(j), subsampled_limit_space_rotations[j]); } for (int j = 0; j < db.nbones(); j++) { fit_ellipsoid_limits( ellipsoid_limit_scales_swing(j), limit_positions_swing(j), limit_rotations_swing(j), subsampled_limit_space_rotations_swing[j]); } for (int j = 0; j < db.nbones(); j++) { fit_ellipsoid_limits( ellipsoid_limit_scales_twist(j), limit_positions_twist(j), limit_rotations_twist(j), subsampled_limit_space_rotations_twist[j]); } // KDop Limits array1d<vec3> kdop_axes(13); kdop_axes( 0) = normalize(vec3( 1.0f, 0.0f, 0.0f)); kdop_axes( 1) = normalize(vec3( 0.0f, 1.0f, 0.0f)); kdop_axes( 2) = normalize(vec3( 0.0f, 0.0f, 1.0f)); kdop_axes( 3) = normalize(vec3( 1.0f, 1.0f, 1.0f)); kdop_axes( 4) = normalize(vec3(-1.0f, 1.0f, 1.0f)); kdop_axes( 5) = normalize(vec3(-1.0f,-1.0f, 1.0f)); kdop_axes( 6) = normalize(vec3( 1.0f,-1.0f, 1.0f)); kdop_axes( 7) = normalize(vec3( 0.0f, 1.0f, 1.0f)); kdop_axes( 8) = normalize(vec3( 0.0f,-1.0f, 1.0f)); kdop_axes( 9) = normalize(vec3( 1.0f, 0.0f, 1.0f)); kdop_axes(10) = normalize(vec3(-1.0f, 0.0f, 1.0f)); kdop_axes(11) = normalize(vec3( 1.0f, 1.0f, 0.0f)); kdop_axes(12) = normalize(vec3(-1.0f, 1.0f, 0.0f)); array2d<float> kdop_limit_mins(db.nbones(), kdop_axes.size); array2d<float> kdop_limit_maxs(db.nbones(), kdop_axes.size); array2d<float> kdop_limit_mins_swing(db.nbones(), kdop_axes.size); array2d<float> kdop_limit_maxs_swing(db.nbones(), kdop_axes.size); array2d<float> kdop_limit_mins_twist(db.nbones(), kdop_axes.size); array2d<float> kdop_limit_maxs_twist(db.nbones(), kdop_axes.size); for (int j = 0; j < db.nbones(); j++) { fit_kdop_limits( kdop_limit_mins(j), kdop_limit_maxs(j), limit_positions(j), limit_rotations(j), subsampled_limit_space_rotations[j], kdop_axes); } for (int j = 0; j < db.nbones(); j++) { fit_kdop_limits( kdop_limit_mins_swing(j), kdop_limit_maxs_swing(j), limit_positions_swing(j), limit_rotations_swing(j), subsampled_limit_space_rotations_swing[j], kdop_axes); } for (int j = 0; j < db.nbones(); j++) { fit_kdop_limits( kdop_limit_mins_twist(j), kdop_limit_maxs_twist(j), limit_positions_twist(j), limit_rotations_twist(j), subsampled_limit_space_rotations_twist[j], kdop_axes); } // Local Adjustment Data array1d<quat> pose_reference_space_rotations = reference_space_rotations(frame_index); array1d<quat> pose_reference_space_rotations_swing = reference_space_rotations_swing(frame_index); array1d<quat> pose_reference_space_rotations_twist = reference_space_rotations_twist(frame_index); array1d<vec3> pose_limit_space_rotations(db.nbones()); array1d<vec3> pose_limit_space_rotations_swing(db.nbones()); array1d<vec3> pose_limit_space_rotations_twist(db.nbones()); for (int i = 0; i < db.nbones(); i++) { pose_limit_space_rotations(i) = quat_to_scaled_angle_axis(pose_reference_space_rotations(i)); pose_limit_space_rotations_swing(i) = quat_to_scaled_angle_axis(pose_reference_space_rotations_swing(i)); pose_limit_space_rotations_twist(i) = quat_to_scaled_angle_axis(pose_reference_space_rotations_twist(i)); } array1d<vec3> pose_limit_space_rotations_projected = pose_limit_space_rotations; array1d<vec3> pose_limit_space_rotations_projected_swing = pose_limit_space_rotations_swing; array1d<vec3> pose_limit_space_rotations_projected_twist = pose_limit_space_rotations_twist; // Go auto update_func = [&]() { float dt = 1.0f / 60.0f; orbit_camera_update( camera, camera_azimuth, camera_altitude, camera_distance, vec3(-0.75f, 1, 0), (IsKeyDown(KEY_LEFT_CONTROL) && IsMouseButtonDown(0)) ? GetMouseDelta().x : 0.0f, (IsKeyDown(KEY_LEFT_CONTROL) && IsMouseButtonDown(0)) ? GetMouseDelta().y : 0.0f, dt); if (reference_pose) { adjusted_bone_positions = reference_positions; adjusted_bone_rotations = reference_rotations; } else { adjusted_bone_positions = db.bone_positions(frame_index); adjusted_bone_rotations = db.bone_rotations(frame_index); } if (!lookat_enabled && ik_enabled) { if (!IsKeyDown(KEY_LEFT_CONTROL) && IsMouseButtonDown(1)) { quat rotation_azimuth = quat_from_angle_axis(camera_azimuth, vec3(0, 1, 0)); ik_target = ik_target + dt * 0.1f * quat_mul_vec3(rotation_azimuth, vec3(GetMouseDelta().x, -GetMouseDelta().y, 0.0f)); } global_bone_computed.zero(); // Compute toe, heel, knee, hip, and root bone positions for (int bone : {Bone_Hips, Bone_RightUpLeg, Bone_RightLeg, Bone_RightFoot, Bone_RightToe}) { forward_kinematics_partial( global_bone_positions, global_bone_rotations, global_bone_computed, adjusted_bone_positions, adjusted_bone_rotations, db.bone_parents, bone); } // Perform simple two-joint IK to place heel ik_two_bone( adjusted_bone_rotations(Bone_RightUpLeg), adjusted_bone_rotations(Bone_RightLeg), global_bone_positions(Bone_RightUpLeg), global_bone_positions(Bone_RightLeg), global_bone_positions(Bone_RightFoot), ik_target + (global_bone_positions(Bone_RightFoot) - global_bone_positions(Bone_RightToe)), quat_mul_vec3(global_bone_rotations(Bone_RightLeg), vec3(0.0f, 1.0f, 0.0f)), global_bone_rotations(Bone_RightUpLeg), global_bone_rotations(Bone_RightLeg), global_bone_rotations(Bone_Hips), ik_max_length_buffer); // Apply Joint Limits for (int bone : { Bone_RightUpLeg, Bone_RightLeg }) { apply_joint_limit( adjusted_bone_rotations(bone), pose_limit_space_rotations(bone), pose_limit_space_rotations_swing(bone), pose_limit_space_rotations_twist(bone), pose_limit_space_rotations_projected(bone), pose_limit_space_rotations_projected_swing(bone), pose_limit_space_rotations_projected_twist(bone), reference_rotations(bone), limit_type, rectangular_limit_mins(bone), rectangular_limit_maxs(bone), rectangular_limit_mins_swing(bone), rectangular_limit_maxs_swing(bone), rectangular_limit_mins_twist(bone), rectangular_limit_maxs_twist(bone), ellipsoid_limit_scales(bone), ellipsoid_limit_scales_swing(bone), ellipsoid_limit_scales_twist(bone), kdop_limit_mins(bone), kdop_limit_maxs(bone), kdop_limit_mins_swing(bone), kdop_limit_maxs_swing(bone), kdop_limit_mins_twist(bone), kdop_limit_maxs_twist(bone), limit_positions(bone), limit_rotations(bone), limit_positions_swing(bone), limit_rotations_swing(bone), limit_positions_twist(bone), limit_rotations_twist(bone), kdop_axes, limit_swing_twist, twist_axes(bone), projection_enabled, projection_soften_enabled, projection_soften_falloff, projection_soften_radius); } // Re-compute toe, heel, and knee positions global_bone_computed.zero(); for (int bone : {Bone_RightToe, Bone_RightFoot, Bone_RightLeg}) { forward_kinematics_partial( global_bone_positions, global_bone_rotations, global_bone_computed, adjusted_bone_positions, adjusted_bone_rotations, db.bone_parents, bone); } // Rotate heel so toe is facing toward contact point ik_look_at( adjusted_bone_rotations(Bone_RightFoot), global_bone_rotations(Bone_RightLeg), global_bone_rotations(Bone_RightFoot), global_bone_positions(Bone_RightFoot), global_bone_positions(Bone_RightToe), ik_target); // Apply Joint Limits for (int bone : { Bone_RightFoot }) { apply_joint_limit( adjusted_bone_rotations(bone), pose_limit_space_rotations(bone), pose_limit_space_rotations_swing(bone), pose_limit_space_rotations_twist(bone), pose_limit_space_rotations_projected(bone), pose_limit_space_rotations_projected_swing(bone), pose_limit_space_rotations_projected_twist(bone), reference_rotations(bone), limit_type, rectangular_limit_mins(bone), rectangular_limit_maxs(bone), rectangular_limit_mins_swing(bone), rectangular_limit_maxs_swing(bone), rectangular_limit_mins_twist(bone), rectangular_limit_maxs_twist(bone), ellipsoid_limit_scales(bone), ellipsoid_limit_scales_swing(bone), ellipsoid_limit_scales_twist(bone), kdop_limit_mins(bone), kdop_limit_maxs(bone), kdop_limit_mins_swing(bone), kdop_limit_maxs_swing(bone), kdop_limit_mins_twist(bone), kdop_limit_maxs_twist(bone), limit_positions(bone), limit_rotations(bone), limit_positions_swing(bone), limit_rotations_swing(bone), limit_positions_twist(bone), limit_rotations_twist(bone), kdop_axes, limit_swing_twist, twist_axes(bone), projection_enabled, projection_soften_enabled, projection_soften_falloff, projection_soften_radius); } } else if (lookat_enabled) { // Compute look-at target if (!IsKeyDown(KEY_LEFT_CONTROL) && IsMouseButtonDown(1)) { lookat_azimuth += dt * 0.1f * GetMouseDelta().x; lookat_altitude += dt * 0.1f * -GetMouseDelta().y; } quat lookat_rotation_azimuth = quat_from_angle_axis(lookat_azimuth, vec3(0, 1, 0)); vec3 lookat_position = quat_mul_vec3(lookat_rotation_azimuth, vec3(0, 0, lookat_distance)); vec3 lookat_axis = normalize(cross(lookat_position, vec3(0, 1, 0))); quat lookat_rotation_altitude = quat_from_angle_axis(lookat_altitude, lookat_axis); lookat_target = vec3(0.0f, 1.5f, 0.0f) + quat_mul_vec3(lookat_rotation_altitude, lookat_position); // Compute FK for head Joint global_bone_computed.zero(); forward_kinematics_partial( global_bone_positions, global_bone_rotations, global_bone_computed, adjusted_bone_positions, adjusted_bone_rotations, db.bone_parents, Bone_Head); // Rotate Spine Joints vec3 lookat_direction = normalize(lookat_target - global_bone_positions(Bone_Head)); float spine_scale = 1.5f; adjusted_bone_rotations(Bone_Spine) = quat_mul( adjusted_bone_rotations(Bone_Spine), quat_from_angle_axis(0.1f * spine_scale * lookat_azimuth, vec3(1, 0, 0))); adjusted_bone_rotations(Bone_Spine1) = quat_mul( adjusted_bone_rotations(Bone_Spine1), quat_from_angle_axis(0.2f * spine_scale * lookat_azimuth, vec3(1, 0, 0))); adjusted_bone_rotations(Bone_Spine2) = quat_mul( adjusted_bone_rotations(Bone_Spine2), quat_from_angle_axis(0.3f * spine_scale * lookat_azimuth, vec3(1, 0, 0))); adjusted_bone_rotations(Bone_Neck) = quat_mul( adjusted_bone_rotations(Bone_Neck), quat_from_angle_axis(0.4f * spine_scale * lookat_azimuth, vec3(1, 0, 0))); adjusted_bone_rotations(Bone_Spine) = quat_mul( adjusted_bone_rotations(Bone_Spine), quat_from_angle_axis(0.1f * spine_scale * lookat_altitude, vec3(0, 0, -1))); adjusted_bone_rotations(Bone_Spine1) = quat_mul( adjusted_bone_rotations(Bone_Spine1), quat_from_angle_axis(0.2f * spine_scale * lookat_altitude, vec3(0, 0, -1))); adjusted_bone_rotations(Bone_Spine2) = quat_mul( adjusted_bone_rotations(Bone_Spine2), quat_from_angle_axis(0.3f * spine_scale * lookat_altitude, vec3(0, 0, -1))); adjusted_bone_rotations(Bone_Neck) = quat_mul( adjusted_bone_rotations(Bone_Neck), quat_from_angle_axis(0.4f * spine_scale * lookat_altitude, vec3(0, 0, -1))); // Apply Joint Limits for (int bone : { Bone_Spine, Bone_Spine1, Bone_Spine2, Bone_Neck }) { apply_joint_limit( adjusted_bone_rotations(bone), pose_limit_space_rotations(bone), pose_limit_space_rotations_swing(bone), pose_limit_space_rotations_twist(bone), pose_limit_space_rotations_projected(bone), pose_limit_space_rotations_projected_swing(bone), pose_limit_space_rotations_projected_twist(bone), reference_rotations(bone), limit_type, rectangular_limit_mins(bone), rectangular_limit_maxs(bone), rectangular_limit_mins_swing(bone), rectangular_limit_maxs_swing(bone), rectangular_limit_mins_twist(bone), rectangular_limit_maxs_twist(bone), ellipsoid_limit_scales(bone), ellipsoid_limit_scales_swing(bone), ellipsoid_limit_scales_twist(bone), kdop_limit_mins(bone), kdop_limit_maxs(bone), kdop_limit_mins_swing(bone), kdop_limit_maxs_swing(bone), kdop_limit_mins_twist(bone), kdop_limit_maxs_twist(bone), limit_positions(bone), limit_rotations(bone), limit_positions_swing(bone), limit_rotations_swing(bone), limit_positions_twist(bone), limit_rotations_twist(bone), kdop_axes, limit_swing_twist, twist_axes(bone), projection_enabled, projection_soften_enabled, projection_soften_falloff, projection_soften_radius); } // Re-Compute FK for head and neck global_bone_computed.zero(); for (int bone : {Bone_Head, Bone_Neck}) { forward_kinematics_partial( global_bone_positions, global_bone_rotations, global_bone_computed, adjusted_bone_positions, adjusted_bone_rotations, db.bone_parents, bone); } // Basic Look-at toward target vec3 head_lookat_curr = quat_mul_vec3( global_bone_rotations(Bone_Head), vec3(0.0f, 1.0f, 0.0f)) + global_bone_positions(Bone_Head); vec3 head_lookat_targ = normalize(lookat_target - global_bone_positions(Bone_Head)) + global_bone_positions(Bone_Head); ik_look_at( adjusted_bone_rotations(Bone_Head), global_bone_rotations(Bone_Neck), global_bone_rotations(Bone_Head), global_bone_positions(Bone_Head), head_lookat_curr, head_lookat_targ); // Apply Joint Limits for (int bone : { Bone_Head }) { apply_joint_limit( adjusted_bone_rotations(bone), pose_limit_space_rotations(bone), pose_limit_space_rotations_swing(bone), pose_limit_space_rotations_twist(bone), pose_limit_space_rotations_projected(bone), pose_limit_space_rotations_projected_swing(bone), pose_limit_space_rotations_projected_twist(bone), reference_rotations(bone), limit_type, rectangular_limit_mins(bone), rectangular_limit_maxs(bone), rectangular_limit_mins_swing(bone), rectangular_limit_maxs_swing(bone), rectangular_limit_mins_twist(bone), rectangular_limit_maxs_twist(bone), ellipsoid_limit_scales(bone), ellipsoid_limit_scales_swing(bone), ellipsoid_limit_scales_twist(bone), kdop_limit_mins(bone), kdop_limit_maxs(bone), kdop_limit_mins_swing(bone), kdop_limit_maxs_swing(bone), kdop_limit_mins_twist(bone), kdop_limit_maxs_twist(bone), limit_positions(bone), limit_rotations(bone), limit_positions_swing(bone), limit_rotations_swing(bone), limit_positions_twist(bone), limit_rotations_twist(bone), kdop_axes, limit_swing_twist, twist_axes(bone), projection_enabled, projection_soften_enabled, projection_soften_falloff, projection_soften_radius); } } else { // Adjust selected bone adjusted_bone_rotations(joint_index) = quat_mul( adjusted_bone_rotations(joint_index), quat_from_euler_xyz(rotation_x, rotation_y, rotation_z)); // Apply joint limits apply_joint_limit( adjusted_bone_rotations(joint_index), pose_limit_space_rotations(joint_index), pose_limit_space_rotations_swing(joint_index), pose_limit_space_rotations_twist(joint_index), pose_limit_space_rotations_projected(joint_index), pose_limit_space_rotations_projected_swing(joint_index), pose_limit_space_rotations_projected_twist(joint_index), reference_rotations(joint_index), limit_type, rectangular_limit_mins(joint_index), rectangular_limit_maxs(joint_index), rectangular_limit_mins_swing(joint_index), rectangular_limit_maxs_swing(joint_index), rectangular_limit_mins_twist(joint_index), rectangular_limit_maxs_twist(joint_index), ellipsoid_limit_scales(joint_index), ellipsoid_limit_scales_swing(joint_index), ellipsoid_limit_scales_twist(joint_index), kdop_limit_mins(joint_index), kdop_limit_maxs(joint_index), kdop_limit_mins_swing(joint_index), kdop_limit_maxs_swing(joint_index), kdop_limit_mins_twist(joint_index), kdop_limit_maxs_twist(joint_index), limit_positions(joint_index), limit_rotations(joint_index), limit_positions_swing(joint_index), limit_rotations_swing(joint_index), limit_positions_twist(joint_index), limit_rotations_twist(joint_index), kdop_axes, limit_swing_twist, twist_axes(joint_index), projection_enabled, projection_soften_enabled, projection_soften_falloff, projection_soften_radius); } // Done! forward_kinematics_full( global_bone_positions, global_bone_rotations, adjusted_bone_positions, adjusted_bone_rotations, db.bone_parents); // Render BeginDrawing(); ClearBackground(RAYWHITE); BeginMode3D(camera); // Draw Targets if (!lookat_enabled && ik_enabled) { DrawSphereWires( to_Vector3(ik_target), 0.025, 4, 8, VIOLET); } else if (lookat_enabled) { DrawLine3D( to_Vector3(global_bone_positions(Bone_Head)), to_Vector3(lookat_target), VIOLET); DrawSphereWires( to_Vector3(lookat_target), 0.025, 4, 8, VIOLET); } // Draw Joint Limit Data float scale = 0.15f; if (limit_swing_twist) { vec3 space_offset_swing = vec3(-1.0f, 1.0f, 0.0f); vec3 space_offset_twist = vec3(-2.0f, 1.0f, 0.0f); draw_current_limit( pose_limit_space_rotations_projected_swing(joint_index), pose_limit_space_rotations_swing(joint_index), space_offset_swing, scale); draw_current_limit( pose_limit_space_rotations_projected_twist(joint_index), pose_limit_space_rotations_twist(joint_index), space_offset_twist, scale); draw_limit_samples( subsampled_limit_space_rotations_swing[joint_index], limit_positions_swing(joint_index), limit_rotations_swing(joint_index), space_offset_swing, scale); draw_limit_samples( subsampled_limit_space_rotations_twist[joint_index], limit_positions_twist(joint_index), limit_rotations_twist(joint_index), space_offset_twist, scale); if (limit_type == LIMIT_TYPE_RECTANGULAR) { draw_rectangular_limit_bounds( limit_positions_swing(joint_index), limit_rotations_swing(joint_index), rectangular_limit_mins_swing(joint_index), rectangular_limit_maxs_swing(joint_index), space_offset_swing, scale); draw_rectangular_limit_bounds( limit_positions_twist(joint_index), limit_rotations_twist(joint_index), rectangular_limit_mins_twist(joint_index), rectangular_limit_maxs_twist(joint_index), space_offset_twist, scale); } else if (limit_type == LIMIT_TYPE_ELLIPSOID) { draw_ellipsoid_limit_bounds( limit_positions_swing(joint_index), limit_rotations_swing(joint_index), ellipsoid_limit_scales_swing(joint_index), space_offset_swing, scale); draw_ellipsoid_limit_bounds( limit_positions_twist(joint_index), limit_rotations_twist(joint_index), ellipsoid_limit_scales_twist(joint_index), space_offset_twist, scale); } else if (limit_type == LIMIT_TYPE_KDOP) { draw_kdop_limit_bounds( limit_positions_swing(joint_index), limit_rotations_swing(joint_index), kdop_limit_mins_swing(joint_index), kdop_limit_maxs_swing(joint_index), kdop_axes, space_offset_swing, scale); draw_kdop_limit_bounds( limit_positions_twist(joint_index), limit_rotations_twist(joint_index), kdop_limit_mins_twist(joint_index), kdop_limit_maxs_twist(joint_index), kdop_axes, space_offset_twist, scale); } else { assert(false); } } else { vec3 space_offset = vec3(-1.0f, 1.0f, 0.0f); draw_current_limit( pose_limit_space_rotations_projected(joint_index), pose_limit_space_rotations(joint_index), space_offset, scale); draw_limit_samples( subsampled_limit_space_rotations[joint_index], limit_positions(joint_index), limit_rotations(joint_index), space_offset, scale); if (limit_type == LIMIT_TYPE_RECTANGULAR) { draw_rectangular_limit_bounds( limit_positions(joint_index), limit_rotations(joint_index), rectangular_limit_mins(joint_index), rectangular_limit_maxs(joint_index), space_offset, scale); } else if (limit_type == LIMIT_TYPE_ELLIPSOID) { draw_ellipsoid_limit_bounds( limit_positions(joint_index), limit_rotations(joint_index), ellipsoid_limit_scales(joint_index), space_offset, scale); } else if (limit_type == LIMIT_TYPE_KDOP) { draw_kdop_limit_bounds( limit_positions(joint_index), limit_rotations(joint_index), kdop_limit_mins(joint_index), kdop_limit_maxs(joint_index), kdop_axes, space_offset, scale); } else { assert(false); } } // Draw Character deform_character_mesh( character_mesh, character_data, global_bone_positions, global_bone_rotations, db.bone_parents); DrawModel(character_model, (Vector3){0.0f, 0.0f, 0.0f}, 1.0f, RAYWHITE); draw_skeleton( global_bone_positions, global_bone_rotations, db.bone_parents, joint_index); // Draw Ground Plane DrawModel(ground_plane_model, (Vector3){0.0f, -0.01f, 0.0f}, 1.0f, WHITE); DrawGrid(20, 1.0f); draw_axis(vec3(), quat()); EndMode3D(); // UI int frame_index_prev = frame_index; int joint_index_prev = joint_index; //--------- float ui_ctrl_hei = 20; GuiGroupBox((Rectangle){ 1010, ui_ctrl_hei, 250, 80 }, "controls"); GuiLabel((Rectangle){ 1030, ui_ctrl_hei + 10, 200, 20 }, "Ctrl + Left Click - Move Camera"); GuiLabel((Rectangle){ 1030, ui_ctrl_hei + 30, 200, 20 }, "Mouse Wheel - Zoom"); GuiLabel((Rectangle){ 1030, ui_ctrl_hei + 50, 200, 20 }, "Right Click - Move target"); //--------- float ui_hei_anim = 20; GuiGroupBox((Rectangle){ 20, ui_hei_anim, 920, 70 }, "animation"); frame_index = (int)GuiSliderBar( (Rectangle){ 100, ui_hei_anim + 10, 800, 20 }, "frame index", TextFormat("%4i", frame_index), frame_index, 0, db.range_stops(0)); reference_pose = GuiCheckBox( (Rectangle){ 100, ui_hei_anim + 40, 20, 20 }, "reference pose", reference_pose); //--------- float ui_hei_rot = 100; GuiGroupBox((Rectangle){ 20, ui_hei_rot, 360, 130 }, "rotation"); joint_index = (int)GuiSliderBar( (Rectangle){ 100, ui_hei_rot + 10, 200, 20 }, "joint", TextFormat("%s", BoneNames[joint_index]), joint_index, 1, db.nbones() - 1); rotation_x = GuiSliderBar( (Rectangle){ 100, ui_hei_rot + 40, 200, 20 }, "rotation x", TextFormat("%3.2f", rotation_x), rotation_x, -PIf, PIf); rotation_y = GuiSliderBar( (Rectangle){ 100, ui_hei_rot + 70, 200, 20 }, "rotation y", TextFormat("%3.2f", rotation_y), rotation_y, -PIf, PIf); rotation_z = GuiSliderBar( (Rectangle){ 100, ui_hei_rot + 100, 200, 20 }, "rotation z", TextFormat("%3.2f", rotation_z), rotation_z, -PIf, PIf); //--------- float ui_hei_proj = 240; GuiGroupBox((Rectangle){ 20, ui_hei_proj, 260, 190 }, "projection"); projection_enabled = GuiCheckBox( (Rectangle){ 120, ui_hei_proj + 10, 20, 20 }, "enabled", projection_enabled); projection_soften_enabled = GuiCheckBox( (Rectangle){ 120, ui_hei_proj + 40, 20, 20 }, "soften", projection_soften_enabled); projection_soften_falloff = GuiSliderBar( (Rectangle){ 120, ui_hei_proj + 70, 120, 20 }, "soften falloff", TextFormat("%3.2f", projection_soften_falloff), projection_soften_falloff, 0.0f, 5.0f); projection_soften_radius = GuiSliderBar( (Rectangle){ 120, ui_hei_proj + 100, 120, 20 }, "soften radius", TextFormat("%3.2f", projection_soften_radius), projection_soften_radius, 0.0f, 1.0f); limit_swing_twist = GuiCheckBox( (Rectangle){ 120, ui_hei_proj + 130, 20, 20 }, "swing twist", limit_swing_twist); if (GuiDropdownBox( (Rectangle){ 120, ui_hei_proj + 160, 120, 20 }, "Rectangular;Ellipsoid;KDop", &limit_type, limit_type_edit)) { limit_type_edit = !limit_type_edit; } //--------- float ui_hei_ik = 440; GuiGroupBox((Rectangle){ 20, ui_hei_ik, 260, 40 }, "inverse kinematics"); ik_enabled = GuiCheckBox( (Rectangle){ 120, ui_hei_ik + 10, 20, 20 }, "enabled", ik_enabled); //--------- float ui_hei_lookat = 490; GuiGroupBox((Rectangle){ 20, ui_hei_lookat, 260, 40 }, "look-at"); lookat_enabled = GuiCheckBox( (Rectangle){ 120, ui_hei_lookat + 10, 20, 20 }, "enabled", lookat_enabled); EndDrawing(); if (joint_index != joint_index_prev || frame_index != frame_index_prev) { rotation_x = 0.0f; rotation_y = 0.0f; rotation_z = 0.0f; } }; #if defined(PLATFORM_WEB) std::function<void()> u{update_func}; emscripten_set_main_loop_arg(update_callback, &u, 0, 1); #else while (!WindowShouldClose()) { update_func(); } #endif // Unload stuff and finish UnloadModel(character_model); UnloadModel(ground_plane_model); UnloadShader(character_shader); UnloadShader(ground_plane_shader); CloseWindow(); return 0; }
35.649565
136
0.567139
[ "mesh", "render", "vector", "model", "transform" ]
5d64f37c8aa3d2c3dbabde71b9f67216f7106b08
50,145
cpp
C++
BuiltinType.cpp
zyd2001/NewBie
6d197d0b4b69b6f4f875c2e0fc0b2c2c506603f4
[ "MIT" ]
null
null
null
BuiltinType.cpp
zyd2001/NewBie
6d197d0b4b69b6f4f875c2e0fc0b2c2c506603f4
[ "MIT" ]
null
null
null
BuiltinType.cpp
zyd2001/NewBie
6d197d0b4b69b6f4f875c2e0fc0b2c2c506603f4
[ "MIT" ]
null
null
null
#include "NewBie_Lang.hpp" #include "NewBie.hpp" #include <codecvt> #include <locale> #include <sstream> using namespace std; namespace zyd2001 { namespace NewBie { wstring_convert<codecvt_utf8<char_t>, char_t> conv; int32_t zyd2001::NewBie::object_container_t::getInt() { return obj->useNativePointer<int32_t>(); } double zyd2001::NewBie::object_container_t::getDouble() { return obj->useNativePointer<double>(); } bool zyd2001::NewBie::object_container_t::getBool() { return obj->useNativePointer<bool>(); } String zyd2001::NewBie::object_container_t::getString() { return obj->useNativePointer<String>(); } Function object_container_t::getFunction() { return obj->useNativePointer<Function>(); } Class object_container_t::getClass() { return obj->useNativePointer<Class>(); } ObjectContainer objectToString(Runner &runner, object_t * obj, const Args & args) { return ObjectContainer(runner, object_str); } #define intBiOp(name, op)\ ObjectContainer int ## name (Runner &runner, object_t * obj, const Args & args)\ {\ int32_t &i1 = obj->useNativePointer<int32_t>();\ int32_t i2 = args[0]->getInt();\ return ObjectContainer(runner, i1 op i2);\ } intBiOp(Add, +) intBiOp(Sub, -) intBiOp(Mul, *) intBiOp(Div, / ) intBiOp(Mod, %) intBiOp(Lt, <) intBiOp(Le, <= ) intBiOp(Gt, > ) intBiOp(Ge, >= ) intBiOp(Eq, == ) intBiOp(Ne, !=) intBiOp(BitAnd, &) intBiOp(BitOr, | ) intBiOp(BitXor, ^) intBiOp(BitLeft, << ) intBiOp(BitRight, >>) #define intBiOpD(name, op)\ ObjectContainer int ## name ## D (Runner &runner, object_t * obj, const Args & args)\ {\ int32_t &i = obj->useNativePointer<int32_t>();\ double d = args[0]->getDouble();\ return ObjectContainer(runner, i op d);\ } intBiOpD(Add, +) intBiOpD(Sub, -) intBiOpD(Mul, *) intBiOpD(Div, / ) intBiOpD(Lt, <) intBiOpD(Le, <= ) intBiOpD(Gt, >) intBiOpD(Ge, >= ) intBiOpD(Eq, == ) intBiOpD(Ne, != ) ObjectContainer intMinus(Runner &runner, object_t * obj, const Args & args) {//int int32_t &i = obj->useNativePointer<int32_t>(); return ObjectContainer(runner, -i); } ObjectContainer intPlus(Runner &runner, object_t * obj, const Args & args) {//int int32_t &i = obj->useNativePointer<int32_t>(); return ObjectContainer(runner, +i); } ObjectContainer intNegate(Runner &runner, object_t * obj, const Args & args) {//int int32_t &i = obj->useNativePointer<int32_t>(); return ObjectContainer(runner, !i); } ObjectContainer intNot(Runner &runner, object_t * obj, const Args & args) {//int int32_t &i = obj->useNativePointer<int32_t>(); return ObjectContainer(runner, ~i); } ObjectContainer intCalli(Runner &runner, object_t * obj, const Args & args) {//int, int int32_t &i = obj->useNativePointer<int32_t>(); int32_t arg = args[0]->getInt(); return ObjectContainer(runner, i * arg); } ObjectContainer intCalld(Runner &runner, object_t * obj, const Args & args) {//int, double int32_t &i = obj->useNativePointer<int32_t>(); double arg = args[0]->getDouble(); return ObjectContainer(runner, i * arg); } ObjectContainer intToBool(Runner &runner, object_t * obj, const Args & args) {//int32_t int32_t &i = obj->useNativePointer<int32_t>(); return ObjectContainer(runner, bool(i)); } ObjectContainer intToString(Runner &runner, object_t * obj, const Args & args) {//int32_t int32_t &i = obj->useNativePointer<int32_t>(); return ObjectContainer(runner, std::to_string(i)); } ObjectContainer intCtorD(Runner & runner, object_t * obj, const Args & args) { int32_t &i = obj->useNativePointer<int32_t>(); double num = args[0]->getDouble(); i = num; return runner.nullObj; } ObjectContainer intCtorStr(Runner & runner, object_t * obj, const Args & args) { int32_t &i = obj->useNativePointer<int32_t>(); String s = args[0]->getString(); long num = stol(s.toStr()); // long is at least 32 bit if (sizeof(long) > sizeof(int32_t)) if (num > INT32_MAX || num < INT32_MIN) throw out_of_range("out of range"); i = static_cast<int32_t>(num); return runner.nullObj; } ObjectContainer intCtorBool(Runner & runner, object_t * obj, const Args & args) { int32_t &i = obj->useNativePointer<int32_t>(); bool b = args[0]->getBool(); i = b ? 1 : 0; return runner.nullObj; } ObjectContainer intCtor(Runner & runner, object_t * obj, const Args & args) { int32_t &i = obj->useNativePointer<int32_t>(); i = 0; return runner.nullObj; } ObjectContainer intCopy(Runner &runner, object_t * obj, const Args & args) { int32_t &i = obj->useNativePointer<int32_t>(); int32_t num = args[0]->getInt(); i = num; return runner.nullObj; } void intPtrDeleter(void * i) { delete static_cast<int32_t*>(i); } #define doubleBiOp(name, op) \ ObjectContainer double ## name (Runner &runner, object_t * obj, const Args & args)\ {\ double &i1 = obj->useNativePointer<double>();\ double i2 = args[0]->getDouble();\ return ObjectContainer(runner, i1 op i2);\ } doubleBiOp(Add, +) doubleBiOp(Sub, -) doubleBiOp(Mul, *) doubleBiOp(Div, / ) doubleBiOp(Lt, <) doubleBiOp(Le, <= ) doubleBiOp(Gt, >) doubleBiOp(Ge, >= ) doubleBiOp(Eq, == ) doubleBiOp(Ne, != ) #define doubleBiOpI(name, op)\ ObjectContainer double ## name ## I(Runner &runner, object_t * obj, const Args & args)\ {\ double &i1 = obj->useNativePointer<double>();\ int32_t i2 = args[0]->getInt();\ return ObjectContainer(runner, i1 op i2);\ } doubleBiOpI(Add, +) doubleBiOpI(Sub, -) doubleBiOpI(Mul, *) doubleBiOpI(Div, / ) doubleBiOpI(Lt, <) doubleBiOpI(Le, <= ) doubleBiOpI(Gt, >) doubleBiOpI(Ge, >= ) doubleBiOpI(Eq, == ) doubleBiOpI(Ne, != ) ObjectContainer doubleMinus(Runner &runner, object_t * obj, const Args & args) {//double double &i = obj->useNativePointer<double>(); return ObjectContainer(runner, -i); } ObjectContainer doublePlus(Runner &runner, object_t * obj, const Args & args) {//double double &i = obj->useNativePointer<double>(); return ObjectContainer(runner, +i); } ObjectContainer doubleNegate(Runner &runner, object_t * obj, const Args & args) {//double double &i = obj->useNativePointer<double>(); return ObjectContainer(runner, !i); } ObjectContainer doubleCalli(Runner &runner, object_t * obj, const Args & args) {//double, int32_t double &d = obj->useNativePointer<double>(); int32_t i = args[0]->getInt(); return ObjectContainer(runner, i * d); } ObjectContainer doubleCalld(Runner &runner, object_t * obj, const Args & args) {//double, double double &d = obj->useNativePointer<double>(); double i = args[0]->getDouble(); return ObjectContainer(runner, i * d); } ObjectContainer doubleToBool(Runner &runner, object_t * obj, const Args & args) {//double double &i = obj->useNativePointer<double>(); return ObjectContainer(runner, bool(i)); } ObjectContainer doubleToString(Runner &runner, object_t * obj, const Args & args) {//double double &i = obj->useNativePointer<double>(); return ObjectContainer(runner, std::to_string(i)); } ObjectContainer doubleCtor(Runner &runner, object_t * obj, const Args & args) { double &i = obj->useNativePointer<double>(); i = 0; return runner.nullObj; } ObjectContainer doubleCtorI(Runner &runner, object_t * obj, const Args & args) { double &i = obj->useNativePointer<double>(); int32_t num = args[0]->getInt(); i = num; return runner.nullObj; } ObjectContainer doubleCtorStr(Runner &runner, object_t * obj, const Args & args) { double &i = obj->useNativePointer<double>(); String num = args[0]->getString(); i = stod(num.toStr()); return runner.nullObj; } ObjectContainer doubleCopy(Runner &runner, object_t * obj, const Args & args) {//double double &i = obj->useNativePointer<double>(); double num = args[0]->getDouble(); i = num; return runner.nullObj; } void doublePtrDeleter(void * i) { delete static_cast<double*>(i); } ObjectContainer booleanEq(Runner & runner, object_t * obj, const Args & args) { bool &b1 = obj->useNativePointer<bool>(); bool b2 = args[0]->getBool(); return ObjectContainer(runner, b1 == b2); } ObjectContainer booleanNe(Runner & runner, object_t * obj, const Args & args) { bool &b1 = obj->useNativePointer<bool>(); bool b2 = args[0]->getBool(); return ObjectContainer(runner, b1 != b2); } ObjectContainer booleanNegate(Runner & runner, object_t * obj, const Args & args) { bool &b = obj->useNativePointer<bool>(); return ObjectContainer(runner, !b); } ObjectContainer booleanAnd(Runner & runner, object_t * obj, const Args & args) { bool &b1 = obj->useNativePointer<bool>(); bool b2 = args[0]->getBool(); return ObjectContainer(runner, b1 && b2); } ObjectContainer booleanOr(Runner & runner, object_t * obj, const Args & args) { bool &b1 = obj->useNativePointer<bool>(); bool b2 = args[0]->getBool(); return ObjectContainer(runner, b1 || b2); } ObjectContainer booleanToString(Runner &runner, object_t * obj, const Args & args) {//bool bool &i = obj->useNativePointer<bool>(); if (i) return ObjectContainer(runner, true_str); else return ObjectContainer(runner, false_str); } ObjectContainer booleanCtor(Runner &runner, object_t * obj, const Args & args) {//bool bool &i = obj->useNativePointer<bool>(); i = false; return runner.nullObj; } ObjectContainer booleanCopy(Runner &runner, object_t * obj, const Args & args) {//bool bool &i = obj->useNativePointer<bool>(); bool b = args[0]->getBool(); i = b; return runner.nullObj; } void booleanPtrDeleter(void * i) { delete static_cast<bool*>(i); } ObjectContainer stringAdd(Runner &runner, object_t * obj, const Args & args) {//string, string String &s1 = obj->useNativePointer<String>(); String s2 = args[0].call(runner, toString_str)->getString(); return ObjectContainer(runner, s1 + s2); } ObjectContainer stringMul(Runner &runner, object_t * obj, const Args & args) {//string, string String &s = obj->useNativePointer<String>(); int32_t i = args[0]->getInt(); std::basic_ostringstream<char_t> os; for (int32_t j = 0; j < i; j++) os << s.get(); return ObjectContainer(runner, os.str()); } #define stringComp(name, op) \ ObjectContainer string ## name (Runner &runner, object_t * obj, const Args & args)\ {\ String &s1 = obj->useNativePointer<String>();\ String s2 = args[0]->getString();\ return ObjectContainer(runner, s1 op s2);\ } stringComp(Lt, <) stringComp(Le, <= ) stringComp(Gt, >) stringComp(Ge, >= ) stringComp(Eq, == ) stringComp(Ne, != ) ObjectContainer stringToBool(Runner &runner, object_t * obj, const Args & args) {//string String &s = obj->useNativePointer<String>(); return ObjectContainer(runner, !s.get().empty()); } ObjectContainer stringToString(Runner &runner, object_t * obj, const Args & args) {//string String &s = obj->useNativePointer<String>(); return ObjectContainer(runner, s); } ObjectContainer stringIndex(Runner &runner, object_t * obj, const Args & args) { String & s = obj->useNativePointer<String>(); int32_t i = args[0]->getInt(); return ObjectContainer(runner, s.ptr->substr(i, 1)); } ObjectContainer stringSubstring(Runner &runner, object_t * obj, const Args & args) { String & s = obj->useNativePointer<String>(); int32_t i1 = args[0]->getInt(); int32_t i2 = args[1]->getInt(); if (i2 == -1) return ObjectContainer(runner, s.ptr->substr(i1)); else return ObjectContainer(runner, s.ptr->substr(i1, i1 + i2)); } ObjectContainer stringSubstr(Runner &runner, object_t * obj, const Args & args) { String & s = obj->useNativePointer<String>(); int32_t i1 = args[0]->getInt(); int32_t i2 = args[1]->getInt(); if (i2 == -1) return ObjectContainer(runner, s.ptr->substr(i1)); else return ObjectContainer(runner, s.ptr->substr(i1, i2)); } ObjectContainer stringCopy(Runner &runner, object_t * obj, const Args & args) {//string String & s = obj->useNativePointer<String>(); String s1 = args[0]->getString(); s = s1; return runner.nullObj; } ObjectContainer stringCtor(Runner &runner, object_t * obj, const Args & args) {//string String & s = obj->useNativePointer<String>(); s = String(); return runner.nullObj; } void stringPtrDeleter(void * p) { delete static_cast<String*>(p); } ObjectContainer functionEq(Runner & runner, object_t * obj, const Args & args) { Function & f = obj->useNativePointer<Function>(); Function f1 = args[0]->getFunction(); return ObjectContainer(runner, f == f1); } ObjectContainer functionNe(Runner & runner, object_t * obj, const Args & args) { Function & f = obj->useNativePointer<Function>(); Function f1 = args[0]->getFunction(); return ObjectContainer(runner, f != f1); } ObjectContainer functionCall(Runner & runner, object_t * obj, const Args & args) { Function & f = obj->useNativePointer<Function>(); object_t * this_ptr = runner.this_ptr; runner.this_ptr = runner.inter->root; return f->call_f(runner, this_ptr, args); // change the call_func_stack } ObjectContainer functionToString(Runner & runner, object_t * obj, const Args & args) { return ObjectContainer(runner, String("function ") + obj->useNativePointer<Function>()->getName()); } ObjectContainer functionCopy(Runner & runner, object_t * obj, const Args & args) { Function & f = obj->useNativePointer<Function>(); Function f1 = args[0]->getFunction(); f = f1; return runner.nullObj; } void functionPtrDeleter(void * p) { delete static_cast<Function*>(p); } ObjectContainer classEq(Runner & runner, object_t * obj, const Args & args) { Class & f = obj->useNativePointer<Class>(); Class f1 = args[0]->getClass(); return ObjectContainer(runner, f == f1); } ObjectContainer classNe(Runner & runner, object_t * obj, const Args & args) { Class & f = obj->useNativePointer<Class>(); Class f1 = args[0]->getClass(); return ObjectContainer(runner, f != f1); } ObjectContainer classCall(Runner & runner, object_t * obj, const Args & args) { Class & cl = obj->useNativePointer<Class>(); return cl->makeObject(runner, args); } ObjectContainer classToString(Runner & runner, object_t * obj, const Args & args) { Class & cl = obj->useNativePointer<Class>(); return ObjectContainer(runner, String("class ") + cl->type_name); } ObjectContainer classCopy(Runner & runner, object_t * obj, const Args & args) { Class & f = obj->useNativePointer<Class>(); Class f1 = args[0]->getClass(); f = f1; return runner.nullObj; } void classPtrDeleter(void * p) { delete static_cast<Class*>(p); } Class InterpreterImp::makeObjectClass() { vector<Class> bases; Function toString = make_shared<function_t>(toString_str, function_t::init_vec { make_pair(make_params(), make_shared<NativeFunction>(NewBie_String, false, objectToString)) }); Operator o; Func dtor = nullFunc; Constructor ctor = make_shared<constructor_t>(constructor_t::init_vec{ make_pair(make_params(), make_shared<NativeConstructor>(NewBie_Variant, true, [&](Runner & runner, object_t * obj, const Args & args) { return *null_obj; }, Args{})), }); Class cl = make_shared<class_t>(this, int_str, NewBie_Int, bases, false, false, false, ctor, dtor, o, class_t::vars(), [](void*) {}); cl->addToPrototype(toString_str, ObjectContainer(*runner, toString), PUBLIC); return cl; } Class InterpreterImp::makeIntClass() { vector<Class> bases{ primitive_class[NewBie_Object] }; Function add = make_shared<function_t>(String("int operator+"), function_t::init_vec { make_pair(make_params(NewBie_Int), make_shared<NativeFunction>(NewBie_Int, false, intAdd)), make_pair(make_params(NewBie_Double), make_shared<NativeFunction>(NewBie_Int, false, intAddD)), }); Function sub = make_shared<function_t>(String("int operator-"), function_t::init_vec { make_pair(make_params(NewBie_Int), make_shared<NativeFunction>(NewBie_Int, false, intSub)), make_pair(make_params(NewBie_Double), make_shared<NativeFunction>(NewBie_Double, false, intSubD)), }); Function mul = make_shared<function_t>(String("int operator*"), function_t::init_vec { make_pair(make_params(NewBie_Int), make_shared<NativeFunction>(NewBie_Int, false, intMul)), make_pair(make_params(NewBie_Double), make_shared<NativeFunction>(NewBie_Double, false, intMulD)), }); Function div = make_shared<function_t>(String("int operator/"), function_t::init_vec { make_pair(make_params(NewBie_Int), make_shared<NativeFunction>(NewBie_Int, false, intDiv)), make_pair(make_params(NewBie_Double), make_shared<NativeFunction>(NewBie_Double, false, intDivD)), }); Function mod = make_shared<function_t>(String("int operator%"), function_t::init_vec { make_pair(make_params(NewBie_Int), make_shared<NativeFunction>(NewBie_Int, false, intMod)) }); Function lt = make_shared<function_t>(String("int operator<"), function_t::init_vec { make_pair(make_params(NewBie_Int), make_shared<NativeFunction>(NewBie_Boolean, false, intLt)), make_pair(make_params(NewBie_Double), make_shared<NativeFunction>(NewBie_Boolean, false, intLtD)), }); Function le = make_shared<function_t>(String("int operator<="), function_t::init_vec { make_pair(make_params(NewBie_Int), make_shared<NativeFunction>(NewBie_Boolean, false, intLe)), make_pair(make_params(NewBie_Double), make_shared<NativeFunction>(NewBie_Boolean, false, intLeD)), }); Function gt = make_shared<function_t>(String("int operator>"), function_t::init_vec { make_pair(make_params(NewBie_Int), make_shared<NativeFunction>(NewBie_Boolean, false, intGt)), make_pair(make_params(NewBie_Double), make_shared<NativeFunction>(NewBie_Boolean, false, intGtD)), }); Function ge = make_shared<function_t>(String("int operator>="), function_t::init_vec { make_pair(make_params(NewBie_Int), make_shared<NativeFunction>(NewBie_Boolean, false, intGe)), make_pair(make_params(NewBie_Double), make_shared<NativeFunction>(NewBie_Boolean, false, intGeD)), }); Function eq = make_shared<function_t>(String("int operator=="), function_t::init_vec { make_pair(make_params(NewBie_Int), make_shared<NativeFunction>(NewBie_Boolean, false, intEq)), make_pair(make_params(NewBie_Double), make_shared<NativeFunction>(NewBie_Boolean, false, intEqD)), }); Function ne = make_shared<function_t>(String("int operator!="), function_t::init_vec { make_pair(make_params(NewBie_Int), make_shared<NativeFunction>(NewBie_Boolean, false, intNe)), make_pair(make_params(NewBie_Double), make_shared<NativeFunction>(NewBie_Boolean, false, intNeD)), }); Function call = make_shared<function_t>(String("int call"), function_t::init_vec { make_pair(make_params(NewBie_Int), make_shared<NativeFunction>(NewBie_Int, false, intCalli)), make_pair(make_params(NewBie_Double), make_shared<NativeFunction>(NewBie_Double, false, intCalld)), }); Function minus = make_shared<function_t>(String("int minus"), function_t::init_vec { make_pair(make_params(), make_shared<NativeFunction>(NewBie_Int, false, intMinus)), }); Function plus = make_shared<function_t>(String("int plus"), function_t::init_vec { make_pair(make_params(), make_shared<NativeFunction>(NewBie_Int, false, intPlus)), }); Function negate = make_shared<function_t>(String("int negate"), function_t::init_vec { make_pair(make_params(), make_shared<NativeFunction>(NewBie_Int, false, intNegate)), }); Function not = make_shared<function_t>(String("int not"), function_t::init_vec { make_pair(make_params(), make_shared<NativeFunction>(NewBie_Int, false, intNot)), }); Function bit_and = make_shared<function_t>(String("int operator&"), function_t::init_vec { make_pair(make_params(NewBie_Int), make_shared<NativeFunction>(NewBie_Int, false, intBitAnd)), }); Function bit_or = make_shared<function_t>(String("int operator|"), function_t::init_vec { make_pair(make_params(NewBie_Int), make_shared<NativeFunction>(NewBie_Int, false, intBitOr)), }); Function bit_xor = make_shared<function_t>(String("int operator^"), function_t::init_vec { make_pair(make_params(NewBie_Int), make_shared<NativeFunction>(NewBie_Int, false, intBitXor)), }); Function bit_left = make_shared<function_t>(String("int operator<<"), function_t::init_vec { make_pair(make_params(NewBie_Int), make_shared<NativeFunction>(NewBie_Int, false, intBitLeft)), }); Function bit_right = make_shared<function_t>(String("int operator>>"), function_t::init_vec { make_pair(make_params(NewBie_Int), make_shared<NativeFunction>(NewBie_Int, false, intBitRight)), }); Function tobool = make_shared<function_t>(String("int tobool"), function_t::init_vec { make_pair(make_params(), make_shared<NativeFunction>(NewBie_Boolean, false, intToBool)), }); Function toString = make_shared<function_t>(toString_str, function_t::init_vec { make_pair(make_params(), make_shared<NativeFunction>(NewBie_String, false, intToString)) }); Func dtor = nullFunc; Constructor ctor = make_shared<constructor_t>(constructor_t::init_vec { make_pair(make_params(NewBie_Int), make_shared<NativeConstructor>(NewBie_Variant, true, intCopy, Args{})), make_pair(make_params(NewBie_Double), make_shared<NativeConstructor>(NewBie_Variant, true, intCtorD, Args{})), make_pair(make_params(NewBie_Boolean), make_shared<NativeConstructor>(NewBie_Variant, true, intCtorBool, Args{})), make_pair(make_params(NewBie_String), make_shared<NativeConstructor>(NewBie_Variant, true, intCtorStr, Args{})), make_pair(make_params(), make_shared<NativeConstructor>(NewBie_Variant, true, intCtor, Args{})), }); Operator o; o.set({ { o_add, add }, { o_sub, sub}, { o_mul, mul }, { o_div, div }, { o_mod, mod }, { o_minus, minus }, { o_plus, plus }, { o_not, not}, {o_negate, negate }, { o_bit_and, bit_and }, { o_bit_or, bit_or }, { o_bit_xor, bit_xor }, { o_bit_left, bit_left }, { o_bit_right, bit_right }, {o_lt, lt}, {o_le, le}, {o_gt, gt}, {o_ge, ge}, {o_eq, eq}, {o_ne, ne}, { o_call, call }, { o_toBool, tobool } }); Class cl = make_shared<class_t>(this, int_str, NewBie_Int, bases, true, false, true, ctor, dtor, o, class_t::vars(), intPtrDeleter); cl->addToPrototype(toString_str, ObjectContainer(*runner, toString), PUBLIC); return cl; } Class InterpreterImp::makeDoubleClass() { vector<Class> bases{ primitive_class[NewBie_Object] }; Function add = make_shared<function_t>(String("double operator+"), function_t::init_vec { make_pair(make_params(NewBie_Int), make_shared<NativeFunction>(NewBie_Double, false, doubleAddI)), make_pair(make_params(NewBie_Double), make_shared<NativeFunction>(NewBie_Double, false, doubleAdd)), }); Function sub = make_shared<function_t>(String("double operator-"), function_t::init_vec { make_pair(make_params(NewBie_Int), make_shared<NativeFunction>(NewBie_Double, false, doubleSubI)), make_pair(make_params(NewBie_Double), make_shared<NativeFunction>(NewBie_Double, false, doubleSub)), }); Function mul = make_shared<function_t>(String("double operator*"), function_t::init_vec { make_pair(make_params(NewBie_Int), make_shared<NativeFunction>(NewBie_Double, false, doubleMulI)), make_pair(make_params(NewBie_Double), make_shared<NativeFunction>(NewBie_Double, false, doubleMul)), }); Function div = make_shared<function_t>(String("double operator/"), function_t::init_vec { make_pair(make_params(NewBie_Int), make_shared<NativeFunction>(NewBie_Double, false, doubleDivI)), make_pair(make_params(NewBie_Double), make_shared<NativeFunction>(NewBie_Double, false, doubleDiv)), }); Function lt = make_shared<function_t>(String("double operator<"), function_t::init_vec { make_pair(make_params(NewBie_Int), make_shared<NativeFunction>(NewBie_Boolean, false, doubleLtI)), make_pair(make_params(NewBie_Double), make_shared<NativeFunction>(NewBie_Boolean, false, doubleLt)), }); Function le = make_shared<function_t>(String("double operator<="), function_t::init_vec { make_pair(make_params(NewBie_Int), make_shared<NativeFunction>(NewBie_Boolean, false, doubleLeI)), make_pair(make_params(NewBie_Double), make_shared<NativeFunction>(NewBie_Boolean, false, doubleLe)), }); Function gt = make_shared<function_t>(String("double operator>"), function_t::init_vec { make_pair(make_params(NewBie_Int), make_shared<NativeFunction>(NewBie_Boolean, false, doubleGtI)), make_pair(make_params(NewBie_Double), make_shared<NativeFunction>(NewBie_Boolean, false, doubleGt)), }); Function ge = make_shared<function_t>(String("double operator>="), function_t::init_vec { make_pair(make_params(NewBie_Int), make_shared<NativeFunction>(NewBie_Boolean, false, doubleGeI)), make_pair(make_params(NewBie_Double), make_shared<NativeFunction>(NewBie_Boolean, false, doubleGe)), }); Function eq = make_shared<function_t>(String("double operator=="), function_t::init_vec { make_pair(make_params(NewBie_Int), make_shared<NativeFunction>(NewBie_Boolean, false, doubleEqI)), make_pair(make_params(NewBie_Double), make_shared<NativeFunction>(NewBie_Boolean, false, doubleEq)), }); Function ne = make_shared<function_t>(String("double operator!="), function_t::init_vec { make_pair(make_params(NewBie_Int), make_shared<NativeFunction>(NewBie_Boolean, false, doubleNeI)), make_pair(make_params(NewBie_Double), make_shared<NativeFunction>(NewBie_Boolean, false, doubleNe)), }); Function call = make_shared<function_t>(String("double call"), function_t::init_vec { make_pair(make_params(NewBie_Int), make_shared<NativeFunction>(NewBie_Boolean, false, doubleCalli)), make_pair(make_params(NewBie_Double), make_shared<NativeFunction>(NewBie_Double, false, doubleCalld)), }); Function minus = make_shared<function_t>(String("double minus"), function_t::init_vec { make_pair(make_params(), make_shared<NativeFunction>(NewBie_Double, false, doubleMinus)), }); Function plus = make_shared<function_t>(String("double plus"), function_t::init_vec { make_pair(make_params(), make_shared<NativeFunction>(NewBie_Double, false, doublePlus)), }); Function negate = make_shared<function_t>(String("double negate"), function_t::init_vec { make_pair(make_params(), make_shared<NativeFunction>(NewBie_Double, false, doubleNegate)), }); Function tobool = make_shared<function_t>(String("double tobool"), function_t::init_vec { make_pair(make_params(), make_shared<NativeFunction>(NewBie_Boolean, false, doubleToBool)), }); Function toString = make_shared<function_t>(toString_str, function_t::init_vec { make_pair(make_params(), make_shared<NativeFunction>(NewBie_String, false, doubleToString)) }); Func dtor = nullFunc; Constructor ctor = make_shared<constructor_t>(constructor_t::init_vec { make_pair(make_params(NewBie_Int), make_shared<NativeConstructor>(NewBie_Variant, true, doubleCtorI, Args{})), make_pair(make_params(NewBie_String), make_shared<NativeConstructor>(NewBie_Variant, true, doubleCtorStr, Args{})), make_pair(make_params(NewBie_Double), make_shared<NativeConstructor>(NewBie_Variant, true, doubleCopy, Args{})), make_pair(make_params(), make_shared<NativeConstructor>(make_shared<NativeFunction>(NewBie_Variant, true, doubleCtor), Args{})), }); Operator o; o.set({ { o_add, add }, { o_sub, sub }, { o_mul, mul}, { o_div, div }, { o_minus, minus }, { o_plus, plus }, { o_negate, negate }, { o_call, call }, { o_toBool, tobool }, { o_lt, lt },{ o_le, le },{ o_gt, gt },{ o_ge, ge },{ o_eq, eq },{ o_ne, ne } }); Class cl = make_shared<class_t>(this, double_str, NewBie_Double, bases, true, false, true, ctor, dtor, o, class_t::vars(), doublePtrDeleter); cl->addToPrototype(toString_str, ObjectContainer(*runner, toString), PUBLIC); return cl; } Class InterpreterImp::makeBooleanClass() { vector<Class> bases{ primitive_class[NewBie_Object] }; Function toString = make_shared<function_t>(toString_str, function_t::init_vec { make_pair(make_params(), make_shared<NativeFunction>(NewBie_String, false, booleanToString)) }); Function eq = make_shared<function_t>(String("boolean operator=="), function_t::init_vec { make_pair(make_params(NewBie_Boolean), make_shared<NativeFunction>(NewBie_Boolean, false, booleanEq)), }); Function ne = make_shared<function_t>(String("boolean operator!="), function_t::init_vec { make_pair(make_params(NewBie_Boolean), make_shared<NativeFunction>(NewBie_Boolean, false, booleanNe)), }); Function and = make_shared<function_t>(String("boolean operator&&"), function_t::init_vec { make_pair(make_params(NewBie_Boolean), make_shared<NativeFunction>(NewBie_Boolean, false, booleanAnd)), }); Function or = make_shared<function_t>(String("boolean operator||"), function_t::init_vec { make_pair(make_params(NewBie_Boolean), make_shared<NativeFunction>(NewBie_Boolean, false, booleanOr)), }); Func dtor = nullFunc; Constructor ctor = make_shared<constructor_t>(constructor_t::init_vec { make_pair(make_params(NewBie_Boolean), make_shared<NativeConstructor>(NewBie_Variant, true, booleanCopy, Args{})), make_pair(make_params(), make_shared<NativeConstructor>(NewBie_Variant, true, booleanCtor, Args{})) }); Operator o; o.set({ {o_and, and},{o_or, or }, {o_eq, eq}, {o_ne, ne} }); Class cl = make_shared<class_t>(this, boolean_str, NewBie_Boolean, bases, true, false, true, ctor, dtor, o, class_t::vars(), booleanPtrDeleter); cl->addToPrototype(toString_str, ObjectContainer(*runner, toString), PUBLIC); return cl; } Class InterpreterImp::makeStringClass() { vector<Class> bases{ primitive_class[NewBie_Object] }; Function add = make_shared<function_t>(String("string operator+"), function_t::init_vec { make_pair(make_params(NewBie_String), make_shared<NativeFunction>(NewBie_String, false, stringAdd)) }); Function mul = make_shared<function_t>(String("string operator*"), function_t::init_vec { make_pair(make_params(NewBie_Int), make_shared<NativeFunction>(NewBie_String, false, stringMul)) }); Function lt = make_shared<function_t>(String("string operator<"), function_t::init_vec { make_pair(make_params(NewBie_String), make_shared<NativeFunction>(NewBie_Boolean, false, stringLt)), }); Function le = make_shared<function_t>(String("string operator<="), function_t::init_vec { make_pair(make_params(NewBie_String), make_shared<NativeFunction>(NewBie_Boolean, false, stringLe)), }); Function gt = make_shared<function_t>(String("string operator>"), function_t::init_vec { make_pair(make_params(NewBie_String), make_shared<NativeFunction>(NewBie_Boolean, false, stringGt)), }); Function ge = make_shared<function_t>(String("string operator>="), function_t::init_vec { make_pair(make_params(NewBie_String), make_shared<NativeFunction>(NewBie_Boolean, false, stringGe)), }); Function eq = make_shared<function_t>(String("string operator=="), function_t::init_vec { make_pair(make_params(NewBie_String), make_shared<NativeFunction>(NewBie_Boolean, false, stringEq)), }); Function ne = make_shared<function_t>(String("string operator!="), function_t::init_vec { make_pair(make_params(NewBie_String), make_shared<NativeFunction>(NewBie_Boolean, false, stringNe)), }); Function tobool = make_shared<function_t>(String("string tobool"), function_t::init_vec { make_pair(make_params(), make_shared<NativeFunction>(NewBie_Boolean, false, stringToBool)) }); Function index = make_shared<function_t>(String("string index"), function_t::init_vec { make_pair(make_params(NewBie_Int), make_shared<NativeFunction>(NewBie_String, false, stringIndex)) }); Function toString = make_shared<function_t>(toString_str, function_t::init_vec { make_pair(make_params(), make_shared<NativeFunction>(NewBie_String, false, stringToString)) }); Function call = make_shared<function_t>(String("string call"), function_t::init_vec { make_pair(make_params(NewBie_Int, NewBie_Int), make_shared<NativeFunction>(NewBie_String, false, stringSubstring)) }); String substr_str = "substr"; String substring_str = "substring"; Function substr = make_shared<function_t>(String("substr"), function_t::init_vec { make_pair(make_params(NewBie_Int, NewBie_Int), make_shared<NativeFunction>(NewBie_String, false, stringSubstr)) }); Function substring = make_shared<function_t>(String("substring"), function_t::init_vec { make_pair(make_params(NewBie_Int, NewBie_Int), make_shared<NativeFunction>(NewBie_String, false, stringSubstring)) }); Func dtor = nullFunc; Constructor ctor = make_shared<constructor_t>(constructor_t::init_vec { make_pair(make_params(NewBie_String), make_shared<NativeConstructor>(NewBie_Variant, true, stringCopy, Args{})), make_pair(make_params(), make_shared<NativeConstructor>(NewBie_Variant, true, stringCtor, Args{})), }); Operator o; o.set({ {o_add, add}, {o_mul, mul}, { o_index, index },{ o_call, call },{ o_toBool, tobool }, { o_lt, lt },{ o_le, le },{ o_gt, gt },{ o_ge, ge },{ o_eq, eq },{ o_ne, ne } }); Class cl = make_shared<class_t>(this, string_str, NewBie_String, bases, true, false, true, ctor, dtor, o, class_t::vars(), stringPtrDeleter); cl->addToPrototype(toString_str, ObjectContainer(*runner, toString), PUBLIC); cl->addToPrototype(substr_str, ObjectContainer(*runner, substr), PUBLIC); cl->addToPrototype(substring_str, ObjectContainer(*runner, substring), PUBLIC); return cl; } Class InterpreterImp::makeFunctionClass() { vector<Class> bases{ primitive_class[NewBie_Object] }; Function eq = make_shared<function_t>(String("function operator=="), function_t::init_vec { make_pair(make_params(NewBie_Function), make_shared<NativeFunction>(NewBie_Variant, false, functionEq)) }); Function ne = make_shared<function_t>(String("function operator!="), function_t::init_vec { make_pair(make_params(NewBie_Function), make_shared<NativeFunction>(NewBie_Variant, false, functionNe)) }); Function call = make_shared<function_t>(String("function call"), function_t::init_vec { make_pair(ParameterList{Parameter(NewBie_Variant, Expression(), false, false, for_functionCall)}, make_shared<NativeFunction>(NewBie_Variant, false, functionCall)) }); Function toString = make_shared<function_t>(toString_str, function_t::init_vec { make_pair(make_params(), make_shared<NativeFunction>(NewBie_String, false, functionToString)) }); Func dtor = nullFunc; Constructor ctor; Operator o; o.set({ {o_eq, eq}, {o_ne, ne}, {o_call, call} }); Class cl = make_shared<class_t>(this, function_str, NewBie_Function, bases, true, false, true, ctor, dtor, o, class_t::vars(), functionPtrDeleter); cl->addToPrototype(toString_str, ObjectContainer(*runner, toString), PUBLIC); return cl; } Class InterpreterImp::makeClassClass() { vector<Class> bases{ primitive_class[NewBie_Object] }; Function eq = make_shared<function_t>(String("class operator=="), function_t::init_vec { make_pair(make_params(NewBie_Class), make_shared<NativeFunction>(NewBie_Variant, false, classEq)) }); Function ne = make_shared<function_t>(String("class operator!="), function_t::init_vec { make_pair(make_params(NewBie_Class), make_shared<NativeFunction>(NewBie_Variant, false, classNe)) }); Function call = make_shared<function_t>(String("class call"), function_t::init_vec { make_pair(ParameterList{ Parameter(NewBie_Variant, Expression(), false, false, for_functionCall) }, make_shared<NativeFunction>(NewBie_Variant, false, classCall)) }); Function toString = make_shared<function_t>(toString_str, function_t::init_vec { make_pair(make_params(), make_shared<NativeFunction>(NewBie_String, false, functionToString)) }); Func dtor = nullFunc; Constructor ctor; Operator o; o.set({ { o_eq, eq },{ o_ne, ne },{ o_call, call } }); Class cl = make_shared<class_t>(this, class_str, NewBie_Class, bases, true, false, true, ctor, dtor, o, class_t::vars(), functionPtrDeleter); cl->addToPrototype(toString_str, ObjectContainer(*runner, toString), PUBLIC); return cl; } zyd2001::NewBie::object_t::object_t(Runner & runner, const int &i) : runner(runner), native_ptr(new int32_t(i)), cl(runner.inter->primitive_class[NewBie_Int]), type(runner.inter->primitive_class[NewBie_Int]->type), type_name(runner.inter->primitive_class[NewBie_Int]->type_name) {} zyd2001::NewBie::object_t::object_t(Runner & runner, const double &d) : runner(runner), native_ptr(new double(d)), cl(runner.inter->primitive_class[NewBie_Double]), type(runner.inter->primitive_class[NewBie_Double]->type), type_name(runner.inter->primitive_class[NewBie_Double]->type_name) {} zyd2001::NewBie::object_t::object_t(Runner & runner, const bool &i) : runner(runner), native_ptr(new bool(i)), cl(runner.inter->primitive_class[NewBie_Boolean]), type(runner.inter->primitive_class[NewBie_Boolean]->type), type_name(runner.inter->primitive_class[NewBie_Boolean]->type_name) {} zyd2001::NewBie::object_t::object_t(Runner & r, const std::string &s) : object_t(r, String(s)) {} zyd2001::NewBie::object_t::object_t(Runner & runner, const String &i) : runner(runner), native_ptr(new String(i)), cl(runner.inter->primitive_class[NewBie_String]), type(runner.inter->primitive_class[NewBie_String]->type), type_name(runner.inter->primitive_class[NewBie_String]->type_name) {} object_t::object_t(Runner & runner, Class c) : runner(runner), native_ptr(new Class(c)), cl(runner.inter->primitive_class[NewBie_Class]), type(runner.inter->primitive_class[NewBie_Class]->type), type_name(runner.inter->primitive_class[NewBie_Class]->type_name) {} zyd2001::NewBie::object_t::object_t(Runner & runner, Function f) : runner(runner), native_ptr(new Function(f)), cl(runner.inter->primitive_class[NewBie_Function]), type(runner.inter->primitive_class[NewBie_Function]->type), type_name(runner.inter->primitive_class[NewBie_Function]->type_name) {} String::String() : ptr(make_shared<basic_string<char_t>>()) {} String::String(const char * s) : String(string(s)) {} String::String(const std::string &s) : ptr(make_shared<basic_string<char_t>>(conv.from_bytes(s))) {} String::String(const char_t *str) : ptr(make_shared<basic_string<char_t>>(str)) {} String::String(const basic_string<char_t> &str) : ptr(make_shared<basic_string<char_t>>(str)) {} basic_string<char_t> &String::get() const { return *ptr; } std::string String::toStr() const { return conv.to_bytes(*ptr); } String zyd2001::NewBie::String::copy() const { return String(get()); } String String::operator+(const String &str) { return String(*(this->ptr) + *str.ptr); } String &String::operator+=(const String &str) { *(this->ptr) += *str.ptr; return *this; } String &String::operator=(const String &str) { String s(str); std::swap(s.ptr, ptr); return *this; } bool String::operator==(const String &str) const { if (this->ptr == str.ptr) return true; else return *(this->ptr) == *str.ptr; } bool String::operator!=(const String & str) const { if (this->ptr != str.ptr) return true; else return *(this->ptr) != *str.ptr; } bool zyd2001::NewBie::String::operator>(const String &s) const { return *ptr > *s.ptr; } bool String::operator>=(const String & s) const { return *ptr >= *s.ptr; } bool zyd2001::NewBie::String::operator<(const String &s) const { return *ptr < *s.ptr; } bool String::operator<=(const String & s) const { return *ptr <= *s.ptr; } size_t zyd2001::NewBie::StringHash::operator()(const String &s) const { return h(*s.ptr); } bool ParamsEqualTo::operator()(const ParameterList& lhs, const ParameterList& rhs) const { if (lhs.size() != rhs.size()) return false; else { for (int i = 0; i < lhs.size(); i++) { if (lhs[i].type != rhs[i].type) return false; } return true; } } std::size_t ParamsHash::operator()(const ParameterList& p) const { std::hash<ObjectType> h; std::size_t seed = 0; for (auto &i : p) seed ^= h(i.type) + 0x9e3779b9 + (seed << 6) + (seed >> 2); return seed; } } }
49.113614
182
0.576468
[ "vector" ]
5d6728cf6d7869b25d55991f45ea2e90a6f5e017
4,022
cpp
C++
scr/wxClient/ChatApp.cpp
dZh0/Chat
966eb227a3cb0cab3d05b2c5091c5b0bf6e5342e
[ "Unlicense" ]
null
null
null
scr/wxClient/ChatApp.cpp
dZh0/Chat
966eb227a3cb0cab3d05b2c5091c5b0bf6e5342e
[ "Unlicense" ]
null
null
null
scr/wxClient/ChatApp.cpp
dZh0/Chat
966eb227a3cb0cab3d05b2c5091c5b0bf6e5342e
[ "Unlicense" ]
null
null
null
#include <wx/busyinfo.h> #include <wx/log.h> #include "ConnectDialog.h" #include "ChatWindow.h" #include "ChatApp.h" wxIMPLEMENT_APP(ChatApp); wxDEFINE_EVENT(EVT_CONVERSATION, wxThreadEvent); wxDEFINE_EVENT(EVT_MESSAGE, wxThreadEvent); wxDEFINE_EVENT(EVT_ERROR, wxThreadEvent); bool ChatApp::OnInit() { Bind(EVT_ERROR, &ChatApp::HandleErrorEvent, this); if (!ChatClient::InitNetwork()) { wxMessageBox("Network inicialization failed", "Error", wxICON_ERROR | wxSTAY_ON_TOP); exit(EXIT_FAILURE); } mainWindow = new ChatWindow(nullptr, wxID_ANY, "Chat"); mainWindow->Show(true); mainWindow->Bind(wxEVT_COMMAND_MENU_SELECTED, &ChatApp::OnConnect, this, ID_CONNECT); //mainWindow->Bind(wxEVT_COMMAND_MENU_SELECTED, &ChatApp::OnDisconnect, this, ID_DISCONNECT); //TODO: Add later mainWindow->Bind(wxEVT_TEXT_ENTER, &ChatApp::OnSendMessage, this); //TODO: Maybe bind after a connection is established? Connect(); return true; } int ChatApp::OnExit() { ChatClient::Disconnect(); return 0; } void ChatApp::OnError(const std::string& errorMsg) { wxThreadEvent event(EVT_ERROR); event.SetString(errorMsg); QueueEvent(event.Clone()); } void ChatApp::OnLoginSuccessful(const std::vector<std::pair<const msg::targetId, std::string>>& conversationList) { for (const auto &cnv: conversationList) { // @METO: This direct approach works because OnLoginSuccesfull() is only called on the main thread. // Alternatavely I can queue a EVT_CONVERSATION for every conversation but it seems like an overkll. Should I? mainWindow->CreateConversation(static_cast<wxWindowID>(cnv.first), cnv.second); } mainWindow->SetStatusText("Welcome to Chat!"); } void ChatApp::OnLoginFailed() { wxMessageBox("Your login request was denied...", "Login Failed"); } void ChatApp::OnNewConversation(const msg::targetId id, const std::string& name) { wxThreadEvent networkEvent(EVT_CONVERSATION); networkEvent.SetId(static_cast<int>(id)); networkEvent.SetString(name); QueueEvent(networkEvent.Clone()); } void ChatApp::OnMessageReceived(const msg::targetId target, const msg::targetId sender, const std::string& message) { wxThreadEvent networkEvent(EVT_MESSAGE); if (IsMe(target)) { networkEvent.SetId(static_cast<int>(sender)); } else { networkEvent.SetId(static_cast<int>(target)); } networkEvent.SetInt(static_cast<int>(sender)); networkEvent.SetString(message); QueueEvent(networkEvent.Clone()); } void ChatApp::OnDisconnect() { //TODO: Maybe clear main window contact list if (updateThread) { updateThread->join(); delete(updateThread); } } void ChatApp::Connect() { if (IsConnected()) { ChatClient::Disconnect(); } ConnectDialog connectPopup(nullptr, serverIP, serverPort, userName); if (connectPopup.ShowModal() == wxID_OK) { wxBusyInfo busyWindow("Connecting...", GetTopWindow()); if (ConnectToServer(std::string(serverIP), wxAtoi(serverPort), std::string(userName), 2, 1000)) { Bind(EVT_CONVERSATION, &ChatWindow::OnNewConversation, mainWindow); Bind(EVT_MESSAGE, &ChatWindow::OnMessageReceived, mainWindow); updateThread = new std::thread(&ChatApp::Update, this); } } } void ChatApp::Update() { while (IsConnected()) { Sleep(1000); ListenForMessage(1000); } } void ChatApp::HandleErrorEvent(wxThreadEvent& event) { wxMessageBox(event.GetString(), "Error", wxICON_ERROR | wxSTAY_ON_TOP); } void ChatApp::OnSendMessage(const wxCommandEvent& event) { //@ METO: _ASSERTE(__acrt_first_block == header) fails when exiting function scope!!! No fix for that bugger. const std::string message = event.GetString().ToStdString(); SendTextMessage(event.GetInt(), message); } void ChatApp::OnConnect(const wxCommandEvent& event) { Connect(); } void ChatApp::OnDisonnect(const wxCommandEvent& event) { wxMessageBox(wxString::Format("TODO: OnDisonnect()\nevent.GetId() %i\nevent.GetInt() %i\nevent.GetString() %s\n\nID_DISCONNECT: %i", event.GetId(), event.GetInt(), event.GetString(), ID_DISCONNECT ), "ChatApp"); ChatClient::Disconnect(); }
26.993289
133
0.743411
[ "vector" ]
5d6aea2114442e0b4739bdb24789bf6f713c85ce
3,230
cpp
C++
pipeline/fudgepacker/source/datablockparam.cpp
DavidCoenFish/ancient-code-0
243fb47b9302a77f9b9392b6e3f90bba2ef3c228
[ "Unlicense" ]
null
null
null
pipeline/fudgepacker/source/datablockparam.cpp
DavidCoenFish/ancient-code-0
243fb47b9302a77f9b9392b6e3f90bba2ef3c228
[ "Unlicense" ]
null
null
null
pipeline/fudgepacker/source/datablockparam.cpp
DavidCoenFish/ancient-code-0
243fb47b9302a77f9b9392b6e3f90bba2ef3c228
[ "Unlicense" ]
null
null
null
//file: DataBlockParam.cpp #include "DataBlockParam.h" #include "DataBlock.h" #include "packcommon.h" #include "main.h" // typedefs typedef std::vector<U8> TArrayByte; static void LocalAppendFlatData( TArrayByte& inout_arrayFlatData, const TArrayByte& in_arrayData, const int in_lowWater, const int in_highWater ) { for (int index = in_lowWater; index < in_highWater; ++index) { inout_arrayFlatData.push_back(in_arrayData[index]); } return; } // construction DataBlockParam::DataBlockParam(const DataBlockParam& in_src) : mArrayFlatData() , mArrayData() , mArrayPairIntWeakDataBlock() , mAlignment(0) { (*this) = in_src; return; } DataBlockParam::DataBlockParam(const int in_alignment) : mArrayFlatData() , mArrayData() , mArrayPairIntWeakDataBlock() , mAlignment(in_alignment) { return; } DataBlockParam::~DataBlockParam() { return; } DataBlockParam& DataBlockParam::operator=(const DataBlockParam& in_rhs) { if (this != &in_rhs) { mArrayFlatData = in_rhs.mArrayFlatData; mArrayData = in_rhs.mArrayData; mArrayPairIntWeakDataBlock = in_rhs.mArrayPairIntWeakDataBlock; mAlignment = in_rhs.mAlignment; } return (*this); } //write to the data block void DataBlockParam::AddU8(const U8 in_data) { PackCommon::Append(mArrayFlatData, in_data); PackCommon::Append(mArrayData, in_data); return; } void DataBlockParam::AddU16(const U16 in_data) { PackCommon::Append(mArrayFlatData, in_data); PackCommon::Append(mArrayData, in_data); return; } void DataBlockParam::AddU32(const U32 in_data) { PackCommon::Append(mArrayFlatData, in_data); PackCommon::Append(mArrayData, in_data); return; } void DataBlockParam::AddR32(const R32 in_data) { PackCommon::Append(mArrayFlatData, in_data); PackCommon::Append(mArrayData, in_data); return; } void DataBlockParam::AddArray(const TArrayByte& in_arrayData) { mArrayFlatData.insert(mArrayFlatData.end(), in_arrayData.begin(), in_arrayData.end()); mArrayData.insert(mArrayData.end(), in_arrayData.begin(), in_arrayData.end()); return; } void DataBlockParam::AddPointer(TPointerDataBlock& in_dataBlock) { if (in_dataBlock) { mArrayFlatData.insert(mArrayFlatData.end(), in_dataBlock->GetArrayFlatData().begin(), in_dataBlock->GetArrayFlatData().end()); const int offset = mArrayData.size(); PackCommon::Append<U32>(mArrayData, 0); mArrayPairIntWeakDataBlock.push_back(TArrayPairIntWeakDataBlock::value_type(offset, in_dataBlock)); } else { PackCommon::Append<U32>(mArrayFlatData, 0); PackCommon::Append<U32>(mArrayData, 0); } return; } const bool DataBlockParam::TestDataBlockMatch(const DataBlockParam& in_dataBlockParam)const { //data size match if (mArrayFlatData.size() != in_dataBlockParam.mArrayFlatData.size()) { return false; } //alignment match if (0 != (mAlignment % in_dataBlockParam.mAlignment)) { return false; } for (int index = 0; index < (int)mArrayFlatData.size(); ++index) { if (mArrayFlatData[index] != in_dataBlockParam.mArrayFlatData[index]) { return false; } } return true; } //smaller number gets data block writen towards start of file const int DataBlockParam::GetWriteSortValue()const { const int size = -(int)((mAlignment << 24) + mArrayData.size()); return size; }
21.972789
128
0.750774
[ "vector" ]
5d6ba02fa3b844193094a13fabf9d7c112d0a7ed
2,668
hpp
C++
openstudiocore/src/model/PhotovoltaicPerformance_Impl.hpp
jasondegraw/OpenStudio
2ab13f6e5e48940929041444e40ad9d36f80f552
[ "blessing" ]
1
2016-12-29T08:45:03.000Z
2016-12-29T08:45:03.000Z
openstudiocore/src/model/PhotovoltaicPerformance_Impl.hpp
jasondegraw/OpenStudio
2ab13f6e5e48940929041444e40ad9d36f80f552
[ "blessing" ]
null
null
null
openstudiocore/src/model/PhotovoltaicPerformance_Impl.hpp
jasondegraw/OpenStudio
2ab13f6e5e48940929041444e40ad9d36f80f552
[ "blessing" ]
null
null
null
/********************************************************************** * Copyright (c) 2008-2016, Alliance for Sustainable Energy. * All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********************************************************************/ #ifndef MODEL_PHOTOVOLTAICPERFORMANCE_IMPL_HPP #define MODEL_PHOTOVOLTAICPERFORMANCE_IMPL_HPP #include "ModelObject_Impl.hpp" namespace openstudio { namespace model { namespace detail { class MODEL_API PhotovoltaicPerformance_Impl : public ModelObject_Impl { public: /** @name Constructors and Destructors */ //@{ PhotovoltaicPerformance_Impl(IddObjectType type, Model_Impl* model); PhotovoltaicPerformance_Impl(const IdfObject& idfObject, Model_Impl* model, bool keepHandle); PhotovoltaicPerformance_Impl(const openstudio::detail::WorkspaceObject_Impl& other, Model_Impl* model, bool keepHandle); PhotovoltaicPerformance_Impl(const PhotovoltaicPerformance_Impl& other, Model_Impl* model, bool keepHandles); virtual ~PhotovoltaicPerformance_Impl() {} //@} /** @name Virtual Methods */ //@{ /// do not allow this object to be removed if it is referenced by a PhotovoltaicGenerator virtual std::vector<openstudio::IdfObject> remove() override; //@} /** @name Getters */ //@{ // DLM: really don't want to implement this for this object, feels too kludgy //virtual boost::optional<ParentObject> parent() override; //@} /** @name Setters */ //@{ // DLM: really don't want to implement this for this object, feels too kludgy //virtual bool setParent(ParentObject& newParent) override; //@} /** @name Other */ //@{ //@} private: REGISTER_LOGGER("openstudio.model.PhotovoltaicPerformance"); }; } // detail } // model } // openstudio #endif // MODEL_PHOTOVOLTAICPERFORMANCE_IMPL_HPP
31.761905
113
0.662294
[ "object", "vector", "model" ]
5d6c644bdf4d75b57e323ba10b6fb3bc55b03513
122
cpp
C++
ThorEngine/Source Code/R_Model.cpp
markitus18/Thor-Engine
d89c75f803357d6493cd018450bceb384d2dd265
[ "Unlicense" ]
12
2019-10-07T12:30:12.000Z
2021-09-25T13:05:26.000Z
ThorEngine/Source Code/R_Model.cpp
markitus18/Thor-Engine
d89c75f803357d6493cd018450bceb384d2dd265
[ "Unlicense" ]
15
2017-06-14T13:10:06.000Z
2020-11-21T11:27:54.000Z
ThorEngine/Source Code/R_Model.cpp
markitus18/Thor-Engine
d89c75f803357d6493cd018450bceb384d2dd265
[ "Unlicense" ]
4
2019-12-17T11:48:45.000Z
2020-11-13T19:09:59.000Z
#include "R_Model.h" R_Model::R_Model() : Resource(ResourceType::MODEL) { isExternal = true; } R_Model::~R_Model() { }
11.090909
50
0.672131
[ "model" ]
5d71828477bf5a709cf228ebcc97f78d0e29dc2c
4,772
cpp
C++
BalanceTree/RBTree_tb.cpp
flyinglandlord/BUAA-SAE-DataStructure-2021
7eb686465b18b125115e03b39e6d83e4ed7a30cb
[ "MIT" ]
2
2022-03-31T01:43:24.000Z
2022-03-31T02:05:14.000Z
BalanceTree/RBTree_tb.cpp
flyinglandlord/BUAA-SAE-DataStructure-2021
7eb686465b18b125115e03b39e6d83e4ed7a30cb
[ "MIT" ]
null
null
null
BalanceTree/RBTree_tb.cpp
flyinglandlord/BUAA-SAE-DataStructure-2021
7eb686465b18b125115e03b39e6d83e4ed7a30cb
[ "MIT" ]
null
null
null
#include "RBTree.c" #include <iostream> #include <vector> #include <algorithm> #include <random> #include <chrono> #include <ctime> using namespace std; vector<int> generate_random_array(int n) { vector<int> arr; arr.clear(); unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); for(int i = 1; i <= n; i++) arr.push_back(i); shuffle(arr.begin(), arr.end(), std::default_random_engine(seed)); return arr; } const int data_mass[] = {1000, 5000, 10000, 50000, 100000, 500000, 1000000, 5000000, 10000000, 50000000, 100000000}; // Test Insert, Delete, Search Function in different data_mass // Repeat 3 times for average void SimpleFunctionTest() { FILE *res_simpletest = fopen("./res/rbtree_simple.txt", "w"); vector<int> arr; int i = 10; for(int i = 0; i < 11; i++) { clock_t timer_s, timer_e; root = NULL; init(); fprintf(res_simpletest, "%d\n", data_mass[i]); for(int k = 1; k <= 5; k++) { cerr << "[Info] Running Test Case " << (i+1) << "." << (k) << "Data Mass: " << data_mass[i] << endl; // Insert Function Test arr = generate_random_array(data_mass[i]); timer_s = clock(); for(auto i : arr) rbtree_insert(root, i); timer_e = clock(); fprintf(res_simpletest, "%f ", (double)(timer_e - timer_s) / CLOCKS_PER_SEC); arr.clear(); // Search Function Test arr = generate_random_array(data_mass[i]); timer_s = clock(); for(auto i : arr) rbtree_search(root, i); timer_e = clock(); fprintf(res_simpletest, "%f ", (double)(timer_e - timer_s) / CLOCKS_PER_SEC); arr.clear(); // Delete Function Test arr = generate_random_array(data_mass[i]); timer_s = clock(); for(auto i : arr) rbtree_delete(root, i); timer_e = clock(); fprintf(res_simpletest, "%f\n", (double)(timer_e - timer_s) / CLOCKS_PER_SEC); arr.clear(); } } fclose(res_simpletest); } vector<int> arr; // Fix the Insert Process 100,0000 // Change the ratio of Delete/Insert ratio, Search/Insert ratio, Measure the time void CombinationFunctionTest() { const int INS_NUM = 1000000; FILE *res_combtest = fopen("./res/rbtree_comb.txt", "w"); FILE *tmp_sea, *tmp_del, *tmp_ins; clock_t timer_s, timer_e; for(int del_num = INS_NUM; del_num >= INS_NUM/100; del_num -= INS_NUM/100) { for(int search_num = INS_NUM; search_num >= INS_NUM/100; search_num -= INS_NUM/100) { root = NULL; init(); cerr << "[Info] Running Test Case " << "Delete/Insert ratio:" << (double)del_num / INS_NUM << "; Search/Insert ratio:" << (double)search_num / INS_NUM << endl; fprintf(res_combtest, "%lf %lf ", (double)del_num / INS_NUM, (double)search_num / INS_NUM); // Insert 1000,000 data first tmp_sea = fopen("./tmp/tmp_sea.txt", "w"); tmp_del = fopen("./tmp/tmp_del.txt", "w"); tmp_ins = fopen("./tmp/tmp_ins.txt", "w"); arr = generate_random_array(INS_NUM); for(auto i : arr) { rbtree_insert(root, i); fprintf(tmp_ins, "%d\n", i); } fclose(tmp_ins);arr.clear(); arr = generate_random_array(search_num); for(auto i : arr) fprintf(tmp_sea, "%d\n", i); arr.clear(); fclose(tmp_sea); arr = generate_random_array(del_num); for(auto i : arr) fprintf(tmp_del, "%d\n", i); arr.clear(); fclose(tmp_del); tmp_sea = fopen("./tmp/tmp_sea.txt", "r"); tmp_del = fopen("./tmp/tmp_del.txt", "r"); timer_s = clock(); for(int i = 0; i < search_num; i++) { int x; fscanf(tmp_sea, "%d", &x); rbtree_search(root, x); } for(int i = 0; i < del_num; i++) { int x; fscanf(tmp_del, "%d", &x); rbtree_delete(root, x); } timer_e = clock(); tmp_ins = fopen("./tmp/tmp_ins.txt", "r"); for(int i = 0; i < INS_NUM; i++) { int x; fscanf(tmp_ins, "%d", &x); rbtree_delete(root, x); } fclose(tmp_ins); fclose(tmp_del); fclose(tmp_sea); fprintf(res_combtest, "%lf\n", (double)(timer_e - timer_s) / CLOCKS_PER_SEC); cerr << (double)(timer_e - timer_s) / CLOCKS_PER_SEC << endl; } } fclose(res_combtest); } int main() { SimpleFunctionTest(); //CombinationFunctionTest(); return 0; }
36.427481
171
0.541702
[ "vector" ]
5d71b682c7953cfd6085545396df6dab63f500b1
8,057
cpp
C++
sql5300.cpp
SAMR1T/5300-Dolphin
aee8cba69d0de7c614eba2c6e96d76e08f65ed12
[ "MIT" ]
null
null
null
sql5300.cpp
SAMR1T/5300-Dolphin
aee8cba69d0de7c614eba2c6e96d76e08f65ed12
[ "MIT" ]
null
null
null
sql5300.cpp
SAMR1T/5300-Dolphin
aee8cba69d0de7c614eba2c6e96d76e08f65ed12
[ "MIT" ]
null
null
null
/* @file sql5300.cpp - main entry for the SQL Shell of the relation manager @author Ruoyang Qiu, Samrit Dhesi @ Seattle University, cpsc4300/5300, 2020 Spring */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "db_cxx.h" #include "SQLParser.h" #include "sqlhelper.h" #include "heap_storage.h" using namespace std; using namespace hsql; DbEnv *_DB_ENV; string expressionToString(Expr *expr); string executeSelectStatement(const SelectStatement *stmt); /* Convert a hyrise Expression AST stands for operator to equivalent SQL Operator @param expr operator expression @return return a SQL operator string equivalent to expr */ string operatorExpressionToString(Expr *expr) { if(expr == NULL) { return "null"; } string result; // NOT Operator if(expr->opType == Expr::NOT) result += "NOT "; result += expressionToString(expr->expr) + " "; // Operator switch(expr->opType) { case Expr::AND: result += "AND"; break; case Expr::OR: result += "OR"; break; default: break; } if(expr->expr2 != NULL) result += expressionToString(expr->expr2); return result; } /* Convert a hyrise Expression ASTto equivalent SQL Operator @param expr expression @return return a SQL string equivalent to expr */ string expressionToString(Expr *expr) { string result; switch(expr->type) { case kExprStar: result += "*"; break; case kExprColumnRef: if(expr->table != NULL) result += string(expr->table) + "."; result += string(expr->name); break; case kExprLiteralFloat: result += to_string(expr->fval); break; case kExprLiteralInt: result += to_string(expr->ival); break; case kExprLiteralString: result += string(expr->name); break; case kExprFunctionRef: result += string(expr->name); result += string(expr->expr->name); break; case kExprOperator: result += operatorExpressionToString(expr); break; default: result += "Unrecognized expression type %d\n"; break; } if(expr->alias != NULL){ result += string(" AS "); result += string(expr->alias); } return result; } /* Convert a hyrise TableRef AST to equivalent SQL string @param col TableRef to unparse @return return a SQL string equivalent to table */ string tableRefInfoToString(TableRef *table) { string result; switch (table->type) { case kTableName: result += string(table->name); if(table->alias != NULL) { result += string(" AS "); result += string(table->alias); } break; case kTableSelect: result += executeSelectStatement(table->select); break; case kTableJoin: result += tableRefInfoToString(table->join->left); switch(table->join->type) { case kJoinInner: result += " JOIN "; break; case kJoinLeft: result += " LEFT JOIN "; break; case kJoinNatural: case kJoinCross: case kJoinOuter: case kJoinLeftOuter: case kJoinRightOuter: case kJoinRight: result += " RIGHT JOIN "; break; } result += tableRefInfoToString(table->join->right); if(table->join->condition != NULL) { result += " ON " + expressionToString(table->join->condition); } break; case kTableCrossProduct: bool firstElement = true; for (TableRef* tbl : *table->list) { if(!firstElement) result += ", "; result += tableRefInfoToString(tbl); firstElement = false; } break; } return result; } /* Convert a hyrise ColumnDefinition AST to equivalent SQL string @param col column definition object @return return a SQL string equivalent to col */ string columnDefinitionToString(const ColumnDefinition *col) { string result(col->name); switch(col->type) { case ColumnDefinition::DOUBLE: result += " DOUBLE"; break; case ColumnDefinition::INT: result += " INT"; break; case ColumnDefinition::TEXT: result += " TEXT"; break; default: result += " ..."; break; } return result; } /* Excute a Select Statement @param stmt Hyrise AST for SelectStatement @returns a string of the SQL statement */ string executeSelectStatement(const SelectStatement *stmt) { string result("SELECT "); // check if the current expressopm is the first element // if not, a comma should be added to split expressions bool firstElement = true; for(Expr *expr : *stmt->selectList) { if(!firstElement) result += ", "; result += expressionToString(expr); firstElement = false; } result += " FROM " + tableRefInfoToString(stmt->fromTable); if(stmt->whereClause != NULL) { result += " WHERE " + expressionToString(stmt->whereClause); } return result; } /* Excute a Select Statement @param stmt Hyrise AST for SelectStatement @returns a string of the SQL statement */ string executeCreateStatement(const CreateStatement *stmt) { string result("CREATE TABLE "); // then if the user puts the if not exist check that if (stmt->ifNotExists) result += "IF NOT EXISTS "; // then the table name is written result += string(stmt->tableName); // now begin the actual create statements, we need parenthesis result += " ("; // now for each column in the query: bool firstElement = true; for (ColumnDefinition *currCol : *stmt->columns) { if (!firstElement) result += ", "; result += columnDefinitionToString(currCol); firstElement = false; } //close the parenthesis of the query result += ")"; // return results return result; } /* Excute a Select Statement @param stmt Hyrise AST for SelectStatement @returns a string of the SQL statement */ string executeInsertStatement(const InsertStatement *stmt) { string result = "INSERT INTO "; result += string(stmt->tableName); if(stmt->columns != NULL) { result += " ("; bool firstElement = true; for(char* col_name : *stmt->columns) { if(!firstElement) result += ", "; result += string(col_name); } result += ") "; } switch(stmt->type) { case InsertStatement::kInsertValues: { result += " VALUES ("; bool firstValue = true; for(Expr* expr : *stmt->values) { if(!firstValue) result += ", "; result += expressionToString(expr); firstValue = false; } result += ") "; break; } case InsertStatement::kInsertSelect: result += executeSelectStatement(stmt->select); break; } return result; } /* Excute a SQL Statement @param stmt Hyrise AST for SQL Statement @returns a string of the SQL statement */ string execute(const SQLStatement *stmt) { switch(stmt->type()) { case kStmtSelect: return executeSelectStatement((const SelectStatement*) stmt); case kStmtCreate: return executeCreateStatement((const CreateStatement*) stmt); case kStmtInsert: return executeInsertStatement((const InsertStatement*) stmt); default: return "Not Implemented"; } } int main(int argc, char **argv) { if(argc != 2) { cerr << "Usage: cpsc5300: dbenvpath" << endl; return 1; } char *envHome = argv[1]; cout << "(sql 5300: running with database environment at " << envHome << endl; DbEnv env(0U); env.set_message_stream(&cout); env.set_error_stream(&cerr); try { env.open(envHome, DB_CREATE | DB_INIT_MPOOL, 0); } catch (DbException &exc) { cerr << "(cpsc5300: " << exc.what() << ")"; exit(1); } _DB_ENV = &env; while(true) { cout << "SQL> "; string query; getline(cin, query); if(query.length() == 0) continue; if(query == "quit") break; if (query == "test") { cout << "test_heap_storage: " << (test_heap_storage() ? "ok" : "failed") << endl; continue; } SQLParserResult *sqlresult = SQLParser::parseSQLString(query); if(!sqlresult->isValid()) { cout << "invalid SQL: " << query << endl; delete sqlresult; continue; } // excute the statement for ( uint i = 0; i < sqlresult->size(); ++i) { cout << execute(sqlresult->getStatement(i)) << endl; } delete sqlresult; } return EXIT_SUCCESS; }
22.568627
93
0.651111
[ "object" ]
5d75089414426ce5ede35b5a674b4109af2432f6
1,935
cpp
C++
Code/PanelTools.cpp
JaumeMontagut/CITM_3_GameEngine
57a85b89a72723ce555a4eec3830e6bf00499de9
[ "MIT" ]
1
2020-07-09T00:38:40.000Z
2020-07-09T00:38:40.000Z
Code/PanelTools.cpp
YessicaSD/CITM_3_GameEngine
57a85b89a72723ce555a4eec3830e6bf00499de9
[ "MIT" ]
null
null
null
Code/PanelTools.cpp
YessicaSD/CITM_3_GameEngine
57a85b89a72723ce555a4eec3830e6bf00499de9
[ "MIT" ]
null
null
null
#include "PanelTools.h" #include "Application.h" #include "ModuleImportTexture.h" #include "imgui/imgui.h" #include "ResourceTexture.h" #include "ModuleResourceManager.h" #include "ModuleTime.h" PanelTools::PanelTools(std::string name, bool active, std::vector<SDL_Scancode> shortcuts):Panel(name, active, shortcuts) { JSONFile atlas_meta; atlas_meta.LoadFile(std::string("Assets/Atlas.png") + "." + META_EXTENSION); UID atlas_uid = atlas_meta.LoadUID("resourceUID"); atlas = (ResourceTexture*)App->resource_manager->GetResource(atlas_uid); if (atlas != nullptr) { atlas->StartUsingResource(); button_width = 72.0f / (float)atlas->width; button_height = 72.0f / (float)atlas->height; } } void PanelTools::Draw() { if (ImGui::Begin(name.c_str())) { if (atlas != nullptr) { //PLAT BUTTON ImGui::PushID("moveHovered"); if (ImGui::ImageButton((ImTextureID)atlas->buffer_id, ImVec2(15, 15), ImVec2(0, 0), ImVec2(button_width, button_height))) { if (App->IsStop()) { App->Play(); } if (App->IsPlay()) { App->Stop(); } } ImGui::PopID(); ImGui::SameLine(); //PAUSE BUTTON ImGui::PushID("PauseButton"); if (ImGui::ImageButton((ImTextureID)atlas->buffer_id, ImVec2(15, 15), ImVec2(button_width, 0), ImVec2(button_width * 2, button_height))) { if (App->IsPlay()) { App->Pause(); } if (App->IsPause()) { App->UnPause(); } } ImGui::PopID(); ImGui::SameLine(); //NEXT STEP BUTTON ImGui::PushID("NextStepButton"); if (ImGui::ImageButton((ImTextureID)atlas->buffer_id, ImVec2(15, 15), ImVec2(button_width * 2, 0), ImVec2(button_width * 3, button_height))) { } ImGui::PopID(); ImGui::SameLine(); ImGui::Text("%f", App->time->GetTime()); } else { ImGui::Text("Error: Atlas.png not loaded. Add 'Atlas.png' to assets folder to play, pause and frame forward."); } } ImGui::End(); }
23.888889
143
0.642894
[ "vector" ]
5d77c74c8ae90d955a5db1fe4501eff4f3f7f709
857
hpp
C++
code/src/lib/Stage/Splitting/Model.hpp
raphaelmenges/visual-stimuli-discovery
e02e9a0283a2d561165a39cf83fe85b8f687d884
[ "MIT" ]
null
null
null
code/src/lib/Stage/Splitting/Model.hpp
raphaelmenges/visual-stimuli-discovery
e02e9a0283a2d561165a39cf83fe85b8f687d884
[ "MIT" ]
null
null
null
code/src/lib/Stage/Splitting/Model.hpp
raphaelmenges/visual-stimuli-discovery
e02e9a0283a2d561165a39cf83fe85b8f687d884
[ "MIT" ]
2
2020-06-25T15:41:56.000Z
2020-07-20T08:36:44.000Z
//! Split model interface and implementations. /*! Provides decision whether split of log dates into different intra-user states should be performed. */ #pragma once #include <Core/VisualChangeClassifier.hpp> #include <Data/Layer.hpp> #include <Core/VisualDebug.hpp> #include <opencv2/core/types.hpp> #include <memory> namespace stage { namespace splitting { namespace model { enum class Result { same, different, no_overlap }; // Check whether split it recommended Result compute( VD(std::shared_ptr<core::visual_debug::Datum> sp_datum, ) std::shared_ptr<const core::VisualChangeClassifier> sp_classifier, const cv::Mat transformed_current_pixels, std::shared_ptr<const data::Layer> sp_current_layer, const cv::Mat potential_pixels, std::shared_ptr<const data::Layer> sp_potential_layer); } } }
23.162162
98
0.731622
[ "model" ]
5d79c422c130895af8e4c11ea14381b41c91f202
828
hpp
C++
ddopt/src/problem/bp/bp_instance.hpp
ctjandra/ddopt-cut
0ca4358e7c27a8a56fb2640d450356dcda91b7f0
[ "MIT" ]
6
2018-02-15T03:54:35.000Z
2022-02-24T03:06:05.000Z
ddopt/src/problem/bp/bp_instance.hpp
ctjandra/ddopt-cut
0ca4358e7c27a8a56fb2640d450356dcda91b7f0
[ "MIT" ]
null
null
null
ddopt/src/problem/bp/bp_instance.hpp
ctjandra/ddopt-cut
0ca4358e7c27a8a56fb2640d450356dcda91b7f0
[ "MIT" ]
2
2021-01-07T02:29:55.000Z
2021-12-05T13:21:13.000Z
/** * Binary problem instance */ #ifndef BP_INSTANCE_HPP_ #define BP_INSTANCE_HPP_ #include "../instance.hpp" #include "bpvar.hpp" #include "bprow.hpp" using namespace std; /** * Binary program instance structure */ class BPInstance : public Instance { public: vector<BPVar*> vars; /**< variables */ vector<BPRow*> rows; /**< constraints */ // int nvars in base Instance class int nrows; BPInstance(vector<BPVar*> _vars, vector<BPRow*> _rows) : vars(_vars), rows(_rows) { nvars = _vars.size(); nrows = _rows.size(); weights = new double[nvars]; for (int i = 0; i < nvars; i++) { weights[i] = _vars[i]->obj; } } ~BPInstance() { delete[] weights; } }; #endif /* BP_INSTANCE_HPP_ */
18
82
0.561594
[ "vector" ]
5d8609dfba6343bd7b4fb23cf2f6aef71a0bd2ea
3,627
cpp
C++
missile.cpp
dridk/tankfighter
2a4f9e72b524bb991ad1d5c665890845d4e288ba
[ "Zlib", "MIT" ]
1
2019-04-17T14:54:19.000Z
2019-04-17T14:54:19.000Z
missile.cpp
dridk/tankfighter
2a4f9e72b524bb991ad1d5c665890845d4e288ba
[ "Zlib", "MIT" ]
null
null
null
missile.cpp
dridk/tankfighter
2a4f9e72b524bb991ad1d5c665890845d4e288ba
[ "Zlib", "MIT" ]
1
2019-04-17T14:54:20.000Z
2019-04-17T14:54:20.000Z
#include "missile.h" #include "player.h" #include "wall.h" #include "coretypes.h" #include "engine.h" #include "engine_event.h" #include "geometry.h" #include <math.h> #include <stdio.h> #include "controller.h" #include "parameters.h" #include "misc.h" using namespace sf; Missile::Missile(Player *player0) :Entity(SHAPE_CIRCLE, player0->getEngine()),player(player0) { Vector2d cvect; position = player->position; angle = player->getCanonAngle(); double canon_length = parameters.getCanonLength(); cvect.x = cos(angle)*canon_length; cvect.y = sin(angle)*canon_length; position += cvect; } Missile::~Missile() { player = NULL; } Vector2d Missile::getSize() const { Vector2d sz; sz.x = parameters.missileDiameter(); sz.y = sz.x; return sz; } Player *Missile::getOwner(void) const { return player; } void Missile::draw(sf::RenderTarget &target) const { Sprite &sprite = *getEngine()->getTextureCache()->getSprite(parameters.missileSpriteName().c_str()); FloatRect r = sprite.getLocalBounds(); sprite.setOrigin(Vector2f(r.width/2, r.height/2)); sprite.setPosition(Vector2f(position.x, position.y)); sprite.setRotation(360/(2*M_PI)*angle+90); if (player) { sprite.setColor(player->getColor()); } drawSprite(sprite, target); } double Missile::getAngle(void) const {return angle;} MissileControllingData::MissileControllingData() { flags = 0; movement = Vector2d(0,0); assigned_position = Vector2d(0, 0); new_angle = 0; must_die = false; } #if 0 double Missile::setAngle(double nangle) {angle = nangle;} double Missile::setPosition(const Vector2d &pos) { position = pos; movement.x = 0; movement.y = 0; } void Missile::move(const Vector2d &vect) { movement = vect; } void Missile::Die(void) { setKilled(); } #endif Int64 Missile::usecGetLifetime(void) { return lifetime.getElapsedTime().asMicroseconds(); } Vector2d Missile::movement(Int64 tm) { Vector2d v; MissileControllingData mcd; player->getController()->reportMissileMovement(this, mcd); if (mcd.flags & MCD_Position) { position = mcd.assigned_position; v.x = 0; v.y = 0; } else if (mcd.flags & MCD_Movement) { v.x = mcd.movement.x * tm * parameters.missileSpeed(); v.y = mcd.movement.y * tm * parameters.missileSpeed(); } if (mcd.flags & MCD_Angle) { angle = mcd.new_angle; } if (mcd.must_die) { getEngine()->destroy(this); } return v; } void Missile::event_received(EngineEvent *event) { Player *dying; if (EntityDestroyedEvent *de = dynamic_cast<EntityDestroyedEvent*>(event)) { if (de->entity == static_cast<Entity*>(player)) { player = NULL; getEngine()->destroy(this); } } else if (CollisionEvent *ce = dynamic_cast<CollisionEvent*>(event)) { if (ce->first == static_cast<Entity*>(this)) { if (dynamic_cast<Wall*>(ce->second)) { ce->interaction = IT_BOUNCE; } else if (static_cast<Entity*>(player) != ce->second && (dying = dynamic_cast<Player*>(ce->second))) { ce->interaction = IT_GHOST; if (player->getController()->missileCollision(this,dying)) { dying->killedBy(player); player->killedPlayer(dying); /* missile dies */ getEngine()->destroy(this); } } } } else if (CompletedMovementEvent *cme = dynamic_cast<CompletedMovementEvent*>(event)) { if (cme->entity == static_cast<Entity*>(this)) { position = cme->position; if (cme->has_new_speed) { double nangle = angle_from_dxdy(cme->new_speed.x, cme->new_speed.y); if (fabs(nangle - angle) >= M_PI*1e-4) angle = nangle; } } } } void Missile::setAngle(double angle0) { angle = angle0; } void Missile::setPosition(const Vector2d &position0) { position = position0; }
26.669118
106
0.693686
[ "geometry" ]
5d8f45f206c896558d401bd362df7725712993e4
19,383
cpp
C++
test/tree_3d.cpp
gnzlbg/htree
30e29145b6b0b0f4d1106f05376df94bd58cadc9
[ "BSL-1.0" ]
15
2015-09-02T13:25:55.000Z
2021-04-23T04:02:19.000Z
test/tree_3d.cpp
gnzlbg/htree
30e29145b6b0b0f4d1106f05376df94bd58cadc9
[ "BSL-1.0" ]
1
2015-11-18T03:50:18.000Z
2016-06-16T08:34:01.000Z
test/tree_3d.cpp
gnzlbg/htree
30e29145b6b0b0f4d1106f05376df94bd58cadc9
[ "BSL-1.0" ]
4
2016-05-20T18:57:27.000Z
2019-03-17T09:18:13.000Z
/// \file tree_3d.cpp #include <fstream> #include "test.hpp" #include "tree.hpp" #include <ndtree/algorithm/dfs_sort.hpp> #include <ndtree/algorithm/node_location.hpp> #include <ndtree/location/slim.hpp> using namespace test; /// Explicit instantiate it template struct ndtree::tree<3>; NDTREE_STATIC_ASSERT_RANDOM_ACCESS_SIZED_RANGE( std::declval<tree<3>>().children(node_idx{})); NDTREE_STATIC_ASSERT_RANDOM_ACCESS_SIZED_RANGE(std::declval<tree<3>>()()); NDTREE_STATIC_ASSERT_RANDOM_ACCESS_SIZED_RANGE(tree<3>::child_positions()); struct uniform_tree { std::vector<node> nodes{ {idx{0}, lvl{0}, pn{i}, cs{1, 2, 3, 4, 5, 6, 7, 8}, pip{}, fn{is(6)}, en{is(12)}, cn{is(8)}, an{}}, // level 1: {idx{1}, lvl{1}, pn{0}, cs{9, 10, 11, 12, 13, 14, 15, 16}, pip{0}, fn{i, 2, i, 3, i, 5}, en{i, i, i, 4, i, i, i, i, i, 6, i, 7}, cn{i, i, i, i, i, i, i, 8}}, {idx{2}, lvl{1}, pn{0}, cs{17, 18, 19, 20, 21, 22, 23, 24}, pip{1}, fn{1, i, i, 4, i, 6}, en{i, i, 3, i, i, i, i, i, 5, i, i, 8}, cn{i, i, i, i, i, i, 7, i}}, {idx{3}, lvl{1}, pn{0}, cs{25, 26, 27, 28, 29, 30, 31, 32}, pip{2}, fn{i, 4, 1, i, i, 7}, en{i, 2, i, i, i, i, i, i, i, 8, 5, i}, cn{i, i, i, i, i, 6, i, i}}, {idx{4}, lvl{1}, pn{0}, cs{33, 34, 35, 36, 37, 38, 39, 40}, pip{3}, fn{3, i, 2, i, i, 8}, en{1, i, i, i, i, i, i, i, 7, i, 6, i}, cn{i, i, i, i, 5, i, i, i}}, // {idx{5}, lvl{1}, pn{0}, cs{41, 42, 43, 44, 45, 46, 47, 48}, pip{4}, fn{i, 6, i, 7, 1, i}, en{i, i, i, 8, i, 2, i, 3, i, i, i, i}, cn{i, i, i, 4, i, i, i, i}}, {idx{6}, lvl{1}, pn{0}, cs{49, 50, 51, 52, 53, 54, 55, 56}, pip{5}, fn{5, i, i, 8, 2, i}, en{i, i, 7, i, 1, i, i, 4, i, i, i, i}, cn{i, i, 3, i, i, i, i, i}}, {idx{7}, lvl{1}, pn{0}, cs{57, 58, 59, 60, 61, 62, 63, 64}, pip{6}, fn{i, 8, 5, i, 3, i}, en{i, 6, i, i, i, 4, 1, i, i, i, i, i}, cn{i, 2, i, i, i, i, i, i}}, {idx{8}, lvl{1}, pn{0}, cs{65, 66, 67, 68, 69, 70, 71, 72}, pip{7}, fn{7, i, 6, i, 4, i}, en{5, i, i, i, 3, i, 2, i, i, i, i, i}, cn{1, i, i, i, i, i, i, i}}, // level 2: {idx{9}, lvl{2}, pn{1}, cs{}, pip{0, 0}, fn{i, 10, i, 11, i, 13}, en{i, i, i, 12, i, i, i, i, i, 14, i, 15}, cn{i, i, i, i, i, i, i, 16}}, {idx{10}, lvl{2}, pn{1}, cs{}, pip{0, 1}, fn{9, 17, i, 12, i, 14}, en{i, i, 11, 19, i, i, i, i, 13, 21, i, 16}, cn{i, i, i, i, i, i, 15, 23}}, {idx{11}, lvl{2}, pn{1}, cs{}, pip{0, 2}, fn{i, 12, 9, 25, i, 15}, en{i, 10, i, 26, i, i, i, i, i, 16, 13, 29}, cn{i, i, i, i, i, 14, i, 30}}, {idx{12}, lvl{2}, pn{1}, cs{}, pip{0, 3}, fn{11, 19, 10, 26, i, 16}, en{9, 17, 25, 33, i, i, i, i, 15, 23, 14, 30}, cn{i, i, i, i, 13, 21, 29, 37}}, {idx{13}, lvl{2}, pn{1}, cs{}, pip{0, 4}, fn{i, 14, i, 15, 9, 41}, en{i, i, i, 16, i, 10, i, 11, i, 42, i, 43}, cn{i, i, i, 12, i, i, i, 44}}, {idx{14}, lvl{2}, pn{1}, cs{}, pip{0, 5}, fn{13, 21, i, 16, 10, 42}, en{i, i, 15, 23, 9, 17, i, 12, 41, 49, i, 44}, cn{i, i, 11, 19, i, i, 43, 51}}, {idx{15}, lvl{2}, pn{1}, cs{}, pip{0, 6}, fn{i, 16, 13, 29, 11, 43}, en{i, 14, i, 30, i, 12, 9, 25, i, 44, 41, 57}, cn{i, 10, i, 26, i, 42, i, 58}}, {idx{16}, lvl{2}, pn{1}, cs{}, pip{0, 7}, fn{15, 23, 14, 30, 12, 44}, en{13, 21, 29, 37, 11, 19, 10, 26, 43, 51, 42, 58}, cn{9, 17, 25, 33, 41, 49, 57, 65}}, // {idx{17}, lvl{2}, pn{2}, cs{}, pip{1, 0}, fn{10, 18, i, 19, i, 21}, en{i, i, 12, 20, i, i, i, i, 14, 22, i, 23}, cn{i, i, i, i, i, i, 16, 24}}, {idx{18}, lvl{2}, pn{2}, cs{}, pip{1, 1}, fn{17, i, i, 20, i, 22}, en{i, i, 19, i, i, i, i, i, 21, i, i, 24}, cn{i, i, i, i, i, i, 23, i}}, {idx{19}, lvl{2}, pn{2}, cs{}, pip{1, 2}, fn{12, 20, 17, 33, i, 23}, en{10, 18, 26, 34, i, i, i, i, 16, 24, 21, 37}, cn{i, i, i, i, 14, 22, 30, 38}}, {idx{20}, lvl{2}, pn{2}, cs{}, pip{1, 3}, fn{19, i, 18, 34, i, 24}, en{17, i, 33, i, i, i, i, i, 23, i, 22, 38}, cn{i, i, i, i, 21, i, 37, i}}, {idx{21}, lvl{2}, pn{2}, cs{}, pip{1, 4}, fn{14, 22, i, 23, 17, 49}, en{i, i, 16, 24, 10, 18, i, 19, 42, 50, i, 51}, cn{i, i, 12, 20, i, i, 44, 52}}, {idx{22}, lvl{2}, pn{2}, cs{}, pip{1, 5}, fn{21, i, i, 24, 18, 50}, en{i, i, 23, i, 17, i, i, 20, 49, i, i, 52}, cn{i, i, 19, i, i, i, 51, i}}, {idx{23}, lvl{2}, pn{2}, cs{}, pip{1, 6}, fn{16, 24, 21, 37, 19, 51}, en{14, 22, 30, 38, 12, 20, 17, 33, 44, 52, 49, 65}, cn{10, 18, 26, 34, 42, 50, 58, 66}}, {idx{24}, lvl{2}, pn{2}, cs{}, pip{1, 7}, fn{23, i, 22, 38, 20, 52}, en{21, i, 37, i, 19, i, 18, 34, 51, i, 50, 66}, cn{17, i, 33, i, 49, i, 65, i}}, // {idx{25}, lvl{2}, pn{3}, cs{}, pip{2, 0}}, {idx{26}, lvl{2}, pn{3}, cs{}, pip{2, 1}}, {idx{27}, lvl{2}, pn{3}, cs{}, pip{2, 2}}, {idx{28}, lvl{2}, pn{3}, cs{}, pip{2, 3}}, {idx{29}, lvl{2}, pn{3}, cs{}, pip{2, 4}}, {idx{30}, lvl{2}, pn{3}, cs{}, pip{2, 5}, fn{29, 37, 16, 32, 26, 58}, en{15, 23, 31, 39, 25, 33, 12, 28, 57, 65, 44, 60}, cn{11, 19, 27, 35, 43, 51, 59, 67}}, {idx{31}, lvl{2}, pn{3}, cs{}, pip{2, 6}}, {idx{32}, lvl{2}, pn{3}, cs{}, pip{2, 7}}, // {idx{33}, lvl{2}, pn{4}, cs{}, pip{3, 0}}, {idx{34}, lvl{2}, pn{4}, cs{}, pip{3, 1}}, {idx{35}, lvl{2}, pn{4}, cs{}, pip{3, 2}}, {idx{36}, lvl{2}, pn{4}, cs{}, pip{3, 3}}, {idx{37}, lvl{2}, pn{4}, cs{}, pip{3, 4}, fn{30, 38, 23, 39, 33, 65}, en{16, 24, 32, 40, 26, 34, 19, 35, 58, 66, 51, 67}, cn{12, 20, 28, 36, 44, 52, 60, 68}}, {idx{38}, lvl{2}, pn{4}, cs{}, pip{3, 5}}, {idx{39}, lvl{2}, pn{4}, cs{}, pip{3, 6}}, {idx{40}, lvl{2}, pn{4}, cs{}, pip{3, 7}}, // {idx{41}, lvl{2}, pn{5}, cs{}, pip{4, 0}, fn{i, 42, i, 43, 13, 45}, en{i, i, i, 44, i, 14, i, 15, i, 46, i, 47}, cn{i, i, i, 16, i, i, i, 48}}, {idx{42}, lvl{2}, pn{5}, cs{}, pip{4, 1}}, {idx{43}, lvl{2}, pn{5}, cs{}, pip{4, 2}}, {idx{44}, lvl{2}, pn{5}, cs{}, pip{4, 3}, fn{43, 51, 42, 58, 16, 48}, en{41, 49, 57, 65, 15, 23, 14, 30, 47, 55, 46, 62}, cn{13, 21, 29, 37, 45, 53, 61, 69}}, {idx{45}, lvl{2}, pn{5}, cs{}, pip{4, 4}, fn{i, 46, i, 47, 41, i}, en{i, i, i, 48, i, 42, i, 43, i, i, i, i}, cn{i, i, i, 44, i, i, i, i}}, {idx{46}, lvl{2}, pn{5}, cs{}, pip{4, 5}}, {idx{47}, lvl{2}, pn{5}, cs{}, pip{4, 6}}, {idx{48}, lvl{2}, pn{5}, cs{}, pip{4, 7}}, // {idx{49}, lvl{2}, pn{6}, cs{}, pip{5, 0}}, {idx{50}, lvl{2}, pn{6}, cs{}, pip{5, 1}, fn{49, i, i, 52, 22, 54}, en{i, i, 51, i, 21, i, i, 24, 53, i, i, 56}, cn{i, i, 23, i, i, i, 55, i}}, {idx{51}, lvl{2}, pn{6}, cs{}, pip{5, 2}, fn{44, 52, 49, 65, 23, 55}, en{42, 50, 58, 66, 16, 24, 21, 37, 48, 56, 53, 69}, cn{14, 22, 30, 38, 46, 54, 62, 70}}, {idx{52}, lvl{2}, pn{6}, cs{}, pip{5, 3}}, {idx{53}, lvl{2}, pn{6}, cs{}, pip{5, 4}}, {idx{54}, lvl{2}, pn{6}, cs{}, pip{5, 5}, fn{53, i, i, 56, 50, i}, en{i, i, 55, i, 49, i, i, 52, i, i, i, i}, cn{i, i, 51, i, i, i, i, i}}, {idx{55}, lvl{2}, pn{6}, cs{}, pip{5, 6}}, {idx{56}, lvl{2}, pn{6}, cs{}, pip{5, 7}}, // {idx{57}, lvl{2}, pn{7}, cs{}, pip{6, 0}}, {idx{58}, lvl{2}, pn{7}, cs{}, pip{6, 1}, fn{57, 65, 44, 60, 30, 62}, en{43, 51, 59, 67, 29, 37, 16, 32, 61, 69, 48, 64}, cn{15, 23, 31, 39, 47, 55, 63, 71}}, {idx{59}, lvl{2}, pn{7}, cs{}, pip{6, 2}, fn{i, 60, 57, i, 31, 63}, en{i, 58, i, i, i, 32, 29, i, i, 64, 61, i}, cn{i, 30, i, i, i, 62, i, i}}, {idx{60}, lvl{2}, pn{7}, cs{}, pip{6, 3}}, {idx{61}, lvl{2}, pn{7}, cs{}, pip{6, 4}}, {idx{62}, lvl{2}, pn{7}, cs{}, pip{6, 5}}, {idx{63}, lvl{2}, pn{7}, cs{}, pip{6, 6}, fn{i, 64, 61, i, 59, i}, en{i, 62, i, i, i, 60, 57, i, i, i, i, i}, cn{i, 58, i, i, i, i, i, i}}, {idx{64}, lvl{2}, pn{7}, cs{}, pip{6, 7}}, // {idx{65}, lvl{2}, pn{8}, cs{}, pip{7, 0}, fn{58, 66, 51, 67, 37, 69}, en{44, 52, 60, 68, 30, 38, 23, 39, 62, 70, 55, 71}, cn{16, 24, 32, 40, 48, 56, 64, 72}}, {idx{66}, lvl{2}, pn{8}, cs{}, pip{7, 1}}, {idx{67}, lvl{2}, pn{8}, cs{}, pip{7, 2}}, {idx{68}, lvl{2}, pn{8}, cs{}, pip{7, 3}, fn{67, i, 66, i, 40, 72}, en{65, i, i, i, 39, i, 38, i, 71, i, 70, i}, cn{37, i, i, i, 69, i, i, i}}, {idx{69}, lvl{2}, pn{8}, cs{}, pip{7, 4}}, {idx{70}, lvl{2}, pn{8}, cs{}, pip{7, 5}}, {idx{71}, lvl{2}, pn{8}, cs{}, pip{7, 6}}, {idx{72}, lvl{2}, pn{8}, cs{}, pip{7, 7}, fn{71, i, 70, i, 68, i}, en{69, i, i, i, 67, i, 66, i, i, i, i, i}, cn{65, i, i, i, i, i, i, i}}, // }; }; struct tree_after_refine { std::vector<node> nodes{ {idx{0}, lvl{0}, pn{i}, cs{1, 2, 3, 4, 5, 6, 7, 8}, pip{}, fn{is(6)}, en{is(12)}, cn{is(8)}, an{}}, // level 1: {idx{1}, lvl{1}, pn{0}, cs{9, 10, 11, 12, 13, 14, 15, 16}, pip{0}, fn{i, 2, i, 3, i, 5}, en{i, i, i, 4, i, i, i, i, i, 6, i, 7}, cn{i, i, i, i, i, i, i, 8}}, {idx{2}, lvl{1}, pn{0}, cs{17, 18, 19, 20, 21, 22, 23, 24}, pip{1}, fn{1, i, i, 4, i, 6}, en{i, i, 3, i, i, i, i, i, 5, i, i, 8}, cn{i, i, i, i, i, i, 7, i}}, {idx{3}, lvl{1}, pn{0}, cs{25, 26, 27, 28, 29, 30, 31, 32}, pip{2}, fn{i, 4, 1, i, i, 7}, en{i, 2, i, i, i, i, i, i, i, 8, 5, i}, cn{i, i, i, i, i, 6, i, i}}, {idx{4}, lvl{1}, pn{0}, cs{33, 34, 35, 36, 37, 38, 39, 40}, pip{3}, fn{3, i, 2, i, i, 8}, en{1, i, i, i, i, i, i, i, 7, i, 6, i}, cn{i, i, i, i, 5, i, i, i}}, // {idx{5}, lvl{1}, pn{0}, cs{41, 42, 43, 44, 45, 46, 47, 48}, pip{4}, fn{i, 6, i, 7, 1, i}, en{i, i, i, 8, i, 2, i, 3, i, i, i, i}, cn{i, i, i, 4, i, i, i, i}}, {idx{6}, lvl{1}, pn{0}, cs{49, 50, 51, 52, 53, 54, 55, 56}, pip{5}, fn{5, i, i, 8, 2, i}, en{i, i, 7, i, 1, i, i, 4, i, i, i, i}, cn{i, i, 3, i, i, i, i, i}}, {idx{7}, lvl{1}, pn{0}, cs{57, 58, 59, 60, 61, 62, 63, 64}, pip{6}, fn{i, 8, 5, i, 3, i}, en{i, 6, i, i, i, 4, 1, i, i, i, i, i}, cn{i, 2, i, i, i, i, i, i}}, {idx{8}, lvl{1}, pn{0}, cs{65, 66, 67, 68, 69, 70, 71, 72}, pip{7}, fn{7, i, 6, i, 4, i}, en{5, i, i, i, 3, i, 2, i, i, i, i, i}, cn{1, i, i, i, i, i, i, i}}, // level 2: {idx{9}, lvl{2}, pn{1}, cs{}, pip{0, 0}, fn{i, 10, i, 11, i, 13}, en{i, i, i, 12, i, i, i, i, i, 14, i, 15}, cn{i, i, i, i, i, i, i, 16}}, {idx{10}, lvl{2}, pn{1}, cs{}, pip{0, 1}, fn{9, 17, i, 12, i, 14}, en{i, i, 11, 19, i, i, i, i, 13, 21, i, 16}, cn{i, i, i, i, i, i, 15, 23}}, {idx{11}, lvl{2}, pn{1}, cs{}, pip{0, 2}, fn{i, 12, 9, 25, i, 15}, en{i, 10, i, 26, i, i, i, i, i, 16, 13, 29}, cn{i, i, i, i, i, 14, i, 30}}, {idx{12}, lvl{2}, pn{1}, cs{}, pip{0, 3}, fn{11, 19, 10, 26, i, 16}, en{9, 17, 25, 33, i, i, i, i, 15, 23, 14, 30}, cn{i, i, i, i, 13, 21, 29, 37}}, {idx{13}, lvl{2}, pn{1}, cs{}, pip{0, 4}, fn{i, 14, i, 15, 9, 41}, en{i, i, i, 16, i, 10, i, 11, i, 42, i, 43}, cn{i, i, i, 12, i, i, i, 44}}, {idx{14}, lvl{2}, pn{1}, cs{}, pip{0, 5}, fn{13, 21, i, 16, 10, 42}, en{i, i, 15, 23, 9, 17, i, 12, 41, 49, i, 44}, cn{i, i, 11, 19, i, i, 43, 51}}, {idx{15}, lvl{2}, pn{1}, cs{}, pip{0, 6}, fn{i, 16, 13, 29, 11, 43}, en{i, 14, i, 30, i, 12, 9, 25, i, 44, 41, 57}, cn{i, 10, i, 26, i, 42, i, 58}}, {idx{16}, lvl{2}, pn{1}, cs{73, 74, 75, 76, 77, 78, 79, 80}, pip{0, 7}, fn{15, 23, 14, 30, 12, 44}, en{13, 21, 29, 37, 11, 19, 10, 26, 43, 51, 42, 58}, cn{9, 17, 25, 33, 41, 49, 57, 65}}, // {idx{17}, lvl{2}, pn{2}, cs{}, pip{1, 0}, fn{10, 18, i, 19, i, 21}, en{i, i, 12, 20, i, i, i, i, 14, 22, i, 23}, cn{i, i, i, i, i, i, 16, 24}}, {idx{18}, lvl{2}, pn{2}, cs{}, pip{1, 1}, fn{17, i, i, 20, i, 22}, en{i, i, 19, i, i, i, i, i, 21, i, i, 24}, cn{i, i, i, i, i, i, 23, i}}, {idx{19}, lvl{2}, pn{2}, cs{}, pip{1, 2}, fn{12, 20, 17, 33, i, 23}, en{10, 18, 26, 34, i, i, i, i, 16, 24, 21, 37}, cn{i, i, i, i, 14, 22, 30, 38}}, {idx{20}, lvl{2}, pn{2}, cs{}, pip{1, 3}, fn{19, i, 18, 34, i, 24}, en{17, i, 33, i, i, i, i, i, 23, i, 22, 38}, cn{i, i, i, i, 21, i, 37, i}}, {idx{21}, lvl{2}, pn{2}, cs{}, pip{1, 4}, fn{14, 22, i, 23, 17, 49}, en{i, i, 16, 24, 10, 18, i, 19, 42, 50, i, 51}, cn{i, i, 12, 20, i, i, 44, 52}}, {idx{22}, lvl{2}, pn{2}, cs{}, pip{1, 5}, fn{21, i, i, 24, 18, 50}, en{i, i, 23, i, 17, i, i, 20, 49, i, i, 52}, cn{i, i, 19, i, i, i, 51, i}}, {idx{23}, lvl{2}, pn{2}, cs{}, pip{1, 6}, fn{16, 24, 21, 37, 19, 51}, en{14, 22, 30, 38, 12, 20, 17, 33, 44, 52, 49, 65}, cn{10, 18, 26, 34, 42, 50, 58, 66}}, {idx{24}, lvl{2}, pn{2}, cs{}, pip{1, 7}, fn{23, i, 22, 38, 20, 52}, en{21, i, 37, i, 19, i, 18, 34, 51, i, 50, 66}, cn{17, i, 33, i, 49, i, 65, i}}, // {idx{25}, lvl{2}, pn{3}, cs{}, pip{2, 0}}, {idx{26}, lvl{2}, pn{3}, cs{}, pip{2, 1}}, {idx{27}, lvl{2}, pn{3}, cs{}, pip{2, 2}}, {idx{28}, lvl{2}, pn{3}, cs{}, pip{2, 3}}, {idx{29}, lvl{2}, pn{3}, cs{}, pip{2, 4}}, {idx{30}, lvl{2}, pn{3}, cs{}, pip{2, 5}, fn{29, 37, 16, 32, 26, 58}, en{15, 23, 31, 39, 25, 33, 12, 28, 57, 65, 44, 60}, cn{11, 19, 27, 35, 43, 51, 59, 67}}, {idx{31}, lvl{2}, pn{3}, cs{}, pip{2, 6}}, {idx{32}, lvl{2}, pn{3}, cs{}, pip{2, 7}}, // {idx{33}, lvl{2}, pn{4}, cs{}, pip{3, 0}}, {idx{34}, lvl{2}, pn{4}, cs{}, pip{3, 1}}, {idx{35}, lvl{2}, pn{4}, cs{}, pip{3, 2}}, {idx{36}, lvl{2}, pn{4}, cs{}, pip{3, 3}}, {idx{37}, lvl{2}, pn{4}, cs{}, pip{3, 4}, fn{30, 38, 23, 39, 33, 65}, en{16, 24, 32, 40, 26, 34, 19, 35, 58, 66, 51, 67}, cn{12, 20, 28, 36, 44, 52, 60, 68}}, {idx{38}, lvl{2}, pn{4}, cs{}, pip{3, 5}}, {idx{39}, lvl{2}, pn{4}, cs{}, pip{3, 6}}, {idx{40}, lvl{2}, pn{4}, cs{}, pip{3, 7}}, // {idx{41}, lvl{2}, pn{5}, cs{}, pip{4, 0}, fn{i, 42, i, 43, 13, 45}, en{i, i, i, 44, i, 14, i, 15, i, 46, i, 47}, cn{i, i, i, 16, i, i, i, 48}}, {idx{42}, lvl{2}, pn{5}, cs{}, pip{4, 1}}, {idx{43}, lvl{2}, pn{5}, cs{}, pip{4, 2}}, {idx{44}, lvl{2}, pn{5}, cs{}, pip{4, 3}, fn{43, 51, 42, 58, 16, 48}, en{41, 49, 57, 65, 15, 23, 14, 30, 47, 55, 46, 62}, cn{13, 21, 29, 37, 45, 53, 61, 69}}, {idx{45}, lvl{2}, pn{5}, cs{}, pip{4, 4}, fn{i, 46, i, 47, 41, i}, en{i, i, i, 48, i, 42, i, 43, i, i, i, i}, cn{i, i, i, 44, i, i, i, i}}, {idx{46}, lvl{2}, pn{5}, cs{}, pip{4, 5}}, {idx{47}, lvl{2}, pn{5}, cs{}, pip{4, 6}}, {idx{48}, lvl{2}, pn{5}, cs{}, pip{4, 7}}, // {idx{49}, lvl{2}, pn{6}, cs{}, pip{5, 0}}, {idx{50}, lvl{2}, pn{6}, cs{}, pip{5, 1}, fn{49, i, i, 52, 22, 54}, en{i, i, 51, i, 21, i, i, 24, 53, i, i, 56}, cn{i, i, 23, i, i, i, 55, i}}, {idx{51}, lvl{2}, pn{6}, cs{}, pip{5, 2}, fn{44, 52, 49, 65, 23, 55}, en{42, 50, 58, 66, 16, 24, 21, 37, 48, 56, 53, 69}, cn{14, 22, 30, 38, 46, 54, 62, 70}}, {idx{52}, lvl{2}, pn{6}, cs{}, pip{5, 3}}, {idx{53}, lvl{2}, pn{6}, cs{}, pip{5, 4}}, {idx{54}, lvl{2}, pn{6}, cs{}, pip{5, 5}, fn{53, i, i, 56, 50, i}, en{i, i, 55, i, 49, i, i, 52, i, i, i, i}, cn{i, i, 51, i, i, i, i, i}}, {idx{55}, lvl{2}, pn{6}, cs{}, pip{5, 6}}, {idx{56}, lvl{2}, pn{6}, cs{}, pip{5, 7}}, // {idx{57}, lvl{2}, pn{7}, cs{}, pip{6, 0}}, {idx{58}, lvl{2}, pn{7}, cs{}, pip{6, 1}, fn{57, 65, 44, 60, 30, 62}, en{43, 51, 59, 67, 29, 37, 16, 32, 61, 69, 48, 64}, cn{15, 23, 31, 39, 47, 55, 63, 71}}, {idx{59}, lvl{2}, pn{7}, cs{}, pip{6, 2}, fn{i, 60, 57, i, 31, 63}, en{i, 58, i, i, i, 32, 29, i, i, 64, 61, i}, cn{i, 30, i, i, i, 62, i, i}}, {idx{60}, lvl{2}, pn{7}, cs{}, pip{6, 3}}, {idx{61}, lvl{2}, pn{7}, cs{}, pip{6, 4}}, {idx{62}, lvl{2}, pn{7}, cs{}, pip{6, 5}}, {idx{63}, lvl{2}, pn{7}, cs{}, pip{6, 6}, fn{i, 64, 61, i, 59, i}, en{i, 62, i, i, i, 60, 57, i, i, i, i, i}, cn{i, 58, i, i, i, i, i, i}}, {idx{64}, lvl{2}, pn{7}, cs{}, pip{6, 7}}, // {idx{65}, lvl{2}, pn{8}, cs{81, 82, 83, 84, 85, 86, 87, 88}, pip{7, 0}, fn{58, 66, 51, 67, 37, 69}, en{44, 52, 60, 68, 30, 38, 23, 39, 62, 70, 55, 71}, cn{16, 24, 32, 40, 48, 56, 64, 72}}, {idx{66}, lvl{2}, pn{8}, cs{}, pip{7, 1}}, {idx{67}, lvl{2}, pn{8}, cs{}, pip{7, 2}}, {idx{68}, lvl{2}, pn{8}, cs{}, pip{7, 3}, fn{67, i, 66, i, 40, 72}, en{65, i, i, i, 39, i, 38, i, 71, i, 70, i}, cn{37, i, i, i, 69, i, i, i}}, {idx{69}, lvl{2}, pn{8}, cs{}, pip{7, 4}}, {idx{70}, lvl{2}, pn{8}, cs{}, pip{7, 5}}, {idx{71}, lvl{2}, pn{8}, cs{}, pip{7, 6}}, {idx{72}, lvl{2}, pn{8}, cs{}, pip{7, 7}, fn{71, i, 70, i, 68, i}, en{69, i, i, i, 67, i, 66, i, i, i, i, i}, cn{65, i, i, i, i, i, i, i}}, // level: 3 {idx{73}, lvl{3}, pn{16}, cs{}, pip{0, 7, 0}}, {idx{74}, lvl{3}, pn{16}, cs{}, pip{0, 7, 1}}, {idx{75}, lvl{3}, pn{16}, cs{}, pip{0, 7, 2}}, {idx{76}, lvl{3}, pn{16}, cs{}, pip{0, 7, 3}}, {idx{77}, lvl{3}, pn{16}, cs{}, pip{0, 7, 4}}, {idx{78}, lvl{3}, pn{16}, cs{}, pip{0, 7, 5}}, {idx{79}, lvl{3}, pn{16}, cs{}, pip{0, 7, 6}}, {idx{80}, lvl{3}, pn{16}, cs{}, pip{0, 7, 7}, fn{79, i, 78, i, 76, i}, en{77, i, i, i, 75, i, 74, i, i, i, i, i}, cn{73, i, i, i, i, i, i, 81}, an{23, 30, 37, 44, 51, 58, 73, 74, 75, 76, 77, 78, 79, 81}}, // {idx{81}, lvl{3}, pn{65}, cs{}, pip{7, 0, 0}, fn{i, 82, i, 83, i, 85}, en{i, i, i, 84, i, i, i, i, i, 86, i, 87}, cn{80, i, i, i, i, i, i, 88}, an{23, 30, 37, 44, 51, 58, 80, 82, 83, 84, 85, 86, 87, 88}}, {idx{82}, lvl{3}, pn{65}, cs{}, pip{7, 0, 1}}, {idx{83}, lvl{3}, pn{65}, cs{}, pip{7, 0, 2}}, {idx{84}, lvl{3}, pn{65}, cs{}, pip{7, 0, 3}}, {idx{85}, lvl{3}, pn{65}, cs{}, pip{7, 0, 4}}, {idx{86}, lvl{3}, pn{65}, cs{}, pip{7, 0, 5}}, {idx{87}, lvl{3}, pn{65}, cs{}, pip{7, 0, 6}}, {idx{88}, lvl{3}, pn{65}, cs{}, pip{7, 0, 7}}, // }; }; template <template <ndtree::uint_t, class...> class Loc> void test_tree() { { // check construction tree<3> t(1); CHECK(t.capacity() == 1_u); CHECK(t.size() == 1_u); CHECK(!t.empty()); CHECK(t.is_leaf(0_n)); } { // check capacity CHECK(tree<3>(1).capacity() == 1_u); CHECK(tree<3>(2).capacity() == 9_u); CHECK(tree<3>(3).capacity() == 9_u); CHECK(tree<3>(4).capacity() == 9_u); CHECK(tree<3>(5).capacity() == 9_u); CHECK(tree<3>(6).capacity() == 9_u); CHECK(tree<3>(7).capacity() == 9_u); CHECK(tree<3>(8).capacity() == 9_u); CHECK(tree<3>(9).capacity() == 9_u); CHECK(tree<3>(10).capacity() == 17_u); CHECK(tree<3>(11).capacity() == 17_u); CHECK(tree<3>(12).capacity() == 17_u); CHECK(tree<3>(13).capacity() == 17_u); CHECK(tree<3>(17).capacity() == 17_u); CHECK(tree<3>(18).capacity() == 25_u); } { tree<3> t(89); CHECK(t.capacity() == 89_u); CHECK(t.size() == 1_u); CHECK(t.is_leaf(0_n)); t.refine(0_n); CHECK(!t.is_leaf(0_n)); CHECK(t.size() == 9_u); t.refine(1_n); t.refine(2_n); t.refine(3_n); t.refine(4_n); t.refine(5_n); t.refine(6_n); t.refine(7_n); t.refine(8_n); CHECK(t.size() == 73_u); check_tree(t, uniform_tree{}, Loc<3>{}); CHECK(t == uniformly_refined_tree<3>(2, 2)); t.refine(16_n); t.refine(65_n); CHECK(t.size() == 89_u); check_tree(t, tree_after_refine{}, Loc<3>{}); CHECK(t != uniformly_refined_tree<3>(2, 3)); } { auto t = uniformly_refined_tree<3>(2, 3); check_tree(t, uniform_tree{}, Loc<3>{}); t.refine(16_n); t.refine(65_n); CHECK(t.size() == 89_u); check_tree(t, tree_after_refine{}, Loc<3>{}); } } int main() { test_tree<location::fast>(); test_tree<location::slim>(); return test::result(); }
46.370813
79
0.435691
[ "vector" ]
5d961dcd66e36ba4e0b371d96333eb9fbbbb585e
3,577
cc
C++
middle-end-optis/procedure-placement/src/lib/pp.cc
obs145628/cle
4a4a18b2ab5a6fbf26629f6845147541edabd7c9
[ "MIT" ]
null
null
null
middle-end-optis/procedure-placement/src/lib/pp.cc
obs145628/cle
4a4a18b2ab5a6fbf26629f6845147541edabd7c9
[ "MIT" ]
null
null
null
middle-end-optis/procedure-placement/src/lib/pp.cc
obs145628/cle
4a4a18b2ab5a6fbf26629f6845147541edabd7c9
[ "MIT" ]
null
null
null
#include "pp.hh" #include <algorithm> #include <iostream> namespace { struct CGVal { std::size_t src; std::size_t dst; int val; CGVal(std::size_t src, std::size_t dst, int val) : src(src), dst(dst), val(val) {} }; class CGQueue { public: void add(const CGVal &ci) { if (ci.src == ci.dst) return; // ignore self-loop CGVal *act = nullptr; // find already available src -> dst edge for (auto &item : _q) if (item.src == ci.src && item.dst == ci.dst) { act = &item; break; } if (act) act->val += ci.val; else { auto it = std::upper_bound( _q.begin(), _q.end(), ci, [](const CGVal &a, const CGVal &b) { return a.val < b.val; }); _q.insert(it, ci); } } CGVal pop() { CGVal res = _q.back(); _q.pop_back(); return res; } void rename(std::size_t prev, std::size_t next) { for (auto &item : _q) { if (item.src == prev) item.src = next; if (item.dst == prev) item.dst = next; } // Rebuild queue to handle doublons that may appear because of renaming: sum // values auto vals = std::move(_q); for (auto &item : vals) add(item); } bool empty() const { return _q.empty(); } void dump(std::ostream &os) { os << "CGQ: {"; for (auto it = _q.rbegin(); it != _q.rend(); ++it) os << "(P" << it->src << ", P" << it->dst << ", " << it->val << "); "; os << "}\n"; } private: std::vector<CGVal> _q; }; using fun_list_t = std::vector<std::string>; class PP { public: PP(Module &mod) : _mod(mod) {} void run(const std::vector<CallInfos> &cg_freqs) { // Step 1: Initialize queue and list std::map<std::string, std::size_t> n2i; for (const auto &fun : _mod.fun()) { _lists.push_back({fun.name()}); n2i.emplace(fun.name(), n2i.size()); } for (const auto &ci : cg_freqs) _cgq.add(CGVal(n2i[ci.src], n2i[ci.dst], ci.val)); _dump(std::cout); // Step 2: Reduce graph until queue empty while (!_cgq.empty()) { _reduce(); _dump(std::cout); } // At this step, there is M lists, one for each connected component of the // callgraph The order in each list is chosen to increase cache locality // Procedures should be put by following the order inside the lists // The position from one list to another doesn't matter std::vector<Function *> new_order; for (const auto &l : _lists) for (const auto &f : l) new_order.push_back(_mod.get_fun(f)); _mod.fun_list().reorder(new_order); } private: Module &_mod; CGQueue _cgq; std::vector<fun_list_t> _lists; // Reduce the graph by poping from the queue (most freq edge) // Then combine the 2 lists related to the vertices of the edge in one // Need to update the values in the queue (rename y by x) void _reduce() { auto next = _cgq.pop(); fun_list_t &lx = _lists[next.src]; fun_list_t &ly = _lists[next.dst]; assert(!lx.empty()); assert(!ly.empty()); _cgq.rename(next.dst, next.src); lx.insert(lx.end(), ly.begin(), ly.end()); ly.clear(); } void _dump(std::ostream &os) { for (std::size_t i = 0; i < _lists.size(); ++i) { if (_lists[i].empty()) continue; os << "P" << i << ": {"; for (auto &f : _lists[i]) os << f << ' '; os << "}; "; } os << "\n"; _cgq.dump(os); os << "\n"; } }; } // namespace void pp_run(Module &mod, const std::vector<CallInfos> &cg_freqs) { PP pp(mod); pp.run(cg_freqs); }
23.379085
80
0.559966
[ "vector" ]
4b68cc61d5c0fe6b9df95af4717c1a1de5fc1198
4,957
cpp
C++
tools/macpo/libmacpo/tracer.cpp
roystgnr/perfexpert
a03b13db9ac83e992e1c5cc3b6e45e52c266fe30
[ "BSD-4-Clause-UC" ]
28
2015-05-05T15:54:25.000Z
2021-09-27T16:23:36.000Z
tools/macpo/libmacpo/tracer.cpp
roystgnr/perfexpert
a03b13db9ac83e992e1c5cc3b6e45e52c266fe30
[ "BSD-4-Clause-UC" ]
15
2015-10-07T20:52:05.000Z
2018-04-18T16:08:41.000Z
tools/macpo/libmacpo/tracer.cpp
roystgnr/perfexpert
a03b13db9ac83e992e1c5cc3b6e45e52c266fe30
[ "BSD-4-Clause-UC" ]
11
2015-01-23T15:41:40.000Z
2020-08-18T03:53:19.000Z
/* * Copyright (c) 2011-2013 University of Texas at Austin. All rights reserved. * * $COPYRIGHT$ * * Additional copyrights may follow * * This file is part of PerfExpert. * * PerfExpert is free software: you can redistribute it and/or modify it under * the terms of the The University of Texas at Austin Research License * * PerfExpert 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. * * Authors: Leonardo Fialho and Ashay Rane * * $HEADER$ */ #include <rose.h> #include <algorithm> #include <string> #include <vector> #include "analysis_profile.h" #include "inst_defs.h" #include "tracer.h" #include "ir_methods.h" #include "macpo_record.h" #include "streams.h" using namespace SageBuilder; using namespace SageInterface; void tracer_t::atTraversalStart() { analysis_profile.start_timer(); stream_list.clear(); statement_list.clear(); } void tracer_t::atTraversalEnd() { analysis_profile.end_timer(); } name_list_t& tracer_t::get_stream_list() { return stream_list; } attrib tracer_t::evaluateInheritedAttribute(SgNode* node, attrib attr) { if (attr.skip) return attr; streams_t streams; streams.traverse(node, attrib()); reference_list_t& reference_list = streams.get_reference_list(); size_t count = 0; for (reference_list_t::iterator it = reference_list.begin(); it != reference_list.end(); it++) { reference_info_t& reference_info = *it; std::string stream = reference_info.name; if (count == reference_info.idx) { stream_list.push_back(stream); count += 1; } } for (reference_list_t::iterator it = reference_list.begin(); it != reference_list.end(); it++) { reference_info_t& reference_info = *it; SgNode* ref_node = reference_info.node; std::string stream = reference_info.name; int16_t ref_access_type = reference_info.access_type; size_t ref_idx = reference_info.idx; SgBasicBlock* containingBB = getEnclosingNode<SgBasicBlock>(ref_node); SgStatement* containingStmt = getEnclosingNode<SgStatement>(ref_node); SgLocatedNode* located_ref = reinterpret_cast<SgLocatedNode*>(ref_node); Sg_File_Info *fileInfo = Sg_File_Info::generateFileInfoForTransformationNode( located_ref->get_file_info()->get_filenameString()); int line_number = 0; SgStatement *stmt = getEnclosingNode<SgStatement>(ref_node); if (stmt) { line_number = stmt->get_file_info()->get_raw_line(); } SgPntrArrRefExp* pntr = isSgPntrArrRefExp(ref_node); ROSE_ASSERT(pntr); SgExpression *param_base = pntr->get_lhs_operand(); SgExpression* expr = isSgExpression(ref_node); ROSE_ASSERT(expr); // Strip unary operators like ++ or -- from the expression. SgExpression* stripped_expr = NULL; stripped_expr = ir_methods::strip_unary_operators(expr); ROSE_ASSERT(stripped_expr && "Bug in stripping unary operators " "from given expression!"); // If not Fortran, cast the address to a void pointer SgExpression *param_addr = SageInterface::is_Fortran_language() ? stripped_expr : buildCastExp( buildAddressOfOp(stripped_expr), buildPointerType(buildVoidType())); SgIntVal* param_line_number = new SgIntVal(fileInfo, line_number); SgIntVal* param_idx = new SgIntVal(fileInfo, ref_idx); SgIntVal* param_read_write = new SgIntVal(fileInfo, ref_access_type); param_line_number->set_endOfConstruct(fileInfo); param_idx->set_endOfConstruct(fileInfo); param_read_write->set_endOfConstruct(fileInfo); std::string function_name = SageInterface::is_Fortran_language() ? "indigo__gen_trace_f" : "indigo__gen_trace_c"; std::vector<SgExpression*> params; params.push_back(param_read_write); params.push_back(param_line_number); params.push_back(param_base); params.push_back(param_addr); params.push_back(param_idx); statement_info_t statement_info; statement_info.statement = ir_methods::prepare_call_statement( containingBB, function_name, params, containingStmt); statement_info.reference_statement = containingStmt; statement_info.before = true; statement_list.push_back(statement_info); } attr.skip = true; return attr; } const analysis_profile_t& tracer_t::get_analysis_profile() { return analysis_profile; } const statement_list_t::iterator tracer_t::stmt_begin() { return statement_list.begin(); } const statement_list_t::iterator tracer_t::stmt_end() { return statement_list.end(); }
31.980645
80
0.682469
[ "vector" ]
4b69f348da8c6a1d158364f1e66f40c543c6f9fa
12,857
cpp
C++
src/ukf.cpp
eoguzinci/unscented-kalman-filter
16e2528dd7bda4dc65f7ebdba07b9b1bdaa98b3f
[ "MIT" ]
null
null
null
src/ukf.cpp
eoguzinci/unscented-kalman-filter
16e2528dd7bda4dc65f7ebdba07b9b1bdaa98b3f
[ "MIT" ]
null
null
null
src/ukf.cpp
eoguzinci/unscented-kalman-filter
16e2528dd7bda4dc65f7ebdba07b9b1bdaa98b3f
[ "MIT" ]
null
null
null
#include "ukf.h" #include "Eigen/Dense" #include <iostream> #include "measurement_package.h" #include <fstream> using namespace std; using Eigen::MatrixXd; using Eigen::VectorXd; using std::vector; /** * Initializes Unscented Kalman filter * This is scaffolding, do not modify */ UKF::UKF() { // counter for metrics lid_count = 0; rad_count = 0; // if this is false, laser measurements will be ignored (except during init) use_laser_ = true; // if this is false, radar measurements will be ignored (except during init) use_radar_ = true; // initial state vector x_ = VectorXd(5); // initial covariance matrix P_ = MatrixXd(5, 5); /* PROCESS NOISE */ // Process noise standard deviation longitudinal acceleration in m/s^2 std_a_ = 3; // Process noise standard deviation yaw acceleration in rad/s^2 std_yawdd_ = 0.4; /* MEASUREMENT NOISE */ //DO NOT MODIFY measurement noise values below these are provided by the sensor manufacturer. // Laser measurement noise standard deviation position1 in m std_laspx_ = 0.15; // Laser measurement noise standard deviation position2 in m std_laspy_ = 0.15; // Radar measurement noise standard deviation radius in m std_radr_ = 0.3; // Radar measurement noise standard deviation angle in rad std_radphi_ = 0.03; // Radar measurement noise standard deviation radius change in m/s std_radrd_ = 0.3; //DO NOT MODIFY measurement noise values above these are provided by the sensor manufacturer. /** TODO: Complete the initialization. See ukf.h for other member properties. Hint: one or more values initialized above might be wildly off... */ // at the beginning, not initialized is_initialized_ = false; // time is 0.0 at the beginning time_us_ = 0.0; // State dimension is 5 for CTRV model [px py v psi dpsi].trasnpose() n_x_ = 5; //Augmented state is concat(state,[n_ddx n_ddpsi]) n_aug_ = 7; // width of sigma points lambda_ = 3- n_x_; // predicted sigma points Xsig_pred_ = MatrixXd(n_x_ , 2*n_aug_+1); // weights for sigma points weights_ = VectorXd(2*n_aug_+1); // NIS for laser NIS_laser_ = 0.0; // NIS for radar NIS_radar_ = 0.0; } UKF::~UKF() {} /** * @param {MeasurementPackage} meas_package The latest measurement data of * either radar or laser. */ void UKF::ProcessMeasurement(MeasurementPackage meas_package) { /** TODO: Complete this function! Make sure you switch between lidar and radar measurements. */ // check first if any sensor type is ignored, if yes do not count it if((meas_package.sensor_type_ == MeasurementPackage::RADAR && use_radar_) || (meas_package.sensor_type_ == MeasurementPackage::LASER && use_laser_)){ /* INITIALIZATION */ if(!is_initialized_){ x_.fill(0.0); P_.Identity(n_x_,n_x_); time_us_ = meas_package.timestamp_; if(meas_package.sensor_type_ == MeasurementPackage::LASER && use_laser_){ x_(0) = meas_package.raw_measurements_(0); x_(1) = meas_package.raw_measurements_(1); } else if (meas_package.sensor_type_ == MeasurementPackage::RADAR && use_radar_){ float ro = meas_package.raw_measurements_(0); float phi = meas_package.raw_measurements_(1); x_(0) = ro * cos(phi); x_(1) = ro * sin(phi); } weights_(0) = lambda_ / (lambda_+n_aug_); for (int i = 1; i < 2*n_aug_+1; ++i) { weights_(i) = 0.5/(lambda_+n_aug_); } // So, it is initialized and won't go throught this part again. is_initialized_ = true; return; } //compute the time elapsed between the current and previous measurements float dt = (meas_package.timestamp_ - time_us_) / 1000000.0; //dt - expressed in seconds time_us_ = meas_package.timestamp_; Prediction(dt); if (meas_package.sensor_type_ == MeasurementPackage::LASER) { UpdateLidar(meas_package); lid_count ++; } else if (meas_package.sensor_type_ == MeasurementPackage::RADAR) { UpdateRadar(meas_package); rad_count ++; } } } /** * Predicts sigma points, the state, and the state covariance matrix. * @param {double} delta_t the change in time (in seconds) between the last * measurement and this one. */ void UKF::Prediction(double delta_t) { /** TODO: Complete this function! Estimate the object's location. Modify the state vector, x_. Predict sigma points, the state, and the state covariance matrix. */ /* Generation of Sigma Points */ //create augmented mean vector VectorXd x_aug = VectorXd(n_aug_); //create augmented state covariance MatrixXd P_aug = MatrixXd(n_aug_, n_aug_); //create augmented sigma point matrix MatrixXd Xsig_aug = MatrixXd(n_aug_, 2 * n_aug_ + 1); //create augmented mean state x_aug.head(n_x_) = x_; x_aug(5) = 0; x_aug(6) = 0; cout << "PREDICTION STEP" << endl; cout<< "-------------" <<endl; //create augmented covariance matrix P_aug.fill(0.0); P_aug.topLeftCorner(n_x_,n_x_) = P_; P_aug(5,5) = std_a_*std_a_; P_aug(6,6) = std_yawdd_*std_yawdd_; //create square root matrix MatrixXd L = P_aug.llt().matrixL(); //create augmented sigma points Xsig_aug.col(0) = x_aug; for (int i = 0; i< n_aug_; i++){ Xsig_aug.col(i+1) = x_aug + sqrt(lambda_+n_aug_) * L.col(i); Xsig_aug.col(i+1+n_aug_) = x_aug - sqrt(lambda_+n_aug_) * L.col(i); } //create matrix with predicted sigma points as columns VectorXd Vsig(n_x_); VectorXd Asig(n_x_); // predict sigma points for (int i = 0; i < 2 * n_aug_ +1; ++i) { Xsig_pred_.col(i) = Xsig_aug.col(i).head(n_x_); Vsig.fill(0.0); if (fabs(Xsig_aug(4))<0.0001){ Vsig(0) = Xsig_aug(2,i)*cos(Xsig_aug(3,i))*delta_t; Vsig(1) = Xsig_aug(2,i)*sin(Xsig_aug(3,i))*delta_t; } else{ Vsig(0) = Xsig_aug(2,i)/Xsig_aug(4,i)*(sin(Xsig_aug(3,i)+Xsig_aug(4,i)*delta_t)-sin(Xsig_aug(3,i))); Vsig(1) = Xsig_aug(2,i)/Xsig_aug(4,i)*(-cos(Xsig_aug(3,i)+Xsig_aug(4,i)*delta_t)+cos(Xsig_aug(3,i))); Vsig(3) = Xsig_aug(4,i)*delta_t; } Xsig_pred_.col(i) += Vsig; Asig(0) = delta_t*delta_t*cos(Xsig_aug(3,i))*Xsig_aug(5,i)/2; Asig(1) = delta_t*delta_t*sin(Xsig_aug(3,i))*Xsig_aug(5,i)/2; Asig(2) = Xsig_aug(5,i)*delta_t; Asig(3) = delta_t*delta_t*Xsig_aug(6,i)/2; Asig(4) = delta_t*Xsig_aug(6,i); Xsig_pred_.col(i) += Asig; } // predicted state mean x_.fill(0.0); for (int i = 0; i < 2 * n_aug_ + 1; i++) { x_ += (weights_(i) * Xsig_pred_.col(i)); } //predicted state covariance matrix P_.fill(0.0); for (int i = 0; i < 2 * n_aug_ + 1; i++) { //iterate over sigma points // state difference VectorXd x_diff = Xsig_pred_.col(i) - x_; //angle normalization x_diff(3) = atan2(sin(x_diff(3)),cos(x_diff(3))); // while (x_diff(3)> M_PI) x_diff(3)-=2.*M_PI; // while (x_diff(3)<-M_PI) x_diff(3)+=2.*M_PI; P_ = P_ + weights_(i) * x_diff * x_diff.transpose() ; } } /** * Updates the state and the state covariance matrix using a laser measurement. * @param {MeasurementPackage} meas_package */ void UKF::UpdateLidar(MeasurementPackage meas_package) { /** TODO: Complete this function! Use lidar data to update the belief about the object's position. Modify the state vector, x_, and covariance, P_. You'll also need to calculate the lidar NIS. */ // store the lidar measurements VectorXd z = meas_package.raw_measurements_; //set measurement dimension, radar can measure px and py int n_z_ = 2; //create matrix for sigma points in measurement space MatrixXd Zsig = MatrixXd(n_z_, 2 * n_aug_ + 1); //mean predicted measurement VectorXd z_pred = VectorXd(n_z_); //measurement covariance matrix S MatrixXd S = MatrixXd(n_z_,n_z_); cout << "LASER UPDATE STEP" << endl; cout<< "-------------" <<endl; // radar measurement transformation for (int j = 0; j < 2*n_aug_+1; ++j) { double px = Xsig_pred_(0,j); double py = Xsig_pred_(1,j); Zsig(0,j) = px; Zsig(1,j) = py; } //mean predicted measurement z_pred.fill(0.0); for (int i = 0; i < 2 * n_aug_ + 1; i++) { z_pred += weights_(i) * Zsig.col(i); } S.fill(0.0); // MatrixXd Z_diff(n_z_,2*n_aug_+1); for (int i = 0; i < 2*n_aug_+1; ++i) { VectorXd z_diff = Zsig.col(i) - z_pred; // Z_diff.col(i) = z_diff; S = S + weights_(i) * z_diff * z_diff.transpose() ; } // add measurement noise covariance matrix MatrixXd R(n_z_,n_z_); R.fill(0.0); R(0,0) = std_laspx_*std_laspx_; R(1,1) = std_laspy_*std_laspy_; S += R; //create matrix for cross correlation Tc MatrixXd Tc = MatrixXd(n_x_, n_z_); Tc.fill(0.0); for (int i = 0; i < 2*n_aug_+1; ++i) { // state difference VectorXd x_diff = Xsig_pred_.col(i) - x_; // covariance difference // VectorXd z_diff = Z_diff.col(i); VectorXd z_diff = Zsig.col(i) - z_pred; //angle normalization x_diff(3) = atan2(sin(x_diff(3)),cos(x_diff(3))); Tc = Tc + weights_(i) * x_diff * z_diff.transpose() ; } //Kalman gain K; MatrixXd K = Tc * S.inverse(); //residual VectorXd z_diff = z - z_pred; //calculate NIS NIS_laser_ = z_diff.transpose() * S.inverse() * z_diff; cout << "NIS_laser" <<endl<< NIS_radar_ << endl; //update state mean and covariance matrix x_ = x_ + K * z_diff; P_ = P_ - K*S*K.transpose(); // // print the output // cout << "x_ = " << x_ << endl; // cout << "P_ = " << P_ << endl; } /** * Updates the state and the state covariance matrix using a radar measurement. * @param {MeasurementPackage} meas_package */ void UKF::UpdateRadar(MeasurementPackage meas_package) { /** TODO: Complete this function! Use radar data to update the belief about the object's position. Modify the state vector, x_, and covariance, P_. You'll also need to calculate the radar NIS. */ // store the radar measurements VectorXd z = meas_package.raw_measurements_; //set measurement dimension, radar can measure r, phi, and r_dot int n_z_ = 3; //create matrix for sigma points in measurement space MatrixXd Zsig = MatrixXd(n_z_, 2 * n_aug_ + 1); cout << "RADAR UPDATE STEP" << endl; cout<< "-------------" <<endl; // radar measurement transformation for (int j = 0; j < 2*n_aug_+1; ++j) { double px = Xsig_pred_(0,j); double py = Xsig_pred_(1,j); double v = Xsig_pred_(2,j); double psi = Xsig_pred_(3,j); Zsig(0,j) = sqrt(px*px+py*py); Zsig(1,j) = atan2(py,px); // prevent divide by 0 if (fabs(Zsig(0,j)) > 1e-4) { Zsig(2,j) = (px*cos(psi)*v + py*sin(psi)*v)/Zsig(0,j); }else{ Zsig(2,j) = 0.0; } } //mean predicted measurement VectorXd z_pred = VectorXd(n_z_); z_pred.fill(0.0); for (int i = 0; i < 2 * n_aug_ + 1; i++) { z_pred += weights_(i) * Zsig.col(i); } //measurement covariance matrix S MatrixXd S = MatrixXd(n_z_,n_z_); S.fill(0.0); // MatrixXd Z_diff(n_z_,2*n_aug_+1); for (int i = 0; i < 2*n_aug_+1; ++i) { VectorXd z_diff = Zsig.col(i) - z_pred; // while (z_diff(1)> M_PI) z_diff(1)-=2.*M_PI; // while (z_diff(1)<-M_PI) z_diff(1)+=2.*M_PI; z_diff(1) = atan2(sin(z_diff(1)),cos(z_diff(1))); // Z_diff.col(i) = z_diff; S = S + weights_(i) * z_diff * z_diff.transpose() ; } // add measurement noise covariance matrix MatrixXd R(n_z_,n_z_); R.fill(0.0); R(0,0) = std_radr_*std_radr_; R(1,1) = std_radphi_*std_radphi_; R(2,2) = std_radrd_*std_radrd_; S += R; //create matrix for cross correlation Tc MatrixXd Tc = MatrixXd(n_x_, n_z_); Tc.fill(0.0); for (int i = 0; i < 2*n_aug_+1; ++i) { // state difference VectorXd x_diff = Xsig_pred_.col(i) - x_; // covariance difference VectorXd z_diff = Zsig.col(i) - z_pred; // VectorXd z_diff = Z_diff.col(i); //angle normalization // while (x_diff(3)> M_PI) x_diff(3)-=2.*M_PI; // while (x_diff(3)<-M_PI) x_diff(3)+=2.*M_PI; // while (z_diff(1)> M_PI) z_diff(1)-=2.*M_PI; // while (z_diff(1)<-M_PI) z_diff(1)+=2.*M_PI; x_diff(3) = atan2(sin(x_diff(3)),cos(x_diff(3))); z_diff(1) = atan2(sin(z_diff(1)),cos(z_diff(1))); Tc = Tc + weights_(i) * x_diff * z_diff.transpose() ; } //Kalman gain K; MatrixXd K = Tc * S.inverse(); //residual VectorXd z_diff = z - z_pred; //angle normalization // while (z_diff(1)> M_PI) z_diff(1)-=2.*M_PI; // while (z_diff(1)<-M_PI) z_diff(1)+=2.*M_PI; z_diff(1) = atan2(sin(z_diff(1)),cos(z_diff(1))); //calculate NIS NIS_radar_ = z_diff.transpose() * S.inverse() * z_diff; cout << "NIS_radar" << endl << NIS_radar_ << endl; // state update x_ = x_ + K*z_diff; // covariance update P_ = P_ - K*S*K.transpose(); // // print the output // cout << "x_ = " << x_ << endl; // cout << "P_ = " << P_ << endl; }
27.413646
151
0.636774
[ "object", "vector", "model" ]
4b6bf92e426c5b4ae726797e815ccba87231649a
22,997
cc
C++
tensorflow/core/kernels/mkl_conv_grad_input_ops.cc
shengfuintel/tensorflow
e67f3af48c94c9456c3ff376dc30c82a4bf982cd
[ "Apache-2.0" ]
522
2016-06-08T02:15:50.000Z
2022-03-02T05:30:36.000Z
tensorflow/core/kernels/mkl_conv_grad_input_ops.cc
shengfuintel/tensorflow
e67f3af48c94c9456c3ff376dc30c82a4bf982cd
[ "Apache-2.0" ]
48
2016-07-26T00:11:55.000Z
2022-02-23T13:36:33.000Z
tensorflow/core/kernels/mkl_conv_grad_input_ops.cc
shengfuintel/tensorflow
e67f3af48c94c9456c3ff376dc30c82a4bf982cd
[ "Apache-2.0" ]
108
2016-06-16T15:34:05.000Z
2022-03-12T13:23:11.000Z
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ // See docs in ../ops/nn_ops.cc. This opkernel uses MKL library, create MKL // layout and primitives, use MKL dnn primitives to compute convolution backward // input #ifdef INTEL_MKL #define USE_EIGEN_TENSOR #define EIGEN_USE_THREADS #include <algorithm> #include <vector> #include "mkl_dnn.h" #include "mkl_dnn_types.h" #include "tensorflow/core/framework/numeric_op.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/register_types.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/framework/tensor_shape.h" #include "tensorflow/core/framework/tensor_slice.h" #include "tensorflow/core/kernels/conv_grad_ops.h" #include "tensorflow/core/kernels/mkl_conv_ops.h" #include "tensorflow/core/kernels/ops_util.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/lib/gtl/array_slice.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/macros.h" #include "tensorflow/core/util/mkl_util.h" #include "tensorflow/core/util/padding.h" #include "tensorflow/core/util/tensor_format.h" #include "tensorflow/core/util/use_cudnn.h" #include "tensorflow/core/util/work_sharder.h" #ifdef INTEL_MKL_DNN #include "mkldnn.hpp" using mkldnn::prop_kind; using mkldnn::stream; using mkldnn::convolution_backward_data; using mkldnn::convolution_direct; using mkldnn::convolution_forward; #endif namespace tensorflow { typedef Eigen::ThreadPoolDevice CPUDevice; #ifndef INTEL_MKL_DNN template <typename Device, class T> class MklConv2DCustomBackpropInputOp : public OpKernel { public: ~MklConv2DCustomBackpropInputOp() {} explicit MklConv2DCustomBackpropInputOp(OpKernelConstruction* context) : OpKernel(context) { string dataformat; OP_REQUIRES_OK(context, context->GetAttr("data_format", &dataformat)); OP_REQUIRES(context, FormatFromString(dataformat, &data_format), errors::InvalidArgument("Invalid data format")); OP_REQUIRES_OK(context, context->GetAttr("strides", &strides)); int stride_n = GetTensorDim(strides, data_format, 'N'); int stride_c = GetTensorDim(strides, data_format, 'C'); OP_REQUIRES( context, (stride_n == 1 && stride_c == 1), errors::InvalidArgument("Current implementation does not yet support " "strides in the batch and depth dimensions.")); OP_REQUIRES_OK(context, context->GetAttr("padding", &padding)); } void Compute(OpKernelContext* context) override { MklConvBackInputOpContext mkl_context; const Tensor& input = MklGetInput(context, 0); const Tensor& filter = MklGetInput(context, 1); GetMklShape(context, 1, &(mkl_context.filter_shape)); bool filter_in_mkl_format = mkl_context.filter_shape.IsMklTensor(); const Tensor& out_backprop = MklGetInput(context, 2); GetMklShape(context, 2, &(mkl_context.outback_shape)); bool outback_in_mkl_format = mkl_context.outback_shape.IsMklTensor(); TensorShape input_shape, filter_shape, outback_shape; // Generate input shape. OP_REQUIRES( context, TensorShapeUtils::IsVector(input.shape()), errors::InvalidArgument( "Conv2DBackpropInput: input_sizes input must be 1-dim, not ", input.dims())); OP_REQUIRES_OK( context, TensorShapeUtils::MakeShape(input.vec<int32>(), &input_shape)); // Generate shape for filter prop if input is in MKL format. if (filter_in_mkl_format) { OP_REQUIRES(context, mkl_context.filter_shape.GetDimension() == 4, errors::InvalidArgument( "Conv2DCustomBackpropInput: size must be 4-dim")); const int64* filter_sizes = (const int64*)mkl_context.filter_shape.GetSizes(); const int64 filter_dims = mkl_context.filter_shape.GetDimension(); OP_REQUIRES_OK(context, TensorShapeUtils::MakeShape( filter_sizes, filter_dims, &filter_shape)); } else { filter_shape = filter.shape(); } // Generate shape for outback prop if input is in MKL format. if (outback_in_mkl_format) { OP_REQUIRES(context, mkl_context.outback_shape.GetDimension() == 4, errors::InvalidArgument( "Conv2DCustomBackpropInput: size must be 4-dim")); MklSizesToTFSizes(context, data_format, mkl_context.outback_shape, &outback_shape); } else { outback_shape = out_backprop.shape(); } ConvBackpropDimensions dims; OP_REQUIRES_OK( context, ConvBackpropComputeDimensions( "Conv2DCustomBackpropInput", /*num_spatial_dims=*/2, input_shape, filter_shape, outback_shape, strides, padding, data_format, &dims)); int64 pad_top, pad_bottom; int64 pad_left, pad_right; OP_REQUIRES_OK( context, GetWindowedOutputSizeVerbose( dims.spatial_dims[0].input_size, dims.spatial_dims[0].filter_size, dims.spatial_dims[0].stride, padding, &dims.spatial_dims[0].output_size, &pad_top, &pad_bottom)); OP_REQUIRES_OK( context, GetWindowedOutputSizeVerbose( dims.spatial_dims[1].input_size, dims.spatial_dims[1].filter_size, dims.spatial_dims[1].stride, padding, &dims.spatial_dims[1].output_size, &pad_left, &pad_right)); mkl_context.in_dims = 4; mkl_context.in_sizes[0] = static_cast<size_t>(dims.spatial_dims[1].input_size); mkl_context.in_sizes[1] = static_cast<size_t>(dims.spatial_dims[0].input_size); mkl_context.in_sizes[2] = static_cast<size_t>(dims.in_depth); mkl_context.in_sizes[3] = static_cast<size_t>(dims.batch_size); mkl_context.out_sizes[0] = static_cast<size_t>(dims.spatial_dims[1].output_size); mkl_context.out_sizes[1] = static_cast<size_t>(dims.spatial_dims[0].output_size); mkl_context.out_sizes[2] = static_cast<size_t>(dims.out_depth); mkl_context.out_sizes[3] = static_cast<size_t>(dims.batch_size); mkl_context.input_offset[0] = static_cast<int>(-pad_left); mkl_context.input_offset[1] = static_cast<int>(-pad_top); mkl_context.conv_strides[0] = static_cast<size_t>(dims.spatial_dims[1].stride); mkl_context.conv_strides[1] = static_cast<size_t>(dims.spatial_dims[0].stride); GetStridesFromSizes(data_format, mkl_context.out_strides, mkl_context.out_sizes); GetStridesFromSizes(data_format, mkl_context.in_strides, mkl_context.in_sizes); mkl_context.filter_size[0] = dims.spatial_dims[1].filter_size; mkl_context.filter_size[1] = dims.spatial_dims[0].filter_size; mkl_context.filter_size[2] = dims.in_depth; mkl_context.filter_size[3] = dims.out_depth; mkl_context.filter_stride[0] = mkl_context.filter_size[2] * mkl_context.filter_size[3]; mkl_context.filter_stride[1] = mkl_context.filter_size[2] * mkl_context.filter_size[0] * mkl_context.filter_size[3]; mkl_context.filter_stride[2] = mkl_context.filter_size[3]; mkl_context.filter_stride[3] = 1; CHECK_EQ( dnnConvolutionCreateBackwardData_F32( &mkl_context.prim_bwddata, NULL, dnnAlgorithmConvolutionDirect, mkl_context.in_dims, mkl_context.in_sizes, mkl_context.out_sizes, mkl_context.filter_size, mkl_context.conv_strides, mkl_context.input_offset, dnnBorderZeros), E_SUCCESS); // Allocate output tensor and shape TensorShape mkl_out_shape; MklShape mklOutputShape; mklOutputShape.SetMklTensor(true); mklOutputShape.SetMklLayout(mkl_context.prim_bwddata, dnnResourceDiffSrc); mklOutputShape.SetTfLayout(mkl_context.in_dims, mkl_context.in_sizes, mkl_context.in_strides); // MKL might change the dimension ordering. // Create mapping to recover the original TF dimension order mklOutputShape.SetTfDimOrder(mkl_context.in_dims, data_format); Tensor* in_backprop = nullptr; mkl_out_shape.AddDim(dnnLayoutGetMemorySize_F32(static_cast<dnnLayout_t>( mklOutputShape.GetMklLayout())) / sizeof(T)); AllocateOutputSetMklShape(context, 0, &in_backprop, mkl_out_shape, mklOutputShape); mkl_context.conv_res[dnnResourceDiffSrc] = static_cast<void*>(const_cast<T*>(in_backprop->flat<T>().data())); mkl_context.MklCreateInputLayouts(context); Tensor mkl_tmp_outbackprop_buf_tensor, mkl_tmp_filter_buf_tensor; mkl_context.MklPrepareConvolutionInputs( context, &mkl_tmp_outbackprop_buf_tensor, &mkl_tmp_filter_buf_tensor); CHECK_EQ(dnnExecute_F32(mkl_context.prim_bwddata, mkl_context.conv_res), E_SUCCESS); mkl_context.MklCleanup(); } private: typedef struct { int in_dims; size_t in_sizes[4]; size_t in_strides[4]; size_t out_sizes[4]; size_t out_strides[4]; int input_offset[2]; size_t filter_size[4]; size_t filter_stride[4]; size_t conv_strides[2]; MklShape filter_shape, outback_shape; dnnPrimitive_t prim_bwddata; void* conv_res[dnnResourceNumber]; dnnLayout_t lt_filter, lt_outbackprop; // Create MKL dnnLayout_t objects for tensors coming into the layer void MklCreateInputLayouts(OpKernelContext* context) { bool filter_in_mkl_format = filter_shape.IsMklTensor(); bool outback_in_mkl_format = outback_shape.IsMklTensor(); if (filter_in_mkl_format) { lt_filter = (dnnLayout_t)filter_shape.GetCurLayout(); } else { CHECK_EQ(dnnLayoutCreate_F32(&lt_filter, in_dims, filter_size, filter_stride), E_SUCCESS); } if (outback_in_mkl_format) { lt_outbackprop = (dnnLayout_t)outback_shape.GetCurLayout(); } else { CHECK_EQ(dnnLayoutCreate_F32(&lt_outbackprop, in_dims, out_sizes, out_strides), E_SUCCESS); } } // Compare incoming input tensor layouts with MKL preferred layouts and // convert data to the preferred layout if necessary void MklPrepareConvolutionInputs(OpKernelContext* context, Tensor* mkl_tmp_outbackprop_buf_tensor, Tensor* mkl_tmp_filter_buf_tensor) { dnnPrimitive_t mkl_convert_filter = nullptr, mkl_convert_outbackprop = nullptr; void *mkl_filter_buf = nullptr, *mkl_outbackprop_buf = nullptr; dnnLayout_t mkl_lt_filter_internal = nullptr, mkl_lt_outbackprop_internal = nullptr; CHECK_EQ(dnnLayoutCreateFromPrimitive_F32( &mkl_lt_filter_internal, prim_bwddata, dnnResourceFilter), E_SUCCESS); const Tensor& filter = MklGetInput(context, 1); CHECK_EQ( dnnLayoutCreateFromPrimitive_F32(&mkl_lt_outbackprop_internal, prim_bwddata, dnnResourceDiffDst), E_SUCCESS); if (!dnnLayoutCompare_F32(mkl_lt_filter_internal, lt_filter)) { // Create conversion primitive CHECK_EQ(dnnConversionCreate_F32(&mkl_convert_filter, lt_filter, mkl_lt_filter_internal), E_SUCCESS); AllocTmpBuffer(context, mkl_tmp_filter_buf_tensor, mkl_lt_filter_internal, &mkl_filter_buf); CHECK_EQ( dnnConversionExecute_F32( mkl_convert_filter, static_cast<void*>(const_cast<T*>(filter.flat<T>().data())), mkl_filter_buf), E_SUCCESS); // Assign filter buf to resources[] for convolution. conv_res[dnnResourceFilter] = mkl_filter_buf; dnnDelete_F32(mkl_convert_filter); } else { // If we do not need any layout conversion for filter, then // we directly assign input filter to resources[]. conv_res[dnnResourceFilter] = static_cast<void*>(const_cast<T*>(filter.flat<T>().data())); } dnnLayoutDelete_F32(mkl_lt_filter_internal); const Tensor& out_backprop = MklGetInput(context, 2); // -- // We do similar steps as above for outputbackprop. if (!dnnLayoutCompare_F32(mkl_lt_outbackprop_internal, lt_outbackprop)) { CHECK_EQ( dnnConversionCreate_F32(&mkl_convert_outbackprop, lt_outbackprop, mkl_lt_outbackprop_internal), E_SUCCESS); AllocTmpBuffer(context, mkl_tmp_outbackprop_buf_tensor, mkl_lt_outbackprop_internal, &mkl_outbackprop_buf); CHECK_EQ(dnnConversionExecute_F32(mkl_convert_outbackprop, static_cast<void*>(const_cast<T*>( out_backprop.flat<T>().data())), mkl_outbackprop_buf), E_SUCCESS); conv_res[dnnResourceDiffDst] = mkl_outbackprop_buf; dnnDelete_F32(mkl_convert_outbackprop); } else { conv_res[dnnResourceDiffDst] = static_cast<void*>(const_cast<T*>(out_backprop.flat<T>().data())); } dnnLayoutDelete_F32(mkl_lt_outbackprop_internal); } // Cleanup member layouts and primitives void MklCleanup() { bool filter_in_mkl_format = filter_shape.IsMklTensor(); bool outback_in_mkl_format = outback_shape.IsMklTensor(); if (!filter_in_mkl_format) dnnLayoutDelete_F32(lt_filter); if (!outback_in_mkl_format) dnnLayoutDelete_F32(lt_outbackprop); dnnDelete_F32(prim_bwddata); } } MklConvBackInputOpContext; std::vector<int32> strides; Padding padding; TensorFormat data_format; }; #else template <typename Device, class T> class MklConv2DCustomBackpropInputOp : public OpKernel { public: ~MklConv2DCustomBackpropInputOp() {} explicit MklConv2DCustomBackpropInputOp(OpKernelConstruction* context) : OpKernel(context) { string data_format_str; OP_REQUIRES_OK(context, context->GetAttr("data_format", &data_format_str)); OP_REQUIRES(context, FormatFromString(data_format_str, &data_format_), errors::InvalidArgument("Invalid data format")); OP_REQUIRES_OK(context, context->GetAttr("strides", &strides_)); int stride_n = GetTensorDim(strides_, data_format_, 'N'); int stride_c = GetTensorDim(strides_, data_format_, 'C'); OP_REQUIRES( context, (stride_n == 1 && stride_c == 1), errors::InvalidArgument("Current implementation does not yet support " "strides in the batch and depth dimensions.")); OP_REQUIRES_OK(context, context->GetAttr("padding", &padding_)); } void Compute(OpKernelContext* context) override { try { auto cpu_engine = engine(engine::cpu, 0); MklDnnData<T> filter(&cpu_engine); MklDnnData<T> outbackprop(&cpu_engine); MklDnnData<T> output(&cpu_engine); // Input tensors const Tensor& input_tensor = MklGetInput(context, 0); const Tensor& filter_tensor = MklGetInput(context, 1); const Tensor& obp_tensor = MklGetInput(context, 2); // Outbackprop // Generate input shape. TensorShape input_shape; OP_REQUIRES( context, TensorShapeUtils::IsVector(input_tensor.shape()), errors::InvalidArgument( "Conv2DBackpropInput: input_sizes input must be 1-dim, not ", input_tensor.dims())); OP_REQUIRES_OK(context, TensorShapeUtils::MakeShape( input_tensor.vec<int32>(), &input_shape)); TensorShape filter_shape = filter_tensor.shape(); TensorShape obp_shape = obp_tensor.shape(); // By default, all dims are in MKL order. Only dims in TF order // are those with prefix tf_order. memory::dims obp_dims, fwd_input_dims, fwd_filter_dims; memory::dims padding_l, padding_r, strides, fwd_output_dims; memory::dims fwd_output_dims_tf_order; // Get forward convolution parameters. MklDnnConvUtil conv_utl(context, strides_, padding_, data_format_); conv_utl.GetConvFwdSizesInMklOrder( input_shape, filter_shape, &fwd_input_dims, &fwd_filter_dims, &strides, &fwd_output_dims_tf_order, &fwd_output_dims, &padding_l, &padding_r); if (!context->status().ok()) return; // Create Convolution forward descriptor since Convolution backward // API needs it. For that, we first need to create input, filter // and output memory descriptors. auto mkl_data_format = TFDataFormatToMklDnnDataFormat(data_format_); auto fwd_src_md = memory::desc(fwd_input_dims, MklDnnType<T>(), mkl_data_format); auto fwd_filter_md = memory::desc(fwd_filter_dims, MklDnnType<T>(), memory::format::hwio); auto fwd_out_md = memory::desc(fwd_output_dims, MklDnnType<T>(), mkl_data_format); auto fwd_desc = convolution_forward::desc( prop_kind::forward, convolution_direct, fwd_src_md, fwd_filter_md, fwd_out_md, strides, padding_l, padding_r, TFPaddingToMklDnnPadding(padding_)); auto fwd_pd = convolution_forward::primitive_desc(fwd_desc, cpu_engine); // Allocate output tensor and shape // TODO(nhasabni): Update this when support for MKL layout is added. // Shape of output of Conv2DBackpropInput is same as 'input' of Conv2D. TensorShape tf_output_shape(input_shape); MklShape mkl_output_mkl_shape; mkl_output_mkl_shape.SetMklTensor(false); Tensor* output_tensor = nullptr; AllocateOutputSetMklShape(context, 0, &output_tensor, tf_output_shape, mkl_output_mkl_shape); // Create memory for user data. // Describe how the inputs and outputs of Convolution look like. Also // specify buffers containing actual input and output data. // Although input shape required is in MKL-DNN order, the layout is // Tensorflow's layout (NHWC or NCHW depending on data format). // Although filter shape (filter_dims) required is in MKL-DNN order, // the layout is Tensorflow's layout (HWIO). // Shape of Conv2DBackpropInput's filter is same as that of Conv2D filter. filter.SetUsrMem(fwd_filter_dims, memory::format::hwio, &filter_tensor); // Outbackprop shape is NHWC or NCHW depending on data format. Since // GetInputSizeInMklOrder function returns size in that order we just use // use that function directly. conv_utl.GetInputSizeInMklOrder(obp_shape, &obp_dims); if (!context->status().ok()) return; outbackprop.SetUsrMem(obp_dims, mkl_data_format, &obp_tensor); // Although output shape required is in MKL-DNN order, // layout is Tensorflow's layout (NHWC or NCHW depending on data format). // Shape of output of Conv2DBackpropInput is same as shape of 'input' // of Conv2D. memory::dims bwd_output_dims = fwd_input_dims; output.SetUsrMem(bwd_output_dims, mkl_data_format, output_tensor); // Create memory descriptors for convolution data w/ no specified format. filter.SetOpMemDesc(fwd_filter_dims, memory::format::any); outbackprop.SetOpMemDesc(obp_dims, memory::format::any); output.SetOpMemDesc(bwd_output_dims, memory::format::any); // Create convolution backward data primitive. auto bwd_desc = convolution_backward_data::desc( convolution_direct, output.GetOpMemDesc(), filter.GetOpMemDesc(), outbackprop.GetOpMemDesc(), strides, padding_l, padding_r, TFPaddingToMklDnnPadding(padding_)); auto bwd_pd = convolution_backward_data::primitive_desc( bwd_desc, cpu_engine, fwd_pd); PrepareAndExecutePrimitive(bwd_pd, &filter, &outbackprop, &output); } catch (mkldnn::error& e) { string error_msg = "Status: " + std::to_string(e.status) + ", message: " + string(e.message) + ", in file " + string(__FILE__) + ":" + std::to_string(__LINE__); OP_REQUIRES_OK( context, errors::Aborted("Operation received an exception:", error_msg)); } } private: std::vector<int32> strides_; Padding padding_; TensorFormat data_format_; // Prepare and execute net - checks for input and output reorders. void PrepareAndExecutePrimitive( const convolution_backward_data::primitive_desc& conv_pd, MklDnnData<T>* filter, MklDnnData<T>* obp, MklDnnData<T>* output) { // Create reorders between user layout and MKL layout if it is needed and // add it to the net before convolution. std::vector<primitive> net; filter->CheckReorderToOpMem(conv_pd.weights_primitive_desc(), &net); obp->CheckReorderToOpMem(conv_pd.diff_dst_primitive_desc(), &net); // Memory for output of convolution. Since we may need reorder on the // output side, we will prepare reorder primitive in case output // reorder to user memory is required. bool output_reorder_required = output->PrepareReorderToUserMemIfReq(conv_pd.diff_src_primitive_desc()); net.push_back(convolution_backward_data( conv_pd, obp->GetOpMem(), filter->GetOpMem(), output->GetOpMem())); // Insert reorder primitive in the net for output reorder if reorder is // required. if (output_reorder_required) { output->InsertReorderToUserMem(&net); } // Handle output reorder stream(stream::kind::eager).submit(net).wait(); } }; #endif // INTEL_MKL_DNN #define REGISTER_MKL_CPU_KERNELS(T) \ REGISTER_KERNEL_BUILDER(Name("_MklConv2DBackpropInput") \ .Device(DEVICE_CPU) \ .TypeConstraint<T>("T") \ .Label(mkl_op_registry::kMklOpLabel), \ MklConv2DCustomBackpropInputOp<CPUDevice, T>); TF_CALL_float(REGISTER_MKL_CPU_KERNELS); #undef REGISTER_MKL_CPU_KERNELS } // namespace tensorflow #endif // INTEL_MKL
42.119048
80
0.677306
[ "shape", "vector" ]
4b6efd7c34ef5c2a1bb0986401c3645a2de8c470
3,562
cpp
C++
src/nighthaunt/TombBanshee.cpp
rweyrauch/AoSSimulator
d2bfbbe0fab904cc543f1a01e62e0b82cf67c27b
[ "MIT" ]
5
2019-02-01T01:41:19.000Z
2021-06-17T02:16:13.000Z
src/nighthaunt/TombBanshee.cpp
rweyrauch/AoSSimulator
d2bfbbe0fab904cc543f1a01e62e0b82cf67c27b
[ "MIT" ]
2
2020-01-14T16:57:42.000Z
2021-04-01T00:53:18.000Z
src/nighthaunt/TombBanshee.cpp
rweyrauch/AoSSimulator
d2bfbbe0fab904cc543f1a01e62e0b82cf67c27b
[ "MIT" ]
1
2019-03-02T20:03:51.000Z
2019-03-02T20:03:51.000Z
/* * Warhammer Age of Sigmar battle simulator. * * Copyright (C) 2019 by Rick Weyrauch - rpweyrauch@gmail.com * * This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) */ #include <UnitFactory.h> #include <Board.h> #include "nighthaunt/TombBanshee.h" #include "NighthauntPrivate.h" namespace Nighthaunt { static const int g_basesize = 25; static const int g_pointsPerUnit = 80; static const int g_wounds = 4; bool TombBanshee::s_registered = false; Unit *TombBanshee::Create(const ParameterList &parameters) { auto procession = (Procession) GetEnumParam("Procession", parameters, g_processions[0]); auto trait = (CommandTrait) GetEnumParam("Command Trait", parameters, g_commandTraits[0]); auto artefact = (Artefact) GetEnumParam("Artefact", parameters, g_artefacts[0]); auto general = GetBoolParam("General", parameters, false); return new TombBanshee(procession, trait, artefact, general); } void TombBanshee::Init() { if (!s_registered) { static FactoryMethod factoryMethod = { TombBanshee::Create, Nighthaunt::ValueToString, Nighthaunt::EnumStringToInt, TombBanshee::ComputePoints, { EnumParameter("Procession", g_processions[0], g_processions), EnumParameter("Command Trait", g_commandTraits[0], g_commandTraits), EnumParameter("Artefact", g_artefacts[0], g_artefacts), BoolParameter("General") }, DEATH, {NIGHTHAUNT} }; s_registered = UnitFactory::Register("Tomb Banshee", factoryMethod); } } TombBanshee::TombBanshee(Procession procession, CommandTrait trait, Artefact artefact, bool isGeneral) : Nighthaunt(procession, "Tomb Banshee", 6, g_wounds, 10, 4, true, g_pointsPerUnit), m_dagger(Weapon::Type::Melee, "Chill Dagger", 1, 1, 4, 3, -2, RAND_D3) { m_keywords = {DEATH, MALIGNANT, NIGHTHAUNT, HERO, TOMB_BANSHEE}; m_weapons = {&m_dagger}; m_battleFieldRole = Role::Leader; setCommandTrait(trait); setArtefact(artefact); setGeneral(isGeneral); auto model = new Model(g_basesize, wounds()); model->addMeleeWeapon(&m_dagger); addModel(model); } Wounds TombBanshee::weaponDamage(const Model* attackingModel, const Weapon *weapon, const Unit *target, int hitRoll, int woundRoll) const { // Frightful Touch if ((hitRoll == 6) && (weapon->name() == m_dagger.name())) { return {0, Dice::RollD3()}; } return Nighthaunt::weaponDamage(attackingModel, weapon, target, hitRoll, woundRoll); } void TombBanshee::onStartShooting(PlayerId player) { Nighthaunt::onStartShooting(player); // Ghostly Howl if (player == owningPlayer()) { auto units = Board::Instance()->getUnitsWithin(this, GetEnemyId(owningPlayer()), 10.0); if (!units.empty()) { const auto roll = Dice::Roll2D6(); if (roll > units[0]->bravery()) { units[0]->applyDamage({0, units[0]->bravery() - roll}, this); } } } } int TombBanshee::ComputePoints(const ParameterList& /*parameters*/) { return g_pointsPerUnit; } } // namespace Nighthaunt
38.717391
143
0.59854
[ "model" ]
4b7500488937b8d2f6427b031fb01b71e9f74001
5,967
hpp
C++
MyApplication/Middlewares/ST/touchgfx/framework/include/touchgfx/widgets/VideoWidget.hpp
rshane960/TouchGFX
1f1465f1aa1215d52264ae0199dafa821939de64
[ "MIT" ]
null
null
null
MyApplication/Middlewares/ST/touchgfx/framework/include/touchgfx/widgets/VideoWidget.hpp
rshane960/TouchGFX
1f1465f1aa1215d52264ae0199dafa821939de64
[ "MIT" ]
null
null
null
MyApplication/Middlewares/ST/touchgfx/framework/include/touchgfx/widgets/VideoWidget.hpp
rshane960/TouchGFX
1f1465f1aa1215d52264ae0199dafa821939de64
[ "MIT" ]
null
null
null
/****************************************************************************** * Copyright (c) 2018(-2021) STMicroelectronics. * All rights reserved. * * This file is part of the TouchGFX 4.18.1 distribution. * * This software is licensed under terms that can be found in the LICENSE file in * the root directory of this software component. * If no LICENSE file comes with this software, it is provided AS-IS. * *******************************************************************************/ /** * @file touchgfx/widgets/VideoWidget.hpp * * Declares the touchgfx::VideoWidget class. */ #ifndef TOUCHGFX_VIDEOWIDGET_HPP #define TOUCHGFX_VIDEOWIDGET_HPP #include <touchgfx/hal/Types.hpp> #include <touchgfx/Bitmap.hpp> #include <touchgfx/Callback.hpp> #include <touchgfx/hal/VideoController.hpp> #include <touchgfx/widgets/Widget.hpp> namespace touchgfx { class VideoWidget; /** * A Widget for displaying video. * * The Widget interacts with a VideoController instance. * * @see VideoController */ class VideoWidget : public Widget { public: /** Default constructor. */ VideoWidget(); /** Destructor. Unregisters the Widget from the Controller. */ ~VideoWidget(); /** Play the video. */ void play(); /** Pause the video. */ void pause(); /** Stop the video. */ void stop(); /** * Check if the video is playing (not paused or stopped). * * @return Returns true if the video is playing. */ bool isPlaying(); /** * Set repeat mode. When set the video is restarted when the end is reached. * * @param repeat When true, the video is repeated. */ void setRepeat(bool repeat); /** * Seek to specific frame. Frame number 1 is the first frame. * The display is not updated updated unless the video is playing. * * @param frameNumber The frame number to seek to. */ void seek(uint32_t frameNumber); /** * Get the current frame number. * * @return Returns the current frame number. */ uint32_t getCurrentFrameNumber(); /** * Associates an action to be performed when the movie has ended. If the video is set to repeat, * the action is also triggered when the animation starts over. * * @param callback The callback is executed when done. The callback is given the VideoWidget. */ void setMovieEndedAction(GenericCallback<const VideoWidget&>& callback) { movieEndedAction = &callback; } /** * Clears the movie ended action previously set by setMovieEndedAction. * * @see setMovieEndedAction */ void clearMovieEndedAction() { movieEndedAction = 0; } /** * Sets the frame rate of the video. * * To get 20 video frames pr second on a 60 fps display use video_frames = 20 and ui_frames = 60. * * @param ui_frames Number of UI frames (divider) * @param video_frames Number of video_frames (dividend) */ void setFrameRate(uint32_t ui_frames, uint32_t video_frames); /** * Set the video data for the stream. * The video is paused and set to start on the first frame. * * @param movie Pointer to the video data. * @param length Length of the vide data. */ void setVideoData(const uint8_t* movie, const uint32_t length); /** * Set the video data for the stream. * The video is paused and set to start on the first frame. * * @param [in,out] reader Reference to a VideoDataReader object. */ void setVideoData(VideoDataReader& reader); /** * Get Video information. * * Get information from the video data. * * @param [in,out] data Pointer to VideoInformation where information should be stored. */ void getVideoInformation(VideoInformation* data); /** * Set video buffer data. * Only used when video frames are decoded to a buffer and not directly to the framebuffer. * * @param [in] videoBuffer Video buffer. */ void setVideoBuffer(uint8_t* const videoBuffer) { buffer = videoBuffer; } /** * Set video buffer format. * Only used when video frames are decoded to a buffer and not directly to the framebuffer. * * @param bufferFormat Format of the videoBuffer (RGB565 or RGB888) * @param width Width of the videoBuffer in pixels * @param height Height of the videoBuffer in pixels */ void setVideoBufferFormat(Bitmap::BitmapFormat bufferFormat, uint16_t width, uint16_t height) { format = bufferFormat; bufferWidth = width; bufferHeight = height; } virtual void handleTickEvent(); virtual void draw(const Rect& invalidatedArea) const; virtual Rect getSolidRect() const; private: /** * Reads information from the video. Sets the video width and height. * Sets the framerate to speed specified in movie. Assumes 60 ui * frame pr. second. */ void readVideoInformation(); VideoController::Handle handle; ///< The handle of this video stream GenericCallback<const VideoWidget&>* movieEndedAction; ///< Pointer to the callback to be executed when the video is done. uint8_t* buffer; ///< The buffer where the pixels are copied from Bitmap::BitmapFormat format; ///< The pixel format for the data. uint16_t bufferWidth; ///< Width (stride) of buffer in pixels (when used) uint16_t bufferHeight; ///< Height of buffer in pixels (when used) uint16_t videoWidth; ///< Width of video in pixels uint16_t videoHeight; ///< Height of video in pixels }; } // namespace touchgfx #endif // TOUCHGFX_VIDEOWIDGET_HPP
30.6
126
0.617396
[ "object" ]
4b7f538e18aa7295d00263fdc235e1e0665a370e
5,318
cpp
C++
src/graph.cpp
pickerxxr/block_greedy
db499b3d80ea43727584b8ab1f9e757ad1d940eb
[ "MIT" ]
11
2021-05-11T08:23:19.000Z
2022-03-23T18:39:46.000Z
src/graph.cpp
pickerxxr/block_greedy
db499b3d80ea43727584b8ab1f9e757ad1d940eb
[ "MIT" ]
1
2021-12-07T09:23:37.000Z
2021-12-07T13:55:14.000Z
src/graph.cpp
pickerxxr/block_greedy
db499b3d80ea43727584b8ab1f9e757ad1d940eb
[ "MIT" ]
2
2021-05-09T02:49:29.000Z
2021-06-15T11:35:04.000Z
#include "graph.hpp" #include "conversions.hpp" #include <iostream> #include <fstream> #include "util.hpp" // returns number of h2h edges size_t mem_graph_t::stream_build(std::ifstream &fin, size_t num_edges, dense_bitset &is_high_degree, dense_bitset &has_high_degree_neighbor, std::vector<size_t> &count, bool write_low_degree_edgelist){ size_t num_all_edges = num_edges; fin.seekg(sizeof(num_vertices) + sizeof(num_edges), std::ios::beg); neighbors = (vid_t *)realloc(neighbors, sizeof(vid_t) * num_edges * 2); // store 2 vids for each edge CHECK(neighbors) << "allocation failed!"; LOG(INFO) << "stream builder starts..."; std::vector<vid_t> offsets(num_vertices, 0); // to put the in-neighbors at the right position when building the column array nedges = num_edges; // num_edges, num_vertices double average_degree = (num_edges * 2.0) / (double)num_vertices; // non-rounded average degree high_degree_threshold = average_degree * high_degree_factor; // this is the th, if exceeded, the node is ignored for csr LOG(INFO) << "Average degree: " << average_degree << std::endl; LOG(INFO) << "High degree threshold: " << high_degree_threshold << std::endl; std::vector<edge_t> tmp_edges; // temporary buffer to read edges from file size_t chunk_size; if (num_edges >= 100000){ chunk_size = 100000; // batch read of so many edges } else { chunk_size = num_edges; } tmp_edges.resize(chunk_size); while (num_edges > 0){ // edges to be read fin.read((char *)&tmp_edges[0], sizeof(edge_t) * chunk_size); for (size_t i = 0; i < chunk_size; i++){ count[tmp_edges[i].first]++; count[tmp_edges[i].second]++; offsets[tmp_edges[i].first]++; } num_edges -= chunk_size; if (num_edges < chunk_size){ // adapt chunk size for last batch read chunk_size = num_edges; } } // now, counts are complete. counts are the degrees of the vertices. /************************ * build the index array * ********************** */ vid_t h_count = 0; // how many high degree vertices are found vdata[0] = mem_adjlist_t(neighbors); if (count[0] > high_degree_threshold){ is_high_degree.set_bit_unsync(0); h_count++; } std::vector<size_t> index(num_vertices, 0); // for index array for (vid_t v = 1; v < num_vertices; v++) { // we ignore the counts of vertices that have a high degree; we also ignore them when building the column array if (count[v-1] <= high_degree_threshold){ index[v] = index[v-1] + count[v-1]; } else{ index[v] = index[v-1]; // ignoring v-1, will not use it in CSR } // set the index array vdata[v] = mem_adjlist_t( neighbors + index[v]); if (count[v] > high_degree_threshold){ is_high_degree.set_bit_unsync(v); h_count++; } } LOG(INFO) << "Number of vertices with high degree " << h_count << std::endl; std::streampos pos(0); h2h_file.seekp(pos); std::streampos pos_low(0); low_degree_file.seekp(pos_low); low_degree_file.write((char *)&num_vertices, sizeof(num_vertices)); low_degree_file.write((char *)&num_edges, sizeof(num_edges)); /**************************** * build the column array * ************************** */ num_edges = nedges; //resizing the chunk size if (num_edges >= 100000){ chunk_size = 100000; // batch read of so many edges } else { chunk_size = num_edges; } fin.seekg(sizeof(num_vertices) + sizeof(num_edges), std::ios::beg); // start read from beginning size_t savings = 0; while (num_edges > 0){ // edges to be read fin.read((char *)&tmp_edges[0], sizeof(edge_t) * chunk_size); for (size_t i = 0; i < chunk_size; i++){ vid_t u = tmp_edges[i].first; vid_t v = tmp_edges[i].second; // we do not build column array for high degree vertices bool low_degree = false; // needed in case we write a low_degree edge list out to file if (count[u] <= high_degree_threshold){ vdata[u].push_back_out(v); low_degree = true; } else{ has_high_degree_neighbor.set_bit_unsync(v); savings++; } if (count[v] <= high_degree_threshold){ vdata[v].push_back_in(u, offsets[v]); low_degree = true; } else{ has_high_degree_neighbor.set_bit_unsync(u); savings++; if (count[u] > high_degree_threshold){ // u AND v are both high degree vertices, treat the edge specially edge_t edge = edge_t(u,v); h2h_file.write((char*)&edge, sizeof(edge_t)); num_h2h_edges++; } } if (write_low_degree_edgelist && low_degree){ edge_t edge = edge_t(u,v); low_degree_file.write((char*)&edge, sizeof(edge_t)); } } num_edges -= chunk_size; if (num_edges < chunk_size){ // adapt chunk size for last batch read chunk_size = num_edges; } } LOG(INFO) << "Edges to a high-degree vertex: " << savings << std::endl; LOG(INFO) << "Edges between two high-degree vertices: " << num_h2h_edges << std::endl; // write the number of vertices and number of low-degree edges to the low-file size_t num_low_edges = num_all_edges - num_h2h_edges; low_degree_file.seekp(pos_low); low_degree_file.write((char *)&num_vertices, sizeof(num_vertices)); low_degree_file.write((char *)&num_low_edges, sizeof(num_edges)); return num_h2h_edges; }
32.82716
201
0.656826
[ "vector" ]
4b8689b82279636ca673577aba3756b074ab514c
54
cc
C++
geometry/render/render_label_class.cc
RobotLocomotion/drake-python3.7
ae397a4c6985262d23e9675b9bf3927c08d027f5
[ "BSD-3-Clause" ]
2
2021-02-25T02:01:02.000Z
2021-03-17T04:52:04.000Z
geometry/render/render_label_class.cc
RobotLocomotion/drake-python3.7
ae397a4c6985262d23e9675b9bf3927c08d027f5
[ "BSD-3-Clause" ]
null
null
null
geometry/render/render_label_class.cc
RobotLocomotion/drake-python3.7
ae397a4c6985262d23e9675b9bf3927c08d027f5
[ "BSD-3-Clause" ]
1
2021-06-13T12:05:39.000Z
2021-06-13T12:05:39.000Z
#include "drake/geometry/render/render_label_class.h"
27
53
0.833333
[ "geometry", "render" ]
4ba23bab8f56d0bb541f0fe6b6d65669e16b7bde
3,331
hpp
C++
cpp/subprojects/common/include/common/rule_induction/rule_induction.hpp
Waguy02/Boomer-Scripted
b06bb9213d64dca0c05d41701dea12666931618c
[ "MIT" ]
8
2020-06-30T01:06:43.000Z
2022-03-14T01:58:29.000Z
cpp/subprojects/common/include/common/rule_induction/rule_induction.hpp
Waguy02/Boomer-Scripted
b06bb9213d64dca0c05d41701dea12666931618c
[ "MIT" ]
3
2020-12-14T11:30:18.000Z
2022-02-07T06:31:51.000Z
cpp/subprojects/common/include/common/rule_induction/rule_induction.hpp
Waguy02/Boomer-Scripted
b06bb9213d64dca0c05d41701dea12666931618c
[ "MIT" ]
4
2020-06-24T08:45:00.000Z
2021-12-23T21:44:51.000Z
/* * @author Michael Rapp (michael.rapp.ml@gmail.com) */ #pragma once #include "common/model/model_builder.hpp" #include "common/post_processing/post_processor.hpp" #include "common/pruning/pruning.hpp" #include "common/sampling/feature_sampling.hpp" #include "common/sampling/weight_vector.hpp" #include "common/sampling/partition.hpp" #include "common/statistics/statistics.hpp" #include "common/thresholds/thresholds.hpp" /** * Defines an interface for all classes that implement an algorithm for inducing individual rules. */ class IRuleInduction { public: virtual ~IRuleInduction() { }; /** * Induces the default rule. * * @param statistics A reference to an object of type `IStatistics` that provides access to the statistics * which should serve as the basis for inducing the default rule * @param modelBuilder A reference to an object of type `IModelBuilder`, the default rule should be added to */ virtual void induceDefaultRule(IStatistics& statistics, IModelBuilder& modelBuilder) const = 0; /** * Induces a new rule. * * @param thresholds A reference to an object of type `IThresholds` that provides access to the * thresholds that may be used by the conditions of the rule * @param labelIndices A reference to an object of type `IIndexVector` that provides access to the indices * of the labels for which the rule may predict * @param weights A reference to an object of type `IWeightVector` that provides access to the weights * of individual training examples * @param partition A reference to an object of type `IPartition` that provides access to the indices of * the training examples that belong to the training set and the holdout set, * respectively * @param featureSampling A reference to an object of type `IFeatureSampling` that should be used for sampling * the features that may be used by a new condition * @param pruning A reference to an object of type `IPruning` that should be used to prune the rule * @param postProcessor A reference to an object of type `IPostProcessor` that should be used to * post-process the predictions of the rule * @param rng A reference to an object of type `RNG` that implements the random number generator * to be used * @param modelBuilder A reference to an object of type `IModelBuilder`, the rule should be added to * @return True, if a rule has been induced, false otherwise */ virtual bool induceRule(IThresholds& thresholds, const IIndexVector& labelIndices, const IWeightVector& weights, IPartition& partition, IFeatureSampling& featureSampling, const IPruning& pruning, const IPostProcessor& postProcessor, RNG& rng, IModelBuilder& modelBuilder) const = 0; };
52.873016
120
0.619934
[ "object", "model" ]
4ba3149c48728a935308aa18dd19e79a9234ca30
6,515
cc
C++
chrome/browser/metrics/perf/metric_provider.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/metrics/perf/metric_provider.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/metrics/perf/metric_provider.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2021-01-05T23:43:46.000Z
2021-01-07T23:36:34.000Z
// Copyright 2019 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/metrics/perf/metric_provider.h" #include "base/bind.h" #include "base/metrics/histogram_functions.h" #include "base/task/post_task.h" #include "base/task/task_traits.h" #include "base/task/thread_pool.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "third_party/metrics_proto/sampled_profile.pb.h" namespace metrics { namespace { // Name prefix of the histogram that counts the number of reports uploaded by a // metric provider. const char kUploadCountHistogramPrefix[] = "ChromeOS.CWP.Upload"; // An upper bound on the count of reports expected to be uploaded by an UMA // callback. const int kMaxValueUploadReports = 10; } // namespace using MetricCollector = internal::MetricCollector; MetricProvider::MetricProvider(std::unique_ptr<MetricCollector> collector) : upload_uma_histogram_(std::string(kUploadCountHistogramPrefix) + collector->ToolName()), // Run the collector at a higher priority to enable fast triggering of // profile collections. In particular, we want fast triggering when // jankiness is detected, but even random based periodic collection // benefits from a higher priority, to avoid biasing the collection to // times when the system is not busy. The work performed on the dedicated // sequence is short and infrequent. Expensive parsing operations are // executed asynchronously on the thread pool. collector_task_runner_(base::ThreadPool::CreateSequencedTaskRunner( {base::TaskPriority::USER_VISIBLE})), metric_collector_(std::move(collector)), weak_factory_(this) { metric_collector_->set_profile_done_callback(base::BindRepeating( &MetricProvider::OnProfileDone, weak_factory_.GetWeakPtr())); } MetricProvider::~MetricProvider() { // Destroy the metric_collector_ on the collector sequence. collector_task_runner_->PostTask( FROM_HERE, base::BindOnce([](std::unique_ptr<MetricCollector> collector_) {}, std::move(metric_collector_))); } void MetricProvider::Init() { // It is safe to use base::Unretained to post tasks to the metric_collector_ // on the collector sequence, since we control its lifetime. Any tasks // posted to it are bound to run before we destroy it on the collector // sequence. collector_task_runner_->PostTask( FROM_HERE, base::BindOnce(&MetricCollector::Init, base::Unretained(metric_collector_.get()))); } bool MetricProvider::GetSampledProfiles( std::vector<SampledProfile>* sampled_profiles) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (cached_profile_data_.empty()) { base::UmaHistogramExactLinear(upload_uma_histogram_, 0, kMaxValueUploadReports); return false; } base::UmaHistogramExactLinear(upload_uma_histogram_, cached_profile_data_.size(), kMaxValueUploadReports); sampled_profiles->insert( sampled_profiles->end(), std::make_move_iterator(cached_profile_data_.begin()), std::make_move_iterator(cached_profile_data_.end())); collector_task_runner_->PostTask( FROM_HERE, base::BindOnce(&MetricCollector::ResetCachedDataSize, base::Unretained(metric_collector_.get()))); cached_profile_data_.clear(); return true; } void MetricProvider::OnUserLoggedIn() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); const base::TimeTicks now = base::TimeTicks::Now(); collector_task_runner_->PostTask( FROM_HERE, base::BindOnce(&MetricCollector::RecordUserLogin, base::Unretained(metric_collector_.get()), now)); } void MetricProvider::Deactivate() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); // Notifies the collector to turn off the timer. Does not delete any data that // was already collected and stored in |cached_profile_data|. collector_task_runner_->PostTask( FROM_HERE, base::BindOnce(&MetricCollector::StopTimer, base::Unretained(metric_collector_.get()))); } void MetricProvider::SuspendDone(base::TimeDelta sleep_duration) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); collector_task_runner_->PostTask( FROM_HERE, base::BindOnce(&MetricCollector::ScheduleSuspendDoneCollection, base::Unretained(metric_collector_.get()), sleep_duration)); } void MetricProvider::OnSessionRestoreDone(int num_tabs_restored) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); collector_task_runner_->PostTask( FROM_HERE, base::BindOnce(&MetricCollector::ScheduleSessionRestoreCollection, base::Unretained(metric_collector_.get()), num_tabs_restored)); } // static void MetricProvider::OnProfileDone( base::WeakPtr<MetricProvider> provider, std::unique_ptr<SampledProfile> sampled_profile) { base::PostTask(FROM_HERE, base::TaskTraits(content::BrowserThread::UI), base::BindOnce(&MetricProvider::AddProfileToCache, provider, std::move(sampled_profile))); } void MetricProvider::OnJankStarted() { collector_task_runner_->PostTask( FROM_HERE, base::BindOnce(&MetricCollector::OnJankStarted, base::Unretained(metric_collector_.get()))); } void MetricProvider::OnJankStopped() { collector_task_runner_->PostTask( FROM_HERE, base::BindOnce(&MetricCollector::OnJankStopped, base::Unretained(metric_collector_.get()))); } void MetricProvider::AddProfileToCache( std::unique_ptr<SampledProfile> sampled_profile) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); collector_task_runner_->PostTask( FROM_HERE, base::BindOnce(&MetricCollector::AddCachedDataDelta, base::Unretained(metric_collector_.get()), sampled_profile->ByteSize())); cached_profile_data_.resize(cached_profile_data_.size() + 1); cached_profile_data_.back().Swap(sampled_profile.get()); if (!cache_updated_callback_.is_null()) cache_updated_callback_.Run(); } } // namespace metrics
39.72561
80
0.701151
[ "vector" ]
4ba8d7ab9a8dc92bb11fe97791f6148b21e92b84
2,779
hh
C++
include/libbio/vcf/variant/abstract_variant_decl.hh
tsnorri/libbio
6cd929ac5f7bcccc340be60a6aa0a4ca6c7cb761
[ "MIT" ]
2
2021-05-21T08:44:53.000Z
2021-12-24T16:22:56.000Z
include/libbio/vcf/variant/abstract_variant_decl.hh
tsnorri/libbio
6cd929ac5f7bcccc340be60a6aa0a4ca6c7cb761
[ "MIT" ]
null
null
null
include/libbio/vcf/variant/abstract_variant_decl.hh
tsnorri/libbio
6cd929ac5f7bcccc340be60a6aa0a4ca6c7cb761
[ "MIT" ]
null
null
null
/* * Copyright (c) 2020 Tuukka Norri * This code is licensed under MIT license (see LICENSE for details). */ #ifndef LIBBIO_VCF_VARIANT_ABSTRACT_VARIANT_DECL_HH #define LIBBIO_VCF_VARIANT_ABSTRACT_VARIANT_DECL_HH #include <libbio/buffer.hh> #include <libbio/types.hh> #include <vector> namespace libbio::vcf { class variant_format; class reader; class metadata_filter; // Declare the constructors here s.t. the initialization code may be written more easily. class abstract_variant { template <typename, typename> friend class formatted_variant; friend class transient_variant_format_access; friend class variant_format_access; template <metadata_value_type, std::int32_t> friend class generic_info_field_base; friend class info_field_base; friend class reader; friend class storable_info_field_base; public: inline static constexpr double UNKNOWN_QUALITY{-1}; typedef std::vector <metadata_filter const *> filter_ptr_vector; protected: reader *m_reader{}; aligned_buffer <std::byte, buffer_base::zero_tag> m_info{}; // Zero on copy b.c. the types may not be TriviallyCopyable. // FIXME: if the range contains only trivially copyable types, copy the bytes. filter_ptr_vector m_filters{}; std::vector <bool> m_assigned_info_fields{}; double m_qual{UNKNOWN_QUALITY}; std::size_t m_variant_index{0}; std::size_t m_lineno{0}; std::size_t m_pos{0}; public: // Make sure that both m_info and m_samples have zero return value for size(), see the formatters’ destructors. abstract_variant() = default; virtual ~abstract_variant() {} inline abstract_variant(reader &vcf_reader, std::size_t const info_size, std::size_t const info_alignment); abstract_variant(abstract_variant const &) = default; abstract_variant(abstract_variant &&) = default; abstract_variant &operator=(abstract_variant const &) & = default; abstract_variant &operator=(abstract_variant &&) & = default; void set_variant_index(std::size_t const idx) { m_variant_index = idx; } void set_lineno(std::size_t const lineno) { m_lineno = lineno; } void set_pos(std::size_t const pos) { m_pos = pos; } void set_qual(double const qual) { m_qual = qual; } class reader *reader() const { return m_reader; } filter_ptr_vector const &filters() const { return m_filters; } std::size_t variant_index() const { return m_variant_index; } std::size_t lineno() const { return m_lineno; } std::size_t pos() const { return m_pos; } inline std::size_t zero_based_pos() const; double qual() const { return m_qual; } protected: inline void reset(); }; } #endif
33.890244
124
0.70529
[ "vector" ]
4baa061fbb295176c8ce3175e2f74bd3005821ce
3,917
cpp
C++
src/core/src/rt_info.cpp
ryanloney/openvino-1
4e0a740eb3ee31062ba0df88fcf438564f67edb7
[ "Apache-2.0" ]
1,127
2018-10-15T14:36:58.000Z
2020-04-20T09:29:44.000Z
src/core/src/rt_info.cpp
ryanloney/openvino-1
4e0a740eb3ee31062ba0df88fcf438564f67edb7
[ "Apache-2.0" ]
439
2018-10-20T04:40:35.000Z
2020-04-19T05:56:25.000Z
src/core/src/rt_info.cpp
ryanloney/openvino-1
4e0a740eb3ee31062ba0df88fcf438564f67edb7
[ "Apache-2.0" ]
414
2018-10-17T05:53:46.000Z
2020-04-16T17:29:53.000Z
// Copyright (C) 2018-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "openvino/core/rt_info.hpp" #include "ngraph/variant.hpp" namespace { std::unordered_map<std::string, std::vector<ov::Any>> get_copyable_attrs(const ov::OutputVector& outputs) { std::unordered_map<std::string, std::vector<ov::Any>> attrs; for (const auto& output : outputs) { for (const auto& item : output.get_rt_info()) { bool copy = true; if (item.second.is<ov::RuntimeAttribute>()) { copy = item.second.as<ov::RuntimeAttribute>().is_copyable(); } if (copy) { attrs[item.first].push_back(item.second); } } } return attrs; } std::unordered_map<std::string, std::vector<ov::Any>> get_copyable_attrs(const ov::NodeVector& nodes) { std::unordered_map<std::string, std::vector<ov::Any>> attrs; for (const auto& node : nodes) { for (const auto& item : node->get_rt_info()) { bool copy = item.first != "opset"; if (item.second.is<ov::RuntimeAttribute>()) { copy = copy && item.second.as<ov::RuntimeAttribute>().is_copyable(); } if (copy) { attrs[item.first].push_back(item.second); } } } return attrs; } template <typename T> ov::Node::RTMap mergeRuntimeInfo(const T& items) { std::unordered_map<std::string, std::vector<ov::Any>> attrs = get_copyable_attrs(items); ov::Node::RTMap merged_attrs; for (auto& item : attrs) { auto attr = *item.second.begin(); if (item.second.size() == 1) { merged_attrs[item.first] = attr; } else { if (attr.is<ov::RuntimeAttribute>()) { auto merge_attr = attr.as<ov::RuntimeAttribute>().merge(items); if (!merge_attr.empty()) { merged_attrs[item.first] = merge_attr; } } } } return merged_attrs; } ov::Any get_opset(const ov::Node::RTMap& rt_info) { auto it = rt_info.find("opset"); if (it != rt_info.end()) { return it->second; } return nullptr; } void assign_runtime_info(const ov::Node::RTMap& from, ov::Node::RTMap& to) { auto opset = get_opset(to); for (auto& item : from) { to[item.first] = item.second; } if (!opset.empty()) { to["opset"] = opset; } } } // namespace void ov::copy_runtime_info(const std::shared_ptr<ov::Node>& from, const std::shared_ptr<ov::Node>& to) { auto& attrs = to->get_rt_info(); auto opset = get_opset(attrs); for (const auto& item : from->get_rt_info()) { bool copy = item.first != "opset"; if (item.second.is<ov::RuntimeAttribute>()) { copy = copy && item.second.as<ov::RuntimeAttribute>().is_copyable(); } if (copy) { attrs[item.first] = item.second; } } if (!opset.empty()) { attrs["opset"] = opset; } } void ov::copy_runtime_info(const std::shared_ptr<ov::Node>& from, ov::NodeVector to) { for (auto& op : to) { copy_runtime_info(from, op); } } void ov::copy_runtime_info(const ov::NodeVector& from, const std::shared_ptr<ov::Node>& to) { auto& rtInfoTo = to->get_rt_info(); assign_runtime_info(mergeRuntimeInfo(from), rtInfoTo); } void ov::copy_runtime_info(const ov::NodeVector& from, ov::NodeVector to) { auto mergedInfo = mergeRuntimeInfo(from); for (auto& node : to) { auto& rtInfoTo = node->get_rt_info(); assign_runtime_info(mergedInfo, rtInfoTo); } } void ov::copy_output_runtime_info(const ov::OutputVector& from, ov::OutputVector to) { auto mergedInfo = mergeRuntimeInfo(from); for (auto& node : to) { auto& rtInfoTo = node.get_rt_info(); assign_runtime_info(mergedInfo, rtInfoTo); } }
30.130769
107
0.585652
[ "vector" ]
4bc54b6af91b3c2805246f255c7d28479414559b
1,880
hpp
C++
JEBIO/JEBIO/Json/TextReader.hpp
jebreimo/JEBLib
9066403a9372951aa8ce4f129cd4877e2ae779ab
[ "BSD-3-Clause" ]
1
2019-12-25T05:30:20.000Z
2019-12-25T05:30:20.000Z
JEBIO/JEBIO/Json/TextReader.hpp
jebreimo/JEBLib
9066403a9372951aa8ce4f129cd4877e2ae779ab
[ "BSD-3-Clause" ]
null
null
null
JEBIO/JEBIO/Json/TextReader.hpp
jebreimo/JEBLib
9066403a9372951aa8ce4f129cd4877e2ae779ab
[ "BSD-3-Clause" ]
null
null
null
#ifndef JEB_TEXTREADER_HPP #define JEB_TEXTREADER_HPP #include <memory> #include <iosfwd> #include <vector> #include <JEB/String/StringConversion.hpp> namespace JEBIO { class TextReader { public: typedef std::vector<char> Buffer; static const size_t DefaultBufferSize = 16 * 1024; /** @brief Opens a file, detects its encoding and return a TextReader. * * @throws std::runtime_error if the file doesn't exist, can't be opened * or has an unrecognized encoding. */ static TextReader open(const std::string& fileName, size_t bufferSize = DefaultBufferSize); TextReader(size_t bufferSize = DefaultBufferSize); TextReader(std::istream& stream, String::Encoding_t streamEncoding, size_t bufferSize = DefaultBufferSize); /** @brief The TextReader will delete stream in its destructor. */ TextReader(std::unique_ptr<std::istream> stream, String::Encoding_t streamEncoding, size_t bufferSize = DefaultBufferSize); TextReader(TextReader&& rhs); ~TextReader(); TextReader& operator=(TextReader&& rhs); bool hasStream() const; std::istream& stream() const; void setStream(std::istream& stream); void setStream(std::unique_ptr<std::istream> streamPtr); std::istream* releaseStream(); String::Encoding_t streamEncoding() const; void setStreamEncoding(String::Encoding_t encoding); String::Encoding_t detectStreamEncoding(); /** @brief Reads a new buffer from the file and discards the previous. */ size_t read(char* buffer, size_t bufferSize); private: bool read(); Buffer m_Buffer; size_t m_BufferOffset; String::StringConverter m_Converter; size_t m_ContentEnd; std::istream* m_Stream; std::unique_ptr<std::istream> m_StreamPtr; }; } #endif
27.246377
77
0.678723
[ "vector" ]
4bc5752ba35fa120ff6049f21280b8356959b3ee
3,086
cc
C++
ons/src/model/OnsMqttQueryClientByClientIdResult.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
ons/src/model/OnsMqttQueryClientByClientIdResult.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
ons/src/model/OnsMqttQueryClientByClientIdResult.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/ons/model/OnsMqttQueryClientByClientIdResult.h> #include <json/json.h> using namespace AlibabaCloud::Ons; using namespace AlibabaCloud::Ons::Model; OnsMqttQueryClientByClientIdResult::OnsMqttQueryClientByClientIdResult() : ServiceResult() {} OnsMqttQueryClientByClientIdResult::OnsMqttQueryClientByClientIdResult(const std::string &payload) : ServiceResult() { parse(payload); } OnsMqttQueryClientByClientIdResult::~OnsMqttQueryClientByClientIdResult() {} void OnsMqttQueryClientByClientIdResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto mqttClientInfoDoNode = value["MqttClientInfoDo"]; if(!mqttClientInfoDoNode["Online"].isNull()) mqttClientInfoDo_.online = mqttClientInfoDoNode["Online"].asString() == "true"; if(!mqttClientInfoDoNode["ClientId"].isNull()) mqttClientInfoDo_.clientId = mqttClientInfoDoNode["ClientId"].asString(); if(!mqttClientInfoDoNode["SocketChannel"].isNull()) mqttClientInfoDo_.socketChannel = mqttClientInfoDoNode["SocketChannel"].asString(); if(!mqttClientInfoDoNode["LastTouch"].isNull()) mqttClientInfoDo_.lastTouch = std::stol(mqttClientInfoDoNode["LastTouch"].asString()); auto allSubScriptonDataNode = mqttClientInfoDoNode["SubScriptonData"]["SubscriptionDo"]; for (auto mqttClientInfoDoNodeSubScriptonDataSubscriptionDo : allSubScriptonDataNode) { MqttClientInfoDo::SubscriptionDo subscriptionDoObject; if(!mqttClientInfoDoNodeSubScriptonDataSubscriptionDo["ParentTopic"].isNull()) subscriptionDoObject.parentTopic = mqttClientInfoDoNodeSubScriptonDataSubscriptionDo["ParentTopic"].asString(); if(!mqttClientInfoDoNodeSubScriptonDataSubscriptionDo["SubTopic"].isNull()) subscriptionDoObject.subTopic = mqttClientInfoDoNodeSubScriptonDataSubscriptionDo["SubTopic"].asString(); if(!mqttClientInfoDoNodeSubScriptonDataSubscriptionDo["Qos"].isNull()) subscriptionDoObject.qos = std::stoi(mqttClientInfoDoNodeSubScriptonDataSubscriptionDo["Qos"].asString()); mqttClientInfoDo_.subScriptonData.push_back(subscriptionDoObject); } if(!value["HelpUrl"].isNull()) helpUrl_ = value["HelpUrl"].asString(); } OnsMqttQueryClientByClientIdResult::MqttClientInfoDo OnsMqttQueryClientByClientIdResult::getMqttClientInfoDo()const { return mqttClientInfoDo_; } std::string OnsMqttQueryClientByClientIdResult::getHelpUrl()const { return helpUrl_; }
39.564103
115
0.798121
[ "model" ]
4bca064e28aefd5209831bbe0b915db27d02560d
847
cpp
C++
0054-spiral-matrix.cpp
Jamesweng/leetcode
1711a2a0e31d831e40137203c9abcba0bf56fcad
[ "Apache-2.0" ]
106
2019-06-08T15:23:45.000Z
2020-04-04T17:56:54.000Z
0054-spiral-matrix.cpp
Jamesweng/leetcode
1711a2a0e31d831e40137203c9abcba0bf56fcad
[ "Apache-2.0" ]
null
null
null
0054-spiral-matrix.cpp
Jamesweng/leetcode
1711a2a0e31d831e40137203c9abcba0bf56fcad
[ "Apache-2.0" ]
3
2019-07-13T05:51:29.000Z
2020-04-04T17:56:57.000Z
class Solution { public: vector<int> spiralOrder(vector<vector<int>>& matrix) { int dir[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; int k = 0, VISITED = 345672384; vector<int> ans; if (matrix.empty()) return ans; int x = 0, y = 0; int total = matrix.size() * matrix[0].size(); while (ans.size() < total) { while (x < matrix.size() && y < matrix[0].size() && matrix[x][y] != VISITED) { ans.push_back(matrix[x][y]); matrix[x][y] = VISITED; x += dir[k][0]; y += dir[k][1]; } x -= dir[k][0]; y -= dir[k][1]; k = (k + 1) % 4; x += dir[k][0]; y += dir[k][1]; } return ans; } };
28.233333
69
0.367178
[ "vector" ]
4bd5b30299060a88d1579a3b270dfb4a34569bae
1,109
cpp
C++
src/window.cpp
FathomRaven/CppCodeReview
9c06304659db4aa192cad7c92efc3fa1af7bd75b
[ "MIT" ]
null
null
null
src/window.cpp
FathomRaven/CppCodeReview
9c06304659db4aa192cad7c92efc3fa1af7bd75b
[ "MIT" ]
1
2021-09-01T11:40:22.000Z
2021-09-01T17:03:48.000Z
src/window.cpp
FathomRaven/CppCodeReview
9c06304659db4aa192cad7c92efc3fa1af7bd75b
[ "MIT" ]
1
2021-08-31T21:56:05.000Z
2021-08-31T21:56:05.000Z
#pragma once #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #include <vector> #include "rect.hpp" #include "window.hpp" #include "constants.hpp" windowApp::windowApp() { SDL_Init(SDL_INIT_VIDEO); window = SDL_CreateWindow("Test Window", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 400, 400, 0); renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED /*| SDL_RENDERER_PRESENTVSYNC <-- would be nice to have this? :thinking:*/); } windowApp::~windowApp() { SDL_DestroyWindow(window); SDL_DestroyRenderer(renderer); } void windowApp::render(Rectangle& p_rect) { SDL_RenderFillRect(renderer, &p_rect.rect); } void windowApp::display() { SDL_RenderPresent(renderer); } void windowApp::clear() { colorChange(BLACK); SDL_RenderClear(renderer); } void windowApp::colorChange(int r, int g, int b, int a) { SDL_SetRenderDrawColor(renderer, r, g, b, a); } void windowApp::renderEverything(std::vector<Rectangle> &rects) { for (std::size_t i = 0, max = rects.size(); i < max; i++) { SDL_RenderFillRect(renderer, &rects[i].rect); } }
21.326923
147
0.698828
[ "render", "vector" ]
4bd69e34e3c3b37fabf164642fc82bf932404bc4
3,647
cpp
C++
lib/Object/ELFObjectFile.cpp
kpdev/llvm-tnt
d81ccf6fad01597f0143a1598d94d7d29002cf41
[ "MIT" ]
1,073
2017-06-28T05:11:54.000Z
2022-03-31T12:52:07.000Z
lib/Object/ELFObjectFile.cpp
kpdev/llvm-tnt
d81ccf6fad01597f0143a1598d94d7d29002cf41
[ "MIT" ]
25
2018-07-23T08:34:15.000Z
2021-11-05T07:13:36.000Z
lib/Object/ELFObjectFile.cpp
kpdev/llvm-tnt
d81ccf6fad01597f0143a1598d94d7d29002cf41
[ "MIT" ]
244
2017-06-28T05:08:57.000Z
2022-03-13T05:03:12.000Z
//===- ELFObjectFile.cpp - ELF object file implementation -------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Part of the ELFObjectFile class implementation. // //===----------------------------------------------------------------------===// #include "llvm/Object/ELFObjectFile.h" #include "llvm/Support/MathExtras.h" namespace llvm { using namespace object; ELFObjectFileBase::ELFObjectFileBase(unsigned int Type, MemoryBufferRef Source) : ObjectFile(Type, Source) {} ErrorOr<std::unique_ptr<ObjectFile>> ObjectFile::createELFObjectFile(MemoryBufferRef Obj) { std::pair<unsigned char, unsigned char> Ident = getElfArchType(Obj.getBuffer()); std::size_t MaxAlignment = 1ULL << countTrailingZeros(uintptr_t(Obj.getBufferStart())); if (MaxAlignment < 2) return object_error::parse_failed; std::error_code EC; std::unique_ptr<ObjectFile> R; if (Ident.first == ELF::ELFCLASS32) { if (Ident.second == ELF::ELFDATA2LSB) R.reset(new ELFObjectFile<ELFType<support::little, false>>(Obj, EC)); else if (Ident.second == ELF::ELFDATA2MSB) R.reset(new ELFObjectFile<ELFType<support::big, false>>(Obj, EC)); else return object_error::parse_failed; } else if (Ident.first == ELF::ELFCLASS64) { if (Ident.second == ELF::ELFDATA2LSB) R.reset(new ELFObjectFile<ELFType<support::little, true>>(Obj, EC)); else if (Ident.second == ELF::ELFDATA2MSB) R.reset(new ELFObjectFile<ELFType<support::big, true>>(Obj, EC)); else return object_error::parse_failed; } else { return object_error::parse_failed; } if (EC) return EC; return std::move(R); } SubtargetFeatures ELFObjectFileBase::getFeatures() const { switch (getEMachine()) { case ELF::EM_MIPS: { SubtargetFeatures Features; unsigned PlatformFlags; getPlatformFlags(PlatformFlags); switch (PlatformFlags & ELF::EF_MIPS_ARCH) { case ELF::EF_MIPS_ARCH_1: break; case ELF::EF_MIPS_ARCH_2: Features.AddFeature("mips2"); break; case ELF::EF_MIPS_ARCH_3: Features.AddFeature("mips3"); break; case ELF::EF_MIPS_ARCH_4: Features.AddFeature("mips4"); break; case ELF::EF_MIPS_ARCH_5: Features.AddFeature("mips5"); break; case ELF::EF_MIPS_ARCH_32: Features.AddFeature("mips32"); break; case ELF::EF_MIPS_ARCH_64: Features.AddFeature("mips64"); break; case ELF::EF_MIPS_ARCH_32R2: Features.AddFeature("mips32r2"); break; case ELF::EF_MIPS_ARCH_64R2: Features.AddFeature("mips64r2"); break; case ELF::EF_MIPS_ARCH_32R6: Features.AddFeature("mips32r6"); break; case ELF::EF_MIPS_ARCH_64R6: Features.AddFeature("mips64r6"); break; default: llvm_unreachable("Unknown EF_MIPS_ARCH value"); } switch (PlatformFlags & ELF::EF_MIPS_MACH) { case ELF::EF_MIPS_MACH_NONE: // No feature associated with this value. break; case ELF::EF_MIPS_MACH_OCTEON: Features.AddFeature("cnmips"); break; default: llvm_unreachable("Unknown EF_MIPS_ARCH value"); } if (PlatformFlags & ELF::EF_MIPS_ARCH_ASE_M16) Features.AddFeature("mips16"); if (PlatformFlags & ELF::EF_MIPS_MICROMIPS) Features.AddFeature("micromips"); return Features; } default: return SubtargetFeatures(); } } } // end namespace llvm
28.944444
80
0.641075
[ "object" ]
4bd81a791c54973fa973bd8b8750a1ca9678d6bf
69,476
cc
C++
chromium/net/quic/quic_packet_generator_test.cc
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
27
2016-04-27T01:02:03.000Z
2021-12-13T08:53:19.000Z
chromium/net/quic/quic_packet_generator_test.cc
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
2
2017-03-09T09:00:50.000Z
2017-09-21T15:48:20.000Z
chromium/net/quic/quic_packet_generator_test.cc
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
17
2016-04-27T02:06:39.000Z
2019-12-18T08:07:00.000Z
// Copyright (c) 2012 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 "net/quic/quic_packet_generator.h" #include <string> #include "base/macros.h" #include "net/quic/crypto/crypto_protocol.h" #include "net/quic/crypto/null_encrypter.h" #include "net/quic/crypto/quic_decrypter.h" #include "net/quic/crypto/quic_encrypter.h" #include "net/quic/quic_flags.h" #include "net/quic/quic_simple_buffer_allocator.h" #include "net/quic/quic_utils.h" #include "net/quic/test_tools/quic_packet_creator_peer.h" #include "net/quic/test_tools/quic_packet_generator_peer.h" #include "net/quic/test_tools/quic_test_utils.h" #include "net/quic/test_tools/simple_quic_framer.h" #include "net/test/gtest_util.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using base::StringPiece; using std::string; using std::vector; using testing::InSequence; using testing::Return; using testing::StrictMock; using testing::_; namespace net { namespace test { namespace { const int64_t kMinFecTimeoutMs = 5u; static const FecSendPolicy kFecSendPolicyList[] = { FEC_ANY_TRIGGER, FEC_ALARM_TRIGGER, }; class MockDelegate : public QuicPacketGenerator::DelegateInterface { public: MockDelegate() {} ~MockDelegate() override {} MOCK_METHOD2(ShouldGeneratePacket, bool(HasRetransmittableData retransmittable, IsHandshake handshake)); MOCK_METHOD1(PopulateAckFrame, void(QuicAckFrame*)); MOCK_METHOD1(PopulateStopWaitingFrame, void(QuicStopWaitingFrame*)); MOCK_METHOD1(OnSerializedPacket, void(SerializedPacket* packet)); MOCK_METHOD2(CloseConnection, void(QuicErrorCode, bool)); MOCK_METHOD0(OnResetFecGroup, void()); void SetCanWriteAnything() { EXPECT_CALL(*this, ShouldGeneratePacket(_, _)).WillRepeatedly(Return(true)); EXPECT_CALL(*this, ShouldGeneratePacket(NO_RETRANSMITTABLE_DATA, _)) .WillRepeatedly(Return(true)); } void SetCanNotWrite() { EXPECT_CALL(*this, ShouldGeneratePacket(_, _)) .WillRepeatedly(Return(false)); EXPECT_CALL(*this, ShouldGeneratePacket(NO_RETRANSMITTABLE_DATA, _)) .WillRepeatedly(Return(false)); } // Use this when only ack frames should be allowed to be written. void SetCanWriteOnlyNonRetransmittable() { EXPECT_CALL(*this, ShouldGeneratePacket(_, _)) .WillRepeatedly(Return(false)); EXPECT_CALL(*this, ShouldGeneratePacket(NO_RETRANSMITTABLE_DATA, _)) .WillRepeatedly(Return(true)); } private: DISALLOW_COPY_AND_ASSIGN(MockDelegate); }; // Simple struct for describing the contents of a packet. // Useful in conjunction with a SimpleQuicFrame for validating that a packet // contains the expected frames. struct PacketContents { PacketContents() : num_ack_frames(0), num_connection_close_frames(0), num_goaway_frames(0), num_rst_stream_frames(0), num_stop_waiting_frames(0), num_stream_frames(0), num_ping_frames(0), num_mtu_discovery_frames(0), fec_group(0) {} size_t num_ack_frames; size_t num_connection_close_frames; size_t num_goaway_frames; size_t num_rst_stream_frames; size_t num_stop_waiting_frames; size_t num_stream_frames; size_t num_ping_frames; size_t num_mtu_discovery_frames; QuicFecGroupNumber fec_group; }; } // namespace class QuicPacketGeneratorTest : public ::testing::TestWithParam<FecSendPolicy> { public: QuicPacketGeneratorTest() : framer_(QuicSupportedVersions(), QuicTime::Zero(), Perspective::IS_CLIENT), generator_(42, &framer_, &random_, &buffer_allocator_, &delegate_), creator_(QuicPacketGeneratorPeer::GetPacketCreator(&generator_)) { generator_.set_fec_send_policy(GetParam()); // TODO(ianswett): Fix this test so it uses a non-null encrypter. FLAGS_quic_never_write_unencrypted_data = false; FLAGS_quic_no_unencrypted_fec = false; } ~QuicPacketGeneratorTest() override { for (SerializedPacket& packet : packets_) { delete packet.packet; delete packet.retransmittable_frames; } } void SavePacket(SerializedPacket* packet) { packets_.push_back(*packet); ASSERT_FALSE(packet->packet->owns_buffer()); scoped_ptr<QuicEncryptedPacket> encrypted_deleter(packets_.back().packet); packets_.back().packet = packets_.back().packet->Clone(); } protected: QuicRstStreamFrame* CreateRstStreamFrame() { return new QuicRstStreamFrame(1, QUIC_STREAM_NO_ERROR, 0); } QuicGoAwayFrame* CreateGoAwayFrame() { return new QuicGoAwayFrame(QUIC_NO_ERROR, 1, string()); } void CheckPacketContains(const PacketContents& contents, size_t packet_index) { ASSERT_GT(packets_.size(), packet_index); const SerializedPacket& packet = packets_[packet_index]; size_t num_retransmittable_frames = contents.num_connection_close_frames + contents.num_goaway_frames + contents.num_rst_stream_frames + contents.num_stream_frames + contents.num_ping_frames; size_t num_frames = contents.num_ack_frames + contents.num_stop_waiting_frames + contents.num_mtu_discovery_frames + num_retransmittable_frames; if (num_retransmittable_frames == 0) { ASSERT_TRUE(packet.retransmittable_frames == nullptr); } else { ASSERT_TRUE(packet.retransmittable_frames != nullptr); EXPECT_EQ(num_retransmittable_frames, packet.retransmittable_frames->frames().size()); } ASSERT_TRUE(packet.packet != nullptr); ASSERT_TRUE(simple_framer_.ProcessPacket(*packet.packet)); EXPECT_EQ(num_frames, simple_framer_.num_frames()); EXPECT_EQ(contents.num_ack_frames, simple_framer_.ack_frames().size()); EXPECT_EQ(contents.num_connection_close_frames, simple_framer_.connection_close_frames().size()); EXPECT_EQ(contents.num_goaway_frames, simple_framer_.goaway_frames().size()); EXPECT_EQ(contents.num_rst_stream_frames, simple_framer_.rst_stream_frames().size()); EXPECT_EQ(contents.num_stream_frames, simple_framer_.stream_frames().size()); EXPECT_EQ(contents.num_stop_waiting_frames, simple_framer_.stop_waiting_frames().size()); EXPECT_EQ(contents.fec_group, simple_framer_.header().fec_group); // From the receiver's perspective, MTU discovery frames are ping frames. EXPECT_EQ(contents.num_ping_frames + contents.num_mtu_discovery_frames, simple_framer_.ping_frames().size()); } void CheckPacketHasSingleStreamFrame(size_t packet_index) { ASSERT_GT(packets_.size(), packet_index); const SerializedPacket& packet = packets_[packet_index]; ASSERT_TRUE(packet.retransmittable_frames != nullptr); EXPECT_EQ(1u, packet.retransmittable_frames->frames().size()); ASSERT_TRUE(packet.packet != nullptr); ASSERT_TRUE(simple_framer_.ProcessPacket(*packet.packet)); EXPECT_EQ(1u, simple_framer_.num_frames()); EXPECT_EQ(1u, simple_framer_.stream_frames().size()); } void CheckAllPacketsHaveSingleStreamFrame() { for (size_t i = 0; i < packets_.size(); i++) { CheckPacketHasSingleStreamFrame(i); } } void CheckPacketIsFec(size_t packet_index, QuicPacketNumber fec_group) { ASSERT_GT(packets_.size(), packet_index); const SerializedPacket& packet = packets_[packet_index]; ASSERT_TRUE(packet.retransmittable_frames == nullptr); ASSERT_TRUE(packet.packet != nullptr); ASSERT_TRUE(simple_framer_.ProcessPacket(*packet.packet)); EXPECT_TRUE(simple_framer_.header().fec_flag); } QuicIOVector CreateData(size_t len) { data_array_.reset(new char[len]); memset(data_array_.get(), '?', len); iov_.iov_base = data_array_.get(); iov_.iov_len = len; return QuicIOVector(&iov_, 1, len); } QuicIOVector MakeIOVector(StringPiece s) { return ::net::MakeIOVector(s, &iov_); } QuicFramer framer_; MockRandom random_; SimpleBufferAllocator buffer_allocator_; StrictMock<MockDelegate> delegate_; QuicPacketGenerator generator_; QuicPacketCreator* creator_; SimpleQuicFramer simple_framer_; vector<SerializedPacket> packets_; private: scoped_ptr<char[]> data_array_; struct iovec iov_; }; class MockDebugDelegate : public QuicPacketCreator::DebugDelegate { public: MOCK_METHOD1(OnFrameAddedToPacket, void(const QuicFrame&)); }; // Run all end to end tests with all supported FEC send polocies. INSTANTIATE_TEST_CASE_P(FecSendPolicy, QuicPacketGeneratorTest, ::testing::ValuesIn(kFecSendPolicyList)); TEST_P(QuicPacketGeneratorTest, ShouldSendAck_NotWritable) { delegate_.SetCanNotWrite(); generator_.SetShouldSendAck(false); EXPECT_TRUE(generator_.HasQueuedFrames()); } TEST_P(QuicPacketGeneratorTest, ShouldSendAck_WritableAndShouldNotFlush) { StrictMock<MockDebugDelegate> debug_delegate; generator_.set_debug_delegate(&debug_delegate); delegate_.SetCanWriteOnlyNonRetransmittable(); generator_.StartBatchOperations(); EXPECT_CALL(delegate_, PopulateAckFrame(_)); EXPECT_CALL(debug_delegate, OnFrameAddedToPacket(_)).Times(1); generator_.SetShouldSendAck(false); EXPECT_TRUE(generator_.HasQueuedFrames()); } TEST_P(QuicPacketGeneratorTest, ShouldSendAck_WritableAndShouldFlush) { delegate_.SetCanWriteOnlyNonRetransmittable(); EXPECT_CALL(delegate_, PopulateAckFrame(_)); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); generator_.SetShouldSendAck(false); EXPECT_FALSE(generator_.HasQueuedFrames()); PacketContents contents; contents.num_ack_frames = 1; CheckPacketContains(contents, 0); } TEST_P(QuicPacketGeneratorTest, ShouldSendAck_MultipleCalls) { // Make sure that calling SetShouldSendAck multiple times does not result in a // crash. Previously this would result in multiple QuicFrames queued in the // packet generator, with all but the last with internal pointers to freed // memory. delegate_.SetCanWriteAnything(); // Only one AckFrame should be created. EXPECT_CALL(delegate_, PopulateAckFrame(_)).Times(1); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .Times(1) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); generator_.StartBatchOperations(); generator_.SetShouldSendAck(false); generator_.SetShouldSendAck(false); generator_.FinishBatchOperations(); } TEST_P(QuicPacketGeneratorTest, AddControlFrame_NotWritable) { delegate_.SetCanNotWrite(); generator_.AddControlFrame(QuicFrame(CreateRstStreamFrame())); EXPECT_TRUE(generator_.HasQueuedFrames()); } TEST_P(QuicPacketGeneratorTest, AddControlFrame_OnlyAckWritable) { delegate_.SetCanWriteOnlyNonRetransmittable(); generator_.AddControlFrame(QuicFrame(CreateRstStreamFrame())); EXPECT_TRUE(generator_.HasQueuedFrames()); } TEST_P(QuicPacketGeneratorTest, AddControlFrame_WritableAndShouldNotFlush) { delegate_.SetCanWriteAnything(); generator_.StartBatchOperations(); generator_.AddControlFrame(QuicFrame(CreateRstStreamFrame())); EXPECT_TRUE(generator_.HasQueuedFrames()); } TEST_P(QuicPacketGeneratorTest, AddControlFrame_NotWritableBatchThenFlush) { delegate_.SetCanNotWrite(); generator_.StartBatchOperations(); generator_.AddControlFrame(QuicFrame(CreateRstStreamFrame())); EXPECT_TRUE(generator_.HasQueuedFrames()); generator_.FinishBatchOperations(); EXPECT_TRUE(generator_.HasQueuedFrames()); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); generator_.FlushAllQueuedFrames(); EXPECT_FALSE(generator_.HasQueuedFrames()); PacketContents contents; contents.num_rst_stream_frames = 1; CheckPacketContains(contents, 0); } TEST_P(QuicPacketGeneratorTest, AddControlFrame_WritableAndShouldFlush) { delegate_.SetCanWriteAnything(); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); generator_.AddControlFrame(QuicFrame(CreateRstStreamFrame())); EXPECT_FALSE(generator_.HasQueuedFrames()); PacketContents contents; contents.num_rst_stream_frames = 1; CheckPacketContains(contents, 0); } TEST_P(QuicPacketGeneratorTest, ConsumeData_NotWritable) { delegate_.SetCanNotWrite(); QuicConsumedData consumed = generator_.ConsumeData( kHeadersStreamId, MakeIOVector("foo"), 2, true, MAY_FEC_PROTECT, nullptr); EXPECT_EQ(0u, consumed.bytes_consumed); EXPECT_FALSE(consumed.fin_consumed); EXPECT_FALSE(generator_.HasQueuedFrames()); } TEST_P(QuicPacketGeneratorTest, ConsumeData_WritableAndShouldNotFlush) { delegate_.SetCanWriteAnything(); generator_.StartBatchOperations(); QuicConsumedData consumed = generator_.ConsumeData( kHeadersStreamId, MakeIOVector("foo"), 2, true, MAY_FEC_PROTECT, nullptr); EXPECT_EQ(3u, consumed.bytes_consumed); EXPECT_TRUE(consumed.fin_consumed); EXPECT_TRUE(generator_.HasQueuedFrames()); } TEST_P(QuicPacketGeneratorTest, ConsumeData_WritableAndShouldFlush) { delegate_.SetCanWriteAnything(); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); QuicConsumedData consumed = generator_.ConsumeData( kHeadersStreamId, MakeIOVector("foo"), 2, true, MAY_FEC_PROTECT, nullptr); EXPECT_EQ(3u, consumed.bytes_consumed); EXPECT_TRUE(consumed.fin_consumed); EXPECT_FALSE(generator_.HasQueuedFrames()); PacketContents contents; contents.num_stream_frames = 1; CheckPacketContains(contents, 0); } // Test the behavior of ConsumeData when the data consumed is for the crypto // handshake stream. Ensure that the packet is always sent and padded even if // the generator operates in batch mode. TEST_P(QuicPacketGeneratorTest, ConsumeData_Handshake) { delegate_.SetCanWriteAnything(); generator_.StartBatchOperations(); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); QuicConsumedData consumed = generator_.ConsumeData( kCryptoStreamId, MakeIOVector("foo"), 0, false, MAY_FEC_PROTECT, nullptr); EXPECT_EQ(3u, consumed.bytes_consumed); EXPECT_FALSE(generator_.HasQueuedFrames()); PacketContents contents; contents.num_stream_frames = 1; CheckPacketContains(contents, 0); ASSERT_EQ(1u, packets_.size()); ASSERT_EQ(kDefaultMaxPacketSize, generator_.GetMaxPacketLength()); EXPECT_EQ(kDefaultMaxPacketSize, packets_[0].packet->length()); } TEST_P(QuicPacketGeneratorTest, ConsumeData_EmptyData) { EXPECT_DFATAL(generator_.ConsumeData(kHeadersStreamId, MakeIOVector(""), 0, false, MAY_FEC_PROTECT, nullptr), "Attempt to consume empty data without FIN."); } TEST_P(QuicPacketGeneratorTest, ConsumeDataMultipleTimes_WritableAndShouldNotFlush) { delegate_.SetCanWriteAnything(); generator_.StartBatchOperations(); generator_.ConsumeData(kHeadersStreamId, MakeIOVector("foo"), 2, true, MAY_FEC_PROTECT, nullptr); QuicConsumedData consumed = generator_.ConsumeData( 3, MakeIOVector("quux"), 7, false, MAY_FEC_PROTECT, nullptr); EXPECT_EQ(4u, consumed.bytes_consumed); EXPECT_FALSE(consumed.fin_consumed); EXPECT_TRUE(generator_.HasQueuedFrames()); } TEST_P(QuicPacketGeneratorTest, ConsumeData_BatchOperations) { delegate_.SetCanWriteAnything(); generator_.StartBatchOperations(); generator_.ConsumeData(kHeadersStreamId, MakeIOVector("foo"), 2, true, MAY_FEC_PROTECT, nullptr); QuicConsumedData consumed = generator_.ConsumeData( 3, MakeIOVector("quux"), 7, false, MAY_FEC_PROTECT, nullptr); EXPECT_EQ(4u, consumed.bytes_consumed); EXPECT_FALSE(consumed.fin_consumed); EXPECT_TRUE(generator_.HasQueuedFrames()); // Now both frames will be flushed out. EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); generator_.FinishBatchOperations(); EXPECT_FALSE(generator_.HasQueuedFrames()); PacketContents contents; contents.num_stream_frames = 2; CheckPacketContains(contents, 0); } TEST_P(QuicPacketGeneratorTest, ConsumeDataFecOnMaxGroupSize) { delegate_.SetCanWriteAnything(); // Send FEC every two packets. creator_->set_max_packets_per_fec_group(2); { InSequence dummy; EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); if (generator_.fec_send_policy() == FEC_ALARM_TRIGGER) { // FEC packet is not sent when send policy is FEC_ALARM_TRIGGER, but FEC // group is closed. EXPECT_CALL(delegate_, OnResetFecGroup()).Times(1); } else { EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); } EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); } // Send enough data to create 3 packets: two full and one partial. Send with // MUST_FEC_PROTECT flag. size_t data_len = 2 * kDefaultMaxPacketSize + 100; QuicConsumedData consumed = generator_.ConsumeData( 3, CreateData(data_len), 0, true, MUST_FEC_PROTECT, nullptr); EXPECT_EQ(data_len, consumed.bytes_consumed); EXPECT_TRUE(consumed.fin_consumed); EXPECT_FALSE(generator_.HasQueuedFrames()); CheckPacketHasSingleStreamFrame(0); CheckPacketHasSingleStreamFrame(1); if (generator_.fec_send_policy() == FEC_ALARM_TRIGGER) { // FEC packet is not sent when send policy is FEC_ALARM_TRIGGER. CheckPacketHasSingleStreamFrame(2); } else { CheckPacketIsFec(2, 1); CheckPacketHasSingleStreamFrame(3); } EXPECT_TRUE(QuicPacketCreatorPeer::IsFecProtected(creator_)); // If FEC send policy is FEC_ANY_TRIGGER, then the FEC packet under // construction will be sent when one more packet is sent (since FEC group // size is 2), or when OnFecTimeout is called. Send more data with // MAY_FEC_PROTECT. This packet should also be protected, and FEC packet is // sent since FEC group size is reached. // // If FEC send policy is FEC_ALARM_TRIGGER, FEC group is closed when the group // size is reached. FEC packet is not sent. { InSequence dummy; EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); if (generator_.fec_send_policy() == FEC_ALARM_TRIGGER) { EXPECT_CALL(delegate_, OnResetFecGroup()).Times(1); } else { EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); } } consumed = generator_.ConsumeData(5, CreateData(1u), 0, true, MAY_FEC_PROTECT, nullptr); EXPECT_EQ(1u, consumed.bytes_consumed); if (generator_.fec_send_policy() == FEC_ALARM_TRIGGER) { CheckPacketHasSingleStreamFrame(3); } else { CheckPacketHasSingleStreamFrame(4); CheckPacketIsFec(5, 4); } EXPECT_FALSE(QuicPacketCreatorPeer::IsFecProtected(creator_)); } TEST_P(QuicPacketGeneratorTest, ConsumeDataSendsFecOnTimeout) { delegate_.SetCanWriteAnything(); creator_->set_max_packets_per_fec_group(1000); // Send data with MUST_FEC_PROTECT flag. No FEC packet is emitted, but the // creator FEC protects all data. EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); QuicConsumedData consumed = generator_.ConsumeData(3, CreateData(1u), 0, true, MUST_FEC_PROTECT, nullptr); EXPECT_EQ(1u, consumed.bytes_consumed); EXPECT_TRUE(consumed.fin_consumed); CheckPacketHasSingleStreamFrame(0); EXPECT_TRUE(QuicPacketCreatorPeer::IsFecProtected(creator_)); // Send more data with MAY_FEC_PROTECT. This packet should also be protected, // and FEC packet is not yet sent. EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); consumed = generator_.ConsumeData(5, CreateData(1u), 0, true, MAY_FEC_PROTECT, nullptr); EXPECT_EQ(1u, consumed.bytes_consumed); CheckPacketHasSingleStreamFrame(1); EXPECT_TRUE(QuicPacketCreatorPeer::IsFecProtected(creator_)); // Calling OnFecTimeout should cause the FEC packet to be emitted. EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); generator_.OnFecTimeout(); CheckPacketIsFec(2, 1); EXPECT_FALSE(QuicPacketCreatorPeer::IsFecProtected(creator_)); // Subsequent data is protected under the next FEC group. Send enough data to // create 2 more packets: one full and one partial. { InSequence dummy; EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); } size_t data_len = kDefaultMaxPacketSize + 1; consumed = generator_.ConsumeData(7, CreateData(data_len), 0, true, MUST_FEC_PROTECT, nullptr); EXPECT_EQ(data_len, consumed.bytes_consumed); EXPECT_TRUE(consumed.fin_consumed); CheckPacketHasSingleStreamFrame(3); CheckPacketHasSingleStreamFrame(4); EXPECT_TRUE(QuicPacketCreatorPeer::IsFecProtected(creator_)); // Calling OnFecTimeout should cause the FEC packet to be emitted. EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); generator_.OnFecTimeout(); CheckPacketIsFec(5, 4); EXPECT_FALSE(QuicPacketCreatorPeer::IsFecProtected(creator_)); } TEST_P(QuicPacketGeneratorTest, GetFecTimeoutFiniteOnlyOnFirstPacketInGroup) { delegate_.SetCanWriteAnything(); creator_->set_max_packets_per_fec_group(6); // Send enough data to create 2 packets: one full and one partial. Send with // MUST_FEC_PROTECT flag. No FEC packet is emitted yet, but the creator FEC // protects all data. { InSequence dummy; EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); } size_t data_len = 1 * kDefaultMaxPacketSize + 100; QuicConsumedData consumed = generator_.ConsumeData( 3, CreateData(data_len), 0, true, MUST_FEC_PROTECT, nullptr); EXPECT_EQ(data_len, consumed.bytes_consumed); EXPECT_TRUE(consumed.fin_consumed); EXPECT_FALSE(generator_.HasQueuedFrames()); CheckPacketHasSingleStreamFrame(0); CheckPacketHasSingleStreamFrame(1); EXPECT_TRUE(QuicPacketCreatorPeer::IsFecProtected(creator_)); // GetFecTimeout returns finite timeout only for first packet in group. EXPECT_EQ(QuicTime::Delta::FromMilliseconds(kMinFecTimeoutMs), generator_.GetFecTimeout(/*packet_number=*/1u)); EXPECT_EQ(QuicTime::Delta::Infinite(), generator_.GetFecTimeout(/*packet_number=*/2u)); // Send more data with MAY_FEC_PROTECT. This packet should also be protected, // and FEC packet is not yet sent. EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); consumed = generator_.ConsumeData(5, CreateData(1u), 0, true, MAY_FEC_PROTECT, nullptr); CheckPacketHasSingleStreamFrame(2); EXPECT_TRUE(QuicPacketCreatorPeer::IsFecProtected(creator_)); // GetFecTimeout returns finite timeout only for first packet in group. EXPECT_EQ(QuicTime::Delta::Infinite(), generator_.GetFecTimeout(/*packet_number=*/3u)); // Calling OnFecTimeout should cause the FEC packet to be emitted. EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); generator_.OnFecTimeout(); CheckPacketIsFec(3, /*fec_group=*/1u); EXPECT_FALSE(QuicPacketCreatorPeer::IsFecProtected(creator_)); // Subsequent data is protected under the next FEC group. Send enough data to // create 2 more packets: one full and one partial. { InSequence dummy; EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); } data_len = kDefaultMaxPacketSize + 1u; consumed = generator_.ConsumeData(7, CreateData(data_len), 0, true, MUST_FEC_PROTECT, nullptr); EXPECT_EQ(data_len, consumed.bytes_consumed); EXPECT_TRUE(consumed.fin_consumed); CheckPacketHasSingleStreamFrame(4); CheckPacketHasSingleStreamFrame(5); EXPECT_TRUE(QuicPacketCreatorPeer::IsFecProtected(creator_)); // GetFecTimeout returns finite timeout for first packet in the new group. EXPECT_EQ(QuicTime::Delta::FromMilliseconds(kMinFecTimeoutMs), generator_.GetFecTimeout(/*packet_number=*/5u)); EXPECT_EQ(QuicTime::Delta::Infinite(), generator_.GetFecTimeout(/*packet_number=*/6u)); // Calling OnFecTimeout should cause the FEC packet to be emitted. EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); generator_.OnFecTimeout(); CheckPacketIsFec(6, /*fec_group=*/5u); EXPECT_FALSE(QuicPacketCreatorPeer::IsFecProtected(creator_)); // Send more data with MAY_FEC_PROTECT. No FEC protection, so GetFecTimeout // returns infinite. EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); consumed = generator_.ConsumeData(9, CreateData(1u), 0, true, MAY_FEC_PROTECT, nullptr); CheckPacketHasSingleStreamFrame(7); EXPECT_FALSE(QuicPacketCreatorPeer::IsFecProtected(creator_)); EXPECT_EQ(QuicTime::Delta::Infinite(), generator_.GetFecTimeout(/*packet_number=*/8u)); } TEST_P(QuicPacketGeneratorTest, ConsumeData_FramesPreviouslyQueued) { // Set the packet size be enough for two stream frames with 0 stream offset, // but not enough for a stream frame of 0 offset and one with non-zero offset. size_t length = NullEncrypter().GetCiphertextSize(0) + GetPacketHeaderSize( creator_->connection_id_length(), true, /*include_path_id=*/false, QuicPacketCreatorPeer::NextPacketNumberLength(creator_), NOT_IN_FEC_GROUP) + // Add an extra 3 bytes for the payload and 1 byte so BytesFree is larger // than the GetMinStreamFrameSize. QuicFramer::GetMinStreamFrameSize(1, 0, false, NOT_IN_FEC_GROUP) + 3 + QuicFramer::GetMinStreamFrameSize(1, 0, true, NOT_IN_FEC_GROUP) + 1; generator_.SetMaxPacketLength(length, /*force=*/false); delegate_.SetCanWriteAnything(); { InSequence dummy; EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); } generator_.StartBatchOperations(); // Queue enough data to prevent a stream frame with a non-zero offset from // fitting. QuicConsumedData consumed = generator_.ConsumeData(kHeadersStreamId, MakeIOVector("foo"), 0, false, MAY_FEC_PROTECT, nullptr); EXPECT_EQ(3u, consumed.bytes_consumed); EXPECT_FALSE(consumed.fin_consumed); EXPECT_TRUE(generator_.HasQueuedFrames()); // This frame will not fit with the existing frame, causing the queued frame // to be serialized, and it will be added to a new open packet. consumed = generator_.ConsumeData(kHeadersStreamId, MakeIOVector("bar"), 3, true, MAY_FEC_PROTECT, nullptr); EXPECT_EQ(3u, consumed.bytes_consumed); EXPECT_TRUE(consumed.fin_consumed); EXPECT_TRUE(generator_.HasQueuedFrames()); creator_->Flush(); EXPECT_FALSE(generator_.HasQueuedFrames()); PacketContents contents; contents.num_stream_frames = 1; CheckPacketContains(contents, 0); CheckPacketContains(contents, 1); } TEST_P(QuicPacketGeneratorTest, NoFecPacketSentWhenBatchEnds) { delegate_.SetCanWriteAnything(); creator_->set_max_packets_per_fec_group(6); generator_.StartBatchOperations(); generator_.ConsumeData(3, MakeIOVector("foo"), 2, true, MUST_FEC_PROTECT, nullptr); QuicConsumedData consumed = generator_.ConsumeData( 5, MakeIOVector("quux"), 7, false, MUST_FEC_PROTECT, nullptr); EXPECT_EQ(4u, consumed.bytes_consumed); EXPECT_FALSE(consumed.fin_consumed); EXPECT_TRUE(generator_.HasQueuedFrames()); // Now both frames will be flushed out, but FEC packet is not yet sent. EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); generator_.FinishBatchOperations(); EXPECT_FALSE(generator_.HasQueuedFrames()); PacketContents contents; contents.num_stream_frames = 2u; contents.fec_group = 1u; CheckPacketContains(contents, 0); // Forcing FEC timeout causes FEC packet to be emitted. EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); generator_.OnFecTimeout(); CheckPacketIsFec(1, /*fec_group=*/1u); } TEST_P(QuicPacketGeneratorTest, FecTimeoutOnRttChange) { EXPECT_EQ(QuicTime::Delta::Zero(), QuicPacketCreatorPeer::GetFecTimeout(creator_)); generator_.OnRttChange(QuicTime::Delta::FromMilliseconds(300)); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(150), QuicPacketCreatorPeer::GetFecTimeout(creator_)); } TEST_P(QuicPacketGeneratorTest, FecGroupSizeOnCongestionWindowChange) { delegate_.SetCanWriteAnything(); creator_->set_max_packets_per_fec_group(50); EXPECT_EQ(50u, creator_->max_packets_per_fec_group()); EXPECT_FALSE(creator_->IsFecGroupOpen()); // On reduced cwnd. generator_.OnCongestionWindowChange(7); EXPECT_EQ(3u, creator_->max_packets_per_fec_group()); // On increased cwnd. generator_.OnCongestionWindowChange(100); EXPECT_EQ(50u, creator_->max_packets_per_fec_group()); // On collapsed cwnd. generator_.OnCongestionWindowChange(1); EXPECT_EQ(2u, creator_->max_packets_per_fec_group()); } TEST_P(QuicPacketGeneratorTest, FecGroupSizeChangeWithOpenGroup) { delegate_.SetCanWriteAnything(); generator_.StartBatchOperations(); creator_->set_max_packets_per_fec_group(50); EXPECT_EQ(50u, creator_->max_packets_per_fec_group()); EXPECT_FALSE(creator_->IsFecGroupOpen()); // Send enough data to create 4 packets with MUST_FEC_PROTECT flag. 3 packets // are sent, one is queued in the creator. { InSequence dummy; EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); } size_t data_len = 3 * kDefaultMaxPacketSize + 1; QuicConsumedData consumed = generator_.ConsumeData( 7, CreateData(data_len), 0, true, MUST_FEC_PROTECT, nullptr); EXPECT_EQ(data_len, consumed.bytes_consumed); EXPECT_TRUE(creator_->IsFecGroupOpen()); // Change FEC groupsize. generator_.OnCongestionWindowChange(2); EXPECT_EQ(2u, creator_->max_packets_per_fec_group()); // If FEC send policy is FEC_ANY_TRIGGER, then send enough data to trigger one // unprotected data packet, causing the FEC packet to also be sent. // // If FEC send policy is FEC_ALARM_TRIGGER, FEC group is closed and FEC packet // is not sent. { InSequence dummy; EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); if (generator_.fec_send_policy() == FEC_ALARM_TRIGGER) { EXPECT_CALL(delegate_, OnResetFecGroup()).Times(1); } else { EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); } } consumed = generator_.ConsumeData(7, CreateData(kDefaultMaxPacketSize), 0, true, MAY_FEC_PROTECT, nullptr); EXPECT_EQ(kDefaultMaxPacketSize, consumed.bytes_consumed); if (generator_.fec_send_policy() == FEC_ANY_TRIGGER) { // Verify that one FEC packet was sent. CheckPacketIsFec(4, /*fec_group=*/1u); } EXPECT_FALSE(creator_->IsFecGroupOpen()); EXPECT_FALSE(QuicPacketCreatorPeer::IsFecProtected(creator_)); } TEST_P(QuicPacketGeneratorTest, SwitchFecOnOff) { delegate_.SetCanWriteAnything(); creator_->set_max_packets_per_fec_group(2); EXPECT_FALSE(QuicPacketCreatorPeer::IsFecProtected(creator_)); // Send one unprotected data packet. EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); QuicConsumedData consumed = generator_.ConsumeData(5, CreateData(1u), 0, true, MAY_FEC_PROTECT, nullptr); EXPECT_EQ(1u, consumed.bytes_consumed); EXPECT_FALSE(generator_.HasQueuedFrames()); EXPECT_FALSE(QuicPacketCreatorPeer::IsFecProtected(creator_)); // Verify that one data packet was sent. PacketContents contents; contents.num_stream_frames = 1; CheckPacketContains(contents, 0); { InSequence dummy; EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); if (generator_.fec_send_policy() == FEC_ALARM_TRIGGER) { // If FEC send policy is FEC_ALARM_TRIGGER, FEC group is closed. EXPECT_CALL(delegate_, OnResetFecGroup()).Times(1); } else { EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); } EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); } // Send enough data to create 3 packets with MUST_FEC_PROTECT flag. size_t data_len = 2 * kDefaultMaxPacketSize + 100; consumed = generator_.ConsumeData(7, CreateData(data_len), 0, true, MUST_FEC_PROTECT, nullptr); EXPECT_EQ(data_len, consumed.bytes_consumed); EXPECT_FALSE(generator_.HasQueuedFrames()); // If FEC send policy is FEC_ANY_TRIGGER, verify that packets sent were 3 data // and 1 FEC. // // If FEC send policy is FEC_ALARM_TRIGGER, verify that packets sent were 3 // data and FEC group is closed. CheckPacketHasSingleStreamFrame(1); CheckPacketHasSingleStreamFrame(2); if (generator_.fec_send_policy() == FEC_ALARM_TRIGGER) { CheckPacketHasSingleStreamFrame(3); } else { CheckPacketIsFec(3, /*fec_group=*/2u); CheckPacketHasSingleStreamFrame(4); } // Calling OnFecTimeout should emit the pending FEC packet. EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); generator_.OnFecTimeout(); if (generator_.fec_send_policy() == FEC_ALARM_TRIGGER) { CheckPacketIsFec(4, /*fec_group=*/4u); } else { CheckPacketIsFec(5, /*fec_group=*/5u); } // Send one unprotected data packet. EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); consumed = generator_.ConsumeData(7, CreateData(1u), 0, true, MAY_FEC_PROTECT, nullptr); EXPECT_EQ(1u, consumed.bytes_consumed); EXPECT_FALSE(generator_.HasQueuedFrames()); EXPECT_FALSE(QuicPacketCreatorPeer::IsFecProtected(creator_)); // Verify that one unprotected data packet was sent. if (generator_.fec_send_policy() == FEC_ALARM_TRIGGER) { CheckPacketContains(contents, 5); } else { CheckPacketContains(contents, 6); } } TEST_P(QuicPacketGeneratorTest, SwitchFecOnWithPendingFrameInCreator) { delegate_.SetCanWriteAnything(); // Enable FEC. creator_->set_max_packets_per_fec_group(2); generator_.StartBatchOperations(); // Queue enough data to prevent a stream frame with a non-zero offset from // fitting. QuicConsumedData consumed = generator_.ConsumeData(7, CreateData(1u), 0, true, MAY_FEC_PROTECT, nullptr); EXPECT_EQ(1u, consumed.bytes_consumed); EXPECT_TRUE(creator_->HasPendingFrames()); // Queue protected data for sending. Should cause queued frames to be flushed. EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); EXPECT_FALSE(QuicPacketCreatorPeer::IsFecProtected(creator_)); consumed = generator_.ConsumeData(7, CreateData(1u), 0, true, MUST_FEC_PROTECT, nullptr); EXPECT_EQ(1u, consumed.bytes_consumed); PacketContents contents; contents.num_stream_frames = 1; // Transmitted packet was not FEC protected. CheckPacketContains(contents, 0); EXPECT_TRUE(QuicPacketCreatorPeer::IsFecProtected(creator_)); EXPECT_TRUE(creator_->HasPendingFrames()); } TEST_P(QuicPacketGeneratorTest, SwitchFecOnWithPendingFramesInGenerator) { // Enable FEC. creator_->set_max_packets_per_fec_group(2); // Queue control frames in generator. delegate_.SetCanNotWrite(); generator_.SetShouldSendAck(true); delegate_.SetCanWriteAnything(); generator_.StartBatchOperations(); // Set up frames to write into the creator when control frames are written. EXPECT_CALL(delegate_, PopulateAckFrame(_)); EXPECT_CALL(delegate_, PopulateStopWaitingFrame(_)); // Generator should have queued control frames, and creator should be empty. EXPECT_TRUE(generator_.HasQueuedFrames()); EXPECT_FALSE(creator_->HasPendingFrames()); EXPECT_FALSE(QuicPacketCreatorPeer::IsFecProtected(creator_)); // Queue protected data for sending. Should cause queued frames to be flushed. EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); QuicConsumedData consumed = generator_.ConsumeData(7, CreateData(1u), 0, true, MUST_FEC_PROTECT, nullptr); EXPECT_EQ(1u, consumed.bytes_consumed); PacketContents contents; contents.num_ack_frames = 1; contents.num_stop_waiting_frames = 1; CheckPacketContains(contents, 0); // FEC protection should be on in creator. EXPECT_TRUE(QuicPacketCreatorPeer::IsFecProtected(creator_)); } TEST_P(QuicPacketGeneratorTest, SwitchFecOnOffWithSubsequentFramesProtected) { delegate_.SetCanWriteAnything(); // Enable FEC. creator_->set_max_packets_per_fec_group(2); EXPECT_FALSE(QuicPacketCreatorPeer::IsFecProtected(creator_)); // Queue stream frame to be protected in creator. generator_.StartBatchOperations(); QuicConsumedData consumed = generator_.ConsumeData(5, CreateData(1u), 0, true, MUST_FEC_PROTECT, nullptr); EXPECT_EQ(1u, consumed.bytes_consumed); // Creator has a pending protected frame. EXPECT_TRUE(creator_->HasPendingFrames()); EXPECT_TRUE(QuicPacketCreatorPeer::IsFecProtected(creator_)); // Add enough unprotected data to exceed size of current packet, so that // current packet is sent. Both frames will be sent out in a single packet. EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); size_t data_len = kDefaultMaxPacketSize; consumed = generator_.ConsumeData(5, CreateData(data_len), 0, true, MAY_FEC_PROTECT, nullptr); EXPECT_EQ(data_len, consumed.bytes_consumed); PacketContents contents; contents.num_stream_frames = 2u; contents.fec_group = 1u; CheckPacketContains(contents, 0); // FEC protection should still be on in creator. EXPECT_TRUE(QuicPacketCreatorPeer::IsFecProtected(creator_)); } TEST_P(QuicPacketGeneratorTest, SwitchFecOnOffWithSubsequentPacketsProtected) { delegate_.SetCanWriteAnything(); // Enable FEC. creator_->set_max_packets_per_fec_group(2); EXPECT_FALSE(QuicPacketCreatorPeer::IsFecProtected(creator_)); // Send first packet, FEC protected. EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); QuicConsumedData consumed = generator_.ConsumeData(5, CreateData(1u), 0, true, MUST_FEC_PROTECT, nullptr); EXPECT_EQ(1u, consumed.bytes_consumed); PacketContents contents; contents.num_stream_frames = 1u; contents.fec_group = 1u; CheckPacketContains(contents, 0); // FEC should still be on in creator. EXPECT_TRUE(QuicPacketCreatorPeer::IsFecProtected(creator_)); // Send unprotected data to cause second packet to be sent, which gets // protected because it happens to fall within an open FEC group. Data packet // will be followed by FEC packet. { InSequence dummy; EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); if (generator_.fec_send_policy() == FEC_ALARM_TRIGGER) { EXPECT_CALL(delegate_, OnResetFecGroup()).Times(1); } else { EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); } } consumed = generator_.ConsumeData(5, CreateData(1u), 0, true, MAY_FEC_PROTECT, nullptr); EXPECT_EQ(1u, consumed.bytes_consumed); contents.num_stream_frames = 1u; CheckPacketContains(contents, 1); if (generator_.fec_send_policy() == FEC_ANY_TRIGGER) { // FEC packet is sent when send policy is FEC_ANY_TRIGGER. CheckPacketIsFec(2, /*fec_group=*/1u); } // FEC protection should be off in creator. EXPECT_FALSE(QuicPacketCreatorPeer::IsFecProtected(creator_)); } TEST_P(QuicPacketGeneratorTest, SwitchFecOnOffThenOnWithCreatorProtectionOn) { delegate_.SetCanWriteAnything(); generator_.StartBatchOperations(); // Enable FEC. creator_->set_max_packets_per_fec_group(2); EXPECT_FALSE(QuicPacketCreatorPeer::IsFecProtected(creator_)); // Queue one byte of FEC protected data. QuicConsumedData consumed = generator_.ConsumeData(5, CreateData(1u), 0, true, MUST_FEC_PROTECT, nullptr); EXPECT_TRUE(creator_->HasPendingFrames()); // Add more unprotected data causing first packet to be sent, FEC protected. EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); size_t data_len = kDefaultMaxPacketSize; consumed = generator_.ConsumeData(5, CreateData(data_len), 0, true, MAY_FEC_PROTECT, nullptr); EXPECT_EQ(data_len, consumed.bytes_consumed); PacketContents contents; contents.num_stream_frames = 2u; contents.fec_group = 1u; CheckPacketContains(contents, 0); // FEC group is still open in creator. EXPECT_TRUE(QuicPacketCreatorPeer::IsFecProtected(creator_)); // Add data that should be protected, large enough to cause second packet to // be sent. Data packet should be followed by FEC packet. { InSequence dummy; EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); if (generator_.fec_send_policy() == FEC_ALARM_TRIGGER) { EXPECT_CALL(delegate_, OnResetFecGroup()).Times(1); } else { EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); } } consumed = generator_.ConsumeData(5, CreateData(data_len), 0, true, MUST_FEC_PROTECT, nullptr); EXPECT_EQ(data_len, consumed.bytes_consumed); CheckPacketContains(contents, 1); if (generator_.fec_send_policy() == FEC_ANY_TRIGGER) { // FEC packet is sent when send policy is FEC_ANY_TRIGGER. CheckPacketIsFec(2, /*fec_group=*/1u); } // FEC protection should remain on in creator. EXPECT_TRUE(QuicPacketCreatorPeer::IsFecProtected(creator_)); } TEST_P(QuicPacketGeneratorTest, ResetFecGroupNoTimeout) { delegate_.SetCanWriteAnything(); // Send FEC packet after 2 packets. creator_->set_max_packets_per_fec_group(2); EXPECT_FALSE(QuicPacketCreatorPeer::IsFecProtected(creator_)); // Send two packets so that when this data is consumed, two packets are sent // out. In FEC_TRIGGER_ANY, this will cause an FEC packet to be sent out and // with FEC_TRIGGER_ALARM, this will cause a Reset to be called. In both // cases, the creator's fec protection will be turned off afterwards. { InSequence dummy; EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); if (generator_.fec_send_policy() == FEC_ALARM_TRIGGER) { // FEC packet is not sent when send policy is FEC_ALARM_TRIGGER, but FEC // group is closed. EXPECT_CALL(delegate_, OnResetFecGroup()).Times(1); } else { EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); } // Fin Packet. EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); } size_t data_len = 2 * kDefaultMaxPacketSize; QuicConsumedData consumed = generator_.ConsumeData( 5, CreateData(data_len), 0, true, MUST_FEC_PROTECT, nullptr); EXPECT_EQ(data_len, consumed.bytes_consumed); EXPECT_TRUE(consumed.fin_consumed); EXPECT_FALSE(generator_.HasQueuedFrames()); CheckPacketHasSingleStreamFrame(0); CheckPacketHasSingleStreamFrame(1); if (generator_.fec_send_policy() == FEC_ALARM_TRIGGER) { // FEC packet is not sent when send policy is FEC_ALARM_TRIGGER. CheckPacketHasSingleStreamFrame(2); } else { // FEC packet is sent after 2 packets and when send policy is // FEC_ANY_TRIGGER. CheckPacketIsFec(2, 1); CheckPacketHasSingleStreamFrame(3); } EXPECT_TRUE(QuicPacketCreatorPeer::IsFecProtected(creator_)); // Do the same send (with MUST_FEC_PROTECT) on a different stream id. { InSequence dummy; EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); // FEC packet is sent after 2 packets and when send policy is // FEC_ANY_TRIGGER. When policy is FEC_ALARM_TRIGGER, FEC group is closed // and FEC packet is not sent. if (generator_.fec_send_policy() == FEC_ALARM_TRIGGER) { EXPECT_CALL(delegate_, OnResetFecGroup()).Times(1); } else { EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); } EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); // FEC packet is sent after 2 packets and when send policy is // FEC_ANY_TRIGGER. When policy is FEC_ALARM_TRIGGER, FEC group is closed // and FEC packet is not sent. if (generator_.fec_send_policy() == FEC_ALARM_TRIGGER) { EXPECT_CALL(delegate_, OnResetFecGroup()).Times(1); } else { EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); } } consumed = generator_.ConsumeData(7, CreateData(data_len), 0, true, MUST_FEC_PROTECT, nullptr); EXPECT_EQ(data_len, consumed.bytes_consumed); EXPECT_TRUE(consumed.fin_consumed); EXPECT_FALSE(generator_.HasQueuedFrames()); if (generator_.fec_send_policy() == FEC_ALARM_TRIGGER) { CheckPacketHasSingleStreamFrame(3); CheckPacketHasSingleStreamFrame(4); CheckPacketHasSingleStreamFrame(5); } else { CheckPacketHasSingleStreamFrame(4); // FEC packet is sent after 2 packets and when send policy is // FEC_ANY_TRIGGER. CheckPacketIsFec(5, 4); CheckPacketHasSingleStreamFrame(6); CheckPacketHasSingleStreamFrame(7); // FEC packet is sent after 2 packets and when send policy is // FEC_ANY_TRIGGER. CheckPacketIsFec(8, 7); } EXPECT_FALSE(QuicPacketCreatorPeer::IsFecProtected(creator_)); // Do the another send (with MAY_FEC_PROTECT) on a different stream id, which // should not produce an FEC packet because the last FEC group has been // closed. { InSequence dummy; EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); } consumed = generator_.ConsumeData(9, CreateData(data_len), 0, true, MAY_FEC_PROTECT, nullptr); EXPECT_EQ(data_len, consumed.bytes_consumed); EXPECT_TRUE(consumed.fin_consumed); EXPECT_FALSE(generator_.HasQueuedFrames()); if (generator_.fec_send_policy() == FEC_ALARM_TRIGGER) { CheckPacketHasSingleStreamFrame(6); CheckPacketHasSingleStreamFrame(7); CheckPacketHasSingleStreamFrame(8); } else { CheckPacketHasSingleStreamFrame(9); CheckPacketHasSingleStreamFrame(10); CheckPacketHasSingleStreamFrame(11); } EXPECT_FALSE(QuicPacketCreatorPeer::IsFecProtected(creator_)); } // 1. Create and send one packet with MUST_FEC_PROTECT. // 2. Call FecTimeout, expect FEC packet is sent. // 3. Do the same thing over again, with a different stream id. TEST_P(QuicPacketGeneratorTest, FecPacketSentOnFecTimeout) { delegate_.SetCanWriteAnything(); creator_->set_max_packets_per_fec_group(1000); EXPECT_FALSE(QuicPacketCreatorPeer::IsFecProtected(creator_)); for (int i = 1; i < 4; i = i + 2) { // Send data with MUST_FEC_PROTECT flag. No FEC packet is emitted, but the // creator FEC protects all data. EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); QuicConsumedData consumed = generator_.ConsumeData( i + 2, CreateData(1u), 0, true, MUST_FEC_PROTECT, nullptr); EXPECT_EQ(1u, consumed.bytes_consumed); EXPECT_TRUE(consumed.fin_consumed); CheckPacketHasSingleStreamFrame(0); EXPECT_TRUE(QuicPacketCreatorPeer::IsFecProtected(creator_)); // Calling OnFecTimeout should cause the FEC packet to be emitted. EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); generator_.OnFecTimeout(); CheckPacketIsFec(i, i); EXPECT_FALSE(QuicPacketCreatorPeer::IsFecProtected(creator_)); } } TEST_P(QuicPacketGeneratorTest, NotWritableThenBatchOperations) { delegate_.SetCanNotWrite(); generator_.SetShouldSendAck(false); generator_.AddControlFrame(QuicFrame(CreateRstStreamFrame())); EXPECT_TRUE(generator_.HasQueuedFrames()); delegate_.SetCanWriteAnything(); generator_.StartBatchOperations(); // When the first write operation is invoked, the ack frame will be returned. EXPECT_CALL(delegate_, PopulateAckFrame(_)); // Send some data and a control frame generator_.ConsumeData(3, MakeIOVector("quux"), 7, false, MAY_FEC_PROTECT, nullptr); generator_.AddControlFrame(QuicFrame(CreateGoAwayFrame())); // All five frames will be flushed out in a single packet. EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); generator_.FinishBatchOperations(); EXPECT_FALSE(generator_.HasQueuedFrames()); PacketContents contents; contents.num_ack_frames = 1; contents.num_goaway_frames = 1; contents.num_rst_stream_frames = 1; contents.num_stream_frames = 1; CheckPacketContains(contents, 0); } TEST_P(QuicPacketGeneratorTest, NotWritableThenBatchOperations2) { delegate_.SetCanNotWrite(); generator_.SetShouldSendAck(false); generator_.AddControlFrame(QuicFrame(CreateRstStreamFrame())); EXPECT_TRUE(generator_.HasQueuedFrames()); delegate_.SetCanWriteAnything(); generator_.StartBatchOperations(); // When the first write operation is invoked, the ack frame will be returned. EXPECT_CALL(delegate_, PopulateAckFrame(_)); { InSequence dummy; // All five frames will be flushed out in a single packet EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); } // Send enough data to exceed one packet size_t data_len = kDefaultMaxPacketSize + 100; QuicConsumedData consumed = generator_.ConsumeData( 3, CreateData(data_len), 0, true, MAY_FEC_PROTECT, nullptr); EXPECT_EQ(data_len, consumed.bytes_consumed); EXPECT_TRUE(consumed.fin_consumed); generator_.AddControlFrame(QuicFrame(CreateGoAwayFrame())); generator_.FinishBatchOperations(); EXPECT_FALSE(generator_.HasQueuedFrames()); // The first packet should have the queued data and part of the stream data. PacketContents contents; contents.num_ack_frames = 1; contents.num_rst_stream_frames = 1; contents.num_stream_frames = 1; CheckPacketContains(contents, 0); // The second should have the remainder of the stream data. PacketContents contents2; contents2.num_goaway_frames = 1; contents2.num_stream_frames = 1; CheckPacketContains(contents2, 1); } TEST_P(QuicPacketGeneratorTest, TestConnectionIdLength) { generator_.SetConnectionIdLength(0); EXPECT_EQ(PACKET_0BYTE_CONNECTION_ID, creator_->connection_id_length()); generator_.SetConnectionIdLength(1); EXPECT_EQ(PACKET_1BYTE_CONNECTION_ID, creator_->connection_id_length()); generator_.SetConnectionIdLength(2); EXPECT_EQ(PACKET_4BYTE_CONNECTION_ID, creator_->connection_id_length()); generator_.SetConnectionIdLength(3); EXPECT_EQ(PACKET_4BYTE_CONNECTION_ID, creator_->connection_id_length()); generator_.SetConnectionIdLength(4); EXPECT_EQ(PACKET_4BYTE_CONNECTION_ID, creator_->connection_id_length()); generator_.SetConnectionIdLength(5); EXPECT_EQ(PACKET_8BYTE_CONNECTION_ID, creator_->connection_id_length()); generator_.SetConnectionIdLength(6); EXPECT_EQ(PACKET_8BYTE_CONNECTION_ID, creator_->connection_id_length()); generator_.SetConnectionIdLength(7); EXPECT_EQ(PACKET_8BYTE_CONNECTION_ID, creator_->connection_id_length()); generator_.SetConnectionIdLength(8); EXPECT_EQ(PACKET_8BYTE_CONNECTION_ID, creator_->connection_id_length()); generator_.SetConnectionIdLength(9); EXPECT_EQ(PACKET_8BYTE_CONNECTION_ID, creator_->connection_id_length()); } // Test whether SetMaxPacketLength() works in the situation when the queue is // empty, and we send three packets worth of data. TEST_P(QuicPacketGeneratorTest, SetMaxPacketLength_Initial) { delegate_.SetCanWriteAnything(); // Send enough data for three packets. size_t data_len = 3 * kDefaultMaxPacketSize + 1; size_t packet_len = kDefaultMaxPacketSize + 100; ASSERT_LE(packet_len, kMaxPacketSize); generator_.SetMaxPacketLength(packet_len, /*force=*/false); EXPECT_EQ(packet_len, generator_.GetCurrentMaxPacketLength()); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .Times(3) .WillRepeatedly(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); QuicConsumedData consumed = generator_.ConsumeData(kHeadersStreamId, CreateData(data_len), /*offset=*/2, /*fin=*/true, MAY_FEC_PROTECT, nullptr); EXPECT_EQ(data_len, consumed.bytes_consumed); EXPECT_TRUE(consumed.fin_consumed); EXPECT_FALSE(generator_.HasQueuedFrames()); // We expect three packets, and first two of them have to be of packet_len // size. We check multiple packets (instead of just one) because we want to // ensure that |max_packet_length_| does not get changed incorrectly by the // generator after first packet is serialized. ASSERT_EQ(3u, packets_.size()); EXPECT_EQ(packet_len, packets_[0].packet->length()); EXPECT_EQ(packet_len, packets_[1].packet->length()); CheckAllPacketsHaveSingleStreamFrame(); } // Test whether SetMaxPacketLength() works in the situation when we first write // data, then change packet size, then write data again. TEST_P(QuicPacketGeneratorTest, SetMaxPacketLength_Middle) { delegate_.SetCanWriteAnything(); // We send enough data to overflow default packet length, but not the altered // one. size_t data_len = kDefaultMaxPacketSize; size_t packet_len = kDefaultMaxPacketSize + 100; ASSERT_LE(packet_len, kMaxPacketSize); // We expect to see three packets in total. EXPECT_CALL(delegate_, OnSerializedPacket(_)) .Times(3) .WillRepeatedly(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); // Send two packets before packet size change. QuicConsumedData consumed = generator_.ConsumeData(kHeadersStreamId, CreateData(data_len), /*offset=*/2, /*fin=*/false, MAY_FEC_PROTECT, nullptr); EXPECT_EQ(data_len, consumed.bytes_consumed); EXPECT_FALSE(consumed.fin_consumed); EXPECT_FALSE(generator_.HasQueuedFrames()); // Make sure we already have two packets. ASSERT_EQ(2u, packets_.size()); // Increase packet size. generator_.SetMaxPacketLength(packet_len, /*force=*/false); EXPECT_EQ(packet_len, generator_.GetCurrentMaxPacketLength()); // Send a packet after packet size change. consumed = generator_.ConsumeData(kHeadersStreamId, CreateData(data_len), 2 + data_len, /*fin=*/true, MAY_FEC_PROTECT, nullptr); EXPECT_EQ(data_len, consumed.bytes_consumed); EXPECT_TRUE(consumed.fin_consumed); EXPECT_FALSE(generator_.HasQueuedFrames()); // We expect first data chunk to get fragmented, but the second one to fit // into a single packet. ASSERT_EQ(3u, packets_.size()); EXPECT_EQ(kDefaultMaxPacketSize, packets_[0].packet->length()); EXPECT_LE(kDefaultMaxPacketSize, packets_[2].packet->length()); CheckAllPacketsHaveSingleStreamFrame(); } // Test whether SetMaxPacketLength() works correctly when we change the packet // size in the middle of the batched packet. TEST_P(QuicPacketGeneratorTest, SetMaxPacketLength_Midpacket) { delegate_.SetCanWriteAnything(); generator_.StartBatchOperations(); size_t first_write_len = kDefaultMaxPacketSize / 2; size_t second_write_len = kDefaultMaxPacketSize; size_t packet_len = kDefaultMaxPacketSize + 100; ASSERT_LE(packet_len, kMaxPacketSize); // First send half of the packet worth of data. We are in the batch mode, so // should not cause packet serialization. QuicConsumedData consumed = generator_.ConsumeData(kHeadersStreamId, CreateData(first_write_len), /*offset=*/2, /*fin=*/false, MAY_FEC_PROTECT, nullptr); EXPECT_EQ(first_write_len, consumed.bytes_consumed); EXPECT_FALSE(consumed.fin_consumed); EXPECT_TRUE(generator_.HasQueuedFrames()); // Make sure we have no packets so far. ASSERT_EQ(0u, packets_.size()); // Increase packet size. Ensure it's not immediately enacted. generator_.SetMaxPacketLength(packet_len, /*force=*/false); EXPECT_EQ(packet_len, generator_.GetMaxPacketLength()); EXPECT_EQ(kDefaultMaxPacketSize, generator_.GetCurrentMaxPacketLength()); // We expect to see exactly one packet serialized after that, since we are in // batch mode and we have sent approximately 3/2 of our MTU. EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); // Send a packet worth of data to the same stream. This should trigger // serialization of other packet. consumed = generator_.ConsumeData(kHeadersStreamId, CreateData(second_write_len), /*offset=*/2 + first_write_len, /*fin=*/true, MAY_FEC_PROTECT, nullptr); EXPECT_EQ(second_write_len, consumed.bytes_consumed); EXPECT_TRUE(consumed.fin_consumed); EXPECT_TRUE(generator_.HasQueuedFrames()); // We expect the first packet to contain two frames, and to not reflect the // packet size change. ASSERT_EQ(1u, packets_.size()); EXPECT_EQ(kDefaultMaxPacketSize, packets_[0].packet->length()); PacketContents contents; contents.num_stream_frames = 2; CheckPacketContains(contents, 0); } // Test whether SetMaxPacketLength() works correctly when we force the change of // the packet size in the middle of the batched packet. TEST_P(QuicPacketGeneratorTest, SetMaxPacketLength_MidpacketFlush) { delegate_.SetCanWriteAnything(); generator_.StartBatchOperations(); size_t first_write_len = kDefaultMaxPacketSize / 2; size_t packet_len = kDefaultMaxPacketSize + 100; size_t second_write_len = packet_len + 1; ASSERT_LE(packet_len, kMaxPacketSize); // First send half of the packet worth of data. We are in the batch mode, so // should not cause packet serialization. QuicConsumedData consumed = generator_.ConsumeData(kHeadersStreamId, CreateData(first_write_len), /*offset=*/2, /*fin=*/false, MAY_FEC_PROTECT, nullptr); EXPECT_EQ(first_write_len, consumed.bytes_consumed); EXPECT_FALSE(consumed.fin_consumed); EXPECT_TRUE(generator_.HasQueuedFrames()); // Make sure we have no packets so far. ASSERT_EQ(0u, packets_.size()); // Expect a packet to be flushed. EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); // Increase packet size. Ensure it's immediately enacted. generator_.SetMaxPacketLength(packet_len, /*force=*/true); EXPECT_EQ(packet_len, generator_.GetMaxPacketLength()); EXPECT_EQ(packet_len, generator_.GetCurrentMaxPacketLength()); EXPECT_FALSE(generator_.HasQueuedFrames()); // We expect to see exactly one packet serialized after that, because we send // a value somewhat exceeding new max packet size, and the tail data does not // get serialized because we are still in the batch mode. EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); // Send a more than a packet worth of data to the same stream. This should // trigger serialization of one packet, and queue another one. consumed = generator_.ConsumeData(kHeadersStreamId, CreateData(second_write_len), /*offset=*/2 + first_write_len, /*fin=*/true, MAY_FEC_PROTECT, nullptr); EXPECT_EQ(second_write_len, consumed.bytes_consumed); EXPECT_TRUE(consumed.fin_consumed); EXPECT_TRUE(generator_.HasQueuedFrames()); // We expect the first packet to be underfilled, and the second packet be up // to the new max packet size. ASSERT_EQ(2u, packets_.size()); EXPECT_GT(kDefaultMaxPacketSize, packets_[0].packet->length()); EXPECT_EQ(packet_len, packets_[1].packet->length()); CheckAllPacketsHaveSingleStreamFrame(); } // Test sending an MTU probe, without any surrounding data. TEST_P(QuicPacketGeneratorTest, GenerateMtuDiscoveryPacket_Simple) { delegate_.SetCanWriteAnything(); const size_t target_mtu = kDefaultMaxPacketSize + 100; static_assert(target_mtu < kMaxPacketSize, "The MTU probe used by the test exceeds maximum packet size"); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); generator_.GenerateMtuDiscoveryPacket(target_mtu, nullptr); EXPECT_FALSE(generator_.HasQueuedFrames()); ASSERT_EQ(1u, packets_.size()); EXPECT_EQ(target_mtu, packets_[0].packet->length()); PacketContents contents; contents.num_mtu_discovery_frames = 1; CheckPacketContains(contents, 0); } // Test sending an MTU probe. Surround it with data, to ensure that it resets // the MTU to the value before the probe was sent. TEST_P(QuicPacketGeneratorTest, GenerateMtuDiscoveryPacket_SurroundedByData) { delegate_.SetCanWriteAnything(); const size_t target_mtu = kDefaultMaxPacketSize + 100; static_assert(target_mtu < kMaxPacketSize, "The MTU probe used by the test exceeds maximum packet size"); // Send enough data so it would always cause two packets to be sent. const size_t data_len = target_mtu + 1; // Send a total of five packets: two packets before the probe, the probe // itself, and two packets after the probe. EXPECT_CALL(delegate_, OnSerializedPacket(_)) .Times(5) .WillRepeatedly(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); // Send data before the MTU probe. QuicConsumedData consumed = generator_.ConsumeData(kHeadersStreamId, CreateData(data_len), /*offset=*/2, /*fin=*/false, MAY_FEC_PROTECT, nullptr); EXPECT_EQ(data_len, consumed.bytes_consumed); EXPECT_FALSE(consumed.fin_consumed); EXPECT_FALSE(generator_.HasQueuedFrames()); // Send the MTU probe. generator_.GenerateMtuDiscoveryPacket(target_mtu, nullptr); EXPECT_FALSE(generator_.HasQueuedFrames()); // Send data after the MTU probe. consumed = generator_.ConsumeData(kHeadersStreamId, CreateData(data_len), /*offset=*/2 + data_len, /*fin=*/true, MAY_FEC_PROTECT, nullptr); EXPECT_EQ(data_len, consumed.bytes_consumed); EXPECT_TRUE(consumed.fin_consumed); EXPECT_FALSE(generator_.HasQueuedFrames()); ASSERT_EQ(5u, packets_.size()); EXPECT_EQ(kDefaultMaxPacketSize, packets_[0].packet->length()); EXPECT_EQ(target_mtu, packets_[2].packet->length()); EXPECT_EQ(kDefaultMaxPacketSize, packets_[3].packet->length()); PacketContents probe_contents; probe_contents.num_mtu_discovery_frames = 1; CheckPacketHasSingleStreamFrame(0); CheckPacketHasSingleStreamFrame(1); CheckPacketContains(probe_contents, 2); CheckPacketHasSingleStreamFrame(3); CheckPacketHasSingleStreamFrame(4); } TEST_P(QuicPacketGeneratorTest, DontCrashOnInvalidStopWaiting) { // Test added to ensure the generator does not crash when an invalid frame is // added. Because this is an indication of internal programming errors, // DFATALs are expected. // A 1 byte packet number length can't encode a gap of 1000. QuicPacketCreatorPeer::SetPacketNumber(creator_, 1000); delegate_.SetCanNotWrite(); generator_.SetShouldSendAck(true); delegate_.SetCanWriteAnything(); generator_.StartBatchOperations(); // Set up frames to write into the creator when control frames are written. EXPECT_CALL(delegate_, PopulateAckFrame(_)); EXPECT_CALL(delegate_, PopulateStopWaitingFrame(_)); // Generator should have queued control frames, and creator should be empty. EXPECT_TRUE(generator_.HasQueuedFrames()); EXPECT_FALSE(creator_->HasPendingFrames()); // This will not serialize any packets, because of the invalid frame. EXPECT_CALL(delegate_, CloseConnection(QUIC_FAILED_TO_SERIALIZE_PACKET, false)); EXPECT_DFATAL(generator_.FinishBatchOperations(), "packet_number_length 1 is too small " "for least_unacked_delta: 1001"); } TEST_P(QuicPacketGeneratorTest, SetCurrentPath) { delegate_.SetCanWriteAnything(); generator_.StartBatchOperations(); QuicConsumedData consumed = generator_.ConsumeData( kHeadersStreamId, MakeIOVector("foo"), 2, true, MAY_FEC_PROTECT, nullptr); EXPECT_EQ(3u, consumed.bytes_consumed); EXPECT_TRUE(consumed.fin_consumed); EXPECT_TRUE(generator_.HasQueuedFrames()); EXPECT_EQ(kDefaultPathId, QuicPacketCreatorPeer::GetCurrentPath(creator_)); // Does not change current path. generator_.SetCurrentPath(kDefaultPathId, 1, 0); EXPECT_EQ(kDefaultPathId, QuicPacketCreatorPeer::GetCurrentPath(creator_)); // Try to switch path when a packet is under construction. QuicPathId kTestPathId1 = 1; EXPECT_DFATAL(generator_.SetCurrentPath(kTestPathId1, 1, 0), "Unable to change paths when a packet is under construction"); EXPECT_EQ(kDefaultPathId, QuicPacketCreatorPeer::GetCurrentPath(creator_)); // Try to switch path after current open packet gets serialized. EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketGeneratorTest::SavePacket)); generator_.FlushAllQueuedFrames(); EXPECT_FALSE(generator_.HasQueuedFrames()); generator_.SetCurrentPath(kTestPathId1, 1, 0); EXPECT_EQ(kTestPathId1, QuicPacketCreatorPeer::GetCurrentPath(creator_)); } } // namespace test } // namespace net
40.440047
80
0.741119
[ "vector" ]
4bdf2a8499f5f4133aa2327baa841e1d6d2229fa
2,946
cpp
C++
UnicornRender/video/source/vulkan/VkMesh.cpp
GrapefruitTechnique/R7
3eaa97ac63bbc1b42e4cabf97d4d12649e36f665
[ "MIT" ]
12
2017-02-18T15:17:53.000Z
2020-02-03T16:20:33.000Z
UnicornRender/video/source/vulkan/VkMesh.cpp
GrapefruitTechnique/R7
3eaa97ac63bbc1b42e4cabf97d4d12649e36f665
[ "MIT" ]
93
2017-02-15T21:05:31.000Z
2020-08-19T06:46:27.000Z
UnicornRender/video/source/vulkan/VkMesh.cpp
GrapefruitTechnique/R-7
3eaa97ac63bbc1b42e4cabf97d4d12649e36f665
[ "MIT" ]
4
2015-10-23T11:55:07.000Z
2016-11-30T10:00:52.000Z
/* * Copyright (C) 2017 by Godlike * This code is licensed under the MIT license (MIT) * (http://opensource.org/licenses/MIT) */ #include <unicorn/video/vulkan/VkMesh.hpp> #include <unicorn/video/Material.hpp> namespace unicorn { namespace video { namespace vulkan { VkMesh::VkMesh(vk::Device device, vk::PhysicalDevice physicalDevice, vk::CommandPool pool, vk::Queue queue, Mesh& mesh) : m_valid(false) , m_device(device) , m_physicalDevice(physicalDevice) , m_pool(pool) , m_queue(queue) , m_mesh(mesh) { m_mesh.MaterialUpdated.connect(this, &VkMesh::OnMaterialUpdated); m_mesh.VerticesUpdated.connect(this, &VkMesh::AllocateOnGPU); } VkMesh::~VkMesh() { DeallocateOnGPU(); m_mesh.VerticesUpdated.disconnect(this, &VkMesh::AllocateOnGPU); m_mesh.MaterialUpdated.disconnect(this, &VkMesh::OnMaterialUpdated); } bool VkMesh::operator==(const Mesh& mesh) const { return &mesh == &m_mesh; } const glm::mat4& VkMesh::GetModelMatrix() const { return m_mesh.GetModelMatrix(); } Mesh const& VkMesh::GetMesh() const { return m_mesh; } void VkMesh::AllocateOnGPU() { m_vertexBuffer.Destroy(); m_indexBuffer.Destroy(); Buffer stagingBuffer; //Vertexes filling auto size = sizeof(m_mesh.GetVertices()[0]) * m_mesh.GetVertices().size(); stagingBuffer.Create(m_physicalDevice, m_device, vk::BufferUsageFlagBits::eTransferSrc, vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent, size); m_vertexBuffer.Create(m_physicalDevice, m_device, vk::BufferUsageFlagBits::eVertexBuffer | vk::BufferUsageFlagBits::eTransferDst, vk::MemoryPropertyFlagBits::eDeviceLocal, size); stagingBuffer.Map(); stagingBuffer.Write(m_mesh.GetVertices().data()); stagingBuffer.CopyToBuffer(m_pool, m_queue, m_vertexBuffer, m_vertexBuffer.GetSize()); stagingBuffer.Destroy(); //Indexes filling size = sizeof(m_mesh.GetIndices()[0]) * m_mesh.GetIndices().size(); stagingBuffer.Create(m_physicalDevice, m_device, vk::BufferUsageFlagBits::eTransferSrc, vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent, size); stagingBuffer.Map(); m_indexBuffer.Create(m_physicalDevice, m_device, vk::BufferUsageFlagBits::eIndexBuffer | vk::BufferUsageFlagBits::eTransferDst, vk::MemoryPropertyFlagBits::eDeviceLocal, size); stagingBuffer.Write(m_mesh.GetIndices().data()); stagingBuffer.CopyToBuffer(m_pool, m_queue, m_indexBuffer, m_indexBuffer.GetSize()); stagingBuffer.Destroy(); m_valid = true; ReallocatedOnGpu.emit(this); } void VkMesh::DeallocateOnGPU() { m_vertexBuffer.Destroy(); m_indexBuffer.Destroy(); } vk::Buffer VkMesh::GetVertexBuffer() const { return m_vertexBuffer.GetVkBuffer(); } vk::Buffer VkMesh::GetIndexBuffer() const { return m_indexBuffer.GetVkBuffer(); } void VkMesh::OnMaterialUpdated() { MaterialUpdated.emit(&m_mesh, this); } } } }
29.168317
184
0.738289
[ "mesh" ]
4be003e75bf7f7edd91a2d33e0c38f1134360592
3,374
cpp
C++
src/solver/AdvectionSolver.cpp
Ozaq/ARTSS
32fc99623bf06db3ceb89fe20504867ccf28959d
[ "MIT" ]
null
null
null
src/solver/AdvectionSolver.cpp
Ozaq/ARTSS
32fc99623bf06db3ceb89fe20504867ccf28959d
[ "MIT" ]
null
null
null
src/solver/AdvectionSolver.cpp
Ozaq/ARTSS
32fc99623bf06db3ceb89fe20504867ccf28959d
[ "MIT" ]
null
null
null
/// \file AdvectionSolver.cpp /// \brief Defines the steps to solve the advection equation /// \date August 22, 2016 /// \author Severt /// \copyright <2015-2020> Forschungszentrum Juelich GmbH. All rights reserved. #include <string> #include <vector> #include <algorithm> #include "AdvectionSolver.h" #include "../interfaces/IAdvection.h" #include "../DomainData.h" #include "SolverSelection.h" AdvectionSolver::AdvectionSolver( Settings::Settings const &settings, FieldController *field_controller, real u_lin, real v_lin, real w_lin) : m_settings(settings), m_field_controller(field_controller), m_u_lin(FieldType::U, u_lin), m_v_lin(FieldType::V, v_lin), m_w_lin(FieldType::W, w_lin) { #ifndef BENCHMARKING m_logger = Utility::create_logger(typeid(this).name()); #endif std::string advectionType = m_settings.get("solver/advection/type"); SolverSelection::SetAdvectionSolver(m_settings, &adv, m_settings.get("solver/advection/type")); m_u_lin.copyin(); m_v_lin.copyin(); m_w_lin.copyin(); control(); } AdvectionSolver::AdvectionSolver(Settings::Settings const &settings, FieldController *field_controller) : AdvectionSolver( settings, field_controller, settings.get_real("initial_conditions/u_lin"), settings.get_real("initial_conditions/v_lin"), settings.get_real("initial_conditions/w_lin")) { } AdvectionSolver::~AdvectionSolver() { delete adv; } //====================================== do_step ================================= // *************************************************************************************** /// \brief brings all calculation steps together into one function /// \param dt time step /// \param sync synchronous kernel launching (true, default: false) // *************************************************************************************** void AdvectionSolver::do_step(real, bool sync) { Field &u = m_field_controller->get_field_u(); Field &v = m_field_controller->get_field_v(); Field &w = m_field_controller->get_field_w(); Field &u0 = m_field_controller->get_field_u0(); Field &v0 = m_field_controller->get_field_v0(); Field &w0 = m_field_controller->get_field_w0(); #pragma acc data present(m_u_lin, m_v_lin, m_w_lin, u, u0, v, v0, w, w0) { // 1. Solve advection equation #ifndef BENCHMARKING m_logger->info("Advect ..."); #endif adv->advect(u, u0, m_u_lin, m_v_lin, m_w_lin, sync); adv->advect(v, v0, m_u_lin, m_v_lin, m_w_lin, sync); adv->advect(w, w0, m_u_lin, m_v_lin, m_w_lin, sync); } } //======================================= Check data ================================== // *************************************************************************************** /// \brief Checks if field specified correctly // *************************************************************************************** void AdvectionSolver::control() { auto fields = Utility::split(m_settings.get("solver/advection/field"), ','); std::sort(fields.begin(), fields.end()); if (fields != std::vector<std::string>({"u", "v", "w"})) { #ifndef BENCHMARKING m_logger->error("Fields not specified correctly!"); #endif std::exit(1); //TODO Error handling } }
36.27957
105
0.572318
[ "vector" ]
4be0d8d12cb452701e29fdcf5eb8a7e36cfd500d
1,651
cpp
C++
src/scenes/editor/toolbox/tool/resize.cpp
Firstbober/MPS
998436b223842b089f0c048b3e7d5676a7688c67
[ "MIT" ]
9
2018-05-15T06:03:51.000Z
2022-01-30T01:23:24.000Z
src/scenes/editor/toolbox/tool/resize.cpp
Firstbober/MPS
998436b223842b089f0c048b3e7d5676a7688c67
[ "MIT" ]
5
2018-06-28T16:48:04.000Z
2021-06-05T21:24:32.000Z
src/scenes/editor/toolbox/tool/resize.cpp
Firstbober/MPS
998436b223842b089f0c048b3e7d5676a7688c67
[ "MIT" ]
9
2018-05-03T19:40:54.000Z
2021-06-05T17:54:32.000Z
#include "resize.hpp" #include "../../drawer.hpp" #include "../toolbox.hpp" #include "../../editor.hpp" void Resize::init(){ iconName = "resize"; Frame * frame = scene->frameMan.getCurrentFrame(); box_width.init(scene).setMinValue(1).setMaxValue(8192).setValue(frame->getWidth()); box_height.init(scene).setMinValue(1).setMaxValue(8192).setValue(frame->getHeight()); but_apply.init(scene).setText("Apply", scene->a.font32, 255, 255, 255); } void Resize::update(){ box_width.update(); box_height.update(); but_apply.update(); } bool Resize::pushEvent(SDL_Event * evt){ bool used=false; if(box_width.pushEvent(evt)){ used=true; } if(box_height.pushEvent(evt)){ used=true; } if(but_apply.pushEvent(evt)){ if(but_apply.isClicked()){ scene->drawer.historyClear(); scene->frameMan.getCurrentFrame()->resize(box_width.getValue(), box_height.getValue()); scene->changeFrame(scene->frameMan.getCurrentFrameIndex()); Float2 p = scene->drawer.getCameraPosition(); scene->drawer.setCameraPosition(p.x, p.y); } used=true; } return used; } void Resize::render(float alpha){ box_width.setPosition(toolbox->getSettingsX(),toolbox->getSettingsY()).setSize(toolbox->getWidth(),75).render(alpha); box_height.setPosition(toolbox->getSettingsX(),toolbox->getSettingsY()+75).setSize(toolbox->getWidth(),75).render(alpha); but_apply.setPosition(toolbox->getSettingsX(),toolbox->getSettingsY()+150).setSize(toolbox->getWidth(),40).render(alpha); } void Resize::select(){ toolbox->setSettingsHeight(190); }
30.018182
125
0.671108
[ "render" ]
4be2cd9cad576e35eb963389e90b30e828a08d64
2,384
cpp
C++
demos/consoleTest.cpp
Steve132/VirtuosoConsole
f9c927301ac1f135f78814266e4284fef6dc81b1
[ "Unlicense" ]
16
2017-07-07T11:05:50.000Z
2022-02-23T08:12:14.000Z
demos/consoleTest.cpp
Steve132/VirtuosoConsole
f9c927301ac1f135f78814266e4284fef6dc81b1
[ "Unlicense" ]
2
2017-07-06T19:00:14.000Z
2017-07-08T18:45:13.000Z
demos/consoleTest.cpp
Steve132/VirtuosoConsole
f9c927301ac1f135f78814266e4284fef6dc81b1
[ "Unlicense" ]
6
2017-04-18T22:06:37.000Z
2022-03-03T16:31:27.000Z
#include "../QuakeStyleConsole.h" using namespace Virtuoso; bool running = true; void printSum(const int& a, const int& b) { std::cout<<a+b<<std::endl; } class Adder { std::string str; public: Adder(const std::string& pr):str(pr){} void add(int a, int b, int c, int d, int e) { std::clog << str << a+b+c+d+e << std::endl; } }; int main() { std::clog << "VirtuosoConsole test program.\n"<<std::endl; std::clog << "Type help, listCmd, or listCVars for usage."<<std::endl; std::clog << "Try runFile with TestCommands.txt."<<std::endl; std::clog << "When you quit, COMMAND_HISTORY.txt will save your history file (which you can also run using runFile)."<<std::endl; Adder a("Sum is "); //a class int health = 0; // a variable like we might have in a game QuakeStyleConsole console; //create the console //binding a template function with a particular value as a command console.bindCommand("quit", [](){running = false;}, "quits the program"); //binding a free function that takes 2 arguments as a command. console.bindCommand("sum", printSum, "Sums two input integer values. Function bound with bindCommand()"); std::function <void (void)> printHistory = [&console]() { for (int i = 0; i < console.historyBuffer().size(); i++) { std::clog << console.historyBuffer()[i] << std::endl; } }; console.bindCommand("printHistory", printHistory , "Print the current command history buffer for the console."); console.bindMemberCommand("sumFiveValues", a, &Adder::add, "Given five integers as input, sum them all. This demonstrates bindMemberCommand() using an object"); //bind the variable to the console console.bindCVar("health", health, "Player health. Example variable bound from c++ code using bindCVar()"); //populate the history buffer with commands from a previous run of the program console.loadHistoryBuffer("COMMAND_HISTORY.txt"); while(running) { std::cout<<"\nexecute next instruction"<<std::endl; // you can pass in whatever istream and ostream you want console.commandExecute(std::cin, std::clog); } std::cout<<"Saving history file"<<std::endl; console.saveHistoryBuffer("COMMAND_HISTORY.txt"); //save commands from this run }
30.961039
165
0.645134
[ "object" ]